CREATE DATABASE  IF NOT EXISTS `vn` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;
USE `vn`;
-- MySQL dump 10.13  Distrib 5.7.17, for Win64 (x86_64)
--
-- Host: db.verdnatura.es    Database: vn
-- ------------------------------------------------------
-- Server version	5.6.25-4-log

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

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

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

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

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

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

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

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

DROP TABLE IF EXISTS `address`;
/*!50001 DROP VIEW IF EXISTS `address`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `address` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `street`,
 1 AS `city`,
 1 AS `postalCode`,
 1 AS `provinceFk`,
 1 AS `phone`,
 1 AS `celular`,
 1 AS `nickname`,
 1 AS `isDefaultAddress`,
 1 AS `active`,
 1 AS `longitude`,
 1 AS `latitude`,
 1 AS `warehouseFk`,
 1 AS `mobile`,
 1 AS `agencyFk`,
 1 AS `isEqualizated`,
 1 AS `defaultAddress`,
 1 AS `customer`,
 1 AS `agency`,
 1 AS `province`,
 1 AS `warehouse`*/;
SET character_set_client = @saved_cs_client;

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

DROP TABLE IF EXISTS `addressForPackaging`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addressForPackaging` (
  `addressFk` int(11) NOT NULL,
  `packagingValue` decimal(10,2) NOT NULL DEFAULT '0.04',
  PRIMARY KEY (`addressFk`),
  CONSTRAINT `addresForPackaging_fk1` FOREIGN KEY (`addressFk`) REFERENCES `vn2008`.`Consignatarios` (`id_consigna`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

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

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

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

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

DROP TABLE IF EXISTS `agencyMode`;
/*!50001 DROP VIEW IF EXISTS `agencyMode`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `agencyMode` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `description`,
 1 AS `view`,
 1 AS `deliveryMethod`,
 1 AS `m3`,
 1 AS `cod71`,
 1 AS `web`,
 1 AS `agency`,
 1 AS `agencyFk`,
 1 AS `agencyService`,
 1 AS `agencyServiceFk`,
 1 AS `inflacion`,
 1 AS `isVolumetric`,
 1 AS `reportMail`*/;
SET character_set_client = @saved_cs_client;

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

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

--
-- Table structure for table `autonomousRegion`
--

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

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

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

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

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

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

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

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

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

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

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

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

DROP TABLE IF EXISTS `buy`;
/*!50001 DROP VIEW IF EXISTS `buy`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `buy` AS SELECT 
 1 AS `id`,
 1 AS `entryFk`,
 1 AS `itemFk`,
 1 AS `amount`,
 1 AS `buyingValue`,
 1 AS `quantity`,
 1 AS `packageFk`,
 1 AS `stickers`,
 1 AS `freightValue`,
 1 AS `packageValue`,
 1 AS `comissionValue`,
 1 AS `packing`,
 1 AS `grouping`,
 1 AS `groupingMode`,
 1 AS `location`,
 1 AS `price1`,
 1 AS `price2`,
 1 AS `price3`,
 1 AS `minPrice`,
 1 AS `producer`,
 1 AS `printedStickers`,
 1 AS `isChecked`*/;
SET character_set_client = @saved_cs_client;

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

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

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

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

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

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

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

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

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

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

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

DROP TABLE IF EXISTS `clientDefaultCompany`;
/*!50001 DROP VIEW IF EXISTS `clientDefaultCompany`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientDefaultCompany` AS SELECT 
 1 AS `id`,
 1 AS `ClientFk`,
 1 AS `CompanyFk`,
 1 AS `started`,
 1 AS `finished`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `clientLog`
--

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

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

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

--
-- Temporary view structure for view `clientNew`
--

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

--
-- Temporary view structure for view `clientNotification`
--

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

--
-- Temporary view structure for view `clientNotificationType`
--

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

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

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

--
-- Temporary view structure for view `clientTransicion`
--

DROP TABLE IF EXISTS `clientTransicion`;
/*!50001 DROP VIEW IF EXISTS `clientTransicion`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientTransicion` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `fi`,
 1 AS `socialName`,
 1 AS `contact`,
 1 AS `street`,
 1 AS `city`,
 1 AS `postcode`,
 1 AS `phone`,
 1 AS `mobile`,
 1 AS `fax`,
 1 AS `isRelevant`,
 1 AS `email`,
 1 AS `iban`,
 1 AS `dueDay`,
 1 AS `accountingAccount`,
 1 AS `isEqualizated`,
 1 AS `provinceFk`,
 1 AS `hasToInvoice`,
 1 AS `credit`,
 1 AS `countryFk`,
 1 AS `isActive`,
 1 AS `gestdocFk`,
 1 AS `quality`,
 1 AS `paymentMethodFk`,
 1 AS `isToBeMailed`,
 1 AS `contactChannelFk`,
 1 AS `hasSepaVnl`,
 1 AS `hasCoreVnl`,
 1 AS `hasCoreVnh`,
 1 AS `riskCalculated`,
 1 AS `clientTypeFk`,
 1 AS `mail_address`,
 1 AS `cplusTerIdNifFk`,
 1 AS `isTaxDataChecked`,
 1 AS `isFreezed`,
 1 AS `creditInsurance`,
 1 AS `isCreatedAsServed`,
 1 AS `hasInvoiceSimplified`,
 1 AS `salesPersonFk`,
 1 AS `isVies`,
 1 AS `eypbc`,
 1 AS `active`,
 1 AS `equalizationTax`,
 1 AS `invoiceByEmail`,
 1 AS `payMethodFk`,
 1 AS `vies`,
 1 AS `hasToInvoiceByAddress`,
 1 AS `typeFk`,
 1 AS `created`,
 1 AS `province`,
 1 AS `Congelado`,
 1 AS `Id_Trabajador`,
 1 AS `workerFk`,
 1 AS `cyc`,
 1 AS `Id_Pais`,
 1 AS `activo`,
 1 AS `gestdoc`,
 1 AS `calidad`,
 1 AS `paymentMethod`,
 1 AS `channel`,
 1 AS `channelFk`,
 1 AS `clientes_tipo_id`,
 1 AS `postcode_id`,
 1 AS `codpos`,
 1 AS `postalAddress`,
 1 AS `sepavnl`,
 1 AS `corevnl`,
 1 AS `corevnh`*/;
SET character_set_client = @saved_cs_client;

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

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

--
-- Temporary view structure for view `clientkk`
--

DROP TABLE IF EXISTS `clientkk`;
/*!50001 DROP VIEW IF EXISTS `clientkk`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientkk` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `fi`,
 1 AS `phone`,
 1 AS `fax`,
 1 AS `email`,
 1 AS `iban`,
 1 AS `dueDay`,
 1 AS `accountingAccount`,
 1 AS `isEqualizated`,
 1 AS `city`,
 1 AS `province`,
 1 AS `provinceFk`,
 1 AS `postcode`,
 1 AS `socialName`,
 1 AS `contact`,
 1 AS `hasToInvoice`,
 1 AS `Congelado`,
 1 AS `Id_Trabajador`,
 1 AS `workerFk`,
 1 AS `credit`,
 1 AS `cyc`,
 1 AS `Id_Pais`,
 1 AS `countryFk`,
 1 AS `activo`,
 1 AS `active`,
 1 AS `gestdoc`,
 1 AS `gestdocFk`,
 1 AS `calidad`,
 1 AS `paymentMethod`,
 1 AS `paymentMethodFk`,
 1 AS `registerDate`,
 1 AS `invoiceByEmail`,
 1 AS `isToBeMailed`,
 1 AS `channel`,
 1 AS `channelFk`,
 1 AS `VIES`,
 1 AS `sepavnl`,
 1 AS `corevnl`,
 1 AS `riskCalculated`,
 1 AS `corevnh`,
 1 AS `clientes_tipo_id`,
 1 AS `clientTypeFk`,
 1 AS `postcode_id`,
 1 AS `postcodeFk`,
 1 AS `mail_address`,
 1 AS `codpos`,
 1 AS `cplusTerIdNifFk`,
 1 AS `postalAddress`,
 1 AS `invoiceByAddress`,
 1 AS `isTaxDataChecked`,
 1 AS `isFreezed`,
 1 AS `creditInsurance`,
 1 AS `isCreatedAsServed`,
 1 AS `hasInvoiceSimplified`*/;
SET character_set_client = @saved_cs_client;

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

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

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

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

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

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

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

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

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

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

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

DROP TABLE IF EXISTS `config`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `config` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `mdbServer` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `fakeEmail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `defaultersMaxAmount` int(10) DEFAULT '200' COMMENT 'maxima deuda permitida a partir de la cual se bloquea a un usuario',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `country`
--

DROP TABLE IF EXISTS `country`;
/*!50001 DROP VIEW IF EXISTS `country`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `country` AS SELECT 
 1 AS `id`,
 1 AS `country`,
 1 AS `CEE`,
 1 AS `isUeeMember`,
 1 AS `Code`,
 1 AS `currencyFk`,
 1 AS `politicalCountryFk`,
 1 AS `geoFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `cplusCorrectingType`
--

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

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

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

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

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

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

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

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

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

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

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

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

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

--
-- Table structure for table `cplusTrascendency472`
--

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

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

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

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

DROP TABLE IF EXISTS `creditClassification`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `creditClassification` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `client` int(11) NOT NULL,
  `dateStart` date NOT NULL,
  `dateEnd` date DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `creditClassifClientFk_idx` (`client`),
  KEY `creditClassifdateEnd_idx` (`dateEnd`),
  CONSTRAINT `creditClassifClientFk` FOREIGN KEY (`client`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2589 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditClassification_BEFORE_UPDATE` BEFORE UPDATE ON `creditClassification` FOR EACH ROW
BEGIN
	IF NEW.client <> OLD.client THEN
		CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT');
    END IF;
    IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN
		UPDATE vn2008.Clientes c
			SET creditInsurance = 0 WHERE c.Id_cliente = NEW.client;
    END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

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

DROP TABLE IF EXISTS `creditInsurance`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `creditInsurance` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `creditClassification` int(11) DEFAULT NULL,
  `credit` int(11) DEFAULT NULL,
  `creationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `grade` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `CreditInsurance_Fk1_idx` (`creditClassification`),
  CONSTRAINT `CreditInsurance_Fk1` FOREIGN KEY (`creditClassification`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1624 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalla los clientes que tienen seguro de credito';
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditInsurance_AFTER_INSERT` AFTER INSERT ON `creditInsurance` FOR EACH ROW
BEGIN
	UPDATE vn2008.Clientes c
		JOIN vn.creditClassification  cc ON cc.client = c.Id_Cliente
        SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification;
        
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

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

DROP TABLE IF EXISTS `dailyTaskLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dailyTaskLog` (
  `state` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

--
-- Temporary view structure for view `deliveryMethod`
--

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

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

DROP TABLE IF EXISTS `ediSpecie`;
/*!50001 DROP VIEW IF EXISTS `ediSpecie`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ediSpecie` AS SELECT 
 1 AS `id`,
 1 AS `genusFk`,
 1 AS `latinSpeciesName`,
 1 AS `entried`,
 1 AS `dued`,
 1 AS `modified`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `entry`
--

DROP TABLE IF EXISTS `entry`;
/*!50001 DROP VIEW IF EXISTS `entry`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `entry` AS SELECT 
 1 AS `id`,
 1 AS `supplierFk`,
 1 AS `ref`,
 1 AS `isInventory`,
 1 AS `isConfirmed`,
 1 AS `isOrdered`,
 1 AS `isRaid`,
 1 AS `commission`,
 1 AS `created`,
 1 AS `evaNotes`,
 1 AS `travelFk`,
 1 AS `currencyFk`,
 1 AS `companyFk`,
 1 AS `gestDocFk`,
 1 AS `invoiceReceivedFk`*/;
SET character_set_client = @saved_cs_client;

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

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

--
-- Temporary view 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 `excuse`
--

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

--
-- Temporary view structure for view `expedition`
--

DROP TABLE IF EXISTS `expedition`;
/*!50001 DROP VIEW IF EXISTS `expedition`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expedition` AS SELECT 
 1 AS `id`,
 1 AS `agency`,
 1 AS `agencyFk`,
 1 AS `ticket`,
 1 AS `ticketFk`,
 1 AS `isBox`,
 1 AS `printingTime`,
 1 AS `item`,
 1 AS `itemFk`,
 1 AS `counter`,
 1 AS `checked`,
 1 AS `workerFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `expence`
--

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

--
-- Temporary view structure for view `grant`
--

DROP TABLE IF EXISTS `grant`;
/*!50001 DROP VIEW IF EXISTS `grant`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `grant` AS SELECT 
 1 AS `group`,
 1 AS `worker`,
 1 AS `company`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `grantGroup`
--

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

--
-- Temporary view structure for view `greuge`
--

DROP TABLE IF EXISTS `greuge`;
/*!50001 DROP VIEW IF EXISTS `greuge`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `greuge` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `description`,
 1 AS `amount`,
 1 AS `shipped`,
 1 AS `created`,
 1 AS `greugeTypeFk`,
 1 AS `ticketFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `greugeType`
--

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

--
-- Temporary view structure for view `ink`
--

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

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

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

--
-- Temporary view structure for view `inkL10n`
--

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

--
-- Temporary view structure for view `intrastat`
--

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

--
-- Temporary view structure for view `invoiceCorrection`
--

DROP TABLE IF EXISTS `invoiceCorrection`;
/*!50001 DROP VIEW IF EXISTS `invoiceCorrection`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceCorrection` AS SELECT 
 1 AS `correctingFk`,
 1 AS `correctedFk`,
 1 AS `cplusRectificationTypeFk`,
 1 AS `cplusInvoiceType477Fk`,
 1 AS `invoiceCorrectionTypeFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `invoiceCorrectionDataSource`
--

DROP TABLE IF EXISTS `invoiceCorrectionDataSource`;
/*!50001 DROP VIEW IF EXISTS `invoiceCorrectionDataSource`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceCorrectionDataSource` AS SELECT 
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `concept`,
 1 AS `price`,
 1 AS `discount`,
 1 AS `refFk`,
 1 AS `saleFk`,
 1 AS `shipped`*/;
SET character_set_client = @saved_cs_client;

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

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

--
-- Temporary view structure for view `invoiceIn`
--

DROP TABLE IF EXISTS `invoiceIn`;
/*!50001 DROP VIEW IF EXISTS `invoiceIn`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceIn` AS SELECT 
 1 AS `id`,
 1 AS `serialNumber`,
 1 AS `serial`,
 1 AS `supplierFk`,
 1 AS `issued`,
 1 AS `supplierRef`,
 1 AS `isBooked`,
 1 AS `currencyFk`,
 1 AS `created`,
 1 AS `companyFk`,
 1 AS `docFk`,
 1 AS `booked`,
 1 AS `operated`,
 1 AS `cplusInvoiceType472Fk`,
 1 AS `cplusRectificationTypeFk`,
 1 AS `cplusSubjectOpFk`,
 1 AS `cplusTaxBreakFk`,
 1 AS `cplusTrascendency472Fk`,
 1 AS `bookEntried`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `invoiceInAwb`
--

DROP TABLE IF EXISTS `invoiceInAwb`;
/*!50001 DROP VIEW IF EXISTS `invoiceInAwb`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceInAwb` AS SELECT 
 1 AS `invoiceInFk`,
 1 AS `awbFk`,
 1 AS `dua`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `invoiceInEntry`
--

DROP TABLE IF EXISTS `invoiceInEntry`;
/*!50001 DROP VIEW IF EXISTS `invoiceInEntry`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceInEntry` AS SELECT 
 1 AS `id`,
 1 AS `invoiceInFk`,
 1 AS `entryFk`,
 1 AS `percentage`,
 1 AS `invoiceInAwbFk`,
 1 AS `isBooked`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `invoiceInIntrastat`
--

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

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

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

--
-- Temporary view structure for view `invoiceInTax`
--

DROP TABLE IF EXISTS `invoiceInTax`;
/*!50001 DROP VIEW IF EXISTS `invoiceInTax`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceInTax` AS SELECT 
 1 AS `id`,
 1 AS `invoiceInFk`,
 1 AS `taxCodeFk`,
 1 AS `taxableBase`,
 1 AS `expenceFk`,
 1 AS `foreignValue`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `invoiceOut`
--

DROP TABLE IF EXISTS `invoiceOut`;
/*!50001 DROP VIEW IF EXISTS `invoiceOut`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceOut` AS SELECT 
 1 AS `id`,
 1 AS `ref`,
 1 AS `serial`,
 1 AS `issued`,
 1 AS `amount`,
 1 AS `clientFk`,
 1 AS `created`,
 1 AS `companyFk`,
 1 AS `dued`,
 1 AS `booked`,
 1 AS `cplusInvoiceType477Fk`,
 1 AS `cplusTaxBreakFk`,
 1 AS `cplusSubjectOpFk`,
 1 AS `cplusTrascendency477Fk`,
 1 AS `pdf`*/;
SET character_set_client = @saved_cs_client;

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

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

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

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

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

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

--
-- Temporary view structure for view `item`
--

DROP TABLE IF EXISTS `item`;
/*!50001 DROP VIEW IF EXISTS `item`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `item` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `typeFk`,
 1 AS `size`,
 1 AS `inkFk`,
 1 AS `category`,
 1 AS `stems`,
 1 AS `originFk`,
 1 AS `description`,
 1 AS `producerFk`,
 1 AS `intrastatFk`,
 1 AS `isOnOffer`,
 1 AS `expenceFk`,
 1 AS `isBargain`,
 1 AS `comment`,
 1 AS `relevancy`,
 1 AS `image`,
 1 AS `taxClassFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `itemBarcode`
--

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

--
-- Temporary view structure for view `itemBotanical`
--

DROP TABLE IF EXISTS `itemBotanical`;
/*!50001 DROP VIEW IF EXISTS `itemBotanical`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemBotanical` AS SELECT 
 1 AS `itemFk`,
 1 AS `botanical`,
 1 AS `genusFk`,
 1 AS `specieFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `itemBotanicalWithGenus`
--

DROP TABLE IF EXISTS `itemBotanicalWithGenus`;
/*!50001 DROP VIEW IF EXISTS `itemBotanicalWithGenus`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemBotanicalWithGenus` AS SELECT 
 1 AS `itemFk`,
 1 AS `ediBotanic`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `itemCategory`
--

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

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

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

--
-- Temporary view structure for view `itemCategoryL10n`
--

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

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

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

--
-- Temporary view structure for view `itemPlacement`
--

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

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

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

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

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

--
-- Temporary view structure for view `itemTagged`
--

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

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

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

--
-- Temporary view structure for view `itemType`
--

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

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

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

--
-- Temporary view 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 `itemVerdecora`
--

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

--
-- Temporary view structure for view `mail`
--

DROP TABLE IF EXISTS `mail`;
/*!50001 DROP VIEW IF EXISTS `mail`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mail` AS SELECT 
 1 AS `id`,
 1 AS `senderFk`,
 1 AS `recipientFk`,
 1 AS `sender`,
 1 AS `replyTo`,
 1 AS `subject`,
 1 AS `body`,
 1 AS `plainTextBody`,
 1 AS `attachment`,
 1 AS `creationDate`,
 1 AS `sent`,
 1 AS `status`*/;
SET character_set_client = @saved_cs_client;

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

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

--
-- Temporary view structure for view `manaSpellers`
--

DROP TABLE IF EXISTS `manaSpellers`;
/*!50001 DROP VIEW IF EXISTS `manaSpellers`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `manaSpellers` AS SELECT 
 1 AS `worker`,
 1 AS `size`,
 1 AS `used`,
 1 AS `pricesModifierRate`,
 1 AS `pricesModifierActivated`,
 1 AS `workerCode`,
 1 AS `firstname`,
 1 AS `name`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `mandate`
--

DROP TABLE IF EXISTS `mandate`;
/*!50001 DROP VIEW IF EXISTS `mandate`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mandate` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `companyFk`,
 1 AS `code`,
 1 AS `created`,
 1 AS `finished`,
 1 AS `mandateTypeFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `mandateType`
--

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

--
-- Table structure for table `manuscript`
--

DROP TABLE IF EXISTS `manuscript`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `manuscript` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(45) CHARACTER SET utf8 NOT NULL,
  `description` text COLLATE utf8_unicode_ci,
  `enabled` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

--
-- Table structure for table `messageInbox`
--

DROP TABLE IF EXISTS `messageInbox`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `messageInbox` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uuid` varchar(50) CHARACTER SET utf8 NOT NULL,
  `sender` varchar(50) CHARACTER SET utf8 NOT NULL,
  `recipient` varchar(45) CHARACTER SET utf8 NOT NULL,
  `finalRecipient` varchar(50) CHARACTER SET utf8 NOT NULL,
  `message` longtext CHARACTER SET utf8,
  `sendDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `read` varchar(45) CHARACTER SET utf8 NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `uuid` (`uuid`(8)),
  KEY `finalRecipient` (`finalRecipient`)
) ENGINE=InnoDB AUTO_INCREMENT=1463317 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_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` (
  `MovPosicion` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Ejercicio` smallint(6) NOT NULL,
  `CodigoEmpresa` smallint(6) NOT NULL,
  `Asiento` int(11) NOT NULL,
  `CargoAbono` varchar(1) COLLATE utf8_unicode_ci NOT NULL,
  `CodigoCuenta` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `Contrapartida` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `FechaAsiento` datetime NOT NULL,
  `TipoDocumento` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
  `DocumentoConta` varchar(9) COLLATE utf8_unicode_ci NOT NULL,
  `Comentario` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `ImporteAsiento` decimal(28,10) NOT NULL,
  `CodigoDiario` smallint(6) NOT NULL,
  `CodigoCanal` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `CodigoActividad` varchar(1) COLLATE utf8_unicode_ci NOT NULL,
  `FechaVencimiento` datetime DEFAULT NULL,
  `NumeroPeriodo` smallint(6) NOT NULL,
  `CodigoUsuario` smallint(6) NOT NULL,
  `FechaGrabacion` datetime NOT NULL,
  `TipoEntrada` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `CodigoDepartamento` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `CodigoSeccion` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `CodigoDivisa` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `ImporteCambio` decimal(28,10) NOT NULL,
  `ImporteDivisa` decimal(28,10) NOT NULL,
  `FactorCambio` decimal(28,10) NOT NULL,
  `CodigoProyecto` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `LibreN1` int(11) NOT NULL,
  `LibreN2` int(11) NOT NULL,
  `LibreA1` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `LibreA2` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `IdDelegacion` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `OrdenMovimientos` int(11) NOT NULL,
  `MovCartera` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `IdProcesoIME` varchar(255) COLLATE utf8_unicode_ci 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) COLLATE utf8_unicode_ci NOT NULL,
  `Factura` int(11) NOT NULL,
  `SuFacturaNo` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `FechaFactura` datetime DEFAULT NULL,
  `ImporteFactura` decimal(28,10) NOT NULL,
  `TipoFactura` varchar(1) COLLATE utf8_unicode_ci NOT NULL,
  `CodigoCuentaFactura` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `CifDni` varchar(13) COLLATE utf8_unicode_ci NOT NULL,
  `Nombre` varchar(35) COLLATE utf8_unicode_ci 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) COLLATE utf8_unicode_ci NOT NULL,
  `Intracomunitaria` smallint(6) NOT NULL,
  `CodigoTerritorio` smallint(6) NOT NULL,
  `SiglaNacion` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `RetencionInformativa` smallint(6) NOT NULL,
  `EjercicioFacturaOriginal` smallint(6) NOT NULL,
  `SerieFacturaOriginal` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `NumeroFacturaOriginal` int(11) NOT NULL,
  `EjercicioFactura` smallint(6) NOT NULL,
  `CobroPagoRetencion` varchar(1) COLLATE utf8_unicode_ci NOT NULL,
  `FechaOperacion` datetime DEFAULT NULL,
  `Exclusion347` smallint(6) NOT NULL,
  `MovIdentificadorIME` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Previsiones` varchar(1) COLLATE utf8_unicode_ci NOT NULL,
  `MantenerAsiento` tinyint(4) NOT NULL,
  `OrdenMovIME` smallint(6) NOT NULL,
  `Metalico347` smallint(6) NOT NULL,
  `ClaveOperacionFactura_` varchar(1) COLLATE utf8_unicode_ci NOT NULL,
  `SerieAgrupacion_` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `NumeroFacturaInicial_` int(11) NOT NULL,
  `NumeroFacturaFinal_` int(11) NOT NULL,
  `IdAsientoExterno` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `IdDiarioExterno` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `IdFacturaExterno` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `IdMovimiento` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `IdCuadre` smallint(6) NOT NULL,
  `FechaCuadre` datetime NOT NULL,
  `TipoCuadre` varchar(4) COLLATE utf8_unicode_ci NOT NULL,
  `AgrupacionCuadre` int(11) NOT NULL,
  `StatusSaldo` smallint(6) NOT NULL,
  `StatusConciliacion` smallint(6) NOT NULL,
  `CodigoConciliacion` int(11) NOT NULL,
  `FechaConciliacion` datetime DEFAULT NULL,
  `TipoConciliacion` smallint(6) NOT NULL,
  `IndicadorContaBanco` varchar(1) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion3` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion4` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion5` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion6` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion7` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion8` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion9` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion2` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion1` varchar(250) COLLATE utf8_unicode_ci 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 DEFAULT NULL,
  `TipoCriterioCaja` tinyint(4) NOT NULL,
  `MovFacturaOrigenIME` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `IdFacturaExternoFinal` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `IdFacturaExternoInicial` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `IdFacturaExternoOriginal` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `NumFacturasExternoAgrupacion` int(11) NOT NULL,
  `CodigoMedioCobro` varchar(1) COLLATE utf8_unicode_ci NOT NULL,
  `MedioCobro` varchar(31) COLLATE utf8_unicode_ci NOT NULL,
  `IvaDeducible1` smallint(6) NOT NULL,
  `IvaDeducible2` smallint(6) NOT NULL,
  `IvaDeducible3` smallint(6) NOT NULL,
  `IvaDeducible4` smallint(6) NOT NULL,
  `TipoRectificativa` smallint(6) NOT NULL,
  `FechaFacturaOriginal` datetime DEFAULT 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) COLLATE utf8_unicode_ci NOT NULL,
  `enlazado` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `movement`
--

DROP TABLE IF EXISTS `movement`;
/*!50001 DROP VIEW IF EXISTS `movement`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `movement` AS SELECT 
 1 AS `id`,
 1 AS `item`,
 1 AS `ticket`,
 1 AS `concept`,
 1 AS `amount`,
 1 AS `quantity`,
 1 AS `price`,
 1 AS `discount`,
 1 AS `cost`,
 1 AS `reservado`,
 1 AS `od`,
 1 AS `priceFixed`,
 1 AS `lastUpdate`*/;
SET character_set_client = @saved_cs_client;

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

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

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

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

--
-- Temporary view structure for view `observationType`
--

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

--
-- Temporary view structure for view `origin`
--

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

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

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

--
-- Temporary view structure for view `originL10n`
--

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

--
-- Temporary view structure for view `outgoingInvoice`
--

DROP TABLE IF EXISTS `outgoingInvoice`;
/*!50001 DROP VIEW IF EXISTS `outgoingInvoice`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `outgoingInvoice` AS SELECT 
 1 AS `id`,
 1 AS `serie`,
 1 AS `dateInvoice`,
 1 AS `total`,
 1 AS `dueDate`,
 1 AS `bank`,
 1 AS `client`,
 1 AS `remittance`,
 1 AS `remit`,
 1 AS `worker`,
 1 AS `creationDate`,
 1 AS `company`,
 1 AS `liquidacion?`,
 1 AS `isPdf`*/;
SET character_set_client = @saved_cs_client;

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

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

--
-- Temporary view structure for view `package`
--

DROP TABLE IF EXISTS `package`;
/*!50001 DROP VIEW IF EXISTS `package`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `package` AS SELECT 
 1 AS `id`,
 1 AS `volume`,
 1 AS `width`,
 1 AS `height`,
 1 AS `depth`,
 1 AS `isPackageReturnable`,
 1 AS `created`,
 1 AS `itemFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `payMethod`
--

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

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

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

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

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

--
-- Temporary view structure for view `plantpassport`
--

DROP TABLE IF EXISTS `plantpassport`;
/*!50001 DROP VIEW IF EXISTS `plantpassport`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `plantpassport` AS SELECT 
 1 AS `producerFk`,
 1 AS `plantpassportAuthorityFk`,
 1 AS `number`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `plantpassportAuthority`
--

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

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

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

--
-- Temporary view structure for view `priceFixed`
--

DROP TABLE IF EXISTS `priceFixed`;
/*!50001 DROP VIEW IF EXISTS `priceFixed`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `priceFixed` AS SELECT 
 1 AS `itemFk`,
 1 AS `rate0`,
 1 AS `rate1`,
 1 AS `rate2`,
 1 AS `rate3`,
 1 AS `started`,
 1 AS `ended`,
 1 AS `bonus`,
 1 AS `warehouseFk`,
 1 AS `created`,
 1 AS `id`,
 1 AS `grouping`,
 1 AS `packing`,
 1 AS `box`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `printServerQueue`
--

DROP TABLE IF EXISTS `printServerQueue`;
/*!50001 DROP VIEW IF EXISTS `printServerQueue`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `printServerQueue` AS SELECT 
 1 AS `id`,
 1 AS `printerFk`,
 1 AS `priorityFk`,
 1 AS `reportFk`,
 1 AS `statusFk`,
 1 AS `started`,
 1 AS `finished`,
 1 AS `param1`,
 1 AS `workerFk`,
 1 AS `param2`,
 1 AS `param3`,
 1 AS `error`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `printingQueue`
--

DROP TABLE IF EXISTS `printingQueue`;
/*!50001 DROP VIEW IF EXISTS `printingQueue`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `printingQueue` AS SELECT 
 1 AS `id`,
 1 AS `printer`,
 1 AS `priority`,
 1 AS `report`,
 1 AS `state`,
 1 AS `startingTime`,
 1 AS `endingTime`,
 1 AS `text`,
 1 AS `worker`,
 1 AS `text2`,
 1 AS `text3`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `producer`
--

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

--
-- Temporary view structure for view `province`
--

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

--
-- Temporary view structure for view `receipt`
--

DROP TABLE IF EXISTS `receipt`;
/*!50001 DROP VIEW IF EXISTS `receipt`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `receipt` AS SELECT 
 1 AS `Id`,
 1 AS `invoiceFk`,
 1 AS `amountPaid`,
 1 AS `amountUnpaid`,
 1 AS `payed`,
 1 AS `workerFk`,
 1 AS `bankFk`,
 1 AS `clientFk`,
 1 AS `created`,
 1 AS `companyFk`,
 1 AS `isConciliate`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `referenceRate`
--

DROP TABLE IF EXISTS `referenceRate`;
/*!50001 DROP VIEW IF EXISTS `referenceRate`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `referenceRate` AS SELECT 
 1 AS `currencyFk`,
 1 AS `dated`,
 1 AS `value`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `role`
--

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

--
-- Temporary view structure for view `route`
--

DROP TABLE IF EXISTS `route`;
/*!50001 DROP VIEW IF EXISTS `route`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `route` AS SELECT 
 1 AS `id`,
 1 AS `workerFk`,
 1 AS `created`,
 1 AS `vehicleFk`,
 1 AS `agencyFk`,
 1 AS `agencyModeFk`,
 1 AS `time`,
 1 AS `isOk`,
 1 AS `kmStart`,
 1 AS `kmEnd`,
 1 AS `started`,
 1 AS `finished`,
 1 AS `gestdocFk`,
 1 AS `cost`,
 1 AS `m3`*/;
SET character_set_client = @saved_cs_client;

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

DROP TABLE IF EXISTS `routeGate`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeGate` (
  `deviceId` varchar(30) CHARACTER SET utf8 NOT NULL,
  `displayText` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`deviceId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

--
-- Temporary view structure for view `sale`
--

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

--
-- Temporary view structure for view `saleComponent`
--

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

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

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

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

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

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

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

--
-- Temporary view structure for view `state`
--

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

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

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

--
-- Temporary view structure for view `supplier`
--

DROP TABLE IF EXISTS `supplier`;
/*!50001 DROP VIEW IF EXISTS `supplier`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `supplier` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `account`,
 1 AS `countryFk`,
 1 AS `nif`,
 1 AS `isFarmer`,
 1 AS `retAccount`,
 1 AS `commission`,
 1 AS `created`,
 1 AS `postcodeFk`,
 1 AS `isActive`,
 1 AS `street`,
 1 AS `city`,
 1 AS `provinceFk`,
 1 AS `postCode`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `supplierAccount`
--

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

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

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

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

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

--
-- Temporary view 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) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `taxClass`
--

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

--
-- Temporary view structure for view `taxClassCode`
--

DROP TABLE IF EXISTS `taxClassCode`;
/*!50001 DROP VIEW IF EXISTS `taxClassCode`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `taxClassCode` AS SELECT 
 1 AS `taxClassFk`,
 1 AS `effectived`,
 1 AS `taxCodeFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `taxCode`
--

DROP TABLE IF EXISTS `taxCode`;
/*!50001 DROP VIEW IF EXISTS `taxCode`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `taxCode` AS SELECT 
 1 AS `id`,
 1 AS `dated`,
 1 AS `code`,
 1 AS `taxTypeFk`,
 1 AS `rate`,
 1 AS `equalizationTax`,
 1 AS `type`,
 1 AS `linkFk`,
 1 AS `isActive`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `taxType`
--

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

--
-- Temporary view structure for view `ticket`
--

DROP TABLE IF EXISTS `ticket`;
/*!50001 DROP VIEW IF EXISTS `ticket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticket` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `warehouseFk`,
 1 AS `shipped`,
 1 AS `landed`,
 1 AS `nickname`,
 1 AS `refFk`,
 1 AS `addressFk`,
 1 AS `isSigned`,
 1 AS `location`,
 1 AS `blocked`,
 1 AS `solution`,
 1 AS `path`,
 1 AS `routeFk`,
 1 AS `company`,
 1 AS `companyFk`,
 1 AS `agencyModeFk`,
 1 AS `loadingOrder`,
 1 AS `created`,
 1 AS `shipment`,
 1 AS `landing`,
 1 AS `customer`,
 1 AS `warehouse`,
 1 AS `client`,
 1 AS `address`,
 1 AS `agencyMode`,
 1 AS `signed`,
 1 AS `package`,
 1 AS `creationDate`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `ticketLog`
--

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

--
-- Temporary view structure for view `ticketObservation`
--

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

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

DROP TABLE IF EXISTS `ticketPackage`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketPackage` (
  `ticket` int(11) NOT NULL,
  `counter` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`ticket`),
  CONSTRAINT `ticketPackage_ticketFk` FOREIGN KEY (`ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `ticketPackaging`
--

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

--
-- Temporary view structure for view `ticketState`
--

DROP TABLE IF EXISTS `ticketState`;
/*!50001 DROP VIEW IF EXISTS `ticketState`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketState` AS SELECT 
 1 AS `ticketFk`,
 1 AS `ticket`,
 1 AS `state`,
 1 AS `productionOrder`,
 1 AS `alertLevel`,
 1 AS `code`,
 1 AS `worker`,
 1 AS `workerFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `ticketStateToday`
--

DROP TABLE IF EXISTS `ticketStateToday`;
/*!50001 DROP VIEW IF EXISTS `ticketStateToday`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketStateToday` AS SELECT 
 1 AS `ticket`,
 1 AS `state`,
 1 AS `productionOrder`,
 1 AS `alertLevel`,
 1 AS `worker`,
 1 AS `code`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `ticketTracking`
--

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

--
-- Table structure for table `ticketTrolley`
--

DROP TABLE IF EXISTS `ticketTrolley`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketTrolley` (
  `ticket` int(11) NOT NULL,
  `labelCount` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ticket`),
  CONSTRAINT `fk_ticketTrolley_vs_ticket` FOREIGN KEY (`ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `time`
--

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

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

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

--
-- Temporary view structure for view `travel`
--

DROP TABLE IF EXISTS `travel`;
/*!50001 DROP VIEW IF EXISTS `travel`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `travel` AS SELECT 
 1 AS `id`,
 1 AS `shipped`,
 1 AS `shipmentHour`,
 1 AS `landed`,
 1 AS `landingHour`,
 1 AS `warehouseInFk`,
 1 AS `warehouseOutFk`,
 1 AS `agencyFk`,
 1 AS `ref`,
 1 AS `isDelivered`,
 1 AS `isReceived`,
 1 AS `m3`*/;
SET character_set_client = @saved_cs_client;

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

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

--
-- Temporary view structure for view `unary`
--

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

--
-- Temporary view structure for view `unaryScan`
--

DROP TABLE IF EXISTS `unaryScan`;
/*!50001 DROP VIEW IF EXISTS `unaryScan`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `unaryScan` AS SELECT 
 1 AS `unaryFk`,
 1 AS `name`,
 1 AS `created`,
 1 AS `type`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `unaryScanLine`
--

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

--
-- Temporary view structure for view `unaryScanLineBuy`
--

DROP TABLE IF EXISTS `unaryScanLineBuy`;
/*!50001 DROP VIEW IF EXISTS `unaryScanLineBuy`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `unaryScanLineBuy` AS SELECT 
 1 AS `unaryScanLineFk`,
 1 AS `itemFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `unaryScanLineExpedition`
--

DROP TABLE IF EXISTS `unaryScanLineExpedition`;
/*!50001 DROP VIEW IF EXISTS `unaryScanLineExpedition`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `unaryScanLineExpedition` AS SELECT 
 1 AS `unaryScanLineFk`,
 1 AS `expeditionFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `user`
--

DROP TABLE IF EXISTS `user`;
/*!50001 DROP VIEW IF EXISTS `user`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `user` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `password`,
 1 AS `role`,
 1 AS `active`,
 1 AS `recoverPass`,
 1 AS `lastPassChange`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `vehicle`
--

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

--
-- Temporary view structure for view `warehouse`
--

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

--
-- Temporary view structure for view `warehouseAlias`
--

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

--
-- Temporary view structure for view `worker`
--

DROP TABLE IF EXISTS `worker`;
/*!50001 DROP VIEW IF EXISTS `worker`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `worker` AS SELECT 
 1 AS `id`,
 1 AS `workerCode`,
 1 AS `firstName`,
 1 AS `name`,
 1 AS `userFk`,
 1 AS `phone`,
 1 AS `bossFk`*/;
SET character_set_client = @saved_cs_client;

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

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

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

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

--
-- Temporary view structure for view `workerTeam`
--

DROP TABLE IF EXISTS `workerTeam`;
/*!50001 DROP VIEW IF EXISTS `workerTeam`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerTeam` AS SELECT 
 1 AS `team`,
 1 AS `user`,
 1 AS `id`,
 1 AS `Id_Trabajador`*/;
SET character_set_client = @saved_cs_client;

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

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

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

DROP TABLE IF EXISTS `workingHours`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workingHours` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timeIn` datetime NOT NULL,
  `timeOut` datetime DEFAULT NULL,
  `userId` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_working_hour_idx` (`userId`),
  CONSTRAINT `user_working_hour` FOREIGN KEY (`userId`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=12912 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena horas de Entrada y de Salida del personal';
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`workingHoursBeforeInsert` BEFORE INSERT ON `workingHours` FOR EACH ROW
BEGIN
	IF (SELECT COUNT(*) FROM workingHours WHERE userId = NEW.userId AND DATE(timeIn) = CURDATE()) > 0 THEN
		CALL util.throw ('ALREADY_LOGGED');
    END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

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

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

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

DROP TABLE IF EXISTS `zoneCalendar`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneCalendar` (
  `zoneFk` int(11) NOT NULL,
  `delivered` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`zoneFk`,`delivered`),
  CONSTRAINT `zoneFk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `zoneGeo`
--

DROP TABLE IF EXISTS `zoneGeo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneGeo` (
  `zoneFk` varchar(45) CHARACTER SET utf8 NOT NULL,
  `geoFk` int(11) NOT NULL,
  `isIncluded` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`zoneFk`,`geoFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `zoneNest`
--

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

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

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

--
-- Dumping events for database 'vn'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `ticketClosure` */;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `ticketClosure` ON SCHEDULE EVERY 1 DAY STARTS '2017-09-18 00:30:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Realiza el cierre de todos los almacenes del dia actual' DO CALL ticketClosureMultiWarehouse(DATE_ADD(CURDATE(), INTERVAL -1 DAY)) */ ;;
/*!50003 SET time_zone             = @saved_time_zone */ ;;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;;
/*!50003 SET character_set_client  = @saved_cs_client */ ;;
/*!50003 SET character_set_results = @saved_cs_results */ ;;
/*!50003 SET collation_connection  = @saved_col_connection */ ;;
DELIMITER ;
/*!50106 SET TIME_ZONE= @save_time_zone */ ;

--
-- Dumping routines for database 'vn'
--
/*!50003 DROP FUNCTION IF EXISTS `agencyIsAvailable` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `agencyIsAvailable`(vAgency INT, vDate DATE, vAddress INT) RETURNS tinyint(1)
BEGIN
/**
 * Comprueba si la agencia esta disponible para la fecha y
 * dirección dadas, es decir, si es posible enviar mercancía
 * desde al menos uno de los almacenes por la agencia, fecha
 * y direcciones especificadas.
 * 
 * @param vAgency Id de agencia
 * @param vDate Fecha de recepción de mercancía
 * @param vAddress Id consignatario, %NULL para recogida
 * @return %TRUE si la agencia esta disponible, %FALSE en caso contrario
 */
	DECLARE vMaxDays INT DEFAULT DATEDIFF(vDate, CURDATE());
	DECLARE vWday TINYINT DEFAULT WEEKDAY(vDate);
	DECLARE vHour TINYINT DEFAULT HOUR(NOW());
	DECLARE vProvince INT;
	DECLARE isAvailable BOOL;

	SELECT province INTO vProvince
		FROM address
		WHERE id = vAddress;

	SELECT COUNT(*) > 0 INTO isAvailable
		FROM agencyHour h
			JOIN agencyMode a
				ON a.agency = h.agency
		WHERE (h.province = vProvince
				OR h.province IS NULL)
			AND (h.weekDay = vWday
				OR h.weekDay IS NULL)
			AND (h.substractDay < vMaxDays
				OR (h.substractDay = vMaxDays AND h.maxHour > vHour))
			AND a.id = vAgency;
				
	RETURN isAvailable;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `clientGetDebt` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `clientGetDebt`(vClient INT, vDate DATE) RETURNS decimal(10,2)
BEGIN
/**
 * Devuelve el saldo de un cliente.
 *
 * @param vClient Identificador del cliente
 * @param vDate Fecha hasta la que tener en cuenta
 * @return Saldo del cliente
 */
	DECLARE vDateEnd DATETIME;
	DECLARE vDateIni DATETIME;
	DECLARE vDebt DECIMAL(10,2);

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

	CALL vn.ticketGetTotal;

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

	DROP TEMPORARY TABLE
		tmp.ticket,
		tmp.ticketTotal;

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

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

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

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

		UNION ALL

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

RETURN IFNULL(vMana,0);

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

DECLARE vDued DATE;

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

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

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

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

	RETURN vTicket;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `getTicketTrolleyLabelCount` */;
ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `getTicketTrolleyLabelCount`(vTicket INT) RETURNS int(11)
BEGIN

DECLARE vLabelCount INT DEFAULT 0;

SELECT labelCount INTO vLabelCount 
FROM ticketTrolley
WHERE ticket = vTicket;

SET vLabelCount = vLabelCount +1 ;

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

RETURN vlabelCount;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `getUser` */;
ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `getUser`() RETURNS int(11)
    DETERMINISTIC
BEGIN
	RETURN getWorker();
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `getUserId` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `getUserId`(userName varchar(30)) RETURNS int(11)
BEGIN
	DECLARE vUser INT;
    
    SELECT id INTO vUser
		FROM account.user
		WHERE `name` = userName;
    
	RETURN vUser;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `getWorker` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `getWorker`() RETURNS int(11)
    DETERMINISTIC
BEGIN
    DECLARE vUser INT;
    
    SELECT id INTO vUser
        FROM worker
        WHERE userFk = account.userGetId();
    
    RETURN vUser;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `getWorkerkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `getWorkerkk`() RETURNS int(11)
    DETERMINISTIC
BEGIN
	DECLARE vUser INT;
    
    SELECT id INTO vUser
		FROM worker
		WHERE user = account.userGetId();
    
	RETURN vUser;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `hasAnyNegativeBase` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `hasAnyNegativeBase`() RETURNS tinyint(1)
BEGIN

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

    DECLARE vCountry INT;
	DECLARE hasAnyNegativeBase BOOLEAN;

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

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

	RETURN hasAnyNegativeBase;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `hasSomeNegativeBase` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `hasSomeNegativeBase`(vTicket INT) RETURNS tinyint(1)
BEGIN

    DECLARE vCountry INT;
	DECLARE hasSomeNegativeBase BOOLEAN;

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

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

	RETURN hasSomeNegativeBase;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `invoiceOutAmount` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `invoiceOutAmount`(vInvoiceRef VARCHAR(15)) RETURNS decimal(10,2)
BEGIN
	DECLARE totalAmount DECIMAL(10,2);

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

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

	SELECT clientTaxArea(vClientFk, vCompanyFk) INTO vArea;
	-- Factura rápida
	IF vType = 'R' THEN
		SELECT 
			CASE vArea 
				WHEN 'CEE'
			THEN 'H'
				WHEN 'WORLD'
			THEN 'E'
				WHEN 'NATIONAL' 
			THEN 'T'
		END
		INTO vSerie;
		-- Factura multiple
	ELSEIF vType = 'M' THEN
		SELECT 
			CASE vArea 
				WHEN 'CEE'
			THEN 'H'
				WHEN 'WORLD'
			THEN 'E'
				WHEN 'NATIONAL' 
			THEN 'M'
		END
		INTO vSerie;
	-- Factura global
	ELSEIF vType = 'G' THEN
		SELECT 
			CASE vArea 
				WHEN 'CEE'
			THEN 'V'
				WHEN 'WORLD'
			THEN 'X'
				WHEN 'NATIONAL' 
			THEN 'A'
		END
		INTO vSerie;
	END IF;
	RETURN vSerie;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `isWorkerBoss` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `isWorkerBoss`(vUserId INT(11)) RETURNS tinyint(1)
    DETERMINISTIC
BEGIN

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

	SET vRecipient = LOWER(vRecipient);

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

	SELECT COUNT(*) INTO vCount FROM tRecipients;

	IF vCount = 0 THEN
		RETURN vCount;
	END IF;    

	SET vUuid = UUID();

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

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

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

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

	CALL ticketGetTotal;

	SELECT total INTO vTotal FROM tmp.ticketTotal;

	DROP TEMPORARY TABLE
		tmp.ticket,
		tmp.ticketTotal;
	
	RETURN vTotal;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticketPositionInPath` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8
BEGIN

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

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

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

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

IF vIsValenciaPath THEN -- Rutas Valencia

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

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

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

ELSE
 SET vPosition = 'MID';

END IF;

RETURN vPosition;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticketPositionInPathkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `ticketPositionInPathkk`(vTicketId INT) RETURNS varchar(10) CHARSET utf8
BEGIN


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

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

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

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


IF vIsValenciaPath THEN -- Rutas Valencia

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

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

		
	
		IF  vExpeditionsCount = 1 THEN

				SET vPosition = 'FIRST';

			ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN

				SET vPosition = 'LAST';
			
			ELSEIF vRestTicketsPacking THEN

				SET vPosition = 'SHARED';
			
			ELSE

				SET vPosition = 'MID';
			
		END IF;

ELSE

		SET vPosition = 'MID';

END IF;

RETURN vPosition;

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

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

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

	SELECT province INTO vProvince
		FROM address
		WHERE id = vAddress;

	DROP TEMPORARY TABLE IF EXISTS tmp.agencyAvailable;
	CREATE TEMPORARY TABLE tmp.agencyAvailable
		(INDEX (agency))
		ENGINE = MEMORY
		SELECT agency, warehouse
			FROM agencyHour h
			WHERE (province = vProvince
					OR province IS NULL)
				AND (weekDay = vWday
					OR weekDay IS NULL)
				AND (substractDay < vMaxDays
					OR (substractDay = vMaxDays AND maxHour > vHour));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `agencyListForMethod` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `agencyListForMethod`(
	vDate DATE, vAddress INT, vMethod VARCHAR(255))
BEGIN
/**
 * Devuelve la lista de agencias disponibles para una forma
 * de envío.
 * 
 * @param vDate Fecha de recepción de mercancía
 * @param vAddress Id consignatario, %NULL para recogida
 * @param vMethod Código de la forma de envío
 * @select Lista de agencias disponibles
 */
	CALL agencyListAvailable (vDate, vAddress);

	SELECT DISTINCT m.id, m.description
		FROM tmp.agencyAvailable a
			JOIN agencyMode m
				ON m.agency = a.agency
			JOIN deliveryMethod d
				ON d.id = m.deliveryMethod
		WHERE d.code = vMethod COLLATE 'utf8_unicode_ci';			

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

    DECLARE vDateShort DATETIME;

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

	DELETE FROM vn.message WHERE sendDate < vDateShort;
    DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
    DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
    
	INSERT INTO vn.dailyTaskLog(state) VALUES('clean END');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientFreeze` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientFreeze`()
BEGIN

	IF day(CURDATE()) IN (10,20,30) THEN
		
		UPDATE vn.client c
			JOIN bi.defaulters d ON d.client = c.id AND d.date = CURDATE()
			JOIN vn.config ON TRUE
			SET c.isFreezed = TRUE
		WHERE d.amount > config.defaultersMaxAmount;
		
    END IF;
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `copyComponentsFromSaleList` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `copyComponentsFromSaleList`(vTargetTicketFk INT)
BEGIN

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

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

	SET @order = 0;

	DROP TEMPORARY TABLE IF EXISTS tmp.newSaleList;

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

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

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `createExternalWorkerkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `createExternalWorkerkk`(
    vFirstName VARCHAR(50),
    vSurname1 VARCHAR(50),
    vSurname2 VARCHAR(50),
    vUser VARCHAR(20),
    vPassword VARCHAR(50),
    vWorkerCode VARCHAR(3)
    )
BEGIN

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

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

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

    DECLARE done BOOL DEFAULT FALSE;

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

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

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

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

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

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

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

    WHILE NOT done DO

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

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

            SELECT LAST_INSERT_ID() 
                INTO vCompra;

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


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

    END WHILE;


    CLOSE rs;



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

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

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

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

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

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

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

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

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

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


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



END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceExpenceMake`(IN vInvoice INT)
BEGIN
/* Inserta las partidas de gasto correspondientes a la factura
 * REQUIERE tabla ticketToInvoice
 *
 * @param vInvoice Numero de factura
 *
 */
	DELETE FROM invoiceOutExpence
		WHERE invoiceOutFk = vInvoice;

	INSERT INTO invoiceOutExpence(
									invoiceOutFk,
									expenceFk,
									amount
								)
		SELECT
			vInvoice,
			expenceFk,
			SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount
			FROM ticketToInvoice t
				JOIN sale s ON s.ticketFk = t.id
				JOIN item i ON i.id = s.itemFk
			GROUP BY i.expenceFk
			HAVING amount != 0;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromAddress` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceFromAddress`(vMaxTicketDate DATETIME,vAddress INT,vCompany INT)
BEGIN    

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

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromClient` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceFromClient`(vMaxTicketDate DATETIME, vClient INT, vCompany INT)
BEGIN    

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

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

	DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`;
    
	CREATE TEMPORARY TABLE `ticketToInvoice`
	(PRIMARY KEY  (`id`))
        ENGINE = MEMORY
        SELECT id FROM vn.ticket
            WHERE id = vTicket AND refFk IS NULL;

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

	DROP TEMPORARY TABLE IF EXISTS newInvoiceIn;

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

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

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

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

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

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

	-- Iva Importacion pendiente

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

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

        -- Linea iva importacion extracomunitaria

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

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

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

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

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

	DROP TEMPORARY TABLE IF EXISTS newInvoiceIn;

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

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

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

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

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

	SET vBookNumberPlus1 = vBookNumber + 1;

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

	-- Apunte del proveedor

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

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

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

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

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

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

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

	-- Linea iva inversor sujeto pasivo

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

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

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

	-- Iva Importacion pendiente

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

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


	-- Linea iva importacion extracomunitaria

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

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

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

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

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

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

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

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

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

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

	-- Linea iva inversor sujeto pasivo

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

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

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

-- Actualización del registro original        
	UPDATE invoiceIn ii
		JOIN newInvoiceIn ni ON ii.id = ni.id
		SET 
			ii.serialNumber = vSerialNumber,
			ii.isBooked = TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingMainkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInBookingMainkk`(vInvoiceInId INT)
BEGIN
	DECLARE vTotalAmount DECIMAL(10,2);
    DECLARE vBookNumber,vSerialNumber INT;
    
    CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber);
       
    SELECT SUM(iit.taxableBase * IF(i.serial = 'R', 1 +(tc.rate/100),1))
			INTO vTotalAmount
		FROM newInvoiceIn i
			JOIN invoiceInTax iit ON iit.invoiceInFk = i.id
			JOIN taxCode tc ON iit.taxCodeFk = tc.id;
        
    SELECT MAX(ASIEN) + 1 
            INTO vBookNumber
		FROM vn2008.XDiario;
 
	-- Apunte del proveedor

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

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

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

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

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

	-- Linea iva inversor sujeto pasivo

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

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

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

-- Actualización del registro original        
	UPDATE invoiceIn ii
		JOIN newInvoiceIn ni ON ii.id = ni.id
		SET 
			ii.serialNumber = vSerialNumber,
			ii.isBooked = TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceMakeByClient` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceMakeByClient`(vClientFk INT, vSerial CHAR(1), vShipped DATE, vCompanyFk INT, OUT vInvoiceId INT)
BEGIN
/**
 * Factura un ticket
 * @param vTicketFk Id del ticket
 * @param vSerial Serie de factura
 * @return Id factura
 */
	CALL invoiceFromClient(vShipped, vClientFk, vCompanyFk);
    CALL invoiceOutMake(vSerial, CURDATE(), vInvoiceId);

    IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
		CALL invoiceOutBooking(vInvoiceId);
        INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(1, 3, vInvoiceId); 
    END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceMakeByTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceMakeByTicket`(vTicketFk INT, vSerial CHAR(1), OUT vInvoiceId INT)
BEGIN
/**
 * Factura un ticket
 * @param vTicketFk Id del ticket
 * @param vSerial Serie de factura
 * @return Id factura
 */
	CALL invoiceFromTicket(vTicketFk);
    CALL invoiceOutMake(vSerial, CURDATE(), vInvoiceId);

    IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
		CALL invoiceOutBooking(vInvoiceId);
        INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(1, 3, vInvoiceId); 
    END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutAgain` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutAgain`(IN vInvoiceRef VARCHAR(15))
BEGIN

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

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

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

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

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

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

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

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vInvoice, vInvoiceRef;

	WHILE NOT done DO

		CALL vn.invoiceOutAgain(vInvoiceRef);

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

	CLOSE rs;

	SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBooking` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutBooking`(IN vInvoice INT)
BEGIN

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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


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

/* Reasentar facturas
*/


	DECLARE vInvoice INT;
	DECLARE vContador INT DEFAULT 0;

	DECLARE done BOOL DEFAULT FALSE;

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

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vInvoice;

	WHILE NOT done DO

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

	END WHILE;

	CLOSE rs;

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

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

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

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

DECLARE done BOOL DEFAULT FALSE;
DECLARE vInvoice INT;

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

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN rs;

FETCH rs INTO vInvoice;

SELECT vInvoice, done;

WHILE NOT done DO

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

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

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

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

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

FETCH rs INTO vInvoice;

END WHILE;


CLOSE rs;


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

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

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutMake`(
	vSerial VARCHAR(255),
	vInvoiceDate DATETIME,
	OUT vNewInvoiceId INT)
BEGIN

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

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

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

    -- Eliminem els tickets que no han de ser facturats
	DELETE ti.* 
        FROM ticketToInvoice ti 
            JOIN ticket t ON t.id = ti.id
            JOIN client c ON c.id = t.clientFk
        WHERE YEAR(t.shipped) < 2001
			OR c.isTaxDataChecked = FALSE;

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

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


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

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

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

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

		CALL invoiceExpenceMake(vNewInvoiceId);
		CALL invoiceTaxMake(vNewInvoiceId,vCountry,vTaxArea);
		
		UPDATE invoiceOut io
				JOIN (
					SELECT SUM(amount) AS total
						FROM invoiceOutExpence 
						WHERE invoiceOutFk = vNewInvoiceId
					) base
				JOIN (
					SELECT SUM(vat) AS total
						FROM invoiceOutTax 
						WHERE invoiceOutFk = vNewInvoiceId
					) vat
			SET io.amount = base.total + vat.total
			WHERE io.id = vNewInvoiceId;
		
	END IF;
    
	DROP TEMPORARY TABLE `ticketToInvoice`;
	COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutMakekk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutMakekk`(
	vSerial VARCHAR(255),
	vInvoiceDate DATETIME,
	OUT vNewInvoiceId INT)
BEGIN

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

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

	SELECT countryFk 
			INTO vCountry
		FROM supplier
		WHERE id = vCompany;
 
	  	SELECT IF(a.isEqualizated 
					AND c.countryFk = vSpainCountryCode 
                    AND i.taxAreaFk = 'NATIONAL',
				'EQU',
                i.taxAreaFk)
			INTO vTaxArea
		FROM invoiceOutSerial i
			JOIN ticketToInvoice tti 
			JOIN ticket t ON t.id = tti.id
			JOIN address a ON a.id = t.addressFk
            JOIN client c ON c.id = t.clientFk
		WHERE i.code = vSerial
        LIMIT 1;
 
	INSERT INTO dailyTaskLog(state) VALUES('invoiceOutMake 1:  START');
    
	START TRANSACTION;
	
	-- Elimina tickets sense moviments
	UPDATE ticket t 
            JOIN ticketToInvoice ti ON ti.id = t.id 
            LEFT JOIN sale s ON s.ticketFk = ti.id
            LEFT JOIN expedition e ON e.ticketFk = t.id
        SET t.shipped = '2000-02-01 00:00:00'
        WHERE s.id IS NULL AND e.id IS NULL;
        
	INSERT INTO dailyTaskLog(state) VALUES('invoiceOutMake 1.1');

    -- Eliminem els tickets que no han de ser facturats
	DELETE ti.* 
        FROM ticketToInvoice ti 
            JOIN ticket t ON t.id = ti.id
            JOIN client c ON c.id = t.clientFk
        WHERE YEAR(t.shipped) < 2001
			OR c.isTaxDataChecked = FALSE;
	INSERT INTO dailyTaskLog(state) VALUES('invoiceOutMake 1.2');

    SELECT SUM(quantity * price * (100 - discount)/100)
            INTO vIsAnySaleToInvoice
        FROM sale s 
            JOIN ticketToInvoice t on t.id = s.ticketFk;
            
	INSERT INTO dailyTaskLog(state) VALUES('invoiceOutMake 1.3');

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


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

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

		DROP TEMPORARY TABLE IF EXISTS tmp.updateInter;
        CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY
			SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador 
				FROM ticketToInvoice ti
					JOIN vn.ticketState ts ON ti.id = ts.ticket
                    JOIN state s 
				WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.id);
	
		INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador)
			SELECT * FROM tmp.updateInter;
            
	INSERT INTO logTicket (action, userFk,originFk, description) 
		SELECT 'UPDATE',account.userGetId(),ti.id, CONCAT('CREA FACTURA ',vNewRef)
			FROM ticketToInvoice ti;

	CALL invoiceExpenceMake(vNewInvoiceId);
	CALL invoiceTaxMake(vNewInvoiceId,vCountry,vTaxArea);
  	
	UPDATE invoiceOut io
			JOIN (
				SELECT SUM(amount) AS total
					FROM invoiceOutExpence 
					WHERE invoiceOutFk = vNewInvoiceId
				) base
			JOIN (
				SELECT SUM(vat) AS total
					FROM invoiceOutTax 
					WHERE invoiceOutFk = vNewInvoiceId
				) vat
		SET io.amount = base.total + vat.total
		WHERE io.id = vNewInvoiceId;
	INSERT INTO dailyTaskLog(state) VALUES('invoiceOutMake 2:  START');
		-- Retrocompatibilidad. Borrar al cambiar el informe de facturas
    UPDATE vn2008.Facturas f
            JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id
        SET f.BI16 = iot.taxableBase, f.IVA16 = iot.vat
        WHERE f.factura_id = vNewInvoiceId
            AND iot.pgcFk IN ('4770000021' ,'4770000215', '4770000002','4771000000','4770000000','4770000020');

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

    UPDATE vn2008.Facturas f
            JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id
        SET f.RE1 = iot.vat
        WHERE f.factura_id = vNewInvoiceId
            AND iot.pgcFk = '4770000110';
	END IF;
    
    
	INSERT INTO dailyTaskLog(state) VALUES('invoiceOutMake 3:  END');
    
	DROP TEMPORARY TABLE `ticketToInvoice`;
	COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpence` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutTaxAndExpence`()
BEGIN

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



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

	DECLARE done BOOL DEFAULT FALSE;

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


	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vInvoice ,vInvoiceRef;

	WHILE NOT done DO

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

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

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

	END WHILE;

	CLOSE rs;

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

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceTaxMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceTaxMake`(IN vInvoice INT, IN vCountry INT, IN vTaxArea VARCHAR(15))
BEGIN
/* Inserta los registros de iva de la factura emitida
* REQUIERE tabla ticketToInvoice
*
* @param vInvoice Id de la factura
*/
	
    DELETE FROM invoiceOutTax
			WHERE invoiceOutFk = vInvoice;
            
    INSERT INTO invoiceOutTax(
							invoiceOutFk,
							pgcFk,
							taxableBase,
							vat
							)
	SELECT vInvoice,
			bp.pgcFk,
			SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) 
                ) taxableBase,
			SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)
                ) * pgc.rate / 100
		FROM ticketToInvoice t
			JOIN sale s ON s.ticketFk = t.id
			JOIN item i ON i.id = s.itemFk
			JOIN itemTaxCountry itc 
				ON itc.itemFk = i.id AND itc.countryFk = vCountry
			JOIN bookingPlanner bp 
				ON bp.countryFk = vCountry 
					AND bp.taxAreaFk = vTaxArea
					AND bp.taxClassFk = itc.taxClassFk
			JOIN pgc ON pgc.code = bp.pgcFk
		GROUP BY pgc.code
        HAVING taxableBase != 0;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemTagArrangedUpdate` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemTagArrangedUpdate`(IN vItem BIGINT)
BEGIN
/**
 * Actualiza la tabla itemTagArranged
 *
 * @param vItem El Id_item de toda la vida. Si es cero, equivale a todos.
 **/
	DELETE 
        FROM itemTagArranged
		WHERE vItem IS NULL 
            OR vItem = itemFk;

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

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

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

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

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

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

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

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

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

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

	DECLARE isBilled BOOLEAN;
    DECLARE arrayTickets VARCHAR(255);

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

	IF NOT isBilled THEN
    
		SELECT GROUP_CONCAT(distinct T.Id_Ticket) INTO arrayTickets
		FROM vn2008.Tickets T LEFT JOIN vn.ticketState ts ON T.Id_Ticket = ts.ticket
        JOIN vn2008.Tickets ticketOriginal ON ticketOriginal.Id_Ticket = vMainTicket
									AND T.empresa_id = ticketOriginal.empresa_id 
									AND T.Id_Consigna = ticketOriginal.Id_Consigna
									AND DATE(T.Fecha) = DATE(ticketOriginal.Fecha)
									AND T.warehouse_id = ticketOriginal.warehouse_id
									AND IF(hasSameAgency <> 0,T.Id_Agencia = ticketOriginal.Id_Agencia,TRUE)
		LEFT JOIN vn.ticketState tsOriginal ON ticketOriginal.Id_Ticket = tsOriginal.ticket
		WHERE ts.alertLevel < 3
		AND T.Factura IS NULL
		AND T.Anotadoencaja = FALSE
        AND T.Id_Ticket <> vMainTicket
        AND ts.alertLevel = tsOriginal.alertLevel;
        
		CALL mergeTicketWithArray(vMainTicket,arrayTickets);
        
	END IF;	


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `mergeTicketWithArray` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `mergeTicketWithArray`(IN vMainTicket INT(11), IN arrayTickets VARCHAR(50))
BEGIN

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

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

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

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

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

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

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

		SELECT GROUP_CONCAT(Id_Ticket SEPARATOR ',') into messageLog FROM vn2008.Tickets_to_fusion;
		CALL vn2008.Ditacio(vMainTicket,'Fusion','T',worker,messageLog,NULL);
           
        DELETE ts FROM vn2008.Tickets_state ts JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket);
		/*
		UPDATE vncontrol.inter M
			JOIN vn2008.Tickets_to_fusion USING(Id_Ticket)
		SET M.Id_Ticket = vMainTicket;
        */
	END IF;	

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nestAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nestAdd`(vScheme VARCHAR(45), vTable VARCHAR(45), vParentFk INT, vChild VARCHAR(45))
BEGIN
    DECLARE vSql TEXT;
    
    -- Check parent childs
    SET vSql = sql_printf('
		SELECT COUNT(c.id) INTO @childs
			FROM %t.%t p
				LEFT JOIN %t.%t c ON c.lft BETWEEN p.lft AND p.rgt AND c.id != %v
			WHERE p.id = %v', 
		vScheme, vTable, vScheme, vTable, vParentFk, vParentFk);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    -- Select left from last child
    IF @childs = 0 THEN
		SET vSql = sql_printf('SELECT lft INTO @vLeft FROM %t.%t WHERE id = %v', vScheme, vTable, vParentFk);
		SET @qrySql := vSql;
    ELSE
        SET vSql = sql_printf('
			SELECT c.rgt INTO @vLeft 
				FROM %t.%t p 
					JOIN %t.%t c ON c.lft BETWEEN p.lft AND p.rgt 
				WHERE p.id = %v 
				ORDER BY c.lft 
				DESC LIMIT 1', 
			vScheme, vTable, vScheme, vTable, vParentFk);
		SET @qrySql := vSql;
    END IF;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    -- Update right
	SET vSql = sql_printf('UPDATE %t.%t SET rgt = rgt + 2 WHERE rgt > %v ORDER BY rgt DESC', vScheme, vTable, @vLeft);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    SET vSql = sql_printf('UPDATE %t.%t SET lft = lft + 2 WHERE lft > %v ORDER BY lft DESC', vScheme, vTable, @vLeft);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    -- Escape character
    SET vChild = REPLACE(vChild, "'", "\\'");
    
    -- Add child
    SET vSql = sql_printf('INSERT INTO %t.%t (name, lft, rgt) VALUES (%v, %v, %v)', vScheme, vTable, vChild, @vLeft + 1, @vLeft + 2);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nestLeave` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nestLeave`(vScheme VARCHAR(45), vTable VARCHAR(45), vParentFk INT)
BEGIN
	DECLARE vSql TEXT;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.tree;
	
    SET vSql = sql_printf('
		CREATE TEMPORARY TABLE tmp.tree ENGINE = MEMORY
		SELECT 
				node.id, 
				node.name,
				node.lft, 
				node.rgt, 
				node.depth, 
				node.sons
			FROM 
				%t.%t AS node,
				%t.%t AS parent
			WHERE 
				node.lft BETWEEN parent.lft AND parent.rgt 
				AND node.depth = parent.depth + 1
				AND parent.id = %v
			GROUP BY node.id
			ORDER BY node.lft',
		vScheme, vTable, vScheme, vTable, vParentFk);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nestTree` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nestTree`(
	vSourceSchema VARCHAR(45), 
	vSourceTable VARCHAR(45), 
	vDestinationSchema VARCHAR(45), 
	vDestinationTable VARCHAR(45))
BEGIN
	DECLARE vSql TEXT;
    
	
	SET vSql = sql_printf('DROP TABLE IF EXISTS %t.%t', vDestinationSchema, vDestinationTable);
	SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
	
    SET vSql = sql_printf('
		CREATE TABLE %t.%t
			SELECT 
					node.id, 
					node.name,
					node.lft, 
					node.rgt, 
					COUNT(parent.id) - 1 depth, 
					CAST((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons
				FROM 
					%t.%t AS node,
					%t.%t AS parent
				WHERE node.lft BETWEEN parent.lft AND parent.rgt
				GROUP BY node.id
				ORDER BY node.lft',
		vDestinationSchema, vDestinationTable, vSourceSchema, vSourceTable, vSourceSchema, vSourceTable);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `noticeSend` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `noticeSend`(vCategoryKey VARCHAR(50), vSender INT, vRecipient INT, vBody TEXT)
BEGIN
    DECLARE vCategoryId INT;
    DECLARE vIsEnabled TINYINT(1);
    
	-- Obtenemos los datos de la categoría
	SELECT c.id, c.isEnabled INTO vCategoryId, vIsEnabled FROM vn.noticeCategory c WHERE keyName = vCategoryKey;
    
    IF vn.noticeHasActive(vCategoryKey, vRecipient) AND vIsEnabled THEN

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

		SELECT vSender, vRecipient;
    END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `observationAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `observationAdd`(vOriginFk INT, vTableCode VARCHAR(45), vDescription TEXT)
BEGIN
/**
 * Guarda las observaciones realizadas por el usuario
 *
 * @param vOriginFk Id del registro de origen
 * @param vTypeCode Código que referencia a la tabla.
 * @param descripcion Texto de la observacion
 */
	DECLARE vTableName VARCHAR(45);
    
	SET vTableName = CONCAT(vTableCode,'Observation');
        
	IF ISNULL(vTableName) THEN
		CALL util.throw('CODE_NOT_FOUND');
	END IF;
    
	SET @qryLog := CONCAT(
		'INSERT INTO ', vTableName, ' (originFk, userFk,  description)',
			' VALUES (', vOriginFk, ', ', account.userGetId(), ', "', vDescription, '")'
    );
    
    PREPARE stmt FROM @qryLog;
    EXECUTE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `printTrolleyLabel` */;
ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `printTrolleyLabel`(vTicket INT, vPrinter INT, vReport INT)
BEGIN
/**
 * Inserta en la cola de impresion una nueva etiqueta de carro, para el sacador
 *
 * @param vTicket Numero del ticket
 * @param vPrinter Numero de impresora
 * @param vReport Numero del informe
 **/
	DECLARE vlabelCount INT DEFAULT 0;
	DECLARE PRIORITY INT DEFAULT 3;
	DECLARE vWorker INT;
	DECLARE vShipmentHour VARCHAR(10);

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

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

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

	SELECT customer, TIMESTAMPADD(DAY, 1,shipment), warehouse, company, address 
			INTO vCustomer, vNewDate, vWarehouse, vCompany, vAddress
		FROM ticket 
        WHERE id = vMainTicket;

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

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

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleSplit` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `saleSplit`(IN vIdMovement BIGINT, IN vQuantity  int)
BEGIN
 	DECLARE vId INT;
    DECLARE vCreated DATE;
    DECLARE vWarehouseId INT;
    DECLARE vCompanyId INT;
    DECLARE vAddressId INT;
    DECLARE vAgencyMode INT;
    DECLARE vNewTicketId BIGINT;
    DECLARE vNewSale BIGINT;
    DECLARE vLanded DATE;
	DECLARE vStarted DATETIME;
	DECLARE vEnded DATETIME;
    DECLARE vCurrentTicket INT;
    


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

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

	INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount)
		SELECT vNewTicketId, itemFk, Concept, vQuantity, price, discount
		FROM sale
		WHERE id = vIdMovement;
	
	SELECT LAST_INSERT_ID() INTO vNewSale;
	
	INSERT INTO saleComponent(saleFk, componentFk, `value`)
		SELECT vNewSale, componentFk, `value`
		FROM saleComponent 
		WHERE saleFk = vIdMovement;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `solunionRiskRequest` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `solunionRiskRequest`()
BEGIN
	
	DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
    CREATE TEMPORARY TABLE tmp.client_list
    (PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
		SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc 
				JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification
                WHERE dateEnd IS NULL
                ORDER BY ci.creationDate DESC) t1 GROUP BY Id_Cliente;
    
    CALL vn2008.risk_vs_client_list(CURDATE());
    
	SELECT 
		c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo,
        cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo,
		f.Consumo consumo_anual, c.Vencimiento, ci.grade
	FROM
		vn2008.Clientes c
			JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente
			JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente
			JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente
		GROUP BY Id_cliente;
        
	DROP TEMPORARY TABLE IF EXISTS tmp.risk;
    DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `stockBuyed` */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `stockBuyed`(vDate DATE)
BEGIN
	DECLARE vVolume DECIMAL(10,2);
	DECLARE vWarehouse INT DEFAULT 7;
    
	CALL stockTraslation(vDate);

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

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

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

     DECLARE vWarehouse INT DEFAULT 7;

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

    CALL `cache`.stock_refresh (FALSE);

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

    CALL vn2008.item_last_buy_(vWarehouse,vDate);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stockTraslationkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `stockTraslationkk`(vDate DATE)
BEGIN
	/**
	 * Calcula el stock del vWarehouse desde FechaInventario hasta v_date
		sin tener en cuenta las salidas del mismo dia vDate
		para ver el transporte a reservar
	 **/

	DECLARE vWarehouse INT DEFAULT 7;

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

    CALL `cache`.stock_refresh (FALSE);

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

    CALL vn2008.item_last_buy_(vWarehouse,vDate);
    
    select * FROM tmp.item;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stockTraslationTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `stockTraslationTest`(vDate DATE)
BEGIN
	/**
	 * Calcula el stock del vWarehouse desde FechaInventario hasta v_date
		sin tener en cuenta las salidas del mismo dia vDate
		para ver el transporte a reservar
	 **/

	DECLARE vWarehouse INT DEFAULT 7;

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

    CALL `cache`.stock_refresh (FALSE);

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

    CALL vn2008.item_last_buy_(vWarehouse,vDate);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `taxGetRates` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `taxGetRates`(vTaxDate DATE)
    READS SQL DATA
BEGIN
/**
 * Calcula una tabla con el IVA aplicable para la fecha data.
 *
 * @param vTaxDate
 * @treturn tmp.taxGroup
 * @treturn tmp.taxTax
 */
    SET vTaxDate = IFNULL(vTaxDate, CURDATE());

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

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

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

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

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

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

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

        IF vDone THEN
			LEAVE proc;
		END IF;

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

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

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

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

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

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

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

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

	INSERT INTO tmp.ticketClosureAgencyList(agencyModeFk) VALUES(vAgencyModeFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClosurekk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosurekk`()
BEGIN
/**
 * Realiza el cierre de todos los 
 * tickets de la table ticketClosure.
 */

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

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

        IF vDone THEN
			LEAVE proc;
		END IF;

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

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

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

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

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

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

            END IF;
		ELSE
			-- Albaran_print
			CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), 20);
            INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); 
        END IF;
        
		-- ticketClosure end
	END LOOP;
	
	CLOSE cur;
    
    INSERT INTO dailyTaskLog(state) VALUES('ticketClosure: END');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureMultiWarehouse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureMultiWarehouse`(vDateTo DATE)
BEGIN
/**
 * Inserta los tickets de todos los almacenes en la tabla temporal
 * para ser cerrados.
 *
 * @param vDate Fecha del cierre
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

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

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

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

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

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

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

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

	CREATE TEMPORARY TABLE ticketClosure ENGINE = MEMORY(
		SELECT 
			t.id AS ticketFk
		FROM expedition e
			INNER JOIN ticket t ON t.id = e.ticketFk
			LEFT JOIN ticketState ts ON ts.ticketFk = t.id
		WHERE 
			ts.alertLevel = 2 
			AND t.warehouseFk = vWarehouseFk
			AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo
			AND t.refFk IS NULL
		GROUP BY e.ticketFk);
        
	CALL ticketClosure();
    
    DROP TEMPORARY TABLE tmp.ticketClosure;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketCreate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreate`(
                       IN vClientId INT
                     , IN vShipped DATE
                     , IN vWarehouseId INT
                     , IN vCompanyFk INT
                     , IN vAddressFk INT
                     , IN vAgencyType INT
                     , IN vRouteFk INT
                     , IN vlanded DATE
                     , OUT vNewTicket INT)
BEGIN
 DECLARE vClientOrnamentales INT DEFAULT 5270;
    DECLARE vCompanyOrn INT DEFAULT 1381;
    DECLARE vProvinceName VARCHAR(255);
        
 SELECT p.name INTO vProvinceName
  FROM vn.client c
   JOIN province p ON p.id = c.provinceFk
        WHERE c.id = vClientId;
        
 IF vProvinceName  IN ('SANTA CRUZ DE TENERIFE','LAS PALMAS DE GRAN CANARIA') AND vClientId <> vClientOrnamentales THEN
  SET vCompanyFk = vCompanyOrn;
 END IF;

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

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


   CALL logAdd(vNewTicket,'insert','ticket',concat('CREA EL TICKET',' ',vNewTicket));
   
    IF (SELECT isCreatedAsServed FROM vn.client WHERE id = vClientId ) <> 0
  THEN
   INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
    SELECT id, vNewTicket, getWorker()
     FROM state 
     WHERE `code` = 'DELIVERED';
 END IF;
   

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTax` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTax`(vBillingDate DATE)
    READS SQL DATA
BEGIN
/**
 * Calcula la base imponible, el IVA y el recargo de equivalencia para
 * un conjunto de tickets.
 *
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @param vBillingDate Fecha de facturación
 * @treturn tmp.ticketTax Impuesto desglosado para cada ticket
 */
	CALL vn.taxGetRates (vBillingDate);

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

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
	CREATE TEMPORARY TABLE tmp.ticketTax
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT t.ticketFk, t.type, t.taxBase, 
				CAST(IF(t.hasTax, t.taxBase * x.rate, 0) AS DECIMAL(10,2)) tax, 
				CAST(IF(t.hasEqualizationTax, t.taxBase * x.equalizationTax, 0) AS DECIMAL(10,2)) equalizationTax
			FROM (
				SELECT i.ticketFk, g.countryFk, g.type
						,SUM(CAST(m.quantity * m.price * (100 - m.discount) / 100 AS DECIMAL(10,2))) AS taxBase
						,NOT(c.isVies AND p.countryFk <> c.countryFk) hasTax
						,c.isEqualizated != FALSE AS hasEqualizationTax
					FROM tmp.ticket i
						JOIN vn.ticket t ON t.id = i.ticketFk
						JOIN vn.sale m ON m.ticketFk = t.id
						JOIN vn.item a ON a.id = m.itemFk
						JOIN vn.client c ON c.id = t.clientFk
						JOIN vn.supplier p ON p.id = t.companyFk
						JOIN tmp.taxClass g
							ON g.countryFk = p.countryFk AND g.taxClassFk = a.taxClassFk
					GROUP BY i.ticketFk, g.type
			) t
			JOIN tmp.taxType x
				ON x.countryFk = t.countryFk AND x.type = t.type;

	DROP TEMPORARY TABLE
		tmp.taxClass,
		tmp.taxType;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTotal` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTotal`()
    READS SQL DATA
BEGIN
/**
 * Calcula el total con IVA para un conjunto de tickets.
 *
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @treturn tmp.ticketTotal Total para cada ticket
 */
	CALL ticketGetTax (NULL);
	
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal;
	CREATE TEMPORARY TABLE tmp.ticketTotal
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT ticketFk, SUM(taxBase + tax + equalizationTax) AS total
			FROM tmp.ticketTax GROUP BY ticketFk;
	
	DROP TEMPORARY TABLE tmp.ticketTax;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByAddress` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByAddress`(
                                                            vStarted DATE,
															vEnded DATETIME,
															vAddress INT,
															vCompany INT
															)
BEGIN

	SET vEnded = util.dayEnd(vEnded);

    DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice;

    CREATE TEMPORARY TABLE vn.ticketToInvoice
        SELECT id
            FROM vn.ticket
            WHERE addressFk = vAddress
                AND companyFk = vCompany
                AND shipped BETWEEN vStarted AND vEnded
                AND refFk IS NULL;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByClient` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByClient`(
                                                            vStarted DATE,
															vEnded DATETIME,
															vClient INT,
															vCompany INT
															)
BEGIN

	SET vEnded = util.dayEnd(vEnded);

    DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice;

    CREATE TEMPORARY TABLE vn.ticketToInvoice
        SELECT id
            FROM vn.ticket
            WHERE clientFk = vClient
                AND companyFk = vCompany
                AND shipped BETWEEN vStarted AND vEnded
                AND refFk IS NULL;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByDate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByDate`(
                                                            vStarted DATE,
															vEnded DATETIME,
															vClient INT,
															vCompany INT
															)
BEGIN

	SET vEnded = util.dayEnd(vEnded);

    DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice;

    CREATE TEMPORARY TABLE vn.ticketToInvoice
        SELECT id
            FROM vn.ticket
            WHERE clientFk = vClient
                AND companyFk = vCompany
                AND shipped BETWEEN vStarted AND vEnded
                AND refFk IS NULL;

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

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

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

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

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

    DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice;

        CREATE TEMPORARY TABLE vn.ticketToInvoice
            SELECT id
                FROM vn.ticket
                WHERE id = vTicket
                    AND refFk IS NULL;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketTrackingAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketTrackingAdd`(vTicketFk INT, vState VARCHAR(25) CHARSET UTF8, vWorkerFk INT)
BEGIN
/**
 * Inserta un registro de cambios en un ticket.
 * @param vTicketFk Id del ticket
 * @param vState Código del estado
 * @param vWorkerFk Id del trabajador
 */
	INSERT INTO ticketTracking (stateFk, ticketFk, workerFk)
		SELECT s.id, vTicketFk, vWorkerFk FROM state s WHERE s.code = vState;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerCreateExternal` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerCreateExternal`(
    vFirstName VARCHAR(50),
    vSurname1 VARCHAR(50),
    vSurname2 VARCHAR(50),
    vUser VARCHAR(20),
    vPassword VARCHAR(50),
    vWorkerCode VARCHAR(3),
    vRole INT(2)
    )
BEGIN

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

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

	DELETE FROM account.account
		WHERE id = vUserId;

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

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

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


-- Dump completed on 2017-12-27  7:51:23
