diff --git a/.dockerignore b/.dockerignore
index afe81bb0f..1a47908ab 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,4 +1,6 @@
node_modules
print/node_modules
-front/node_modules
-services
\ No newline at end of file
+front
+db
+e2e
+storage
diff --git a/.gitignore b/.gitignore
index b741a2d44..895a6a8dc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,4 @@ print.*.json
db.json
junit.xml
.DS_Store
+storage
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 05d23f3bb..03479d27a 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -3,12 +3,20 @@
// Carácter predeterminado de final de línea.
"files.eol": "\n",
"editor.codeActionsOnSave": {
- "source.fixAll.eslint": true
+ "source.fixAll.eslint": "explicit"
},
"search.useIgnoreFiles": false,
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"eslint.format.enable": true,
"[javascript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
- }
+ },
+ "[json]": {
+ "editor.defaultFormatter": "vscode.json-language-features"
+ },
+ "cSpell.words": [
+ "salix",
+ "fdescribe",
+ "Loggable"
+ ]
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d677b80e3..c031a3874 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,263 +5,347 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-## [2342.01] - 2023-10-19
+## [24.16.01] - 2024-04-18
+
+## [2414.01] - 2024-04-04
+
+## [2408.01] - 2024-02-22
+
+## [2406.01] - 2024-02-08
### Added
+
### Changed
+
### Fixed
+## [2404.01] - 2024-01-25
+
+### Added
+
+### Changed
+
+### Fixed
+
+## [2402.01] - 2024-01-11
+
+### Added
+
+### Changed
+
+### Fixed
+
+## [2400.01] - 2024-01-04
+
+### Added
+
+### Changed
+
+### Fixed
+
+## [2350.01] - 2023-12-14
+
+### Características Añadidas 🆕
+
+- **Tickets → Expediciones:** Añadido soporte para Viaexpress
+
+## [2348.01] - 2023-11-30
+
+### Características Añadidas 🆕
+
+- **Tickets → Adelantar:** Permite mover lineas sin generar negativos
+- **Tickets → Adelantar:** Permite modificar la fecha de los tickets
+- **Trabajadores → Notificaciones:** Nueva sección (lilium)
+
+### Correcciones 🛠️
+
+- **Tickets → RocketChat:** Arreglada detección de cambios
+
+## [2346.01] - 2023-11-16
+
+### Added
+
+### Changed
+
+### Fixed
+
+## [2342.01] - 2023-11-02
+
+### Added
+
+- (Usuarios -> Foto) Se muestra la foto del trabajador
+
+### Fixed
+
+- (Usuarios -> Historial) Abre el descriptor del usuario correctamente
+
## [2340.01] - 2023-10-05
-### Added
-- (Usuarios -> Foto) Se muestra la foto del trabajador
-
-### Changed
-### Fixed
-- (Usuarios -> Historial) Abre el descriptor del usuario correctamente
-
## [2338.01] - 2023-09-21
### Added
-- (Ticket -> Servicios) Se pueden abonar servicios
-- (Facturas -> Datos básicos) Muestra valores por defecto
-- (Facturas -> Borrado) Notificación al borrar un asiento ya enlazado en Sage
-### Changed
-- (Trabajadores -> Calendario) Icono de check arreglado cuando pulsas un tipo de dia
-### Fixed
+- (Ticket -> Servicios) Se pueden abonar servicios
+- (Facturas -> Datos básicos) Muestra valores por defecto
+- (Facturas -> Borrado) Notificación al borrar un asiento ya enlazado en Sage
+
+### Changed
+
+- (Trabajadores -> Calendario) Icono de check arreglado cuando pulsas un tipo de dia
## [2336.01] - 2023-09-07
-### Added
-
-### Changed
-
-### Fixed
-
-
## [2334.01] - 2023-08-24
### Added
-- (General -> Errores) Botón para enviar cau con los datos del error
+- (General -> Errores) Botón para enviar cau con los datos del error
## [2332.01] - 2023-08-10
### Added
-- (Trabajadores -> Gestión documental) Soporte para Docuware
-- (General -> Agencia) Soporte para Viaexpress
-- (Tickets -> SMS) Nueva sección en Lilium
+
+- (Trabajadores -> Gestión documental) Soporte para Docuware
+- (General -> Agencia) Soporte para Viaexpress
+- (Tickets -> SMS) Nueva sección en Lilium
### Changed
-- (General -> Tickets) Devuelve el motivo por el cual no es editable
-- (Desplegables -> Trabajadores) Mejorados
-- (General -> Clientes) Razón social y dirección en mayúsculas
+
+- (General -> Tickets) Devuelve el motivo por el cual no es editable
+- (Desplegables -> Trabajadores) Mejorados
+- (General -> Clientes) Razón social y dirección en mayúsculas
### Fixed
-- (Clientes -> SMS) Al pasar el ratón por encima muestra el mensaje completo
+- (Clientes -> SMS) Al pasar el ratón por encima muestra el mensaje completo
## [2330.01] - 2023-07-27
### Added
-- (Artículos -> Vista Previa) Añadido campo "Plástico reciclado"
-- (Rutas -> Troncales) Nueva sección
-- (Tickets -> Opciones) Opción establecer peso
-- (Clientes -> SMS) Nueva sección
+
+- (Artículos -> Vista Previa) Añadido campo "Plástico reciclado"
+- (Rutas -> Troncales) Nueva sección
+- (Tickets -> Opciones) Opción establecer peso
+- (Clientes -> SMS) Nueva sección
### Changed
-- (General -> Iconos) Añadidos nuevos iconos
-- (Clientes -> Razón social) Permite crear clientes con la misma razón social según el país
+- (General -> Iconos) Añadidos nuevos iconos
+- (Clientes -> Razón social) Permite crear clientes con la misma razón social según el país
## [2328.01] - 2023-07-13
### Added
-- (Clientes -> Morosos) Añadida columna "es trabajador"
-- (Trabajadores -> Departamentos) Nueva sección
-- (Trabajadores -> Departamentos) Añadido listado de Trabajadores por departamento
-- (Trabajadores -> Departamentos) Añadido características de departamento e información
+
+- (Clientes -> Morosos) Añadida columna "es trabajador"
+- (Trabajadores -> Departamentos) Nueva sección
+- (Trabajadores -> Departamentos) Añadido listado de Trabajadores por departamento
+- (Trabajadores -> Departamentos) Añadido características de departamento e información
### Changed
### Fixed
-- (Trabajadores -> Departamentos) Arreglado búscador
+- (Trabajadores -> Departamentos) Arreglado búscador
## [2326.01] - 2023-06-29
### Added
-- (Entradas -> Correo) Al cambiar el tipo de cambio enviará un correo a las personas designadas
-- (General -> Históricos) Botón para ver el estado del registro en cada punto
-- (General -> Históricos) Al filtar por registro se muestra todo el histórial desde que fue creado
-- (Tickets -> Índice) Permite enviar varios albaranes a Docuware
+
+- (Entradas -> Correo) Al cambiar el tipo de cambio enviará un correo a las personas designadas
+- (General -> Históricos) Botón para ver el estado del registro en cada punto
+- (General -> Históricos) Al filtar por registro se muestra todo el histórial desde que fue creado
+- (Tickets -> Índice) Permite enviar varios albaranes a Docuware
### Changed
-- (General -> Históricos) Los registros se muestran agrupados por usuario y entidad
-- (Facturas -> Facturación global) Optimizada, generación de PDFs y notificaciones en paralelo
+
+- (General -> Históricos) Los registros se muestran agrupados por usuario y entidad
+- (Facturas -> Facturación global) Optimizada, generación de PDFs y notificaciones en paralelo
### Fixed
-- (General -> Históricos) Duplicidades eliminadas
-- (Facturas -> Facturación global) Solucionados fallos que paran el proceso
+
+- (General -> Históricos) Duplicidades eliminadas
+- (Facturas -> Facturación global) Solucionados fallos que paran el proceso
## [2324.01] - 2023-06-15
### Added
-- (Tickets -> Abono) Al abonar permite crear el ticket abono con almacén o sin almmacén
-- (General -> Desplegables) Mejorada eficiencia de carga de datos
-- (General -> Históricos) Ahora, ademas de los ids, se muestra la descripión de los atributos
-- (General -> Históricos) Botón para hacer más ágil mostrar sólo los cambios en un registro
-- (General -> Históricos) Filtro por cambios
+
+- (Tickets -> Abono) Al abonar permite crear el ticket abono con almacén o sin almmacén
+- (General -> Desplegables) Mejorada eficiencia de carga de datos
+- (General -> Históricos) Ahora, ademas de los ids, se muestra la descripión de los atributos
+- (General -> Históricos) Botón para hacer más ágil mostrar sólo los cambios en un registro
+- (General -> Históricos) Filtro por cambios
### Changed
-- (General -> Permisos) Mejorada seguridad
-- (General -> Históricos) Elementos de la interfaz reorganizados para hacerla más ágil e intuitiva
+
+- (General -> Permisos) Mejorada seguridad
+- (General -> Históricos) Elementos de la interfaz reorganizados para hacerla más ágil e intuitiva
### Fixed
+
-
-
-
## [2322.01] - 2023-06-01
### Added
-- (Tickets -> Crear Factura) Al facturar se envia automáticamente el pdf al cliente
-- (Artículos -> Histórico) Filtro para mostrar lo anterior al inventario
-- (Trabajadores -> Nuevo trabajador) Permite elegir el método de pago
+
+- (Tickets -> Crear Factura) Al facturar se envia automáticamente el pdf al cliente
+- (Artículos -> Histórico) Filtro para mostrar lo anterior al inventario
+- (Trabajadores -> Nuevo trabajador) Permite elegir el método de pago
### Changed
-- (Trabajadores -> Nuevo trabajador) Los clientes se crean sin 'TR' pero se añade tipo de negocio 'Trabajador'
-- (Tickets -> Expediciones) Interfaz mejorada y contador añadido
+
+- (Trabajadores -> Nuevo trabajador) Los clientes se crean sin 'TR' pero se añade tipo de negocio 'Trabajador'
+- (Tickets -> Expediciones) Interfaz mejorada y contador añadido
+
### Fixed
-- (Tickets -> Líneas) Se permite hacer split de líneas al mismo ticket
-- (Tickets -> Cambiar estado) Ahora muestra la lista completa de todos los estados
-
+- (Tickets -> Líneas) Se permite hacer split de líneas al mismo ticket
+- (Tickets -> Cambiar estado) Ahora muestra la lista completa de todos los estados
## [2320.01] - 2023-05-25
### Added
-- (Tickets -> Crear Factura) Al facturar se envia automáticamente el pdf al cliente
+- (Tickets -> Crear Factura) Al facturar se envia automáticamente el pdf al cliente
### Changed
-- (Trabajadores -> Nuevo trabajador) Los clientes se crean sin 'TR' pero se añade tipo de negocio 'Trabajador'
+
+- (Trabajadores -> Nuevo trabajador) Los clientes se crean sin 'TR' pero se añade tipo de negocio 'Trabajador'
### Fixed
+
-
-
-
## [2318.01] - 2023-05-08
### Added
-- (Usuarios -> Histórico) Nueva sección
-- (Roles -> Histórico) Nueva sección
-- (Trabajadores -> Dar de alta) Permite elegir el método de pago
+
+- (Usuarios -> Histórico) Nueva sección
+- (Roles -> Histórico) Nueva sección
+- (Trabajadores -> Dar de alta) Permite elegir el método de pago
### Changed
-- (Artículo -> Precio fijado) Modificado el buscador superior por uno lateral
-- (Trabajadores -> Dar de alta) Quitada obligatoriedad del iban
+
+- (Artículo -> Precio fijado) Modificado el buscador superior por uno lateral
+- (Trabajadores -> Dar de alta) Quitada obligatoriedad del iban
### Fixed
-- (Ticket -> Boxing) Arreglado selección de horas
-- (Cesta -> Índice) Optimizada búsqueda
-
+- (Ticket -> Boxing) Arreglado selección de horas
+- (Cesta -> Índice) Optimizada búsqueda
## [2314.01] - 2023-04-20
### Added
-- (Clientes -> Morosos) Ahora se puede filtrar por las columnas "Desde" y "Fecha Ú. O.". También se envia un email al comercial cuando se añade una nota.
-- (Monitor tickets) Muestra un icono al lado de la zona, si el ticket es frágil y se envía por agencia
-- (Facturas recibidas -> Bases negativas) Nueva sección
+
+- (Clientes -> Morosos) Ahora se puede filtrar por las columnas "Desde" y "Fecha Ú. O.". También se envia un email al comercial cuando se añade una nota.
+- (Monitor tickets) Muestra un icono al lado de la zona, si el ticket es frágil y se envía por agencia
+- (Facturas recibidas -> Bases negativas) Nueva sección
### Fixed
-- (Clientes -> Morosos) Ahora se mantienen los elementos seleccionados al hacer sroll.
+
+- (Clientes -> Morosos) Ahora se mantienen los elementos seleccionados al hacer sroll.
## [2312.01] - 2023-04-06
### Added
-- (Monitor tickets) Muestra un icono al lado de la zona, si el ticket es frágil y se envía por agencia
+
+- (Monitor tickets) Muestra un icono al lado de la zona, si el ticket es frágil y se envía por agencia
### Changed
-- (Monitor tickets) Cuando se filtra por 'Pendiente' ya no muestra los estados de 'Previa'
-- (Envíos -> Extra comunitarios) Se agrupan las entradas del mismo travel. Añadidos campos Referencia y Importe.
-- (Envíos -> Índice) Cambiado el buscador superior por uno lateral
+
+- (Monitor tickets) Cuando se filtra por 'Pendiente' ya no muestra los estados de 'Previa'
+- (Envíos -> Extra comunitarios) Se agrupan las entradas del mismo travel. Añadidos campos Referencia y Importe.
+- (Envíos -> Índice) Cambiado el buscador superior por uno lateral
## [2310.01] - 2023-03-23
### Added
-- (Trabajadores -> Control de horario) Ahora se puede confirmar/no confirmar el registro horario de cada semana desde esta sección
+
+- (Trabajadores -> Control de horario) Ahora se puede confirmar/no confirmar el registro horario de cada semana desde esta sección
### Fixed
-- (Clientes -> Listado extendido) Resuelto error al filtrar por clientes inactivos desde la columna "Activo"
-- (General) Al pasar el ratón por encima del icono de "Borrar" en un campo, se hacía más grande afectando a la interfaz
+
+- (Clientes -> Listado extendido) Resuelto error al filtrar por clientes inactivos desde la columna "Activo"
+- (General) Al pasar el ratón por encima del icono de "Borrar" en un campo, se hacía más grande afectando a la interfaz
## [2308.01] - 2023-03-09
### Added
-- (Proveedores -> Datos fiscales) Añadido checkbox 'Vies'
-- (Client -> Descriptor) Nuevo icono $ con barrotes para los clientes con impago
-- (Trabajador -> Datos Básicos) Añadido nuevo campo Taquilla
-- (Trabajador -> PDA) Nueva sección
+
+- (Proveedores -> Datos fiscales) Añadido checkbox 'Vies'
+- (Client -> Descriptor) Nuevo icono $ con barrotes para los clientes con impago
+- (Trabajador -> Datos Básicos) Añadido nuevo campo Taquilla
+- (Trabajador -> PDA) Nueva sección
### Changed
-- (Ticket -> Borrar ticket) Restringido el borrado de tickets con abono
+
+- (Ticket -> Borrar ticket) Restringido el borrado de tickets con abono
## [2306.01] - 2023-02-23
### Added
-- (Tickets -> Datos Básicos) Mensaje de confirmación al intentar generar tickets con negativos
-- (Artículos) El visible y disponible se calcula a partir de un almacén diferente dependiendo de la sección en la que te encuentres. Se ha añadido un icono que informa sobre a partir de que almacén se esta calculando.
+
+- (Tickets -> Datos Básicos) Mensaje de confirmación al intentar generar tickets con negativos
+- (Artículos) El visible y disponible se calcula a partir de un almacén diferente dependiendo de la sección en la que te encuentres. Se ha añadido un icono que informa sobre a partir de que almacén se esta calculando.
### Changed
-- (General -> Inicio) Ahora permite recuperar la contraseña tanto con el correo de recuperación como el usuario
+
+- (General -> Inicio) Ahora permite recuperar la contraseña tanto con el correo de recuperación como el usuario
### Fixed
-- (Monitor de tickets) Cuando ordenas por columna, ya no se queda deshabilitado el botón de 'Actualizar'
-- (Zone -> Días de entrega) Al hacer click en un día, muestra correctamente las zonas
-- (Artículos) El disponible en la vista previa se muestra correctamente
+
+- (Monitor de tickets) Cuando ordenas por columna, ya no se queda deshabilitado el botón de 'Actualizar'
+- (Zone -> Días de entrega) Al hacer click en un día, muestra correctamente las zonas
+- (Artículos) El disponible en la vista previa se muestra correctamente
## [2304.01] - 2023-02-09
### Added
-- (Rutas) Al descargar varias facturas se comprime en un zip
-- (Trabajadores -> Nuevo trabajador) Nueva sección
-- (Tickets -> Adelantar tickets) Añadidos campos "líneas" y "litros" al ticket origen
-- (Tickets -> Adelantar tickets) Nuevo icono muestra cuando las agencias de los tickets origen/destino son distintas
+
+- (Rutas) Al descargar varias facturas se comprime en un zip
+- (Trabajadores -> Nuevo trabajador) Nueva sección
+- (Tickets -> Adelantar tickets) Añadidos campos "líneas" y "litros" al ticket origen
+- (Tickets -> Adelantar tickets) Nuevo icono muestra cuando las agencias de los tickets origen/destino son distintas
### Changed
-- (Entradas -> Compras) Cambiados los campos "Precio Grouping/Packing" por "PVP" y "Precio" por "Coste"
-- (Artículos -> Últimas entradas) Cambiados los campos "P.P.U." y "P.P.P." por "PVP"
-- (Rutas -> Sumario/Tickets) Actualizados campos de los tickets
-- (Proveedores -> Crear/Editar) Permite añadir Proveedores con la misma razón social pero con países distintos
-- (Tickets -> Adelantar tickets) Cambiados selectores de estado por checks "Pendiente origen/destino"
-- (Tickets -> Adelantar tickets) Cambiado stock de destino a origen.
+
+- (Entradas -> Compras) Cambiados los campos "Precio Grouping/Packing" por "PVP" y "Precio" por "Coste"
+- (Artículos -> Últimas entradas) Cambiados los campos "P.P.U." y "P.P.P." por "PVP"
+- (Rutas -> Sumario/Tickets) Actualizados campos de los tickets
+- (Proveedores -> Crear/Editar) Permite añadir Proveedores con la misma razón social pero con países distintos
+- (Tickets -> Adelantar tickets) Cambiados selectores de estado por checks "Pendiente origen/destino"
+- (Tickets -> Adelantar tickets) Cambiado stock de destino a origen.
### Fixed
-- (Artículos -> Etiquetas) Permite intercambiar la relevancia entre dos etiquetas.
-- (Cliente -> Datos Fiscales) No se permite seleccionar 'Notificar vía e-mail' a los clientes sin e-mail
-- (Tickets -> Datos básicos) Permite guardar la hora de envío
-- (Tickets -> Añadir pago) Eliminado "null" en las referencias
-- (Tickets -> Adelantar tickets) Permite ordenar por importe
-- (Tickets -> Adelantar tickets) El filtrado por encajado muestra también los tickets sin tipo de encajado
+
+- (Artículos -> Etiquetas) Permite intercambiar la relevancia entre dos etiquetas.
+- (Cliente -> Datos Fiscales) No se permite seleccionar 'Notificar vía e-mail' a los clientes sin e-mail
+- (Tickets -> Datos básicos) Permite guardar la hora de envío
+- (Tickets -> Añadir pago) Eliminado "null" en las referencias
+- (Tickets -> Adelantar tickets) Permite ordenar por importe
+- (Tickets -> Adelantar tickets) El filtrado por encajado muestra también los tickets sin tipo de encajado
## [2302.01] - 2023-01-26
### Added
-- (General -> Inicio) Permite recuperar la contraseña
-- (Tickets -> Opciones) Subir albarán a Docuware
-- (Tickets -> Opciones) Enviar correo con PDF de Docuware
-- (Artículos -> Datos Básicos) Añadido campo Unidades/Caja
+
+- (General -> Inicio) Permite recuperar la contraseña
+- (Tickets -> Opciones) Subir albarán a Docuware
+- (Tickets -> Opciones) Enviar correo con PDF de Docuware
+- (Artículos -> Datos Básicos) Añadido campo Unidades/Caja
### Changed
-- (Reclamaciones -> Descriptor) Cambiado el campo Agencia por Zona
-- (Tickets -> Líneas preparadas) Actualizada sección para que sea más visual
+
+- (Reclamaciones -> Descriptor) Cambiado el campo Agencia por Zona
+- (Tickets -> Líneas preparadas) Actualizada sección para que sea más visual
### Fixed
-- (General) Al utilizar el traductor de Google se descuadraban los iconos
+
+- (General) Al utilizar el traductor de Google se descuadraban los iconos
### Removed
-- (Tickets -> Control clientes) Eliminada sección
+
+- (Tickets -> Control clientes) Eliminada sección
diff --git a/Jenkinsfile b/Jenkinsfile
index cf9b8cd67..821316c87 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -1,144 +1,254 @@
#!/usr/bin/env groovy
+
+def PROTECTED_BRANCH
+def FROM_GIT
+def RUN_TESTS
+def RUN_BUILD
+
+def BRANCH_ENV = [
+ test: 'test',
+ master: 'production'
+]
+
+node {
+ stage('Setup') {
+ env.BACK_REPLICAS = 1
+ env.NODE_ENV = BRANCH_ENV[env.BRANCH_NAME] ?: 'dev'
+
+ PROTECTED_BRANCH = [
+ 'dev',
+ 'test',
+ 'master'
+ ].contains(env.BRANCH_NAME)
+
+ FROM_GIT = env.JOB_NAME.startsWith('gitea/')
+ RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT
+ RUN_BUILD = PROTECTED_BRANCH && FROM_GIT
+
+ // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables
+ echo "NODE_NAME: ${env.NODE_NAME}"
+ echo "WORKSPACE: ${env.WORKSPACE}"
+
+ configFileProvider([
+ configFile(fileId: 'salix.properties',
+ variable: 'PROPS_FILE')
+ ]) {
+ def props = readProperties file: PROPS_FILE
+ props.each {key, value -> env."${key}" = value }
+ props.each {key, value -> echo "${key}: ${value}" }
+ }
+
+ if (PROTECTED_BRANCH) {
+ configFileProvider([
+ configFile(fileId: "salix.branch.${env.BRANCH_NAME}",
+ variable: 'BRANCH_PROPS_FILE')
+ ]) {
+ def props = readProperties file: BRANCH_PROPS_FILE
+ props.each {key, value -> env."${key}" = value }
+ props.each {key, value -> echo "${key}: ${value}" }
+ }
+ }
+ }
+}
pipeline {
agent any
options {
disableConcurrentBuilds()
}
+ tools {
+ nodejs 'node-v20'
+ }
environment {
PROJECT_NAME = 'salix'
- STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}"
+ STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}"
}
stages {
- stage('Checkout') {
- steps {
- script {
- switch (env.BRANCH_NAME) {
- case 'master':
- env.NODE_ENV = 'production'
- env.BACK_REPLICAS = 4
- break
- case 'test':
- env.NODE_ENV = 'test'
- env.BACK_REPLICAS = 2
- break
- }
- }
-
- configFileProvider([
- configFile(fileId: "salix.groovy",
- variable: 'GROOVY_FILE')
- ]) {
- load env.GROOVY_FILE
- }
-
- setEnv()
- }
- }
stage('Install') {
environment {
- NODE_ENV = ""
- }
- steps {
- nodejs('node-v20') {
- sh 'npm install --no-audit --prefer-offline'
- sh 'gulp install --ci'
- }
- }
- }
- stage('Test') {
- when { not { anyOf {
- branch 'test'
- branch 'master'
- }}}
- environment {
- NODE_ENV = ""
- TZ = 'Europe/Madrid'
+ NODE_ENV = ''
}
parallel {
- stage('Frontend') {
+ stage('Back') {
steps {
- nodejs('node-v20') {
- sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=2'
+ sh 'pnpm install --prefer-offline'
+ }
+ }
+ stage('Print') {
+ when {
+ expression { FROM_GIT }
+ }
+ steps {
+ sh 'pnpm install --prefer-offline --prefix=print'
+ }
+ }
+ stage('Front') {
+ when {
+ expression { FROM_GIT }
+ }
+ steps {
+ sh 'pnpm install --prefer-offline --prefix=front'
+ }
+ }
+ }
+ }
+ stage('Stack') {
+ parallel {
+ stage('Back') {
+ stages {
+ stage('Test') {
+ when {
+ expression { RUN_TESTS }
+ }
+ environment {
+ NODE_ENV = ''
+ }
+ steps {
+ sh 'node back/tests.js --ci --junit --network jenkins'
+ }
+ post {
+ always {
+ junit(
+ testResults: 'junitresults.xml',
+ allowEmptyResults: true
+ )
+ }
+ }
+ }
+ stage('Build') {
+ when {
+ expression { RUN_BUILD }
+ }
+ steps {
+ script {
+ def packageJson = readJSON file: 'package.json'
+ env.VERSION = packageJson.version
+ }
+ sh 'docker-compose build back'
+ }
}
}
}
- stage('Backend') {
- steps {
- nodejs('node-v20') {
- sh 'npm run test:back:ci'
+ stage('Front') {
+ when {
+ expression { FROM_GIT }
+ }
+ stages {
+ stage('Test') {
+ when {
+ expression { RUN_TESTS }
+ }
+ environment {
+ NODE_ENV = ''
+ }
+ steps {
+ sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=10'
+ }
+ post {
+ always {
+ junit(
+ testResults: 'junit.xml',
+ allowEmptyResults: true
+ )
+ }
+ }
+ }
+ stage('Build') {
+ when {
+ expression { RUN_BUILD }
+ }
+ steps {
+ script {
+ def packageJson = readJSON file: 'package.json'
+ env.VERSION = packageJson.version
+ }
+ sh 'gulp build'
+ sh 'docker-compose build front'
+ }
}
}
}
}
}
- stage('Build') {
- when { anyOf {
- branch 'test'
- branch 'master'
- }}
+ stage('Push') {
+ when {
+ expression { RUN_BUILD }
+ }
environment {
CREDENTIALS = credentials('docker-registry')
}
steps {
- nodejs('node-v20') {
- sh 'gulp build'
+ script {
+ def packageJson = readJSON file: 'package.json'
+ env.VERSION = packageJson.version
}
-
- dockerBuild()
+ sh 'docker login --username $CREDENTIALS_USR --password $CREDENTIALS_PSW $REGISTRY'
+ sh 'docker-compose push'
}
}
stage('Deploy') {
- when { anyOf {
- branch 'test'
- branch 'master'
- }}
- environment {
- DOCKER_HOST = "${env.SWARM_HOST}"
+ when {
+ expression { PROTECTED_BRANCH }
}
- steps {
- sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}"
- }
- }
- stage('Database') {
- when { anyOf {
- branch 'test'
- branch 'master'
- }}
- steps {
- configFileProvider([
- configFile(fileId: "config.${env.NODE_ENV}.ini",
- variable: 'MYSQL_CONFIG')
- ]) {
- sh 'cp "$MYSQL_CONFIG" db/config.$NODE_ENV.ini'
- }
+ parallel {
+ stage('Database') {
+ steps {
+ configFileProvider([
+ configFile(fileId: "config.${env.NODE_ENV}.ini",
+ variable: 'MYSQL_CONFIG')
+ ]) {
+ sh 'mkdir -p db/remotes'
+ sh 'cp "$MYSQL_CONFIG" db/remotes/$NODE_ENV.ini'
+ }
- sh 'db/import-changes.sh -f $NODE_ENV'
+ sh 'npx myt push $NODE_ENV --force --commit'
+ }
+ }
+ stage('Docker') {
+ when {
+ expression { FROM_GIT }
+ }
+ environment {
+ DOCKER_HOST = "${env.SWARM_HOST}"
+ }
+ steps {
+ script {
+ def packageJson = readJSON file: 'package.json'
+ env.VERSION = packageJson.version
+ }
+ sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}"
+ }
+ }
}
}
}
post {
- always {
+ success {
script {
- if (!['master', 'test'].contains(env.BRANCH_NAME)) {
- try {
- junit 'junitresults.xml'
- junit 'junit.xml'
- } catch (e) {
- echo e.toString()
- }
- }
+ if (env.BRANCH_NAME == 'master' && FROM_GIT) {
+ env.GIT_COMMIT_MSG = sh(
+ script: 'git log -1 --pretty=%B ${GIT_COMMIT}',
+ returnStdout: true
+ ).trim()
- if (!env.COMMITTER_EMAIL || currentBuild.currentResult == 'SUCCESS') return;
- try {
- mail(
- to: env.COMMITTER_EMAIL,
- subject: "Pipeline: ${env.JOB_NAME} (${env.BUILD_NUMBER}): ${currentBuild.currentResult}",
- body: "Check status at ${env.BUILD_URL}"
+ String message = env.GIT_COMMIT_MSG
+ int index = message.indexOf('\n')
+ if (index != -1)
+ message = message.substring(0, index)
+
+ setEnv()
+ rocketSend(
+ channel: 'vn-database',
+ message: "*DB version uploaded:* ${message}"
+ +"\n$COMMITTER_EMAIL ($BRANCH_NAME)"
+ +"\n$RUN_DISPLAY_URL",
+ rawMessage: true
)
- } catch (e) {
- echo e.toString()
}
}
}
+ unsuccessful {
+ setEnv()
+ sendEmail()
+ }
}
}
diff --git a/README.md b/README.md
index 59f5dbcf7..b420bc44f 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ Salix is also the scientific name of a beautifull tree! :)
Required applications.
-* Node.js >= 16.x LTS
+* Node.js
* Docker
* Git
@@ -17,20 +17,7 @@ You will need to install globally the following items.
$ sudo npm install -g jest gulp-cli
```
-For the usage of jest --watch on macOs.
-```
-$ brew install watchman
-```
-* [watchman](https://facebook.github.io/watchman/)
-
-## Linux Only Prerequisites
-
-Your user must be on the docker group to use it so you will need to run this command:
-```
-$ sudo usermod -a -G docker yourusername
-```
-
-## Getting Started // Installing
+## Installing dependencies and launching
Pull from repository.
@@ -76,29 +63,6 @@ In Visual Studio Code we use the ESLint extension.
ext install dbaeumer.vscode-eslint
```
-Gitlens for visualization of code authorship
-```
-ext install eamodio.gitlens
-```
-
-Spanish language pack
-```
-ext install ms-ceintl.vscode-language-pack-es
-```
-
-### Recommended extensions
-
-Material icon Theme
-```
-ext install pkief.material-icon-theme
-```
-
-Material UI Themes
-```
-ext install equinusocio.vsc-material-theme
-```
-
-
## Built With
* [angularjs](https://angularjs.org/)
diff --git a/Dockerfile b/back/Dockerfile
similarity index 79%
rename from Dockerfile
rename to back/Dockerfile
index e1173ad73..363192a0b 100644
--- a/Dockerfile
+++ b/back/Dockerfile
@@ -1,4 +1,4 @@
-FROM debian:bullseye-slim
+FROM debian:bookworm-slim
ENV TZ Europe/Madrid
ARG DEBIAN_FRONTEND=noninteractive
@@ -13,7 +13,7 @@ RUN apt-get update \
graphicsmagick \
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
- && npm install -g npm@9.6.6
+ && corepack enable pnpm
# Puppeteer
@@ -25,7 +25,13 @@ RUN apt-get update \
libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 \
libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 \
libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 \
- fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget \
+ fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget
+
+# Extra dependencies
+
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends \
+ samba-common-bin samba-dsdb-modules\
&& rm -rf /var/lib/apt/lists/* \
&& npm -g install pm2
@@ -33,12 +39,12 @@ RUN apt-get update \
WORKDIR /salix
-COPY print/package.json print/package-lock.json print/
-RUN npm --prefix ./print install --omit=dev ./print
+COPY print/package.json print/pnpm-lock.yaml print/
+RUN pnpm install --prod --prefix=print
-COPY package.json package-lock.json ./
+COPY package.json pnpm-lock.yaml ./
COPY loopback/package.json loopback/
-RUN npm install --omit=dev
+RUN pnpm install --prod
COPY loopback loopback
COPY back back
diff --git a/back/methods/chat/sendCheckingPresence.js b/back/methods/chat/sendCheckingPresence.js
index 274ec3a5b..85b66e94b 100644
--- a/back/methods/chat/sendCheckingPresence.js
+++ b/back/methods/chat/sendCheckingPresence.js
@@ -26,15 +26,14 @@ module.exports = Self => {
Self.sendCheckingPresence = async(ctx, recipientId, message) => {
if (!recipientId) return false;
-
const models = Self.app.models;
+
const userId = ctx.req.accessToken.userId;
const sender = await models.VnUser.findById(userId, {fields: ['id']});
const recipient = await models.VnUser.findById(recipientId, null);
// Prevent sending messages to yourself
if (recipientId == userId) return false;
-
if (!recipient)
throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`);
diff --git a/back/methods/collection/assign.js b/back/methods/collection/assign.js
new file mode 100644
index 000000000..0484eb5a8
--- /dev/null
+++ b/back/methods/collection/assign.js
@@ -0,0 +1,32 @@
+const UserError = require('vn-loopback/util/user-error');
+module.exports = Self => {
+ Self.remoteMethodCtx('assign', {
+ description: 'Assign a collection',
+ accessType: 'WRITE',
+ http: {
+ path: `/assign`,
+ verb: 'POST'
+ },
+ returns: {
+ type: ['object'],
+ root: true
+ },
+ });
+
+ Self.assign = async(ctx, options) => {
+ const userId = ctx.req.accessToken.userId;
+ const myOptions = {userId};
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const [, , [{collectionFk}]] =
+ await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk); SELECT @vCollectionFk collectionFk',
+ [userId], myOptions);
+
+ if (!collectionFk) throw new UserError('There are not picking tickets');
+ await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions);
+
+ return collectionFk;
+ };
+};
diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js
new file mode 100644
index 000000000..78945dc80
--- /dev/null
+++ b/back/methods/collection/getSales.js
@@ -0,0 +1,157 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('getSales', {
+ description: 'Get sales from ticket or collection',
+ accessType: 'READ',
+ accepts: [
+ {
+ arg: 'collectionOrTicketFk',
+ type: 'number',
+ required: true
+ }, {
+ arg: 'print',
+ type: 'boolean',
+ required: true
+ }, {
+ arg: 'source',
+ type: 'string',
+ required: true
+ },
+
+ ],
+ returns: {
+ type: 'Object',
+ root: true
+ },
+ http: {
+ path: `/getSales`,
+ verb: 'GET'
+ },
+ });
+
+ Self.getSales = async(ctx, collectionOrTicketFk, print, source, options) => {
+ const userId = ctx.req.accessToken.userId;
+ const myOptions = {userId};
+ const $t = ctx.req.__;
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const [{id}] = await Self.rawSql('SELECT vn.ticket_get(?) as id',
+ [collectionOrTicketFk],
+ myOptions);
+
+ const [tickets] = await Self.rawSql('CALL vn.collection_getTickets(?)', [id], myOptions);
+
+ if (source) {
+ await Self.rawSql(
+ 'CALL vn.ticketStateToday_setState(?,?)', [id, source], myOptions
+ );
+ }
+
+ const [sales] = await Self.rawSql('CALL vn.sale_getFromTicketOrCollection(?)',
+ [id], myOptions);
+
+ const isPicker = source != 'CHECKER';
+ const [placements] = await Self.rawSql('CALL vn.collectionPlacement_get(?, ?)',
+ [id, isPicker], myOptions
+ );
+
+ if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions);
+
+ for (let ticket of tickets) {
+ let observations = ticket.observaciones.split(' ');
+
+ for (let observation of observations) {
+ const salesPerson = ticket.salesPersonFk;
+ if (observation.startsWith('#') || observation.startsWith('@')) {
+ await models.Chat.send(ctx,
+ observation,
+ $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson})
+ );
+ }
+ }
+ }
+
+ return getCollection(id, tickets, sales, placements, myOptions);
+ };
+
+ async function getCollection(id, tickets, sales, placements, options) {
+ const collection = {
+ collectionFk: id,
+ tickets: [],
+ };
+ for (let ticket of tickets) {
+ const {ticketFk} = ticket;
+ ticket.sales = [];
+
+ const barcodes = await getBarcodes(ticketFk, options);
+ await Self.rawSql(
+ 'CALL util.log_add(?, ?, ?, ?, ?, ?, ?, ?)',
+ ['vn', 'ticket', 'Ticket', ticketFk, ticketFk, 'select', null, null],
+ options
+ );
+
+ for (let sale of sales) {
+ if (sale.ticketFk == ticketFk) {
+ sale.placements = [];
+ for (const salePlacement of placements) {
+ if (salePlacement.saleFk == sale.saleFk && salePlacement.order) {
+ const placement = {
+ saleFk: salePlacement.saleFk,
+ itemFk: salePlacement.itemFk,
+ placement: salePlacement.placement,
+ shelving: salePlacement.shelving,
+ created: salePlacement.created,
+ visible: salePlacement.visible,
+ order: salePlacement.order,
+ grouping: salePlacement.grouping,
+ priority: salePlacement.priority,
+ saleOrder: salePlacement.saleOrder,
+ isPreviousPrepared: salePlacement.isPreviousPrepared,
+ itemShelvingSaleFk: salePlacement.itemShelvingSaleFk,
+ ticketFk: salePlacement.ticketFk,
+ id: salePlacement.id
+ };
+ sale.placements.push(placement);
+ }
+ }
+
+ sale.barcodes = [];
+ for (const barcode of barcodes) {
+ if (barcode.movementId == sale.saleFk) {
+ if (barcode.code) {
+ sale.barcodes.push(barcode.code);
+ sale.barcodes.push(`0 ${barcode.code}`);
+ }
+
+ if (barcode.id) {
+ sale.barcodes.push(barcode.id);
+ sale.barcodes.push(`0 ${barcode.id}`);
+ }
+ }
+ }
+
+ ticket.sales.push(sale);
+ }
+ }
+ collection.tickets.push(ticket);
+ }
+
+ return collection;
+ }
+
+ async function getBarcodes(ticketId, options) {
+ const query =
+ `SELECT s.id movementId,
+ b.code,
+ c.id
+ FROM vn.sale s
+ LEFT JOIN vn.itemBarcode b ON b.itemFk = s.itemFk
+ LEFT JOIN vn.buy c ON c.itemFk = s.itemFk
+ LEFT JOIN vn.entry e ON e.id = c.entryFk
+ LEFT JOIN vn.travel tr ON tr.id = e.travelFk
+ WHERE s.ticketFk = ?
+ AND tr.landed >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)`;
+ return Self.rawSql(query, [ticketId], options);
+ }
+};
diff --git a/back/methods/collection/getSectors.js b/back/methods/collection/getSectors.js
deleted file mode 100644
index 12ad0dc06..000000000
--- a/back/methods/collection/getSectors.js
+++ /dev/null
@@ -1,20 +0,0 @@
-module.exports = Self => {
- Self.remoteMethod('getSectors', {
- description: 'Get all sectors',
- accessType: 'READ',
- returns: {
- type: 'Object',
- root: true
- },
- http: {
- path: `/getSectors`,
- verb: 'GET'
- }
- });
-
- Self.getSectors = async() => {
- const query = `CALL vn.sector_get()`;
- const [result] = await Self.rawSql(query);
- return result;
- };
-};
diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js
index 445fc070d..50117b954 100644
--- a/back/methods/collection/getTickets.js
+++ b/back/methods/collection/getTickets.js
@@ -26,7 +26,7 @@ module.exports = Self => {
Self.getTickets = async(ctx, id, print, options) => {
const userId = ctx.req.accessToken.userId;
- const origin = ctx.req.headers.origin;
+ const url = await Self.app.models.Url.getUrl();
const $t = ctx.req.__;
const myOptions = {};
@@ -36,7 +36,6 @@ module.exports = Self => {
myOptions.userId = userId;
const promises = [];
-
const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions);
const sales = await Self.rawSql(`
SELECT s.ticketFk,
@@ -50,7 +49,7 @@ module.exports = Self => {
ish.packing,
ish.grouping,
s.isAdded,
- s.originalQuantity,
+ s.originalQuantity,
s.quantity saleQuantity,
iss.quantity reservedQuantity,
SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id) accumulatedQuantity,
@@ -76,7 +75,7 @@ module.exports = Self => {
LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
LEFT JOIN origin o ON o.id = i.originFk
WHERE tc.collectionFk = ?
- GROUP BY ish.id, p.code, p2.code
+ GROUP BY s.id, ish.id, p.code, p2.code
ORDER BY pickingOrder;`, [id], myOptions);
if (print)
@@ -86,24 +85,19 @@ module.exports = Self => {
if (tickets && tickets.length) {
for (const ticket of tickets) {
const ticketId = ticket.ticketFk;
-
- // SEND ROCKET
if (ticket.observaciones != '') {
for (observation of ticket.observaciones.split(' ')) {
if (['#', '@'].includes(observation.charAt(0))) {
promises.push(Self.app.models.Chat.send(ctx, observation,
$t('The ticket is in preparation', {
ticketId: ticketId,
- ticketUrl: `${origin}/#!/ticket/${ticketId}/summary`,
+ ticketUrl: `${url}ticket/${ticketId}/summary`,
salesPersonId: ticket.salesPersonFk
})));
}
}
}
-
- // SET COLLECTION
if (sales && sales.length) {
- // GET BARCODES
const barcodes = await Self.rawSql(`
SELECT s.id saleFk, b.code, c.id
FROM vn.sale s
@@ -111,16 +105,13 @@ module.exports = Self => {
LEFT JOIN vn.buy c ON c.itemFk = s.itemFk
LEFT JOIN vn.entry e ON e.id = c.entryFk
LEFT JOIN vn.travel tr ON tr.id = e.travelFk
- WHERE s.ticketFk = ?
+ WHERE s.ticketFk = ?
AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`,
[ticketId], myOptions);
-
- // BINDINGS
ticket.sales = [];
for (const sale of sales) {
if (sale.ticketFk === ticketId) {
sale.Barcodes = [];
-
if (barcodes && barcodes.length) {
for (const barcode of barcodes) {
if (barcode.saleFk === sale.saleFk) {
@@ -131,7 +122,6 @@ module.exports = Self => {
}
}
}
-
ticket.sales.push(sale);
}
}
@@ -140,7 +130,6 @@ module.exports = Self => {
}
}
await Promise.all(promises);
-
return collection;
};
};
diff --git a/back/methods/collection/newCollection.js b/back/methods/collection/newCollection.js
deleted file mode 100644
index 2be9f8b0e..000000000
--- a/back/methods/collection/newCollection.js
+++ /dev/null
@@ -1,133 +0,0 @@
-module.exports = Self => {
- Self.remoteMethodCtx('newCollection', {
- description: 'Make a new collection of tickets',
- accessType: 'WRITE',
- accepts: [{
- arg: 'collectionFk',
- type: 'Number',
- required: false,
- description: 'The collection id'
- }, {
- arg: 'sectorFk',
- type: 'Number',
- required: true,
- description: 'The sector of worker'
- }, {
- arg: 'vWagons',
- type: 'Number',
- required: true,
- description: 'The number of wagons'
- }],
- returns: {
- type: 'Object',
- root: true
- },
- http: {
- path: `/newCollection`,
- verb: 'POST'
- }
- });
-
- Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => {
- let query = '';
- const userId = ctx.req.accessToken.userId;
-
- if (!collectionFk) {
- query = `CALL vn.collectionTrain_newBeta(?,?,?)`;
- const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId], {userId});
- if (result.length == 0)
- throw new Error(`No collections for today`);
-
- collectionFk = result[0].vCollectionFk;
- }
-
- query = `CALL vn.collectionTicket_get(?)`;
- const [tickets] = await Self.rawSql(query, [collectionFk], {userId});
-
- query = `CALL vn.collectionSale_get(?)`;
- const [sales] = await Self.rawSql(query, [collectionFk], {userId});
-
- query = `CALL vn.collectionPlacement_get(?)`;
- const [placements] = await Self.rawSql(query, [collectionFk], {userId});
-
- query = `CALL vn.collectionSticker_print(?,?)`;
- await Self.rawSql(query, [collectionFk, sectorFk], {userId});
-
- return makeCollection(tickets, sales, placements, collectionFk);
- };
-
- /**
- * Returns a collection json
- * @param {*} tickets - Request tickets
- * @param {*} sales - Request sales
- * @param {*} placements - Request placements
- * @param {*} collectionFk - Request placements
- * @return {Object} Collection JSON
- */
- async function makeCollection(tickets, sales, placements, collectionFk) {
- let collection = [];
-
- for (let i = 0; i < tickets.length; i++) {
- let ticket = {};
- ticket['ticketFk'] = tickets[i]['ticketFk'];
- ticket['level'] = tickets[i]['level'];
- ticket['agencyName'] = tickets[i]['agencyName'];
- ticket['warehouseFk'] = tickets[i]['warehouseFk'];
- ticket['salesPersonFk'] = tickets[i]['salesPersonFk'];
-
- let ticketSales = [];
-
- for (let x = 0; x < sales.length; x++) {
- if (sales[x]['ticketFk'] == ticket['ticketFk']) {
- let sale = {};
- sale['collectionFk'] = collectionFk;
- sale['ticketFk'] = sales[x]['ticketFk'];
- sale['saleFk'] = sales[x]['saleFk'];
- sale['itemFk'] = sales[x]['itemFk'];
- sale['quantity'] = sales[x]['quantity'];
- if (sales[x]['quantityPicked'] != null)
- sale['quantityPicked'] = sales[x]['quantityPicked'];
- else
- sale['quantityPicked'] = 0;
- sale['longName'] = sales[x]['longName'];
- sale['size'] = sales[x]['size'];
- sale['color'] = sales[x]['color'];
- sale['discount'] = sales[x]['discount'];
- sale['price'] = sales[x]['price'];
- sale['stems'] = sales[x]['stems'];
- sale['category'] = sales[x]['category'];
- sale['origin'] = sales[x]['origin'];
- sale['clientFk'] = sales[x]['clientFk'];
- sale['productor'] = sales[x]['productor'];
- sale['reserved'] = sales[x]['reserved'];
- sale['isPreviousPrepared'] = sales[x]['isPreviousPrepared'];
- sale['isPrepared'] = sales[x]['isPrepared'];
- sale['isControlled'] = sales[x]['isControlled'];
-
- let salePlacements = [];
-
- for (let z = 0; z < placements.length; z++) {
- if (placements[z]['saleFk'] == sale['saleFk']) {
- let placement = {};
- placement['saleFk'] = placements[z]['saleFk'];
- placement['itemFk'] = placements[z]['itemFk'];
- placement['placement'] = placements[z]['placement'];
- placement['shelving'] = placements[z]['shelving'];
- placement['created'] = placements[z]['created'];
- placement['visible'] = placements[z]['visible'];
- placement['order'] = placements[z]['order'];
- placement['grouping'] = placements[z]['grouping'];
- salePlacements.push(placement);
- }
- }
- sale['placements'] = salePlacements;
- ticketSales.push(sale);
- }
- }
- ticket['sales'] = ticketSales;
- collection.push(ticket);
- }
-
- return collection;
- }
-};
diff --git a/back/methods/collection/spec/assign.spec.js b/back/methods/collection/spec/assign.spec.js
new file mode 100644
index 000000000..745343819
--- /dev/null
+++ b/back/methods/collection/spec/assign.spec.js
@@ -0,0 +1,38 @@
+const models = require('vn-loopback/server/server').models;
+const LoopBackContext = require('loopback-context');
+
+describe('ticket assign()', () => {
+ let ctx;
+ let options;
+ let tx;
+ beforeEach(async() => {
+ ctx = {
+ req: {
+ accessToken: {userId: 1106},
+ headers: {origin: 'http://localhost'},
+ __: value => value
+ },
+ args: {}
+ };
+
+ spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
+ active: ctx.req
+ });
+
+ options = {transaction: tx};
+ tx = await models.Sale.beginTransaction({});
+ options.transaction = tx;
+ });
+
+ afterEach(async() => {
+ await tx.rollback();
+ });
+
+ it('should throw an error when there is not picking tickets', async() => {
+ try {
+ await models.Collection.assign(ctx, options);
+ } catch (e) {
+ expect(e.message).toEqual('There are not picking tickets');
+ }
+ });
+});
diff --git a/back/methods/collection/spec/getSales.spec.js b/back/methods/collection/spec/getSales.spec.js
new file mode 100644
index 000000000..e6205cc79
--- /dev/null
+++ b/back/methods/collection/spec/getSales.spec.js
@@ -0,0 +1,62 @@
+const {models} = require('vn-loopback/server/server');
+
+describe('collection getSales()', () => {
+ const collectionOrTicketFk = 999999;
+ const print = true;
+ const source = 'CHECKER';
+
+ beforeAll(() => {
+ ctx = {
+ req: {
+ accessToken: {userId: 9},
+ headers: {origin: 'http://localhost'},
+ }
+ };
+ });
+
+ it('should return a collection with tickets, placements and barcodes settled correctly', async() => {
+ const tx = await models.Collection.beginTransaction({});
+ const options = {transaction: tx};
+ try {
+ const collection = await models.Collection.getSales(ctx,
+ collectionOrTicketFk, print, source, options);
+
+ const [firstTicket] = collection.tickets;
+ const [firstSale] = firstTicket.sales;
+ const [firstPlacement] = firstSale.placements;
+
+ expect(collection.tickets.length).toBeTruthy();
+ expect(collection.collectionFk).toEqual(firstTicket.ticketFk);
+
+ expect(firstSale.ticketFk).toEqual(firstTicket.ticketFk);
+ expect(firstSale.placements.length).toBeTruthy();
+ expect(firstSale.barcodes.length).toBeTruthy();
+
+ expect(firstSale.saleFk).toEqual(firstPlacement.saleFk);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should print a sticker', async() => {
+ const tx = await models.Collection.beginTransaction({});
+ const options = {transaction: tx};
+ const query = 'SELECT * FROM printQueue pq JOIN printQueueArgs pqa ON pqa.printQueueFk = pq.id';
+ try {
+ const printQueueBefore = await models.Collection.rawSql(
+ query, [], options);
+ await models.Collection.getSales(ctx,
+ collectionOrTicketFk, true, source, options);
+ const printQueueAfter = await models.Collection.rawSql(
+ query, [], options);
+
+ expect(printQueueAfter.length).toEqual(printQueueBefore.length + 1);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+});
diff --git a/back/methods/collection/spec/getSectors.spec.js b/back/methods/collection/spec/getSectors.spec.js
deleted file mode 100644
index d8fa60663..000000000
--- a/back/methods/collection/spec/getSectors.spec.js
+++ /dev/null
@@ -1,11 +0,0 @@
-const {models} = require('vn-loopback/server/server');
-
-describe('getSectors()', () => {
- it('return list of sectors', async() => {
- let response = await models.Collection.getSectors();
-
- expect(response.length).toBeGreaterThan(0);
- expect(response[0].id).toEqual(1);
- expect(response[0].description).toEqual('First sector');
- });
-});
diff --git a/back/methods/collection/spec/newCollection.spec.js b/back/methods/collection/spec/newCollection.spec.js
deleted file mode 100644
index e729594d1..000000000
--- a/back/methods/collection/spec/newCollection.spec.js
+++ /dev/null
@@ -1,12 +0,0 @@
-const {models} = require('vn-loopback/server/server');
-
-describe('newCollection()', () => {
- it('should return a new collection', async() => {
- pending('#3400 analizar que hacer con rutas de back collection');
- let ctx = {req: {accessToken: {userId: 1106}}};
- let response = await models.Collection.newCollection(ctx, 1, 1, 1);
-
- expect(response.length).toBeGreaterThan(0);
- expect(response[0].ticketFk).toEqual(2);
- });
-});
diff --git a/back/methods/collection/spec/setSaleQuantity.spec.js b/back/methods/collection/spec/setSaleQuantity.spec.js
index fdc1bce1a..b563f5b19 100644
--- a/back/methods/collection/spec/setSaleQuantity.spec.js
+++ b/back/methods/collection/spec/setSaleQuantity.spec.js
@@ -18,6 +18,14 @@ describe('setSaleQuantity()', () => {
it('should change quantity sale', async() => {
const tx = await models.Ticket.beginTransaction({});
+ spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => {
+ if (sqlStatement.includes('catalog_calcFromItem')) {
+ sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY
+ SELECT 100 as available;`;
+ params = null;
+ }
+ return models.Ticket.rawSql(sqlStatement, params, options);
+ });
try {
const options = {transaction: tx};
diff --git a/back/methods/dms/downloadFile.js b/back/methods/dms/downloadFile.js
index 1b9150053..6f2451505 100644
--- a/back/methods/dms/downloadFile.js
+++ b/back/methods/dms/downloadFile.js
@@ -29,7 +29,8 @@ module.exports = Self => {
http: {
path: `/:id/downloadFile`,
verb: 'GET'
- }
+ },
+ // accessScopes: ['read:multimedia']
});
Self.downloadFile = async function(ctx, id) {
diff --git a/back/methods/dms/removeFile.js b/back/methods/dms/removeFile.js
index a9ff36883..dc55b4d38 100644
--- a/back/methods/dms/removeFile.js
+++ b/back/methods/dms/removeFile.js
@@ -22,8 +22,8 @@ module.exports = Self => {
Self.removeFile = async(ctx, id, options) => {
const models = Self.app.models;
- let tx;
const myOptions = {};
+ let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
diff --git a/back/methods/dms/uploadFile.js b/back/methods/dms/uploadFile.js
index a4212b804..9748b8225 100644
--- a/back/methods/dms/uploadFile.js
+++ b/back/methods/dms/uploadFile.js
@@ -49,7 +49,6 @@ module.exports = Self => {
Self.uploadFile = async(ctx, options) => {
const models = Self.app.models;
const TempContainer = models.TempContainer;
- const DmsContainer = models.DmsContainer;
const fileOptions = {};
const args = ctx.args;
@@ -79,19 +78,21 @@ module.exports = Self => {
const addedDms = [];
for (const uploadedFile of files) {
- const newDms = await createDms(ctx, uploadedFile, myOptions);
- const pathHash = DmsContainer.getHash(newDms.id);
-
const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name);
srcFile = path.join(file.client.root, file.container, file.name);
- const dmsContainer = await DmsContainer.container(pathHash);
- const dstFile = path.join(dmsContainer.client.root, pathHash, newDms.file);
-
- await fs.move(srcFile, dstFile, {
- overwrite: true
- });
-
+ const data = {
+ workerFk: ctx.req.accessToken.userId,
+ dmsTypeFk: args.dmsTypeId,
+ companyFk: args.companyId,
+ warehouseFk: args.warehouseId,
+ reference: args.reference,
+ description: args.description,
+ contentType: uploadedFile.type,
+ hasFile: args.hasFile
+ };
+ const extension = await models.DmsContainer.getFileExtension(uploadedFile.name);
+ const newDms = await Self.createFromFile(data, extension, srcFile, myOptions);
addedDms.push(newDms);
}
@@ -107,27 +108,4 @@ module.exports = Self => {
throw e;
}
};
-
- async function createDms(ctx, file, myOptions) {
- const models = Self.app.models;
- const myUserId = ctx.req.accessToken.userId;
- const args = ctx.args;
-
- const newDms = await Self.create({
- workerFk: myUserId,
- dmsTypeFk: args.dmsTypeId,
- companyFk: args.companyId,
- warehouseFk: args.warehouseId,
- reference: args.reference,
- description: args.description,
- contentType: file.type,
- hasFile: args.hasFile
- }, myOptions);
-
- let fileName = file.name;
- const extension = models.DmsContainer.getFileExtension(fileName);
- fileName = `${newDms.id}.${extension}`;
-
- return newDms.updateAttribute('file', fileName, myOptions);
- }
};
diff --git a/back/methods/docuware/download.js b/back/methods/docuware/download.js
index a0d72ce01..4aa40197f 100644
--- a/back/methods/docuware/download.js
+++ b/back/methods/docuware/download.js
@@ -42,7 +42,8 @@ module.exports = Self => {
http: {
path: `/:id/download`,
verb: 'GET'
- }
+ },
+ // accessScopes: ['read:multimedia']
});
Self.download = async function(id, fileCabinet, filter) {
diff --git a/back/methods/docuware/specs/upload.spec.js b/back/methods/docuware/specs/upload.spec.js
index 3b8c55a50..866499b66 100644
--- a/back/methods/docuware/specs/upload.spec.js
+++ b/back/methods/docuware/specs/upload.spec.js
@@ -24,15 +24,40 @@ describe('docuware upload()', () => {
});
it('should try upload file', async() => {
+ const tx = await models.Docuware.beginTransaction({});
spyOn(ticketModel, 'deliveryNotePdf').and.returnValue(new Promise(resolve => resolve({})));
let error;
try {
- await models.Docuware.upload(ctx, ticketIds, fileCabinetName);
+ const options = {transaction: tx};
+ const user = await models.UserConfig.findById(userId, null, options);
+ await user.updateAttribute('tabletFk', 'Tablet1', options);
+ await models.Docuware.upload(ctx, ticketIds, fileCabinetName, options);
+
+ await tx.rollback();
} catch (e) {
- error = e.message;
+ error = e;
+ await tx.rollback();
}
- expect(error).toEqual('Action not allowed on the test environment');
+ expect(error.message).toEqual('Action not allowed on the test environment');
+ });
+
+ it('should throw error when not have tablet assigned', async() => {
+ const tx = await models.Docuware.beginTransaction({});
+ spyOn(ticketModel, 'deliveryNotePdf').and.returnValue(new Promise(resolve => resolve({})));
+
+ let error;
+ try {
+ const options = {transaction: tx};
+ await models.Docuware.upload(ctx, ticketIds, fileCabinetName, options);
+
+ await tx.rollback();
+ } catch (e) {
+ error = e;
+ await tx.rollback();
+ }
+
+ expect(error.message).toEqual('This user does not have an assigned tablet');
});
});
diff --git a/back/methods/docuware/upload.js b/back/methods/docuware/upload.js
index 7055bf8d5..27be72295 100644
--- a/back/methods/docuware/upload.js
+++ b/back/methods/docuware/upload.js
@@ -29,12 +29,24 @@ module.exports = Self => {
}
});
- Self.upload = async function(ctx, ticketIds, fileCabinet) {
+ Self.upload = async function(ctx, ticketIds, fileCabinet, options) {
delete ctx.args.ticketIds;
const models = Self.app.models;
const action = 'store';
- const options = await Self.getOptions();
+ const myOptions = {};
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const userConfig = await models.UserConfig.findById(ctx.req.accessToken.userId, {
+ fields: ['tabletFk']
+ }, myOptions);
+
+ if (!userConfig?.tabletFk)
+ throw new UserError('This user does not have an assigned tablet');
+
+ const docuwareOptions = await Self.getOptions();
const fileCabinetId = await Self.getFileCabinet(fileCabinet);
const dialogId = await Self.getDialog(fileCabinet, action, fileCabinetId);
@@ -45,7 +57,7 @@ module.exports = Self => {
const deliveryNote = await models.Ticket.deliveryNotePdf(ctx, {
id,
type: 'deliveryNote'
- });
+ }, myOptions);
// get ticket data
const ticket = await models.Ticket.findById(id, {
include: [{
@@ -54,7 +66,7 @@ module.exports = Self => {
fields: ['id', 'name', 'fi']
}
}]
- });
+ }, myOptions);
// upload file
const templateJson = {
@@ -102,7 +114,7 @@ module.exports = Self => {
{
'FieldName': 'FILTRO_TABLET',
'ItemElementName': 'string',
- 'Item': 'Tablet1',
+ 'Item': userConfig.tabletFk,
}
]
};
@@ -116,11 +128,11 @@ module.exports = Self => {
const deleteJson = {
'Field': [{'FieldName': 'ESTADO', 'Item': 'Pendiente eliminar', 'ItemElementName': 'String'}]
};
- const deleteUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents/${docuwareFile.id}/Fields`;
- await axios.put(deleteUri, deleteJson, options.headers);
+ const deleteUri = `${docuwareOptions.url}/FileCabinets/${fileCabinetId}/Documents/${docuwareFile.id}/Fields`;
+ await axios.put(deleteUri, deleteJson, docuwareOptions.headers);
}
- const uploadUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`;
+ const uploadUri = `${docuwareOptions.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`;
const FormData = require('form-data');
const data = new FormData();
@@ -130,7 +142,7 @@ module.exports = Self => {
headers: {
'Content-Type': 'multipart/form-data',
'X-File-ModifiedDate': Date.vnNew(),
- 'Cookie': options.headers.headers.Cookie,
+ 'Cookie': docuwareOptions.headers.headers.Cookie,
...data.getHeaders()
},
};
@@ -141,11 +153,11 @@ module.exports = Self => {
const $t = ctx.req.__;
const message = $t('Failed to upload delivery note', {id});
if (uploaded.length)
- await models.TicketTracking.setDelivered(ctx, uploaded);
+ await models.TicketTracking.setDelivered(ctx, uploaded, myOptions);
throw new UserError(message);
}
uploaded.push(id);
}
- return models.TicketTracking.setDelivered(ctx, ticketIds);
+ return models.TicketTracking.setDelivered(ctx, ticketIds, myOptions);
};
};
diff --git a/back/methods/image/download.js b/back/methods/image/download.js
index c4037b809..9ac06f30b 100644
--- a/back/methods/image/download.js
+++ b/back/methods/image/download.js
@@ -47,7 +47,8 @@ module.exports = Self => {
http: {
path: `/:collection/:size/:id/download`,
verb: 'GET'
- }
+ },
+ // accessScopes: ['read:multimedia']
});
Self.download = async function(ctx, collection, size, id) {
@@ -87,6 +88,6 @@ module.exports = Self => {
await fs.access(file.path);
const stream = fs.createReadStream(file.path);
- return [stream, file.contentType, `filename="${file.name}"`];
+ return [stream, file.contentType, `filename="${fileName}"`];
};
};
diff --git a/back/methods/image/specs/download.spec.js b/back/methods/image/specs/download.spec.js
index 1258a916a..bc23a0dcd 100644
--- a/back/methods/image/specs/download.spec.js
+++ b/back/methods/image/specs/download.spec.js
@@ -4,20 +4,21 @@ describe('image download()', () => {
const collection = 'user';
const size = '160x160';
const employeeId = 1;
+ const developerId = 9;
+ const jessicaJonesId = 1110;
const ctx = {req: {accessToken: {userId: employeeId}}};
it('should return the image content-type of the user', async() => {
- const userId = 9;
- const image = await models.Image.download(ctx, collection, size, userId);
+ const image = await models.Image.download(ctx, collection, size, developerId);
const contentType = image[1];
expect(contentType).toEqual('image/png');
});
- it(`should return false if the user doesn't have image`, async() => {
- const userId = 1110;
- const image = await models.Image.download(ctx, collection, size, userId);
+ it('should return the user profile picture', async() => {
+ const image = await models.Image.download(ctx, collection, size, jessicaJonesId);
+ const fileName = image[2];
- expect(image).toBeFalse();
+ expect(fileName).toMatch('1110.png');
});
});
diff --git a/back/methods/image/specs/upload.spec.js b/back/methods/image/specs/upload.spec.js
index 144770bcf..63c5cfb65 100644
--- a/back/methods/image/specs/upload.spec.js
+++ b/back/methods/image/specs/upload.spec.js
@@ -95,10 +95,7 @@ describe('image upload()', () => {
spyOn(containerModel, 'upload');
const ctx = {req: {accessToken: {userId: hhrrId}},
- args: {
- id: itemId,
- collection: 'user'
- }
+ args: {id: itemId, collection: 'user'}
};
try {
@@ -109,7 +106,7 @@ describe('image upload()', () => {
});
it('should try to upload a file for the collection "catalog" and throw a privilege error', async() => {
- const ctx = {req: {accessToken: {userId: hhrrId}},
+ const ctx = {req: {accessToken: {userId: 1}},
args: {
id: workerId,
collection: 'catalog'
diff --git a/back/methods/machine-worker/specs/updateInTime.spec.js b/back/methods/machine-worker/specs/updateInTime.spec.js
new file mode 100644
index 000000000..f166214b0
--- /dev/null
+++ b/back/methods/machine-worker/specs/updateInTime.spec.js
@@ -0,0 +1,132 @@
+const {models} = require('vn-loopback/server/server');
+
+describe('machineWorker updateInTime()', () => {
+ const itBoss = 104;
+ const davidCharles = 1106;
+
+ beforeAll(async() => {
+ ctx = {
+ req: {
+ accessToken: {},
+ headers: {origin: 'http://localhost'},
+ __: value => value
+ }
+ };
+ });
+
+ it('should throw an error if the plate does not exist', async() => {
+ const tx = await models.MachineWorker.beginTransaction({});
+ const options = {transaction: tx};
+ const plate = 'RE-123';
+ ctx.req.accessToken.userId = 1106;
+ try {
+ await models.MachineWorker.updateInTime(ctx, plate, options);
+ await tx.rollback();
+ } catch (e) {
+ const error = e;
+
+ expect(error.message).toContain('the plate does not exist');
+ await tx.rollback();
+ }
+ });
+
+ it('should grab a machine where is not in use', async() => {
+ const tx = await models.MachineWorker.beginTransaction({});
+ const options = {transaction: tx};
+ const plate = 'RE-003';
+ ctx.req.accessToken.userId = 1107;
+ try {
+ const totalBefore = await models.MachineWorker.find(null, options);
+ await models.MachineWorker.updateInTime(ctx, plate, options);
+ const totalAfter = await models.MachineWorker.find(null, options);
+
+ expect(totalAfter.length).toEqual(totalBefore.length + 1);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ }
+ });
+
+ describe('less than 12h', () => {
+ const plate = 'RE-001';
+ it('should trow an error if it is not himself', async() => {
+ const tx = await models.MachineWorker.beginTransaction({});
+ const options = {transaction: tx};
+ ctx.req.accessToken.userId = davidCharles;
+
+ try {
+ await models.MachineWorker.updateInTime(ctx, plate, options);
+ await tx.rollback();
+ } catch (e) {
+ const error = e;
+
+ expect(error.message).toContain('This machine is already in use');
+ await tx.rollback();
+ }
+ });
+
+ it('should throw an error if it is himself with a different machine', async() => {
+ const tx = await models.MachineWorker.beginTransaction({});
+ const options = {transaction: tx};
+ ctx.req.accessToken.userId = itBoss;
+ const plate = 'RE-003';
+ try {
+ await models.MachineWorker.updateInTime(ctx, plate, options);
+ await tx.rollback();
+ } catch (e) {
+ const error = e;
+
+ expect(error.message).toEqual('You are already using a machine');
+ await tx.rollback();
+ }
+ });
+
+ it('should set the out time if it is himself', async() => {
+ const tx = await models.MachineWorker.beginTransaction({});
+ const options = {transaction: tx};
+ ctx.req.accessToken.userId = itBoss;
+
+ try {
+ const isNotParked = await models.MachineWorker.findOne({
+ where: {workerFk: itBoss}
+ }, options);
+ await models.MachineWorker.updateInTime(ctx, plate, options);
+ const isParked = await models.MachineWorker.findOne({
+ where: {workerFk: itBoss}
+ }, options);
+
+ expect(isNotParked.outTime).toBeNull();
+ expect(isParked.outTime).toBeDefined();
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ }
+ });
+ });
+
+ describe('equal or more than 12h', () => {
+ const plate = 'RE-002';
+ it('should set the out time and grab the machine', async() => {
+ const tx = await models.MachineWorker.beginTransaction({});
+ const options = {transaction: tx};
+ ctx.req.accessToken.userId = davidCharles;
+ const filter = {
+ where: {workerFk: davidCharles, machineFk: 2}
+ };
+ try {
+ const isNotParked = await models.MachineWorker.findOne(filter, options);
+ const totalBefore = await models.MachineWorker.find(null, options);
+ await models.MachineWorker.updateInTime(ctx, plate, options);
+ const isParked = await models.MachineWorker.findOne(filter, options);
+ const totalAfter = await models.MachineWorker.find(null, options);
+
+ expect(isNotParked.outTime).toBeNull();
+ expect(isParked.outTime).toBeDefined();
+ expect(totalAfter.length).toEqual(totalBefore.length + 1);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ }
+ });
+ });
+});
diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js
new file mode 100644
index 000000000..44fad2c05
--- /dev/null
+++ b/back/methods/machine-worker/updateInTime.js
@@ -0,0 +1,77 @@
+const UserError = require('vn-loopback/util/user-error');
+module.exports = Self => {
+ Self.remoteMethodCtx('updateInTime', {
+ description: 'Updates the corresponding registry if the worker has been registered in the last few hours',
+ accessType: 'WRITE',
+ accepts: [
+ {
+ arg: 'plate',
+ type: 'string',
+ }
+ ],
+ http: {
+ path: `/updateInTime`,
+ verb: 'POST'
+ }
+ });
+
+ Self.updateInTime = async(ctx, plate, options) => {
+ const models = Self.app.models;
+ const userId = ctx.req.accessToken.userId;
+ const $t = ctx.req.__;
+
+ let tx;
+ const myOptions = {};
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ if (!myOptions.transaction) {
+ tx = await Self.beginTransaction({});
+ myOptions.transaction = tx;
+ }
+
+ try {
+ const machine = await models.Machine.findOne({
+ fields: ['id', 'plate'],
+ where: {plate}
+ }, myOptions);
+
+ if (!machine)
+ throw new UserError($t('the plate does not exist', {plate}));
+
+ const machineWorker = await Self.findOne({
+ where: {
+ or: [{machineFk: machine.id}, {workerFk: userId}],
+ outTime: null,
+ }
+ }, myOptions);
+
+ const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions);
+ const hoursDifference = (Date.vnNow() - machineWorker?.inTime?.getTime() ?? 0) / (60 * 60 * 1000);
+
+ if (machineWorker) {
+ const isHimself = userId == machineWorker.workerFk;
+ const isSameMachine = machine.id == machineWorker.machineFk;
+
+ if (hoursDifference < maxHours && !isHimself)
+ throw new UserError($t('This machine is already in use.'));
+
+ if (hoursDifference < maxHours && isHimself && !isSameMachine)
+ throw new UserError($t('You are already using a machine'));
+
+ await machineWorker.updateAttributes({
+ outTime: Date.vnNew()
+ }, myOptions);
+ }
+
+ if (!machineWorker || hoursDifference >= maxHours)
+ await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions);
+
+ if (tx) await tx.commit();
+ } catch (e) {
+ if (tx) await tx.rollback();
+ throw e;
+ }
+ };
+};
diff --git a/back/methods/mobile-app-version-control/getVersion.js b/back/methods/mobile-app-version-control/getVersion.js
new file mode 100644
index 000000000..9ace4e14a
--- /dev/null
+++ b/back/methods/mobile-app-version-control/getVersion.js
@@ -0,0 +1,50 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('getVersion', {
+ description: 'gets app version data',
+ accessType: 'READ',
+ accepts: [{
+ arg: 'app',
+ type: 'string',
+ required: true
+ }],
+ returns: {
+ type: ['object'],
+ root: true
+ },
+ http: {
+ path: `/getVersion`,
+ verb: 'GET'
+ }
+ });
+
+ Self.getVersion = async(ctx, app) => {
+ const {models} = Self.app;
+ const userId = ctx.req.accessToken.userId;
+
+ const workerFk = await models.WorkerAppTester.findOne({
+ where: {
+ workerFk: userId
+ }
+ });
+ let fields = ['id', 'appName'];
+
+ if (workerFk)
+ fields = fields.concat(['isVersionBetaCritical', 'versionBeta', 'urlBeta']);
+ else
+ fields = fields.concat(['isVersionCritical', 'version', 'urlProduction']);
+
+ const filter = {
+ where: {
+ appName: app
+ },
+ fields,
+ };
+
+ const result = await Self.findOne(filter);
+ return {
+ isVersionCritical: result?.isVersionBetaCritical ?? result?.isVersionCritical,
+ version: result?.versionBeta ?? result?.version,
+ url: result?.urlBeta ?? result?.urlProduction
+ };
+ };
+};
diff --git a/back/methods/mobile-app-version-control/specs/getVersion.spec.js b/back/methods/mobile-app-version-control/specs/getVersion.spec.js
new file mode 100644
index 000000000..da738c432
--- /dev/null
+++ b/back/methods/mobile-app-version-control/specs/getVersion.spec.js
@@ -0,0 +1,29 @@
+const {models} = require('vn-loopback/server/server');
+
+describe('mobileAppVersionControl getVersion()', () => {
+ const appName = 'delivery';
+ const appNameVersion = '9.2';
+ const appNameVersionBeta = '9.7';
+ beforeAll(async() => {
+ ctx = {
+ req: {
+ accessToken: {},
+ headers: {origin: 'http://localhost'},
+ }
+ };
+ });
+
+ it('should get the version app', async() => {
+ ctx.req.accessToken.userId = 9;
+ const {version} = await models.MobileAppVersionControl.getVersion(ctx, appName);
+
+ expect(version).toEqual(appNameVersion);
+ });
+
+ it('should get the beta version app', async() => {
+ ctx.req.accessToken.userId = 66;
+ const {version} = await models.MobileAppVersionControl.getVersion(ctx, appName);
+
+ expect(version).toEqual(appNameVersionBeta);
+ });
+});
diff --git a/back/methods/mrw-config/cancelShipment.ejs b/back/methods/mrw-config/cancelShipment.ejs
new file mode 100644
index 000000000..9ef401bc8
--- /dev/null
+++ b/back/methods/mrw-config/cancelShipment.ejs
@@ -0,0 +1,20 @@
+
+
+
+ <%= mrw.franchiseCode %>
+ <%= mrw.subscriberCode %>
+
+ <%= mrw.user %>
+ <%= mrw.password %>
+
+
+
+
+
+
+ <%= externalId %>
+
+
+
+
+
\ No newline at end of file
diff --git a/back/methods/mrw-config/cancelShipment.js b/back/methods/mrw-config/cancelShipment.js
new file mode 100644
index 000000000..218b6a96b
--- /dev/null
+++ b/back/methods/mrw-config/cancelShipment.js
@@ -0,0 +1,46 @@
+const axios = require('axios');
+const fs = require('fs');
+const ejs = require('ejs');
+const {DOMParser} = require('xmldom');
+
+module.exports = Self => {
+ Self.remoteMethod('cancelShipment', {
+ description: 'Cancel a shipment by providing the expedition ID, interacting with MRW WebService',
+ accessType: 'WRITE',
+ accepts: [{
+ arg: 'expeditionFk',
+ type: 'number',
+ required: true
+ }],
+ returns: {
+ type: ['object'],
+ root: true
+ },
+ http: {
+ path: `/cancelShipment`,
+ verb: 'POST'
+ }
+ });
+
+ Self.cancelShipment = async expeditionFk => {
+ const models = Self.app.models;
+
+ const mrw = await models.MrwConfig.findOne();
+ const {externalId} = await models.Expedition.findById(expeditionFk);
+
+ const template = fs.readFileSync(__dirname + '/cancelShipment.ejs', 'utf-8');
+ const renderedXml = ejs.render(template, {mrw, externalId});
+ const response = await axios.post(mrw.url, renderedXml, {
+ headers: {
+ 'Content-Type': 'application/soap+xml; charset=utf-8'
+ }
+ });
+
+ const xmlString = response.data;
+ const parser = new DOMParser();
+ const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
+ const [resultElement] = xmlDoc.getElementsByTagName('Mensaje');
+
+ return resultElement.textContent;
+ };
+};
diff --git a/back/methods/mrw-config/createShipment.ejs b/back/methods/mrw-config/createShipment.ejs
new file mode 100644
index 000000000..bf8a07dab
--- /dev/null
+++ b/back/methods/mrw-config/createShipment.ejs
@@ -0,0 +1,43 @@
+
+
+
+
+ <%= mrw.franchiseCode %>
+ <%= mrw.subscriberCode %>
+
+ <%= mrw.user %>
+ <%= mrw.password %>
+
+
+
+
+
+
+
+
+ <%= expeditionData.street %>
+
+
+ <%= expeditionData.postalCode %>
+ <%= expeditionData.city %>
+
+
+
+ <%= expeditionData.fi %>
+ <%= expeditionData.clientName %>
+ <%= expeditionData.phone %>
+
+
+ <%= expeditionData.created %>
+ <%= expeditionData.expeditionDataId %>
+ <%= expeditionData.serviceType %>
+ 1
+ <%= expeditionData.weekDays %>
+ <%= expeditionData.kg %>
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js
new file mode 100644
index 000000000..12263de03
--- /dev/null
+++ b/back/methods/mrw-config/createShipment.js
@@ -0,0 +1,118 @@
+const axios = require('axios');
+const {DOMParser} = require('xmldom');
+const fs = require('fs');
+const ejs = require('ejs');
+const UserError = require('vn-loopback/util/user-error');
+
+module.exports = Self => {
+ Self.remoteMethod('createShipment', {
+ description: 'Create an expedition and return a base64Binary label from de MRW WebService',
+ accessType: 'WRITE',
+ accepts: [{
+ arg: 'expeditionFk',
+ type: 'number',
+ required: true
+ }],
+ returns: {
+ type: ['object'],
+ root: true
+ },
+ http: {
+ path: `/createShipment`,
+ verb: 'POST'
+ }
+ });
+
+ Self.createShipment = async(expeditionFk, options) => {
+ const myOptions = {};
+ let tx;
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ if (!myOptions.transaction) {
+ tx = await Self.beginTransaction({});
+ myOptions.transaction = tx;
+ }
+
+ const models = Self.app.models;
+ const mrw = await models.MrwConfig.findOne(null, myOptions);
+
+ if (!mrw)
+ throw new UserError(`Some mrwConfig parameters are not set`);
+
+ const query =
+ `SELECT CASE co.code
+ WHEN 'ES' THEN a.postalCode
+ WHEN 'PT' THEN LEFT(a.postalCode, 4)
+ WHEN 'AD' THEN REPLACE(a.postalCode, 'AD', '00')
+ END postalCode,
+ a.city,
+ a.street,
+ co.code countryCode,
+ c.fi,
+ c.name clientName,
+ c.phone,
+ DATE_FORMAT(t.shipped, '%d/%m/%Y') created,
+ t.shipped,
+ e.id expeditionId,
+ LPAD(IF(mw.params IS NULL, ms.serviceType, mw.serviceType), 4 ,'0') serviceType,
+ IF(mw.weekdays, 'S', 'N') weekDays
+ FROM expedition e
+ JOIN ticket t ON e.ticketFk = t.id
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN mrwService ms ON ms.agencyModeCodeFk = am.code
+ LEFT JOIN mrwServiceWeekday mw ON mw.weekdays = DATE_FORMAT(t.shipped, '%a')
+ JOIN client c ON t.clientFk = c.id
+ JOIN address a ON t.addressFk = a.id
+ JOIN province p ON a.provinceFk = p.id
+ JOIN country co ON co.id = p.countryFk
+ WHERE e.id = ?
+ LIMIT 1`;
+
+ const [expeditionData] = await Self.rawSql(query, [expeditionFk], myOptions);
+
+ if (!expeditionData)
+ throw new UserError(`This expedition is not a MRW shipment`);
+
+ const today = Date.vnNew();
+ today.setHours(0, 0, 0, 0);
+ if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today)
+ throw new UserError(`This ticket has a shipped date earlier than today`);
+
+ const shipmentResponse = await sendXmlDoc('createShipment', {mrw, expeditionData}, 'application/soap+xml');
+ const shipmentId = getTextByTag(shipmentResponse, 'NumeroEnvio');
+
+ if (!shipmentId)
+ throw new UserError(getTextByTag(shipmentResponse, 'Mensaje'));
+
+ const getLabelResponse = await sendXmlDoc('getLabel', {mrw, shipmentId}, 'text/xml');
+ const file = getTextByTag(getLabelResponse, 'EtiquetaFile');
+
+ try {
+ await models.Expedition.updateAll({id: expeditionFk}, {externalId: shipmentId}, myOptions);
+ if (tx) await tx.commit();
+ } catch (error) {
+ if (tx) await tx.rollback();
+ throw error;
+ }
+ return file;
+ };
+
+ function getTextByTag(xmlDoc, tag) {
+ return xmlDoc?.getElementsByTagName(tag)[0]?.textContent;
+ }
+
+ async function sendXmlDoc(xmlDock, params, contentType) {
+ const parser = new DOMParser();
+
+ const xmlTemplate = fs.readFileSync(__dirname + `/${xmlDock}.ejs`, 'utf-8');
+ const renderedTemplate = ejs.render(xmlTemplate, params);
+ const data = await axios.post(params.mrw.url, renderedTemplate, {
+ headers: {
+ 'Content-Type': `${contentType}; charset=utf-8`
+ }
+ });
+ return parser.parseFromString(data.data, 'text/xml');
+ }
+};
diff --git a/back/methods/mrw-config/getLabel.ejs b/back/methods/mrw-config/getLabel.ejs
new file mode 100644
index 000000000..09bdb3f6c
--- /dev/null
+++ b/back/methods/mrw-config/getLabel.ejs
@@ -0,0 +1,25 @@
+
+
+
+ <%= mrw.franchiseCode %>
+ <%= mrw.subscriberCode %>
+
+ <%= mrw.user %>
+ <%= mrw.password %>
+
+
+
+
+
+ <%= shipmentId %>
+ 1
+
+
+
+ 0
+ 0
+ 0
+
+
+
+
\ No newline at end of file
diff --git a/back/methods/mrw-config/specs/createShipment.spec.js b/back/methods/mrw-config/specs/createShipment.spec.js
new file mode 100644
index 000000000..0f48bc2d3
--- /dev/null
+++ b/back/methods/mrw-config/specs/createShipment.spec.js
@@ -0,0 +1,121 @@
+const models = require('vn-loopback/server/server').models;
+const axios = require('axios');
+const fs = require('fs');
+
+const mockBase64Binary = 'base64BinaryString';
+const ticket1 = {
+ 'id': '44',
+ 'clientFk': 1101,
+ 'shipped': Date.vnNew(),
+ 'nickname': 'MRW',
+ 'addressFk': 1,
+ 'agencyModeFk': 999
+};
+
+const expedition1 = {
+ 'id': 17,
+ 'agencyModeFk': 999,
+ 'ticketFk': 44,
+ 'freightItemFk': 71,
+ 'created': '2001-01-01',
+ 'counter': 1,
+ 'workerFk': 18,
+ 'packagingFk': '94',
+ 'hostFk': '',
+ 'stateTypeFk': 3,
+ 'hasNewRoute': 0,
+ 'isBox': 71,
+ 'editorFk': 100
+};
+
+let tx;
+let options;
+
+describe('MRWConfig createShipment()', () => {
+ beforeEach(async() => {
+ options = tx = undefined;
+ tx = await models.MrwConfig.beginTransaction({});
+ options = {transaction: tx};
+
+ await models.Agency.create(
+ {'id': 999, 'name': 'mrw'},
+ options
+ );
+
+ await models.AgencyMode.create(
+ {'id': 999, 'name': 'mrw', 'agencyFk': 999, 'code': 'mrw'},
+ options
+ );
+
+ await models.MrwConfig.create(
+ {
+ 'id': 1,
+ 'url': 'https://url.com',
+ 'user': 'user',
+ 'password': 'password',
+ 'franchiseCode': 'franchiseCode',
+ 'subscriberCode': 'subscriberCode'
+ }, options
+ );
+
+ await models.Application.rawSql(
+ `INSERT INTO vn.mrwService
+ SET agencyModeCodeFk = 'mrw',
+ clientType = 1,
+ serviceType = 1,
+ kg = 1`, null, options
+ );
+ await models.Ticket.create(ticket1, options);
+ await models.Expedition.create(expedition1, options);
+ });
+
+ afterEach(async() => {
+ await tx.rollback();
+ });
+
+ it('should create a shipment and return a base64Binary label', async() => {
+ const mockPostResponses = [
+ {data: fs.readFileSync(__dirname + '/mockGetLabel.xml', 'utf-8')},
+ {data: fs.readFileSync(__dirname + '/mockCreateShipment.xml', 'utf-8')}
+ ];
+
+ spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop()));
+
+ const base64Binary = await models.MrwConfig.createShipment(expedition1.id, options);
+
+ expect(base64Binary).toEqual(mockBase64Binary);
+ });
+
+ it('should fail if mrwConfig has no data', async() => {
+ let error;
+ await models.MrwConfig.createShipment(expedition1.id).catch(e => {
+ error = e;
+ }).finally(async() => {
+ expect(error.message).toEqual(`Some mrwConfig parameters are not set`);
+ });
+
+ expect(error).toBeDefined();
+ });
+
+ it('should fail if expeditionFk is not a MrwExpedition', async() => {
+ let error;
+ await models.MrwConfig.createShipment(undefined, options).catch(e => {
+ error = e;
+ }).finally(async() => {
+ expect(error.message).toEqual(`This expedition is not a MRW shipment`);
+ });
+ });
+
+ it(' should fail if the creation date of this ticket is before the current date it', async() => {
+ let error;
+ const yesterday = Date.vnNew();
+
+ yesterday.setDate(yesterday.getDate() - 1);
+ await models.Ticket.updateAll({id: ticket1.id}, {shipped: yesterday}, options);
+ await models.MrwConfig.createShipment(expedition1.id, options).catch(e => {
+ error = e;
+ }).finally(async() => {
+ expect(error.message).toEqual(`This ticket has a shipped date earlier than today`);
+ });
+ });
+});
diff --git a/back/methods/mrw-config/specs/mockCreateShipment.xml b/back/methods/mrw-config/specs/mockCreateShipment.xml
new file mode 100644
index 000000000..dacc5d3f3
--- /dev/null
+++ b/back/methods/mrw-config/specs/mockCreateShipment.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
+ 1
+
+ 1
+ 1
+ http://url.com
+
+
+
+
\ No newline at end of file
diff --git a/back/methods/mrw-config/specs/mockGetLabel.xml b/back/methods/mrw-config/specs/mockGetLabel.xml
new file mode 100644
index 000000000..0401ce2c7
--- /dev/null
+++ b/back/methods/mrw-config/specs/mockGetLabel.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+ 1
+
+ base64BinaryString
+
+
+
+
\ No newline at end of file
diff --git a/back/methods/notification/getList.js b/back/methods/notification/getList.js
new file mode 100644
index 000000000..3881f0f63
--- /dev/null
+++ b/back/methods/notification/getList.js
@@ -0,0 +1,54 @@
+module.exports = Self => {
+ Self.remoteMethod('getList', {
+ description: 'Get list of the available and active notification subscriptions',
+ accessType: 'READ',
+ accepts: [
+ {
+ arg: 'id',
+ type: 'number',
+ description: 'User to modify',
+ http: {source: 'path'}
+ }
+ ],
+ returns: {
+ type: 'object',
+ root: true
+ },
+ http: {
+ path: `/:id/getList`,
+ verb: 'GET'
+ }
+ });
+
+ Self.getList = async(id, options) => {
+ const activeNotificationsMap = new Map();
+
+ const myOptions = {};
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const availableNotificationsMap = await Self.getAvailable(id, myOptions);
+ const activeNotifications = await Self.app.models.NotificationSubscription.find({
+ fields: ['id', 'notificationFk'],
+ include: {relation: 'notification'},
+ where: {userFk: id}
+ }, myOptions);
+
+ for (active of activeNotifications) {
+ activeNotificationsMap.set(active.notificationFk, {
+ id: active.id,
+ notificationFk: active.notificationFk,
+ name: active.notification().name,
+ description: active.notification().description,
+ active: true
+ });
+ availableNotificationsMap.delete(active.notificationFk);
+ }
+
+ return {
+ active: [...activeNotificationsMap.entries()],
+ available: [...availableNotificationsMap.entries()]
+ };
+ };
+};
diff --git a/back/methods/notification/specs/getList.spec.js b/back/methods/notification/specs/getList.spec.js
new file mode 100644
index 000000000..6c60d3505
--- /dev/null
+++ b/back/methods/notification/specs/getList.spec.js
@@ -0,0 +1,13 @@
+const models = require('vn-loopback/server/server').models;
+
+describe('NotificationSubscription getList()', () => {
+ it('should return a list of available and active notifications of a user', async() => {
+ const userId = 9;
+ const {active, available} = await models.NotificationSubscription.getList(userId);
+ const notifications = await models.Notification.find({});
+ const totalAvailable = notifications.length - active.length;
+
+ expect(active.length).toEqual(3);
+ expect(available.length).toEqual(totalAvailable);
+ });
+});
diff --git a/back/methods/osticket/sendToSupport.js b/back/methods/osticket/sendToSupport.js
index 5b9ebb4e3..e17093839 100644
--- a/back/methods/osticket/sendToSupport.js
+++ b/back/methods/osticket/sendToSupport.js
@@ -35,11 +35,18 @@ module.exports = Self => {
let html = `Motivo: ${reason} `;
html += `Usuario: ${ctx.req.accessToken.userId} ${emailUser.email} `;
+ delete additionalData.backError.config.headers.Authorization;
+ const httpRequest = JSON.parse(additionalData?.httpRequest);
+
+ if (httpRequest)
+ delete httpRequest.config.headers.Authorization;
+ additionalData.httpRequest = httpRequest;
+
for (const data in additionalData)
html += `${data}: ${tryParse(additionalData[data])} `;
- const subjectReason = JSON.parse(additionalData?.httpRequest)?.data?.error;
- smtp.send({
+ const subjectReason = httpRequest?.data?.error;
+ await smtp.send({
to: `${config.app.reportEmail}, ${emailUser.email}`,
subject:
'[Support-Salix] ' +
diff --git a/back/methods/postcode/filter.js b/back/methods/postcode/filter.js
new file mode 100644
index 000000000..4c3fc0cd3
--- /dev/null
+++ b/back/methods/postcode/filter.js
@@ -0,0 +1,80 @@
+const {ParameterizedSQL} = require('loopback-connector');
+const {buildFilter} = require('vn-loopback/util/filter');
+
+module.exports = Self => {
+ Self.remoteMethod('filter', {
+ description:
+ 'Find all postcodes of the model matched by postcode, town, province or country.',
+ accessType: 'READ',
+ accepts: [
+ {
+ arg: 'filter',
+ type: 'object',
+ description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string',
+ http: {source: 'query'}
+ },
+ {
+ arg: 'search',
+ type: 'string',
+ description: 'Value to filter',
+ http: {source: 'query'}
+ },
+ ],
+ returns: {
+ type: ['object'],
+ root: true,
+ },
+ http: {
+ path: `/filter`,
+ verb: 'GET',
+ },
+ });
+ Self.filter = async(ctx, filter, options) => {
+ const myOptions = {};
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ filter = ctx?.filter ?? {};
+
+ const conn = Self.dataSource.connector;
+ const where = buildFilter(filter?.where, (param, value) => {
+ switch (param) {
+ case 'search':
+ return {
+ or: [
+ {'pc.code': {like: `%${value}%`}},
+ {'t.name': {like: `%${value}%`}},
+ {'p.name': {like: `%${value}%`}},
+ {'c.country': {like: `%${value}%`}}
+ ]
+ };
+ }
+ }) ?? {};
+ delete ctx.filter.where;
+
+ const stmts = [];
+ let stmt;
+ stmt = new ParameterizedSQL(`
+ SELECT
+ pc.townFk,
+ t.provinceFk,
+ p.countryFk,
+ pc.code,
+ t.name as town,
+ p.name as province,
+ c.country
+ FROM
+ postCode pc
+ JOIN town t on t.id = pc.townFk
+ JOIN province p on p.id = t.provinceFk
+ JOIN country c on c.id = p.countryFk
+ `);
+
+ stmt.merge(conn.makeSuffix({where, ...ctx}));
+ const itemsIndex = stmts.push(stmt) - 1;
+
+ const sql = ParameterizedSQL.join(stmts, ';');
+ const result = await conn.executeStmt(sql, myOptions);
+ return itemsIndex === 0 ? result : result[itemsIndex];
+ };
+};
diff --git a/back/methods/postcode/specs/filter.spec.js b/back/methods/postcode/specs/filter.spec.js
new file mode 100644
index 000000000..60ac24809
--- /dev/null
+++ b/back/methods/postcode/specs/filter.spec.js
@@ -0,0 +1,111 @@
+const {models} = require('vn-loopback/server/server');
+
+describe('Postcode filter()', () => {
+ it('should retrieve with no filter', async() => {
+ const tx = await models.Postcode.beginTransaction({});
+ const options = {transaction: tx};
+
+ try {
+ const ctx = {
+ filter: {
+ },
+ limit: 1
+ };
+ const results = await models.Postcode.filter(ctx, options);
+
+ expect(results.length).toEqual(1);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should retrieve with filter as postcode', async() => {
+ const tx = await models.Postcode.beginTransaction({});
+ const options = {transaction: tx};
+
+ try {
+ const ctx = {
+ filter: {
+ where: {
+ search: 46,
+ }
+ },
+ };
+ const results = await models.Postcode.filter(ctx, options);
+
+ expect(results.length).toEqual(4);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should retrieve with filter as city', async() => {
+ const tx = await models.Postcode.beginTransaction({});
+ const options = {transaction: tx};
+
+ try {
+ const ctx = {
+ filter: {
+ where: {
+ search: 'Alz',
+ }
+ },
+ };
+ const results = await models.Postcode.filter(ctx, options);
+
+ expect(results.length).toEqual(1);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should retrieve with filter as province', async() => {
+ const tx = await models.Postcode.beginTransaction({});
+ const options = {transaction: tx};
+
+ try {
+ const ctx = {
+ filter: {
+ where: {
+ search: 'one',
+ }
+ },
+ };
+ const results = await models.Postcode.filter(ctx, options);
+
+ expect(results.length).toEqual(4);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should retrieve with filter as country', async() => {
+ const tx = await models.Postcode.beginTransaction({});
+ const options = {transaction: tx};
+
+ try {
+ const ctx = {
+ filter: {
+ where: {
+ search: 'Ec',
+ }
+ },
+ };
+ const results = await models.Postcode.filter(ctx, options);
+
+ expect(results.length).toEqual(1);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+});
diff --git a/back/methods/url/getByUser.js b/back/methods/url/getByUser.js
new file mode 100644
index 000000000..dd4805182
--- /dev/null
+++ b/back/methods/url/getByUser.js
@@ -0,0 +1,40 @@
+module.exports = function(Self) {
+ Self.remoteMethod('getByUser', {
+ description: 'returns the starred modules for the current user',
+ accessType: 'READ',
+ accepts: [{
+ arg: 'userId',
+ type: 'number',
+ description: 'The user id',
+ required: true,
+ http: {source: 'path'}
+ }],
+ returns: {
+ type: 'object',
+ root: true
+ },
+ http: {
+ path: `/:userId/get-by-user`,
+ verb: 'GET'
+ }
+ });
+
+ Self.getByUser = async userId => {
+ const models = Self.app.models;
+ const appNames = ['hedera'];
+ const filter = {
+ fields: ['appName', 'url'],
+ where: {
+ appName: {inq: appNames},
+ environment: process.env.NODE_ENV ?? 'development',
+ }
+ };
+
+ const isWorker = await models.Account.findById(userId, {fields: ['id']});
+ if (!isWorker)
+ return models.Url.find(filter);
+
+ appNames.push('salix');
+ return models.Url.find(filter);
+ };
+};
diff --git a/back/methods/url/getUrl.js b/back/methods/url/getUrl.js
new file mode 100644
index 000000000..ef741e5a0
--- /dev/null
+++ b/back/methods/url/getUrl.js
@@ -0,0 +1,30 @@
+module.exports = Self => {
+ Self.remoteMethod('getUrl', {
+ description: 'Returns the colling app name',
+ accessType: 'READ',
+ accepts: [
+ {
+ arg: 'app',
+ type: 'string',
+ required: false
+ }
+ ],
+ returns: {
+ type: 'object',
+ root: true
+ },
+ http: {
+ path: `/getUrl`,
+ verb: 'get'
+ }
+ });
+ Self.getUrl = async(appName = 'salix') => {
+ const {url} = await Self.app.models.Url.findOne({
+ where: {
+ appName,
+ environment: process.env.NODE_ENV || 'development'
+ }
+ });
+ return url;
+ };
+};
diff --git a/back/methods/url/specs/getByUser.spec.js b/back/methods/url/specs/getByUser.spec.js
new file mode 100644
index 000000000..f6af6ec00
--- /dev/null
+++ b/back/methods/url/specs/getByUser.spec.js
@@ -0,0 +1,19 @@
+const {models} = require('vn-loopback/server/server');
+
+describe('getByUser()', () => {
+ const worker = 1;
+ const notWorker = 2;
+ it(`should return only hedera url if not is worker`, async() => {
+ const urls = await models.Url.getByUser(notWorker);
+
+ expect(urls.length).toEqual(1);
+ expect(urls[0].appName).toEqual('hedera');
+ });
+
+ it(`should return more than hedera url`, async() => {
+ const urls = await models.Url.getByUser(worker);
+
+ expect(urls.length).toBeGreaterThan(1);
+ expect(urls.find(url => url.appName == 'salix').appName).toEqual('salix');
+ });
+});
diff --git a/back/methods/viaexpress-config/deleteExpedition.ejs b/back/methods/viaexpress-config/deleteExpedition.ejs
new file mode 100644
index 000000000..3be459a8d
--- /dev/null
+++ b/back/methods/viaexpress-config/deleteExpedition.ejs
@@ -0,0 +1,11 @@
+
+
+
+
+ <%= viaexpressConfig.client %>
+ <%= viaexpressConfig.user %>
+ <%= viaexpressConfig.password %>
+ <%= externalId %>
+
+
+
diff --git a/back/methods/viaexpress-config/deleteExpedition.js b/back/methods/viaexpress-config/deleteExpedition.js
new file mode 100644
index 000000000..189745554
--- /dev/null
+++ b/back/methods/viaexpress-config/deleteExpedition.js
@@ -0,0 +1,45 @@
+const axios = require('axios');
+const {DOMParser} = require('xmldom');
+
+module.exports = Self => {
+ Self.remoteMethod('deleteExpedition', {
+ description: 'Delete a shipment by providing the expedition ID, interacting with Viaexpress API',
+ accessType: 'WRITE',
+ accepts: [{
+ arg: 'expeditionFk',
+ type: 'number',
+ required: true
+ }],
+ returns: {
+ type: ['object'],
+ root: true
+ },
+ http: {
+ path: `/deleteExpedition`,
+ verb: 'POST'
+ }
+ });
+
+ Self.deleteExpedition = async expeditionFk => {
+ const models = Self.app.models;
+
+ const viaexpressConfig = await models.ViaexpressConfig.findOne({
+ fields: ['url']
+ });
+
+ const renderedXml = await models.ViaexpressConfig.deleteExpeditionRenderer(expeditionFk);
+ const response = await axios.post(`${viaexpressConfig.url}ServicioVxClientes.asmx`, renderedXml, {
+ headers: {
+ 'Content-Type': 'application/soap+xml; charset=utf-8'
+ }
+ });
+
+ const xmlString = response.data;
+ const parser = new DOMParser();
+ const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
+ const resultElement = xmlDoc.getElementsByTagName('DeleteEnvioResult')[0];
+ const result = resultElement.textContent;
+
+ return result;
+ };
+};
diff --git a/back/methods/viaexpress-config/deleteExpeditionRenderer.js b/back/methods/viaexpress-config/deleteExpeditionRenderer.js
new file mode 100644
index 000000000..645eaddd1
--- /dev/null
+++ b/back/methods/viaexpress-config/deleteExpeditionRenderer.js
@@ -0,0 +1,44 @@
+const fs = require('fs');
+const ejs = require('ejs');
+
+module.exports = Self => {
+ Self.remoteMethod('deleteExpeditionRenderer', {
+ description: 'Renders the data from an XML',
+ accessType: 'READ',
+ accepts: [{
+ arg: 'expeditionFk',
+ type: 'number',
+ required: true
+ }],
+ returns: {
+ type: ['object'],
+ root: true
+ },
+ http: {
+ path: `/deleteExpeditionRenderer`,
+ verb: 'GET'
+ }
+ });
+
+ Self.deleteExpeditionRenderer = async expeditionFk => {
+ const models = Self.app.models;
+
+ const viaexpressConfig = await models.ViaexpressConfig.findOne({
+ fields: ['client', 'user', 'password']
+ });
+
+ const expedition = await models.Expedition.findOne({
+ fields: ['id', 'externalId'],
+ where: {id: expeditionFk}
+ });
+
+ const data = {
+ viaexpressConfig,
+ externalId: expedition.externalId
+ };
+
+ const template = fs.readFileSync(__dirname + '/deleteExpedition.ejs', 'utf-8');
+ const renderedXml = ejs.render(template, data);
+ return renderedXml;
+ };
+};
diff --git a/back/methods/viaexpress-config/internationalExpedition.js b/back/methods/viaexpress-config/internationalExpedition.js
index 698bb1dac..df50b21e5 100644
--- a/back/methods/viaexpress-config/internationalExpedition.js
+++ b/back/methods/viaexpress-config/internationalExpedition.js
@@ -20,7 +20,7 @@ module.exports = Self => {
}
});
- Self.internationalExpedition = async expeditionFk => {
+ Self.internationalExpedition = async (expeditionFk) => {
const models = Self.app.models;
const viaexpressConfig = await models.ViaexpressConfig.findOne({
diff --git a/back/methods/viaexpress-config/renderer.js b/back/methods/viaexpress-config/renderer.js
index e9abce5ca..c8533ea6b 100644
--- a/back/methods/viaexpress-config/renderer.js
+++ b/back/methods/viaexpress-config/renderer.js
@@ -20,11 +20,11 @@ module.exports = Self => {
}
});
- Self.renderer = async expeditionFk => {
+ Self.renderer = async (expeditionFk) => {
const models = Self.app.models;
const viaexpressConfig = await models.ViaexpressConfig.findOne({
- fields: ['client', 'user', 'password', 'defaultWeight', 'deliveryType']
+ fields: ['client', 'user', 'password', 'defaultWeight', 'deliveryType', 'agencyModeFk']
});
const expedition = await models.Expedition.findOne({
@@ -34,7 +34,7 @@ module.exports = Self => {
{
relation: 'ticket',
scope: {
- fields: ['shipped', 'addressFk', 'clientFk', 'companyFk'],
+ fields: ['shipped', 'addressFk', 'clientFk', 'companyFk', 'agencyModeFk'],
include: [
{
relation: 'client',
@@ -102,7 +102,6 @@ module.exports = Self => {
}
]
}
-
}
]
});
@@ -110,13 +109,15 @@ module.exports = Self => {
const ticket = expedition.ticket();
const sender = ticket.company().client();
const shipped = ticket.shipped.toISOString();
+ const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk)
const data = {
viaexpressConfig,
sender,
senderAddress: sender.defaultAddress(),
client: ticket.client(),
address: ticket.address(),
- shipped
+ shipped,
+ isInterdia
};
const template = fs.readFileSync(__dirname + '/template.ejs', 'utf-8');
diff --git a/back/methods/viaexpress-config/template.ejs b/back/methods/viaexpress-config/template.ejs
index 0b6eb468c..f9acfe316 100644
--- a/back/methods/viaexpress-config/template.ejs
+++ b/back/methods/viaexpress-config/template.ejs
@@ -13,7 +13,7 @@
000
- 0
+ <%= isInterdia %>0
diff --git a/back/methods/vn-user/privileges.js b/back/methods/vn-user/privileges.js
index 08cfaaae8..9f936c29b 100644
--- a/back/methods/vn-user/privileges.js
+++ b/back/methods/vn-user/privileges.js
@@ -68,7 +68,7 @@ module.exports = Self => {
userToUpdate.hasGrant = hasGrant;
if (roleFk) {
- const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions);
+ const role = await models.VnRole.findById(roleFk, {fields: ['name']}, myOptions);
const hasRole = await Self.hasRole(userId, role.name, myOptions);
if (!hasRole)
diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js
index 9850267d6..d00085d8a 100644
--- a/back/methods/vn-user/renew-token.js
+++ b/back/methods/vn-user/renew-token.js
@@ -1,4 +1,4 @@
-const UserError = require('vn-loopback/util/user-error');
+const {models} = require('vn-loopback/server/server');
module.exports = Self => {
Self.remoteMethodCtx('renewToken', {
@@ -16,20 +16,31 @@ module.exports = Self => {
});
Self.renewToken = async function(ctx) {
- const models = Self.app.models;
- const token = ctx.req.accessToken;
+ const {accessToken: token} = ctx.req;
- const now = new Date();
+ // Check if current token is valid
+
+ const {renewPeriod, courtesyTime} = await models.AccessTokenConfig.findOne({
+ fields: ['renewPeriod', 'courtesyTime']
+ });
+ const now = Date.now();
const differenceMilliseconds = now - token.created;
const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
+ const isNotExceeded = differenceSeconds < renewPeriod - courtesyTime;
+ if (isNotExceeded)
+ return token;
- const fields = ['renewPeriod', 'courtesyTime'];
- const accessTokenConfig = await models.AccessTokenConfig.findOne({fields});
+ // Schedule to remove current token
+ setTimeout(async() => {
+ try {
+ await Self.logout(token.id);
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.error(err);
+ }
+ }, courtesyTime * 1000);
- if (differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime)
- throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded');
-
- await Self.logout(token.id);
+ // Create new accessToken
const user = await Self.findById(token.userId);
const accessToken = await user.createAccessToken();
diff --git a/back/methods/vn-user/share-token.js b/back/methods/vn-user/share-token.js
new file mode 100644
index 000000000..8efa22db4
--- /dev/null
+++ b/back/methods/vn-user/share-token.js
@@ -0,0 +1,27 @@
+
+module.exports = Self => {
+ Self.remoteMethodCtx('shareToken', {
+ description: 'Returns token to view files or images and share it',
+ accessType: 'WRITE',
+ accepts: [],
+ returns: {
+ type: 'Object',
+ root: true
+ },
+ http: {
+ path: `/shareToken`,
+ verb: 'GET'
+ }
+ });
+
+ Self.shareToken = async function(ctx) {
+ const {accessToken: token} = ctx.req;
+
+ const user = await Self.findById(token.userId);
+ const multimediaToken = await user.accessTokens.create({
+ scopes: ['read:multimedia']
+ });
+
+ return {multimediaToken};
+ };
+};
diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js
index b9e0d2f70..782046641 100644
--- a/back/methods/vn-user/sign-in.js
+++ b/back/methods/vn-user/sign-in.js
@@ -49,8 +49,7 @@ module.exports = Self => {
if (vnUser.twoFactor)
throw new ForbiddenError(null, 'REQUIRES_2FA');
}
-
- return Self.validateLogin(user, password);
+ return Self.validateLogin(user, password, ctx);
};
Self.passExpired = async vnUser => {
diff --git a/back/methods/vn-user/specs/privileges.spec.js b/back/methods/vn-user/specs/privileges.spec.js
index 3d25eecf9..04d9c09ff 100644
--- a/back/methods/vn-user/specs/privileges.spec.js
+++ b/back/methods/vn-user/specs/privileges.spec.js
@@ -70,7 +70,7 @@ describe('VnUser privileges()', () => {
const tx = await models.VnUser.beginTransaction({});
const options = {transaction: tx};
- const agency = await models.Role.findOne({
+ const agency = await models.VnRole.findOne({
where: {
name: 'agency'
}
diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js
new file mode 100644
index 000000000..8d9bbf11c
--- /dev/null
+++ b/back/methods/vn-user/specs/renew-token.spec.js
@@ -0,0 +1,50 @@
+const {models} = require('vn-loopback/server/server');
+describe('Renew Token', () => {
+ const startingTime = Date.now();
+ let ctx = null;
+ beforeAll(async() => {
+ const unAuthCtx = {
+ req: {
+ headers: {},
+ connection: {
+ remoteAddress: '127.0.0.1'
+ },
+ getLocale: () => 'en'
+ },
+ args: {}
+ };
+ let login = await models.VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare');
+ let accessToken = await models.AccessToken.findById(login.token);
+ ctx = {req: {accessToken: accessToken}};
+ });
+
+ beforeEach(() => {
+ jasmine.clock().install();
+ jasmine.clock().mockDate(new Date(startingTime));
+ });
+
+ afterEach(() => {
+ jasmine.clock().uninstall();
+ });
+
+ it('should renew token', async() => {
+ const mockDate = new Date(startingTime + 26600000);
+ jasmine.clock().mockDate(mockDate);
+ const {id} = await models.VnUser.renewToken(ctx);
+
+ expect(id).not.toEqual(ctx.req.accessToken.id);
+ });
+
+ it('NOT should renew', async() => {
+ let error;
+ let response;
+ try {
+ response = await models.VnUser.renewToken(ctx);
+ } catch (e) {
+ error = e;
+ }
+
+ expect(error).toBeUndefined();
+ expect(response.id).toEqual(ctx.req.accessToken.id);
+ });
+});
diff --git a/back/methods/vn-user/specs/share-token.spec.js b/back/methods/vn-user/specs/share-token.spec.js
new file mode 100644
index 000000000..aaa83817c
--- /dev/null
+++ b/back/methods/vn-user/specs/share-token.spec.js
@@ -0,0 +1,27 @@
+const {models} = require('vn-loopback/server/server');
+describe('Share Token', () => {
+ let ctx = null;
+ beforeAll(async() => {
+ const unAuthCtx = {
+ req: {
+ headers: {},
+ connection: {
+ remoteAddress: '127.0.0.1'
+ },
+ getLocale: () => 'en'
+ },
+ args: {}
+ };
+ let login = await models.VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare');
+ let accessToken = await models.AccessToken.findById(login.token);
+ ctx = {req: {accessToken: accessToken}};
+ });
+
+ it('should renew token', async() => {
+ const multimediaToken = await models.VnUser.shareToken(ctx);
+
+ expect(Object.keys(multimediaToken).length).toEqual(1);
+ expect(multimediaToken.multimediaToken.userId).toEqual(ctx.req.accessToken.userId);
+ expect(multimediaToken.multimediaToken.scopes[0]).toEqual('read:multimedia');
+ });
+});
diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js
index f4cad88b9..a14dd301e 100644
--- a/back/methods/vn-user/specs/sign-in.spec.js
+++ b/back/methods/vn-user/specs/sign-in.spec.js
@@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server');
describe('VnUser Sign-in()', () => {
const employeeId = 1;
- const unauthCtx = {
+ const unAuthCtx = {
req: {
headers: {},
connection: {
@@ -12,10 +12,21 @@ describe('VnUser Sign-in()', () => {
},
args: {}
};
- const {VnUser, AccessToken} = models;
+ const {VnUser, AccessToken, SignInLog} = models;
describe('when credentials are correct', () => {
+ it('should return the token if user uses email', async() => {
+ let login = await VnUser.signIn(unAuthCtx, 'salesAssistant@mydomain.com', 'nightmare');
+ let accessToken = await AccessToken.findById(login.token);
+ let ctx = {req: {accessToken: accessToken}};
+ let signInLog = await SignInLog.find({where: {token: accessToken.id}});
+
+ expect(signInLog.length).toEqual(0);
+
+ await VnUser.logout(ctx.req.accessToken.id);
+ });
+
it('should return the token', async() => {
- let login = await VnUser.signIn(unauthCtx, 'salesAssistant', 'nightmare');
+ let login = await VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare');
let accessToken = await AccessToken.findById(login.token);
let ctx = {req: {accessToken: accessToken}};
@@ -25,7 +36,7 @@ describe('VnUser Sign-in()', () => {
});
it('should return the token if the user doesnt exist but the client does', async() => {
- let login = await VnUser.signIn(unauthCtx, 'PetterParker', 'nightmare');
+ let login = await VnUser.signIn(unAuthCtx, 'PetterParker', 'nightmare');
let accessToken = await AccessToken.findById(login.token);
let ctx = {req: {accessToken: accessToken}};
@@ -40,7 +51,7 @@ describe('VnUser Sign-in()', () => {
let error;
try {
- await VnUser.signIn(unauthCtx, 'IDontExist', 'TotallyWrongPassword');
+ await VnUser.signIn(unAuthCtx, 'IDontExist', 'TotallyWrongPassword');
} catch (e) {
error = e;
}
@@ -61,7 +72,7 @@ describe('VnUser Sign-in()', () => {
const options = {transaction: tx};
await employee.updateAttribute('twoFactor', 'email', options);
- await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options);
+ await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options);
await tx.rollback();
} catch (e) {
await tx.rollback();
@@ -86,7 +97,7 @@ describe('VnUser Sign-in()', () => {
const options = {transaction: tx};
await employee.updateAttribute('passExpired', yesterday, options);
- await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options);
+ await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options);
await tx.rollback();
} catch (e) {
await tx.rollback();
diff --git a/back/methods/vn-user/update-user.js b/back/methods/vn-user/update-user.js
new file mode 100644
index 000000000..ddaae8548
--- /dev/null
+++ b/back/methods/vn-user/update-user.js
@@ -0,0 +1,39 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('updateUser', {
+ description: 'Update user data',
+ accepts: [
+ {
+ arg: 'id',
+ type: 'integer',
+ description: 'The user id',
+ required: true,
+ http: {source: 'path'}
+ }, {
+ arg: 'name',
+ type: 'string',
+ description: 'The user name',
+ }, {
+ arg: 'nickname',
+ type: 'string',
+ description: 'The user nickname',
+ }, {
+ arg: 'email',
+ type: 'string',
+ description: 'The user email'
+ }, {
+ arg: 'lang',
+ type: 'string',
+ description: 'The user lang'
+ }
+ ],
+ http: {
+ path: `/:id/update-user`,
+ verb: 'PATCH'
+ }
+ });
+
+ Self.updateUser = async(ctx, id, name, nickname, email, lang) => {
+ await Self.userSecurity(ctx, id);
+ await Self.upsertWithWhere({id}, {name, nickname, email, lang});
+ };
+};
diff --git a/back/methods/vn-user/validate-token.js b/back/methods/vn-user/validate-token.js
deleted file mode 100644
index 7bccfe0b1..000000000
--- a/back/methods/vn-user/validate-token.js
+++ /dev/null
@@ -1,17 +0,0 @@
-module.exports = Self => {
- Self.remoteMethod('validateToken', {
- description: 'Validates the current logged user token',
- returns: {
- type: 'Boolean',
- root: true
- },
- http: {
- path: `/validateToken`,
- verb: 'GET'
- }
- });
-
- Self.validateToken = async function() {
- return true;
- };
-};
diff --git a/back/model-config.json b/back/model-config.json
index ebc0e321b..f48ec11e6 100644
--- a/back/model-config.json
+++ b/back/model-config.json
@@ -13,10 +13,10 @@
"AuthCode": {
"dataSource": "vn"
},
- "Bank": {
+ "Accounting": {
"dataSource": "vn"
},
- "Buyer": {
+ "Buyer": {
"dataSource": "vn"
},
"Campaign": {
@@ -79,15 +79,24 @@
"Language": {
"dataSource": "vn"
},
+ "Machine": {
+ "dataSource": "vn"
+ },
"MachineWorker": {
"dataSource": "vn"
},
+ "MachineWorkerConfig": {
+ "dataSource": "vn"
+ },
"MobileAppVersionControl": {
"dataSource": "vn"
},
"Module": {
"dataSource": "vn"
},
+ "MrwConfig": {
+ "dataSource": "vn"
+ },
"Notification": {
"dataSource": "vn"
},
@@ -139,9 +148,6 @@
"Warehouse": {
"dataSource": "vn"
},
- "VnUser": {
- "dataSource": "vn"
- },
"OsTicket": {
"dataSource": "osticket"
},
@@ -156,8 +162,17 @@
},
"ViaexpressConfig": {
"dataSource": "vn"
+ },
+ "VnUser": {
+ "dataSource": "vn"
+ },
+ "VnRole": {
+ "dataSource": "vn"
+ },
+ "WorkerActivity": {
+ "dataSource": "vn"
+ },
+ "WorkerActivityType": {
+ "dataSource": "vn"
}
-}
-
-
-
+}
\ No newline at end of file
diff --git a/back/models/bank.json b/back/models/accounting.json
similarity index 85%
rename from back/models/bank.json
rename to back/models/accounting.json
index da73b1141..979947471 100644
--- a/back/models/bank.json
+++ b/back/models/accounting.json
@@ -1,9 +1,9 @@
{
- "name": "Bank",
+ "name": "Accounting",
"base": "VnModel",
"options": {
"mysql": {
- "table": "bank"
+ "table": "accounting"
}
},
"properties": {
@@ -22,10 +22,7 @@
},
"accountingTypeFk": {
"type": "number",
- "required": true,
- "mysql": {
- "columnName": "cash"
- }
+ "required": true
},
"entityFk": {
"type": "number",
diff --git a/back/models/bank-entity.js b/back/models/bank-entity.js
index c89e0b364..ac352f93c 100644
--- a/back/models/bank-entity.js
+++ b/back/models/bank-entity.js
@@ -8,6 +8,26 @@ module.exports = Self => {
});
Self.validatesUniquenessOf('bic', {
- message: 'This BIC already exist.'
+ message: 'This BIC already exist'
});
+
+ Self.validatesPresenceOf('countryFk', {
+ message: 'CountryFK cannot be empty'
+ });
+
+ Self.validateAsync('bic', checkBic, {
+ message: 'Bank entity id must be specified'
+ });
+ async function checkBic(err, done) {
+ const filter = {
+ fields: ['code'],
+ where: {id: this.countryFk}
+ };
+ const country = await Self.app.models.Country.findOne(filter);
+ const code = country ? country.code.toLowerCase() : null;
+
+ if (code == 'es' && !this.id)
+ err();
+ done();
+ }
};
diff --git a/back/models/chat.js b/back/models/chat.js
index a18edbd3f..882db747e 100644
--- a/back/models/chat.js
+++ b/back/models/chat.js
@@ -7,17 +7,14 @@ module.exports = Self => {
Self.observe('before save', async function(ctx) {
if (!ctx.isNewInstance) return;
-
let {message} = ctx.instance;
if (!message) return;
const parts = message.match(/(?<=\[)[a-zA-Z0-9_\-+!@#$%^&*()={};':"\\|,.<>/?\s]*(?=])/g);
if (!parts) return;
-
const replacedParts = parts.map(part => {
return part.replace(/[!$%^&*()={};':"\\,.<>/?]/g, '');
});
-
for (const [index, part] of parts.entries())
message = message.replace(part, replacedParts[index]);
diff --git a/back/models/collection.js b/back/models/collection.js
index bfa906af6..f2c2f1566 100644
--- a/back/models/collection.js
+++ b/back/models/collection.js
@@ -1,8 +1,8 @@
module.exports = Self => {
require('../methods/collection/getCollection')(Self);
- require('../methods/collection/newCollection')(Self);
- require('../methods/collection/getSectors')(Self);
require('../methods/collection/setSaleQuantity')(Self);
require('../methods/collection/previousLabel')(Self);
require('../methods/collection/getTickets')(Self);
+ require('../methods/collection/assign')(Self);
+ require('../methods/collection/getSales')(Self);
};
diff --git a/back/models/dms-type.json b/back/models/dms-type.json
index de3d564b4..d3e96a986 100644
--- a/back/models/dms-type.json
+++ b/back/models/dms-type.json
@@ -17,10 +17,6 @@
"type": "string",
"required": true
},
- "path": {
- "type": "string",
- "required": true
- },
"code": {
"type": "string",
"required": true
@@ -29,12 +25,12 @@
"relations": {
"readRole": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "readRoleFk"
},
"writeRole": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "writeRoleFk"
}
},
diff --git a/back/models/dms.js b/back/models/dms.js
index 24c072f56..d6eab4fe4 100644
--- a/back/models/dms.js
+++ b/back/models/dms.js
@@ -1,4 +1,6 @@
const UserError = require('vn-loopback/util/user-error');
+const fs = require('fs-extra');
+const path = require('path');
module.exports = Self => {
require('../methods/dms/downloadFile')(Self);
@@ -35,4 +37,32 @@ module.exports = Self => {
return [stream, dms.contentType, `filename="${dms.file}"`];
};
+
+ Self.getPath = async function(dms) {
+ const models = Self.app.models;
+ const pathHash = await models.DmsContainer.getHash(dms.id);
+ const dmsContainer = await models.DmsContainer.container(pathHash);
+ const dstFile = path.join(dmsContainer.client.root, pathHash, dms.file);
+ return dstFile;
+ };
+
+ Self.createWithExtension = async function(data, extension, options) {
+ const newDms = await Self.create(data, options);
+ return newDms.updateAttribute('file', `${newDms.id}.${extension}`, options);
+ };
+
+ Self.createFromFile = async function(data, extension, srcFile, options) {
+ const dms = await Self.createWithExtension(data, extension, options);
+ const dstFile = await Self.getPath(dms);
+ await fs.move(srcFile, dstFile, {overwrite: true});
+ return dms;
+ };
+
+ Self.createFromStream = async function(data, extension, stream, options) {
+ const dms = await Self.createWithExtension(data, extension, options);
+ const dstFile = await Self.getPath(dms);
+ const writeStream = await fs.createWriteStream(dstFile);
+ await stream.pipe(writeStream);
+ return dms;
+ };
};
diff --git a/back/models/docuwareTablet.json b/back/models/docuwareTablet.json
new file mode 100644
index 000000000..dbbf62f56
--- /dev/null
+++ b/back/models/docuwareTablet.json
@@ -0,0 +1,17 @@
+{
+ "name": "docuwareTablet",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "docuwareTablet"
+ }
+ },
+ "properties": {
+ "tablet": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ }
+ }
+}
diff --git a/back/models/image-collection.json b/back/models/image-collection.json
index 186ab0208..ae0e0adcd 100644
--- a/back/models/image-collection.json
+++ b/back/models/image-collection.json
@@ -46,12 +46,12 @@
},
"readRole": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "readRoleFk"
},
"writeRole": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "writeRoleFk"
}
},
@@ -64,4 +64,3 @@
}
]
}
-
\ No newline at end of file
diff --git a/back/models/machine-worker-config.json b/back/models/machine-worker-config.json
new file mode 100644
index 000000000..dfb77124e
--- /dev/null
+++ b/back/models/machine-worker-config.json
@@ -0,0 +1,18 @@
+{
+ "name": "MachineWorkerConfig",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "vn.machineWorkerConfig"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true
+ },
+ "maxHours": {
+ "type": "number"
+ }
+ }
+}
diff --git a/back/models/machine-worker.js b/back/models/machine-worker.js
new file mode 100644
index 000000000..cbc5fd53e
--- /dev/null
+++ b/back/models/machine-worker.js
@@ -0,0 +1,3 @@
+module.exports = Self => {
+ require('../methods/machine-worker/updateInTime')(Self);
+};
diff --git a/back/models/machine.json b/back/models/machine.json
new file mode 100644
index 000000000..7029091a2
--- /dev/null
+++ b/back/models/machine.json
@@ -0,0 +1,18 @@
+{
+ "name": "Machine",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "vn.machine"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true
+ },
+ "plate": {
+ "type": "string"
+ }
+ }
+}
diff --git a/back/models/mobile-app-version-control.js b/back/models/mobile-app-version-control.js
new file mode 100644
index 000000000..ee8fa2ab6
--- /dev/null
+++ b/back/models/mobile-app-version-control.js
@@ -0,0 +1,3 @@
+module.exports = Self => {
+ require('../methods/mobile-app-version-control/getVersion')(Self);
+};
diff --git a/back/models/mobile-app-version-control.json b/back/models/mobile-app-version-control.json
new file mode 100644
index 000000000..819ad33f5
--- /dev/null
+++ b/back/models/mobile-app-version-control.json
@@ -0,0 +1,39 @@
+{
+ "name": "MobileAppVersionControl",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "vn.mobileAppVersionControl"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true
+ },
+ "appName": {
+ "type": "string"
+ },
+
+ "version": {
+ "type": "string"
+ },
+
+ "isVersionCritical": {
+ "type": "boolean"
+ },
+
+ "urlProduction": {
+ "type": "string"
+ },
+ "urlBeta": {
+ "type": "string"
+ },
+ "versionBeta": {
+ "type": "string"
+ },
+ "isVersionBetaCritical": {
+ "type": "boolean"
+ }
+ }
+}
diff --git a/back/models/mrw-config.js b/back/models/mrw-config.js
new file mode 100644
index 000000000..f764b91cc
--- /dev/null
+++ b/back/models/mrw-config.js
@@ -0,0 +1,4 @@
+module.exports = Self => {
+ require('../methods/mrw-config/createShipment')(Self);
+ require('../methods/mrw-config/cancelShipment')(Self);
+};
diff --git a/back/models/mrw-config.json b/back/models/mrw-config.json
new file mode 100644
index 000000000..50cf7e8fc
--- /dev/null
+++ b/back/models/mrw-config.json
@@ -0,0 +1,32 @@
+{
+ "name": "MrwConfig",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "mrwConfig"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true,
+ "required": true
+ },
+ "url": {
+ "type": "string",
+ "required": true
+ },
+ "user": {
+ "type": "string"
+ },
+ "password": {
+ "type": "string"
+ },
+ "franchiseCode": {
+ "type": "string"
+ },
+ "subscriberCode": {
+ "type": "string"
+ }
+ }
+}
diff --git a/back/models/notificationAcl.json b/back/models/notificationAcl.json
index a20187961..9ab85530f 100644
--- a/back/models/notificationAcl.json
+++ b/back/models/notificationAcl.json
@@ -24,8 +24,8 @@
},
"role": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "roleFk"
}
}
-}
\ No newline at end of file
+}
diff --git a/back/models/notificationSubscription.js b/back/models/notificationSubscription.js
index f1b2811fa..8efb83e7d 100644
--- a/back/models/notificationSubscription.js
+++ b/back/models/notificationSubscription.js
@@ -1,62 +1,74 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
+ require('../methods/notification/getList')(Self);
+
Self.observe('before save', async function(ctx) {
+ await checkModifyPermission(ctx);
+ });
+
+ Self.observe('before delete', async function(ctx) {
+ await checkModifyPermission(ctx);
+ });
+
+ async function checkModifyPermission(ctx) {
const models = Self.app.models;
+ const instance = ctx.instance;
const userId = ctx.options.accessToken.userId;
- const user = await ctx.instance.userFk;
- const modifiedUser = await getUserToModify(null, user, models);
- if (userId != modifiedUser.id && userId != modifiedUser.bossFk)
- throw new UserError('You dont have permission to modify this user');
- });
+ let notificationFk;
+ let workerId;
- Self.remoteMethod('deleteNotification', {
- description: 'Deletes a notification subscription',
- accepts: [
- {
- arg: 'ctx',
- type: 'object',
- http: {source: 'context'}
- },
- {
- arg: 'notificationId',
- type: 'number',
- required: true
- },
- ],
- returns: {
- type: 'object',
- root: true
- },
- http: {
- verb: 'POST',
- path: '/deleteNotification'
+ if (instance) {
+ notificationFk = instance.notificationFk;
+ workerId = instance.userFk;
+ } else {
+ const notificationSubscription = await models.NotificationSubscription.findById(ctx.where.id);
+ notificationFk = notificationSubscription.notificationFk;
+ workerId = notificationSubscription.userFk;
}
- });
- Self.deleteNotification = async function(ctx, notificationId) {
- const models = Self.app.models;
- const user = ctx.req.accessToken.userId;
- const modifiedUser = await getUserToModify(notificationId, null, models);
+ const worker = await models.Worker.findById(workerId, {fields: ['id', 'bossFk']});
+ const available = await Self.getAvailable(workerId);
+ const hasAcl = available.has(notificationFk);
- if (user != modifiedUser.id && user != modifiedUser.bossFk)
- throw new UserError('You dont have permission to modify this user');
-
- await models.NotificationSubscription.destroyById(notificationId);
- };
-
- async function getUserToModify(notificationId, userFk, models) {
- let userToModify = userFk;
- if (notificationId) {
- const subscription = await models.NotificationSubscription.findById(notificationId);
- userToModify = subscription.userFk;
- }
- return await models.Worker.findOne({
- fields: ['id', 'bossFk'],
- where: {
- id: userToModify
- }
- });
+ if (!hasAcl || (userId != worker.id && userId != worker.bossFk))
+ throw new UserError('The notification subscription of this worker cant be modified');
}
+
+ Self.getAvailable = async function(userId, options) {
+ const availableNotificationsMap = new Map();
+ const models = Self.app.models;
+
+ const myOptions = {};
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const roles = await models.RoleMapping.find({
+ fields: ['roleId'],
+ where: {principalId: userId}
+ }, myOptions);
+
+ const availableNotifications = await models.NotificationAcl.find({
+ fields: ['notificationFk', 'roleFk'],
+ include: {relation: 'notification'},
+ where: {
+ roleFk: {
+ inq: roles.map(role => role.roleId),
+ },
+ }
+ }, myOptions);
+
+ for (available of availableNotifications) {
+ availableNotificationsMap.set(available.notificationFk, {
+ id: null,
+ notificationFk: available.notificationFk,
+ name: available.notification().name,
+ description: available.notification().description,
+ active: false
+ });
+ }
+ return availableNotificationsMap;
+ };
};
diff --git a/back/models/payment.json b/back/models/payment.json
index 7eca36e4d..ed354969e 100644
--- a/back/models/payment.json
+++ b/back/models/payment.json
@@ -47,7 +47,7 @@
},
"bank": {
"type": "belongsTo",
- "model": "Bank",
+ "model": "Accounting",
"foreignKey": "bankFk"
},
"payMethod": {
diff --git a/back/models/postcode.js b/back/models/postcode.js
index b08fdaa40..63fd0657f 100644
--- a/back/models/postcode.js
+++ b/back/models/postcode.js
@@ -1,6 +1,7 @@
let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
+ require('../methods/postcode/filter.js')(Self);
Self.rewriteDbError(function(err) {
if (err.code === 'ER_DUP_ENTRY')
return new UserError(`This postcode already exists`);
diff --git a/back/models/specs/mailAliasAccount.spec.js b/back/models/specs/mailAliasAccount.spec.js
new file mode 100644
index 000000000..8f0278a50
--- /dev/null
+++ b/back/models/specs/mailAliasAccount.spec.js
@@ -0,0 +1,56 @@
+const models = require('vn-loopback/server/server').models;
+
+describe('loopback model MailAliasAccount', () => {
+ it('should add a mail Alias', async() => {
+ const tx = await models.MailAliasAccount.beginTransaction({});
+ let error;
+
+ try {
+ const options = {transaction: tx, accessToken: {userId: 9}};
+ await models.MailAliasAccount.create({mailAlias: 2, account: 5}, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error).toBeUndefined();
+ });
+
+ it('should add a mail Alias of an inherit role', async() => {
+ const tx = await models.MailAliasAccount.beginTransaction({});
+ let error;
+
+ try {
+ const options = {transaction: tx, accessToken: {userId: 9}};
+ await models.MailAliasAccount.create({mailAlias: 3, account: 5}, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error).toBeUndefined();
+ });
+
+ it('should delete a mail Alias', async() => {
+ const tx = await models.MailAliasAccount.beginTransaction({});
+ let error;
+
+ try {
+ const options = {transaction: tx, accessToken: {userId: 1}};
+ const mailAclId = 2;
+ await models.MailAliasAccount.destroyAll({id: mailAclId}, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error).toBeUndefined();
+ });
+});
+
diff --git a/back/models/specs/notificationSubscription.spec.js b/back/models/specs/notificationSubscription.spec.js
index c7f37abed..c2adcbc59 100644
--- a/back/models/specs/notificationSubscription.spec.js
+++ b/back/models/specs/notificationSubscription.spec.js
@@ -1,74 +1,126 @@
const models = require('vn-loopback/server/server').models;
describe('loopback model NotificationSubscription', () => {
- it('Should fail to delete a notification if the user is not editing itself or a subordinate', async() => {
+ it('should fail to add a notification subscription if the worker doesnt have ACLs', async() => {
const tx = await models.NotificationSubscription.beginTransaction({});
+ let error;
try {
- const options = {transaction: tx};
- const user = 9;
+ const options = {transaction: tx, accessToken: {userId: 9}};
+ await models.NotificationSubscription.create({notificationFk: 1, userFk: 62}, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error.message).toEqual('The notification subscription of this worker cant be modified');
+ });
+
+ it('should fail to add a notification subscription if the user isnt editing itself or subordinate', async() => {
+ const tx = await models.NotificationSubscription.beginTransaction({});
+ let error;
+
+ try {
+ const options = {transaction: tx, accessToken: {userId: 1}};
+ await models.NotificationSubscription.create({notificationFk: 1, userFk: 9}, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error.message).toEqual('The notification subscription of this worker cant be modified');
+ });
+
+ it('should fail to delete a notification subscription if the user isnt editing itself or subordinate', async() => {
+ const tx = await models.NotificationSubscription.beginTransaction({});
+ let error;
+
+ try {
+ const options = {transaction: tx, accessToken: {userId: 9}};
const notificationSubscriptionId = 2;
- const ctx = {req: {accessToken: {userId: user}}};
- const notification = await models.NotificationSubscription.findById(notificationSubscriptionId);
+ await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options);
- let error;
-
- try {
- await models.NotificationSubscription.deleteNotification(ctx, notification.id, options);
- } catch (e) {
- error = e;
- }
-
- expect(error.message).toContain('You dont have permission to modify this user');
await tx.rollback();
} catch (e) {
await tx.rollback();
- throw e;
+ error = e;
}
+
+ expect(error.message).toEqual('The notification subscription of this worker cant be modified');
});
- it('Should delete a notification if the user is editing itself', async() => {
+ it('should add a notification subscription if the user is editing itself', async() => {
const tx = await models.NotificationSubscription.beginTransaction({});
+ let error;
try {
- const options = {transaction: tx};
- const user = 9;
+ const options = {transaction: tx, accessToken: {userId: 9}};
+ await models.NotificationSubscription.create({notificationFk: 2, userFk: 9}, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error).toBeUndefined();
+ });
+
+ it('should delete a notification subscription if the user is editing itself', async() => {
+ const tx = await models.NotificationSubscription.beginTransaction({});
+ let error;
+
+ try {
+ const options = {transaction: tx, accessToken: {userId: 9}};
+ const notificationSubscriptionId = 6;
+ await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error).toBeUndefined();
+ });
+
+ it('should add a notification subscription if the user is editing a subordinate', async() => {
+ const tx = await models.NotificationSubscription.beginTransaction({});
+ let error;
+
+ try {
+ const options = {transaction: tx, accessToken: {userId: 9}};
+ await models.NotificationSubscription.create({notificationFk: 1, userFk: 5}, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error).toBeUndefined();
+ });
+
+ it('should delete a notification subscription if the user is editing a subordinate', async() => {
+ const tx = await models.NotificationSubscription.beginTransaction({});
+ let error;
+
+ try {
+ const options = {transaction: tx, accessToken: {userId: 19}};
const notificationSubscriptionId = 4;
- const ctx = {req: {accessToken: {userId: user}}};
- const notification = await models.NotificationSubscription.findById(notificationSubscriptionId);
+ await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options);
- await models.NotificationSubscription.deleteNotification(ctx, notification.id, options);
-
- const deletedNotification = await models.NotificationSubscription.findById(notificationSubscriptionId);
-
- expect(deletedNotification).toBeNull();
await tx.rollback();
} catch (e) {
await tx.rollback();
- throw e;
+ error = e;
}
- });
- it('Should delete a notification if the user is editing a subordinate', async() => {
- const tx = await models.NotificationSubscription.beginTransaction({});
-
- try {
- const options = {transaction: tx};
- const user = 9;
- const notificationSubscriptionId = 5;
- const ctx = {req: {accessToken: {userId: user}}};
- const notification = await models.NotificationSubscription.findById(notificationSubscriptionId);
-
- await models.NotificationSubscription.deleteNotification(ctx, notification.id, options);
-
- const deletedNotification = await models.NotificationSubscription.findById(notificationSubscriptionId);
-
- expect(deletedNotification).toBeNull();
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- throw e;
- }
+ expect(error).toBeUndefined();
});
});
diff --git a/back/models/specs/vn-user.spec.js b/back/models/specs/vn-user.spec.js
index 3700b919a..8689a7854 100644
--- a/back/models/specs/vn-user.spec.js
+++ b/back/models/specs/vn-user.spec.js
@@ -1,4 +1,5 @@
const models = require('vn-loopback/server/server').models;
+const ForbiddenError = require('vn-loopback/util/forbiddenError');
describe('loopback model VnUser', () => {
it('should return true if the user has the given role', async() => {
@@ -12,4 +13,42 @@ describe('loopback model VnUser', () => {
expect(result).toBeFalsy();
});
+
+ describe('userSecurity', () => {
+ const itManagementId = 115;
+ const hrId = 37;
+ const employeeId = 1;
+
+ it('should check if you are the same user', async() => {
+ const ctx = {options: {accessToken: {userId: employeeId}}};
+ await models.VnUser.userSecurity(ctx, employeeId);
+ });
+
+ it('should check for higher privileges', async() => {
+ const ctx = {options: {accessToken: {userId: itManagementId}}};
+ await models.VnUser.userSecurity(ctx, employeeId);
+ });
+
+ it('should check if you have medium privileges and the user email is not verified', async() => {
+ const ctx = {options: {accessToken: {userId: hrId}}};
+ await models.VnUser.userSecurity(ctx, employeeId);
+ });
+
+ it('should throw an error if you have medium privileges and the users email is verified', async() => {
+ const tx = await models.VnUser.beginTransaction({});
+ const ctx = {options: {accessToken: {userId: hrId}}};
+ try {
+ const options = {transaction: tx};
+ const userToUpdate = await models.VnUser.findById(1, null, options);
+ userToUpdate.updateAttribute('emailVerified', 1, options);
+
+ await models.VnUser.userSecurity(ctx, employeeId, options);
+ await tx.rollback();
+ } catch (error) {
+ await tx.rollback();
+
+ expect(error).toEqual(new ForbiddenError());
+ }
+ });
+ });
});
diff --git a/back/models/url.js b/back/models/url.js
new file mode 100644
index 000000000..b603e9eb5
--- /dev/null
+++ b/back/models/url.js
@@ -0,0 +1,4 @@
+module.exports = Self => {
+ require('../methods/url/getByUser')(Self);
+ require('../methods/url/getUrl')(Self);
+};
diff --git a/back/models/user-config.json b/back/models/user-config.json
index 52125dc01..5c5df1b9e 100644
--- a/back/models/user-config.json
+++ b/back/models/user-config.json
@@ -26,6 +26,9 @@
},
"darkMode": {
"type": "boolean"
+ },
+ "tabletFk": {
+ "type": "string"
}
},
"relations": {
@@ -43,6 +46,11 @@
"type": "belongsTo",
"model": "VnUser",
"foreignKey": "userFk"
- }
+ },
+ "Tablet": {
+ "type": "belongsTo",
+ "model": "docuwareTablet",
+ "foreignKey": "tabletFk"
+ }
}
}
diff --git a/back/models/viaexpress-config.js b/back/models/viaexpress-config.js
index d0335b28b..d00c99e82 100644
--- a/back/models/viaexpress-config.js
+++ b/back/models/viaexpress-config.js
@@ -1,4 +1,6 @@
module.exports = Self => {
require('../methods/viaexpress-config/internationalExpedition')(Self);
require('../methods/viaexpress-config/renderer')(Self);
+ require('../methods/viaexpress-config/deleteExpedition')(Self);
+ require('../methods/viaexpress-config/deleteExpeditionRenderer')(Self);
};
diff --git a/back/models/viaexpress-config.json b/back/models/viaexpress-config.json
index 8df24201b..acab1f7e6 100644
--- a/back/models/viaexpress-config.json
+++ b/back/models/viaexpress-config.json
@@ -29,6 +29,9 @@
},
"deliveryType": {
"type": "string"
+ },
+ "agencyModeFk": {
+ "type": "number"
}
}
}
diff --git a/back/models/vn-role.json b/back/models/vn-role.json
new file mode 100644
index 000000000..c7d7e172b
--- /dev/null
+++ b/back/models/vn-role.json
@@ -0,0 +1,13 @@
+{
+ "name": "VnRole",
+ "base": "Role",
+ "validateUpsert": true,
+ "options": {
+ "mysql": {
+ "table": "account.role"
+ }
+ },
+ "mixins": {
+ "Loggable": true
+ }
+}
diff --git a/back/models/vn-user.js b/back/models/vn-user.js
index cf210b61b..b59f13ffa 100644
--- a/back/models/vn-user.js
+++ b/back/models/vn-user.js
@@ -1,6 +1,8 @@
const vnModel = require('vn-loopback/common/models/vn-model');
-const LoopBackContext = require('loopback-context');
const {Email} = require('vn-print');
+const ForbiddenError = require('vn-loopback/util/forbiddenError');
+const LoopBackContext = require('loopback-context');
+const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
vnModel(Self);
@@ -8,10 +10,11 @@ module.exports = function(Self) {
require('../methods/vn-user/sign-in')(Self);
require('../methods/vn-user/acl')(Self);
require('../methods/vn-user/recover-password')(Self);
- require('../methods/vn-user/validate-token')(Self);
require('../methods/vn-user/privileges')(Self);
require('../methods/vn-user/validate-auth')(Self);
require('../methods/vn-user/renew-token')(Self);
+ require('../methods/vn-user/share-token')(Self);
+ require('../methods/vn-user/update-user')(Self);
Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create');
@@ -77,10 +80,10 @@ module.exports = function(Self) {
Self.getRoles = async(userId, options) => {
const result = await Self.rawSql(
`SELECT r.name
- FROM account.user u
- JOIN account.roleRole rr ON rr.role = u.role
- JOIN account.role r ON r.id = rr.inheritsFrom
- WHERE u.id = ?`, [userId], options);
+ FROM account.user u
+ JOIN account.roleRole rr ON rr.role = u.role
+ JOIN account.role r ON r.id = rr.inheritsFrom
+ WHERE u.id = ?`, [userId], options);
const roles = [];
for (const role of result)
@@ -122,11 +125,43 @@ module.exports = function(Self) {
return email.send();
});
- Self.validateLogin = async function(user, password) {
- let loginInfo = Object.assign({password}, Self.userUses(user));
- token = await Self.login(loginInfo, 'user');
+ /**
+ * Sign-in validate
+ * @param {String} user The user
+ * @param {Object} userToken Options
+ * @param {Object} token accessToken
+ * @param {Object} ctx context
+ */
+ Self.signInValidate = async(user, userToken, token, ctx) => {
+ const [[key, value]] = Object.entries(Self.userUses(user));
+ const isOwner = Self.rawSql(`SELECT ? = ? `, [userToken[key], value]);
+ if (!isOwner) {
+ await Self.app.models.SignInLog.create({
+ userName: user,
+ token: token.id,
+ userFk: userToken.id,
+ ip: ctx.req.ip,
+ owner: isOwner
+ });
+ throw new UserError('Try again');
+ }
+ };
+
+ /**
+ * Validate login params
+ * @param {String} user The user
+ * @param {String} password
+ * @param {Object} ctx context
+ */
+ Self.validateLogin = async function(user, password, ctx) {
+ const loginInfo = Object.assign({password}, Self.userUses(user));
+ const token = await Self.login(loginInfo, 'user');
const userToken = await token.user.get();
+
+ if (ctx)
+ await Self.signInValidate(user, userToken, token, ctx);
+
try {
await Self.app.models.Account.sync(userToken.name, password);
} catch (err) {
@@ -175,48 +210,85 @@ module.exports = function(Self) {
};
Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls =
- Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls
- .filter(acl => acl.property != 'changePassword');
+ Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls
+ .filter(acl => acl.property != 'changePassword');
- // FIXME: https://redmine.verdnatura.es/issues/5761
- // Self.afterRemote('prototype.patchAttributes', async(ctx, instance) => {
- // if (!ctx.args || !ctx.args.data.email) return;
+ Self.userSecurity = async(ctx, userId, options) => {
+ const models = Self.app.models;
+ const accessToken = ctx?.options?.accessToken || LoopBackContext.getCurrentContext().active.accessToken;
+ const ctxToken = {req: {accessToken}};
- // const loopBackContext = LoopBackContext.getCurrentContext();
- // const httpCtx = {req: loopBackContext.active};
- // const httpRequest = httpCtx.req.http.req;
- // const headers = httpRequest.headers;
- // const origin = headers.origin;
- // const url = origin.split(':');
+ if (userId === accessToken.userId) return;
- // class Mailer {
- // async send(verifyOptions, cb) {
- // const params = {
- // url: verifyOptions.verifyHref,
- // recipient: verifyOptions.to,
- // lang: ctx.req.getLocale()
- // };
+ const myOptions = {};
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
- // const email = new Email('email-verify', params);
- // email.send();
+ const hasHigherPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'higherPrivileges', myOptions);
+ if (hasHigherPrivileges) return;
- // cb(null, verifyOptions.to);
- // }
- // }
+ const hasMediumPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'mediumPrivileges', myOptions);
+ const user = await models.VnUser.findById(userId, {fields: ['id', 'emailVerified']}, myOptions);
+ if (!user.emailVerified && hasMediumPrivileges) return;
- // const options = {
- // type: 'email',
- // to: instance.email,
- // from: {},
- // redirect: `${origin}/#!/account/${instance.id}/basic-data?emailConfirmed`,
- // template: false,
- // mailer: new Mailer,
- // host: url[1].split('/')[2],
- // port: url[2],
- // protocol: url[0],
- // user: Self
- // };
+ throw new ForbiddenError();
+ };
- // await instance.verify(options);
- // });
+ Self.observe('after save', async ctx => {
+ const instance = ctx?.instance;
+ const newEmail = instance?.email;
+ const oldEmail = ctx?.hookState?.oldInstance?.email;
+ if (!ctx.isNewInstance && (!newEmail || !oldEmail || newEmail == oldEmail)) return;
+
+ const loopBackContext = LoopBackContext.getCurrentContext();
+ const httpCtx = {req: loopBackContext.active};
+ const httpRequest = httpCtx.req.http.req;
+ const headers = httpRequest.headers;
+ const origin = headers.origin;
+ const url = origin.split(':');
+
+ const env = process.env.NODE_ENV;
+ const liliumUrl = await Self.app.models.Url.findOne({
+ where: {
+ and: [
+ {appName: 'lilium'},
+ {environment: env}
+ ]
+ }
+ });
+
+ class Mailer {
+ async send(verifyOptions, cb) {
+ try {
+ const url = new URL(verifyOptions.verifyHref);
+ if (process.env.NODE_ENV) url.port = '';
+
+ const email = new Email('email-verify', {
+ url: url.href,
+ recipient: verifyOptions.to
+ });
+ await email.send();
+
+ cb(null, verifyOptions.to);
+ } catch (err) {
+ cb(err);
+ }
+ }
+ }
+
+ const options = {
+ type: 'email',
+ to: newEmail,
+ from: {},
+ redirect: `${liliumUrl.url}verifyEmail?userId=${instance.id}`,
+ template: false,
+ mailer: new Mailer,
+ host: url[1].split('/')[2],
+ port: url[2],
+ protocol: url[0],
+ user: Self
+ };
+
+ await instance.verify(options, ctx.options);
+ });
};
diff --git a/back/models/vn-user.json b/back/models/vn-user.json
index 9e3f8df89..5f6ac3f47 100644
--- a/back/models/vn-user.json
+++ b/back/models/vn-user.json
@@ -1,104 +1,103 @@
{
- "name": "VnUser",
- "base": "User",
- "validateUpsert": true,
- "options": {
- "mysql": {
- "table": "account.user"
- }
- },
+ "name": "VnUser",
+ "base": "User",
+ "validateUpsert": true,
+ "options": {
+ "mysql": {
+ "table": "account.user"
+ }
+ },
+ "mixins": {
+ "Loggable": true
+ },
"resetPasswordTokenTTL": "604800",
- "properties": {
- "id": {
- "type": "number",
- "id": true
- },
- "name": {
- "type": "string",
- "required": true
- },
- "username": {
- "type": "string",
- "mysql": {
- "columnName": "name"
- }
- },
- "password": {
- "type": "string",
- "required": true
- },
- "roleFk": {
- "type": "number",
- "mysql": {
- "columnName": "role"
- }
- },
- "nickname": {
- "type": "string"
- },
- "lang": {
- "type": "string"
- },
- "active": {
- "type": "boolean"
- },
- "email": {
- "type": "string"
- },
- "created": {
- "type": "date"
- },
- "updated": {
- "type": "date"
- },
- "image": {
- "type": "string"
- },
- "hasGrant": {
- "type": "boolean"
- },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true
+ },
+ "name": {
+ "type": "string",
+ "required": true
+ },
+ "username": {
+ "type": "string"
+ },
+ "roleFk": {
+ "type": "number",
+ "mysql": {
+ "columnName": "role"
+ }
+ },
+ "nickname": {
+ "type": "string"
+ },
+ "lang": {
+ "type": "string"
+ },
+ "active": {
+ "type": "boolean"
+ },
+ "email": {
+ "type": "string"
+ },
+ "emailVerified": {
+ "type": "boolean"
+ },
+ "created": {
+ "type": "date"
+ },
+ "updated": {
+ "type": "date"
+ },
+ "image": {
+ "type": "string"
+ },
+ "hasGrant": {
+ "type": "boolean"
+ },
"passExpired": {
"type": "date"
},
- "twoFactor": {
- "type": "string"
- }
- },
- "relations": {
- "role": {
- "type": "belongsTo",
- "model": "Role",
- "foreignKey": "roleFk"
- },
- "roles": {
- "type": "hasMany",
- "model": "RoleRole",
- "foreignKey": "role",
- "primaryKey": "roleFk"
- },
- "emailUser": {
- "type": "hasOne",
- "model": "EmailUser",
- "foreignKey": "userFk"
- },
- "worker": {
- "type": "hasOne",
- "model": "Worker",
- "foreignKey": "id"
- },
- "userConfig": {
- "type": "hasOne",
- "model": "UserConfig",
- "foreignKey": "userFk"
- }
- },
- "acls": [
- {
- "property": "signIn",
- "accessType": "EXECUTE",
- "principalType": "ROLE",
- "principalId": "$everyone",
- "permission": "ALLOW"
+ "twoFactor": {
+ "type": "string"
+ }
+ },
+ "relations": {
+ "role": {
+ "type": "belongsTo",
+ "model": "VnRole",
+ "foreignKey": "roleFk"
+ },
+ "roles": {
+ "type": "hasMany",
+ "model": "RoleRole",
+ "foreignKey": "role",
+ "primaryKey": "roleFk"
+ },
+ "emailUser": {
+ "type": "hasOne",
+ "model": "EmailUser",
+ "foreignKey": "userFk"
+ },
+ "worker": {
+ "type": "hasOne",
+ "model": "Worker",
+ "foreignKey": "id"
+ },
+ "userConfig": {
+ "type": "hasOne",
+ "model": "UserConfig",
+ "foreignKey": "userFk"
+ }
+ },
+ "acls": [
+ {
+ "property": "signIn",
+ "accessType": "EXECUTE",
+ "principalType": "ROLE",
+ "principalId": "$everyone",
+ "permission": "ALLOW"
},
{
"property": "recoverPassword",
@@ -107,28 +106,35 @@
"principalId": "$everyone",
"permission": "ALLOW"
},
- {
- "property": "validateToken",
- "accessType": "EXECUTE",
- "principalType": "ROLE",
- "principalId": "$authenticated",
- "permission": "ALLOW"
- },
- {
+ {
"property": "validateAuth",
- "accessType": "EXECUTE",
- "principalType": "ROLE",
- "principalId": "$everyone",
- "permission": "ALLOW"
- },
- {
- "property": "privileges",
- "accessType": "*",
- "principalType": "ROLE",
- "principalId": "$authenticated",
- "permission": "ALLOW"
- }
- ],
+ "accessType": "EXECUTE",
+ "principalType": "ROLE",
+ "principalId": "$everyone",
+ "permission": "ALLOW"
+ },
+ {
+ "property": "privileges",
+ "accessType": "*",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ },
+ {
+ "property": "renewToken",
+ "accessType": "WRITE",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ },
+ {
+ "property": "shareToken",
+ "accessType": "WRITE",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ }
+ ],
"scopes": {
"preview": {
"fields": [
@@ -144,7 +150,8 @@
"image",
"hasGrant",
"realm",
- "email"
+ "email",
+ "emailVerified"
]
}
}
diff --git a/back/models/workerActivity.json b/back/models/workerActivity.json
new file mode 100644
index 000000000..e3b994f77
--- /dev/null
+++ b/back/models/workerActivity.json
@@ -0,0 +1,39 @@
+{
+ "name": "WorkerActivity",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "workerActivity"
+ }
+ },
+ "properties": {
+ "id": {
+ "id": true,
+ "type": "number"
+ },
+ "created": {
+ "type": "date"
+ },
+ "model": {
+ "type": "string"
+ },
+ "event": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "relations": {
+ "workerFk": {
+ "type": "belongsTo",
+ "model": "Worker",
+ "foreignKey": "workerFk"
+ },
+ "workerActivityTypeFk": {
+ "type": "belongsTo",
+ "model": "WorkerActivityType",
+ "foreignKey": "workerActivityTypeFk"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/back/models/workerActivityType.json b/back/models/workerActivityType.json
new file mode 100644
index 000000000..f010363a7
--- /dev/null
+++ b/back/models/workerActivityType.json
@@ -0,0 +1,19 @@
+{
+ "name": "WorkerActivityType",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "workerActivityType"
+ }
+ },
+ "properties": {
+ "code": {
+ "id": true,
+ "type": "string"
+ },
+ "description": {
+ "type": "string",
+ "required": false
+ }
+ }
+}
\ No newline at end of file
diff --git a/back/tests-helper.js b/back/tests-helper.js
new file mode 100644
index 000000000..b88fa1fd6
--- /dev/null
+++ b/back/tests-helper.js
@@ -0,0 +1,34 @@
+/* eslint-disable no-console */
+const app = require('vn-loopback/server/server');
+let dataSources = require('../loopback/server/datasources.json');
+
+async function init() {
+ console.log('Initializing backend.');
+
+ dataSources = JSON.parse(JSON.stringify(dataSources));
+ Object.assign(dataSources.vn, {
+ host: process.env.DB_HOST,
+ port: process.env.DB_PORT
+ });
+
+ const bootOptions = {dataSources};
+ await new Promise((resolve, reject) => {
+ app.boot(bootOptions,
+ err => err ? reject(err) : resolve());
+ });
+ // FIXME: Workaround to wait for loopback to be ready
+ await app.models.Application.status();
+}
+
+async function deinit() {
+ console.log('Stopping backend.');
+ await app.disconnect();
+}
+
+module.exports = {
+ init,
+ deinit
+};
+
+if (require.main === module)
+ init();
diff --git a/back/tests.js b/back/tests.js
index 97e548d33..50698eb92 100644
--- a/back/tests.js
+++ b/back/tests.js
@@ -1,80 +1,123 @@
-const Docker = require('../db/docker.js');
-let dataSources = require('../loopback/server/datasources.json');
+/* eslint-disable no-console */
+const path = require('path');
+const getopts = require('getopts');
+const Myt = require('@verdnatura/myt/myt');
+const Run = require('@verdnatura/myt/myt-run');
+const helper = require('./tests-helper');
-process.on('warning', warning => {
- console.log(warning.name);
- console.log(warning.message);
- console.log(warning.stack);
+const opts = getopts(process.argv.slice(2), {
+ string: [
+ 'network'
+ ],
+ boolean: [
+ 'ci',
+ 'junit'
+ ]
});
-process.on('exit', async function() {
- if (container) await container.rm();
-});
+let server;
+const PARALLEL = false;
+const SETUP_TIMEOUT = 15 * 60 * 1000;
+const SPEC_TIMEOUT = 30 * 1000;
+
+process.on('exit', teardown);
+process.on('uncaughtException', onError);
+process.on('unhandledRejection', onError);
+
+const exitSignals = [
+ 'SIGINT',
+ 'SIGUSR1',
+ 'SIGUSR2'
+];
+for (const signal of exitSignals)
+ process.on(signal, () => process.exit());
+
+async function setup() {
+ console.log('Building and running DB container.');
+
+ const myt = new Myt();
+ await myt.init({
+ workspace: path.join(__dirname, '..'),
+ random: true,
+ ci: opts.ci,
+ tmpfs: process.platform == 'linux',
+ network: opts.network || null
+ });
+ server = await myt.run(Run);
+ await myt.deinit();
+
+ const {dbConfig} = server;
+ process.env.DB_HOST = dbConfig.host;
+ process.env.DB_PORT = dbConfig.port;
+
+ if (!PARALLEL)
+ await helper.init();
+}
+
+async function teardown() {
+ if (!server) return;
+ const oldServer = server;
+ server = null;
+
+ if (!PARALLEL)
+ await helper.deinit();
+
+ console.log('Stopping and removing DB container.');
+ await oldServer.rm();
+}
+
+async function onError(err) {
+ console.error(err);
+ process.exit(1);
+}
-let container;
async function test() {
- let isCI = false;
+ let runner;
+ const config = {
+ globalSetup: setup,
+ globalSetupTimeout: SETUP_TIMEOUT,
+ globalTeardown: teardown,
+ globalTeardownTimeout: SETUP_TIMEOUT,
+ spec_dir: '.',
+ spec_files: [
+ 'back/**/*[sS]pec.js',
+ 'loopback/**/*[sS]pec.js',
+ 'modules/*/back/**/*.[sS]pec.js'
+ ],
+ helpers: []
+ };
- if (process.argv[2] === 'ci')
- isCI = true;
+ if (PARALLEL) {
+ const ParallelRunner = require('jasmine/parallel');
+ runner = new ParallelRunner({numWorkers: 1});
+ config.helpers.push(`back/tests-helper.js`);
+ } else {
+ const Jasmine = require('jasmine');
+ runner = new Jasmine();
- container = new Docker();
-
- await container.run(isCI);
- dataSources = JSON.parse(JSON.stringify(dataSources));
-
- Object.assign(dataSources.vn, {
- host: container.dbConf.host,
- port: container.dbConf.port
- });
-
- const bootOptions = {dataSources};
- const app = require('vn-loopback/server/server');
- await new Promise((resolve, reject) => {
- app.boot(bootOptions,
- err => err ? reject(err) : resolve());
- });
- // FIXME: Workaround to wait for loopback to be ready
- await app.models.Application.status();
-
- const Jasmine = require('jasmine');
- const jasmine = new Jasmine();
-
- const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
- jasmine.addReporter(new SpecReporter({
- spec: {
- displaySuccessful: isCI,
- displayPending: isCI
- },
- summary: {
- displayPending: false,
- }
- }));
-
- if (isCI) {
- const JunitReporter = require('jasmine-reporters');
- jasmine.addReporter(new JunitReporter.JUnitXmlReporter());
-
- jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 90000;
- jasmine.exitOnCompletion = true;
+ const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
+ runner.addReporter(new SpecReporter({
+ spec: {
+ displaySuccessful: opts.ci,
+ displayPending: opts.ci
+ },
+ summary: {
+ displayPending: false,
+ }
+ }));
}
- const backSpecs = [
- './back/**/*[sS]pec.js',
- './loopback/**/*[sS]pec.js',
- './modules/*/back/**/*.[sS]pec.js'
- ];
+ if (opts.junit) {
+ const JunitReporter = require('jasmine-reporters');
+ runner.addReporter(new JunitReporter.JUnitXmlReporter());
+ }
+ if (opts.ci)
+ runner.jasmine.DEFAULT_TIMEOUT_INTERVAL = SPEC_TIMEOUT;
- jasmine.loadConfig({
- spec_dir: '.',
- spec_files: backSpecs,
- helpers: [],
- });
-
- await jasmine.execute();
- if (app) await app.disconnect();
- if (container) await container.rm();
- console.log('App disconnected & container removed');
+ // runner.loadConfigFile('back/jasmine.json');
+ runner.loadConfig(config);
+ process.env.SPEC_IS_RUNNING = true;
+ await runner.execute();
}
test();
diff --git a/db/.archive/224701/00-ACL.sql b/db/.archive/224701/00-ACL.sql
deleted file mode 100644
index 2cce197b2..000000000
--- a/db/.archive/224701/00-ACL.sql
+++ /dev/null
@@ -1,49 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('ClientConsumptionQueue', '*', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'deliveryNotePdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'deliveryNoteEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'deliveryNoteCsvPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'deliveryNoteCsvEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'campaignMetricsPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'campaignMetricsEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientWelcomeHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientWelcomeEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'creditRequestPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'creditRequestHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'creditRequestEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'printerSetupHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'printerSetupEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'sepaCoreEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorStHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorStEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorNdHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorNdEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientDebtStatementPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientDebtStatementHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientDebtStatementEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'incotermsAuthorizationPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'incotermsAuthorizationHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'incotermsAuthorizationEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'consumptionSendQueued', 'WRITE', 'ALLOW', 'ROLE', 'system'),
- ('InvoiceOut', 'invoiceEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('InvoiceOut', 'exportationPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('InvoiceOut', 'sendQueued', 'WRITE', 'ALLOW', 'ROLE', 'system'),
- ('Ticket', 'invoiceCsvPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'invoiceCsvEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Supplier', 'campaignMetricsPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Supplier', 'campaignMetricsEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Travel', 'extraCommunityPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Travel', 'extraCommunityEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Entry', 'entryOrderPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('OsTicket', 'osTicketReportEmail', 'WRITE', 'ALLOW', 'ROLE', 'system'),
- ('Item', 'buyerWasteEmail', 'WRITE', 'ALLOW', 'ROLE', 'system'),
- ('Claim', 'claimPickupPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Claim', 'claimPickupEmail', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'),
- ('Item', 'labelPdf', 'READ', 'ALLOW', 'ROLE', 'employee');
-
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Sector','*','READ','ALLOW','ROLE','employee');
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Sector','*','WRITE','ALLOW','ROLE','employee');
diff --git a/db/.archive/224701/00-clientConsumptionQueue.sql b/db/.archive/224701/00-clientConsumptionQueue.sql
deleted file mode 100644
index 2734d32cc..000000000
--- a/db/.archive/224701/00-clientConsumptionQueue.sql
+++ /dev/null
@@ -1,9 +0,0 @@
-create table `vn`.`clientConsumptionQueue`
-(
- id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
- params json not null,
- queued datetime default current_timestamp() not null,
- printed datetime null,
- status varchar(50) default '' null
-)
- comment 'Queue for client consumption PDF mailing';
diff --git a/db/.archive/224701/00-invoiceOutQueue.sql b/db/.archive/224701/00-invoiceOutQueue.sql
deleted file mode 100644
index 52ed4a113..000000000
--- a/db/.archive/224701/00-invoiceOutQueue.sql
+++ /dev/null
@@ -1 +0,0 @@
-rename table `vn`.`invoiceOut_queue` to `vn`.`invoiceOutQueue`;
diff --git a/db/.archive/224701/00-itemConfig.sql b/db/.archive/224701/00-itemConfig.sql
deleted file mode 100644
index b148aa094..000000000
--- a/db/.archive/224701/00-itemConfig.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-ALTER TABLE `vn`.`itemConfig`
- ADD id int null PRIMARY KEY first;
-
-ALTER TABLE `vn`.`itemConfig`
- ADD wasteRecipients VARCHAR(50) NOT NULL comment 'Weekly waste report schedule recipients';
diff --git a/db/.archive/224701/00-printConfig.sql b/db/.archive/224701/00-printConfig.sql
deleted file mode 100644
index c5af09ac9..000000000
--- a/db/.archive/224701/00-printConfig.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-create table `salix`.`printConfig`
-(
- id int auto_increment,
- itRecipient varchar(50) null comment 'IT recipients for report mailing',
- incidencesEmail varchar(50) null comment 'CAU destinatary email',
- constraint printConfig_pk
- primary key (id)
-)
- comment 'Print service config';
-
diff --git a/db/.archive/224701/00-sample.sql b/db/.archive/224701/00-sample.sql
deleted file mode 100644
index f84cd723e..000000000
--- a/db/.archive/224701/00-sample.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-alter table `vn`.`sample`
- add model VARCHAR(25) null comment 'Model name in plural';
-
-UPDATE vn.sample t
- SET t.model = 'Clients'
- WHERE t.id IN(12, 13, 14, 15, 16, 18, 19, 20);
\ No newline at end of file
diff --git a/db/.archive/224701/00-user_hasGrant.sql b/db/.archive/224701/00-user_hasGrant.sql
deleted file mode 100644
index 60d1273d8..000000000
--- a/db/.archive/224701/00-user_hasGrant.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `account`.`user` ADD hasGrant TINYINT(1) NOT NULL;
diff --git a/db/.archive/224702/00-ACL_workerDisableExcluded.sql b/db/.archive/224702/00-ACL_workerDisableExcluded.sql
deleted file mode 100644
index 2fd9e8b12..000000000
--- a/db/.archive/224702/00-ACL_workerDisableExcluded.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalId)
- VALUES ('WorkerDisableExcluded','*','*','ALLOW','hr');
\ No newline at end of file
diff --git a/db/.archive/224702/00-aclBusiness.sql b/db/.archive/224702/00-aclBusiness.sql
deleted file mode 100644
index 8ea2c6d83..000000000
--- a/db/.archive/224702/00-aclBusiness.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Business', '*', '*', 'ALLOW', 'ROLE', 'hr');
\ No newline at end of file
diff --git a/db/.archive/224702/00-aclUsesMana.sql b/db/.archive/224702/00-aclUsesMana.sql
deleted file mode 100644
index 5bb7178dd..000000000
--- a/db/.archive/224702/00-aclUsesMana.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Sale', 'usesMana', '*', 'ALLOW', 'ROLE', 'employee');
\ No newline at end of file
diff --git a/db/.archive/224702/00-defaultPayDem_sameAs_production.sql b/db/.archive/224702/00-defaultPayDem_sameAs_production.sql
deleted file mode 100644
index 294247338..000000000
--- a/db/.archive/224702/00-defaultPayDem_sameAs_production.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `vn`.`payDem` (id,payDem)
- VALUES (7,'0');
diff --git a/db/.archive/224702/00-invoiceInPdf.sql b/db/.archive/224702/00-invoiceInPdf.sql
deleted file mode 100644
index bce256c05..000000000
--- a/db/.archive/224702/00-invoiceInPdf.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('InvoiceIn', 'invoiceInPdf', 'READ', 'ALLOW', 'ROLE', 'administrative'),
- ('InvoiceIn', 'invoiceInEmail', 'WRITE', 'ALLOW', 'ROLE', 'administrative');
diff --git a/db/.archive/224702/00-newSupplier_ACL.sql b/db/.archive/224702/00-newSupplier_ACL.sql
deleted file mode 100644
index c88f3de3f..000000000
--- a/db/.archive/224702/00-newSupplier_ACL.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `salix`.`ACL` (model,property,accessType,principalId)
- VALUES ('Supplier','newSupplier','WRITE','administrative');
diff --git a/db/.archive/224702/00-notificationTables.sql b/db/.archive/224702/00-notificationTables.sql
deleted file mode 100644
index 2db7d9874..000000000
--- a/db/.archive/224702/00-notificationTables.sql
+++ /dev/null
@@ -1,63 +0,0 @@
-USE util;
-
-CREATE TABLE notification(
- id INT PRIMARY KEY,
- `name` VARCHAR(255) UNIQUE,
- `description` VARCHAR(255)
-);
-
-CREATE TABLE notificationAcl(
- notificationFk INT,
- roleFk INT(10) unsigned,
- PRIMARY KEY(notificationFk, roleFk)
-);
-
-ALTER TABLE `util`.`notificationAcl` ADD CONSTRAINT `notificationAcl_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `util`.`notification` (`id`)
- ON DELETE CASCADE
- ON UPDATE CASCADE;
-
-ALTER TABLE `util`.`notificationAcl` ADD CONSTRAINT `notificationAcl_ibfk_2` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role`(`id`)
- ON DELETE RESTRICT
- ON UPDATE CASCADE;
-
-CREATE TABLE notificationSubscription(
- notificationFk INT,
- userFk INT(10) unsigned,
- PRIMARY KEY(notificationFk, userFk)
-);
-
-ALTER TABLE `util`.`notificationSubscription` ADD CONSTRAINT `notificationSubscription_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `util`.`notification` (`id`)
- ON DELETE CASCADE
- ON UPDATE CASCADE;
-
-ALTER TABLE `util`.`notificationSubscription` ADD CONSTRAINT `notificationSubscription_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user`(`id`)
- ON DELETE CASCADE
- ON UPDATE CASCADE;
-
-CREATE TABLE notificationQueue(
- id INT PRIMARY KEY AUTO_INCREMENT,
- notificationFk VARCHAR(255),
- params JSON,
- authorFk INT(10) unsigned NULL,
- `status` ENUM('pending', 'sent', 'error') NOT NULL DEFAULT 'pending',
- created DATETIME DEFAULT CURRENT_TIMESTAMP,
- INDEX(notificationFk),
- INDEX(authorFk),
- INDEX(status)
-);
-
-ALTER TABLE `util`.`notificationQueue` ADD CONSTRAINT `nnotificationQueue_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `util`.`notification` (`name`)
- ON DELETE CASCADE
- ON UPDATE CASCADE;
-
-ALTER TABLE `util`.`notificationQueue` ADD CONSTRAINT `notificationQueue_ibfk_2` FOREIGN KEY (`authorFk`) REFERENCES `account`.`user`(`id`)
- ON DELETE CASCADE
- ON UPDATE CASCADE;
-
-CREATE TABLE notificationConfig(
- id INT PRIMARY KEY AUTO_INCREMENT,
- cleanDays MEDIUMINT
-);
-
-INSERT INTO notificationConfig
- SET cleanDays = 90;
diff --git a/db/.archive/224702/00-payMethodFk_Allow_Null.sql b/db/.archive/224702/00-payMethodFk_Allow_Null.sql
deleted file mode 100644
index 6d9931d3c..000000000
--- a/db/.archive/224702/00-payMethodFk_Allow_Null.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`supplier` MODIFY COLUMN payMethodFk tinyint(3) unsigned NULL;
\ No newline at end of file
diff --git a/db/.archive/224702/00-supplierActivityFk_Allow_Null.sql b/db/.archive/224702/00-supplierActivityFk_Allow_Null.sql
deleted file mode 100644
index 62aac0556..000000000
--- a/db/.archive/224702/00-supplierActivityFk_Allow_Null.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`supplier` MODIFY COLUMN supplierActivityFk varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL NULL;
\ No newline at end of file
diff --git a/db/.archive/224702/00-ticket_closeByTicket.sql b/db/.archive/224702/00-ticket_closeByTicket.sql
deleted file mode 100644
index f378b1146..000000000
--- a/db/.archive/224702/00-ticket_closeByTicket.sql
+++ /dev/null
@@ -1,35 +0,0 @@
-drop procedure `vn`.`ticket_closeByTicket`;
-
-DELIMITER $$
-$$
-create
- definer = `root`@`localhost` procedure `vn`.`ticket_closeByTicket`(IN vTicketFk int)
-BEGIN
-
-/**
- * Inserta el ticket en la tabla temporal
- * para ser cerrado.
- *
- * @param vTicketFk Id del ticket
- */
-
- DROP TEMPORARY TABLE IF EXISTS tmp.ticket_close;
- CREATE TEMPORARY TABLE tmp.ticket_close ENGINE = MEMORY (
- SELECT
- t.id AS ticketFk
- FROM ticket t
- JOIN agencyMode am ON am.id = t.agencyModeFk
- LEFT JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN alertLevel al ON al.id = ts.alertLevel
- WHERE al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered')
- AND t.id = vTicketFk
- AND t.refFk IS NULL
- GROUP BY t.id);
-
- CALL ticket_close();
-
- DROP TEMPORARY TABLE tmp.ticket_close;
-END$$
-DELIMITER ;
-
-
diff --git a/db/.archive/224801/00-ACL.sql b/db/.archive/224801/00-ACL.sql
deleted file mode 100644
index 0b726538c..000000000
--- a/db/.archive/224801/00-ACL.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
-VALUES
- ('ClaimRma', '*', 'READ', 'ALLOW', 'ROLE', 'claimManager'),
- ('ClaimRma', '*', 'WRITE', 'ALLOW', 'ROLE', 'claimManager');
-
diff --git a/db/.archive/224801/00-claim.sql b/db/.archive/224801/00-claim.sql
deleted file mode 100644
index 0b9879878..000000000
--- a/db/.archive/224801/00-claim.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`claim` ADD rma varchar(100) NULL ;
\ No newline at end of file
diff --git a/db/.archive/224801/00-claimRma.sql b/db/.archive/224801/00-claimRma.sql
deleted file mode 100644
index 91e1ebaba..000000000
--- a/db/.archive/224801/00-claimRma.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-CREATE TABLE `vn`.`claimRma` (
- id INT UNSIGNED auto_increment NOT NULL PRIMARY KEY,
- code varchar(100) NOT NULL,
- created timestamp DEFAULT current_timestamp() NOT NULL,
- workerFk INTEGER UNSIGNED NOT NULL
-)
-ENGINE=InnoDB;
diff --git a/db/.archive/224901/00-aclNotification.sql b/db/.archive/224901/00-aclNotification.sql
deleted file mode 100644
index 51d6b2471..000000000
--- a/db/.archive/224901/00-aclNotification.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Notification', '*', 'WRITE', 'ALLOW', 'ROLE', 'developer');
diff --git a/db/.archive/224901/00-packingSiteConfig.sql b/db/.archive/224901/00-packingSiteConfig.sql
deleted file mode 100644
index 945b5a54c..000000000
--- a/db/.archive/224901/00-packingSiteConfig.sql
+++ /dev/null
@@ -1,12 +0,0 @@
-CREATE TABLE `vn`.`packingSiteConfig` (
- `id` INT(11) NOT NULL AUTO_INCREMENT,
- `shinobiUrl` varchar(255) NOT NULL,
- `shinobiToken` varchar(255) NOT NULL,
- `shinobiGroupKey` varchar(255) NOT NULL,
- `avgBoxingTime` INT(3) NULL,
- PRIMARY KEY (`id`)
- );
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Boxing', '*', '*', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/.archive/224901/00-packingSiteUpdate.sql b/db/.archive/224901/00-packingSiteUpdate.sql
deleted file mode 100644
index 14313fd52..000000000
--- a/db/.archive/224901/00-packingSiteUpdate.sql
+++ /dev/null
@@ -1,56 +0,0 @@
-ALTER TABLE `vn`.`packingSite` ADD monitorId varchar(255) NULL;
-
-UPDATE `vn`.`packingSite`
- SET monitorId = 'VbiUcajdaT'
- WHERE code = 'h1';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'qKMPn9aaVe'
- WHERE code = 'h2';
-UPDATE `vn`.`packingSite`
- SET monitorId = '3CtdIAGPAv'
- WHERE code = 'h3';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'Xme2hiqz1f'
- WHERE code = 'h4';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'aulxefgfJU'
- WHERE code = 'h5';
-UPDATE `vn`.`packingSite`
- SET monitorId = '6Ou0D1bhBw'
- WHERE code = 'h6';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'eVUvnE6pNw'
- WHERE code = 'h7';
-UPDATE `vn`.`packingSite`
- SET monitorId = '0wsmSvqmrs'
- WHERE code = 'h8';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'r2l2RyyF4I'
- WHERE code = 'h9';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'EdjHLIiDVD'
- WHERE code = 'h10';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'czC45kmwqI'
- WHERE code = 'h11';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'PNsmxPaCwQ'
- WHERE code = 'h12';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'agVssO0FDC'
- WHERE code = 'h13';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'f2SPNENHPo'
- WHERE code = 'h14';
-UPDATE `vn`.`packingSite`
- SET monitorId = '6UR7gUZxks'
- WHERE code = 'h15';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'bOB0f8WZ2V'
- WHERE code = 'h16';
-UPDATE `vn`.`packingSite`
- SET monitorId = 'MIR1nXaL0n'
- WHERE code = 'h17';
-UPDATE `vn`.`packingSite`
- SET monitorId = '0Oj9SgGTXR'
- WHERE code = 'h18';
diff --git a/db/.archive/224901/00-salix_url.sql b/db/.archive/224901/00-salix_url.sql
deleted file mode 100644
index ea5c3b606..000000000
--- a/db/.archive/224901/00-salix_url.sql
+++ /dev/null
@@ -1,33 +0,0 @@
-CREATE TABLE `salix`.`url` (
- `appName` varchar(100) NOT NULL,
- `environment` varchar(100) NOT NULL,
- `url` varchar(255) NOT NULL,
- PRIMARY KEY (`appName`,`environment`)
-);
-
-INSERT INTO `salix`.`url` (`appName`, `environment`, `url`)
- VALUES
- ('salix', 'production', 'https://salix.verdnatura.es/#!/');
-INSERT INTO `salix`.`url` (`appName`, `environment`, `url`)
- VALUES
- ('salix', 'test', 'https://test-salix.verdnatura.es/#!/');
-INSERT INTO `salix`.`url` (`appName`, `environment`, `url`)
- VALUES
- ('salix', 'dev', 'http://localhost:5000/#!/');
-INSERT INTO `salix`.`url` (`appName`, `environment`, `url`)
- VALUES
- ('lilium', 'production', 'https://lilium.verdnatura.es/#/');
-INSERT INTO `salix`.`url` (`appName`, `environment`, `url`)
- VALUES
- ('lilium', 'test', 'https://test-lilium.verdnatura.es/#/');
-INSERT INTO `salix`.`url` (`appName`, `environment`, `url`)
- VALUES
- ('lilium', 'dev', 'http://localhost:8080/#/');
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Url', '*', 'READ', 'ALLOW', 'ROLE', 'employee');
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Url', '*', 'WRITE', 'ALLOW', 'ROLE', 'it');
diff --git a/db/.archive/224902/00-aclUserPassword.sql b/db/.archive/224902/00-aclUserPassword.sql
deleted file mode 100644
index b92b54c28..000000000
--- a/db/.archive/224902/00-aclUserPassword.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-DELETE FROM `salix`.`ACL`
- WHERE model = 'UserPassword';
diff --git a/db/.archive/224902/00-deletePickupContact.sql b/db/.archive/224902/00-deletePickupContact.sql
deleted file mode 100644
index 6bfa662c5..000000000
--- a/db/.archive/224902/00-deletePickupContact.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`claimConfig` DROP COLUMN `pickupContact`;
diff --git a/db/.archive/224902/00-itemShelvingACL.sql b/db/.archive/224902/00-itemShelvingACL.sql
deleted file mode 100644
index fc32fe1ed..000000000
--- a/db/.archive/224902/00-itemShelvingACL.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
-VALUES
- ('ItemShelving', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('ItemShelving', '*', 'WRITE', 'ALLOW', 'ROLE', 'production');
\ No newline at end of file
diff --git a/db/.archive/224902/00-itemShelvingPlacementSupplyStockACL.sql b/db/.archive/224902/00-itemShelvingPlacementSupplyStockACL.sql
deleted file mode 100644
index 25eac8d51..000000000
--- a/db/.archive/224902/00-itemShelvingPlacementSupplyStockACL.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
-VALUES
- ('ItemShelvingPlacementSupplyStock', '*', 'READ', 'ALLOW', 'ROLE', 'employee');
-
diff --git a/db/.archive/224902/00-workerTimeControlMail.sql b/db/.archive/224902/00-workerTimeControlMail.sql
deleted file mode 100644
index e3d169a83..000000000
--- a/db/.archive/224902/00-workerTimeControlMail.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`workerTimeControlMail` CHANGE emailResponse reason text CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL;
\ No newline at end of file
diff --git a/db/.archive/224902/00-zone_getPostalCode.sql b/db/.archive/224902/00-zone_getPostalCode.sql
deleted file mode 100644
index 58a281cb2..000000000
--- a/db/.archive/224902/00-zone_getPostalCode.sql
+++ /dev/null
@@ -1,54 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`zone_getPostalCode`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getPostalCode`(vSelf INT)
-BEGIN
-/**
- * Devuelve los códigos postales incluidos en una zona
- */
- DECLARE vGeoFk INT DEFAULT NULL;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes;
- CREATE TEMPORARY TABLE tmp.zoneNodes (
- geoFk INT,
- name VARCHAR(100),
- parentFk INT,
- sons INT,
- isChecked BOOL DEFAULT 0,
- zoneFk INT,
- PRIMARY KEY zoneNodesPk (zoneFk, geoFk),
- INDEX(geoFk))
- ENGINE = MEMORY;
-
- CALL zone_getLeaves2(vSelf, NULL , NULL);
-
- UPDATE tmp.zoneNodes zn
- SET isChecked = 0
- WHERE parentFk IS NULL;
-
- myLoop: LOOP
- SET vGeoFk = NULL;
- SELECT geoFk INTO vGeoFk
- FROM tmp.zoneNodes zn
- WHERE NOT isChecked
- LIMIT 1;
-
- CALL zone_getLeaves2(vSelf, vGeoFk, NULL);
- UPDATE tmp.zoneNodes
- SET isChecked = TRUE
- WHERE geoFk = vGeoFk;
-
- IF vGeoFk IS NULL THEN
- LEAVE myLoop;
- END IF;
- END LOOP;
-
- DELETE FROM tmp.zoneNodes
- WHERE sons > 0;
-
- SELECT zn.geoFk, zn.name
- FROM tmp.zoneNodes zn
- JOIN zone z ON z.id = zn.zoneFk;
-END$$
-DELIMITER ;
diff --git a/db/.archive/224903/00-ACL_notification_InvoiceE.sql b/db/.archive/224903/00-ACL_notification_InvoiceE.sql
deleted file mode 100644
index 660efc41e..000000000
--- a/db/.archive/224903/00-ACL_notification_InvoiceE.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('NotificationQueue','*','*','ALLOW','ROLE','employee');
diff --git a/db/.archive/224903/00-aclInvoiceOut.sql b/db/.archive/224903/00-aclInvoiceOut.sql
deleted file mode 100644
index 7715045b5..000000000
--- a/db/.archive/224903/00-aclInvoiceOut.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('InvoiceOut', 'clientsToInvoice', 'WRITE', 'ALLOW', 'ROLE', 'invoicing');
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('InvoiceOut', 'invoiceClient', 'WRITE', 'ALLOW', 'ROLE', 'invoicing');
\ No newline at end of file
diff --git a/db/.archive/224903/00-alter_expedition_itemFk.sql b/db/.archive/224903/00-alter_expedition_itemFk.sql
deleted file mode 100644
index d2849481b..000000000
--- a/db/.archive/224903/00-alter_expedition_itemFk.sql
+++ /dev/null
@@ -1 +0,0 @@
-Alter table `vn`.`expedition` RENAME COLUMN itemFk TO itemFk__;
\ No newline at end of file
diff --git a/db/.archive/224903/00-clientHasInvoiceElectronic.sql b/db/.archive/224903/00-clientHasInvoiceElectronic.sql
deleted file mode 100644
index 21f68c9ca..000000000
--- a/db/.archive/224903/00-clientHasInvoiceElectronic.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-ALTER TABLE
- `vn`.`client`
-ADD
- COLUMN `hasElectronicInvoice` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Registro de facturas mediante FACe'
-AFTER
- `hasInvoiceSimplified`;
-
--- sería más correcto hasElectronicInvoice pero ya existe un campo hasInvoiceSimplified
\ No newline at end of file
diff --git a/db/.archive/224903/00-collection_missingTrash.sql b/db/.archive/224903/00-collection_missingTrash.sql
deleted file mode 100644
index d4467c699..000000000
--- a/db/.archive/224903/00-collection_missingTrash.sql
+++ /dev/null
@@ -1 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`collection_missingTrash`;
diff --git a/db/.archive/224903/00-deleteInvoiceOutQueue.sql b/db/.archive/224903/00-deleteInvoiceOutQueue.sql
deleted file mode 100644
index 87a3059a0..000000000
--- a/db/.archive/224903/00-deleteInvoiceOutQueue.sql
+++ /dev/null
@@ -1 +0,0 @@
-DROP TABLE `vn`.`invoiceOutQueue`;
\ No newline at end of file
diff --git a/db/.archive/224903/00-editTrackedACL.sql b/db/.archive/224903/00-editTrackedACL.sql
deleted file mode 100644
index e768fb7c7..000000000
--- a/db/.archive/224903/00-editTrackedACL.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Sale', 'editTracked', 'WRITE', 'ALLOW', 'ROLE', 'production'),
- ('Sale', 'editFloramondo', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant');
diff --git a/db/.archive/224903/00-greuge.sql b/db/.archive/224903/00-greuge.sql
deleted file mode 100644
index ec4bf3146..000000000
--- a/db/.archive/224903/00-greuge.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`greuge` CHANGE `userFK` `userFk` int(10) unsigned DEFAULT NULL NULL;
\ No newline at end of file
diff --git a/db/.archive/224903/00-isCompensationACL.sql b/db/.archive/224903/00-isCompensationACL.sql
deleted file mode 100644
index ac01758b0..000000000
--- a/db/.archive/224903/00-isCompensationACL.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Receipt', 'balanceCompensationEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Receipt', 'balanceCompensationPdf', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/.archive/224903/00-osTicketConfig.sql b/db/.archive/224903/00-osTicketConfig.sql
deleted file mode 100644
index 10a58b6c8..000000000
--- a/db/.archive/224903/00-osTicketConfig.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-ALTER TABLE `vn`.`osTicketConfig` DROP COLUMN `action`;
-ALTER TABLE `vn`.`osTicketConfig` ADD responseType varchar(100) NULL;
-ALTER TABLE `vn`.`osTicketConfig` ADD fromEmailId INT NULL;
-ALTER TABLE `vn`.`osTicketConfig` ADD replyTo varchar(100) NULL;
-
-UPDATE `vn`.`osTicketConfig`
- SET responseType='reply', fromEmailId=5, replyTo='all'
-WHERE id=0;
\ No newline at end of file
diff --git a/db/.archive/224903/00-ticket_canMerge.sql b/db/.archive/224903/00-ticket_canMerge.sql
deleted file mode 100644
index 843237b64..000000000
--- a/db/.archive/224903/00-ticket_canMerge.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`ticket_canMerge`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canMerge`(vDated DATE, vScopeDays INT, vLitersMax INT, vLinesMax INT, vWarehouseFk INT)
-BEGIN
- CALL vn.ticket_canbePostponed(vDated,TIMESTAMPADD(DAY, vScopeDays, vDated),vLitersMax,vLinesMax,vWarehouseFk);
-END $$
-DELIMITER ;
-
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
-VALUES
- ('Ticket', 'getTicketsFuture', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'merge', 'WRITE', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/.archive/224903/00-ticket_canbePostponed.sql b/db/.archive/224903/00-ticket_canbePostponed.sql
deleted file mode 100644
index c691fa4bd..000000000
--- a/db/.archive/224903/00-ticket_canbePostponed.sql
+++ /dev/null
@@ -1,79 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`ticket_canbePostponed`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canbePostponed`(vOriginDated DATE, vFutureDated DATE, vLitersMax INT, vLinesMax INT, vWarehouseFk INT)
-BEGIN
-/**
- * Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro
- *
- * @param vOriginDated Fecha en cuestión
- * @param vFutureDated Fecha en el futuro a sondear
- * @param vLitersMax Volumen máximo de los tickets a catapultar
- * @param vLinesMax Número máximo de lineas de los tickets a catapultar
- * @param vWarehouseFk Identificador de vn.warehouse
- */
- DROP TEMPORARY TABLE IF EXISTS tmp.filter;
- CREATE TEMPORARY TABLE tmp.filter
- (INDEX (id))
- SELECT sv.ticketFk id,
- GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
- CAST(sum(litros) AS DECIMAL(10,0)) liters,
- CAST(count(*) AS DECIMAL(10,0)) `lines`,
- st.name state,
- sub2.id ticketFuture,
- t.landed originETD,
- sub2.landed destETD,
- sub2.iptd tfIpt,
- sub2.state tfState,
- t.clientFk,
- t.warehouseFk,
- ts.alertLevel,
- t.shipped,
- sub2.shipped tfShipped,
- t.workerFk,
- st.code code,
- sub2.code tfCode
- FROM vn.saleVolume sv
- JOIN vn.sale s ON s.id = sv.saleFk
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.ticket t ON t.id = sv.ticketFk
- JOIN vn.address a ON a.id = t.addressFk
- JOIN vn.province p ON p.id = a.provinceFk
- JOIN vn.country c ON c.id = p.countryFk
- JOIN vn.ticketState ts ON ts.ticketFk = t.id
- JOIN vn.state st ON st.id = ts.stateFk
- JOIN vn.alertLevel al ON al.id = ts.alertLevel
- LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
- LEFT JOIN (
- SELECT *
- FROM (
- SELECT
- t.addressFk ,
- t.id,
- t.landed,
- t.shipped,
- st.name state,
- st.code code,
- GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) iptd
- FROM vn.ticket t
- JOIN vn.ticketState ts ON ts.ticketFk = t.id
- JOIN vn.state st ON st.id = ts.stateFk
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- WHERE t.shipped BETWEEN vFutureDated
- AND util.dayend(vFutureDated)
- AND t.warehouseFk = vWarehouseFk
- GROUP BY t.id
- ) sub
- GROUP BY sub.addressFk
- ) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id
- WHERE t.shipped BETWEEN vOriginDated AND util.dayend(vOriginDated)
- AND t.warehouseFk = vWarehouseFk
- AND al.code = 'FREE'
- AND tp.ticketFk IS NULL
- GROUP BY sv.ticketFk
- HAVING liters <= IFNULL(vLitersMax, 9999) AND `lines` <= IFNULL(vLinesMax, 9999) AND ticketFuture;
-END$$
-DELIMITER ;
-
diff --git a/db/.archive/224903/00-timeBusiness_calculate.sql b/db/.archive/224903/00-timeBusiness_calculate.sql
deleted file mode 100644
index 6345475dd..000000000
--- a/db/.archive/224903/00-timeBusiness_calculate.sql
+++ /dev/null
@@ -1,88 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`timeBusiness_calculate`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME)
-BEGIN
-/**
- * Horas que debe trabajar un empleado según contrato y día.
- * @param vDatedFrom workerTimeControl
- * @param vDatedTo workerTimeControl
- * @table tmp.user(userFk)
- * @return tmp.timeBusinessCalculate
- */
- DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate;
- CREATE TEMPORARY TABLE tmp.timeBusinessCalculate
- (INDEX (departmentFk))
- SELECT dated,
- businessFk,
- userFk,
- departmentFk,
- hourStart,
- hourEnd,
- timeTable,
- timeWorkSeconds,
- SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal,
- timeWorkSeconds / 3600 timeWorkDecimal,
- timeWorkSeconds timeBusinessSeconds,
- SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal,
- timeWorkSeconds / 3600 timeBusinessDecimal,
- name type,
- permissionRate,
- hoursWeek,
- discountRate,
- isAllowedToWork
- FROM(SELECT t.dated,
- b.id businessFk,
- w.id,
- b.departmentFk,
- IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,5) ORDER BY j.start ASC SEPARATOR ' - ')) hourStart ,
- IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,5) ORDER BY j.end ASC SEPARATOR ' - ')) hourEnd,
- IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,5), " - ", LEFT(j.end,5) ORDER BY j.end ASC SEPARATOR ' - ')) timeTable,
- IF(j.start = NULL, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)), 0)) timeWorkSeconds,
- at2.name,
- at2.permissionRate,
- at2.discountRate,
- cl.hours_week hoursWeek,
- at2.isAllowedToWork
- FROM time t
- LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo)
- LEFT JOIN worker w ON w.id = b.workerFk
- JOIN tmp.`user` u ON u.userFK = w.id
- LEFT JOIN workCenter wc ON wc.id = b.workcenterFK
- LEFT JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = b.calendarTypeFk
- LEFT JOIN postgresql.journey j ON j.business_id = b.id AND j.day_id = WEEKDAY(t.dated) + 1
- LEFT JOIN postgresql.calendar_employee ce ON ce.businessFk = b.id AND ce.date = t.dated
- LEFT JOIN absenceType at2 ON at2.id = ce.calendar_state_id
- WHERE t.dated BETWEEN vDatedFrom AND vDatedTo
- GROUP BY w.id, t.dated
- )sub;
-
- UPDATE tmp.timeBusinessCalculate t
- LEFT JOIN postgresql.journey j ON j.business_id = t.businessFk
- SET t.timeWorkSeconds = t.hoursWeek / 5 * 3600,
- t.timeWorkSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600),
- t.timeWorkDecimal = t.hoursWeek / 5,
- t.timeBusinessSeconds = t.hoursWeek / 5 * 3600,
- t.timeBusinessSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600),
- t.timeBusinessDecimal = t.hoursWeek / 5
- WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND j.journey_id IS NULL ;
-
- UPDATE tmp.timeBusinessCalculate t
- SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionRate) ,
- t.timeWorkSexagesimal = SEC_TO_TIME ((t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate)) * 3600),
- t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate)
- WHERE permissionRate <> 0;
-
- UPDATE tmp.timeBusinessCalculate t
- JOIN calendarHolidays ch ON ch.dated = t.dated
- JOIN business b ON b.id = t.businessFk
- AND b.workcenterFk = ch.workcenterFk
- SET t.timeWorkSeconds = 0,
- t.timeWorkSexagesimal = 0,
- t.timeWorkDecimal = 0,
- t.permissionrate = 1,
- t.type = 'Festivo'
- WHERE t.type IS NULL;
-END$$
-DELIMITER ;
diff --git a/db/.archive/224903/01-updateClientHasInvoiceElectronic.sql b/db/.archive/224903/01-updateClientHasInvoiceElectronic.sql
deleted file mode 100644
index af1c8ca9a..000000000
--- a/db/.archive/224903/01-updateClientHasInvoiceElectronic.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-UPDATE
- `vn`.`client`
-SET
- hasElectronicInvoice = TRUE
-WHERE
- businessTypeFk = 'officialOrganism';
\ No newline at end of file
diff --git a/db/.archive/225001/00-aclMdbApp.sql b/db/.archive/225001/00-aclMdbApp.sql
deleted file mode 100644
index b5b60546c..000000000
--- a/db/.archive/225001/00-aclMdbApp.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('MdbApp', 'lock', 'WRITE', 'ALLOW', 'ROLE', 'developer'),
- ('MdbApp', 'unlock', 'WRITE', 'ALLOW', 'ROLE', 'developer');
diff --git a/db/.archive/225001/00-updateCollection.sql b/db/.archive/225001/00-updateCollection.sql
deleted file mode 100644
index 6d4ec4307..000000000
--- a/db/.archive/225001/00-updateCollection.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-UPDATE `vn`.`collection`
- SET sectorFk=1
- WHERE id=1;
diff --git a/db/.archive/225201/00-ACL_saveSign.sql b/db/.archive/225201/00-ACL_saveSign.sql
deleted file mode 100644
index 16f9931c4..000000000
--- a/db/.archive/225201/00-ACL_saveSign.sql
+++ /dev/null
@@ -1 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalId`) VALUES ('Dms','saveSign','*','ALLOW','employee');
diff --git a/db/.archive/225201/00-aclTicketLog.sql b/db/.archive/225201/00-aclTicketLog.sql
deleted file mode 100644
index edba17ab4..000000000
--- a/db/.archive/225201/00-aclTicketLog.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('TicketLog', 'getChanges', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/.archive/225201/00-entryDeleteRef.sql b/db/.archive/225201/00-entryDeleteRef.sql
deleted file mode 100644
index 7e47eae63..000000000
--- a/db/.archive/225201/00-entryDeleteRef.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`entry` DROP COLUMN `ref`;
diff --git a/db/.archive/225201/00-invoiceInConfig.sql b/db/.archive/225201/00-invoiceInConfig.sql
deleted file mode 100644
index a27b59440..000000000
--- a/db/.archive/225201/00-invoiceInConfig.sql
+++ /dev/null
@@ -1,12 +0,0 @@
-CREATE TABLE `vn`.`invoiceInConfig` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `retentionRate` int(3) NOT NULL,
- `retentionName` varchar(25) NOT NULL,
- `sageWithholdingFk` smallint(6) NOT NULL,
- PRIMARY KEY (`id`),
- CONSTRAINT `invoiceInConfig_sageWithholdingFk` FOREIGN KEY (`sageWithholdingFk`) REFERENCES `sage`.`TiposRetencion`(`CodigoRetencion`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-INSERT INTO `vn`.`invoiceInConfig` (`id`, `retentionRate`, `retentionName`, `sageWithholdingFk`)
- VALUES
- (1, -2, 'Retención 2%', 2);
diff --git a/db/.archive/225201/00-invoiceOut_new.sql b/db/.archive/225201/00-invoiceOut_new.sql
deleted file mode 100644
index 4c60b50bc..000000000
--- a/db/.archive/225201/00-invoiceOut_new.sql
+++ /dev/null
@@ -1,225 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`invoiceOut_new`;
-DELIMITER $$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOut_new`(
- vSerial VARCHAR(255),
- vInvoiceDate DATETIME,
- vTaxArea VARCHAR(25),
- OUT vNewInvoiceId INT)
-BEGIN
-/**
- * Creación de facturas emitidas.
- * requiere previamente tabla tmp.ticketToInvoice(id).
- *
- * @param vSerial serie a la cual se hace la factura
- * @param vInvoiceDate fecha de la factura
- * @param vTaxArea tipo de iva en relacion a la empresa y al cliente
- * @param vNewInvoiceId id de la factura que se acaba de generar
- * @return vNewInvoiceId
- */
- DECLARE vSpainCountryCode INT DEFAULT 1;
- DECLARE vIsAnySaleToInvoice BOOL;
- DECLARE vIsAnyServiceToInvoice BOOL;
- DECLARE vNewRef VARCHAR(255);
- DECLARE vWorker INT DEFAULT account.myUser_getId();
- DECLARE vCompany INT;
- DECLARE vSupplier INT;
- DECLARE vClient INT;
- DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1;
- DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6;
- DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2;
- DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R';
- DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S';
- DECLARE vNewInvoiceInId INT;
- DECLARE vIsInterCompany BOOL;
-
- SET vInvoiceDate = IFNULL(vInvoiceDate,CURDATE());
-
- SELECT t.clientFk, t.companyFk
- INTO vClient, vCompany
- FROM tmp.ticketToInvoice tt
- JOIN ticket t ON t.id = tt.id
- LIMIT 1;
-
- -- Eliminem de tmp.ticketToInvoice els tickets que no han de ser facturats
- DELETE ti.*
- FROM tmp.ticketToInvoice ti
- JOIN ticket t ON t.id = ti.id
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- JOIN supplier su ON su.id = t.companyFk
- JOIN client c ON c.id = t.clientFk
- LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = su.countryFk
- WHERE YEAR(t.shipped) < 2001
- OR c.isTaxDataChecked = FALSE
- OR t.isDeleted
- OR c.hasToInvoice = FALSE
- OR itc.id IS NULL;
-
- SELECT SUM(s.quantity * s.price * (100 - s.discount)/100), ts.id
- INTO vIsAnySaleToInvoice, vIsAnyServiceToInvoice
- FROM tmp.ticketToInvoice t
- LEFT JOIN sale s ON s.ticketFk = t.id
- LEFT JOIN ticketService ts ON ts.ticketFk = t.id;
-
- IF (vIsAnySaleToInvoice OR vIsAnyServiceToInvoice)
- AND (vCorrectingSerial = vSerial OR NOT hasAnyNegativeBase())
- THEN
-
- -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial
- INSERT INTO invoiceOut
- (
- ref,
- serial,
- issued,
- clientFk,
- dued,
- companyFk,
- cplusInvoiceType477Fk
- )
- SELECT
- 1,
- vSerial,
- vInvoiceDate,
- vClient,
- getDueDate(vInvoiceDate, dueDay),
- vCompany,
- IF(vSerial = vCorrectingSerial,
- vCplusCorrectingInvoiceTypeFk,
- IF(vSerial = vSimplifiedSerial,
- vCplusSimplifiedInvoiceTypeFk,
- vCplusStandardInvoiceTypeFk))
- FROM client
- WHERE id = vClient;
-
-
- SET vNewInvoiceId = LAST_INSERT_ID();
-
- SELECT `ref`
- INTO vNewRef
- FROM invoiceOut
- WHERE id = vNewInvoiceId;
-
- UPDATE ticket t
- JOIN tmp.ticketToInvoice ti ON ti.id = t.id
- SET t.refFk = vNewRef;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.updateInter;
- CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY
- SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador
- FROM tmp.ticketToInvoice ti
- LEFT JOIN ticketState ts ON ti.id = ts.ticket
- JOIN state s
- WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = 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.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef)
- FROM tmp.ticketToInvoice ti;
-
- CALL invoiceExpenceMake(vNewInvoiceId);
- CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
-
- UPDATE invoiceOut io
- JOIN (
- SELECT SUM(amount) AS total
- FROM invoiceOutExpence
- WHERE invoiceOutFk = vNewInvoiceId
- ) base
- JOIN (
- SELECT SUM(vat) AS total
- FROM invoiceOutTax
- WHERE invoiceOutFk = vNewInvoiceId
- ) vat
- SET io.amount = base.total + vat.total
- WHERE io.id = vNewInvoiceId;
-
- DROP TEMPORARY TABLE tmp.updateInter;
-
- SELECT ios.isCEE INTO vIsInterCompany
- FROM vn.ticket t
- JOIN vn.invoiceOut io ON io.`ref` = t.refFk
- JOIN vn.invoiceOutSerial ios ON ios.code = io.serial
- WHERE t.refFk = vNewRef
- LIMIT 1;
-
- IF (vIsInterCompany) THEN
-
- SELECT vCompany INTO vSupplier;
- SELECT id INTO vCompany FROM company WHERE clientFk = vClient;
-
- INSERT INTO invoiceIn(supplierFk, supplierRef, issued, companyFk)
- SELECT vSupplier, vNewRef, vInvoiceDate, vCompany;
-
- SET vNewInvoiceInId = LAST_INSERT_ID();
-
- DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
- CREATE TEMPORARY TABLE tmp.ticket
- (KEY (ticketFk))
- ENGINE = MEMORY
- SELECT id ticketFk
- FROM tmp.ticketToInvoice;
-
- CALL `ticket_getTax`('NATIONAL');
-
- SET @vTaxableBaseServices := 0.00;
- SET @vTaxCodeGeneral := NULL;
-
- INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenceFk, sub.taxTypeSageFk , sub.transactionTypeSageFk
- FROM (
- SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk
- FROM tmp.ticketServiceTax tst
- JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code
- WHERE i.isService
- HAVING taxableBase
- ) sub;
-
- INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk
- FROM tmp.ticketTax tt
- JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code
- WHERE !i.isService
- GROUP BY tt.pgcFk
- HAVING taxableBase
- ORDER BY tt.priority;
-
- CALL invoiceInDueDay_calculate(vNewInvoiceInId);
-
- INSERT INTO invoiceInIntrastat (
- invoiceInFk,
- intrastatFk,
- amount,
- stems,
- countryFk,
- net)
- SELECT
- vNewInvoiceInId invoiceInFk,
- i.intrastatFk,
- CAST(SUM((s.quantity * s.price * (100 - s.discount) / 100 )) AS DECIMAL(10,2)) subtotal,
- CAST(SUM(IFNULL(i.stems, 1) * s.quantity) AS DECIMAL(10,2)) stems,
- su.countryFk,
- CAST(SUM(IFNULL(i.stems, 1)
- * s.quantity
- * IF(ic.grams, ic.grams, i.weightByPiece) / 1000) AS DECIMAL(10,2)) netKg
- FROM sale s
- JOIN ticket t ON s.ticketFk = t.id
- JOIN supplier su ON su.id = t.companyFk
- JOIN item i ON i.id = s.itemFk
- JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk
- JOIN intrastat ir ON ir.id = i.intrastatFk
- WHERE t.refFk = vNewRef;
-
- DROP TEMPORARY TABLE tmp.ticket;
- DROP TEMPORARY TABLE tmp.ticketAmount;
- DROP TEMPORARY TABLE tmp.ticketTax;
- DROP TEMPORARY TABLE tmp.ticketServiceTax;
-
- END IF;
-
- END IF;
-
- DROP TEMPORARY TABLE `tmp`.`ticketToInvoice`;
-END$$
-DELIMITER ;
diff --git a/db/.archive/225201/00-mdbApp.sql b/db/.archive/225201/00-mdbApp.sql
deleted file mode 100644
index 3202e3f08..000000000
--- a/db/.archive/225201/00-mdbApp.sql
+++ /dev/null
@@ -1,11 +0,0 @@
-CREATE TABLE `vn`.`mdbApp` (
- `app` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL,
- `baselineBranchFk` varchar(255) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
- `userFk` int(10) unsigned DEFAULT NULL,
- `locked` datetime DEFAULT NULL,
- PRIMARY KEY (`app`),
- KEY `mdbApp_FK` (`userFk`),
- KEY `mdbApp_FK_1` (`baselineBranchFk`),
- CONSTRAINT `mdbApp_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT `mdbApp_FK_1` FOREIGN KEY (`baselineBranchFk`) REFERENCES `mdbBranch` (`name`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci
diff --git a/db/.archive/225201/00-notification_send.sql b/db/.archive/225201/00-notification_send.sql
deleted file mode 100644
index a422cebac..000000000
--- a/db/.archive/225201/00-notification_send.sql
+++ /dev/null
@@ -1,24 +0,0 @@
-DROP FUNCTION IF EXISTS `util`.`notification_send`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` FUNCTION `util`.`notification_send`(vNotificationName VARCHAR(255), vParams TEXT, vAuthorFk INT) RETURNS int(11)
- MODIFIES SQL DATA
-BEGIN
-/**
- * Sends a notification.
- *
- * @param vNotificationName The notification name
- * @param vParams The notification parameters formatted as JSON
- * @param vAuthorFk The notification author or %NULL if there is no author
- * @return The notification id
- */
-
- INSERT INTO notificationQueue
- SET notificationFk = vNotificationName,
- params = vParams,
- authorFk = vAuthorFk;
-
- RETURN LAST_INSERT_ID();
-END$$
-DELIMITER ;
diff --git a/db/.archive/225201/00-ticketSms.sql b/db/.archive/225201/00-ticketSms.sql
deleted file mode 100644
index f454f99b1..000000000
--- a/db/.archive/225201/00-ticketSms.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-CREATE TABLE `vn`.`ticketSms` (
- `smsFk` mediumint(8) unsigned NOT NULL,
- `ticketFk` int(11) DEFAULT NULL,
- PRIMARY KEY (`smsFk`),
- KEY `ticketSms_FK_1` (`ticketFk`),
- CONSTRAINT `ticketSms_FK` FOREIGN KEY (`smsFk`) REFERENCES `sms` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `ticketSms_FK_1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci
diff --git a/db/.archive/225201/00-ticket_canAdvance.sql b/db/.archive/225201/00-ticket_canAdvance.sql
deleted file mode 100644
index acc4dcc4a..000000000
--- a/db/.archive/225201/00-ticket_canAdvance.sql
+++ /dev/null
@@ -1,104 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`ticket_canAdvance`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT)
-BEGIN
-/**
- * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar.
- *
- * @param vDateFuture Fecha de los tickets que se quieren adelantar.
- * @param vDateToAdvance Fecha a cuando se quiere adelantar.
- * @param vWarehouseFk Almacén
- */
-
- DECLARE vDateInventory DATE;
-
- SELECT inventoried INTO vDateInventory FROM vn.config;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.stock;
- CREATE TEMPORARY TABLE tmp.stock
- (itemFk INT PRIMARY KEY,
- amount INT)
- ENGINE = MEMORY;
-
- INSERT INTO tmp.stock(itemFk, amount)
- SELECT itemFk, SUM(quantity) amount FROM
- (
- SELECT itemFk, quantity
- FROM vn.itemTicketOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM vn.itemEntryIn
- WHERE landed >= vDateInventory
- AND landed < vDateFuture
- AND isVirtualStock = FALSE
- AND warehouseInFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM vn.itemEntryOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseOutFk = vWarehouseFk
- ) t
- GROUP BY itemFk HAVING amount != 0;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.filter;
- CREATE TEMPORARY TABLE tmp.filter
- (INDEX (id))
- SELECT s.ticketFk futureId,
- t2.ticketFk id,
- sum((s.quantity <= IFNULL(st.amount,0))) hasStock,
- count(DISTINCT s.id) saleCount,
- t2.state,
- t2.stateCode,
- st.name futureState,
- st.code futureStateCode,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
- t2.ipt,
- t.workerFk,
- CAST(sum(litros) AS DECIMAL(10,0)) liters,
- CAST(count(*) AS DECIMAL(10,0)) `lines`,
- t2.shipped,
- t.shipped futureShipped,
- t2.totalWithVat,
- t.totalWithVat futureTotalWithVat
- FROM vn.ticket t
- JOIN vn.ticketState ts ON ts.ticketFk = t.id
- JOIN vn.state st ON st.id = ts.stateFk
- JOIN vn.saleVolume sv ON t.id = sv.ticketFk
- JOIN (SELECT
- t2.id ticketFk,
- t2.addressFk,
- st.name state,
- st.code stateCode,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
- t2.shipped,
- t2.totalWithVat
- FROM vn.ticket t2
- JOIN vn.sale s ON s.ticketFk = t2.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.ticketState ts ON ts.ticketFk = t2.id
- JOIN vn.state st ON st.id = ts.stateFk
- LEFT JOIN vn.itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- WHERE t2.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance)
- AND t2.warehouseFk = vWarehouseFk
- GROUP BY t2.id) t2 ON t2.addressFk = t.addressFk
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- LEFT JOIN vn.itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- LEFT JOIN tmp.stock st ON st.itemFk = s.itemFk
- WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
- AND t.warehouseFk = vWarehouseFk
- GROUP BY t.id;
-
- DROP TEMPORARY TABLE tmp.stock;
-END$$
-DELIMITER ;
-
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
-VALUES
- ('Ticket', 'getTicketsAdvance', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/.archive/225201/00-ticket_canbePostponed.sql b/db/.archive/225201/00-ticket_canbePostponed.sql
deleted file mode 100644
index 572824b4b..000000000
--- a/db/.archive/225201/00-ticket_canbePostponed.sql
+++ /dev/null
@@ -1,73 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`ticket_canbePostponed`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canbePostponed`(vOriginDated DATE, vFutureDated DATE, vWarehouseFk INT)
-BEGIN
-/**
- * Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro
- *
- * @param vOriginDated Fecha en cuestión
- * @param vFutureDated Fecha en el futuro a sondear
- * @param vWarehouseFk Identificador de vn.warehouse
- */
- DROP TEMPORARY TABLE IF EXISTS tmp.filter;
- CREATE TEMPORARY TABLE tmp.filter
- (INDEX (id))
- SELECT sv.ticketFk id,
- sub2.id futureId,
- GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
- CAST(sum(litros) AS DECIMAL(10,0)) liters,
- CAST(count(*) AS DECIMAL(10,0)) `lines`,
- st.name state,
- sub2.iptd futureIpt,
- sub2.state futureState,
- t.clientFk,
- t.warehouseFk,
- ts.alertLevel,
- t.shipped,
- sub2.shipped futureShipped,
- t.workerFk,
- st.code stateCode,
- sub2.code futureStateCode
- FROM vn.saleVolume sv
- JOIN vn.sale s ON s.id = sv.saleFk
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.ticket t ON t.id = sv.ticketFk
- JOIN vn.address a ON a.id = t.addressFk
- JOIN vn.province p ON p.id = a.provinceFk
- JOIN vn.country c ON c.id = p.countryFk
- JOIN vn.ticketState ts ON ts.ticketFk = t.id
- JOIN vn.state st ON st.id = ts.stateFk
- JOIN vn.alertLevel al ON al.id = ts.alertLevel
- LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
- LEFT JOIN (
- SELECT *
- FROM (
- SELECT
- t.addressFk,
- t.id,
- t.shipped,
- st.name state,
- st.code code,
- GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) iptd
- FROM vn.ticket t
- JOIN vn.ticketState ts ON ts.ticketFk = t.id
- JOIN vn.state st ON st.id = ts.stateFk
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- WHERE t.shipped BETWEEN vFutureDated
- AND util.dayend(vFutureDated)
- AND t.warehouseFk = vWarehouseFk
- GROUP BY t.id
- ) sub
- GROUP BY sub.addressFk
- ) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id
- WHERE t.shipped BETWEEN vOriginDated AND util.dayend(vOriginDated)
- AND t.warehouseFk = vWarehouseFk
- AND al.code = 'FREE'
- AND tp.ticketFk IS NULL
- GROUP BY sv.ticketFk
- HAVING futureId;
-END$$
-DELIMITER ;
diff --git a/db/.archive/225201/00-ticket_split_merge.sql b/db/.archive/225201/00-ticket_split_merge.sql
deleted file mode 100644
index a1a6579e6..000000000
--- a/db/.archive/225201/00-ticket_split_merge.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-DROP PROCEDURE IF EXISTS `ticket_split`;
-DROP PROCEDURE IF EXISTS `ticket_merge`;
diff --git a/db/.archive/225201/00-utilNotification.sql b/db/.archive/225201/00-utilNotification.sql
deleted file mode 100644
index 74f0de5e2..000000000
--- a/db/.archive/225201/00-utilNotification.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `util`.`notification` (id, name, description) VALUES(3, 'book-entries-imported-incorrectly', 'accounting entries exported incorrectly');
-INSERT INTO `util`.`notificationAcl` (notificationFk, roleFk) VALUES(3, 5);
-INSERT IGNORE INTO `util`.`notificationSubscription` (notificationFk, userFk) VALUES(3, 19663);
-
diff --git a/db/.archive/225201/01-create_stateI18n.sql b/db/.archive/225201/01-create_stateI18n.sql
deleted file mode 100644
index 799360b1e..000000000
--- a/db/.archive/225201/01-create_stateI18n.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-CREATE TABLE `vn`.`stateI18n` (
- `stateFk` tinyint(3) unsigned NOT NULL,
- `lang` char(2) NOT NULL,
- `name` varchar(255) NOT NULL,
- PRIMARY KEY (`stateFk`, `lang`),
- CONSTRAINT `stateI18n_state_id` FOREIGN KEY (`stateFk`) REFERENCES `vn`.`state` (`id`)
-) ENGINE = InnoDB DEFAULT CHARSET = utf8;
diff --git a/db/.archive/225201/01-modules.sql b/db/.archive/225201/01-modules.sql
deleted file mode 100644
index 243d2d016..000000000
--- a/db/.archive/225201/01-modules.sql
+++ /dev/null
@@ -1,60 +0,0 @@
-UPDATE salix.module t
-SET t.code = 'supplier'
-WHERE t.code LIKE 'Suppliers' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'travel'
-WHERE t.code LIKE 'Travels' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'ticket'
-WHERE t.code LIKE 'Tickets' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'zone'
-WHERE t.code LIKE 'Zones' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'monitor'
-WHERE t.code LIKE 'Monitors' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'entry'
-WHERE t.code LIKE 'Entries' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'invoiceIn'
-WHERE t.code LIKE 'Invoices in' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'customer'
-WHERE t.code LIKE 'Clients' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'route'
-WHERE t.code LIKE 'Routes' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'item'
-WHERE t.code LIKE 'Items' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'claim'
-WHERE t.code LIKE 'Claims' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'account'
-WHERE t.code LIKE 'Users' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'invoiceOut'
-WHERE t.code LIKE 'Invoices out' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'order'
-WHERE t.code LIKE 'Orders' ESCAPE '#';
-
-UPDATE salix.module t
-SET t.code = 'worker'
-WHERE t.code LIKE 'Workers' ESCAPE '#';
-
diff --git a/db/.archive/225201/02-insert_stateI18n.sql b/db/.archive/225201/02-insert_stateI18n.sql
deleted file mode 100644
index 7df36d662..000000000
--- a/db/.archive/225201/02-insert_stateI18n.sql
+++ /dev/null
@@ -1,73 +0,0 @@
-INSERT INTO
- `vn`.`stateI18n` (`stateFk`, `lang`, `name`)
-VALUES
- (1, 'en', 'Fix'),
- (1, 'es', 'Arreglar'),
- (2, 'en', 'Free'),
- (2, 'es', 'Libre'),
- (3, 'en', 'OK'),
- (3, 'es', 'OK'),
- (4, 'en', 'Printed'),
- (4, 'es', 'Impreso'),
- (5, 'en', 'Preparation'),
- (5, 'es', 'Preparación'),
- (6, 'en', 'In Review'),
- (6, 'es', 'En Revisión'),
- (7, 'en', 'Unfinished'),
- (7, 'es', 'Sin Acabar'),
- (8, 'en', 'Reviewed'),
- (8, 'es', 'Revisado'),
- (9, 'en', 'Fitting'),
- (9, 'es', 'Encajando'),
- (10, 'en', 'Fitted'),
- (10, 'es', 'Encajado'),
- (11, 'en', 'Billed'),
- (11, 'es', 'Facturado'),
- (12, 'en', 'Blocked'),
- (12, 'es', 'Bloqueado'),
- (13, 'en', 'In Delivery'),
- (13, 'es', 'En Reparto'),
- (14, 'en', 'Prepared'),
- (14, 'es', 'Preparado'),
- (15, 'en', 'Pending Collection'),
- (15, 'es', 'Pendiente de Recogida'),
- (16, 'en', 'Delivered'),
- (16, 'es', 'Entregado'),
- (20, 'en', 'Assigned'),
- (20, 'es', 'Asignado'),
- (21, 'en', 'Returned'),
- (21, 'es', 'Retornado'),
- (22, 'en', 'Pending to extend'),
- (22, 'es', 'Pendiente ampliar'),
- (23, 'en', 'URGENT'),
- (23, 'es', 'URGENTE'),
- (24, 'en', 'Chained'),
- (24, 'es', 'Encadenado'),
- (25, 'en', 'Shipping'),
- (25, 'es', 'Embarcando'),
- (26, 'en', 'Preparation'),
- (26, 'es', 'Preparación previa'),
- (27, 'en', 'Assisted preparation'),
- (27, 'es', 'Preparación asistida'),
- (28, 'en', 'Preparation OK'),
- (28, 'es', 'Previa OK'),
- (29, 'en', 'Preparation Printed'),
- (29, 'es', 'Previa Impreso'),
- (30, 'en', 'Shipped'),
- (30, 'es', 'Embarcado'),
- (31, 'en', 'Stowaway printed'),
- (31, 'es', 'Polizón Impreso'),
- (32, 'en', 'Stowaway OK'),
- (32, 'es', 'Polizón OK'),
- (33, 'en', 'Auto_Printed'),
- (33, 'es', 'Auto_Impreso'),
- (34, 'en', 'Pending payment'),
- (34, 'es', 'Pendiente de pago'),
- (35, 'en', 'Half-Embedded'),
- (35, 'es', 'Semi-Encajado'),
- (36, 'en', 'Preparation Reviewing'),
- (36, 'es', 'Previa Revisando'),
- (37, 'en', 'Preparation Reviewed'),
- (37, 'es', 'Previa Revisado'),
- (38, 'en', 'Preparation Chamber'),
- (38, 'es', 'Preparación Cámara');
\ No newline at end of file
diff --git a/db/.archive/225201/02-starredModule.sql b/db/.archive/225201/02-starredModule.sql
deleted file mode 100644
index 3ca67fce4..000000000
--- a/db/.archive/225201/02-starredModule.sql
+++ /dev/null
@@ -1,16 +0,0 @@
-UPDATE `vn`.starredModule SET moduleFk = 'customer' WHERE moduleFk = 'Clients';
-UPDATE `vn`.starredModule SET moduleFk = 'ticket' WHERE moduleFk = 'Tickets';
-UPDATE `vn`.starredModule SET moduleFk = 'route' WHERE moduleFk = 'Routes';
-UPDATE `vn`.starredModule SET moduleFk = 'zone' WHERE moduleFk = 'Zones';
-UPDATE `vn`.starredModule SET moduleFk = 'order' WHERE moduleFk = 'Orders';
-UPDATE `vn`.starredModule SET moduleFk = 'claim' WHERE moduleFk = 'Claims';
-UPDATE `vn`.starredModule SET moduleFk = 'item' WHERE moduleFk = 'Items';
-UPDATE `vn`.starredModule SET moduleFk = 'worker' WHERE moduleFk = 'Workers';
-UPDATE `vn`.starredModule SET moduleFk = 'entry' WHERE moduleFk = 'Entries';
-UPDATE `vn`.starredModule SET moduleFk = 'invoiceOut' WHERE moduleFk = 'Invoices out';
-UPDATE `vn`.starredModule SET moduleFk = 'invoiceIn' WHERE moduleFk = 'Invoices in';
-UPDATE `vn`.starredModule SET moduleFk = 'monitor' WHERE moduleFk = 'Monitors';
-UPDATE `vn`.starredModule SET moduleFk = 'user' WHERE moduleFk = 'Users';
-UPDATE `vn`.starredModule SET moduleFk = 'supplier' WHERE moduleFk = 'Suppliers';
-UPDATE `vn`.starredModule SET moduleFk = 'travel' WHERE moduleFk = 'Travels';
-UPDATE `vn`.starredModule SET moduleFk = 'shelving' WHERE moduleFk = 'Shelvings';
\ No newline at end of file
diff --git a/db/.archive/225202/00-mdbApp.sql b/db/.archive/225202/00-mdbApp.sql
deleted file mode 100644
index 50c595d71..000000000
--- a/db/.archive/225202/00-mdbApp.sql
+++ /dev/null
@@ -1,28 +0,0 @@
-ALTER TABLE `vn`.`mdbApp` DROP PRIMARY KEY;
-ALTER TABLE `vn`.`mdbApp` ADD CONSTRAINT mdbApp_PK PRIMARY KEY (app,baselineBranchFk);
-
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('com','master');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('enc','master');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('ent','master');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('eti','master');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('lab','master');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('tpv','master');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('com','dev');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('enc','dev');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('ent','dev');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('eti','dev');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('lab','dev');
-INSERT INTO `vn`.`mdbApp` (app,baselineBranchFk)
- VALUES ('tpv','dev');
-
diff --git a/db/.archive/225203/00-mdbApp.sql b/db/.archive/225203/00-mdbApp.sql
deleted file mode 100644
index 32a21eb6b..000000000
--- a/db/.archive/225203/00-mdbApp.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-UPDATE `vn`.`osTicketConfig`
-SET oldStatus='1,6'
-WHERE id=0;
-
-
diff --git a/db/.archive/230201/00-ACL_ItemShelvingSale.sql b/db/.archive/230201/00-ACL_ItemShelvingSale.sql
deleted file mode 100644
index 38b65f89a..000000000
--- a/db/.archive/230201/00-ACL_ItemShelvingSale.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalId`)
- VALUES ('ItemShelvingSale','*','*','ALLOW','employee');
diff --git a/db/.archive/230201/00-SupplierUniqueKey.sql b/db/.archive/230201/00-SupplierUniqueKey.sql
deleted file mode 100644
index 9c0d4a192..000000000
--- a/db/.archive/230201/00-SupplierUniqueKey.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`supplier` ADD UNIQUE (name, countryFk);
diff --git a/db/.archive/230201/00-autoincrement_VnReport_VnPrinter.sql b/db/.archive/230201/00-autoincrement_VnReport_VnPrinter.sql
deleted file mode 100644
index a28bf6e90..000000000
--- a/db/.archive/230201/00-autoincrement_VnReport_VnPrinter.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-SET FOREIGN_KEY_CHECKS = 0;
-ALTER TABLE `vn`.`report` MODIFY COLUMN id tinyint(3) unsigned NOT NULL AUTO_INCREMENT;
-ALTER TABLE `vn`.`printer` MODIFY COLUMN id tinyint(3) unsigned NOT NULL AUTO_INCREMENT;
-SET FOREIGN_KEY_CHECKS = 1;
diff --git a/db/.archive/230201/00-borradoLogicoIPT.sql b/db/.archive/230201/00-borradoLogicoIPT.sql
deleted file mode 100644
index ae7ecf0ca..000000000
--- a/db/.archive/230201/00-borradoLogicoIPT.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-ALTER TABLE `vn`.`itemPackingType` ADD isActive BOOLEAN NOT NULL;
-UPDATE `vn`.`itemPackingType` SET isActive = 0 WHERE code IN ('P', 'F');
-UPDATE `vn`.`itemPackingType` SET isActive = 1 WHERE code IN ('V', 'H');
diff --git a/db/.archive/230201/00-docuwareStore.sql b/db/.archive/230201/00-docuwareStore.sql
deleted file mode 100644
index b20c2554f..000000000
--- a/db/.archive/230201/00-docuwareStore.sql
+++ /dev/null
@@ -1,23 +0,0 @@
-CREATE OR REPLACE TABLE `vn`.`docuware` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `code` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
- `fileCabinetName` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
- `action` varchar(255) COLLATE utf8mb3_unicode_ci NOT NULL,
- `dialogName` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL,
- `findById` varchar(50) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-INSERT INTO `vn`.`docuware` (`code`, `fileCabinetName`, `action`, `dialogName`, `findById`)
- VALUES
- ('deliveryNote', 'Albaranes cliente', 'find', 'find', 'N__ALBAR_N'),
- ('deliveryNote', 'Albaranes cliente', 'store', 'Archivar', 'N__ALBAR_N');
-
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalId`)
- VALUES
- ('Docuware','checkFile','READ','ALLOW','employee'),
- ('Docuware','download','READ','ALLOW','salesPerson'),
- ('Docuware','upload','WRITE','ALLOW','productionAssi'),
- ('Docuware','deliveryNoteEmail','WRITE','ALLOW','salesPerson');
-
-ALTER TABLE `vn`.`docuwareConfig` CHANGE token cookie varchar(1000) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL;
diff --git a/db/.archive/230201/00-kkearSaleChecked.sql b/db/.archive/230201/00-kkearSaleChecked.sql
deleted file mode 100644
index 3ea107da5..000000000
--- a/db/.archive/230201/00-kkearSaleChecked.sql
+++ /dev/null
@@ -1,173 +0,0 @@
-DELETE FROM `salix`.`ACL` WHERE model="SaleChecked";
-DROP TABLE IF EXISTS `vn`.`saleChecked`;
-DROP PROCEDURE IF EXISTS `vn`.`clean`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clean`()
-BEGIN
- DECLARE vDateShort DATETIME;
- DECLARE vOneYearAgo DATE;
- DECLARE vFourYearsAgo DATE;
- DECLARE v18Month DATE;
- DECLARE v26Month DATE;
- DECLARE v3Month DATE;
- DECLARE vTrashId VARCHAR(15);
-
- SET vDateShort = util.VN_CURDATE() - INTERVAL 2 MONTH;
- SET vOneYearAgo = util.VN_CURDATE() - INTERVAL 1 YEAR;
- SET vFourYearsAgo = util.VN_CURDATE() - INTERVAL 4 YEAR;
- SET v18Month = util.VN_CURDATE() - INTERVAL 18 MONTH;
- SET v26Month = util.VN_CURDATE() - INTERVAL 26 MONTH;
- SET v3Month = util.VN_CURDATE() - INTERVAL 3 MONTH;
-
- DELETE FROM ticketParking WHERE created < vDateShort;
- DELETE FROM routesMonitor WHERE dated < vDateShort;
- DELETE FROM workerTimeControlLog WHERE created < vDateShort;
- DELETE FROM `message` WHERE sendDate < vDateShort;
- DELETE FROM messageInbox WHERE sendDate < vDateShort;
- DELETE FROM messageInbox WHERE sendDate < vDateShort;
- DELETE FROM workerTimeControl WHERE timed < vFourYearsAgo;
- DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0;
- DELETE FROM ticketDown WHERE created < TIMESTAMPADD(DAY,-1,util.VN_CURDATE());
- DELETE FROM entryLog WHERE creationDate < vDateShort;
- DELETE IGNORE FROM expedition WHERE created < v26Month;
- DELETE FROM sms WHERE created < v18Month;
- DELETE FROM saleTracking WHERE created < vOneYearAgo;
- DELETE FROM ticketTracking WHERE created < v18Month;
- DELETE tobs FROM ticketObservation tobs
- JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
- DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo;
- DELETE FROM sharingCart where ended < vDateShort;
- DELETE FROM sharingClient where ended < vDateShort;
- DELETE tw.* FROM ticketWeekly tw
- LEFT JOIN sale s ON s.ticketFk = tw.ticketFk WHERE s.itemFk IS NULL;
- DELETE FROM claim WHERE ticketCreated < vFourYearsAgo;
- DELETE FROM message WHERE sendDate < vDateShort;
- -- Robert ubicacion anterior de trevelLog comentario para debug
- DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Month;
- DELETE bm
- FROM buyMark bm
- JOIN buy b ON b.id = bm.id
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed <= vDateShort;
- DELETE FROM vn.buy WHERE created < vDateShort AND entryFk = 9200;
- DELETE FROM vn.itemShelvingLog WHERE created < vDateShort;
- DELETE FROM vn.stockBuyed WHERE creationDate < vDateShort;
- DELETE FROM vn.itemCleanLog WHERE created < util.VN_NOW() - INTERVAL 1 YEAR;
- DELETE FROM printQueue WHERE statusCode = 'printed' AND created < vDateShort;
-
- -- Equipos duplicados
- DELETE w.*
- FROM workerTeam w
- JOIN (SELECT id, team, workerFk, COUNT(*) - 1 as duplicated
- FROM workerTeam
- GROUP BY team,workerFk
- HAVING duplicated
- ) d ON d.team = w.team AND d.workerFk = w.workerFk AND d.id != w.id;
-
- DELETE sc
- FROM saleComponent sc
- JOIN sale s ON s.id= sc.saleFk
- JOIN ticket t ON t.id= s.ticketFk
- WHERE t.shipped < v18Month;
-
- DELETE c
- FROM vn.claim c
- JOIN vn.claimState cs ON cs.id = c.claimStateFk
- WHERE cs.description = "Anulado" AND
- c.created < vDateShort;
- DELETE
- FROM vn.expeditionTruck
- WHERE ETD < v3Month;
-
- -- borrar travels sin entradas
- DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete;
- CREATE TEMPORARY TABLE tmp.thermographToDelete
- SELECT th.id,th.dmsFk
- FROM vn.travel t
- LEFT JOIN vn.entry e ON e.travelFk = t.id
- JOIN vn.travelThermograph th ON th.travelFk = t.id
- WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL;
-
- SELECT dt.id INTO vTrashId
- FROM vn.dmsType dt
- WHERE dt.code = 'trash';
-
- UPDATE tmp.thermographToDelete th
- JOIN vn.dms d ON d.id = th.dmsFk
- SET d.dmsTypeFk = vTrashId;
-
- DELETE th
- FROM tmp.thermographToDelete tmp
- JOIN vn.travelThermograph th ON th.id = tmp.id;
-
- DELETE t
- FROM vn.travel t
- LEFT JOIN vn.entry e ON e.travelFk = t.id
- WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL;
-
- UPDATE dms d
- JOIN dmsType dt ON dt.id = d.dmsTypeFk
- SET d.dmsTypeFk = vTrashId
- WHERE created < TIMESTAMPADD(MONTH, -dt.monthToDelete, util.VN_CURDATE());
-
- -- borrar entradas sin compras
- DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete;
- CREATE TEMPORARY TABLE tmp.entryToDelete
- SELECT e.*
- FROM vn.entry e
- LEFT JOIN vn.buy b ON b.entryFk = e.id
- JOIN vn.entryConfig ec ON e.id != ec.defaultEntry
- WHERE e.dated < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND b.entryFK IS NULL;
-
- DELETE e
- FROM vn.entry e
- JOIN tmp.entryToDelete tmp ON tmp.id = e.id;
-
- -- borrar de route registros menores a 4 años
- DROP TEMPORARY TABLE IF EXISTS tmp.routeToDelete;
- CREATE TEMPORARY TABLE tmp.routeToDelete
- SELECT *
- FROM vn.route r
- WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE());
-
- UPDATE tmp.routeToDelete tmp
- JOIN vn.dms d ON d.id = tmp.gestdocFk
- SET d.dmsTypeFk = vTrashId;
-
- DELETE r
- FROM tmp.routeToDelete tmp
- JOIN vn.route r ON r.id = tmp.id;
-
- -- borrar registros de dua y awb menores a 2 años
- DROP TEMPORARY TABLE IF EXISTS tmp.duaToDelete;
- CREATE TEMPORARY TABLE tmp.duaToDelete
- SELECT *
- FROM vn.dua
- WHERE operated < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
-
- UPDATE tmp.duaToDelete tm
- JOIN vn.dms d ON d.id = tm.gestdocFk
- SET d.dmsTypeFk = vTrashId;
-
- DELETE d
- FROM tmp.duaToDelete tmp
- JOIN vn.dua d ON d.id = tmp.id;
-
- DELETE FROM vn.awb WHERE created < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
-
- -- Borra los registros de collection y ticketcollection
- DELETE FROM vn.collection WHERE created < vDateShort;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete;
- DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete;
- DROP TEMPORARY TABLE IF EXISTS tmp.duaToDelete;
-
- DELETE FROM travelLog WHERE creationDate < v3Month;
-
- CALL shelving_clean;
-
-END$$
-DELIMITER ;
diff --git a/db/.archive/230201/00-validPriorities_ItemConfig.sql b/db/.archive/230201/00-validPriorities_ItemConfig.sql
deleted file mode 100644
index 0b32d5de8..000000000
--- a/db/.archive/230201/00-validPriorities_ItemConfig.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-ALTER TABLE `vn`.`itemConfig` ADD defaultTag INT DEFAULT 56 NOT NULL;
-ALTER TABLE `vn`.`itemConfig` ADD CONSTRAINT itemConfig_FK FOREIGN KEY (defaultTag) REFERENCES vn.tag(id);
-ALTER TABLE `vn`.`itemConfig` ADD validPriorities varchar(50) DEFAULT '[1,2,3]' NOT NULL;
-ALTER TABLE `vn`.`itemConfig` ADD defaultPriority INT DEFAULT 2 NOT NULL;
-ALTER TABLE `vn`.`item` MODIFY COLUMN relevancy tinyint(1) DEFAULT 0 NOT NULL COMMENT 'La web ordena de forma descendiente por este campo para mostrar los artículos';
diff --git a/db/.archive/230201/00-workerTimeControlConfig.sql b/db/.archive/230201/00-workerTimeControlConfig.sql
deleted file mode 100644
index c04acd936..000000000
--- a/db/.archive/230201/00-workerTimeControlConfig.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-ALTER TABLE `vn`.`workerTimeControlConfig` ADD teleworkingStart INT NULL COMMENT 'Hora comienzo jornada de los teletrabajdores expresada en segundos';
-ALTER TABLE `vn`.`workerTimeControlConfig` ADD teleworkingStartBreakTime INT NULL COMMENT 'Hora comienzo descanso de los teletrabjadores expresada en segundos';
-
-UPDATE `vn`.`workerTimeControlConfig`
- SET `teleworkingStart`=28800, `teleworkingStartBreakTime`=32400
-WHERE `id`=1;
diff --git a/db/.archive/230202/00-itemConfig.sql b/db/.archive/230202/00-itemConfig.sql
deleted file mode 100644
index 0b32d5de8..000000000
--- a/db/.archive/230202/00-itemConfig.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-ALTER TABLE `vn`.`itemConfig` ADD defaultTag INT DEFAULT 56 NOT NULL;
-ALTER TABLE `vn`.`itemConfig` ADD CONSTRAINT itemConfig_FK FOREIGN KEY (defaultTag) REFERENCES vn.tag(id);
-ALTER TABLE `vn`.`itemConfig` ADD validPriorities varchar(50) DEFAULT '[1,2,3]' NOT NULL;
-ALTER TABLE `vn`.`itemConfig` ADD defaultPriority INT DEFAULT 2 NOT NULL;
-ALTER TABLE `vn`.`item` MODIFY COLUMN relevancy tinyint(1) DEFAULT 0 NOT NULL COMMENT 'La web ordena de forma descendiente por este campo para mostrar los artículos';
diff --git a/db/.archive/230401/00-ACL.sql b/db/.archive/230401/00-ACL.sql
deleted file mode 100644
index ae9f781f7..000000000
--- a/db/.archive/230401/00-ACL.sql
+++ /dev/null
@@ -1,18 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
-VALUES ('VnUser', '*', '*', 'ALLOW', 'ROLE', 'employee');
-
-INSERT INTO `salix`.`ACL` (id, model, property, accessType, permission, principalType, principalId)
-VALUES ('VnUser', 'acl', 'READ', 'ALLOW', 'ROLE', 'account');
-
-INSERT INTO `salix`.`ACL` (id, model, property, accessType, permission, principalType, principalId)
-VALUES ('VnUser', 'getCurrentUserData', 'READ', 'ALLOW', 'ROLE', 'account');
-
-INSERT INTO `salix`.`ACL` (id, model, property, accessType, permission, principalType, principalId)
-VALUES ('VnUser', 'changePassword', '*', 'ALLOW', 'ROLE', 'account');
-
-
-
-UPDATE `hedera`.`imageCollection` t
-SET t.model = 'VnUser'
-WHERE t.id = 6;
-
diff --git a/db/.archive/230401/00-ACL_tag_update.sql b/db/.archive/230401/00-ACL_tag_update.sql
deleted file mode 100644
index 3c103e990..000000000
--- a/db/.archive/230401/00-ACL_tag_update.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Tag', 'onSubmit', 'WRITE', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/.archive/230401/00-createWorker.sql b/db/.archive/230401/00-createWorker.sql
deleted file mode 100644
index 7ca2c41ee..000000000
--- a/db/.archive/230401/00-createWorker.sql
+++ /dev/null
@@ -1,24 +0,0 @@
-UPDATE `salix`.`ACL`
-SET accessType='READ'
-WHERE model='Worker'
- AND property='*'
- AND accessType='*'
- AND permission='ALLOW'
- AND principalType='ROLE'
- AND principalId='employee';
-
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Worker', 'updateAttributes', 'WRITE', 'ALLOW', 'ROLE', 'hr'),
- ('Worker', 'createAbsence', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'updateAbsence', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'deleteAbsence', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'new', 'WRITE', 'ALLOW', 'ROLE', 'hr'),
- ('Role', '*', 'READ', 'ALLOW', 'ROLE', 'hr');
-
-ALTER TABLE `vn`.`workerConfig` ADD roleFk int(10) unsigned NOT NULL COMMENT 'Rol por defecto al dar de alta un trabajador nuevo';
-UPDATE `vn`.`workerConfig`
- SET roleFk = 1
- WHERE id = 1;
-
diff --git a/db/.archive/230401/00-ticket_canAdvance.sql b/db/.archive/230401/00-ticket_canAdvance.sql
deleted file mode 100644
index fd9d451bf..000000000
--- a/db/.archive/230401/00-ticket_canAdvance.sql
+++ /dev/null
@@ -1,110 +0,0 @@
-DROP PROCEDURE IF EXISTS vn.ticket_canAdvance;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT)
-BEGIN
-/**
- * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar.
- *
- * @param vDateFuture Fecha de los tickets que se quieren adelantar.
- * @param vDateToAdvance Fecha a cuando se quiere adelantar.
- * @param vWarehouseFk Almacén
- */
-
- DECLARE vDateInventory DATE;
-
- SELECT inventoried INTO vDateInventory FROM vn.config;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.stock;
- CREATE TEMPORARY TABLE tmp.stock
- (itemFk INT PRIMARY KEY,
- amount INT)
- ENGINE = MEMORY;
-
- INSERT INTO tmp.stock(itemFk, amount)
- SELECT itemFk, SUM(quantity) amount FROM
- (
- SELECT itemFk, quantity
- FROM vn.itemTicketOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM vn.itemEntryIn
- WHERE landed >= vDateInventory
- AND landed < vDateFuture
- AND isVirtualStock = FALSE
- AND warehouseInFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM vn.itemEntryOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseOutFk = vWarehouseFk
- ) t
- GROUP BY itemFk HAVING amount != 0;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.filter;
- CREATE TEMPORARY TABLE tmp.filter
- (INDEX (id))
- SELECT s.ticketFk futureId,
- t2.ticketFk id,
- count(DISTINCT s.id) saleCount,
- t2.state,
- t2.isNotValidated,
- st.name futureState,
- st.isNotValidated futureIsNotValidated,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
- t2.ipt,
- t.workerFk,
- CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
- CAST(COUNT(*) AS DECIMAL(10,0)) `futureLines`,
- t2.shipped,
- t.shipped futureShipped,
- t2.totalWithVat,
- t.totalWithVat futureTotalWithVat,
- t2.agency,
- am.name futureAgency,
- t2.lines,
- t2.liters,
- SUM((s.quantity <= IFNULL(st.amount,0))) hasStock
- FROM vn.ticket t
- JOIN vn.ticketState ts ON ts.ticketFk = t.id
- JOIN vn.state st ON st.id = ts.stateFk
- JOIN vn.saleVolume sv ON t.id = sv.ticketFk
- JOIN (SELECT
- t2.id ticketFk,
- t2.addressFk,
- st.isNotValidated,
- st.name state,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
- t2.shipped,
- t2.totalWithVat,
- am.name agency,
- CAST(SUM(litros) AS DECIMAL(10,0)) liters,
- CAST(COUNT(*) AS DECIMAL(10,0)) `lines`
- FROM vn.ticket t2
- JOIN vn.saleVolume sv ON t2.id = sv.ticketFk
- JOIN vn.sale s ON s.ticketFk = t2.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.ticketState ts ON ts.ticketFk = t2.id
- JOIN vn.state st ON st.id = ts.stateFk
- JOIN vn.agencyMode am ON t2.agencyModeFk = am.id
- LEFT JOIN vn.itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- WHERE t2.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance)
- AND t2.warehouseFk = vWarehouseFk
- GROUP BY t2.id) t2 ON t2.addressFk = t.addressFk
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.agencyMode am ON t.agencyModeFk = am.id
- LEFT JOIN vn.itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- LEFT JOIN tmp.stock st ON st.itemFk = s.itemFk
- WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
- AND t.warehouseFk = vWarehouseFk
- GROUP BY t.id;
-
- DROP TEMPORARY TABLE tmp.stock;
-END$$
-DELIMITER ;
diff --git a/db/.archive/230401/00-updateIsToBeMailed.sql b/db/.archive/230401/00-updateIsToBeMailed.sql
deleted file mode 100644
index 1bb177f57..000000000
--- a/db/.archive/230401/00-updateIsToBeMailed.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-UPDATE `vn`.`client`
- SET isToBeMailed = FALSE
- WHERE
- mailAddress is NULL
- AND email is NULL
- AND isToBeMailed = TRUE;
diff --git a/db/.archive/230403/00-clienteCompensado.sql b/db/.archive/230403/00-clienteCompensado.sql
deleted file mode 100644
index ff1982b93..000000000
--- a/db/.archive/230403/00-clienteCompensado.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Client', 'getClientOrSupplierReference', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/.archive/230404/00-ticket_canAdvance.sql b/db/.archive/230404/00-ticket_canAdvance.sql
deleted file mode 100644
index d7386e9d1..000000000
--- a/db/.archive/230404/00-ticket_canAdvance.sql
+++ /dev/null
@@ -1,127 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`ticket_canAdvance`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT)
-BEGIN
-/**
- * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar.
- *
- * @param vDateFuture Fecha de los tickets que se quieren adelantar.
- * @param vDateToAdvance Fecha a cuando se quiere adelantar.
- * @param vWarehouseFk Almacén
- */
-
- DECLARE vDateInventory DATE;
-
- SELECT inventoried INTO vDateInventory FROM config;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.stock;
- CREATE TEMPORARY TABLE tmp.stock
- (itemFk INT PRIMARY KEY,
- amount INT)
- ENGINE = MEMORY;
-
- INSERT INTO tmp.stock(itemFk, amount)
- SELECT itemFk, SUM(quantity) amount FROM
- (
- SELECT itemFk, quantity
- FROM itemTicketOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM itemEntryIn
- WHERE landed >= vDateInventory
- AND landed < vDateFuture
- AND isVirtualStock = FALSE
- AND warehouseInFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM itemEntryOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseOutFk = vWarehouseFk
- ) t
- GROUP BY itemFk HAVING amount != 0;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.filter;
- CREATE TEMPORARY TABLE tmp.filter
- (INDEX (id))
-
- SELECT
- origin.ticketFk futureId,
- dest.ticketFk id,
- dest.state,
- origin.futureState,
- origin.futureIpt,
- dest.ipt,
- origin.workerFk,
- origin.futureLiters,
- origin.futureLines,
- dest.shipped,
- origin.shipped futureShipped,
- dest.totalWithVat,
- origin.totalWithVat futureTotalWithVat,
- dest.agency,
- origin.futureAgency,
- dest.lines,
- dest.liters,
- origin.futureLines - origin.hasStock AS notMovableLines,
- (origin.futureLines = origin.hasStock) AS isFullMovable
- FROM (
- SELECT
- s.ticketFk,
- t.workerFk,
- t.shipped,
- t.totalWithVat,
- st.name futureState,
- t.addressFk,
- am.name futureAgency,
- count(s.id) futureLines,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
- CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
- SUM((s.quantity <= IFNULL(st.amount,0))) hasStock
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN saleVolume sv ON sv.saleFk = s.id
- JOIN item i ON i.id = s.itemFk
- JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN state st ON st.id = ts.stateFk
- JOIN agencyMode am ON t.agencyModeFk = am.id
- LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- LEFT JOIN tmp.stock st ON st.itemFk = i.id
- WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
- AND t.warehouseFk = vWarehouseFk
- GROUP BY t.id
- ) origin
- JOIN (
- SELECT
- t.id ticketFk,
- t.addressFk,
- st.name state,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
- t.shipped,
- t.totalWithVat,
- am.name agency,
- CAST(SUM(litros) AS DECIMAL(10,0)) liters,
- CAST(COUNT(*) AS DECIMAL(10,0)) `lines`
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN saleVolume sv ON sv.saleFk = s.id
- JOIN item i ON i.id = s.itemFk
- JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN state st ON st.id = ts.stateFk
- JOIN agencyMode am ON t.agencyModeFk = am.id
- LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance)
- AND t.warehouseFk = vWarehouseFk
- AND st.order <= 5
- GROUP BY t.id
- ) dest ON dest.addressFk = origin.addressFk
- WHERE origin.hasStock != 0;
-
- DROP TEMPORARY TABLE tmp.stock;
-END$$
-DELIMITER ;
diff --git a/db/.archive/230601/00-acl_claim.sql b/db/.archive/230601/00-acl_claim.sql
deleted file mode 100644
index 4e680eb4f..000000000
--- a/db/.archive/230601/00-acl_claim.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES('ClaimBeginning', 'isEditable', 'READ', 'ALLOW', 'ROLE', 'employee');
-
-DELETE FROM `salix`.`ACL`
- WHERE model='Claim' AND property='isEditable';
-
diff --git a/db/.archive/230601/00-acl_notifications.sql b/db/.archive/230601/00-acl_notifications.sql
deleted file mode 100644
index ab40b16a5..000000000
--- a/db/.archive/230601/00-acl_notifications.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (model,property,accessType,principalId)
- VALUES
- ('NotificationSubscription','*','*','employee'),
- ('NotificationAcl','*','READ','employee');
diff --git a/db/.archive/230601/00-itemConfig_warehouseFk.sql b/db/.archive/230601/00-itemConfig_warehouseFk.sql
deleted file mode 100644
index c860986d6..000000000
--- a/db/.archive/230601/00-itemConfig_warehouseFk.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-ALTER TABLE `vn`.`itemConfig` ADD warehouseFk smallint(6) unsigned NULL;
-UPDATE `vn`.`itemConfig`
- SET warehouseFk=60
-WHERE id=0;
diff --git a/db/.archive/230601/00-uniqueKeyNotificationSubscription.sql b/db/.archive/230601/00-uniqueKeyNotificationSubscription.sql
deleted file mode 100644
index 623ecf770..000000000
--- a/db/.archive/230601/00-uniqueKeyNotificationSubscription.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-ALTER TABLE
- `util`.`notificationSubscription`
-ADD
- CONSTRAINT `notificationSubscription_UN` UNIQUE KEY (`notificationFk`, `userFk`);
\ No newline at end of file
diff --git a/db/.archive/230601/01-alter_notSubs.sql b/db/.archive/230601/01-alter_notSubs.sql
deleted file mode 100644
index 07ea7c2bf..000000000
--- a/db/.archive/230601/01-alter_notSubs.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-ALTER TABLE `util`.`notificationSubscription`
-ADD `id` int(11) auto_increment NULL,
-DROP PRIMARY KEY,
-ADD CONSTRAINT PRIMARY KEY (`id`);
-
-ALTER TABLE `util`.`notificationSubscription`
-ADD KEY `notificationSubscription_ibfk_1` (`notificationFk`);
diff --git a/db/.archive/230801/00-acl_itemConfig.sql b/db/.archive/230801/00-acl_itemConfig.sql
deleted file mode 100644
index 8c35022b4..000000000
--- a/db/.archive/230801/00-acl_itemConfig.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('ItemConfig', '*', '*', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/.archive/230801/00-supplierIsVies.sql b/db/.archive/230801/00-supplierIsVies.sql
deleted file mode 100644
index 5861e7615..000000000
--- a/db/.archive/230801/00-supplierIsVies.sql
+++ /dev/null
@@ -1,16 +0,0 @@
-ALTER TABLE `vn`.`supplier` ADD `isVies` tinyint(4) DEFAULT 0 NOT NULL;
-
-UPDATE `vn`.`supplier` s
- JOIN vn.country c ON c.id = s.countryFk
- SET s.nif = MID(s.nif, 3, LENGTH(s.nif)-1), s.isVies = TRUE
-WHERE s.nif <> TRIM(IF(c.code = LEFT(s.nif, 2), MID(s.nif, 3, LENGTH(s.nif)-1), s.nif));
-
-INSERT IGNORE INTO `vn`.`chat`
-(senderFk, recipient, checkUserStatus, message, status, attempts)
-VALUES(19263, '#informatica-cau', 0, '
-```
-UPDATE `vn`.`supplier` s
- JOIN vn.country c ON c.id = s.countryFk
- SET s.nif = MID(s.nif, 3, LENGTH(s.nif)-1), s.isVies = TRUE
-WHERE s.nif <> TRIM(IF(c.code = LEFT(s.nif, 2), MID(s.nif, 3, LENGTH(s.nif)-1), s.nif));
-```', 0, 0);
diff --git a/db/.archive/230801/00-workerLocker.sql b/db/.archive/230801/00-workerLocker.sql
deleted file mode 100644
index 0a72cca1e..000000000
--- a/db/.archive/230801/00-workerLocker.sql
+++ /dev/null
@@ -1,15 +0,0 @@
-ALTER TABLE `vn`.`worker` ADD locker INT UNSIGNED NULL UNIQUE;
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('DeviceProduction', '*', '*', 'ALLOW', 'ROLE', 'hr'),
- ('DeviceProductionModels', '*', '*', 'ALLOW', 'ROLE', 'hr'),
- ('DeviceProductionState', '*', '*', 'ALLOW', 'ROLE', 'hr'),
- ('DeviceProductionUser', '*', '*', 'ALLOW', 'ROLE', 'hr'),
- ('DeviceProduction', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('DeviceProductionModels', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('DeviceProductionState', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('DeviceProductionUser', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('Worker', 'deallocatePDA', '*', 'ALLOW', 'ROLE', 'hr'),
- ('Worker', 'allocatePDA', '*', 'ALLOW', 'ROLE', 'hr'),
- ('Worker', 'deallocatePDA', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('Worker', 'allocatePDA', '*', 'ALLOW', 'ROLE', 'productionAssi');
diff --git a/db/.archive/231001/00-delivery.sql b/db/.archive/231001/00-delivery.sql
deleted file mode 100644
index 3a9269183..000000000
--- a/db/.archive/231001/00-delivery.sql
+++ /dev/null
@@ -1,74 +0,0 @@
-DROP TABLE `vn`.`dmsRecover`;
-
-ALTER TABLE `vn`.`delivery` DROP FOREIGN KEY delivery_FK;
-ALTER TABLE `vn`.`delivery` DROP COLUMN addressFk;
-ALTER TABLE `vn`.`delivery` ADD ticketFk INT NOT NULL;
-ALTER TABLE `vn`.`delivery` ADD CONSTRAINT delivery_ticketFk_FK FOREIGN KEY (`ticketFk`) REFERENCES `vn`.`ticket`(`id`);
-
-DELETE FROM `salix`.`ACL` WHERE `property` = 'saveSign';
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalId`)
- VALUES
- ('Ticket','saveSign','WRITE','ALLOW','employee');
-
-DROP PROCEDURE IF EXISTS vn.route_getTickets;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_getTickets`(vRouteFk INT)
-BEGIN
-/**
- * Pasado un RouteFk devuelve la información
- * de sus tickets.
- *
- * @param vRouteFk
- *
- * @select Información de los tickets
- */
-
- SELECT
- t.id Id,
- t.clientFk Client,
- a.id Address,
- t.packages Packages,
- a.street AddressName,
- a.postalCode PostalCode,
- a.city City,
- sub2.itemPackingTypeFk PackingType,
- c.phone ClientPhone,
- c.mobile ClientMobile,
- a.phone AddressPhone,
- a.mobile AddressMobile,
- d.longitude Longitude,
- d.latitude Latitude,
- wm.mediaValue SalePersonPhone,
- tob.Note Note,
- t.isSigned Signed
- FROM ticket t
- JOIN client c ON t.clientFk = c.id
- JOIN address a ON t.addressFk = a.id
- LEFT JOIN delivery d ON t.id = d.ticketFk
- LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk
- LEFT JOIN
- (SELECT tob.description Note, t.id
- FROM ticketObservation tob
- JOIN ticket t ON tob.ticketFk = t.id
- JOIN observationType ot ON ot.id = tob.observationTypeFk
- WHERE t.routeFk = vRouteFk
- AND ot.code = 'delivery'
- )tob ON tob.id = t.id
- LEFT JOIN
- (SELECT sub.ticketFk,
- CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeFk
- FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- WHERE t.routeFk = vRouteFk
- GROUP BY t.id,i.itemPackingTypeFk)sub
- GROUP BY sub.ticketFk
- ) sub2 ON sub2.ticketFk = t.id
- WHERE t.routeFk = vRouteFk
- GROUP BY t.id
- ORDER BY t.priority;
-END$$
-DELIMITER ;
diff --git a/db/.archive/231001/00-invoiceOut.sql b/db/.archive/231001/00-invoiceOut.sql
deleted file mode 100644
index 4404c8f4a..000000000
--- a/db/.archive/231001/00-invoiceOut.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-ALTER TABLE vn.invoiceOutSerial
- ADD `type` ENUM('global', 'quick') DEFAULT NULL NULL;
-
- UPDATE vn.invoiceOutSerial
- SET type = 'global'
- WHERE code IN ('A','V');
\ No newline at end of file
diff --git a/db/.archive/231001/00-report.sql b/db/.archive/231001/00-report.sql
deleted file mode 100644
index 0bc7c8da4..000000000
--- a/db/.archive/231001/00-report.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-UPDATE `vn`.`report`
- SET `method`='InvoiceOuts/{refFk}/invoice-out-pdf'
-WHERE name='invoice';
-
-ALTER TABLE `vn`.`printQueue` MODIFY COLUMN printerFk tinyint(3) unsigned DEFAULT 82 NOT NULL;
-
diff --git a/db/.archive/231001/02-invoiceOut_new.sql b/db/.archive/231001/02-invoiceOut_new.sql
deleted file mode 100644
index d2b96eff7..000000000
--- a/db/.archive/231001/02-invoiceOut_new.sql
+++ /dev/null
@@ -1,258 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`invoiceOut_new`;
-
-DELIMITER $$
-$$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOut_new`(
- vSerial VARCHAR(255),
- vInvoiceDate DATE,
- vTaxArea VARCHAR(25),
- OUT vNewInvoiceId INT)
-BEGIN
-/**
- * Creación de facturas emitidas.
- * requiere previamente tabla tmp.ticketToInvoice(id).
- *
- * @param vSerial serie a la cual se hace la factura
- * @param vInvoiceDate fecha de la factura
- * @param vTaxArea tipo de iva en relacion a la empresa y al cliente
- * @param vNewInvoiceId id de la factura que se acaba de generar
- * @return vNewInvoiceId
- */
- DECLARE vIsAnySaleToInvoice BOOL;
- DECLARE vIsAnyServiceToInvoice BOOL;
- DECLARE vNewRef VARCHAR(255);
- DECLARE vWorker INT DEFAULT account.myUser_getId();
- DECLARE vCompanyFk INT;
- DECLARE vInterCompanyFk INT;
- DECLARE vClientFk INT;
- DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1;
- DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6;
- DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2;
- DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R';
- DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S';
- DECLARE vNewInvoiceInFk INT;
- DECLARE vIsInterCompany BOOL DEFAULT FALSE;
- DECLARE vIsCEESerial BOOL DEFAULT FALSE;
- DECLARE vIsCorrectInvoiceDate BOOL;
- DECLARE vMaxShipped DATE;
-
- SET vInvoiceDate = IFNULL(vInvoiceDate, util.CURDATE());
-
- SELECT t.clientFk,
- t.companyFk,
- MAX(DATE(t.shipped)),
- DATE(vInvoiceDate) >= invoiceOut_getMaxIssued(
- vSerial,
- t.companyFk,
- YEAR(vInvoiceDate))
- INTO vClientFk,
- vCompanyFk,
- vMaxShipped,
- vIsCorrectInvoiceDate
- FROM tmp.ticketToInvoice tt
- JOIN ticket t ON t.id = tt.id;
-
- IF(vMaxShipped > vInvoiceDate) THEN
- CALL util.throw("Invoice date can't be less than max date");
- END IF;
-
- IF NOT vIsCorrectInvoiceDate THEN
- CALL util.throw('Exists an invoice with a previous date');
- END IF;
-
- -- Eliminem de tmp.ticketToInvoice els tickets que no han de ser facturats
- DELETE ti.*
- FROM tmp.ticketToInvoice ti
- JOIN ticket t ON t.id = ti.id
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- JOIN supplier su ON su.id = t.companyFk
- JOIN client c ON c.id = t.clientFk
- LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = su.countryFk
- WHERE (YEAR(t.shipped) < 2001 AND t.isDeleted)
- OR c.isTaxDataChecked = FALSE
- OR t.isDeleted
- OR c.hasToInvoice = FALSE
- OR itc.id IS NULL;
-
- SELECT SUM(s.quantity * s.price * (100 - s.discount)/100) <> 0
- INTO vIsAnySaleToInvoice
- FROM tmp.ticketToInvoice t
- JOIN sale s ON s.ticketFk = t.id;
-
- SELECT COUNT(*) > 0 INTO vIsAnyServiceToInvoice
- FROM tmp.ticketToInvoice t
- JOIN ticketService ts ON ts.ticketFk = t.id;
-
- IF (vIsAnySaleToInvoice OR vIsAnyServiceToInvoice)
- AND (vCorrectingSerial = vSerial OR NOT hasAnyNegativeBase())
- THEN
-
- -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial
- INSERT INTO invoiceOut(
- ref,
- serial,
- issued,
- clientFk,
- dued,
- companyFk,
- cplusInvoiceType477Fk
- )
- SELECT
- 1,
- vSerial,
- vInvoiceDate,
- vClientFk,
- getDueDate(vInvoiceDate, dueDay),
- vCompanyFk,
- IF(vSerial = vCorrectingSerial,
- vCplusCorrectingInvoiceTypeFk,
- IF(vSerial = vSimplifiedSerial,
- vCplusSimplifiedInvoiceTypeFk,
- vCplusStandardInvoiceTypeFk))
- FROM client
- WHERE id = vClientFk;
-
- SET vNewInvoiceId = LAST_INSERT_ID();
-
- SELECT `ref`
- INTO vNewRef
- FROM invoiceOut
- WHERE id = vNewInvoiceId;
-
- UPDATE ticket t
- JOIN tmp.ticketToInvoice ti ON ti.id = t.id
- SET t.refFk = vNewRef;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.updateInter;
- CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY
- SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador
- FROM tmp.ticketToInvoice ti
- LEFT JOIN ticketState ts ON ti.id = ts.ticket
- JOIN state s
- WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = getAlert3State(ti.id);
-
- INSERT INTO ticketTracking(stateFk,ticketFk,workerFk)
- SELECT * FROM tmp.updateInter;
-
- INSERT INTO ticketLog (action, userFk, originFk, description)
- SELECT 'UPDATE', account.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef)
- FROM tmp.ticketToInvoice ti;
-
- CALL invoiceExpenceMake(vNewInvoiceId);
- CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
-
- UPDATE invoiceOut io
- JOIN (
- SELECT SUM(amount) total
- FROM invoiceOutExpence
- WHERE invoiceOutFk = vNewInvoiceId
- ) base
- JOIN (
- SELECT SUM(vat) total
- FROM invoiceOutTax
- WHERE invoiceOutFk = vNewInvoiceId
- ) vat
- SET io.amount = base.total + vat.total
- WHERE io.id = vNewInvoiceId;
-
- DROP TEMPORARY TABLE tmp.updateInter;
-
- SELECT COUNT(*), id
- INTO vIsInterCompany, vInterCompanyFk
- FROM company
- WHERE clientFk = vClientFk;
-
- IF (vIsInterCompany) THEN
-
- INSERT INTO invoiceIn(supplierFk, supplierRef, issued, companyFk)
- SELECT vCompanyFk, vNewRef, vInvoiceDate, vInterCompanyFk;
-
- SET vNewInvoiceInFk = LAST_INSERT_ID();
-
- DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
- CREATE TEMPORARY TABLE tmp.ticket
- (KEY (ticketFk))
- ENGINE = MEMORY
- SELECT id ticketFk
- FROM tmp.ticketToInvoice;
-
- CALL `ticket_getTax`('NATIONAL');
-
- SET @vTaxableBaseServices := 0.00;
- SET @vTaxCodeGeneral := NULL;
-
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInFk,
- @vTaxableBaseServices,
- sub.expenceFk,
- sub.taxTypeSageFk,
- sub.transactionTypeSageFk
- FROM (
- SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase,
- i.expenceFk,
- i.taxTypeSageFk,
- i.transactionTypeSageFk,
- @vTaxCodeGeneral := i.taxClassCodeFk
- FROM tmp.ticketServiceTax tst
- JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code
- WHERE i.isService
- HAVING taxableBase
- ) sub;
-
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInFk,
- SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral,
- @vTaxableBaseServices, 0) taxableBase,
- i.expenceFk,
- i.taxTypeSageFk ,
- i.transactionTypeSageFk
- FROM tmp.ticketTax tt
- JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code
- WHERE !i.isService
- GROUP BY tt.pgcFk
- HAVING taxableBase
- ORDER BY tt.priority;
-
- CALL invoiceInDueDay_calculate(vNewInvoiceInFk);
-
- SELECT COUNT(*) INTO vIsCEESerial
- FROM invoiceOutSerial
- WHERE code = vSerial;
-
- IF vIsCEESerial THEN
-
- INSERT INTO invoiceInIntrastat (
- invoiceInFk,
- intrastatFk,
- amount,
- stems,
- countryFk,
- net)
- SELECT
- vNewInvoiceInFk,
- i.intrastatFk,
- SUM(CAST((s.quantity * s.price * (100 - s.discount) / 100 ) AS DECIMAL(10, 2))),
- SUM(CAST(IFNULL(i.stems, 1) * s.quantity AS DECIMAL(10, 2))),
- su.countryFk,
- CAST(SUM(IFNULL(i.stems, 1)
- * s.quantity
- * IF(ic.grams, ic.grams, IFNULL(i.weightByPiece, 0)) / 1000) AS DECIMAL(10, 2))
- FROM sale s
- JOIN ticket t ON s.ticketFk = t.id
- JOIN supplier su ON su.id = t.companyFk
- JOIN item i ON i.id = s.itemFk
- LEFT JOIN itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk
- WHERE t.refFk = vNewRef
- GROUP BY i.intrastatFk;
-
- END IF;
- DROP TEMPORARY TABLE tmp.ticket;
- DROP TEMPORARY TABLE tmp.ticketAmount;
- DROP TEMPORARY TABLE tmp.ticketTax;
- DROP TEMPORARY TABLE tmp.ticketServiceTax;
- END IF;
- END IF;
- DROP TEMPORARY TABLE tmp.`ticketToInvoice`;
-END$$
-DELIMITER ;
diff --git a/db/.gitignore b/db/.gitignore
index 34fb91784..54ed9df77 100644
--- a/db/.gitignore
+++ b/db/.gitignore
@@ -1 +1,11 @@
-config.*.ini
+.DS_Store
+node_modules
+remotes/*.ini
+!remotes/local.ini
+!remotes/docker.ini
+dump/.changes
+dump/fixtures.local.sql
+.dBeaver
+.idea
+.project
+.dbeaver/
diff --git a/db/.pullinfo.json b/db/.pullinfo.json
new file mode 100644
index 000000000..f4afbc5fb
--- /dev/null
+++ b/db/.pullinfo.json
@@ -0,0 +1,16 @@
+{
+ "lastPull": "2024-02-15T08:58:24.000Z",
+ "shaSums": {
+ "srt": {
+ "view": {
+ "routePalletized": "765f8933a6a5a86dfe8f22825cc77351bc8620cdf1be9d3f25abb130460f3a61",
+ "ticketPalletized": "c327f3243e717cc607f01d3747967ba68158f90ef1038986b0aa6ae6d5ce7309"
+ }
+ },
+ "vn": {
+ "view": {
+ "expeditionPallet_Print": "288cbd6e8289df083ed5eb1a2c808f7a82ba4c90c8ad9781104808a7a54471fb"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/db/Dockerfile b/db/Dockerfile
deleted file mode 100644
index 8eeed35e5..000000000
--- a/db/Dockerfile
+++ /dev/null
@@ -1,45 +0,0 @@
-FROM mariadb:10.7.7
-
-ENV MYSQL_ROOT_PASSWORD root
-ENV TZ Europe/Madrid
-ARG MOCKDATE=2001-01-01 11:00:00
-ARG DEBIAN_FRONTEND=noninteractive
-
-COPY docker/docker.cnf /etc/mysql/conf.d/
-COPY \
- docker/docker-start.sh \
- docker/docker-init.sh \
- docker/docker-temp-stop.sh \
- docker/docker-dump.sh \
- docker/docker-structure.sh \
- docker/docker-fixtures.sh \
- /usr/local/bin/
-
-RUN mkdir /mysql-data \
- && chown -R mysql:mysql /mysql-data
-
-WORKDIR /docker-boot
-
-COPY \
- import-changes.sh \
- config.ini \
- dump/structure.sql \
- dump/mockDate.sql \
- dump/dumpedFixtures.sql \
- ./
-RUN sed -i -e 's/@mockDate/'"$MOCKDATE"'/g' mockDate.sql \
- && gosu mysql docker-structure.sh
-COPY changes ./changes
-COPY dump/fixtures.sql ./
-RUN gosu mysql docker-fixtures.sh
-
-RUN echo "[INFO] -> Import finished" \
- && rm -rf /docker-boot
-
-USER mysql
-ENTRYPOINT ["docker-start.sh"]
-
-CMD ["mysqld"]
-
-HEALTHCHECK --interval=2s --timeout=10s --retries=200 \
- CMD mysqladmin ping -h 127.0.0.1 -u root --password=root || exit 1
diff --git a/db/changes/231201/00-ACL.sql b/db/changes/231201/00-ACL.sql
deleted file mode 100644
index 47a818977..000000000
--- a/db/changes/231201/00-ACL.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
-VALUES ('Operator', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Operator', '*', 'WRITE', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/231201/00-chatRefactor.sql b/db/changes/231201/00-chatRefactor.sql
deleted file mode 100644
index 66d1bf3bf..000000000
--- a/db/changes/231201/00-chatRefactor.sql
+++ /dev/null
@@ -1,16 +0,0 @@
-ALTER TABLE `vn`.`chat` ADD statusNew enum('pending','sent','error','sending') DEFAULT 'pending' NOT NULL;
-
-UPDATE `vn`.`chat`
- SET statusNew = 'pending'
-WHERE status = 0;
-
-UPDATE `vn`.`chat`
- SET statusNew = 'sent'
-WHERE status = 1;
-
-UPDATE `vn`.`chat`
- SET statusNew = 'error'
-WHERE status = 2;
-
-ALTER TABLE `vn`.`chat` CHANGE status status__ tinyint(1) DEFAULT NULL NULL;
-ALTER TABLE `vn`.`chat` CHANGE statusNew status enum('pending','sent','error','sending') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT 'pending' NOT NULL;
diff --git a/db/changes/231201/00-invoiceInSerial.sql b/db/changes/231201/00-invoiceInSerial.sql
deleted file mode 100644
index de476027c..000000000
--- a/db/changes/231201/00-invoiceInSerial.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-ALTER TABLE `vn`.`invoiceInConfig` ADD daysAgo INT UNSIGNED DEFAULT 45 COMMENT 'Días en el pasado para mostrar facturas en invoiceIn series en salix';
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('InvoiceIn', 'getSerial', 'READ', 'ALLOW', 'ROLE', 'administrative');
diff --git a/db/changes/231201/00-itemType_isFragile.sql b/db/changes/231201/00-itemType_isFragile.sql
deleted file mode 100644
index ecc1bfbb2..000000000
--- a/db/changes/231201/00-itemType_isFragile.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-ALTER TABLE `vn`.`itemType` ADD isFragile tinyint(1) NULL;
-ALTER TABLE `vn`.`itemType` MODIFY COLUMN isFragile tinyint(1) DEFAULT 0 NOT NULL;
-
-UPDATE `vn`.`itemType`
- SET isFragile = 1
-WHERE code IN ('ZKA', 'ZKE');
-
-UPDATE `vn`.`itemType`
- SET isFragile = 1
-WHERE id IN (SELECT it.id
- FROM `vn`.`itemCategory` ic
- JOIN `vn`.`itemType` it ON it.categoryFk = ic.id
- WHERE ic.code = 'plant');
-
diff --git a/db/changes/231201/00-mailACL.sql b/db/changes/231201/00-mailACL.sql
deleted file mode 100644
index ac687818d..000000000
--- a/db/changes/231201/00-mailACL.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId)
-VALUES('Mail', '*', '*', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/231201/00-operator.sql b/db/changes/231201/00-operator.sql
deleted file mode 100644
index 9b7815b41..000000000
--- a/db/changes/231201/00-operator.sql
+++ /dev/null
@@ -1,159 +0,0 @@
-ALTER TABLE `vn`.`operator` ADD sectorFk int(11) NULL;
-ALTER TABLE `vn`.`operator` ADD labelerFk tinyint(3) unsigned NULL;
-ALTER TABLE `vn`.`operator` ADD CONSTRAINT operator_FK_5 FOREIGN KEY (labelerFk) REFERENCES `vn`.`printer`(id) ON DELETE CASCADE ON UPDATE CASCADE;
-
-UPDATE `vn`.`operator` o
-JOIN (SELECT id, sectorFk, labelerFk
- FROM `vn`.`worker`) sub ON sub.id = o.workerFk
- SET o.sectorFk = sub.sectorFk,
- o.labelerFk = sub.labelerFk;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_printSticker`(
- vSelf INT,
- vLabelCount INT
-)
-BEGIN
-/**
- * Prints a yellow label from a collection or a ticket
- *
- * @param vSelf collection or ticket
- * @param vLabelCount number of times the collection has been printed
- */
- DECLARE vPrintArgs JSON DEFAULT JSON_OBJECT('collectionOrTicketFk', vSelf);
-
- IF vLabelCount IS NULL THEN
- INSERT INTO ticketTrolley
- SELECT ticketFk, 1
- FROM ticketCollection
- WHERE collectionFk = vSelf
- ON DUPLICATE KEY UPDATE labelCount = labelCount + 1;
- ELSE
- SET vPrintArgs = JSON_MERGE_PATCH(vPrintArgs, JSON_OBJECT('labelCount', vLabelCount));
- END IF;
-
- CALL report_print(
- 'LabelCollection',
- (SELECT o.labelerFk FROM operator o WHERE o.workerFk = account.myUser_getId()),
- account.myUser_getId(),
- vPrintArgs,
- 'high'
- );
-END$$
-DELIMITER ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionPallet_printLabel`(vSelf INT)
-BEGIN
-/**
- * Calls the report_print procedure and passes it
- * the necessary parameters for printing.
- *
- * @param vSelf expeditioPallet id.
- */
- DECLARE vPrinterFk INT;
- DECLARE vUserFk INT DEFAULT account.myUser_getId();
-
- SELECT o.labelerFk INTO vPrinterFk
- FROM operator o
- WHERE o.workerFk = vUserFk;
-
- CALL vn.report_print(
- 'LabelPalletExpedition',
- vPrinterFk,
- account.myUser_getId(),
- JSON_OBJECT('palletFk', vSelf, 'userFk', vUserFk),
- 'high'
- );
-
- UPDATE vn.expeditionPallet
- SET isPrint = TRUE
- WHERE id = vSelf;
-END$$
-DELIMITER ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_getAlternatives`(vShelvingFk VARCHAR(10))
-BEGIN
-/**
- * Devuelve un listado de posibles ubicaciones alternativas a ubicar los item de la matricula
- * del carro que se le ha pasado.
- *
- * @param vShelvingFk matricula del carro
- */
- SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder
- FROM itemShelving is2
- JOIN shelving sh ON sh.code = is2.shelvingFk
- JOIN parking p ON p.id = sh.parkingFk
- JOIN sector s ON s.id = p.sectorFk
- LEFT JOIN operator o ON o.sectorFk = s.id
- LEFT JOIN worker w ON w.sectorFk = s.id AND w.id = account.myUser_getId()
- JOIN warehouse wh ON wh.id = s.warehouseFk
- JOIN itemShelving is3 ON is3.itemFk = is2.itemFk AND is3.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
- WHERE is2.shelvingFk <> vShelvingFk COLLATE utf8_unicode_ci
- GROUP BY is2.id
- ORDER BY p.pickingOrder DESC;
-END$$
-DELIMITER ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`operator_beforeInsert`
- BEFORE INSERT ON `operator`
- FOR EACH ROW
-BEGIN
- CALL vn.printer_checkSector(NEW.labelerFk, NEW.sectorFk);
-END$$
-DELIMITER ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`operator_beforeUpdate`
- BEFORE UPDATE ON `operator`
- FOR EACH ROW
-BEGIN
- IF NOT (NEW.labelerFk <=> OLD.labelerFk AND NEW.sectorFk <=> OLD.sectorFk) THEN
- CALL vn.printer_checkSector(NEW.labelerFk, NEW.sectorFk);
- END IF;
-END$$
-DELIMITER ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`worker_beforeUpdate`
- BEFORE UPDATE ON `worker`
- FOR EACH ROW
-BEGIN
- IF NOT (NEW.labelerFk <=> OLD.labelerFk AND NEW.sectorFk <=> OLD.sectorFk) THEN
- CALL vn.printer_checkSector(NEW.labelerFk, NEW.sectorFk);
-
- INSERT IGNORE INTO vn.operator (workerFk)
- VALUES (NEW.id);
-
- UPDATE operator
- SET labelerFk = NEW.labelerFk,
- sectorFk = NEW.sectorFk
- WHERE workerFk = NEW.id;
- END IF;
-END$$
-DELIMITER ;
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `vn`.`operatorWorkerCode`
-AS SELECT `o`.`workerFk` AS `workerFk`,
- concat(`w`.`firstName`, ' ', `w`.`lastName`) AS `fullName`,
- `w`.`code` AS `code`,
- `o`.`numberOfWagons` AS `numberOfWagons`
-FROM (
- (
- `vn`.`worker` `w`
- JOIN `vn`.`operator` `o` ON(`o`.`workerFk` = `w`.`id`)
- )
- JOIN `vn`.`sector` `s` ON(`o`.`sectorFk` = `s`.`id`)
- )
-WHERE `o`.`sectorFk` IS NOT NULL
- AND `s`.`code` IN (
- 'H2',
- 'H2',
- 'PEQUES_H',
- 'ALTILLO COMP',
- 'ALTILLO ARTI'
- )
\ No newline at end of file
diff --git a/db/changes/231201/00-supplierAccount_deleteTriggers.sql b/db/changes/231201/00-supplierAccount_deleteTriggers.sql
deleted file mode 100644
index d7f9f734a..000000000
--- a/db/changes/231201/00-supplierAccount_deleteTriggers.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-DROP TRIGGER `vn`.`supplierAccount_afterInsert`;
-DROP TRIGGER `vn`.`supplierAccount_afterUpdate`;
-DROP TRIGGER `vn`.`supplierAccount_afterDelete`;
diff --git a/db/changes/231201/00-wagon.sql b/db/changes/231201/00-wagon.sql
deleted file mode 100644
index 9e817bac4..000000000
--- a/db/changes/231201/00-wagon.sql
+++ /dev/null
@@ -1,71 +0,0 @@
-CREATE TABLE `vn`.`wagonType` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `name` varchar(30) NOT NULL UNIQUE,
- `divisible` tinyint(1) NOT NULL DEFAULT 0,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
-
-CREATE TABLE `vn`.`wagonTypeColor` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `name` varchar(30) NOT NULL UNIQUE,
- `rgb` varchar(30) NOT NULL UNIQUE,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
-
-CREATE TABLE `vn`.`wagonTypeTray` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `typeFk` int(11) unsigned,
- `height` int(11) unsigned NOT NULL,
- `colorFk` int(11) unsigned,
- PRIMARY KEY (`id`),
- UNIQUE KEY (`typeFk`,`height`),
- CONSTRAINT `wagonTypeTray_type` FOREIGN KEY (`typeFk`) REFERENCES `wagonType` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `wagonTypeTray_color` FOREIGN KEY (`colorFk`) REFERENCES `wagonTypeColor` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
-
-CREATE TABLE `vn`.`wagonConfig` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `width` int(11) unsigned DEFAULT 1350,
- `height` int(11) unsigned DEFAULT 1900,
- `maxWagonHeight` int(11) unsigned DEFAULT 200,
- `minHeightBetweenTrays` int(11) unsigned DEFAULT 50,
- `maxTrays` int(11) unsigned DEFAULT 6,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
-
-CREATE TABLE `vn`.`collectionWagon` (
- `collectionFk` int(11) NOT NULL,
- `wagonFk` int(11) NOT NULL,
- `position` int(11) unsigned,
- PRIMARY KEY (`collectionFk`,`position`),
- UNIQUE KEY `collectionWagon_unique` (`collectionFk`,`wagonFk`),
- CONSTRAINT `collectionWagon_collection` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `collectionWagon_wagon` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
-
-CREATE TABLE `vn`.`collectionWagonTicket` (
- `ticketFk` int(11) NOT NULL,
- `wagonFk` int(11) NOT NULL,
- `trayFk` int(11) unsigned NOT NULL,
- `side` SET('L', 'R') NULL,
- PRIMARY KEY (`ticketFk`),
- CONSTRAINT `collectionWagonTicket_ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `collectionWagonTicket_wagon` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `collectionWagonTicket_tray` FOREIGN KEY (`trayFk`) REFERENCES `wagonTypeTray` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
-
-ALTER TABLE `vn`.`wagon` ADD `typeFk` int(11) unsigned NOT NULL;
-ALTER TABLE `vn`.`wagon` ADD `label` int(11) unsigned NOT NULL;
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('WagonType', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('WagonTypeColor', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('WagonTypeTray', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('WagonConfig', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('CollectionWagon', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('CollectionWagonTicket', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('Wagon', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('WagonType', 'createWagonType', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('WagonType', 'deleteWagonType', '*', 'ALLOW', 'ROLE', 'productionAssi'),
- ('WagonType', 'editWagonType', '*', 'ALLOW', 'ROLE', 'productionAssi');
-
diff --git a/db/changes/231202/00-delivery.sql b/db/changes/231202/00-delivery.sql
deleted file mode 100644
index 3a9269183..000000000
--- a/db/changes/231202/00-delivery.sql
+++ /dev/null
@@ -1,74 +0,0 @@
-DROP TABLE `vn`.`dmsRecover`;
-
-ALTER TABLE `vn`.`delivery` DROP FOREIGN KEY delivery_FK;
-ALTER TABLE `vn`.`delivery` DROP COLUMN addressFk;
-ALTER TABLE `vn`.`delivery` ADD ticketFk INT NOT NULL;
-ALTER TABLE `vn`.`delivery` ADD CONSTRAINT delivery_ticketFk_FK FOREIGN KEY (`ticketFk`) REFERENCES `vn`.`ticket`(`id`);
-
-DELETE FROM `salix`.`ACL` WHERE `property` = 'saveSign';
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalId`)
- VALUES
- ('Ticket','saveSign','WRITE','ALLOW','employee');
-
-DROP PROCEDURE IF EXISTS vn.route_getTickets;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_getTickets`(vRouteFk INT)
-BEGIN
-/**
- * Pasado un RouteFk devuelve la información
- * de sus tickets.
- *
- * @param vRouteFk
- *
- * @select Información de los tickets
- */
-
- SELECT
- t.id Id,
- t.clientFk Client,
- a.id Address,
- t.packages Packages,
- a.street AddressName,
- a.postalCode PostalCode,
- a.city City,
- sub2.itemPackingTypeFk PackingType,
- c.phone ClientPhone,
- c.mobile ClientMobile,
- a.phone AddressPhone,
- a.mobile AddressMobile,
- d.longitude Longitude,
- d.latitude Latitude,
- wm.mediaValue SalePersonPhone,
- tob.Note Note,
- t.isSigned Signed
- FROM ticket t
- JOIN client c ON t.clientFk = c.id
- JOIN address a ON t.addressFk = a.id
- LEFT JOIN delivery d ON t.id = d.ticketFk
- LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk
- LEFT JOIN
- (SELECT tob.description Note, t.id
- FROM ticketObservation tob
- JOIN ticket t ON tob.ticketFk = t.id
- JOIN observationType ot ON ot.id = tob.observationTypeFk
- WHERE t.routeFk = vRouteFk
- AND ot.code = 'delivery'
- )tob ON tob.id = t.id
- LEFT JOIN
- (SELECT sub.ticketFk,
- CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeFk
- FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- WHERE t.routeFk = vRouteFk
- GROUP BY t.id,i.itemPackingTypeFk)sub
- GROUP BY sub.ticketFk
- ) sub2 ON sub2.ticketFk = t.id
- WHERE t.routeFk = vRouteFk
- GROUP BY t.id
- ORDER BY t.priority;
-END$$
-DELIMITER ;
diff --git a/db/changes/231203/00-delivery.sql b/db/changes/231203/00-delivery.sql
deleted file mode 100644
index 0815ec421..000000000
--- a/db/changes/231203/00-delivery.sql
+++ /dev/null
@@ -1,67 +0,0 @@
-DELETE FROM `salix`.`ACL` WHERE `property` = 'saveSign';
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalId`)
- VALUES
- ('Ticket','saveSign','WRITE','ALLOW','employee');
-
-DROP PROCEDURE IF EXISTS vn.route_getTickets;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_getTickets`(vRouteFk INT)
-BEGIN
-/**
- * Pasado un RouteFk devuelve la información
- * de sus tickets.
- *
- * @param vRouteFk
- *
- * @select Información de los tickets
- */
-
- SELECT
- t.id Id,
- t.clientFk Client,
- a.id Address,
- t.packages Packages,
- a.street AddressName,
- a.postalCode PostalCode,
- a.city City,
- sub2.itemPackingTypeFk PackingType,
- c.phone ClientPhone,
- c.mobile ClientMobile,
- a.phone AddressPhone,
- a.mobile AddressMobile,
- d.longitude Longitude,
- d.latitude Latitude,
- wm.mediaValue SalePersonPhone,
- tob.Note Note,
- t.isSigned Signed
- FROM ticket t
- JOIN client c ON t.clientFk = c.id
- JOIN address a ON t.addressFk = a.id
- LEFT JOIN delivery d ON t.id = d.ticketFk
- LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk
- LEFT JOIN
- (SELECT tob.description Note, t.id
- FROM ticketObservation tob
- JOIN ticket t ON tob.ticketFk = t.id
- JOIN observationType ot ON ot.id = tob.observationTypeFk
- WHERE t.routeFk = vRouteFk
- AND ot.code = 'delivery'
- )tob ON tob.id = t.id
- LEFT JOIN
- (SELECT sub.ticketFk,
- CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeFk
- FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- WHERE t.routeFk = vRouteFk
- GROUP BY t.id,i.itemPackingTypeFk)sub
- GROUP BY sub.ticketFk
- ) sub2 ON sub2.ticketFk = t.id
- WHERE t.routeFk = vRouteFk
- GROUP BY t.id
- ORDER BY t.priority;
-END$$
-DELIMITER ;
diff --git a/db/changes/231204/00-rollbackDelivery.sql b/db/changes/231204/00-rollbackDelivery.sql
deleted file mode 100644
index d7fa6b587..000000000
--- a/db/changes/231204/00-rollbackDelivery.sql
+++ /dev/null
@@ -1,83 +0,0 @@
-CREATE TABLE `vn`.`dmsRecover` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `ticketFk` int(11) DEFAULT NULL,
- `sign` text DEFAULT NULL,
- `created` timestamp NULL DEFAULT current_timestamp(),
- PRIMARY KEY (`id`),
- KEY `ticketFk_idx` (`ticketFk`),
- CONSTRAINT `ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDB AUTO_INCREMENT=31917 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-ALTER TABLE `vn`.`delivery` ADD addressFk INT;
-
-DROP PROCEDURE IF EXISTS `vn`.`route_getTickets`;
-
-DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_getTickets`(vRouteFk INT)
-BEGIN
-/**
- * Pasado un RouteFk devuelve la información
- * de sus tickets.
- *
- * @param vRouteFk
- * @select Información de los tickets
- */
-SELECT *
- FROM (
- SELECT t.id Id,
- t.clientFk Client,
- a.id Address,
- a.nickname ClientName,
- t.packages Packages,
- a.street AddressName,
- a.postalCode PostalCode,
- a.city City,
- sub2.itemPackingTypeFk PackingType,
- c.phone ClientPhone,
- c.mobile ClientMobile,
- a.phone AddressPhone,
- a.mobile AddressMobile,
- d.longitude Longitude,
- d.latitude Latitude,
- wm.mediaValue SalePersonPhone,
- tob.description Note,
- t.isSigned Signed,
- t.priority
- FROM ticket t
- JOIN client c ON t.clientFk = c.id
- JOIN address a ON t.addressFk = a.id
- LEFT JOIN delivery d ON d.addressFk = a.id
- LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk
- LEFT JOIN(
- SELECT tob.description, t.id
- FROM ticketObservation tob
- JOIN ticket t ON tob.ticketFk = t.id
- JOIN observationType ot ON ot.id = tob.observationTypeFk
- WHERE t.routeFk = vRouteFk
- AND ot.code = 'delivery'
- )tob ON tob.id = t.id
- LEFT JOIN(
- SELECT sub.ticketFk,
- CONCAT('(',
- GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk
- ORDER BY sub.items DESC SEPARATOR ','),
- ') ') itemPackingTypeFk
- FROM (
- SELECT s.ticketFk, i.itemPackingTypeFk, COUNT(*) items
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- WHERE t.routeFk = vRouteFk
- GROUP BY t.id, i.itemPackingTypeFk
- )sub
- GROUP BY sub.ticketFk
- )sub2 ON sub2.ticketFk = t.id
- WHERE t.routeFk = vRouteFk
- ORDER BY d.id DESC
- LIMIT 10000000000000000000
- )sub3
- GROUP BY sub3.id
- ORDER BY sub3.priority;
-END$$
-DELIMITER ;
diff --git a/db/changes/231205/00-printQueueArgs.sql b/db/changes/231205/00-printQueueArgs.sql
deleted file mode 100644
index 972031325..000000000
--- a/db/changes/231205/00-printQueueArgs.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`printQueueArgs` MODIFY COLUMN value varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NULL;
diff --git a/db/changes/231401/00-claimBeginningAfterInsert.sql b/db/changes/231401/00-claimBeginningAfterInsert.sql
deleted file mode 100644
index 230b6defb..000000000
--- a/db/changes/231401/00-claimBeginningAfterInsert.sql
+++ /dev/null
@@ -1 +0,0 @@
-DROP TRIGGER IF EXISTS `vn`.`claimBeginning_afterInsert`;
diff --git a/db/changes/231401/00-negativeBases.sql b/db/changes/231401/00-negativeBases.sql
deleted file mode 100644
index 0bdc6f2dc..000000000
--- a/db/changes/231401/00-negativeBases.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('InvoiceIn', 'negativeBases', 'READ', 'ALLOW', 'ROLE', 'administrative'),
- ('InvoiceIn', 'negativeBasesCsv', 'READ', 'ALLOW', 'ROLE', 'administrative');
diff --git a/db/changes/231401/00-workerNotes.sql b/db/changes/231401/00-workerNotes.sql
deleted file mode 100644
index 0d9eaae7e..000000000
--- a/db/changes/231401/00-workerNotes.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-CREATE TABLE `vn`.`workerObservation` (
- `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
- `workerFk` int(10) unsigned DEFAULT NULL,
- `userFk` int(10) unsigned DEFAULT NULL,
- `text` text COLLATE utf8mb3_unicode_ci NOT NULL,
- `created` timestamp NOT NULL DEFAULT current_timestamp(),
- PRIMARY KEY (`id`),
- CONSTRAINT `workerFk_workerObservation_FK` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `userFk_workerObservation_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user`(`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a un trabajador';
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('WorkerObservation', '*', '*', 'ALLOW', 'ROLE', 'hr');
diff --git a/db/changes/231402/00-negativeBases.sql b/db/changes/231402/00-negativeBases.sql
deleted file mode 100644
index f7d6cdfb0..000000000
--- a/db/changes/231402/00-negativeBases.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-UPDATE `salix`.`ACL`
- SET model = 'InvoiceOut'
- WHERE property IN ('negativeBases', 'negativeBasesCsv');
diff --git a/db/changes/231801/00-aclClientInforma.sql b/db/changes/231801/00-aclClientInforma.sql
deleted file mode 100644
index 6222d2632..000000000
--- a/db/changes/231801/00-aclClientInforma.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
-VALUES ('ClientInforma', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('ClientInforma', '*', 'WRITE', 'ALLOW', 'ROLE', 'financial');
diff --git a/db/changes/231801/00-acl_receiptEmail.sql b/db/changes/231801/00-acl_receiptEmail.sql
deleted file mode 100644
index 2de8adf50..000000000
--- a/db/changes/231801/00-acl_receiptEmail.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Receipt', 'receiptEmail', '*', 'ALLOW', 'ROLE', 'salesAssistant');
diff --git a/db/changes/231801/00-clientInforma.sql b/db/changes/231801/00-clientInforma.sql
deleted file mode 100644
index 9bf757fc3..000000000
--- a/db/changes/231801/00-clientInforma.sql
+++ /dev/null
@@ -1,16 +0,0 @@
-ALTER TABLE `vn`.`client` ADD rating INT UNSIGNED DEFAULT NULL NULL COMMENT 'información proporcionada por Informa';
-ALTER TABLE `vn`.`client` ADD recommendedCredit INT UNSIGNED DEFAULT NULL NULL COMMENT 'información proporcionada por Informa';
-
-CREATE TABLE `vn`.`clientInforma` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `clientFk` int(11) NOT NULL,
- `rating` int(10) unsigned DEFAULT NULL,
- `recommendedCredit` int(10) unsigned DEFAULT NULL,
- `workerFk` int(10) unsigned NOT NULL,
- `created` timestamp NOT NULL DEFAULT current_timestamp(),
- PRIMARY KEY (`id`),
- KEY `informaWorkers_fk_idx` (`workerFk`),
- KEY `informaClientFk` (`clientFk`),
- CONSTRAINT `informa_ClienteFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `informa_workers_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE
-) ENGINE=InnoDB CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='información proporcionada por Informa, se actualiza desde el hook de client (salix)';
diff --git a/db/changes/231801/00-client_setRatingAcl.sql b/db/changes/231801/00-client_setRatingAcl.sql
deleted file mode 100644
index 6687b11ec..000000000
--- a/db/changes/231801/00-client_setRatingAcl.sql
+++ /dev/null
@@ -1,63 +0,0 @@
-DELETE FROM `salix`.`ACL` WHERE id=7;
-
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('Client', 'setRating', 'WRITE', 'ALLOW', 'ROLE', 'financial');
-
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('Client', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'addressesPropagateRe', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'canBeInvoiced', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'canCreateTicket', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'consumption', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'createAddress', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'createWithUser', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'extendedListFilter', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'getAverageInvoiced', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'getCard', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'getDebt', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'getMana', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'transactions', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'hasCustomerRole', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'isValidClient', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'lastActiveTickets', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'sendSms', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'setPassword', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'summary', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'updateAddress', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'updateFiscalData', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'uploadFile', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'campaignMetricsPdf', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'campaignMetricsEmail', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientWelcomeHtml', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientWelcomeEmail', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'printerSetupHtml', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'printerSetupEmail', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'sepaCoreEmail', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorPdf', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorStHtml', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorStEmail', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorNdHtml', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'letterDebtorNdEmail', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientDebtStatementPdf', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientDebtStatementHtml', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'clientDebtStatementEmail', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'creditRequestPdf', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'creditRequestHtml', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'creditRequestEmail', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'incotermsAuthorizationPdf', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'incotermsAuthorizationHtml', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'incotermsAuthorizationEmail', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'consumptionSendQueued', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'filter', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'getClientOrSupplierReference', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'upsert', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'create', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'replaceById', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'updateAttributes', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'updateAttributes', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'deleteById', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'replaceOrCreate', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'updateAll', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Client', 'upsertWithWhere', '*', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/231801/00-deleteProcs_refund.sql b/db/changes/231801/00-deleteProcs_refund.sql
deleted file mode 100644
index 8bf8982f4..000000000
--- a/db/changes/231801/00-deleteProcs_refund.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-DROP PROCEDURE `vn`.`refund`;
-DROP PROCEDURE `vn`.`ticket_doRefund`;
diff --git a/db/changes/231801/00-deviceProduction.sql b/db/changes/231801/00-deviceProduction.sql
deleted file mode 100644
index 37a2f1371..000000000
--- a/db/changes/231801/00-deviceProduction.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-DROP TRIGGER `vn`.`deviceProduction_afterInsert`;
-DROP TRIGGER `vn`.`deviceProduction_afterUpdate`;
-
-DROP TRIGGER `vn`.`deviceProductionUser_afterDelete`;
-
diff --git a/db/changes/231801/00-kkearEntryNotes.sql b/db/changes/231801/00-kkearEntryNotes.sql
deleted file mode 100644
index ff5c7ce29..000000000
--- a/db/changes/231801/00-kkearEntryNotes.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`entry` DROP COLUMN `notes`;
\ No newline at end of file
diff --git a/db/changes/231801/00-newCompanyI18n.sql b/db/changes/231801/00-newCompanyI18n.sql
deleted file mode 100644
index 948b9cb08..000000000
--- a/db/changes/231801/00-newCompanyI18n.sql
+++ /dev/null
@@ -1,9 +0,0 @@
--- vn.companyI18n definition
-CREATE TABLE `vn`.`companyI18n` (
- `companyFk` smallint(5) unsigned NOT NULL,
- `lang` char(2) CHARACTER SET utf8mb3 NOT NULL,
- `footnotes` longtext COLLATE utf8mb3_unicode_ci DEFAULT NULL,
- PRIMARY KEY (`companyFk`,`lang`),
- CONSTRAINT `companyI18n_FK` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
diff --git a/db/changes/231801/00-newTableWeb.sql b/db/changes/231801/00-newTableWeb.sql
deleted file mode 100644
index 1a2402956..000000000
--- a/db/changes/231801/00-newTableWeb.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`company` ADD `web` varchar(100) NULL;
\ No newline at end of file
diff --git a/db/changes/231801/00-observationEmailACL.sql b/db/changes/231801/00-observationEmailACL.sql
deleted file mode 100644
index 1a5d475e8..000000000
--- a/db/changes/231801/00-observationEmailACL.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Defaulter', 'observationEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/231801/00-optimiceZoneEstimatedDelivery.sql b/db/changes/231801/00-optimiceZoneEstimatedDelivery.sql
deleted file mode 100644
index 209e1efc3..000000000
--- a/db/changes/231801/00-optimiceZoneEstimatedDelivery.sql
+++ /dev/null
@@ -1,77 +0,0 @@
-CREATE OR REPLACE
-ALGORITHM = UNDEFINED VIEW `vn`.`zoneEstimatedDelivery` AS
-select
- `t`.`zoneFk` AS `zoneFk`,
- cast(`util`.`VN_CURDATE`() + interval hour(ifnull(`zc`.`hour`, `z`.`hour`)) * 60 + minute(ifnull(`zc`.`hour`, `z`.`hour`)) minute as time) AS `hourTheoretical`,
- cast(sum(`sv`.`volume`) as decimal(5, 1)) AS `totalVolume`,
- cast(sum(if(`s`.`alertLevel` < 2, `sv`.`volume`, 0)) as decimal(5, 1)) AS `remainingVolume`,
- greatest(
- ifnull(`lhp`.`m3`, 0),
- ifnull(`dl`.`minSpeed`, 0)
- ) AS `speed`,
- cast(`zc`.`hour` + interval -sum(if(`s`.`alertLevel` < 2, `sv`.`volume`, 0)) * 60 / greatest(ifnull(`lhp`.`m3`, 0), ifnull(`dl`.`minSpeed`, 0)) minute as time) AS `hourEffective`,
- floor(-sum(if(`s`.`alertLevel` < 2, `sv`.`volume`, 0)) * 60 / greatest(ifnull(`lhp`.`m3`, 0), ifnull(`dl`.`minSpeed`, 0))) AS `minutesLess`,
- cast(`zc`.`hour` + interval -sum(if(`s`.`alertLevel` < 2, `sv`.`volume`, 0)) * 60 / greatest(ifnull(`lhp`.`m3`, 0), ifnull(`dl`.`minSpeed`, 0)) minute as time) AS `etc`
-from
- (
- (
- (
- (
- (
- (
- (
- (
- (
- `vn`.`ticket` `t`
- join `vn`.`ticketStateToday` `tst` on
- (
- `tst`.`ticket` = `t`.`id`
- )
- )
- join `vn`.`state` `s` on
- (
- `s`.`id` = `tst`.`state`
- )
- )
- join `vn`.`saleVolume` `sv` on
- (
- `sv`.`ticketFk` = `t`.`id`
- )
- )
- left join `vn`.`lastHourProduction` `lhp` on
- (
- `lhp`.`warehouseFk` = `t`.`warehouseFk`
- )
- )
- join `vn`.`warehouse` `w` on
- (
- `w`.`id` = `t`.`warehouseFk`
- )
- )
- join `vn`.`warehouseAlias` `wa` on
- (
- `wa`.`id` = `w`.`aliasFk`
- )
- )
- straight_join `vn`.`zone` `z` on
- (
- `z`.`id` = `t`.`zoneFk`
- )
- )
- left join `vn`.`zoneClosure` `zc` on
- (
- `zc`.`zoneFk` = `t`.`zoneFk`
- and `zc`.`dated` = `util`.`VN_CURDATE`()
- )
- )
- left join `cache`.`departure_limit` `dl` on
- (
- `dl`.`warehouse_id` = `t`.`warehouseFk`
- and `dl`.`fecha` = `util`.`VN_CURDATE`()
- )
- )
-where
- `w`.`hasProduction` <> 0
- and cast(`t`.`shipped` as date) = `util`.`VN_CURDATE`()
-group by
- `t`.`zoneFk`;
diff --git a/db/changes/231801/00-saleTracking.sql b/db/changes/231801/00-saleTracking.sql
deleted file mode 100644
index d651a2447..000000000
--- a/db/changes/231801/00-saleTracking.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`sale_setQuantity`;
-DROP PROCEDURE IF EXISTS `vn`.`collection_updateSale`;
-DROP PROCEDURE IF EXISTS `vn`.`replaceMovimientosMark`;
-DROP PROCEDURE IF EXISTS `vn`.`saleTracking_Replace`;
-DROP PROCEDURE IF EXISTS `vn`.`sale_updateOriginalQuantity`;
diff --git a/db/changes/231801/00-ticketConfig.sql b/db/changes/231801/00-ticketConfig.sql
deleted file mode 100644
index 7c8aa83a4..000000000
--- a/db/changes/231801/00-ticketConfig.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`ticketConfig` ADD daysForWarningClaim INT DEFAULT 2 NOT NULL COMMENT 'dias restantes hasta que salte el aviso de reclamación fuera de plazo';
diff --git a/db/changes/231801/00-updateIsVies.sql b/db/changes/231801/00-updateIsVies.sql
deleted file mode 100644
index 4e5277559..000000000
--- a/db/changes/231801/00-updateIsVies.sql
+++ /dev/null
@@ -1,5 +0,0 @@
- UPDATE `vn`.`supplier` s
- JOIN `vn`.`country` c ON c.id = s.countryFk
- SET s.nif = MID(REPLACE(s.nif, ' ', ''), 3, LENGTH(REPLACE(s.nif, ' ', '')) - 1)
- WHERE s.isVies = TRUE
- AND c.code = LEFT(REPLACE(s.nif, ' ', ''), 2);
diff --git a/db/changes/231801/00-updateisViesClient.sql b/db/changes/231801/00-updateisViesClient.sql
deleted file mode 100644
index a153c5219..000000000
--- a/db/changes/231801/00-updateisViesClient.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-UPDATE IGNORE `vn`.`client` c
- JOIN `vn`.`country` co ON co.id = c.countryFk
- SET c.fi = MID(REPLACE(c.fi, ' ', ''), 3, LENGTH(REPLACE(c.fi, ' ', '')) - 1)
- WHERE c.isVies = TRUE
- AND co.code = LEFT(REPLACE(c.fi, ' ', ''), 2);
diff --git a/db/changes/231801/00-userAcl.sql b/db/changes/231801/00-userAcl.sql
deleted file mode 100644
index 9eb3ebf28..000000000
--- a/db/changes/231801/00-userAcl.sql
+++ /dev/null
@@ -1,20 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('VnUser','acl','READ','ALLOW','ROLE','account'),
- ('VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),
- ('VnUser','changePassword', 'WRITE', 'ALLOW', 'ROLE', 'account'),
- ('Account','exists','READ','ALLOW','ROLE','account');
-
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('Account','exists','READ','ALLOW','ROLE','account');
-
-DELETE FROM `salix`.`ACL` WHERE (model, property) = ('Account', 'acl');
-DELETE FROM `salix`.`ACL` WHERE (model, property) = ('Account', 'getCurrentUserData');
-DELETE FROM `salix`.`ACL` WHERE (model, property) = ('Account', 'changePassword');
-DELETE FROM `salix`.`ACL` WHERE model = 'UserAccount';
-
-UPDATE `hedera`.`imageCollection` t
-SET t.model = 'VnUser'
-WHERE t.id = 6;
-
diff --git a/db/changes/231801/00-userRoleLog.sql b/db/changes/231801/00-userRoleLog.sql
deleted file mode 100644
index ae5da13cb..000000000
--- a/db/changes/231801/00-userRoleLog.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('UserLog', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('RoleLog', '*', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/231801/01-viewCompany10L.sql b/db/changes/231801/01-viewCompany10L.sql
deleted file mode 100644
index 335827b42..000000000
--- a/db/changes/231801/01-viewCompany10L.sql
+++ /dev/null
@@ -1,12 +0,0 @@
--- vn.companyL10n source
-
-CREATE OR REPLACE
-ALGORITHM = UNDEFINED VIEW `vn`.`companyL10n` AS
-select
- `c`.`id` AS `id`,
- ifnull(`ci`.`footnotes`, `c`.`footnotes`) AS `footnotes`
-from
- (`vn`.`company` `c`
-left join `vn`.`companyI18n` `ci` on
- (`ci`.`companyFk` = `c`.`id`
- and `ci`.`lang` = `util`.`LANG`()));
\ No newline at end of file
diff --git a/db/changes/232001/00-clientWorkerName.sql b/db/changes/232001/00-clientWorkerName.sql
deleted file mode 100644
index 676d26691..000000000
--- a/db/changes/232001/00-clientWorkerName.sql
+++ /dev/null
@@ -1,73 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientCreate`(
- vFirstname VARCHAR(50),
- vSurnames VARCHAR(50),
- vFi VARCHAR(9),
- vAddress TEXT,
- vPostcode CHAR(5),
- vCity VARCHAR(25),
- vProvinceFk SMALLINT(5),
- vCompanyFk SMALLINT(5),
- vPhone VARCHAR(11),
- vEmail VARCHAR(255),
- vUserFk INT)
-BEGIN
-/**
- * Create new client
- *
- */
- DECLARE vPayMethodFk INT DEFAULT 4;
- DECLARE vDueDay INT DEFAULT 5;
- DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00;
- DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1;
- DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE;
- DECLARE vMandateTypeFk INT DEFAULT 2;
-
- INSERT INTO `client` (
- id,
- name,
- street,
- fi,
- phone,
- email,
- provinceFk,
- city,
- postcode,
- socialName,
- payMethodFk,
- dueDay,
- credit,
- isTaxDataChecked,
- hasCoreVnl,
- isEqualizated)
- VALUES (
- vUserFk,
- CONCAT(vFirstname, ' ', vSurnames),
- vAddress,
- TRIM(vFi),
- vPhone,
- vEmail,
- vProvinceFk,
- vCity,
- vPostcode,
- CONCAT(vSurnames, ' ', vFirstname),
- vPayMethodFk,
- vDueDay,
- vDefaultCredit,
- vIsTaxDataChecked,
- vHasCoreVnl,
- FALSE
- ) ON duplicate key update
- payMethodFk = vPayMethodFk,
- dueDay = vDueDay,
- credit = vDefaultCredit,
- isTaxDataChecked = vIsTaxDataChecked,
- hasCoreVnl = vHasCoreVnl,
- isActive = TRUE;
-
- IF (SELECT COUNT(*) FROM mandate WHERE clientFk = vUserFk AND companyFk = vCompanyFk AND mandateTypeFk = vMandateTypeFk) = 0 THEN
- INSERT INTO mandate (clientFk, companyFk, mandateTypeFk)
- VALUES (vUserFk, vCompanyFk, vMandateTypeFk);
- END IF;
-END$$
-DELIMITER ;
\ No newline at end of file
diff --git a/db/changes/232001/00-createWorker.sql b/db/changes/232001/00-createWorker.sql
deleted file mode 100644
index 0ea7ecbe8..000000000
--- a/db/changes/232001/00-createWorker.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-INSERT INTO `vn`.`businessType` (`code`, `description`)
- VALUES ('worker','Trabajador');
-
-ALTER TABLE `vn`.`workerConfig` ADD businessTypeFk varchar(100) NULL
- COMMENT 'Tipo de negocio por defecto al dar de alta un trabajador nuevo';
-
-UPDATE `vn`.`workerConfig`
- SET businessTypeFk = 'worker'
- WHERE id = 1;
-
- UPDATE `vn`.`client` c
- JOIN `vn`.`worker` w ON w.id = c.id
- SET c.name = REPLACE(c.name, 'TR ', ''),
- c.businessTypeFk = 'worker';
diff --git a/db/changes/232001/00-wagon.sql b/db/changes/232001/00-wagon.sql
deleted file mode 100644
index bdb384db5..000000000
--- a/db/changes/232001/00-wagon.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`wagon` ADD CONSTRAINT `wagon_type` FOREIGN KEY (`typeFk`) REFERENCES `wagonType` (`id`) ON UPDATE CASCADE;
diff --git a/db/changes/232201/00-defaulterView.sql b/db/changes/232201/00-defaulterView.sql
deleted file mode 100644
index 8b56e5945..000000000
--- a/db/changes/232201/00-defaulterView.sql
+++ /dev/null
@@ -1,20 +0,0 @@
--- vn.defaulter source
-
-CREATE OR REPLACE
-ALGORITHM = UNDEFINED VIEW `vn`.`defaulter` AS
-select
- `d`.`clientFk` AS `clientFk`,
- `d`.`created` AS `created`,
- `d`.`amount` AS `amount`,
- `d`.`defaulterSinced` AS `defaulterSinced`,
- `d`.`hasChanged` AS `hasChanged`,
- `c`.`countryFk` AS `country`,
- `c`.`payMethodFk` AS `payMethod`
-from
- (((`bs`.`defaulter` `d`
-join `vn`.`client` `c` on
- (`c`.`id` = `d`.`clientFk`))
-join `vn`.`country` `co` on
- (`co`.`id` = `c`.`countryFk`))
-join `vn`.`payMethod` `pm` on
- (`pm`.`id` = `c`.`payMethodFk`));
\ No newline at end of file
diff --git a/db/changes/232201/00-procedurecanAdvance.sql b/db/changes/232201/00-procedurecanAdvance.sql
deleted file mode 100644
index 9d5c24296..000000000
--- a/db/changes/232201/00-procedurecanAdvance.sql
+++ /dev/null
@@ -1,127 +0,0 @@
-DELIMITER $$
-$$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT)
-BEGIN
-/**
- * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar.
- *
- * @param vDateFuture Fecha de los tickets que se quieren adelantar.
- * @param vDateToAdvance Fecha a cuando se quiere adelantar.
- * @param vWarehouseFk Almacén
- */
-
- DECLARE vDateInventory DATE;
-
- SELECT inventoried INTO vDateInventory FROM config;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.stock;
- CREATE TEMPORARY TABLE tmp.stock
- (itemFk INT PRIMARY KEY,
- amount INT)
- ENGINE = MEMORY;
-
- INSERT INTO tmp.stock(itemFk, amount)
- SELECT itemFk, SUM(quantity) amount FROM
- (
- SELECT itemFk, quantity
- FROM itemTicketOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM itemEntryIn
- WHERE landed >= vDateInventory
- AND landed < vDateFuture
- AND isVirtualStock = FALSE
- AND warehouseInFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM itemEntryOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseOutFk = vWarehouseFk
- ) t
- GROUP BY itemFk HAVING amount != 0;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.filter;
- CREATE TEMPORARY TABLE tmp.filter
- (INDEX (id))
-SELECT
- origin.ticketFk futureId,
- dest.ticketFk id,
- dest.state,
- origin.futureState,
- origin.futureIpt,
- dest.ipt,
- origin.workerFk,
- origin.futureLiters,
- origin.futureLines,
- dest.shipped,
- origin.shipped futureShipped,
- dest.totalWithVat,
- origin.totalWithVat futureTotalWithVat,
- dest.agency,
- origin.futureAgency,
- dest.lines,
- dest.liters,
- origin.futureLines - origin.hasStock AS notMovableLines,
- (origin.futureLines = origin.hasStock) AS isFullMovable,
- origin.classColor,
- dest.classColor futureClassColor
- FROM (
- SELECT
- s.ticketFk,
- t.workerFk,
- t.shipped,
- t.totalWithVat,
- st.name futureState,
- t.addressFk,
- am.name futureAgency,
- count(s.id) futureLines,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
- CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
- SUM((s.quantity <= IFNULL(st.amount,0))) hasStock,
- st.classColor
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN saleVolume sv ON sv.saleFk = s.id
- JOIN item i ON i.id = s.itemFk
- JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN state st ON st.id = ts.stateFk
- JOIN agencyMode am ON t.agencyModeFk = am.id
- LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- LEFT JOIN tmp.stock st ON st.itemFk = i.id
- WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
- AND t.warehouseFk = vWarehouseFk
- GROUP BY t.id
- ) origin
- JOIN (
- SELECT
- t.id ticketFk,
- t.addressFk,
- st.name state,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
- t.shipped,
- t.totalWithVat,
- am.name agency,
- CAST(SUM(litros) AS DECIMAL(10,0)) liters,
- CAST(COUNT(*) AS DECIMAL(10,0)) `lines`,
- st.classColor
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN saleVolume sv ON sv.saleFk = s.id
- JOIN item i ON i.id = s.itemFk
- JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN state st ON st.id = ts.stateFk
- JOIN agencyMode am ON t.agencyModeFk = am.id
- LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance)
- AND t.warehouseFk = vWarehouseFk
- AND st.order <= 5
- GROUP BY t.id
- ) dest ON dest.addressFk = origin.addressFk
- WHERE origin.hasStock != 0;
- DROP TEMPORARY TABLE tmp.stock;
-END$$
-DELIMITER ;
\ No newline at end of file
diff --git a/db/changes/232201/00-workerConfigPayMethod.sql b/db/changes/232201/00-workerConfigPayMethod.sql
deleted file mode 100644
index 8896f636d..000000000
--- a/db/changes/232201/00-workerConfigPayMethod.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-ALTER TABLE `vn`.`workerConfig` ADD payMethodFk tinyint(3) unsigned NULL;
-ALTER TABLE `vn`.`workerConfig` ADD CONSTRAINT workerConfig_FK FOREIGN KEY (roleFk) REFERENCES account.`role`(id) ON DELETE RESTRICT ON UPDATE CASCADE;
-ALTER TABLE `vn`.`workerConfig` ADD CONSTRAINT workerConfig_FK_1 FOREIGN KEY (payMethodFk) REFERENCES `vn`.`payMethod`(id) ON DELETE SET NULL ON UPDATE CASCADE;
-
-UPDATE `vn`.`workerConfig`
- SET payMethodFk = 4
- WHERE id=1;
diff --git a/db/changes/232202/00-procedurecanAdvance.sql b/db/changes/232202/00-procedurecanAdvance.sql
deleted file mode 100644
index d82294b3c..000000000
--- a/db/changes/232202/00-procedurecanAdvance.sql
+++ /dev/null
@@ -1,127 +0,0 @@
-DELIMITER $$
-$$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT)
-BEGIN
-/**
- * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar.
- *
- * @param vDateFuture Fecha de los tickets que se quieren adelantar.
- * @param vDateToAdvance Fecha a cuando se quiere adelantar.
- * @param vWarehouseFk Almacén
- */
-
- DECLARE vDateInventory DATE;
-
- SELECT inventoried INTO vDateInventory FROM config;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.stock;
- CREATE TEMPORARY TABLE tmp.stock
- (itemFk INT PRIMARY KEY,
- amount INT)
- ENGINE = MEMORY;
-
- INSERT INTO tmp.stock(itemFk, amount)
- SELECT itemFk, SUM(quantity) amount FROM
- (
- SELECT itemFk, quantity
- FROM itemTicketOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM itemEntryIn
- WHERE landed >= vDateInventory
- AND landed < vDateFuture
- AND isVirtualStock = FALSE
- AND warehouseInFk = vWarehouseFk
- UNION ALL
- SELECT itemFk, quantity
- FROM itemEntryOut
- WHERE shipped >= vDateInventory
- AND shipped < vDateFuture
- AND warehouseOutFk = vWarehouseFk
- ) t
- GROUP BY itemFk HAVING amount != 0;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.filter;
- CREATE TEMPORARY TABLE tmp.filter
- (INDEX (id))
-SELECT
- origin.ticketFk futureId,
- dest.ticketFk id,
- dest.state,
- origin.futureState,
- origin.futureIpt,
- dest.ipt,
- origin.workerFk,
- origin.futureLiters,
- origin.futureLines,
- dest.shipped,
- origin.shipped futureShipped,
- dest.totalWithVat,
- origin.totalWithVat futureTotalWithVat,
- dest.agency,
- origin.futureAgency,
- dest.lines,
- dest.liters,
- origin.futureLines - origin.hasStock AS notMovableLines,
- (origin.futureLines = origin.hasStock) AS isFullMovable,
- origin.classColor futureClassColor,
- dest.classColor
- FROM (
- SELECT
- s.ticketFk,
- t.workerFk,
- t.shipped,
- t.totalWithVat,
- st.name futureState,
- t.addressFk,
- am.name futureAgency,
- count(s.id) futureLines,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
- CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
- SUM((s.quantity <= IFNULL(st.amount,0))) hasStock,
- st.classColor
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN saleVolume sv ON sv.saleFk = s.id
- JOIN item i ON i.id = s.itemFk
- JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN state st ON st.id = ts.stateFk
- JOIN agencyMode am ON t.agencyModeFk = am.id
- LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- LEFT JOIN tmp.stock st ON st.itemFk = i.id
- WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
- AND t.warehouseFk = vWarehouseFk
- GROUP BY t.id
- ) origin
- JOIN (
- SELECT
- t.id ticketFk,
- t.addressFk,
- st.name state,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
- t.shipped,
- t.totalWithVat,
- am.name agency,
- CAST(SUM(litros) AS DECIMAL(10,0)) liters,
- CAST(COUNT(*) AS DECIMAL(10,0)) `lines`,
- st.classColor
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN saleVolume sv ON sv.saleFk = s.id
- JOIN item i ON i.id = s.itemFk
- JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN state st ON st.id = ts.stateFk
- JOIN agencyMode am ON t.agencyModeFk = am.id
- LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance)
- AND t.warehouseFk = vWarehouseFk
- AND st.order <= 5
- GROUP BY t.id
- ) dest ON dest.addressFk = origin.addressFk
- WHERE origin.hasStock != 0;
- DROP TEMPORARY TABLE tmp.stock;
-END$$
-DELIMITER ;
diff --git a/db/changes/232401/00-buyConfig_travelConfig.sql b/db/changes/232401/00-buyConfig_travelConfig.sql
deleted file mode 100644
index 0f73ddc8c..000000000
--- a/db/changes/232401/00-buyConfig_travelConfig.sql
+++ /dev/null
@@ -1,28 +0,0 @@
-CREATE TABLE `vn`.`buyConfig` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `monthsAgo` int(11) NOT NULL DEFAULT 6 COMMENT 'Meses desde la última compra',
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-CREATE TABLE `vn`.`travelConfig` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `warehouseInFk` smallint(6) unsigned NOT NULL DEFAULT 8 COMMENT 'Warehouse de origen',
- `warehouseOutFk` smallint(6) unsigned NOT NULL DEFAULT 60 COMMENT 'Warehouse destino',
- `agencyFk` int(11) NOT NULL DEFAULT 1378 COMMENT 'Agencia por defecto',
- `companyFk` smallint(5) unsigned NOT NULL DEFAULT 442 COMMENT 'Compañía por defecto',
- PRIMARY KEY (`id`),
- KEY `travelConfig_FK` (`warehouseInFk`),
- KEY `travelConfig_FK_1` (`warehouseOutFk`),
- KEY `travelConfig_FK_2` (`agencyFk`),
- KEY `travelConfig_FK_3` (`companyFk`),
- CONSTRAINT `travelConfig_FK` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `travelConfig_FK_1` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `travelConfig_FK_2` FOREIGN KEY (`agencyFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `travelConfig_FK_3` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Entry', 'addFromPackaging', 'WRITE', 'ALLOW', 'ROLE', 'production'),
- ('Entry', 'addFromBuy', 'WRITE', 'ALLOW', 'ROLE', 'production'),
- ('Supplier', 'getItemsPackaging', 'READ', 'ALLOW', 'ROLE', 'production');
diff --git a/db/changes/232401/00-printer.sql b/db/changes/232401/00-printer.sql
deleted file mode 100644
index 6280c2c6d..000000000
--- a/db/changes/232401/00-printer.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-ALTER TABLE `vn`.`sector` DROP COLUMN `printerFk`;
-ALTER TABLE `vn`.`sector` ADD COLUMN `mainPrinterFk` tinyint(3) unsigned;
-ALTER TABLE `vn`.`sector` ADD CONSTRAINT sector_FK_1 FOREIGN KEY (mainPrinterFk) REFERENCES vn.printer(id) ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/db/changes/232401/00-ticket_warehouse.sql b/db/changes/232401/00-ticket_warehouse.sql
deleted file mode 100644
index b5255ee3f..000000000
--- a/db/changes/232401/00-ticket_warehouse.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`ticket` MODIFY COLUMN warehouseFk smallint(6) unsigned DEFAULT NULL NULL;
diff --git a/db/changes/232401/00-userPassExpired.sql b/db/changes/232401/00-userPassExpired.sql
deleted file mode 100644
index 2d4b45937..000000000
--- a/db/changes/232401/00-userPassExpired.sql
+++ /dev/null
@@ -1,76 +0,0 @@
-ALTER TABLE `account`.`user` ADD passExpired DATE DEFAULT NULL;
-
-DROP PROCEDURE `account`.`myUser_changePassword`;
-DROP PROCEDURE `account`.`myUser_restorePassword`;
-DROP PROCEDURE `account`.`user_changePassword`;
-DROP PROCEDURE `account`.`user_restorePassword`;
-DROP PROCEDURE `account`.`user_setPassword`;
-
-ALTER TABLE account.`user` CHANGE password password__ char(64) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL COMMENT 'Deprecated';
-ALTER TABLE account.`user` CHANGE bcryptPassword password varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL;
-
-DELIMITER $$
-$$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`user_beforeUpdate`
- BEFORE UPDATE ON `user`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF !(NEW.`name` <=> OLD.`name`) THEN
- CALL user_checkName (NEW.`name`);
- END IF;
-
- IF !(NEW.`password` <=> OLD.`password`) THEN
- SET NEW.lastPassChange = util.VN_NOW();
- END IF;
-END$$
-DELIMITER ;
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `account`.`accountDovecot` AS
-select
- `u`.`name` AS `name`,
- `u`.`password` AS `password`
-from
- (`account`.`user` `u`
-join `account`.`account` `a` on
- (`a`.`id` = `u`.`id`))
-where
- `u`.`active` <> 0;
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `salix`.`User` AS
-select
- `account`.`user`.`id` AS `id`,
- `account`.`user`.`realm` AS `realm`,
- `account`.`user`.`name` AS `username`,
- `account`.`user`.`password` AS `password`,
- `account`.`user`.`email` AS `email`,
- `account`.`user`.`emailVerified` AS `emailVerified`,
- `account`.`user`.`verificationToken` AS `verificationToken`
-from
- `account`.`user`;
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `vn`.`workerTimeControlUserInfo` AS
-select
- `u`.`id` AS `userFk`,
- `w`.`firstName` AS `name`,
- `w`.`lastName` AS `surname`,
- `u`.`name` AS `user`,
- `u`.`password` AS `password`,
- `wd`.`departmentFk` AS `departmentFk`,
- left(`c`.`fi`,
- 8) AS `dni`
-from
- (((`account`.`user` `u`
-join `vn`.`worker` `w` on
- (`w`.`userFk` = `u`.`id`))
-join `vn`.`client` `c` on
- (`c`.`id` = `u`.`id`))
-left join `vn`.`workerDepartment` `wd` on
- (`wd`.`workerFk` = `w`.`id`));
diff --git a/db/changes/232402/00-hotFix_travelConfig.sql b/db/changes/232402/00-hotFix_travelConfig.sql
deleted file mode 100644
index 65450a74d..000000000
--- a/db/changes/232402/00-hotFix_travelConfig.sql
+++ /dev/null
@@ -1,22 +0,0 @@
-CREATE TABLE `vn`.`travelConfig` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `warehouseInFk` smallint(6) unsigned NOT NULL DEFAULT 8 COMMENT 'Warehouse de origen',
- `warehouseOutFk` smallint(6) unsigned NOT NULL DEFAULT 60 COMMENT 'Warehouse destino',
- `agencyFk` int(11) NOT NULL DEFAULT 1378 COMMENT 'Agencia por defecto',
- `companyFk` int(10) unsigned NOT NULL DEFAULT 442 COMMENT 'Compañía por defecto',
- PRIMARY KEY (`id`),
- KEY `travelConfig_FK` (`warehouseInFk`),
- KEY `travelConfig_FK_1` (`warehouseOutFk`),
- KEY `travelConfig_FK_2` (`agencyFk`),
- KEY `travelConfig_FK_3` (`companyFk`),
- CONSTRAINT `travelConfig_FK` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `travelConfig_FK_1` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `travelConfig_FK_2` FOREIGN KEY (`agencyFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `travelConfig_FK_3` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Entry', 'addFromPackaging', 'WRITE', 'ALLOW', 'ROLE', 'production'),
- ('Entry', 'addFromBuy', 'WRITE', 'ALLOW', 'ROLE', 'production'),
- ('Supplier', 'getItemsPackaging', 'READ', 'ALLOW', 'ROLE', 'production');
diff --git a/db/changes/232601/00-aclAccount.sql b/db/changes/232601/00-aclAccount.sql
deleted file mode 100644
index bf8106b98..000000000
--- a/db/changes/232601/00-aclAccount.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-DELETE
- FROM `salix`.`ACL`
- WHERE model='Account' AND property='*' AND accessType='*';
-
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('Account', '*', 'WRITE', 'ALLOW', 'ROLE', 'sysadmin'),
- ('Account', '*', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/232601/00-aclInvoiceTickets.sql b/db/changes/232601/00-aclInvoiceTickets.sql
deleted file mode 100644
index 2c221950e..000000000
--- a/db/changes/232601/00-aclInvoiceTickets.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES('Ticket', 'invoiceTickets', 'WRITE', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/232601/00-aclMailAliasAccount.sql b/db/changes/232601/00-aclMailAliasAccount.sql
deleted file mode 100644
index 619e9bb6e..000000000
--- a/db/changes/232601/00-aclMailAliasAccount.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-DELETE FROM `salix`.`ACL` WHERE model = 'MailAliasAccount';
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('MailAliasAccount', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('MailAliasAccount', '*', 'WRITE', 'ALLOW', 'ROLE', 'itManagement');
diff --git a/db/changes/232601/00-aclMailForward.sql b/db/changes/232601/00-aclMailForward.sql
deleted file mode 100644
index afe2acec8..000000000
--- a/db/changes/232601/00-aclMailForward.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-DELETE FROM `salix`.`ACL` WHERE model = 'MailForward';
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('MailForward', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('MailForward', '*', 'WRITE', 'ALLOW', 'ROLE', 'itManagement');
diff --git a/db/changes/232601/00-aclRole.sql b/db/changes/232601/00-aclRole.sql
deleted file mode 100644
index e16f052be..000000000
--- a/db/changes/232601/00-aclRole.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-DELETE FROM `salix`.`ACL` WHERE model = 'Role';
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Role', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Role', '*', 'WRITE', 'ALLOW', 'ROLE', 'it');
diff --git a/db/changes/232601/00-aclVnUser.sql b/db/changes/232601/00-aclVnUser.sql
deleted file mode 100644
index 39fa2cb14..000000000
--- a/db/changes/232601/00-aclVnUser.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-DELETE
- FROM `salix`.`ACL`
- WHERE model = 'VnUser' AND property = '*' AND principalId = 'employee';
-
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('VnUser', '*', '*', 'ALLOW', 'ROLE', 'itManagement'),
- ('VnUser', '__get__preview', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('VnUser', 'preview', '*', 'ALLOW', 'ROLE', 'employee'),
- ('VnUser', 'create', '*', 'ALLOW', 'ROLE', 'itManagement');
diff --git a/db/changes/232601/00-aclVnUser_renewToken.sql b/db/changes/232601/00-aclVnUser_renewToken.sql
deleted file mode 100644
index aa20f7a82..000000000
--- a/db/changes/232601/00-aclVnUser_renewToken.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('VnUser', 'renewToken', 'WRITE', 'ALLOW', 'ROLE', 'employee')
diff --git a/db/changes/232601/00-salix.sql b/db/changes/232601/00-salix.sql
deleted file mode 100644
index 44366abce..000000000
--- a/db/changes/232601/00-salix.sql
+++ /dev/null
@@ -1,11 +0,0 @@
-CREATE TABLE `salix`.`accessTokenConfig` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `renewPeriod` int(10) unsigned DEFAULT NULL,
- `courtesyTime` int(10) unsigned DEFAULT NULL,
- `renewInterval` int(10) unsigned DEFAULT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-INSERT IGNORE INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `courtesyTime`, `renewInterval`)
- VALUES
- (1, 21600, 5, 300);
diff --git a/db/changes/232601/00-useSpecificsAcls.sql b/db/changes/232601/00-useSpecificsAcls.sql
deleted file mode 100644
index d124786f6..000000000
--- a/db/changes/232601/00-useSpecificsAcls.sql
+++ /dev/null
@@ -1,121 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Ticket', 'editDiscount', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'),
- ('Ticket', 'editDiscount', 'WRITE', 'ALLOW', 'ROLE', 'salesPerson'),
- ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'salesAssistant'),
- ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'deliveryAssistant'),
- ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'buyer'),
- ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'claimManager'),
- ('Ticket', 'deleteTicketWithPartPrepared', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'),
- ('Ticket', 'editZone', 'WRITE', 'ALLOW', 'ROLE', 'deliveryAssistant'),
- ('State', 'editableStates', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('State', 'seeEditableStates', 'READ', 'ALLOW', 'ROLE', 'administrative'),
- ('State', 'seeEditableStates', 'READ', 'ALLOW', 'ROLE', 'production'),
- ('State', 'isSomeEditable', 'READ', 'ALLOW', 'ROLE', 'salesPerson'),
- ('State', 'isAllEditable', 'READ', 'ALLOW', 'ROLE', 'production'),
- ('State', 'isAllEditable', 'READ', 'ALLOW', 'ROLE', 'administrative'),
- ('Agency', 'seeExpired', 'READ', 'ALLOW', 'ROLE', 'administrative'),
- ('Agency', 'seeExpired', 'READ', 'ALLOW', 'ROLE', 'productionBoss'),
- ('Claim', 'createAfterDeadline', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'),
- ('Client', 'editAddressLogifloraAllowed', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'),
- ('Client', 'editFiscalDataWithoutTaxDataCheck', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'),
- ('Client', 'editVerifiedDataWithoutTaxDataCheck', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'),
- ('Client', 'editCredit', 'WRITE', 'ALLOW', 'ROLE', 'financialBoss'),
- ('Client', 'isNotEditableCredit', 'WRITE', 'ALLOW', 'ROLE', 'financialBoss'),
- ('InvoiceOut', 'canCreatePdf', 'WRITE', 'ALLOW', 'ROLE', 'invoicing'),
- ('Supplier', 'editPayMethodCheck', 'WRITE', 'ALLOW', 'ROLE', 'financial'),
- ('Worker', 'isTeamBoss', 'WRITE', 'ALLOW', 'ROLE', 'teamBoss'),
- ('Worker', 'forceIsSubordinate', 'READ', 'ALLOW', 'ROLE', 'hr'),
- ('Claim', 'editState', 'WRITE', 'ALLOW', 'ROLE', 'claimManager');
-
-DELETE FROM `salix`.`ACL`
- WHERE
- model = 'Claim'
- AND property = '*'
- AND accessType = '*';
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Claim', 'find', 'READ', 'ALLOW', 'ROLE', 'salesPerson'),
- ('Claim', 'findById', 'READ', 'ALLOW', 'ROLE', 'salesPerson'),
- ('Claim', 'findOne', 'READ', 'ALLOW', 'ROLE', 'salesPerson'),
- ('Claim', 'getSummary', 'READ', 'ALLOW', 'ROLE', 'salesPerson'),
- ('Claim', 'updateClaim', 'WRITE', 'ALLOW', 'ROLE', 'salesPerson'),
- ('Claim', 'regularizeClaim', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'),
- ('Claim', 'updateClaimDestination', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'),
- ('Claim', 'downloadFile', 'READ', 'ALLOW', 'ROLE', 'claimManager'),
- ('Claim', 'deleteById', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'),
- ('Claim', 'filter', 'READ', 'ALLOW', 'ROLE', 'salesPerson'),
- ('Claim', 'logs', 'READ', 'ALLOW', 'ROLE', 'claimManager');
-
-DELETE FROM `salix`.`ACL`
- WHERE
- model = 'Ticket'
- AND property = '*'
- AND accessType = '*';
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Ticket', 'find', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'findById', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'findOne', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'getVolume', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'getTotalVolume', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'summary', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'priceDifference', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'componentUpdate', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'new', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'isEditable', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'setDeleted', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'restore', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'getSales', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'getSalesPersonMana', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'filter', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'makeInvoice', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'updateEditableTicket', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'updateDiscount', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'transferSales', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'sendSms', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'isLocked', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'freightCost', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'getComponentsSum', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Ticket', 'updateAttributes', 'WRITE', 'ALLOW', 'ROLE', 'delivery'), -- Change Priority in Route tickets
- ('Ticket', 'deliveryNoteCsv', 'READ', 'ALLOW', 'ROLE', 'employee');
-
-DELETE FROM `salix`.`ACL`
- WHERE
- model = 'State'
- AND property = '*'
- AND accessType = 'READ';
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('State', 'find', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('State', 'findById', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('State', 'findOne', 'READ', 'ALLOW', 'ROLE', 'employee');
-
-DELETE FROM `salix`.`ACL`
- WHERE
- model = 'Worker'
- AND property = '*'
- AND accessType = 'READ';
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Worker', 'find', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'findById', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'findOne', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'filter', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'getWorkedHours', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'active', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'activeWithRole', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'uploadFile', 'WRITE', 'ALLOW', 'ROLE', 'hr'),
- ('Worker', 'contracts', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'holidays', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'activeContract', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Worker', 'activeWithInheritedRole', 'READ', 'ALLOW', 'ROLE', 'employee');
-
-DELETE FROM `salix`.`ACL`
- WHERE model = 'Client'
- AND property = 'updateUser'
- AND accessType = '*';
diff --git a/db/changes/232601/01-invoiceOutPdf.sql b/db/changes/232601/01-invoiceOutPdf.sql
deleted file mode 100644
index e013736df..000000000
--- a/db/changes/232601/01-invoiceOutPdf.sql
+++ /dev/null
@@ -1,13 +0,0 @@
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES
- ('InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),
- ('InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing');
-
-CREATE OR REPLACE TABLE `vn`.`invoiceOutConfig` (
- id INT UNSIGNED auto_increment NOT NULL,
- parallelism int UNSIGNED DEFAULT 1 NOT NULL,
- PRIMARY KEY (id)
-)
-ENGINE=InnoDB
-DEFAULT CHARSET=utf8mb3
-COLLATE=utf8mb3_unicode_ci;
diff --git a/db/changes/232602/01-aclAddAlias.sql b/db/changes/232602/01-aclAddAlias.sql
deleted file mode 100644
index d4df3cd44..000000000
--- a/db/changes/232602/01-aclAddAlias.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-DELETE FROM `salix`.`ACL` WHERE model = 'MailAliasAccount';
-
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('MailAliasAccount', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('MailAliasAccount', 'create', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('MailAliasAccount', 'deleteById', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('MailAliasAccount', 'canEditAlias', 'WRITE', 'ALLOW', 'ROLE', 'itManagement');
diff --git a/db/changes/232801/00-authCode.sql b/db/changes/232801/00-authCode.sql
deleted file mode 100644
index a256db43f..000000000
--- a/db/changes/232801/00-authCode.sql
+++ /dev/null
@@ -1,13 +0,0 @@
-create table `salix`.`authCode`
-(
- userFk int UNSIGNED not null,
- code int not null,
- expires bigint not null,
- constraint authCode_pk
- primary key (userFk),
- constraint authCode_unique
- unique (code),
- constraint authCode_user_id_fk
- foreign key (userFk) references `account`.`user` (id)
- on update cascade on delete cascade
-);
diff --git a/db/changes/232801/00-client_create.sql b/db/changes/232801/00-client_create.sql
deleted file mode 100644
index d21094dad..000000000
--- a/db/changes/232801/00-client_create.sql
+++ /dev/null
@@ -1,89 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`clientCreate`;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_create`(
- vFirstname VARCHAR(50),
- vSurnames VARCHAR(50),
- vFi VARCHAR(9),
- vAddress TEXT,
- vPostcode CHAR(5),
- vCity VARCHAR(25),
- vProvinceFk SMALLINT(5),
- vCompanyFk SMALLINT(5),
- vPhone VARCHAR(11),
- vEmail VARCHAR(255),
- vUserFk INT
-)
-BEGIN
-/**
- * Create new client
- *
- * @params vFirstname firstName
- * @params vSurnames surnames
- * @params vFi company code from accounting transactions
- * @params vAddress address
- * @params vPostcode postCode
- * @params vCity city
- * @params vProvinceFk province
- * @params vCompanyFk company in which he has become a client
- * @params vPhone telephone number
- * @params vEmail email address
- * @params vUserFk user id
- */
- DECLARE vPayMethodFk INT;
- DECLARE vDueDay INT;
- DECLARE vDefaultCredit DECIMAL(10, 2);
- DECLARE vIsTaxDataChecked TINYINT(1);
- DECLARE vHasCoreVnl BOOLEAN;
- DECLARE vMandateTypeFk INT;
-
- SELECT defaultPayMethodFk,
- defaultDueDay,
- defaultCredit,
- defaultIsTaxDataChecked,
- defaultHasCoreVnl,
- defaultMandateTypeFk
- INTO vPayMethodFk,
- vDueDay,
- vDefaultCredit,
- vIsTaxDataChecked,
- vHasCoreVnl,
- vMandateTypeFk
- FROM clientConfig;
-
- INSERT INTO `client`
- SET id = vUserFk,
- name = CONCAT(vFirstname, ' ', vSurnames),
- street = vAddress,
- fi = TRIM(vFi),
- phone = vPhone,
- email = vEmail,
- provinceFk = vProvinceFk,
- city = vCity,
- postcode = vPostcode,
- socialName = CONCAT(vSurnames, ' ', vFirstname),
- payMethodFk = vPayMethodFk,
- dueDay = vDueDay,
- credit = vDefaultCredit,
- isTaxDataChecked = vIsTaxDataChecked,
- hasCoreVnl = vHasCoreVnl,
- isEqualizated = FALSE
- ON duplicate KEY UPDATE
- payMethodFk = vPayMethodFk,
- dueDay = vDueDay,
- credit = vDefaultCredit,
- isTaxDataChecked = vIsTaxDataChecked,
- hasCoreVnl = vHasCoreVnl,
- isActive = TRUE;
-
- INSERT INTO mandate (clientFk, companyFk, mandateTypeFk)
- SELECT vUserFk, vCompanyFk, vMandateTypeFk
- WHERE NOT EXISTS (
- SELECT id
- FROM mandate
- WHERE clientFk = vUserFk
- AND companyFk = vCompanyFk
- AND mandateTypeFk = vMandateTypeFk
- );
-END$$
-DELIMITER ;
diff --git a/db/changes/232801/00-client_create2.sql b/db/changes/232801/00-client_create2.sql
deleted file mode 100644
index f2e660351..000000000
--- a/db/changes/232801/00-client_create2.sql
+++ /dev/null
@@ -1,17 +0,0 @@
-ALTER TABLE `vn`.`clientConfig` ADD defaultPayMethodFk tinyint(3) unsigned NULL;
-ALTER TABLE `vn`.`clientConfig` ADD defaultDueDay int unsigned NULL;
-ALTER TABLE `vn`.`clientConfig` ADD defaultCredit decimal(10, 2) NULL;
-ALTER TABLE `vn`.`clientConfig` ADD defaultIsTaxDataChecked tinyint(1) NULL;
-ALTER TABLE `vn`.`clientConfig` ADD defaultHasCoreVnl boolean NULL;
-ALTER TABLE `vn`.`clientConfig` ADD defaultMandateTypeFk smallint(5) NULL;
-ALTER TABLE `vn`.`clientConfig` ADD CONSTRAINT clientNewConfigPayMethod_FK FOREIGN KEY (defaultPayMethodFk) REFERENCES vn.payMethod(id);
-ALTER TABLE `vn`.`clientConfig` ADD CONSTRAINT clientNewConfigMandateType_FK FOREIGN KEY (defaultMandateTypeFk) REFERENCES vn.mandateType(id);
-
-UPDATE `vn`.`clientConfig`
- SET defaultPayMethodFk = 4,
- defaultDueDay = 5,
- defaultCredit = 300.0,
- defaultIsTaxDataChecked = 1,
- defaultHasCoreVnl = 1,
- defaultMandateTypeFk = 2
- WHERE id = 1;
diff --git a/db/changes/232801/00-department.sql b/db/changes/232801/00-department.sql
deleted file mode 100644
index 3dcb8501d..000000000
--- a/db/changes/232801/00-department.sql
+++ /dev/null
@@ -1,24 +0,0 @@
-alter table `vn`.`department`
- add `twoFactor` ENUM ('email') null comment 'Default user two-factor auth type';
-
-drop trigger `vn`.`department_afterUpdate`;
-
-DELIMITER $$
-$$
-create definer = root@localhost trigger `vn`.`department_afterUpdate`
- after update
- on department
- for each row
-BEGIN
- IF !(OLD.parentFk <=> NEW.parentFk) THEN
- UPDATE vn.department_recalc SET isChanged = TRUE;
- END IF;
-
- IF !(OLD.twoFactor <=> NEW.twoFactor) THEN
- UPDATE account.user u
- JOIN vn.workerDepartment wd ON wd.workerFk = u.id
- SET u.twoFactor = NEW.twoFactor
- WHERE wd.departmentFk = NEW.id;
- END IF;
-END;$$
-DELIMITER ;
diff --git a/db/changes/232801/00-fix_editCredit.sql b/db/changes/232801/00-fix_editCredit.sql
deleted file mode 100644
index ff0d9e2b3..000000000
--- a/db/changes/232801/00-fix_editCredit.sql
+++ /dev/null
@@ -1,13 +0,0 @@
-UPDATE `salix`.`ACL`
- SET principalId='financialBoss'
- WHERE
- model = 'Client'
- AND property = 'editCredit';
-
-UPDATE `salix`.`ACL`
- SET property='zeroCreditEditor'
- WHERE
- model = 'Client'
- AND property = 'isNotEditableCredit';
-
-
diff --git a/db/changes/232801/00-user.sql b/db/changes/232801/00-user.sql
deleted file mode 100644
index 376b3dbb1..000000000
--- a/db/changes/232801/00-user.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-alter table `account`.`user`
- add `twoFactor` ENUM ('email') null comment 'Two-factor auth type';
-
-DELETE FROM `salix`.`ACL`
- WHERE model = 'VnUser' AND property = 'changePassword';
diff --git a/db/changes/232802/01-aclWorkerDisable.sql b/db/changes/232802/01-aclWorkerDisable.sql
deleted file mode 100644
index 149dd6f15..000000000
--- a/db/changes/232802/01-aclWorkerDisable.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('WorkerDisableExcluded', '*', 'READ', 'ALLOW', 'ROLE', 'itManagement'),
- ('WorkerDisableExcluded', '*', 'WRITE', 'ALLOW', 'ROLE', 'itManagement');
diff --git a/db/changes/233001/.gitkeep b/db/changes/233001/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/233001/00-aclSaleTracking.sql b/db/changes/233001/00-aclSaleTracking.sql
deleted file mode 100644
index 6a699091a..000000000
--- a/db/changes/233001/00-aclSaleTracking.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('SaleTracking', 'deleteSaleGroupDetail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('SaleTracking', 'replaceOrCreate', 'WRITE', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/233001/00-clientSms.sql b/db/changes/233001/00-clientSms.sql
deleted file mode 100644
index e1e34f6b2..000000000
--- a/db/changes/233001/00-clientSms.sql
+++ /dev/null
@@ -1,15 +0,0 @@
-CREATE TABLE `vn`.`clientSms` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `clientFk` int(11) NOT NULL,
- `smsFk` mediumint(8) unsigned NOT NULL,
- PRIMARY KEY (`id`),
- KEY `clientSms_FK` (`clientFk`),
- KEY `clientSms_FK_1` (`smsFk`),
- CONSTRAINT `clientSms_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `clientSms_FK_1` FOREIGN KEY (`smsFk`) REFERENCES `sms` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('ClientSms', 'find', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('ClientSms', 'create', 'WRITE', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/233001/00-company.sql b/db/changes/233001/00-company.sql
deleted file mode 100644
index a3b61b9cc..000000000
--- a/db/changes/233001/00-company.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`company` MODIFY COLUMN sage200Company int(2) DEFAULT 10 NOT NULL;
diff --git a/db/changes/233001/00-fixACLVehicle.sql b/db/changes/233001/00-fixACLVehicle.sql
deleted file mode 100644
index 6625f0d5c..000000000
--- a/db/changes/233001/00-fixACLVehicle.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalId`)
- VALUES
- ('Vehicle','sorted','WRITE','ALLOW','employee');
\ No newline at end of file
diff --git a/db/changes/233001/00-itemRecycle.sql b/db/changes/233001/00-itemRecycle.sql
deleted file mode 100644
index c191e5d1c..000000000
--- a/db/changes/233001/00-itemRecycle.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-ALTER TABLE `vn`.`item` ADD recycledPlastic INT NULL;
-ALTER TABLE `vn`.`item` ADD nonRecycledPlastic INT NULL;
diff --git a/db/changes/233001/00-itemShelving_inventory.sql b/db/changes/233001/00-itemShelving_inventory.sql
deleted file mode 100644
index b0b080ef3..000000000
--- a/db/changes/233001/00-itemShelving_inventory.sql
+++ /dev/null
@@ -1,64 +0,0 @@
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_inventory`(vParkingFromFk VARCHAR(8), vParkingToFk VARCHAR(8))
-BEGIN
-/**
- * Devuelve un listado de ubicaciones a revisar
- *
- * @param vParkingFromFk Parking de partida, identificador de parking
- * @param vParkingToFk Parking de llegada, identificador de parking
-*/
-
- DECLARE vSectorFk INT;
- DECLARE vPickingOrderFrom INT;
- DECLARE vPickingOrderTo INT;
-
- SELECT p.sectorFk, p.pickingOrder INTO vSectorFk, vPickingOrderFrom
- FROM parking p
- WHERE p.code = vParkingFromFk COLLATE 'utf8mb3_general_ci';
-
- SELECT p.pickingOrder INTO vPickingOrderTo
- FROM parking p
- WHERE p.code = vParkingToFk COLLATE 'utf8mb3_general_ci';
-
- CALL visible_getMisfit(vSectorFk);
-
- SELECT ish.id,
- p.pickingOrder,
- p.code parking,
- ish.shelvingFk,
- ish.itemFk,
- i.longName,
- ish.visible,
- p.sectorFk,
- it.workerFk buyer,
- CONCAT('http:',ic.url, '/catalog/1600x900/',i.image) urlImage,
- ish.isChecked,
- CASE
- WHEN s.notPrepared > sm.parked THEN 0
- WHEN sm.visible > sm.parked THEN 1
- ELSE 2
- END priority
- FROM itemShelving ish
- JOIN item i ON i.id = ish.itemFk
- JOIN itemType it ON it.id = i.typeFk
- JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
- JOIN parking p ON p.id = sh.parkingFk
- JOIN (SELECT s.itemFk, sum(s.quantity) notPrepared
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- JOIN warehouse w ON w.id = t.warehouseFk
- JOIN config c ON c.mainWarehouseFk = w.id
- WHERE t.shipped BETWEEN util.VN_CURDATE()
- AND util.dayEnd(util.VN_CURDATE())
- AND s.isPicked = FALSE
- GROUP BY s.itemFk) s ON s.itemFk = i.id
- JOIN hedera.imageConfig ic
- WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo
- AND p.sectorFk = vSectorFk
- ORDER BY p.pickingOrder;
-
-END$$
-DELIMITER ;
-
diff --git a/db/changes/233001/00-noUniqueSocialName.sql b/db/changes/233001/00-noUniqueSocialName.sql
deleted file mode 100644
index 0dc4c832f..000000000
--- a/db/changes/233001/00-noUniqueSocialName.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-ALTER TABLE `vn`.`country`
-ADD COLUMN `isSocialNameUnique` tinyint(1) NOT NULL DEFAULT 1;
diff --git a/db/changes/233001/00-roadmap.sql b/db/changes/233001/00-roadmap.sql
deleted file mode 100644
index 9b5db54eb..000000000
--- a/db/changes/233001/00-roadmap.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-ALTER TABLE `vn`.`roadmap` COMMENT='Troncales diarios que se contratan';
-ALTER TABLE `vn`.`roadmap` ADD price decimal(10,2) NULL;
-ALTER TABLE `vn`.`roadmap` ADD driverName varchar(45) NULL;
-ALTER TABLE `vn`.`roadmap` ADD name varchar(45) NOT NULL;
-ALTER TABLE `vn`.`roadmap` CHANGE name name varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL AFTER id;
-ALTER TABLE `vn`.`roadmap` MODIFY COLUMN etd datetime NOT NULL;
-
-ALTER TABLE `vn`.`expeditionTruck` COMMENT='Distintas paradas que hacen los trocales';
diff --git a/db/changes/233001/00-roadmapACL.sql b/db/changes/233001/00-roadmapACL.sql
deleted file mode 100644
index 4fc116f86..000000000
--- a/db/changes/233001/00-roadmapACL.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Roadmap', '*', '*', 'ALLOW', 'ROLE', 'palletizerBoss'),
- ('Roadmap', '*', '*', 'ALLOW', 'ROLE', 'productionBoss'),
- ('ExpeditionTruck', '*', '*', 'ALLOW', 'ROLE', 'palletizerBoss'),
- ('ExpeditionTruck', '*', '*', 'ALLOW', 'ROLE', 'productionBoss');
diff --git a/db/changes/233001/00-ticketWeight.sql b/db/changes/233001/00-ticketWeight.sql
deleted file mode 100644
index 0b727b434..000000000
--- a/db/changes/233001/00-ticketWeight.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-UPDATE `vn`.`ticket` t
- JOIN `vn`.`ticketObservation` o ON o.ticketFk = t.id
- SET t.weight = cast(REPLACE(o.description, ',', '.') as decimal(10,2))
- WHERE o.observationTypeFk = 6;
-
-DELETE FROM `vn`.`ticketObservation` WHERE observationTypeFk = 6;
-DELETE FROM `vn`.`observationType` WHERE id = 6;
diff --git a/db/changes/233201/.gitkeep b/db/changes/233201/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/233201/00-acl_viaexpressConfig.sql b/db/changes/233201/00-acl_viaexpressConfig.sql
deleted file mode 100644
index d4c186dd4..000000000
--- a/db/changes/233201/00-acl_viaexpressConfig.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('ViaexpressConfig', 'internationalExpedition', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('ViaexpressConfig', 'renderer', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/233201/00-transferClient.sql b/db/changes/233201/00-transferClient.sql
deleted file mode 100644
index 8a7ce0543..000000000
--- a/db/changes/233201/00-transferClient.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`)
- VALUES ('Ticket','transferClient','WRITE','ALLOW','ROLE','administrative');
\ No newline at end of file
diff --git a/db/changes/233201/00-updatePrice.sql b/db/changes/233201/00-updatePrice.sql
deleted file mode 100644
index 959943d6f..000000000
--- a/db/changes/233201/00-updatePrice.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`)
- VALUES ('Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer');
diff --git a/db/changes/233201/00-viaexpress.sql b/db/changes/233201/00-viaexpress.sql
deleted file mode 100644
index 42cf3b647..000000000
--- a/db/changes/233201/00-viaexpress.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-CREATE TABLE `vn`.`viaexpressConfig` (
- id int auto_increment NOT NULL,
- url varchar(100) NOT NULL,
- client varchar(100) NOT NULL,
- user varchar(100) NOT NULL,
- password varchar(100) NOT NULL,
- defaultWeight decimal(10,2) NOT NULL,
- deliveryType varchar(5) NOT NULL,
- CONSTRAINT viaexpressConfig_PK PRIMARY KEY (id)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
diff --git a/db/changes/233201/00-workerDocuware.sql b/db/changes/233201/00-workerDocuware.sql
deleted file mode 100644
index 2f2c4a1cd..000000000
--- a/db/changes/233201/00-workerDocuware.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-ALTER TABLE `vn`.`docuware` ADD dmsTypeFk INT(11) DEFAULT NULL NULL;
-ALTER TABLE `vn`.`docuware` ADD CONSTRAINT docuware_FK FOREIGN KEY (dmsTypeFk) REFERENCES `vn`.`dmsType`(id) ON DELETE RESTRICT ON UPDATE CASCADE;
-INSERT INTO `vn`.`docuware` (code, fileCabinetName, `action`, dialogName, findById, dmsTypeFk)
- VALUES
- ('hr', 'RRHH', 'find', 'Búsqueda', 'N__DOCUMENTO', NULL); -- set dmsTypeFk 3 when deploy in production
-
-INSERT INTO `salix`.`url` (appName, environment, url)
- VALUES
- ('docuware', 'production', 'https://verdnatura.docuware.cloud/DocuWare/Platform/');
-
diff --git a/db/changes/233202/00-ticketSmsACL.sql b/db/changes/233202/00-ticketSmsACL.sql
deleted file mode 100644
index a25a876f8..000000000
--- a/db/changes/233202/00-ticketSmsACL.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('TicketSms', 'find', 'READ', 'ALLOW', 'ROLE', 'salesPerson');
diff --git a/db/changes/233401/00-setDeleted_acl.sql b/db/changes/233401/00-setDeleted_acl.sql
deleted file mode 100644
index cdeff9522..000000000
--- a/db/changes/233401/00-setDeleted_acl.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-UPDATE `salix`.`ACL`
- SET principalId='salesPerson'
- WHERE
- model='Ticket'
- AND property='setDeleted'
- AND accessType='WRITE';
diff --git a/db/changes/233601/.gitkeep b/db/changes/233601/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/233601/00-addExpeditionState.sql b/db/changes/233601/00-addExpeditionState.sql
deleted file mode 100644
index fb236b0c3..000000000
--- a/db/changes/233601/00-addExpeditionState.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`)
- VALUES ('ExpeditionState','addExpeditionState','WRITE','ALLOW','ROLE','delivery');
\ No newline at end of file
diff --git a/db/changes/233601/00-createClaimReader.sql b/db/changes/233601/00-createClaimReader.sql
deleted file mode 100644
index e913c0ed9..000000000
--- a/db/changes/233601/00-createClaimReader.sql
+++ /dev/null
@@ -1,31 +0,0 @@
-INSERT INTO `account`.`role` (`name`, `description`, `hasLogin`)
- VALUES ('claimViewer','Trabajadores que consulta las reclamaciones ',1);
-
-INSERT INTO `account`.`roleInherit` (`role`,`inheritsFrom`)
- SELECT `r`.`id`, `r2`.`id`
- FROM `account`.`role` `r`
- JOIN `account`.`role` `r2` ON `r2`.`name` = 'claimViewer'
- WHERE `r`.`name` IN (
- 'salesPerson',
- 'buyer',
- 'deliveryBoss',
- 'handmadeBoss'
- );
-
-DELETE FROM `salix`.`ACL`
- WHERE `model`= 'claim'
- AND `property` IN (
- 'filter',
- 'find',
- 'findById',
- 'getSummary'
- );
-
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`)
- VALUES ('Claim','filter','READ','ALLOW','ROLE','claimViewer');
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`)
- VALUES ('Claim','find','READ','ALLOW','ROLE','claimViewer');
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`)
- VALUES ('Claim','findById','READ','ALLOW','ROLE','claimViewer');
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`)
- VALUES ('Claim','getSummary','READ','ALLOW','ROLE','claimViewer');
\ No newline at end of file
diff --git a/db/changes/233601/00-department.sql b/db/changes/233601/00-department.sql
deleted file mode 100644
index 777d26b9f..000000000
--- a/db/changes/233601/00-department.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-UPDATE `vn`.`department`
- SET code='VN'
-WHERE name='VERDNATURA';
diff --git a/db/changes/233601/00-saleGroupDetail.sql b/db/changes/233601/00-saleGroupDetail.sql
deleted file mode 100644
index d16478716..000000000
--- a/db/changes/233601/00-saleGroupDetail.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-DELETE FROM `vn`.`saleGroupDetail` WHERE id IN (468106,468104,468107,468105,495210,495208,495207,495209,462879,462880,447186,450623,450622,455606,455605,455827,455829,455828,459067,460689,460691,460690,460692,462408,463403,463405,463404,463129,463127,463126,463128,468098,468096,468099,468097,468310,468314,468313,475654,468325,473248,474803,474739,475042,475052,475047,475041,475051,475046,475040,475050,475045,475039,475049,475044,475038,475048,475043,474888,474892,474890,474887,474891,474889,481109,481107,481105,481108,481106,481110,479008,490787,490792,490791,485295,485294,485293,485528,490796,487853,487959,491303,490789,490914,490913,492305,492310,492307,492304,492309,492306,492303,492308,494111,494110,494480,494482,494481,494483,495202,495200,495199,495201,497209,499765,499763,499767,499764,499768,499766,502014,502013,508820,508819,508818,463133,463131,463130,463132,468102,468100,468103,468101,468311,468316,468315,468327,474894,474898,474896,474893,474897,474895,495206,495204,495203,495205,499771,499769,499773,499770,499774,499772);
-ALTER TABLE `vn`.`saleGroupDetail` ADD CONSTRAINT saleGroupDetail_UN UNIQUE KEY (saleFk);
-
-INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalId`)
- VALUES
- ('SaleGroupDetail','deleteById','WRITE','ALLOW','employee');
-
diff --git a/db/changes/233801/.gitkeep b/db/changes/233801/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/233801/00-firstScript.sql b/db/changes/233801/00-firstScript.sql
deleted file mode 100644
index 47b96b3bc..000000000
--- a/db/changes/233801/00-firstScript.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`province` ADD CONSTRAINT `countryName_UN` UNIQUE KEY (`countryFk`,`name`);
diff --git a/db/changes/233801/01-deviceLog_acl.sql b/db/changes/233801/01-deviceLog_acl.sql
deleted file mode 100644
index 2b646a6a3..000000000
--- a/db/changes/233801/01-deviceLog_acl.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-
--- ALTER TABLE `vn`.`deviceLog` ADD serialNumber varchar(45) DEFAULT NULL NULL;
-
--- INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId)
--- VALUES( 'DeviceLog', 'create', 'WRITE', 'ALLOW', 'ROLE', 'employee');
-
diff --git a/db/changes/233802/.gitkeep b/db/changes/233802/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/233802/00-collectionGetTicketsACL.sql b/db/changes/233802/00-collectionGetTicketsACL.sql
deleted file mode 100644
index 06b584386..000000000
--- a/db/changes/233802/00-collectionGetTicketsACL.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL`(model, property, accessType, permission, principalType, principalId)
- VALUES
- ('Collection', 'getTickets', 'WRITE', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/234001/.gitkeep b/db/changes/234001/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/234001/00-aclClient.sql b/db/changes/234001/00-aclClient.sql
deleted file mode 100644
index 109b3a4fb..000000000
--- a/db/changes/234001/00-aclClient.sql
+++ /dev/null
@@ -1,42 +0,0 @@
--- No encuentro este back
-DELETE FROM `salix`.`ACL` WHERE property = 'activeWorkersWithRole';
-DELETE FROM `salix`.`ACL` WHERE model = 'Client' AND property = '*';
-
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Client','findOne','READ','ALLOW','ROLE','employee');
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Client','findById','READ','ALLOW','ROLE','employee');
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Client','find','READ','ALLOW','ROLE','employee');
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Client','exists','READ','ALLOW','ROLE','employee');
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Client','__get__addresses','READ','ALLOW','ROLE','employee');
-
-DELETE FROM `salix`.`ACL` WHERE model = 'Client' AND property = '*' AND accessType IN (
- 'campaignMetricsEmail',
- 'campaignMetricsPdf',
- 'clientDebtStatementEmail',
- 'clientDebtStatementHtml',
- 'clientDebtStatementPdf',
- 'clientWelcomeEmail',
- 'clientWelcomeHtml',
- 'consumptionSendQueued',
- 'creditRequestEmail',
- 'creditRequestHtml',
- 'creditRequestPdf',
- 'getClientOrSupplierReference',
- 'incotermsAuthorizationEmail',
- 'incotermsAuthorizationHtml',
- 'incotermsAuthorizationPdf',
- 'letterDebtorNdEmail',
- 'letterDebtorNdHtml',
- 'letterDebtorPdf',
- 'letterDebtorStEmail',
- 'letterDebtorStHtml',
- 'printerSetupEmail',
- 'printerSetupHtml',
- 'sepaCoreEmail',
- 'setPassword',
- 'updateUser',
- 'uploadFile');
diff --git a/db/changes/234001/00-dropUserFk.sql b/db/changes/234001/00-dropUserFk.sql
deleted file mode 100644
index d6ce328a8..000000000
--- a/db/changes/234001/00-dropUserFk.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-ALTER TABLE `vn`.`worker` DROP KEY `user_id_UNIQUE`;
-
-ALTER TABLE `vn`.`worker` DROP COLUMN `userFk`;
-
diff --git a/db/changes/234001/00-models.sql b/db/changes/234001/00-models.sql
deleted file mode 100644
index abf1e3ea5..000000000
--- a/db/changes/234001/00-models.sql
+++ /dev/null
@@ -1,11 +0,0 @@
-INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId)
- VALUES
- ('ExpeditionMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('WorkerMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee'),
- ('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'),
- ('MistakesTypes', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'),
- ('MistakeType','*','READ','ALLOW','ROLE','employee'),
- ('MachineWorker', '*', 'READ', 'ALLOW', 'ROLE', 'coolerAssist'),
- ('Printer','*','READ','ALLOW','ROLE','employee'),
- ('SaleMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'production');
diff --git a/db/changes/234001/00-ticketConfig.sql b/db/changes/234001/00-ticketConfig.sql
deleted file mode 100644
index 5429878b4..000000000
--- a/db/changes/234001/00-ticketConfig.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-
- INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES('Item', 'setVisibleDiscard', 'WRITE', 'ALLOW', 'ROLE', 'employee');
-
- INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES('Address', 'getAddress', 'READ', 'ALLOW', 'ROLE', 'employee');
-
diff --git a/db/changes/234001/00-updateAfterBusinnesInsert.sql b/db/changes/234001/00-updateAfterBusinnesInsert.sql
deleted file mode 100644
index 71356db80..000000000
--- a/db/changes/234001/00-updateAfterBusinnesInsert.sql
+++ /dev/null
@@ -1,57 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `account`.`account_enable`(vSelf INT)
-BEGIN
-/**
- * Enables a worker's account and sets up email configurations.
- */
- UPDATE user
- SET active = TRUE
- WHERE id = vSelf;
-
- INSERT IGNORE INTO account
- SET id = vSelf;
-
- INSERT IGNORE INTO mailAliasAccount (mailAlias, account)
- SELECT id, vSelf
- FROM mailAlias
- WHERE alias = 'general';
-
- INSERT IGNORE INTO mailForward (account, forwardTo)
- SELECT vSelf, email
- FROM user
- WHERE id = vSelf;
-END$$
-DELIMITER ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_updateBusiness`(vSelf INT)
-BEGIN
-/**
- * Activates an account and configures its email settings.
- *
- * @param vSelf account id.
- */
- DECLARE vOldBusinessFk INT;
- DECLARE vNewBusinessFk INT;
-
- SELECT businessFk INTO vOldBusinessFk FROM worker WHERE id = vSelf;
-
- SELECT id INTO vNewBusinessFk
- FROM business
- WHERE workerFk = vSelf
- AND util.VN_CURDATE() BETWEEN started AND IFNULL(ended, util.VN_CURDATE());
-
- UPDATE worker
- SET businessFk = vNewBusinessFk
- WHERE id = vSelf;
-
- IF NOT (vOldBusinessFk <=> vNewBusinessFk) THEN
- IF vNewBusinessFk IS NULL THEN
- CALL workerDisable(vSelf);
- END IF;
- IF vOldBusinessFk IS NULL THEN
- CALL account.account_enable(vSelf);
- END IF;
- END IF;
-END$$
-DELIMITER ;
diff --git a/db/changes/234001/01-aclAccount.sql b/db/changes/234001/01-aclAccount.sql
deleted file mode 100644
index d749b52ab..000000000
--- a/db/changes/234001/01-aclAccount.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-DELETE FROM `salix`.`ACL` WHERE model = 'Account' AND property = '*' AND principalId = 'employee';
-
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Account','findOne','READ','ALLOW','ROLE','employee');
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Account','findById','READ','ALLOW','ROLE','employee');
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Account','find','READ','ALLOW','ROLE','employee');
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Account','exists','READ','ALLOW','ROLE','employee');
diff --git a/db/changes/234001/01-deliveryAssistantACL.sql b/db/changes/234001/01-deliveryAssistantACL.sql
deleted file mode 100644
index 0f273325f..000000000
--- a/db/changes/234001/01-deliveryAssistantACL.sql
+++ /dev/null
@@ -1,21 +0,0 @@
--- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values.
-INSERT INTO `account`.`role` (name, description)
- VALUES ('deliveryAssistant','Jefe auxiliar repartos');
-
-INSERT INTO `account`.`roleInherit` (role, inheritsFrom)
- SELECT (SELECT id FROM account.role r1 WHERE r1.name = 'deliveryAssistant'), ri.inheritsFrom
- FROM account.roleInherit ri
- JOIN account.role r2 ON r2.id = ri.`role`
- WHERE r2.name = 'deliveryBoss';
-
-DELETE `account`.`roleInherit` FROM `account`.`roleInherit`
- JOIN `account`.`role` r ON `account`.`roleInherit`.role = r.id
- WHERE r.name = 'deliveryBoss';
-
-INSERT INTO `account`.`roleInherit` (role, inheritsFrom)
- SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role,
- (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit;
-
-UPDATE `salix`.`ACL`
- SET principalId='deliveryAssistant'
- WHERE principalId='deliveryBoss';
diff --git a/db/changes/234001/01-workerCreate.sql b/db/changes/234001/01-workerCreate.sql
deleted file mode 100644
index 166c65a26..000000000
--- a/db/changes/234001/01-workerCreate.sql
+++ /dev/null
@@ -1,20 +0,0 @@
-DELIMITER $$
-$$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerCreate`(
- vFirstname VARCHAR(50),
- vLastName VARCHAR(50),
- vCode CHAR(3),
- vBossFk INT,
- vUserFk INT,
- vFi VARCHAR(15) ,
- vBirth DATE
-)
-BEGIN
-/**
- * Create new worker
- *
- */
- INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth)
- VALUES (vUserFk, vCode, vFirstname, vLastName, vBossFk, vFi, vBirth);
-END$$
-DELIMITER ;
diff --git a/db/changes/234001/02-roleSync.sql b/db/changes/234001/02-roleSync.sql
deleted file mode 100644
index 6fe47f691..000000000
--- a/db/changes/234001/02-roleSync.sql
+++ /dev/null
@@ -1,2 +0,0 @@
--- Locally it fails because it is executed before the fixtures and the roleConfig table is empty
-CALL `account`.`role_syncPrivileges`();
diff --git a/db/changes/234002/.gitkeep b/db/changes/234002/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/234002/01-itemShelvingSale.sql b/db/changes/234002/01-itemShelvingSale.sql
deleted file mode 100644
index 817c6317a..000000000
--- a/db/changes/234002/01-itemShelvingSale.sql
+++ /dev/null
@@ -1,291 +0,0 @@
-ALTER TABLE `vn`.`itemShelvingSale` DROP COLUMN IF EXISTS isPicked;
-
-ALTER TABLE`vn`.`itemShelvingSale`
- ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL;
-
-ALTER TABLE `vn`.`productionConfig` DROP COLUMN IF EXISTS orderMode;
-
-ALTER TABLE `vn`.`productionConfig`
- ADD orderMode ENUM('Location', 'Age') NOT NULL DEFAULT 'Location';
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveByCollection`(
- vCollectionFk INT(11)
-)
-BEGIN
-/**
- * Reserva cantidades con ubicaciones para el contenido de una colección
- *
- * @param vCollectionFk Identificador de collection
- */
- CREATE OR REPLACE TEMPORARY TABLE tmp.sale
- (INDEX(saleFk))
- ENGINE = MEMORY
- SELECT s.id saleFk, NULL userFk
- FROM ticketCollection tc
- JOIN sale s ON s.ticketFk = tc.ticketFk
- LEFT JOIN (
- SELECT DISTINCT saleFk
- FROM saleTracking st
- JOIN state s ON s.id = st.stateFk
- WHERE st.isChecked
- AND s.semaphore = 1)st ON st.saleFk = s.id
- WHERE tc.collectionFk = vCollectionFk
- AND st.saleFk IS NULL
- AND NOT s.isPicked;
-
- CALL itemShelvingSale_reserve();
-END$$
-DELIMITER ;
-
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setQuantity`(
- vItemShelvingSaleFk INT(10),
- vQuantity DECIMAL(10,0),
- vIsItemShelvingSaleEmpty BOOLEAN
-)
-BEGIN
-/**
- * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity
- * en vn.itemShelvingSale y vn.sale.isPicked en caso necesario.
- * Si la reserva de la ubicación es fallida, se regulariza la situación
- *
- * @param vItemShelvingSaleFk Id itemShelvingSaleFK
- * @param vQuantity Cantidad real que se ha cogido de la ubicación
- * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha
- * quedado vacio tras el movimiento
- */
- DECLARE vSaleFk INT;
- DECLARE vCursorSaleFk INT;
- DECLARE vItemShelvingFk INT;
- DECLARE vReservedQuantity INT;
- DECLARE vRemainingQuantity INT;
- DECLARE vItemFk INT;
- DECLARE vUserFk INT;
- DECLARE vDone BOOLEAN DEFAULT FALSE;
- DECLARE vSales CURSOR FOR
- SELECT iss.saleFk, iss.userFk
- FROM itemShelvingSale iss
- JOIN sale s ON s.id = iss.saleFk
- WHERE iss.id = vItemShelvingSaleFk
- AND s.itemFk = vItemFk
- AND NOT iss.isPicked;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
- IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN
- CALL util.throw('Booking completed');
- END IF;
-
- SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk
- INTO vItemFk, vSaleFk, vItemShelvingFk
- FROM itemShelvingSale iss
- JOIN sale s ON s.id = iss.saleFk
- WHERE iss.id = vItemShelvingSaleFk
- AND NOT iss.isPicked;
-
- UPDATE itemShelvingSale
- SET isPicked = TRUE,
- quantity = vQuantity
- WHERE id = vItemShelvingSaleFk;
-
- UPDATE itemShelving
- SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity))
- WHERE id = vItemShelvingFk;
-
- IF vIsItemShelvingSaleEmpty THEN
- OPEN vSales;
-l: LOOP
- SET vDone = FALSE;
- FETCH vSales INTO vCursorSaleFk, vUserFk;
- IF vDone THEN
- LEAVE l;
- END IF;
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.sale
- (INDEX(saleFk, userFk))
- ENGINE = MEMORY
- SELECT vCursorSaleFk, vUserFk;
-
- CALL itemShelvingSale_reserveWhitUser();
- DROP TEMPORARY TABLE tmp.sale;
-
- END LOOP;
- CLOSE vSales;
-
- DELETE iss
- FROM itemShelvingSale iss
- JOIN sale s ON s.id = iss.saleFk
- WHERE iss.id = vItemShelvingSaleFk
- AND s.itemFk = vItemFk
- AND NOT iss.isPicked;
- END IF;
-
- SELECT SUM(quantity) INTO vRemainingQuantity
- FROM itemShelvingSale
- WHERE saleFk = vSaleFk
- AND NOT isPicked;
-
- IF vRemainingQuantity THEN
- CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL);
-
- SELECT SUM(quantity) INTO vRemainingQuantity
- FROM itemShelvingSale
- WHERE saleFk = vSaleFk
- AND NOT isPicked;
-
- IF NOT vRemainingQuantity <=> 0 THEN
- SELECT SUM(iss.quantity)
- INTO vReservedQuantity
- FROM itemShelvingSale iss
- WHERE iss.saleFk = vSaleFk;
-
- CALL saleTracking_new(
- vSaleFk,
- TRUE,
- vReservedQuantity,
- `account`.`myUser_getId`(),
- NULL,
- 'PREPARED',
- TRUE);
-
- UPDATE sale s
- SET s.quantity = vReservedQuantity
- WHERE s.id = vSaleFk ;
- END IF;
- END IF;
-END$$
-DELIMITER ;
-
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserve`()
-BEGIN
-/**
- * Reserva cantidades con ubicaciones para un conjunto de sales del mismo wareHouse
- *
- * @table tmp.sale(saleFk, userFk)
- */
- DECLARE vCalcFk INT;
- DECLARE vWarehouseFk INT;
- DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW());
- DECLARE vLastPickingOrder INT;
-
- SELECT t.warehouseFk, MAX(p.pickingOrder)
- INTO vWarehouseFk, vLastPickingOrder
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN tmp.sale ts ON ts.saleFk = s.id
- LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk
- LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- LEFT JOIN shelving sh ON sh.code = ish.shelvingFk
- LEFT JOIN parking p ON p.id = sh.parkingFk
- WHERE t.warehouseFk IS NOT NULL;
-
- IF vWarehouseFk IS NULL THEN
- CALL util.throw('Warehouse not set');
- END IF;
-
- CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
-
- SET @outstanding = 0;
- SET @oldsaleFk = 0;
-
- CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity
- (INDEX(saleFk))
- ENGINE = MEMORY
- SELECT saleFk, userFk, quantityToReserve, itemShelvingFk
- FROM( SELECT saleFk,
- sub.userFk,
- itemShelvingFk ,
- IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding),
- @qtr := LEAST(@outstanding, available) quantityToReserve,
- @outStanding := @outStanding - @qtr,
- @oldsaleFk := saleFk
- FROM(
- SELECT ts.saleFk,
- ts.userFk,
- s.quantity,
- ish.id itemShelvingFk,
- ish.visible - IFNULL(ishr.reservedQuantity, 0) available
- FROM tmp.sale ts
- JOIN sale s ON s.id = ts.saleFk
- JOIN itemShelving ish ON ish.itemFk = s.itemFk
- LEFT JOIN (
- SELECT itemShelvingFk, SUM(quantity) reservedQuantity
- FROM itemShelvingSale
- WHERE NOT isPicked
- GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id
- JOIN shelving sh ON sh.code = ish.shelvingFk
- JOIN parking p ON p.id = sh.parkingFk
- JOIN sector sc ON sc.id = p.sectorFk
- JOIN warehouse w ON w.id = sc.warehouseFk
- JOIN productionConfig pc
- WHERE w.id = vWarehouseFk
- AND NOT sc.isHideForPickers
- ORDER BY
- s.id,
- p.pickingOrder >= vLastPickingOrder,
- sh.priority DESC,
- ish.visible >= s.quantity DESC,
- s.quantity MOD ish.grouping = 0 DESC,
- ish.grouping DESC,
- IF(pc.orderMode = 'Location', p.pickingOrder, ish.created)
- )sub
- )sub2
- WHERE quantityToReserve > 0;
-
- INSERT INTO itemShelvingSale(
- itemShelvingFk,
- saleFk,
- quantity,
- userFk)
- SELECT itemShelvingFk,
- saleFk,
- quantityToReserve,
- IFNULL(userFk, getUser())
- FROM tSalePlacementQuantity spl;
-
- DROP TEMPORARY TABLE tmp.sale;
-END$$
-DELIMITER ;
-
-
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveBySale`(
- vSelf INT ,
- vQuantity INT,
- vUserFk INT
-)
-BEGIN
-/**
- * Reserva cantida y ubicación para una saleFk
- *
- * @param vSelf Identificador de la venta
- * @param vQuantity Cantidad a reservar
- * @param vUserFk Id de usuario que realiza la reserva
- */
- CREATE OR REPLACE TEMPORARY TABLE tmp.sale
- ENGINE = MEMORY
- SELECT vSelf saleFk, vUserFk userFk;
-
- CALL itemShelvingSale_reserve();
-END$$
-DELIMITER ;
-
-
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelvingSale_AFTER_INSERT`
- AFTER INSERT ON `itemShelvingSale`
- FOR EACH ROW
-BEGIN
-
- UPDATE vn.sale
- SET isPicked = TRUE
- WHERE id = NEW.saleFk;
-
-END$$
-DELIMITER ;
diff --git a/db/changes/234201/.gitkeep b/db/changes/234201/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/234201/00-aclClient.sql b/db/changes/234201/00-aclClient.sql
deleted file mode 100644
index 3df9522cf..000000000
--- a/db/changes/234201/00-aclClient.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-
-INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId)
- VALUES('TicketCollection', '*', 'WRITE', 'ALLOW', 'ROLE', 'production');
diff --git a/db/changes/234201/00-supplierAccountCheckLength.sql b/db/changes/234201/00-supplierAccountCheckLength.sql
deleted file mode 100644
index 55a68e37b..000000000
--- a/db/changes/234201/00-supplierAccountCheckLength.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-UPDATE `vn`.`supplier`
- SET account = LPAD(id,10,'0')
- WHERE account IS NULL;
-
-ALTER TABLE `vn`.`supplier` ADD CONSTRAINT supplierAccountTooShort CHECK (LENGTH(account) = 10);
-ALTER TABLE `vn`.`supplier` MODIFY COLUMN account varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT 4100000000 NOT NULL COMMENT 'Default accounting code for suppliers.';
diff --git a/db/docker.js b/db/docker.js
deleted file mode 100644
index ae49c3337..000000000
--- a/db/docker.js
+++ /dev/null
@@ -1,211 +0,0 @@
-const exec = require('child_process').exec;
-const log = require('fancy-log');
-const dataSources = require('../loopback/server/datasources.json');
-
-module.exports = class Docker {
- constructor(name) {
- Object.assign(this, {
- id: name,
- name,
- isRandom: name == null,
- dbConf: Object.assign({}, dataSources.vn)
- });
- }
-
- /**
- * Builds the database image and runs a container. It only rebuilds the
- * image when fixtures have been modified or when the day on which the
- * image was built is different to today. Some workarounds have been used
- * to avoid a bug with OverlayFS driver on MacOS.
- *
- * @param {Boolean} ci continuous integration environment argument
- * @param {String} networkName Name of the container network
- */
- async run(ci, networkName = 'jenkins') {
- log('Building container image...');
- await this.execP(`docker build -t salix-db ./db`);
- log('Image built.');
-
- let dockerArgs;
-
- if (this.isRandom)
- dockerArgs = '-p 3306';
- else {
- try {
- await this.rm();
- } catch (e) {}
- dockerArgs = `--name ${this.name} -p 3306:${this.dbConf.port}`;
- }
-
- let runChown = process.platform != 'linux';
-
- let network = '';
- if (ci) network = `--network="${networkName}"`;
-
- log('Starting container...');
- const container = await this.execP(
- `docker run ${network} --env RUN_CHOWN=${runChown} -d ${dockerArgs} salix-db`);
- this.id = container.stdout.trim();
-
- try {
- if (this.isRandom) {
- let inspect = await this.execP(`docker inspect -f "{{json .NetworkSettings}}" ${this.id}`);
- let netSettings = JSON.parse(inspect.stdout);
-
- if (ci) {
- this.dbConf.host = netSettings.Networks[networkName].IPAddress;
- this.dbConf.port = 3306;
- } else
- this.dbConf.port = netSettings.Ports['3306/tcp'][0]['HostPort'];
- }
-
- await this.wait();
- } catch (err) {
- if (this.isRandom)
- await this.rm();
- throw err;
- }
- }
-
- /**
- * Does the minium effort to start the database container, if it doesn't exists
- * calls the 'docker' task, if it is started does nothing. Keep in mind that when
- * you do not rebuild the docker you may be using an outdated version of it.
- * See the 'docker' task for more info.
- */
- async start() {
- let state;
- try {
- let result = await this.execP(`docker inspect -f "{{json .State}}" ${this.id}`);
- state = JSON.parse(result.stdout);
- } catch (err) {
- return await this.run();
- }
-
- switch (state.Status) {
- case 'running':
- return;
- case 'exited':
- await this.execP(`docker start ${this.id}`);
- await this.wait();
- return;
- default:
- throw new Error(`Unknown docker status: ${state.Status}`);
- }
- }
-
- waitForHealthy() {
- return new Promise((resolve, reject) => {
- let interval = 100;
- let elapsedTime = 0;
- let maxInterval = 4 * 60 * 1000;
-
- log('Waiting for MySQL init process...');
-
- async function checker() {
- elapsedTime += interval;
- let status;
-
- try {
- let result = await this.execP(`docker inspect -f "{{.State.Health.Status}}" ${this.id}`);
- status = result.stdout.trimEnd();
- } catch (err) {
- return reject(new Error(err.message));
- }
-
- if (status == 'unhealthy')
- return reject(new Error('Docker exited, please see the docker logs for more info'));
-
- if (status == 'healthy') {
- log('MySQL process ready.');
- return resolve();
- }
-
- if (elapsedTime >= maxInterval)
- reject(new Error(`MySQL not initialized whithin ${elapsedTime / 1000} secs`));
- else
- setTimeout(bindedChecker, interval);
- }
- let bindedChecker = checker.bind(this);
- bindedChecker();
- });
- }
-
- wait() {
- return new Promise((resolve, reject) => {
- const mysql = require('mysql2');
-
- let interval = 100;
- let elapsedTime = 0;
- let maxInterval = 4 * 60 * 1000;
-
- let myConf = {
- user: this.dbConf.username,
- password: this.dbConf.password,
- host: this.dbConf.host,
- port: this.dbConf.port,
- connectTimeout: maxInterval
- };
-
- log('Waiting for MySQL init process...');
-
- async function checker() {
- elapsedTime += interval;
- let state;
-
- try {
- let result = await this.execP(`docker inspect -f "{{json .State}}" ${this.id}`);
- state = JSON.parse(result.stdout);
- } catch (err) {
- return reject(new Error(err.message));
- }
-
- if (state.Status === 'exited')
- return reject(new Error('Docker exited, please see the docker logs for more info'));
-
- let conn = mysql.createConnection(myConf);
-
- conn.on('error', () => {});
- conn.connect(err => {
- conn.destroy();
- if (!err) {
- log('MySQL process ready.');
- return resolve();
- }
-
- if (elapsedTime >= maxInterval)
- reject(new Error(`MySQL not initialized whithin ${elapsedTime / 1000} secs`));
- else
- setTimeout(bindedChecker, interval);
- });
- }
- let bindedChecker = checker.bind(this);
- bindedChecker();
- });
- }
-
- rm() {
- return this.execP(`docker stop ${this.id} && docker rm -v ${this.id}`);
- }
-
- /**
- * Promisified version of exec().
- *
- * @param {String} command The exec command
- * @return {Promise} The promise
- */
- execP(command) {
- return new Promise((resolve, reject) => {
- exec(command, (err, stdout, stderr) => {
- if (err)
- reject(err);
- else {
- resolve({
- stdout: stdout,
- stderr: stderr
- });
- }
- });
- });
- }
-};
diff --git a/db/docker/docker-dump.sh b/db/docker/docker-dump.sh
deleted file mode 100755
index 0d7a379a7..000000000
--- a/db/docker/docker-dump.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/bin/bash
-
-export MYSQL_PWD=root
-FILE="/docker-boot/$1.sql"
-echo "[INFO] -> Importing $FILE"
-mysql -u root --default-character-set=utf8 --comments -f < "$FILE"
diff --git a/db/docker/docker-fixtures.sh b/db/docker/docker-fixtures.sh
deleted file mode 100755
index 0de6114d9..000000000
--- a/db/docker/docker-fixtures.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/bash
-
-. /usr/local/bin/docker-entrypoint.sh
-CMD=mysqld
-
-docker_setup_env "$CMD"
-docker_temp_server_start "$CMD"
-bash import-changes.sh
-docker-dump.sh fixtures
-docker_temp_server_stop
diff --git a/db/docker/docker-init.sh b/db/docker/docker-init.sh
deleted file mode 100755
index ccd14283e..000000000
--- a/db/docker/docker-init.sh
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/bin/bash
-
-. /usr/local/bin/docker-entrypoint.sh
-CMD=mysqld
-
-mysql_check_config "$CMD"
-docker_setup_env "$CMD"
-docker_create_db_directories
-
-docker_verify_minimum_env
-docker_init_database_dir "$CMD"
-docker_temp_server_start "$CMD"
-docker_setup_db
-docker_process_init_files /docker-entrypoint-initdb.d/*
diff --git a/db/docker/docker-start.sh b/db/docker/docker-start.sh
deleted file mode 100755
index 1db1933d1..000000000
--- a/db/docker/docker-start.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/bash
-
-# XXX: Workaround to avoid OverlayFS bug on MacOs
-# https://docs.docker.com/storage/storagedriver/overlayfs-driver/#limitations-on-overlayfs-compatibility
-
-if [ "$RUN_CHOWN" = "true" ]; then
- chown -R mysql:mysql /mysql-data
-fi
-
-exec "$@"
diff --git a/db/docker/docker-structure.sh b/db/docker/docker-structure.sh
deleted file mode 100755
index 75a1c24f3..000000000
--- a/db/docker/docker-structure.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/bash
-
-. docker-init.sh
-docker-dump.sh structure
-docker-dump.sh mockDate
-docker-dump.sh dumpedFixtures
-. docker-temp-stop.sh
diff --git a/db/docker/docker-temp-stop.sh b/db/docker/docker-temp-stop.sh
deleted file mode 100644
index df66959df..000000000
--- a/db/docker/docker-temp-stop.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/bash
-
-. /usr/local/bin/docker-entrypoint.sh
-CMD=mysqld
-
-docker_setup_env "$CMD"
-docker_temp_server_stop
diff --git a/db/docker/docker.cnf b/db/docker/docker.cnf
deleted file mode 100644
index be79ecf69..000000000
--- a/db/docker/docker.cnf
+++ /dev/null
@@ -1,8 +0,0 @@
-[mysqld]
-innodb_log_file_size = 4M
-innodb_autoextend_increment = 4
-innodb_page_size = 8K
-log_bin_trust_function_creators = ON
-datadir = /mysql-data
-sql_mode = NO_ENGINE_SUBSTITUTION
-skip-log-bin
diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql
new file mode 100644
index 000000000..8a419f697
--- /dev/null
+++ b/db/dump/.dump/data.sql
@@ -0,0 +1,2913 @@
+USE `util`;
+/*!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 */;
+
+INSERT INTO `version` VALUES ('vn-database','10962','5411433e529d50d68b3a0675b1a0a6215ea931ca','2024-03-25 17:47:37','10969');
+
+INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10113','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:13:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10114','00-updateConfig.sql','jenkins@10.0.2.69','2022-04-27 13:37:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10116','00-firstScript.sql','jenkins@10.0.2.69','2022-04-28 11:10:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10118','00-firstScript.sql','jenkins@10.0.2.69','2022-04-29 08:10:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10119','00-AfegirFKPart1.sql','jenkins@10.0.2.69','2022-05-05 10:13:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10119','01-AfegirFkPart2.sql','jenkins@10.0.2.69','2022-05-05 10:22:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10125','00-firstScript.sql','jenkins@10.0.2.68','2022-05-18 18:44:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10127','00-firstScript.sql','jenkins@10.0.2.69','2022-05-02 11:04:46',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10128','00-firstScript.sql','jenkins@10.0.2.69','2022-05-02 13:04:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10129','00-firstScript.sql','jenkins@10.0.2.69','2022-05-03 08:21:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10132','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:22:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10133','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 14:32:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10134','00-firstScript.sql','jenkins@10.0.2.69','2022-05-06 07:45:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10135','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 08:46:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10136','00-workerTimeControl.sql','jenkins@10.0.2.69','2022-05-09 13:51:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10138','00-firstScript.sql','jenkins@10.0.2.69','2022-05-10 13:58:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10139','00-firstScript.sql','jenkins@10.0.2.68','2022-05-16 14:32:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10139','01-secondScript.sql','jenkins@10.0.2.68','2022-05-17 12:16:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10141','00-firstScript.sql','jenkins@10.0.2.70','2022-05-12 08:27:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10142','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:20:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10143','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:20:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10144','00-AfegirFKPArt1.sql','jenkins@10.0.2.68','2022-05-20 09:22:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10147','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10149','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10150','00-firstScript.sql','jenkins@10.0.2.68','2022-05-17 09:57:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10152','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10153','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10154','00-compressionKk.sql','jenkins@10.0.2.68','2022-05-20 09:22:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10157','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10158','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:21',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10160','00-firstScript.sql','jenkins@10.0.2.69','2022-06-30 09:30:50',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10163','00-firstScript.sql','jenkins@10.0.2.68','2022-05-23 08:17:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10164','00-borrarSectorsDesus.sql','jenkins@10.0.2.68','2022-06-02 12:47:21',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10165','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10166','00-firstScript.sql','jenkins@10.0.2.68','2022-05-24 16:11:21',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10167','00-renameVnActiveContrat.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10168','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10169','00-createTableBankEntityConfig.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10169','02-addNotNullToBankEntityBic.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10171','00-volumeConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-18 14:11:11',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10171','01-itemWeight.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-18 16:01:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10171','02-agencymode.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-18 16:01:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10172','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10174','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 08:46:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10175','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10177','00-crearTablaSpecialLabels.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10178','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10179','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10183','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10184','00-firstScript.sql','jenkins@10.0.2.68','2022-06-03 08:05:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10185','00-firstScript.sql','jenkins@10.0.2.68','2022-06-06 09:07:45',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10186','00-desactivar_trigger.sql','jenkins@10.0.2.68','2022-06-07 09:31:23',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10186','01-alter_Table_buy.sql','jenkins@10.0.2.68','2022-06-07 09:34:47',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10186','02-alter_table_entryConfig.sql','jenkins@10.0.2.68','2022-06-07 09:34:47',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10186','04-regularizar_Sticker_Inventario.sql','jenkins@10.0.2.68','2022-06-07 09:34:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10186','09-reactivar_trigger.sql','jenkins@10.0.2.68','2022-06-07 09:34:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10187','00-firstScript.sql','jenkins@10.0.2.68','2022-06-06 12:37:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10188','00-firstScript.sql','jenkins@10.0.2.68','2022-06-06 14:03:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10189','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10191','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10193','00-delete.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10193','01-botanicExport.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10193','02-item.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10193','03-autonomy.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10193','03-turn.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10193','04-country.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10194','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10195','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10200','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10201','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10202','00-Remove_FK_to_ediGenus.sql','jenkins@10.0.2.69','2022-06-17 09:04:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10203','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10204','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10205','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:21',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10207','00-Alter_table_entry.sql','jenkins@10.0.2.69','2022-06-16 07:22:50',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10207','01-Update_invoiceAmount.sql','jenkins@10.0.2.69','2022-06-16 07:23:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10208','00-firstScript.sql','jenkins@10.0.2.69','2022-06-30 09:31:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10209','00-firstScript.sql','jenkins@10.0.2.69','2022-06-16 08:47:40',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10211','01-firstScript.sql','jenkins@10.0.2.69','2022-06-17 07:11:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10215','00-renameIsInventory.sql','jenkins@10.0.2.69','2022-06-30 09:31:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10216','00-firstScript.sql','jenkins@10.0.2.69','2022-06-23 11:15:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10216','01-batchIndex.sql','jenkins@10.0.2.70','2022-06-27 18:10:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10219','00-AddCollectionFkOnPackingSite.sql','jenkins@10.0.2.70','2022-06-29 09:23:42',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10219','01-AddFkToCollectionFk.sql','jenkins@10.0.2.70','2022-06-29 09:23:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10220','00-createPersonalProtectionEquipment.sql','jenkins@10.0.2.69','2022-06-30 09:31:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10222','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:12:40',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10223','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:52',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10224','00-cosetes.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-21 12:03:45',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10229','00-firstScript.sql','jenkins@10.0.2.69','2022-07-01 11:59:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10231','01-tablaEktConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:25:39',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10233','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10235','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10236','00-firstScript.sql','jenkins@10.0.2.69','2022-07-05 12:11:40',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10237','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10238','00-worker_mobileExtension.sql','jenkins@10.0.2.69','2022-07-14 09:14:09',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10239','00-firstScript.sql','jenkins@10.0.2.69','2022-07-07 21:51:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10241','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-29 08:14:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10242','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:14:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10243','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:14:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10245','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:34:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10247','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:34:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10248','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-20 17:27:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10250','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:36:40',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10253','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:36:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10254','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10256','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10258','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10259','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-02 08:54:56',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10261','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-22 08:42:20',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10262','00-createTablepackagingWithFreight.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10262','01-alterTablePackagingConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10262','02-insertsInicials.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10262','03-createTablepackingWithoutFreight.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10263','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10265','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10267','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10267','01-fixMerge.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10275','00-improvedGeneralLog.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-01 09:55:56',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10277','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10278','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-01 17:51:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10279','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10281','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10282','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10283','00-alterTable.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10284','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-04 16:59:08',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10285','00-firstScript.sql','jenkins@swarm-worker3.static.verdnatura.es','2022-08-05 09:19:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10287','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:35:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10288','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:35:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10289','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10291','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-10 14:19:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10293','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10297','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-16 12:43:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10298','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-13 21:04:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10299','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10301','00-productionConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10301','01-drop.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10301','02-collection.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10302','00-CreateTableEntryType.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10302','01-insertDataEntryType.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10302','02-alterTableEntry.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10303','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:23',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10304','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:23:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10304','01-altertableticket.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:23:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10305','00-ektAssign.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:24:52',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10306','00-deliveryInformation.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:25:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10307','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:25:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10308','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:26:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10309','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-06 11:37:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10310','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10311','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-06 11:37:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10312','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10313','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:27:21',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10314','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-20 12:37:19',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10315','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:31:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10317','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:31:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10318','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:31:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10319','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-20 12:37:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10320','00-operator.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10320','01-collection.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10320','02-productionConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10321','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 11:11:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10322','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-09 09:19:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10326','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10328','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10329','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10330','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10332','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10334','00-collectionHotbed.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10334','01-saleGroupDetail.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10335','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10336','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10337','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10339','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-19 09:41:19',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10340','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10341','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10342','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10343','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:35:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10345','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10347','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10347','01-addVirtualField.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10349','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10350','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-30 10:11:56',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10352','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10353','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10354','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10356','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-10 22:35:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10356','01-orderConfigFk.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-10 22:35:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10356','02-orderConfigDrop.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-10 22:35:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10357','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10359','00-improvedGeneralLog_collate.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:39',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10360','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:39',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10361','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 11:16:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10362','00-dropUdfs.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-10 11:01:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10363','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10365','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-13 19:30:46',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10368','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10369','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-14 13:38:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10370','00-deleteForeignKey.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10370','01-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:47',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10370','02-deleteTable.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:49',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10370','03-accion.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:49',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10370','04-inter.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10371','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:23',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10372','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10373','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-19 08:31:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10378','00-rename_routeUserPercentage.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10379','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10382','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:47:20',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10383','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10384','00-business_workcenterFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:18:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10385','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10386','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10387','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-16 14:05:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10388','00-resizeUtilVerionLogCode.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:47:20',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10388','01-resizeUtilVersionCode.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:47:20',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10390','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10391','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:23',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10394','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10395','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10396','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 15:36:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10397','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10399','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10400','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10402','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-21 14:11:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10404','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10405','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:58:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10407','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:49',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10408','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:23',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10409','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:49',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10412','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-30 12:45:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10413','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10416','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10420','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10421','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10426','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:40',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10428','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-26 13:27:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10431','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10433','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-26 13:27:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10434','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-26 13:27:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10435','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-13 07:30:10',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10436','00-createFkWorker.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:58:59',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10436','01-addStateToWorkerProductivity.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10436','02-DeprecateVnSaleTrackingState.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10436','03-DeprecateColumnVnSaleTrackingActionFk.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10436','04-DropSchemaVnControl.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10436','05-RemoveFkWorkerProductivity.sql','jenkins@db-proxy2.static.verdnatura.es','2023-02-17 14:51:19',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10439','00-fixRole.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:13:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10440','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10444','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10445','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10448','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10450','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-27 08:28:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10451','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-06 08:08:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10452','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:30:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10453','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 14:04:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10454','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:30:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10455','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:30:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10456','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:00:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10457','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:00:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10458','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10459','00-alterTableUtilConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10459','01-createFunctionCurdate.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10459','02-createFunctionMockTime.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10459','03-createFunctionMockTimeBase.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10459','04-createFunctionNow.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10460','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10461','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10463','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-03 12:59:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10468','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10469','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10470','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10471','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10472','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10477','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10478','00-dropBasket.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10478','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10478','01-orderConfigured.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:29:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10478','02-configuredUpdate.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:29:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10478','99-privileges.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:29:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10480','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-17 15:09:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10481','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-17 16:37:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10482','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-02-21 10:00:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10485','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10488','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10491','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10492','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10493','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:18:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10495','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:19',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10498','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10500','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-03-03 07:06:03',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10501','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-03-03 10:52:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10502','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10504','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:13:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10506','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10506','01-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10506','02-secondScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10506','03-thirdScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10507','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:35:23',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10508','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10510','00-dropBusinessFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:47',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10510','01-createTableProfessionalCategory.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:47',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10510','02-exportToNewTable.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:47',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10510','03-RecreateFK.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10510','04-kkPostgresqlTable.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10511','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10512','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:52',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10513','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:56',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10514','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10516','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10521','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-21 06:58:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10522','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10523','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10524','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10524','01-rateEditorFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10525','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-21 12:42:50',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10526','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10528','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:37:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10530','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-03-23 14:49:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10531','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-24 11:47:10',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10532','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-24 11:17:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10533','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:37:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10537','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-29 15:18:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10538','00-createChronopostConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10538','01-createChronopostService.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10538','02-createChronopostExpedition.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10538','03-createChronopostSenderAddress.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10538','04-addgrantPrivilegies.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10538','05-updateChronopostConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 11:54:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10539','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:37:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10540','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:18:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10545','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-11 08:31:03',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10546','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:08:10',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10547','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:21:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10549','00-updateUpdateLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:29:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10549','01-updateInsertLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:30:11',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10549','02-updateDeleteLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:30:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10549','03-deleteEmptyLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:31:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10549','04-optimizeLogTables.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:33:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10550','00-editorFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:42:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10550','01-originFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10552','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-13 08:25:10',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10554','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:08:10',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10557','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-17 07:45:56',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10559','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-18 10:53:50',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10560','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-17 09:19:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10562','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10563','00-delivery_ticketFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-20 09:30:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10566','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-20 10:08:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10567','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-20 10:18:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10568','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10569','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-24 09:14:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10570','00-createSendingConfig.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10570','01-createSendingServiceWeekday.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10570','02-createSendingService.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10570','03-permisos.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10571','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:13:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10573','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:23',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10575','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-26 11:27:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10577','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-27 14:00:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10578','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10579','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-28 11:27:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10580','00-itemTypeDropConstraint.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-28 18:18:52',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10580','01-itemTypeAddConstraint.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-28 18:19:10',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10581','00-itemTypeAutoIncrement.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-28 19:06:46',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10582','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10583','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10584','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','00-ticketLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:20:10',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','01-entryLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:21:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','02-claimLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:28:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','03-clientLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:28:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','04-invoiceInLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:28:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','05-itemLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:29:46',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','06-routeLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','07-shelvingLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','08-supplierLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','09-travelLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','10-workerLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:42',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','11-zoneLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','12-userLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10585','13-roleLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10587','00-arcRead_addMinimum.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-16 13:13:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10593','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10596','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10597','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10598','00-workerLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10598','01-supplierLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10598','02-workerTimeControlLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10598','03-workerClockLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10599','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10601','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-17 09:26:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10602','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-18 08:52:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10606','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-18 09:26:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10608','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-18 12:36:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10609','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-01 08:28:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10610','00-updateCompanyId.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10610','01-updateSupplierId.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:39',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10610','02-invoiceOutCompany.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-01 09:49:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10611','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-19 14:39:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10613','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10614','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:40',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10615','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:40',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10616','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:18:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10616','01-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:18:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10617','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10618','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 12:55:56',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10619','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10620','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:20:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10624','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-30 19:01:10',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10625','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10626','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 13:32:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10628','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10630','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-02 13:30:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10631','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-05 08:37:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10632','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10633','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10634','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-06 12:15:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10637','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:19',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10640','00-companyFkDrop.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:43:23',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10640','01-companyFkAi.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:43:23',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10640','02-companyFkCreate.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:47:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10640','04-supplierFkDrop.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:48:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10640','05-supplierFkAi.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:53:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10640','06-supplierFkCreate.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 15:06:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10642','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 14:04:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10643','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-09 15:04:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10644','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10645','00-addNewFields.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:11',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10645','01-updateCollectionWagonPrimaryKey.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:11',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10645','02-updateWagonPrimaryKey.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10645','03-addFieldToPackingSite.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10647','00-renombrarTabla.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 14:04:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10648','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10649','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-16 10:59:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10651','00-comparativeCountryFk.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:17:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10651','01-comparativeAddConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:17:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10651','02-nightTaskAddNewTask.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:17:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10652','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 14:04:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10653','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:20',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10655','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10656','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10657','00-renameErrorProduction.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10657','01-changeNightTask.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10657','02-addCodeToClaimResponsible.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10657','03-grantSelectGrafana.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10658','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10659','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10661','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:27:50',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10662','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10663','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10665','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-30 08:52:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10666','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10667','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10668','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10671','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-25 14:56:50',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10675','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10676','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10677','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10678','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10679','00-tables.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10680','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-07-18 14:58:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10682','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10683','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10684','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10685','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-05 09:53:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10690','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-07-27 10:52:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10691','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-07-31 13:37:21',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10692','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10693','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10694','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-02 09:50:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10695','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-02 13:40:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10696','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-03 16:54:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10698','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-03 08:53:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10699','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-03 15:24:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10700','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-29 09:42:11',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10701','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10702','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 12:50:46',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10704','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-29 09:42:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10705','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-16 14:16:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10707','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-21 12:31:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10708','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10712','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10714','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-28 13:01:45',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10716','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:27:50',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10717','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:28:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10718','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10719','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-01 12:53:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10720','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:22',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10721','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10724','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10725','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-12 14:15:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10726','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 15:32:20',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10727','00-addPrinterField.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10727','01-createTableScreenModel.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10727','02-createTableScreen.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10727','03-createTableScreenModel.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10727','04-createTableScanner.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10727','05-createTablePackingSiteDeviceLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10727','06-alterTablePrinterModel.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10727','07-AddFieldsToPackingSite.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10730','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-15 11:42:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10733','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-05 09:54:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10736','00-workerBossNull.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-22 00:02:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10738','00-addFieldToTravel.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10738','01-copyDataToTravel.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10738','03-deprecateDuaAwbFk.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10739','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-10 10:19:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10740','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10741','01-refactorCplusTrascendency472.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10741','02-refactorCplusTrascendency477.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10741','03-refactorCplusInvoiceType477.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10741','04-refactorCplusInvoiceType472.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10741','05-fixes.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10744','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-13 09:23:19',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10746','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-10-16 18:22:46',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10747','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10748','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10748','01-SecondScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10749','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-10-22 16:08:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10750','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-23 13:04:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10750','00-ticket_addGrants.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10751','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10752','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-24 14:07:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10753','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-10-24 14:37:21',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10754','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10755','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10756','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-11-03 07:14:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10757','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:30:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10758','00-sectorType.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:17:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10758','01-dipole.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:17:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10758','02-agencyMode.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10758','03-item.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:44',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10761','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:30:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10764','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2024-01-04 12:07:59',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10768','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-11-30 13:11:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10771','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-11-30 13:11:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10773','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-11-30 13:11:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10775','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2024-01-03 10:18:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10778','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-11-30 13:11:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10781','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10782','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2024-01-03 10:18:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10783','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-24 14:49:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10784','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10785','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:33:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10785','02-invoiceIn.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:33:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10785','02-invoiceInTax.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:33:39',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10785','02-item.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:33:39',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10789','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-14 12:33:39',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10792','00-buy.sql','jenkins@db-proxy2.static.verdnatura.es','2024-01-03 10:20:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10798','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2024-01-03 10:21:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10799','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-12-26 12:00:59',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10800','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2024-01-03 10:21:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10801','00-firstScript.sql','jenkins@test-db-proxy1.servers.dc.verdnatura.es','2024-01-11 05:53:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10806','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2024-01-03 11:56:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10808','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10809','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10810','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2024-01-04 14:29:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10811','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10812','00-update.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10812','01-delete.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10812','02-rename.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10812','03-changePosition.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10812','04-unique.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10813','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10815','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2024-01-09 18:11:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10816','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10817','00-invoiceOutConfig_refLen.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-24 21:47:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10818','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-25 09:00:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10819','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10820','00-grants.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10825','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-01 10:24:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10827','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-23 12:32:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10828','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10828','01-RevokeClientes_regalos_lista.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10832','00-newWareHouse.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:01:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10832','00-util_tx_commit.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10832','00-util_tx_rollback.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10832','00-util_tx_start.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10832','01-update_procedure_TravelCloneWithEntries.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10832','02-grant_privileges_util_tx.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:52',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','01-Bancos_poliza.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:52',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','03-Entradas_orden.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','04-Pagares.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','05-Proveedores_gestdoc.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','06-Remesas.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','07-Saldos_Prevision.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','08-Series.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','09-Split_lines.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','10-Split.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','11-Vehiculos_consumo.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','12-account_conciliacion.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','13-account_detail.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','14-account_detail_type.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','15-agencia_descuadre.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','16-airline.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','17-airport.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','18-albaran.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','19-albaran_gestdoc.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','20-albaran_state.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','21-awb_component.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','22-awb_component_template.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','23-awb_component_type.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','24-awb_gestdoc.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','25-awb_recibida.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','26-awb_role.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','27-awb_unit.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','28-balance_nest_tree.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','29-buy_edi_k012.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','30-buy_edi_k03.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','31-buy_edi_k04.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','32-definitivo.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','33-dropTables.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10835','34-permisos.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10838','00-createInventoryConfig.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-07 22:36:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10841','00-entryDms.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10845','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10848','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','00-roleLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','01-userLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','02-entryLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','03-clientLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','04-itemLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','05-shelvingLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','06-workerLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','07-deviceProductionLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','08-zoneLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','09-rateLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','10-ticketLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','11-userLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','12-routeLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','13-claimLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','14-supplierLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','15-invoiceInLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','16-travelLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10849','17-packingSiteDeviceLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10851','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-01-30 13:31:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10853','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10853','00-secondScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10854','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-30 16:20:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10855','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10856','00-cloneAcl.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10857','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10858','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10861','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10862','00-alterAgencyTermConfig.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10862','00-alterGastosResumen.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10862','00-alterInvoiceOutTaxConfig.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10862','00-alterItemGroupToOffer.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10862','01-ventasContablesPk.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10862','02-updateExpenseRegularize.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10862','03-updateExpense.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10862','04-updateExpenseConflict.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10863','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:59',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10865','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:59',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10867','00-createAclInvoiceIn.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:32:59',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10867','01-createInvoiceInCorrection.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10868','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10869','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10871','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10872','00-aclUpdateFiscalData.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10873','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10874','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10876','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10878','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10879','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10882','00-vehicle.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10883','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10884','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10885','00-revokeUpdateClient.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10888','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-16 07:39:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10889','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-23 09:55:56',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10890','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-22 08:33:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10891','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','01-financialProductType.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','02-flight.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:12:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','03-gastos_resumen.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','04-integra2.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','05-integra2_province.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','06-intervalos__delete.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','10-mail_templates__delete.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','12-ticket_location__delete.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','13-turn__delete.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','14-movement_label.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','15-pago_sdc.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','25-warehouse_pickup.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','29-kk.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:03',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10896','30-permissions.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:03',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10898','00-table.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:03',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10903','00-professionalCategoryAddCode.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-23 08:38:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10905','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:01:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10906','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10908','00-createSupplierDms.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10909','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-26 11:07:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10912','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 08:13:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10913','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:01:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10914','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-28 11:52:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10915','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:01:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10918','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:01:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10922','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-02-29 13:44:58',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10923','00-createParkingLog.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:15:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10923','01-aclParkingLog.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:15:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10924','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:15:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10925','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:15:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10926','00-refactorClaimState.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:15:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10928','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:15:52',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10929','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-21 07:16:19',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10940','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-03-06 16:48:18',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10941','00-restoreVn2008Jerarquia.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-03-07 09:36:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10942','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-07 10:24:45',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10943','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-03-07 10:29:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10946','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-03-08 07:56:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10959','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-18 13:32:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','10962','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-25 08:27:35',NULL,NULL);
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
+USE `account`;
+/*!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 */;
+
+INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 09:04:58','2023-06-08 18:47:57',NULL);
+INSERT INTO `role` VALUES (2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 09:04:58','2023-06-02 22:33:28',NULL);
+INSERT INTO `role` VALUES (3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 09:04:58','2017-05-19 09:04:58',NULL);
+INSERT INTO `role` VALUES (5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 09:04:58','2017-05-19 09:04:58',NULL);
+INSERT INTO `role` VALUES (6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 09:04:58','2017-05-19 09:04:58',NULL);
+INSERT INTO `role` VALUES (9,'developer','Desarrolladores del sistema',1,'2017-05-19 09:04:58','2017-05-19 09:04:58',NULL);
+INSERT INTO `role` VALUES (11,'account','Privilegios relacionados con el login',0,'2017-05-19 09:04:58','2017-09-20 19:06:35',NULL);
+INSERT INTO `role` VALUES (13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 09:04:58','2021-06-30 15:29:30',NULL);
+INSERT INTO `role` VALUES (15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 09:04:58','2018-02-12 11:50:10',NULL);
+INSERT INTO `role` VALUES (16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 09:04:58','2017-05-19 09:04:58',NULL);
+INSERT INTO `role` VALUES (17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 09:04:58','2017-05-19 09:04:58',NULL);
+INSERT INTO `role` VALUES (18,'salesPerson','Departamento de ventas',1,'2017-05-19 09:04:58','2017-05-19 09:04:58',NULL);
+INSERT INTO `role` VALUES (19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 09:04:58','2017-08-16 14:38:27',NULL);
+INSERT INTO `role` VALUES (20,'manager','Gerencia',1,'2017-06-01 16:57:02','2022-07-29 09:36:15',NULL);
+INSERT INTO `role` VALUES (21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 14:40:52','2017-08-16 14:40:52',NULL);
+INSERT INTO `role` VALUES (22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 11:08:12','2017-09-07 11:08:12',NULL);
+INSERT INTO `role` VALUES (30,'financialBoss','Director finaciero',1,'2017-09-21 13:05:36','2017-09-21 13:05:36',NULL);
+INSERT INTO `role` VALUES (31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 14:57:26','2017-10-10 14:59:27',NULL);
+INSERT INTO `role` VALUES (32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 14:58:58','2017-10-10 14:59:20',NULL);
+INSERT INTO `role` VALUES (33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 17:43:34','2018-01-29 17:43:34',NULL);
+INSERT INTO `role` VALUES (34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 17:44:39','2018-02-23 08:58:53',NULL);
+INSERT INTO `role` VALUES (35,'buyer','Departamento de compras',1,'2018-02-12 11:35:42','2018-02-12 11:35:42',NULL);
+INSERT INTO `role` VALUES (36,'replenisher','Trabajadores de camara',1,'2018-02-16 15:07:10','2019-04-12 07:38:08',NULL);
+INSERT INTO `role` VALUES (37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 18:34:53','2018-02-22 18:34:53',NULL);
+INSERT INTO `role` VALUES (38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 18:35:09','2018-02-22 18:35:09',NULL);
+INSERT INTO `role` VALUES (39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 11:37:36','2018-02-23 11:38:41',NULL);
+INSERT INTO `role` VALUES (40,'handmade','Departamento de confección',1,'2018-02-23 12:14:53','2018-02-23 12:39:12',NULL);
+INSERT INTO `role` VALUES (41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 12:15:09','2018-02-23 12:39:26',NULL);
+INSERT INTO `role` VALUES (42,'artificial','Departamento de artificial',1,'2018-02-23 12:39:59','2018-02-23 12:39:59',NULL);
+INSERT INTO `role` VALUES (43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 12:40:16','2018-02-23 12:40:16',NULL);
+INSERT INTO `role` VALUES (44,'accessory','Departamento de complementos',1,'2018-02-23 12:41:12','2018-02-23 12:41:12',NULL);
+INSERT INTO `role` VALUES (45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 12:41:23','2018-02-23 12:41:23',NULL);
+INSERT INTO `role` VALUES (47,'cooler','Empleados de cámara',1,'2018-02-23 14:08:18','2018-02-23 14:08:18',NULL);
+INSERT INTO `role` VALUES (48,'coolerBoss','Jefe de cámara',1,'2018-02-23 14:12:01','2023-03-13 09:49:43',NULL);
+INSERT INTO `role` VALUES (49,'production','Empleado de producción',1,'2018-02-26 16:28:23','2021-02-12 10:42:35',NULL);
+INSERT INTO `role` VALUES (50,'productionBoss','Jefe de producción',1,'2018-02-26 16:34:12','2018-02-26 16:34:12',NULL);
+INSERT INTO `role` VALUES (51,'marketing','Departamento de marketing',1,'2018-03-01 08:28:39','2018-03-01 08:28:39',NULL);
+INSERT INTO `role` VALUES (52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 08:28:57','2018-03-01 08:28:57',NULL);
+INSERT INTO `role` VALUES (53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 08:44:35','2019-02-01 14:47:57',NULL);
+INSERT INTO `role` VALUES (54,'itemPicker','Sacador en cámara',1,'2018-03-05 13:08:17','2018-03-05 13:08:17',NULL);
+INSERT INTO `role` VALUES (55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 13:08:31','2018-03-05 13:08:31',NULL);
+INSERT INTO `role` VALUES (56,'delivery','Personal de reparto',1,'2018-05-30 08:07:02','2018-05-30 08:07:02',NULL);
+INSERT INTO `role` VALUES (57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 08:07:19','2018-05-30 08:07:19',NULL);
+INSERT INTO `role` VALUES (58,'packager','Departamento encajadores',1,'2019-01-21 13:43:45','2019-01-21 13:43:45',NULL);
+INSERT INTO `role` VALUES (59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 13:44:10','2019-01-21 13:44:10',NULL);
+INSERT INTO `role` VALUES (60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 14:29:01','2019-01-29 14:29:01',NULL);
+INSERT INTO `role` VALUES (61,'replenisherBoss','Jefe de Complementos/Camara',1,'2019-07-01 08:44:07','2024-02-01 12:07:29',19336);
+INSERT INTO `role` VALUES (62,'noLogin','Role without login access to MySQL',0,'2019-07-01 08:50:19','2019-07-02 15:42:05',NULL);
+INSERT INTO `role` VALUES (64,'balanceSheet','Consulta de Balance',0,'2019-07-16 14:12:08','2019-07-16 14:12:08',NULL);
+INSERT INTO `role` VALUES (65,'officeBoss','Jefe de filial',1,'2019-08-02 08:54:26','2019-08-02 08:54:26',NULL);
+INSERT INTO `role` VALUES (66,'sysadmin','Administrador de sistema',1,'2019-08-08 08:58:56','2019-08-08 08:58:56',NULL);
+INSERT INTO `role` VALUES (67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 09:09:23','2020-01-03 09:09:23',NULL);
+INSERT INTO `role` VALUES (69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 13:36:09','2023-03-13 09:50:07',NULL);
+INSERT INTO `role` VALUES (70,'trainee','Alumno de prácticas',1,'2020-03-04 12:00:25','2020-03-04 12:00:25',NULL);
+INSERT INTO `role` VALUES (71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 12:50:07','2020-10-02 12:50:07',NULL);
+INSERT INTO `role` VALUES (72,'claimManager','Personal de reclamaciones',1,'2020-10-13 12:01:32','2020-10-26 08:29:46',NULL);
+INSERT INTO `role` VALUES (73,'financial','Departamento de finanzas',1,'2020-11-16 10:30:27','2020-11-16 10:30:27',NULL);
+INSERT INTO `role` VALUES (74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 11:24:27','2021-02-03 11:24:27',NULL);
+INSERT INTO `role` VALUES (75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 11:24:27','2021-02-03 11:24:27',NULL);
+INSERT INTO `role` VALUES (76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 14:06:50','2020-12-17 08:49:41',NULL);
+INSERT INTO `role` VALUES (100,'root','Rol con todos los privilegios',0,'2018-04-23 16:33:36','2020-11-12 07:50:07',NULL);
+INSERT INTO `role` VALUES (101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 11:53:17','2021-06-16 11:53:17',NULL);
+INSERT INTO `role` VALUES (102,'preservedBoss','Responsable preservado',1,'2021-09-14 15:45:37','2021-09-14 15:45:37',NULL);
+INSERT INTO `role` VALUES (103,'it','Departamento de informática',1,'2021-11-11 10:48:22','2021-11-11 10:48:22',NULL);
+INSERT INTO `role` VALUES (104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 10:48:49','2021-11-11 10:48:49',NULL);
+INSERT INTO `role` VALUES (105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 13:41:09','2021-11-11 13:41:09',NULL);
+INSERT INTO `role` VALUES (106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 15:51:16','2021-11-23 15:51:16',NULL);
+INSERT INTO `role` VALUES (107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 07:47:10','2022-02-08 07:47:10',NULL);
+INSERT INTO `role` VALUES (108,'system','System user',1,'2022-05-16 10:09:51','2022-05-16 10:09:51',NULL);
+INSERT INTO `role` VALUES (109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 15:45:56','2022-06-14 15:45:56',NULL);
+INSERT INTO `role` VALUES (110,'palletizer','Paletizadores',1,'2022-12-02 13:56:22','2022-12-02 13:56:30',NULL);
+INSERT INTO `role` VALUES (111,'entryEditor','Entry editor',1,'2023-01-13 12:21:55','2023-01-13 12:21:55',NULL);
+INSERT INTO `role` VALUES (112,'maintenance','Personal de mantenimiento',1,'2023-01-19 07:23:35','2023-01-19 07:23:35',NULL);
+INSERT INTO `role` VALUES (114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 07:31:16','2023-05-17 13:07:21',NULL);
+INSERT INTO `role` VALUES (115,'itManagement','TI management',1,'2023-03-29 09:27:55','2023-03-29 09:28:04',NULL);
+INSERT INTO `role` VALUES (119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 13:51:54','2023-06-07 13:51:54',NULL);
+INSERT INTO `role` VALUES (120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 09:07:21','2023-06-19 09:07:21',21709);
+INSERT INTO `role` VALUES (121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 16:48:19','2023-06-23 16:48:19',NULL);
+INSERT INTO `role` VALUES (122,'logisticAssist','Jefe auxiliar de logística',1,'2023-06-26 09:21:15','2024-03-15 13:38:26',19295);
+INSERT INTO `role` VALUES (123,'deliveryAssistant','Jefe auxiliar repartos',1,'2023-10-05 08:47:48','2023-10-05 08:47:48',10578);
+INSERT INTO `role` VALUES (124,'hrBuyer','Recursos Humanos con Buyer',1,'2023-10-23 13:50:43','2023-10-23 13:50:43',NULL);
+INSERT INTO `role` VALUES (125,'claimViewer','Trabajadores que consulta las reclamaciones ',1,'2023-11-16 09:14:46','2023-11-16 09:14:46',10578);
+INSERT INTO `role` VALUES (126,'greenhouseBoss','Jefe de invernadero',1,'2023-11-16 14:32:13','2023-11-16 14:32:13',NULL);
+INSERT INTO `role` VALUES (127,'timeControl','Tablet para fichar',1,'2024-01-09 16:36:56','2024-01-09 16:36:56',NULL);
+INSERT INTO `role` VALUES (129,'buyerAssistant','Comprador que tienes mas permisos para ayudar al buyerBoss en algunas tareas',1,'2024-02-06 06:59:12','2024-02-06 06:59:12',783);
+
+INSERT INTO `roleInherit` VALUES (1,1,2,NULL);
+INSERT INTO `roleInherit` VALUES (2,1,3,NULL);
+INSERT INTO `roleInherit` VALUES (3,1,70,NULL);
+INSERT INTO `roleInherit` VALUES (4,2,11,NULL);
+INSERT INTO `roleInherit` VALUES (5,3,11,NULL);
+INSERT INTO `roleInherit` VALUES (6,5,1,NULL);
+INSERT INTO `roleInherit` VALUES (8,5,33,NULL);
+INSERT INTO `roleInherit` VALUES (10,11,6,NULL);
+INSERT INTO `roleInherit` VALUES (11,13,1,NULL);
+INSERT INTO `roleInherit` VALUES (12,15,35,NULL);
+INSERT INTO `roleInherit` VALUES (16,17,20,NULL);
+INSERT INTO `roleInherit` VALUES (17,17,37,NULL);
+INSERT INTO `roleInherit` VALUES (18,17,39,NULL);
+INSERT INTO `roleInherit` VALUES (19,17,64,NULL);
+INSERT INTO `roleInherit` VALUES (20,18,1,NULL);
+INSERT INTO `roleInherit` VALUES (21,19,21,NULL);
+INSERT INTO `roleInherit` VALUES (22,20,13,NULL);
+INSERT INTO `roleInherit` VALUES (23,20,16,NULL);
+INSERT INTO `roleInherit` VALUES (24,20,65,NULL);
+INSERT INTO `roleInherit` VALUES (25,21,13,NULL);
+INSERT INTO `roleInherit` VALUES (26,21,18,NULL);
+INSERT INTO `roleInherit` VALUES (27,21,53,NULL);
+INSERT INTO `roleInherit` VALUES (28,22,13,NULL);
+INSERT INTO `roleInherit` VALUES (29,22,21,NULL);
+INSERT INTO `roleInherit` VALUES (30,30,5,NULL);
+INSERT INTO `roleInherit` VALUES (31,30,20,NULL);
+INSERT INTO `roleInherit` VALUES (32,30,22,NULL);
+INSERT INTO `roleInherit` VALUES (33,30,53,NULL);
+INSERT INTO `roleInherit` VALUES (34,30,64,NULL);
+INSERT INTO `roleInherit` VALUES (35,31,1,NULL);
+INSERT INTO `roleInherit` VALUES (36,32,1,NULL);
+INSERT INTO `roleInherit` VALUES (37,34,1,NULL);
+INSERT INTO `roleInherit` VALUES (38,34,13,NULL);
+INSERT INTO `roleInherit` VALUES (39,34,33,NULL);
+INSERT INTO `roleInherit` VALUES (40,35,1,NULL);
+INSERT INTO `roleInherit` VALUES (42,36,47,NULL);
+INSERT INTO `roleInherit` VALUES (43,37,1,NULL);
+INSERT INTO `roleInherit` VALUES (44,38,37,NULL);
+INSERT INTO `roleInherit` VALUES (45,38,64,NULL);
+INSERT INTO `roleInherit` VALUES (46,39,5,NULL);
+INSERT INTO `roleInherit` VALUES (47,39,21,NULL);
+INSERT INTO `roleInherit` VALUES (48,39,57,NULL);
+INSERT INTO `roleInherit` VALUES (49,40,1,NULL);
+INSERT INTO `roleInherit` VALUES (50,40,49,NULL);
+INSERT INTO `roleInherit` VALUES (51,41,13,NULL);
+INSERT INTO `roleInherit` VALUES (52,41,35,NULL);
+INSERT INTO `roleInherit` VALUES (53,41,40,NULL);
+INSERT INTO `roleInherit` VALUES (54,42,35,NULL);
+INSERT INTO `roleInherit` VALUES (55,42,49,NULL);
+INSERT INTO `roleInherit` VALUES (56,43,13,NULL);
+INSERT INTO `roleInherit` VALUES (57,43,42,NULL);
+INSERT INTO `roleInherit` VALUES (58,44,1,NULL);
+INSERT INTO `roleInherit` VALUES (59,45,13,NULL);
+INSERT INTO `roleInherit` VALUES (60,45,44,NULL);
+INSERT INTO `roleInherit` VALUES (61,47,1,NULL);
+INSERT INTO `roleInherit` VALUES (62,48,13,NULL);
+INSERT INTO `roleInherit` VALUES (63,48,47,NULL);
+INSERT INTO `roleInherit` VALUES (64,49,36,NULL);
+INSERT INTO `roleInherit` VALUES (65,49,58,NULL);
+INSERT INTO `roleInherit` VALUES (66,50,13,NULL);
+INSERT INTO `roleInherit` VALUES (67,50,21,NULL);
+INSERT INTO `roleInherit` VALUES (70,50,57,NULL);
+INSERT INTO `roleInherit` VALUES (72,51,1,NULL);
+INSERT INTO `roleInherit` VALUES (73,52,13,NULL);
+INSERT INTO `roleInherit` VALUES (74,52,19,NULL);
+INSERT INTO `roleInherit` VALUES (76,52,51,NULL);
+INSERT INTO `roleInherit` VALUES (77,53,1,NULL);
+INSERT INTO `roleInherit` VALUES (78,54,1,NULL);
+INSERT INTO `roleInherit` VALUES (79,55,13,NULL);
+INSERT INTO `roleInherit` VALUES (80,55,54,NULL);
+INSERT INTO `roleInherit` VALUES (81,56,1,NULL);
+INSERT INTO `roleInherit` VALUES (84,58,1,NULL);
+INSERT INTO `roleInherit` VALUES (85,59,13,NULL);
+INSERT INTO `roleInherit` VALUES (87,60,5,NULL);
+INSERT INTO `roleInherit` VALUES (91,61,13,NULL);
+INSERT INTO `roleInherit` VALUES (92,61,36,NULL);
+INSERT INTO `roleInherit` VALUES (94,65,35,NULL);
+INSERT INTO `roleInherit` VALUES (97,67,5,NULL);
+INSERT INTO `roleInherit` VALUES (98,67,37,NULL);
+INSERT INTO `roleInherit` VALUES (99,69,35,NULL);
+INSERT INTO `roleInherit` VALUES (101,70,11,NULL);
+INSERT INTO `roleInherit` VALUES (102,71,1,NULL);
+INSERT INTO `roleInherit` VALUES (103,71,58,NULL);
+INSERT INTO `roleInherit` VALUES (105,72,18,NULL);
+INSERT INTO `roleInherit` VALUES (106,73,5,NULL);
+INSERT INTO `roleInherit` VALUES (107,73,64,NULL);
+INSERT INTO `roleInherit` VALUES (108,73,19,NULL);
+INSERT INTO `roleInherit` VALUES (109,59,50,NULL);
+INSERT INTO `roleInherit` VALUES (115,39,76,NULL);
+INSERT INTO `roleInherit` VALUES (117,65,76,NULL);
+INSERT INTO `roleInherit` VALUES (118,30,76,NULL);
+INSERT INTO `roleInherit` VALUES (124,5,76,NULL);
+INSERT INTO `roleInherit` VALUES (125,37,76,NULL);
+INSERT INTO `roleInherit` VALUES (126,38,76,NULL);
+INSERT INTO `roleInherit` VALUES (128,42,76,NULL);
+INSERT INTO `roleInherit` VALUES (129,35,76,NULL);
+INSERT INTO `roleInherit` VALUES (130,60,76,NULL);
+INSERT INTO `roleInherit` VALUES (131,21,76,NULL);
+INSERT INTO `roleInherit` VALUES (132,18,76,NULL);
+INSERT INTO `roleInherit` VALUES (133,50,76,NULL);
+INSERT INTO `roleInherit` VALUES (134,20,76,NULL);
+INSERT INTO `roleInherit` VALUES (135,41,76,NULL);
+INSERT INTO `roleInherit` VALUES (136,17,76,NULL);
+INSERT INTO `roleInherit` VALUES (137,52,76,NULL);
+INSERT INTO `roleInherit` VALUES (139,37,74,NULL);
+INSERT INTO `roleInherit` VALUES (140,51,74,NULL);
+INSERT INTO `roleInherit` VALUES (141,51,75,NULL);
+INSERT INTO `roleInherit` VALUES (142,35,75,NULL);
+INSERT INTO `roleInherit` VALUES (143,15,49,NULL);
+INSERT INTO `roleInherit` VALUES (145,17,67,NULL);
+INSERT INTO `roleInherit` VALUES (146,38,13,NULL);
+INSERT INTO `roleInherit` VALUES (148,101,13,NULL);
+INSERT INTO `roleInherit` VALUES (150,15,56,NULL);
+INSERT INTO `roleInherit` VALUES (152,69,47,NULL);
+INSERT INTO `roleInherit` VALUES (153,48,35,NULL);
+INSERT INTO `roleInherit` VALUES (154,102,1,NULL);
+INSERT INTO `roleInherit` VALUES (167,9,103,NULL);
+INSERT INTO `roleInherit` VALUES (168,66,9,NULL);
+INSERT INTO `roleInherit` VALUES (169,104,100,NULL);
+INSERT INTO `roleInherit` VALUES (172,103,76,NULL);
+INSERT INTO `roleInherit` VALUES (173,103,1,NULL);
+INSERT INTO `roleInherit` VALUES (174,103,44,NULL);
+INSERT INTO `roleInherit` VALUES (175,103,45,NULL);
+INSERT INTO `roleInherit` VALUES (176,103,11,NULL);
+INSERT INTO `roleInherit` VALUES (177,103,39,NULL);
+INSERT INTO `roleInherit` VALUES (178,103,17,NULL);
+INSERT INTO `roleInherit` VALUES (179,103,5,NULL);
+INSERT INTO `roleInherit` VALUES (180,103,67,NULL);
+INSERT INTO `roleInherit` VALUES (181,103,3,NULL);
+INSERT INTO `roleInherit` VALUES (182,103,34,NULL);
+INSERT INTO `roleInherit` VALUES (183,103,42,NULL);
+INSERT INTO `roleInherit` VALUES (184,103,43,NULL);
+INSERT INTO `roleInherit` VALUES (185,103,64,NULL);
+INSERT INTO `roleInherit` VALUES (186,103,35,NULL);
+INSERT INTO `roleInherit` VALUES (187,103,101,NULL);
+INSERT INTO `roleInherit` VALUES (188,103,75,NULL);
+INSERT INTO `roleInherit` VALUES (189,103,71,NULL);
+INSERT INTO `roleInherit` VALUES (190,103,72,NULL);
+INSERT INTO `roleInherit` VALUES (191,103,47,NULL);
+INSERT INTO `roleInherit` VALUES (192,103,69,NULL);
+INSERT INTO `roleInherit` VALUES (193,103,48,NULL);
+INSERT INTO `roleInherit` VALUES (194,103,2,NULL);
+INSERT INTO `roleInherit` VALUES (195,103,56,NULL);
+INSERT INTO `roleInherit` VALUES (196,103,57,NULL);
+INSERT INTO `roleInherit` VALUES (197,103,32,NULL);
+INSERT INTO `roleInherit` VALUES (198,103,73,NULL);
+INSERT INTO `roleInherit` VALUES (199,103,30,NULL);
+INSERT INTO `roleInherit` VALUES (200,103,31,NULL);
+INSERT INTO `roleInherit` VALUES (201,103,6,NULL);
+INSERT INTO `roleInherit` VALUES (202,103,40,NULL);
+INSERT INTO `roleInherit` VALUES (203,103,41,NULL);
+INSERT INTO `roleInherit` VALUES (204,103,37,NULL);
+INSERT INTO `roleInherit` VALUES (205,103,38,NULL);
+INSERT INTO `roleInherit` VALUES (206,103,53,NULL);
+INSERT INTO `roleInherit` VALUES (207,103,33,NULL);
+INSERT INTO `roleInherit` VALUES (210,103,54,NULL);
+INSERT INTO `roleInherit` VALUES (211,103,55,NULL);
+INSERT INTO `roleInherit` VALUES (212,103,15,NULL);
+INSERT INTO `roleInherit` VALUES (213,103,16,NULL);
+INSERT INTO `roleInherit` VALUES (215,103,51,NULL);
+INSERT INTO `roleInherit` VALUES (216,103,52,NULL);
+INSERT INTO `roleInherit` VALUES (218,103,65,NULL);
+INSERT INTO `roleInherit` VALUES (219,103,58,NULL);
+INSERT INTO `roleInherit` VALUES (220,103,59,NULL);
+INSERT INTO `roleInherit` VALUES (221,103,102,NULL);
+INSERT INTO `roleInherit` VALUES (222,103,49,NULL);
+INSERT INTO `roleInherit` VALUES (223,103,60,NULL);
+INSERT INTO `roleInherit` VALUES (224,103,50,NULL);
+INSERT INTO `roleInherit` VALUES (225,103,36,NULL);
+INSERT INTO `roleInherit` VALUES (226,103,61,NULL);
+INSERT INTO `roleInherit` VALUES (228,103,21,NULL);
+INSERT INTO `roleInherit` VALUES (229,103,19,NULL);
+INSERT INTO `roleInherit` VALUES (230,103,18,NULL);
+INSERT INTO `roleInherit` VALUES (231,103,13,NULL);
+INSERT INTO `roleInherit` VALUES (232,103,22,NULL);
+INSERT INTO `roleInherit` VALUES (233,103,70,NULL);
+INSERT INTO `roleInherit` VALUES (234,103,74,NULL);
+INSERT INTO `roleInherit` VALUES (237,66,103,NULL);
+INSERT INTO `roleInherit` VALUES (238,103,20,NULL);
+INSERT INTO `roleInherit` VALUES (239,106,11,NULL);
+INSERT INTO `roleInherit` VALUES (240,107,60,NULL);
+INSERT INTO `roleInherit` VALUES (241,21,72,NULL);
+INSERT INTO `roleInherit` VALUES (242,20,9,NULL);
+INSERT INTO `roleInherit` VALUES (246,102,35,NULL);
+INSERT INTO `roleInherit` VALUES (247,108,1,NULL);
+INSERT INTO `roleInherit` VALUES (248,102,13,NULL);
+INSERT INTO `roleInherit` VALUES (249,109,18,NULL);
+INSERT INTO `roleInherit` VALUES (250,109,13,NULL);
+INSERT INTO `roleInherit` VALUES (251,51,21,NULL);
+INSERT INTO `roleInherit` VALUES (253,48,49,NULL);
+INSERT INTO `roleInherit` VALUES (254,110,1,NULL);
+INSERT INTO `roleInherit` VALUES (255,110,76,NULL);
+INSERT INTO `roleInherit` VALUES (256,48,69,NULL);
+INSERT INTO `roleInherit` VALUES (257,47,111,NULL);
+INSERT INTO `roleInherit` VALUES (258,43,111,NULL);
+INSERT INTO `roleInherit` VALUES (259,72,111,NULL);
+INSERT INTO `roleInherit` VALUES (260,35,111,NULL);
+INSERT INTO `roleInherit` VALUES (261,5,111,NULL);
+INSERT INTO `roleInherit` VALUES (262,112,1,NULL);
+INSERT INTO `roleInherit` VALUES (263,114,112,NULL);
+INSERT INTO `roleInherit` VALUES (264,51,35,NULL);
+INSERT INTO `roleInherit` VALUES (265,72,49,NULL);
+INSERT INTO `roleInherit` VALUES (266,101,18,NULL);
+INSERT INTO `roleInherit` VALUES (268,65,57,NULL);
+INSERT INTO `roleInherit` VALUES (269,65,59,NULL);
+INSERT INTO `roleInherit` VALUES (270,65,49,NULL);
+INSERT INTO `roleInherit` VALUES (271,65,18,NULL);
+INSERT INTO `roleInherit` VALUES (272,65,13,NULL);
+INSERT INTO `roleInherit` VALUES (273,60,35,NULL);
+INSERT INTO `roleInherit` VALUES (275,50,59,NULL);
+INSERT INTO `roleInherit` VALUES (276,60,49,NULL);
+INSERT INTO `roleInherit` VALUES (280,5,53,NULL);
+INSERT INTO `roleInherit` VALUES (281,5,18,NULL);
+INSERT INTO `roleInherit` VALUES (282,50,60,NULL);
+INSERT INTO `roleInherit` VALUES (283,5,21,NULL);
+INSERT INTO `roleInherit` VALUES (285,58,76,NULL);
+INSERT INTO `roleInherit` VALUES (288,115,66,NULL);
+INSERT INTO `roleInherit` VALUES (290,104,115,NULL);
+INSERT INTO `roleInherit` VALUES (291,115,103,NULL);
+INSERT INTO `roleInherit` VALUES (297,21,33,NULL);
+INSERT INTO `roleInherit` VALUES (298,49,54,NULL);
+INSERT INTO `roleInherit` VALUES (299,112,49,NULL);
+INSERT INTO `roleInherit` VALUES (300,114,13,NULL);
+INSERT INTO `roleInherit` VALUES (302,5,35,NULL);
+INSERT INTO `roleInherit` VALUES (303,69,49,NULL);
+INSERT INTO `roleInherit` VALUES (306,119,110,NULL);
+INSERT INTO `roleInherit` VALUES (307,1,76,NULL);
+INSERT INTO `roleInherit` VALUES (309,120,9,NULL);
+INSERT INTO `roleInherit` VALUES (310,120,66,NULL);
+INSERT INTO `roleInherit` VALUES (311,120,13,25508);
+INSERT INTO `roleInherit` VALUES (312,115,120,NULL);
+INSERT INTO `roleInherit` VALUES (314,43,18,NULL);
+INSERT INTO `roleInherit` VALUES (315,121,35,NULL);
+INSERT INTO `roleInherit` VALUES (316,121,21,NULL);
+INSERT INTO `roleInherit` VALUES (318,16,122,NULL);
+INSERT INTO `roleInherit` VALUES (319,37,49,NULL);
+INSERT INTO `roleInherit` VALUES (320,37,18,NULL);
+INSERT INTO `roleInherit` VALUES (328,57,123,10578);
+INSERT INTO `roleInherit` VALUES (329,123,33,NULL);
+INSERT INTO `roleInherit` VALUES (330,123,56,NULL);
+INSERT INTO `roleInherit` VALUES (332,103,112,NULL);
+INSERT INTO `roleInherit` VALUES (333,57,13,NULL);
+INSERT INTO `roleInherit` VALUES (334,60,123,NULL);
+INSERT INTO `roleInherit` VALUES (335,124,37,NULL);
+INSERT INTO `roleInherit` VALUES (336,124,35,NULL);
+INSERT INTO `roleInherit` VALUES (337,103,124,NULL);
+INSERT INTO `roleInherit` VALUES (338,35,125,10578);
+INSERT INTO `roleInherit` VALUES (339,57,125,10578);
+INSERT INTO `roleInherit` VALUES (340,41,125,10578);
+INSERT INTO `roleInherit` VALUES (341,18,125,10578);
+INSERT INTO `roleInherit` VALUES (346,126,15,NULL);
+INSERT INTO `roleInherit` VALUES (347,102,49,NULL);
+INSERT INTO `roleInherit` VALUES (350,49,75,NULL);
+INSERT INTO `roleInherit` VALUES (351,72,35,NULL);
+INSERT INTO `roleInherit` VALUES (353,110,49,NULL);
+INSERT INTO `roleInherit` VALUES (354,103,119,NULL);
+INSERT INTO `roleInherit` VALUES (355,127,11,NULL);
+INSERT INTO `roleInherit` VALUES (356,123,125,NULL);
+INSERT INTO `roleInherit` VALUES (357,36,35,NULL);
+INSERT INTO `roleInherit` VALUES (358,36,49,NULL);
+INSERT INTO `roleInherit` VALUES (359,129,35,NULL);
+INSERT INTO `roleInherit` VALUES (360,101,129,NULL);
+INSERT INTO `roleInherit` VALUES (361,50,112,NULL);
+INSERT INTO `roleInherit` VALUES (362,122,15,NULL);
+
+INSERT INTO `userPassword` VALUES (1,7,1,0,2,1);
+
+INSERT INTO `accountConfig` VALUES (1,'/mnt/homes','/bin/bash',10000,5,60,5,30);
+
+INSERT INTO `mailConfig` VALUES (1,'verdnatura.es');
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
+USE `salix`;
+/*!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 */;
+
+INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (5,'AgencyService','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (9,'ClientObservation','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (11,'ContactChannel','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (13,'Employee','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (14,'PayMethod','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (16,'FakeProduction','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (17,'Warehouse','* ','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (20,'TicketState','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (24,'Delivery','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (25,'Zone','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (26,'ClientCredit','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (30,'GreugeType','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (31,'Mandate','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (32,'MandateType','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (33,'Company','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (34,'Greuge','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (35,'AddressObservation','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (36,'ObservationType','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (37,'Greuge','*','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (38,'AgencyMode','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (41,'ItemBotanical','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher');
+INSERT INTO `ACL` VALUES (44,'ItemPlacement','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (45,'ItemBarcode','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher');
+INSERT INTO `ACL` VALUES (51,'ItemTag','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (53,'Item','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (54,'Item','*','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (55,'Recovery','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (56,'Recovery','*','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (58,'CreditClassification','*','*','ALLOW','ROLE','insurance');
+INSERT INTO `ACL` VALUES (60,'CreditInsurance','*','*','ALLOW','ROLE','insurance');
+INSERT INTO `ACL` VALUES (61,'InvoiceOut','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (63,'TicketObservation','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (65,'Sale','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (66,'TicketTracking','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (68,'TicketPackaging','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (69,'Packaging','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (70,'Packaging','*','WRITE','ALLOW','ROLE','logistic');
+INSERT INTO `ACL` VALUES (72,'SaleComponent','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (73,'Expedition','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (75,'Expedition','*','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (77,'WorkerMana','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (78,'TicketTracking','*','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (79,'Ticket','state','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (80,'Sale','deleteSales','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (81,'Sale','moveToTicket','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (82,'Sale','updateQuantity','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (83,'Sale','updatePrice','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (84,'Sale','updateDiscount','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (85,'SaleTracking','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (86,'Order','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (87,'OrderRow','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (88,'ClientContact','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (90,'Sale','reserve','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (91,'TicketWeekly','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (94,'Agency','landsThatDay','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (96,'ClaimEnd','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (98,'ClaimBeginning','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (102,'Claim','createFromSales','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss');
+INSERT INTO `ACL` VALUES (105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss');
+INSERT INTO `ACL` VALUES (106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss');
+INSERT INTO `ACL` VALUES (108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss');
+INSERT INTO `ACL` VALUES (109,'UserConfig','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (110,'Accounting','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (111,'ClientLog','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (112,'Defaulter','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (113,'ClientRisk','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (114,'Receipt','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (115,'Receipt','*','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (116,'BankEntity','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (117,'ClientSample','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (119,'Travel','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (120,'Travel','*','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (121,'Item','regularize','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (122,'TicketRequest','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (127,'TicketLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (129,'TicketService','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (130,'Expedition','*','WRITE','ALLOW','ROLE','packager');
+INSERT INTO `ACL` VALUES (131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (132,'CreditClassification','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss');
+INSERT INTO `ACL` VALUES (135,'ZoneGeo','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (138,'LabourHoliday','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (141,'Zone','*','*','ALLOW','ROLE','logisticBoss');
+INSERT INTO `ACL` VALUES (142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (144,'Stowaway','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (147,'UserConfigView','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (148,'UserConfigView','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (149,'Sip','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (150,'Sip','*','WRITE','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (151,'Department','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (152,'Department','*','WRITE','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (154,'Route','*','WRITE','ALLOW','ROLE','delivery');
+INSERT INTO `ACL` VALUES (155,'Calendar','*','READ','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (156,'WorkerLabour','*','READ','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (157,'Calendar','absences','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory');
+INSERT INTO `ACL` VALUES (160,'TicketServiceType','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (161,'TicketConfig','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (165,'TicketDms','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (172,'Sms','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (173,'Sms','send','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (176,'Device','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (177,'Device','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (179,'ItemLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (180,'RouteLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (183,'Dms','downloadFile','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (186,'ClientDms','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (191,'Agency','getLanded','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (192,'Agency','getShipped','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (197,'Dms','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (199,'ClaimDms','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (203,'UserPhone','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (205,'WorkerDms','*','READ','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (206,'Chat','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (207,'Chat','sendMessage','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (211,'TravelLog','*','READ','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (212,'Thermograph','*','*','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (214,'Entry','*','*','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (216,'TravelThermograph','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (218,'Intrastat','*','*','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account');
+INSERT INTO `ACL` VALUES (226,'ClientObservation','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (227,'Address','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (228,'AddressObservation','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (230,'ClientCredit','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (231,'ClientContact','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (232,'ClientSample','*','READ','ALLOW','ROLE','trainee');
+INSERT INTO `ACL` VALUES (233,'EntryLog','*','READ','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (234,'WorkerLog','find','READ','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (235,'CustomsAgent','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (236,'Buy','*','*','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (237,'WorkerDms','filter','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (238,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (239,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (248,'RoleMapping','*','READ','ALLOW','ROLE','account');
+INSERT INTO `ACL` VALUES (249,'UserPassword','*','READ','ALLOW','ROLE','account');
+INSERT INTO `ACL` VALUES (250,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (251,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (252,'Supplier','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (253,'Supplier','*','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (254,'SupplierLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (256,'Image','*','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (257,'FixedPrice','*','*','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (258,'PayDem','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (261,'SupplierAccount','*','*','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (262,'Entry','*','*','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (263,'InvoiceIn','*','*','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (264,'StarredModule','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss');
+INSERT INTO `ACL` VALUES (266,'ZoneLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss');
+INSERT INTO `ACL` VALUES (268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss');
+INSERT INTO `ACL` VALUES (269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (270,'SupplierAddress','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (271,'SalesMonitor','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant');
+INSERT INTO `ACL` VALUES (279,'MailAlias','*','*','ALLOW','ROLE','marketing');
+INSERT INTO `ACL` VALUES (283,'EntryObservation','*','*','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin');
+INSERT INTO `ACL` VALUES (285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin');
+INSERT INTO `ACL` VALUES (286,'ACL','*','*','ALLOW','ROLE','developer');
+INSERT INTO `ACL` VALUES (287,'AccessToken','*','*','ALLOW','ROLE','developer');
+INSERT INTO `ACL` VALUES (293,'RoleInherit','*','*','ALLOW','ROLE','it');
+INSERT INTO `ACL` VALUES (294,'RoleRole','*','*','ALLOW','ROLE','it');
+INSERT INTO `ACL` VALUES (295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin');
+INSERT INTO `ACL` VALUES (296,'Collection','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (297,'Sale','clone','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (302,'AgencyTerm','*','*','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (304,'Edi','updateData','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (305,'EducationLevel','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (310,'ExpeditionState','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (311,'Expense','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (312,'Expense','*','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (314,'SupplierActivity','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (318,'MdbVersion','*','*','ALLOW','ROLE','developer');
+INSERT INTO `ACL` VALUES (319,'ItemType','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (320,'ItemType','*','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (327,'Sale','clone','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (328,'Sale','clone','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (334,'ShelvingLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (337,'Parking','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (338,'Shelving','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (339,'OsTicket','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (340,'OsTicketConfig','*','*','ALLOW','ROLE','it');
+INSERT INTO `ACL` VALUES (341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system');
+INSERT INTO `ACL` VALUES (368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system');
+INSERT INTO `ACL` VALUES (371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system');
+INSERT INTO `ACL` VALUES (379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system');
+INSERT INTO `ACL` VALUES (380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (382,'Item','labelPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (383,'Sector','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (384,'Sector','*','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer');
+INSERT INTO `ACL` VALUES (388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (391,'Notification','*','WRITE','ALLOW','ROLE','system');
+INSERT INTO `ACL` VALUES (392,'Boxing','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (393,'Url','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (394,'Url','*','WRITE','ALLOW','ROLE','it');
+INSERT INTO `ACL` VALUES (395,'ItemShelving','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (396,'ItemShelving','*','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (398,'NotificationQueue','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (401,'Sale','editTracked','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (406,'Ticket','merge','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic');
+INSERT INTO `ACL` VALUES (408,'ZipConfig','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (409,'Item','*','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone');
+INSERT INTO `ACL` VALUES (416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (418,'EntryLog','*','READ','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone');
+INSERT INTO `ACL` VALUES (421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (422,'Docuware','checkFile','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (423,'Docuware','download','READ','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone');
+INSERT INTO `ACL` VALUES (427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated');
+INSERT INTO `ACL` VALUES (428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated');
+INSERT INTO `ACL` VALUES (429,'ItemConfig','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (433,'Worker','createAbsence','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (436,'Worker','new','WRITE','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (439,'NotificationSubscription','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (440,'NotificationAcl','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (441,'MdbApp','*','READ','ALLOW','ROLE','$everyone');
+INSERT INTO `ACL` VALUES (442,'MdbApp','*','*','ALLOW','ROLE','developer');
+INSERT INTO `ACL` VALUES (443,'ItemConfig','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (444,'DeviceProduction','*','*','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (446,'DeviceProductionState','*','*','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (453,'Worker','allocatePDA','*','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (456,'Zone','*','*','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (458,'Operator','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (459,'Operator','*','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (464,'WorkerObservation','*','*','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (465,'ClientInforma','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial');
+INSERT INTO `ACL` VALUES (467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (468,'Client','setRating','WRITE','ALLOW','ROLE','financial');
+INSERT INTO `ACL` VALUES (470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (472,'Client','canCreateTicket','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (473,'Client','consumption','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (474,'Client','createAddress','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (475,'Client','createWithUser','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (476,'Client','extendedListFilter','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (478,'Client','getCard','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (479,'Client','getDebt','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (480,'Client','getMana','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (481,'Client','transactions','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (483,'Client','isValidClient','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (485,'Client','sendSms','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (486,'Client','setPassword','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (487,'Client','summary','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (488,'Client','updateAddress','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (489,'Client','updateFiscalData','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (491,'Client','uploadFile','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (514,'Client','filter','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (516,'Client','upsert','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (518,'Client','replaceById','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (519,'Client','updateAttributes','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (520,'Client','updateAttributes','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (521,'Client','deleteById','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (523,'Client','updateAll','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (527,'VnUser','acl','READ','ALLOW','ROLE','account');
+INSERT INTO `ACL` VALUES (528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account');
+INSERT INTO `ACL` VALUES (530,'Account','exists','READ','ALLOW','ROLE','account');
+INSERT INTO `ACL` VALUES (531,'Account','exists','READ','ALLOW','ROLE','account');
+INSERT INTO `ACL` VALUES (532,'UserLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (533,'RoleLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (534,'WagonType','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (540,'Wagon','*','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi');
+INSERT INTO `ACL` VALUES (544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (545,'Agency','find','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist');
+INSERT INTO `ACL` VALUES (547,'WorkerLog','models','READ','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (556,'State','editableStates','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (558,'State','seeEditableStates','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (560,'State','isAllEditable','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (561,'State','isAllEditable','READ','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss');
+INSERT INTO `ACL` VALUES (564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss');
+INSERT INTO `ACL` VALUES (569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss');
+INSERT INTO `ACL` VALUES (570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial');
+INSERT INTO `ACL` VALUES (572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss');
+INSERT INTO `ACL` VALUES (573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (585,'Claim','logs','READ','ALLOW','ROLE','claimManager');
+INSERT INTO `ACL` VALUES (586,'Ticket','find','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (587,'Ticket','findById','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (588,'Ticket','findOne','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (589,'Ticket','getVolume','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (591,'Ticket','summary','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (594,'Ticket','new','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (595,'Ticket','isEditable','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (597,'Ticket','restore','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (598,'Ticket','getSales','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (600,'Ticket','filter','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (606,'Ticket','isLocked','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (607,'Ticket','freightCost','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery');
+INSERT INTO `ACL` VALUES (610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (611,'State','find','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (612,'State','findById','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (613,'State','findOne','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (614,'Worker','find','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (615,'Worker','findById','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (616,'Worker','findOne','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (617,'Worker','filter','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (619,'Worker','active','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (622,'Worker','contracts','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (623,'Worker','holidays','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (624,'Worker','activeContract','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss');
+INSERT INTO `ACL` VALUES (630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss');
+INSERT INTO `ACL` VALUES (635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss');
+INSERT INTO `ACL` VALUES (639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant');
+INSERT INTO `ACL` VALUES (654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant');
+INSERT INTO `ACL` VALUES (655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system');
+INSERT INTO `ACL` VALUES (659,'Account','*','*','ALLOW','ROLE','developerBoss');
+INSERT INTO `ACL` VALUES (664,'MailForward','*','*','ALLOW','ROLE','itManagement');
+INSERT INTO `ACL` VALUES (667,'VnUser','*','*','ALLOW','ROLE','itManagement');
+INSERT INTO `ACL` VALUES (668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (669,'VnUser','preview','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (670,'VnUser','create','*','ALLOW','ROLE','itManagement');
+INSERT INTO `ACL` VALUES (672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing');
+INSERT INTO `ACL` VALUES (676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','developerBoss');
+INSERT INTO `ACL` VALUES (684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement');
+INSERT INTO `ACL` VALUES (685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement');
+INSERT INTO `ACL` VALUES (686,'MailForward','*','*','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (687,'ClientSms','find','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (688,'ClientSms','create','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss');
+INSERT INTO `ACL` VALUES (691,'Roadmap','*','*','ALLOW','ROLE','productionBoss');
+INSERT INTO `ACL` VALUES (692,'ExpeditionTruck','*','*','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss');
+INSERT INTO `ACL` VALUES (695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (703,'Worker','search','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (704,'ExpeditionState','addExpeditionState','WRITE','ALLOW','ROLE','delivery');
+INSERT INTO `ACL` VALUES (705,'SaleGroupDetail','deleteById','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (706,'Ticket','setDeleted','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (707,'DeviceLog','create','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (708,'Collection','getTickets','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (709,'Client','findOne','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (710,'Client','findById','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (711,'Client','find','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (712,'Client','exists','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (713,'Client','__get__addresses','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (714,'ExpeditionMistakeType','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (715,'WorkerMistakeType','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (716,'ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (717,'WorkerMistake','*','WRITE','ALLOW','ROLE','coolerAssist');
+INSERT INTO `ACL` VALUES (718,'MistakesTypes','*','WRITE','ALLOW','ROLE','coolerAssist');
+INSERT INTO `ACL` VALUES (719,'MistakeType','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (720,'MachineWorker','*','READ','ALLOW','ROLE','coolerAssist');
+INSERT INTO `ACL` VALUES (721,'Printer','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (722,'SaleMistake','*','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (723,'Item','setVisibleDiscard','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (724,'Address','getAddress','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (725,'Account','findOne','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (726,'Account','findById','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (727,'Account','find','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (728,'Account','exists','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (729,'Sale','clone','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (730,'Ticket','setDeleted','WRITE','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (732,'Sale','isInPreparing','*','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (733,'Train','*','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (734,'WorkerDepartment','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (735,'VnUser','higherPrivileges','*','ALLOW','ROLE','itManagement');
+INSERT INTO `ACL` VALUES (736,'VnUser','mediumPrivileges','*','ALLOW','ROLE','hr');
+INSERT INTO `ACL` VALUES (737,'VnUser','updateUser','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (738,'TicketCollection','*','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (739,'Worker','setPassword','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (740,'Url','getByUser','READ','ALLOW','ROLE','$everyone');
+INSERT INTO `ACL` VALUES (741,'Claim','__get__lines','READ','ALLOW','ROLE','claimViewer');
+INSERT INTO `ACL` VALUES (742,'AddressShortage','*','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (743,'Claim','filter','READ','ALLOW','ROLE','claimViewer');
+INSERT INTO `ACL` VALUES (744,'Claim','find','READ','ALLOW','ROLE','claimViewer');
+INSERT INTO `ACL` VALUES (745,'Claim','findById','READ','ALLOW','ROLE','claimViewer');
+INSERT INTO `ACL` VALUES (746,'Claim','getSummary','READ','ALLOW','ROLE','claimViewer');
+INSERT INTO `ACL` VALUES (747,'CplusRectificationType','*','READ','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (748,'SiiTypeInvoiceOut','*','READ','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (749,'InvoiceCorrectionType','*','READ','ALLOW','ROLE','salesPerson');
+INSERT INTO `ACL` VALUES (750,'InvoiceOut','transferInvoice','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (751,'Application','executeProc','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (752,'Application','executeFunc','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (753,'NotificationSubscription','getList','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (754,'Route','find','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (755,'Route','findById','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (756,'Route','findOne','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (757,'Route','getRoutesByWorker','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (758,'Route','canViewAllRoute','READ','ALLOW','ROLE','deliveryAssistant');
+INSERT INTO `ACL` VALUES (759,'Route','cmr','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (760,'Route','downloadCmrsZip','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (761,'Route','downloadZip','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (762,'Route','filter','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (763,'Route','getByWorker','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (764,'Route','getDeliveryPoint','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (765,'Route','getExternalCmrs','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (766,'Route','getSuggestedTickets','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (767,'Route','getTickets','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (768,'Route','guessPriority','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (769,'Route','insertTicket','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (770,'Route','getDeliveryPoint','READ','ALLOW','ROLE','deliveryBoss');
+INSERT INTO `ACL` VALUES (771,'Route','summary','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (772,'Route','getExpeditionSummary','READ','ALLOW','ROLE','delivery');
+INSERT INTO `ACL` VALUES (773,'WorkerTimeControl','login','READ','ALLOW','ROLE','timeControl');
+INSERT INTO `ACL` VALUES (774,'WorkerTimeControl','getClockIn','READ','ALLOW','ROLE','timeControl');
+INSERT INTO `ACL` VALUES (775,'WorkerTimeControl','clockIn','WRITE','ALLOW','ROLE','timeControl');
+INSERT INTO `ACL` VALUES (776,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (777,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (778,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (779,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (780,'WorkerTimeControl','updateWorkerTimeControlMail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (781,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (782,'WorkerTimeControl','getMailStates','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (783,'WorkerTimeControl','resendWeeklyHourEmail','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (784,'VnRole','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (785,'VnRole','*','WRITE','ALLOW','ROLE','it');
+INSERT INTO `ACL` VALUES (786,'State','isAllEditable','READ','ALLOW','ROLE','delivery');
+INSERT INTO `ACL` VALUES (787,'Ticket','makePdfList','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (788,'Ticket','invoiceTicketsAndPdf','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (789,'InvoiceIn','*','*','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (790,'InvoiceIn','getSerial','READ','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (791,'InvoiceIn','corrective','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (792,'InvoiceInCorrection','*','*','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (793,'Supplier','updateAllFiscalData','WRITE','ALLOW','ROLE','administrative');
+INSERT INTO `ACL` VALUES (794,'Supplier','updateFiscalData','WRITE','ALLOW','ROLE','buyer');
+INSERT INTO `ACL` VALUES (795,'Ticket','myLastModified','*','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (796,'MrwConfig','cancelShipment','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (797,'MrwConfig','createShipment','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (798,'MailAliasAccount','*','*','ALLOW','ROLE','itManagement');
+INSERT INTO `ACL` VALUES (799,'Ticket','saveCmr','*','ALLOW','ROLE','developer');
+INSERT INTO `ACL` VALUES (800,'EntryDms','*','*','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (801,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (802,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (803,'ExpeditionPallet','*','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (804,'DeviceProduction','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (805,'Collection','assign','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (806,'ExpeditionPallet','getPallet','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (807,'MachineWorker','updateInTime','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (808,'MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (809,'SaleTracking','delete','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (810,'SaleTracking','updateTracking','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (811,'SaleTracking','setPicked','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (812,'ExpeditionPallet','*','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (813,'Sale','getFromSectorCollection','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (814,'ItemBarcode','delete','WRITE','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (815,'WorkerActivityType','*','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (816,'WorkerActivity','*','*','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (817,'ParkingLog','*','READ','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (818,'ExpeditionPallet','*','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (819,'Ticket','addSaleByCode','WRITE','ALLOW','ROLE','production');
+
+INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee');
+INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee');
+INSERT INTO `fieldAcl` VALUES (3,'Client','email','update','employee');
+INSERT INTO `fieldAcl` VALUES (4,'Client','phone','update','employee');
+INSERT INTO `fieldAcl` VALUES (5,'Client','mobile','update','employee');
+INSERT INTO `fieldAcl` VALUES (6,'Client','contactChannelFk','update','employee');
+INSERT INTO `fieldAcl` VALUES (7,'Client','socialName','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (8,'Client','fi','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (9,'Client','street','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (10,'Client','postcode','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (11,'Client','city','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (12,'Client','countryFk','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (13,'Client','provinceFk','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (14,'Client','isActive','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (15,'Client','salesPersonFk','update','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (16,'Client','hasToInvoice','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (17,'Client','isToBeMailed','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (18,'Client','isEqualizated','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (19,'Client','isFreezed','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (20,'Client','isVies','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (21,'Client','hasToInvoiceByAddress','update','salesPerson');
+INSERT INTO `fieldAcl` VALUES (22,'Client','isTaxDataChecked','update','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (23,'Client','payMethodFk','update','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (24,'Client','dueDay','update','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (25,'Client','iban','update','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (26,'Client','bankEntityFk','update','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (27,'Client','hasLcr','update','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (28,'Client','hasCoreVnl','update','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (29,'Client','hasSepaVnl','update','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (30,'Client','credit','update','teamBoss');
+INSERT INTO `fieldAcl` VALUES (31,'BankEntity','*','insert','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (32,'Address','isDefaultAddress','*','employee');
+INSERT INTO `fieldAcl` VALUES (33,'Address','nickname','*','employee');
+INSERT INTO `fieldAcl` VALUES (34,'Address','postalCode','*','employee');
+INSERT INTO `fieldAcl` VALUES (35,'Address','provinceFk','*','employee');
+INSERT INTO `fieldAcl` VALUES (36,'Address','agencyModeFk','*','employee');
+INSERT INTO `fieldAcl` VALUES (37,'Address','phone','*','employee');
+INSERT INTO `fieldAcl` VALUES (38,'Address','mobile','*','employee');
+INSERT INTO `fieldAcl` VALUES (39,'Address','street','*','employee');
+INSERT INTO `fieldAcl` VALUES (40,'Address','city','*','employee');
+INSERT INTO `fieldAcl` VALUES (41,'Address','isActive','*','employee');
+INSERT INTO `fieldAcl` VALUES (42,'Address','isEqualizated','*','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (43,'Address','clientFk','insert','employee');
+INSERT INTO `fieldAcl` VALUES (44,'ClientObservation','*','insert','employee');
+INSERT INTO `fieldAcl` VALUES (45,'Recovery','*','insert','administrative');
+INSERT INTO `fieldAcl` VALUES (46,'Recovery','finished','update','administrative');
+INSERT INTO `fieldAcl` VALUES (47,'CreditClassification','finished','update','creditInsurance');
+INSERT INTO `fieldAcl` VALUES (48,'Account','*','update','employee');
+INSERT INTO `fieldAcl` VALUES (49,'Greuge','*','insert','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (50,'ClientSample','*','insert','employee');
+INSERT INTO `fieldAcl` VALUES (51,'Item','*','*','buyer');
+INSERT INTO `fieldAcl` VALUES (52,'Item','*','*','marketingBoss');
+INSERT INTO `fieldAcl` VALUES (53,'ItemBotanical','*','*','buyer');
+INSERT INTO `fieldAcl` VALUES (54,'ClaimEnd','*','*','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (55,'Receipt','*','*','administrative');
+INSERT INTO `fieldAcl` VALUES (56,'ClaimBeginning','*','*','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (57,'TicketRequest','*','*','salesPerson');
+INSERT INTO `fieldAcl` VALUES (58,'ClaimBeginning','*','*','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (59,'TicketRequest','*','*','salesPerson');
+INSERT INTO `fieldAcl` VALUES (60,'ClaimBeginning','*','*','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (61,'TicketRequest','*','*','salesPerson');
+INSERT INTO `fieldAcl` VALUES (62,'ClaimBeginning','*','*','salesAssistant');
+INSERT INTO `fieldAcl` VALUES (63,'TicketRequest','*','*','salesPerson');
+INSERT INTO `fieldAcl` VALUES (64,'ClaimBeginning','*','*','salesAssistant');
+
+INSERT INTO `module` VALUES ('account');
+INSERT INTO `module` VALUES ('claim');
+INSERT INTO `module` VALUES ('customer');
+INSERT INTO `module` VALUES ('entry');
+INSERT INTO `module` VALUES ('invoiceIn');
+INSERT INTO `module` VALUES ('invoiceOut');
+INSERT INTO `module` VALUES ('item');
+INSERT INTO `module` VALUES ('monitor');
+INSERT INTO `module` VALUES ('order');
+INSERT INTO `module` VALUES ('route');
+INSERT INTO `module` VALUES ('shelving');
+INSERT INTO `module` VALUES ('supplier');
+INSERT INTO `module` VALUES ('ticket');
+INSERT INTO `module` VALUES ('travel');
+INSERT INTO `module` VALUES ('wagon');
+INSERT INTO `module` VALUES ('worker');
+INSERT INTO `module` VALUES ('zone');
+
+INSERT INTO `defaultViewConfig` VALUES ('itemsIndex','{\"intrastat\":false,\"stemMultiplier\":false,\"landed\":false,\"producer\":false}');
+INSERT INTO `defaultViewConfig` VALUES ('latestBuys','{\"intrastat\":false,\"description\":false,\"density\":false,\"isActive\":false,\n \"freightValue\":false,\"packageValue\":false,\"isIgnored\":false,\"price2\":false,\"ektFk\":false,\"weight\":false,\n \"size\":false,\"comissionValue\":false,\"landing\":false}');
+INSERT INTO `defaultViewConfig` VALUES ('ticketsMonitor','{\"id\":false}');
+INSERT INTO `defaultViewConfig` VALUES ('clientsDetail','{\"id\":true,\"phone\":true,\"city\":true,\"socialName\":true,\"salesPersonFk\":true,\"email\":true,\"name\":false,\"fi\":false,\"credit\":false,\"creditInsurance\":false,\"mobile\":false,\"street\":false,\"countryFk\":false,\"provinceFk\":false,\"postcode\":false,\"created\":false,\"businessTypeFk\":false,\"payMethodFk\":false,\"sageTaxTypeFk\":false,\"sageTransactionTypeFk\":false,\"isActive\":false,\"isVies\":false,\"isTaxDataChecked\":false,\"isEqualizated\":false,\"isFreezed\":false,\"hasToInvoice\":false,\"hasToInvoiceByAddress\":false,\"isToBeMailed\":false,\"hasLcr\":false,\"hasCoreVnl\":false,\"hasSepaVnl\":false}');
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
+USE `vn`;
+/*!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 */;
+
+INSERT INTO `alertLevel` VALUES ('FREE',0,1);
+INSERT INTO `alertLevel` VALUES ('ON_PREPARATION',1,1);
+INSERT INTO `alertLevel` VALUES ('PACKED',2,0);
+INSERT INTO `alertLevel` VALUES ('DELIVERED',3,0);
+
+INSERT INTO `bookingPlanner` VALUES (5,'2017-07-01 00:00:00','4770000002','WORLD',7,4,1);
+INSERT INTO `bookingPlanner` VALUES (6,'2017-07-01 00:00:00','4770000010','NATIONAL',3,1,1);
+INSERT INTO `bookingPlanner` VALUES (8,'2017-07-01 00:00:00','4770000021','NATIONAL',1,2,1);
+INSERT INTO `bookingPlanner` VALUES (9,'2017-07-01 00:00:00','4770000101','EQU',3,1,1);
+INSERT INTO `bookingPlanner` VALUES (11,'2017-07-01 00:00:00','4770000110','EQU',4,1,1);
+INSERT INTO `bookingPlanner` VALUES (12,'2017-07-01 00:00:00','4770000215','EQU',1,2,1);
+INSERT INTO `bookingPlanner` VALUES (13,'2017-07-01 00:00:00','4770000521','EQU',2,2,1);
+INSERT INTO `bookingPlanner` VALUES (15,'2017-07-01 00:00:00','4771000000','CEE',3,1,1);
+INSERT INTO `bookingPlanner` VALUES (16,'2017-07-01 00:00:00','4771000001','CEE',8,3,1);
+INSERT INTO `bookingPlanner` VALUES (19,'2017-07-05 13:54:58','4770000020','NATIONAL',7,4,1);
+INSERT INTO `bookingPlanner` VALUES (20,'2017-07-05 14:09:24','4771000000','CEE',1,2,1);
+INSERT INTO `bookingPlanner` VALUES (21,'2017-07-05 14:09:24','4771000000','CEE',7,4,1);
+INSERT INTO `bookingPlanner` VALUES (22,'2017-07-05 14:12:14','4770000002','WORLD',3,1,1);
+INSERT INTO `bookingPlanner` VALUES (23,'2017-07-05 14:12:14','4770000002','WORLD',1,2,1);
+INSERT INTO `bookingPlanner` VALUES (24,'2017-07-06 10:07:21','4770000002','WORLD',7,4,5);
+INSERT INTO `bookingPlanner` VALUES (25,'2017-07-06 10:07:21','HolandaRED','NATIONAL',3,1,5);
+INSERT INTO `bookingPlanner` VALUES (27,'2017-07-06 10:07:21','HolandaGEN','NATIONAL',1,2,5);
+INSERT INTO `bookingPlanner` VALUES (32,'2017-07-06 10:07:21','4771000000','CEE',3,1,5);
+INSERT INTO `bookingPlanner` VALUES (33,'2017-07-06 10:07:21','4771000001','CEE',8,3,5);
+INSERT INTO `bookingPlanner` VALUES (34,'2017-07-06 10:07:21','4770000020','NATIONAL',7,4,5);
+INSERT INTO `bookingPlanner` VALUES (35,'2017-07-06 10:07:21','4771000000','CEE',1,2,5);
+INSERT INTO `bookingPlanner` VALUES (36,'2017-07-06 10:07:21','4771000000','CEE',7,4,5);
+INSERT INTO `bookingPlanner` VALUES (37,'2017-07-06 10:07:21','4770000002','WORLD',3,1,5);
+INSERT INTO `bookingPlanner` VALUES (38,'2017-07-06 10:07:21','4770000002','WORLD',1,2,5);
+INSERT INTO `bookingPlanner` VALUES (82,'2019-01-01 12:51:56','4770000504','EQU',5,5,1);
+INSERT INTO `bookingPlanner` VALUES (83,'2019-09-11 12:54:03','4770000405','EQU',6,5,1);
+INSERT INTO `bookingPlanner` VALUES (84,'2019-09-11 12:58:17','4770000004','NATIONAL',5,5,1);
+INSERT INTO `bookingPlanner` VALUES (85,'2019-09-19 00:00:00','4771000000','CEE',5,5,1);
+INSERT INTO `bookingPlanner` VALUES (86,'2021-10-14 00:00:00','4770000002','WORLD',5,5,1);
+
+INSERT INTO `businessType` VALUES ('decoration','Decoración');
+INSERT INTO `businessType` VALUES ('events','Eventos');
+INSERT INTO `businessType` VALUES ('florist','Floristería');
+INSERT INTO `businessType` VALUES ('gardenCentre','Vivero');
+INSERT INTO `businessType` VALUES ('gardening','Jardinería');
+INSERT INTO `businessType` VALUES ('individual','Particular');
+INSERT INTO `businessType` VALUES ('mortuary','Funeraria');
+INSERT INTO `businessType` VALUES ('officialOrganism','Organismo oficial');
+INSERT INTO `businessType` VALUES ('others','Otros');
+INSERT INTO `businessType` VALUES ('otherSector','Profesional de otro sector');
+INSERT INTO `businessType` VALUES ('restoration','Restauración');
+INSERT INTO `businessType` VALUES ('trainingCentre','Centro de formación');
+INSERT INTO `businessType` VALUES ('wholesaler','Mayorista');
+INSERT INTO `businessType` VALUES ('worker','Trabajador');
+
+INSERT INTO `companyI18n` VALUES (442,'en','In compliance with the provisions of Organic Law 15/1999, on the Protection of Personal Data, we inform you that the personal data you provide will be included in automated files of VERDNATURA LEVANTE SL, being able at all times to exercise the rights of access, rectification, cancellation and opposition, communicating it in writing to the registered office of the entity. The purpose of the file is administrative management, accounting, and billing.');
+INSERT INTO `companyI18n` VALUES (442,'fr','Conformément aux dispositions de la loi organique 15/1999 sur la protection des données personnelles, nous vous informons que les données personnelles que vous fournissez seront incluses dans des dossiers. VERDNATURA LEVANTE S.L., vous pouvez à tout moment, exercer les droits d``accès, de rectification, d``annulation et d``opposition, en communiquant par écrit au siège social de la société. Le dossier a pour objet la gestion administrative, la comptabilité et la facturation.');
+INSERT INTO `companyI18n` VALUES (442,'pt','Em cumprimento do disposto na lei Orgânica 15/1999, de Protecção de Dados de Carácter Pessoal, comunicamos que os dados pessoais que facilite se incluirão nos ficheiros automatizados de VERDNATURA LEVANTE S.L., podendo em todo momento exercer os direitos de acesso, rectificação, cancelação e oposição, comunicando por escrito ao domicílio social da entidade. A finalidade do ficheiro é a gestão administrativa, contabilidade e facturação.');
+
+INSERT INTO `cplusRectificationType` VALUES (1,'Campo vacio');
+INSERT INTO `cplusRectificationType` VALUES (2,'I – Por diferencias');
+INSERT INTO `cplusRectificationType` VALUES (3,'S – Por sustitución');
+
+INSERT INTO `cplusSubjectOp` VALUES (1,'Campo vacio');
+INSERT INTO `cplusSubjectOp` VALUES (2,'S1 – Sujeta – No exenta');
+INSERT INTO `cplusSubjectOp` VALUES (3,'S2 – Sujeta – No exenta – Inv. Suj. Pasivo');
+
+INSERT INTO `cplusTaxBreak` VALUES (1,'Campo vacio');
+INSERT INTO `cplusTaxBreak` VALUES (2,'E1 - Exenta por el artículo 20');
+INSERT INTO `cplusTaxBreak` VALUES (3,'E2 - Exenta por el artículo 21');
+INSERT INTO `cplusTaxBreak` VALUES (4,'E3 - Exenta por el artículo 22');
+INSERT INTO `cplusTaxBreak` VALUES (5,'E4 - Exenta por el artículo 24');
+INSERT INTO `cplusTaxBreak` VALUES (6,'E5 - Exenta por el artículo 25');
+INSERT INTO `cplusTaxBreak` VALUES (7,'E6 - Exenta por otros');
+
+INSERT INTO `claimResponsible` VALUES (1,'Compradores',0,'buy');
+INSERT INTO `claimResponsible` VALUES (2,'Proveedor',0,'sup');
+INSERT INTO `claimResponsible` VALUES (3,'Entradores',0,'ent');
+INSERT INTO `claimResponsible` VALUES (4,'Camareros',0,'bar');
+INSERT INTO `claimResponsible` VALUES (6,'Sacadores',0,'pic');
+INSERT INTO `claimResponsible` VALUES (7,'Revisadores',0,'chk');
+INSERT INTO `claimResponsible` VALUES (8,'Calidad general',0,'qas');
+INSERT INTO `claimResponsible` VALUES (9,'Encajadores',0,'pck');
+INSERT INTO `claimResponsible` VALUES (10,'Clima',0,'wea');
+INSERT INTO `claimResponsible` VALUES (11,'Comerciales',1,'com');
+INSERT INTO `claimResponsible` VALUES (12,'Clientes',1,'cli');
+INSERT INTO `claimResponsible` VALUES (13,'Administración',0,'adm');
+INSERT INTO `claimResponsible` VALUES (14,'Agencia',0,'age');
+INSERT INTO `claimResponsible` VALUES (15,'Repartidores',0,'del');
+INSERT INTO `claimResponsible` VALUES (16,'Informatica',0,'ite');
+INSERT INTO `claimResponsible` VALUES (17,'Transp.origen',0,'tra');
+INSERT INTO `claimResponsible` VALUES (18,'Confeccion',0,'con');
+INSERT INTO `claimResponsible` VALUES (19,'OTROS',0,'oth');
+INSERT INTO `claimResponsible` VALUES (21,'Gerencia',0,'man');
+INSERT INTO `claimResponsible` VALUES (22,'Paletizadores',0,'pal');
+INSERT INTO `claimResponsible` VALUES (23,'Preparación Previa',0,'pre');
+INSERT INTO `claimResponsible` VALUES (24,'Almacén PCA',0,'war');
+INSERT INTO `claimResponsible` VALUES (25,'Huelga',0,'str');
+
+INSERT INTO `claimReason` VALUES (1,'Prisas',0);
+INSERT INTO `claimReason` VALUES (2,'Novato',0);
+INSERT INTO `claimReason` VALUES (3,'Exceso de confianza',0);
+INSERT INTO `claimReason` VALUES (4,'Exceso de celo',0);
+INSERT INTO `claimReason` VALUES (5,'Indiferencia',0);
+INSERT INTO `claimReason` VALUES (6,'Extraviado o Hurto',0);
+INSERT INTO `claimReason` VALUES (7,'Incompetencia',0);
+INSERT INTO `claimReason` VALUES (8,'Ubicación erronea',0);
+INSERT INTO `claimReason` VALUES (9,'Dat.Inctos/Pak.conf',0);
+INSERT INTO `claimReason` VALUES (10,'Datos duplicados',0);
+INSERT INTO `claimReason` VALUES (11,'Fallo stock',0);
+INSERT INTO `claimReason` VALUES (12,'Innovación',0);
+INSERT INTO `claimReason` VALUES (13,'Distracción',1);
+INSERT INTO `claimReason` VALUES (15,'Portes indebidos',0);
+INSERT INTO `claimReason` VALUES (16,'Baja calidad',0);
+INSERT INTO `claimReason` VALUES (17,'Defectuoso',0);
+INSERT INTO `claimReason` VALUES (19,'Endiñado',0);
+INSERT INTO `claimReason` VALUES (20,'Calor',0);
+INSERT INTO `claimReason` VALUES (21,'Frio',0);
+INSERT INTO `claimReason` VALUES (22,'Cambiado',0);
+INSERT INTO `claimReason` VALUES (24,'Cansancio',1);
+INSERT INTO `claimReason` VALUES (25,'Mal etiquetado',1);
+INSERT INTO `claimReason` VALUES (26,'Cantidad malentendido',0);
+INSERT INTO `claimReason` VALUES (30,'No revisado',1);
+INSERT INTO `claimReason` VALUES (34,'Error fotografia',0);
+INSERT INTO `claimReason` VALUES (40,'Fallo Personal VN',0);
+INSERT INTO `claimReason` VALUES (41,'Fallo Personal Cliente',0);
+INSERT INTO `claimReason` VALUES (42,'Otros',0);
+INSERT INTO `claimReason` VALUES (43,'Precio alto',0);
+INSERT INTO `claimReason` VALUES (44,'Abuso de confianza',0);
+INSERT INTO `claimReason` VALUES (45,'Retraso Agencia',0);
+INSERT INTO `claimReason` VALUES (46,'Delicado',0);
+INSERT INTO `claimReason` VALUES (47,'Seco',0);
+INSERT INTO `claimReason` VALUES (48,'Retraso Reparto',0);
+INSERT INTO `claimReason` VALUES (49,'Mal Embalado',0);
+INSERT INTO `claimReason` VALUES (50,'Tumbado',0);
+INSERT INTO `claimReason` VALUES (51,'Enfermo/Plaga',0);
+INSERT INTO `claimReason` VALUES (52,'Mala gestión comercial',0);
+INSERT INTO `claimReason` VALUES (53,'Mala gestión comprador',0);
+INSERT INTO `claimReason` VALUES (54,'A2',0);
+INSERT INTO `claimReason` VALUES (55,'Entrega 48h o más',0);
+
+INSERT INTO `claimRedelivery` VALUES (1,'Cliente');
+INSERT INTO `claimRedelivery` VALUES (2,'No dev./No especif.');
+INSERT INTO `claimRedelivery` VALUES (3,'Reparto');
+INSERT INTO `claimRedelivery` VALUES (4,'Agencia');
+INSERT INTO `claimRedelivery` VALUES (5,'Tour');
+INSERT INTO `claimRedelivery` VALUES (6,'Fuera Peninsula');
+
+INSERT INTO `claimResult` VALUES (1,'Otros daños');
+INSERT INTO `claimResult` VALUES (2,'Roces');
+INSERT INTO `claimResult` VALUES (3,'Humedad');
+INSERT INTO `claimResult` VALUES (4,'Deshidratacion');
+INSERT INTO `claimResult` VALUES (5,'Error identidad');
+INSERT INTO `claimResult` VALUES (6,'Incompleto (Faltas)');
+INSERT INTO `claimResult` VALUES (7,'Error packing');
+INSERT INTO `claimResult` VALUES (8,'Error color');
+INSERT INTO `claimResult` VALUES (9,'Error medida');
+INSERT INTO `claimResult` VALUES (10,'Error origen');
+INSERT INTO `claimResult` VALUES (11,'Envejecido');
+INSERT INTO `claimResult` VALUES (12,'Venta Perdida');
+INSERT INTO `claimResult` VALUES (13,'Duplicacion');
+INSERT INTO `claimResult` VALUES (14,'Rechazado');
+INSERT INTO `claimResult` VALUES (15,'Rotura');
+INSERT INTO `claimResult` VALUES (16,'Deterioro/Estropeado');
+INSERT INTO `claimResult` VALUES (17,'Podrido');
+INSERT INTO `claimResult` VALUES (18,'Baboso');
+INSERT INTO `claimResult` VALUES (19,'Cocido');
+INSERT INTO `claimResult` VALUES (20,'Congelado');
+INSERT INTO `claimResult` VALUES (21,'Machacado');
+INSERT INTO `claimResult` VALUES (22,'Error precio');
+INSERT INTO `claimResult` VALUES (23,'Manchado');
+INSERT INTO `claimResult` VALUES (24,'No entregado');
+INSERT INTO `claimResult` VALUES (25,'Cobro indebido');
+INSERT INTO `claimResult` VALUES (26,'Decepcion/Esperaba mas');
+INSERT INTO `claimResult` VALUES (27,'Otros');
+INSERT INTO `claimResult` VALUES (28,'Baboso/Cocido');
+INSERT INTO `claimResult` VALUES (29,'Video Camara');
+
+INSERT INTO `component` VALUES (10,'Precios Especiales',4,NULL,NULL,1,'specialPrices',0);
+INSERT INTO `component` VALUES (14,'porte extra por dia semana',6,NULL,NULL,1,'extraCostPerWeekDay',0);
+INSERT INTO `component` VALUES (15,'reparto',6,NULL,NULL,1,'delivery',1);
+INSERT INTO `component` VALUES (17,'recobro',5,NULL,NULL,1,'debtCollection',0);
+INSERT INTO `component` VALUES (21,'ajuste',4,NULL,NULL,1,'adjustment',0);
+INSERT INTO `component` VALUES (22,'venta por paquete',9,1,NULL,0,'salePerPackage',0);
+INSERT INTO `component` VALUES (23,'venta por caja',9,2,NULL,0,'salePerBox',0);
+INSERT INTO `component` VALUES (28,'valor de compra',1,NULL,NULL,1,'purchaseValue',1);
+INSERT INTO `component` VALUES (29,'margen',4,NULL,NULL,1,'margin',1);
+INSERT INTO `component` VALUES (32,'descuento ultimas unidades',9,3,-0.05,0,'lastUnitsDiscount',0);
+INSERT INTO `component` VALUES (33,'venta por caja',9,1,NULL,0,'salePerBox',0);
+INSERT INTO `component` VALUES (34,'descuento comprador',4,NULL,NULL,1,'buyerDiscount',0);
+INSERT INTO `component` VALUES (35,'cartera comprador',10,NULL,NULL,1,NULL,0);
+INSERT INTO `component` VALUES (36,'descuadre',4,NULL,NULL,1,'imbalance',0);
+INSERT INTO `component` VALUES (37,'maná',7,4,NULL,0,'mana',0);
+INSERT INTO `component` VALUES (38,'embolsado',9,NULL,NULL,1,'bagged',0);
+INSERT INTO `component` VALUES (39,'maná auto',7,NULL,NULL,1,'autoMana',0);
+INSERT INTO `component` VALUES (40,'cambios Santos 2016',4,NULL,NULL,1,NULL,0);
+INSERT INTO `component` VALUES (41,'bonificacion porte',6,NULL,NULL,1,'freightCharge',0);
+INSERT INTO `component` VALUES (42,'promocion Francia',4,NULL,NULL,1,'frenchOffer',0);
+INSERT INTO `component` VALUES (43,'promocion Floramondo',4,NULL,NULL,1,'floramondoPromo',0);
+INSERT INTO `component` VALUES (44,'rappel cadena',2,NULL,NULL,1,'rappel',0);
+INSERT INTO `component` VALUES (45,'maná reclamacion',7,4,NULL,0,'manaClaim',0);
+INSERT INTO `component` VALUES (46,'recargo a particular',2,NULL,0.25,0,'individual',0);
+INSERT INTO `component` VALUES (47,'promocion Italia',4,NULL,NULL,1,'italianOffer',0);
+INSERT INTO `component` VALUES (48,'fusión de lineas',4,NULL,NULL,1,'lineFusion',0);
+INSERT INTO `component` VALUES (49,'sustitución',4,NULL,NULL,1,'substitution',0);
+
+INSERT INTO `componentType` VALUES (1,'coste',1,0,'COST');
+INSERT INTO `componentType` VALUES (2,'com ventas',1,1,NULL);
+INSERT INTO `componentType` VALUES (3,'com compras',1,1,NULL);
+INSERT INTO `componentType` VALUES (4,'empresa',1,1,'MARGIN');
+INSERT INTO `componentType` VALUES (5,'cliente',0,0,NULL);
+INSERT INTO `componentType` VALUES (6,'agencia',0,0,'FREIGHT');
+INSERT INTO `componentType` VALUES (7,'cartera_comercial',0,0,'MANA');
+INSERT INTO `componentType` VALUES (8,'cartera_producto',0,1,NULL);
+INSERT INTO `componentType` VALUES (9,'maniobra',1,0,NULL);
+INSERT INTO `componentType` VALUES (10,'cartera_comprador',0,1,NULL);
+INSERT INTO `componentType` VALUES (11,'errores',0,1,NULL);
+INSERT INTO `componentType` VALUES (12,'otros',0,1,NULL);
+
+INSERT INTO `continent` VALUES (1,'Asia','AS');
+INSERT INTO `continent` VALUES (2,'América','AM');
+INSERT INTO `continent` VALUES (3,'África','AF');
+INSERT INTO `continent` VALUES (4,'Europa','EU');
+INSERT INTO `continent` VALUES (5,'Oceanía','OC');
+
+INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,110,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (22,'shopping','COMPRAS',2,3,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (23,'CMA','CAMARA',13,14,NULL,72,1,1,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (31,'it','INFORMATICA',4,5,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (34,'accounting','CONTABILIDAD',6,7,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (35,'finance','FINANZAS',8,9,NULL,0,0,0,1,0,1,'/1/',NULL,1,'begonya@verdnatura.es',1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (36,'labor','LABORAL',10,11,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (37,'PROD','PRODUCCION',12,35,NULL,72,1,1,1,11,1,'/1/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (38,'picking','SACADO',15,16,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (39,'packing','ENCAJADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',36,37,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (43,'VT','VENTAS',38,69,NULL,0,0,0,1,15,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (44,'management','GERENCIA',70,71,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',72,73,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (46,'delivery','REPARTO',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',76,77,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',39,40,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (55,NULL,'TALLER NATURAL',19,20,14548,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1118,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (56,NULL,'TALLER ARTIFICIAL',21,22,8470,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1927,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (58,'CMP','CAMPOS',84,87,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',88,89,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,1,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (61,NULL,'VNH',90,93,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',94,95,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (68,NULL,'COMPLEMENTOS',23,24,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',96,97,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (80,'vallesTeam','EQUIPO J VALLES',43,44,4250,72,0,0,2,0,43,'/1/43/','jvp_equipo',1,'equipojvalles@verdnatura.es',0,0,0,0,NULL,NULL,'5300',NULL);
+INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',98,99,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (89,NULL,'COORDINACION',100,101,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (90,NULL,'TRAILER',91,92,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (91,'artificial','ARTIFICIAL',25,26,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (92,NULL,'EQUIPO SILVERIO',45,46,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (94,'brocalTeam','EQUIPO J BROCAL',47,48,3797,0,0,0,2,0,43,'/1/43/','jes_equipo',0,'equipojbrocal@verdnatura.es',0,0,0,0,NULL,NULL,'5100',NULL);
+INSERT INTO `department` VALUES (95,'zambranoTeam','EQUIPO C ZAMBRANO',49,50,4667,0,0,0,2,0,43,'/1/43/','czg_equipo',0,'equipoczambrano@verdnatura.es',0,0,0,0,NULL,NULL,'5000',NULL);
+INSERT INTO `department` VALUES (96,NULL,'EQUIPO C LOPEZ',51,52,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (115,NULL,'EQUIPO CLAUDI',53,54,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (123,NULL,'EQUIPO ELENA BASCUÑANA',55,56,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',102,103,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (125,'miriamMarTeam','EQUIPO MIRIAM MAR',57,58,1118,0,0,0,2,0,43,'/1/43/','mir_equipo',0,'equipomirgir@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL);
+INSERT INTO `department` VALUES (126,NULL,'PRESERVADO',27,28,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (128,NULL,'PALETIZADO',29,30,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (130,NULL,'REVISION',31,32,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',85,86,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',59,60,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',61,62,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'francia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL);
+INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',63,64,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL);
+INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',104,105,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',106,107,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (137,'sorter','SORTER',108,109,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (139,'soriaTeam','EQUIPO J SORIA ',65,66,3803,0,0,0,2,0,43,'/1/43/','jss_equipo',1,'equipojsoria@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL);
+INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',67,68,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (141,NULL,'PREVIA',33,34,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL);
+
+INSERT INTO `docuware` VALUES (1,'deliveryNote','Albaranes cliente','find','find','N__ALBAR_N',NULL);
+INSERT INTO `docuware` VALUES (2,'deliveryNote','Albaranes cliente','store','Archivar','N__ALBAR_N',NULL);
+INSERT INTO `docuware` VALUES (3,'hr','RRHH','find','Búsqueda','N__DOCUMENTO',3);
+
+INSERT INTO `itemPackingType` VALUES ('F','Fruta y Verdura',0);
+INSERT INTO `itemPackingType` VALUES ('H','Horizontal',1);
+INSERT INTO `itemPackingType` VALUES ('P','Pienso',0);
+INSERT INTO `itemPackingType` VALUES ('V','Vertical',1);
+
+INSERT INTO `pgc` VALUES ('4722000000',0.00,'Importación Exento ',1,0,0,1,0);
+INSERT INTO `pgc` VALUES ('4722000010',10.00,'Importación Reducido ',1,0,0,1,0);
+INSERT INTO `pgc` VALUES ('4722000021',21.00,'Importación General ',1,0,0,1,0);
+INSERT INTO `pgc` VALUES ('4770000001',8.00,'Reducido',1,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4770000002',0.00,'Extra-Community supply',3,1,0,2,0);
+INSERT INTO `pgc` VALUES ('4770000004',4.00,'Super reducido',1,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4770000010',10.00,'Reducido',1,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4770000020',0.00,'Exento',7,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4770000021',21.00,'General',1,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4770000101',10.00,'Reducido ',1,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4770000108',8.00,'Reducido',1,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4770000110',1.40,'Rec. Eq. Reducido',1,0,0,1,1);
+INSERT INTO `pgc` VALUES ('4770000215',21.00,'General',1,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4770000405',0.50,'Rec. Eq. Super Reducido',1,0,0,1,1);
+INSERT INTO `pgc` VALUES ('4770000504',4.00,'Super reducido',1,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4770000521',5.20,'Rec. Eq. General',1,0,0,1,1);
+INSERT INTO `pgc` VALUES ('4770000701',1.00,'Rec. Eq. Reducido',1,0,0,1,1);
+INSERT INTO `pgc` VALUES ('4771000000',0.00,'Intra-Community supply',6,1,1,1,0);
+INSERT INTO `pgc` VALUES ('4771000001',0.00,'Intra-Community services',7,1,1,1,0);
+INSERT INTO `pgc` VALUES ('HolandaGEN',21.00,'General',1,0,0,1,0);
+INSERT INTO `pgc` VALUES ('HolandaRED',9.00,'Reducido',1,0,0,1,0);
+INSERT INTO `pgc` VALUES ('IGIC cero',0.00,'Cero',1,0,0,1,0);
+INSERT INTO `pgc` VALUES ('IGIC gener',6.50,'General',1,0,0,1,0);
+INSERT INTO `pgc` VALUES ('IGIC reduc',3.00,'Reducido',1,0,0,1,0);
+
+INSERT INTO `sample` VALUES (1,'Carta_1','Aviso inicial por saldo deudor',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (2,'Carta_2','Reiteracion de aviso por saldo deudor',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (3,'Cred_Up','Notificación de aumento de crédito',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (4,'Cred_down','Notificación de reducción de crédito',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (5,'Pet_CC','Petición de datos bancarios B2B',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (6,'SolCredito','Solicitud de crédito',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (7,'LeyPago','Ley de pagos',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (8,'Pet_CC_Core','Petición de datos bancarios CORE',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (9,'nueva_alta','Documento de nueva alta de cliente',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (10,'client_welcome','Email de bienvenida para nuevo cliente',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (11,'setup_printer','Email de instalación de impresora',0,0,1,0,NULL);
+INSERT INTO `sample` VALUES (12,'client-welcome','Bienvenida como nuevo cliente',1,0,1,0,'Clients');
+INSERT INTO `sample` VALUES (13,'printer-setup','Instalación y configuración de impresora de coronas',1,0,1,0,'Clients');
+INSERT INTO `sample` VALUES (14,'sepa-core','Solicitud de domiciliación bancaria',1,1,0,0,'Clients');
+INSERT INTO `sample` VALUES (15,'letter-debtor-st','Aviso inicial por saldo deudor',1,1,1,0,'Clients');
+INSERT INTO `sample` VALUES (16,'letter-debtor-nd','Aviso reiterado por saldo deudor',1,1,1,0,'Clients');
+INSERT INTO `sample` VALUES (17,'client-lcr','Email de solicitud de datos bancarios LCR',0,1,1,0,NULL);
+INSERT INTO `sample` VALUES (18,'client-debt-statement','Extracto del cliente',1,0,1,1,'Clients');
+INSERT INTO `sample` VALUES (19,'credit-request','Solicitud de crédito',1,1,1,0,'Clients');
+INSERT INTO `sample` VALUES (20,'incoterms-authorization','Autorización de incoterms',1,1,1,0,'Clients');
+
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (1,'Operación de régimen general');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (2,'Operaciones por las que los empresarios satisfacen compensaciones REAGYP');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (3,'Operaciones a las que se aplique el régimen especial de bienes usados, objetos de arte, antigüedades y objetos de colección (135 - 139 de LIVA)');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (4,'Régimen especial oro de inversión');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (5,'Régimen especial agencias de viajes');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (6,'Régimen especial grupo de entidades en IVA (Nivel Avanzado)');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (7,'Régimen especial criterio de caja');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (8,'Operaciones sujetas al IPSI / IGIC');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (9,'Adquisiciones intracomunitarias de bienes y prestaciones de servicios');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (12,'Operaciones de arrendamiento de local de negocio');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (13,'Factura correspondiente a una importación (informada sin asociar a un DUA)');
+INSERT INTO `siiTrascendencyInvoiceIn` VALUES (14,'Primer semestre 2017');
+
+INSERT INTO `siiTypeInvoiceIn` VALUES (1,'F1','Factura');
+INSERT INTO `siiTypeInvoiceIn` VALUES (2,'F2','Factura simplificada (ticket)');
+INSERT INTO `siiTypeInvoiceIn` VALUES (3,'F3','Factura emitida en sustitución de facturas simplificadas facturadas y declaradas');
+INSERT INTO `siiTypeInvoiceIn` VALUES (4,'F4','Asiento resumen de facturas');
+INSERT INTO `siiTypeInvoiceIn` VALUES (5,'F5','Importaciones (DUA)');
+INSERT INTO `siiTypeInvoiceIn` VALUES (6,'F6','Otros justificantes contables');
+INSERT INTO `siiTypeInvoiceIn` VALUES (7,'R1','Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)');
+INSERT INTO `siiTypeInvoiceIn` VALUES (8,'R2','Factura rectificativa (Art. 80.3)');
+INSERT INTO `siiTypeInvoiceIn` VALUES (9,'R3','Factura rectificativa (Art. 80.4)');
+INSERT INTO `siiTypeInvoiceIn` VALUES (10,'R4','Factura rectificativa (Resto)');
+INSERT INTO `siiTypeInvoiceIn` VALUES (11,'R5','Factura rectificativa en facturas simplificadas');
+
+INSERT INTO `siiTypeInvoiceOut` VALUES (1,'F1','Factura');
+INSERT INTO `siiTypeInvoiceOut` VALUES (2,'F2','Factura simplificada (ticket)');
+INSERT INTO `siiTypeInvoiceOut` VALUES (3,'F3','Factura emitida en sustitución de facturas simplificadas facturadas y declaradas');
+INSERT INTO `siiTypeInvoiceOut` VALUES (4,'F4','Asiento resumen de facturas');
+INSERT INTO `siiTypeInvoiceOut` VALUES (5,'R1','Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)');
+INSERT INTO `siiTypeInvoiceOut` VALUES (6,'R2','Factura rectificativa (Art. 80.3)');
+INSERT INTO `siiTypeInvoiceOut` VALUES (7,'R3','Factura rectificativa (Art. 80.4)');
+INSERT INTO `siiTypeInvoiceOut` VALUES (8,'R4','Factura rectificativa (Resto)');
+INSERT INTO `siiTypeInvoiceOut` VALUES (9,'R5','Factura rectificativa en facturas simplificadas');
+
+INSERT INTO `silexACL` VALUES (1,'workerTimeControl','clockIn','$everyone');
+INSERT INTO `silexACL` VALUES (2,'workerTimeControl','getClockIn','$everyone');
+INSERT INTO `silexACL` VALUES (3,'workerTimeControl','login','$everyone');
+INSERT INTO `silexACL` VALUES (4,'security','device_checkLogin','employee');
+INSERT INTO `silexACL` VALUES (5,'security','getVersion','employee');
+INSERT INTO `silexACL` VALUES (6,'security','login','employee');
+INSERT INTO `silexACL` VALUES (7,'delivery','addNote','employee');
+INSERT INTO `silexACL` VALUES (8,'delivery','expeditionState_add','employee');
+INSERT INTO `silexACL` VALUES (9,'delivery','expeditionState_addByExpedition','employee');
+INSERT INTO `silexACL` VALUES (10,'delivery','expeditionState_addByExpeditionMulti','employee');
+INSERT INTO `silexACL` VALUES (11,'delivery','expeditionState_addByRoute','employee');
+INSERT INTO `silexACL` VALUES (12,'delivery','expedition_getLog','employee');
+INSERT INTO `silexACL` VALUES (13,'delivery','getExpeditionFromRoute','employee');
+INSERT INTO `silexACL` VALUES (14,'delivery','getInfo','employee');
+INSERT INTO `silexACL` VALUES (15,'delivery','getInfoCompany','employee');
+INSERT INTO `silexACL` VALUES (16,'delivery','getInfoFreelance','employee');
+INSERT INTO `silexACL` VALUES (17,'delivery','getWorkers','employee');
+INSERT INTO `silexACL` VALUES (18,'delivery','get_routes','employee');
+INSERT INTO `silexACL` VALUES (19,'delivery','get_tickets','employee');
+INSERT INTO `silexACL` VALUES (20,'delivery','get_version','employee');
+INSERT INTO `silexACL` VALUES (21,'delivery','saveLoadersWorkers','employee');
+INSERT INTO `silexACL` VALUES (22,'delivery','save_sign','employee');
+INSERT INTO `silexACL` VALUES (23,'delivery','setRouteOk','employee');
+INSERT INTO `silexACL` VALUES (24,'delivery','updateExpeditionChecked','employee');
+INSERT INTO `silexACL` VALUES (25,'delivery','update_routes','employee');
+INSERT INTO `silexACL` VALUES (26,'almacennew','barcodes_edit','employee');
+INSERT INTO `silexACL` VALUES (27,'almacennew','barcodeToItem','employee');
+INSERT INTO `silexACL` VALUES (28,'almacennew','buffer_setTypeByName','employee');
+INSERT INTO `silexACL` VALUES (29,'almacennew','buy_updateGrouping','employee');
+INSERT INTO `silexACL` VALUES (30,'almacennew','buy_updatePacking','employee');
+INSERT INTO `silexACL` VALUES (31,'almacennew','checkRouteExpeditionScanPut','employee');
+INSERT INTO `silexACL` VALUES (32,'almacennew','clearShelvingList','employee');
+INSERT INTO `silexACL` VALUES (33,'almacennew','collectionAddItem','employee');
+INSERT INTO `silexACL` VALUES (34,'almacennew','collectionGet','employee');
+INSERT INTO `silexACL` VALUES (35,'almacennew','collectionIncreaseQuantity','employee');
+INSERT INTO `silexACL` VALUES (36,'almacennew','collectionMissingTrash','employee');
+INSERT INTO `silexACL` VALUES (37,'almacennew','collectionNew','employee');
+INSERT INTO `silexACL` VALUES (38,'almacennew','collectionStickerPrint','employee');
+INSERT INTO `silexACL` VALUES (39,'almacennew','collection_getTickets','employee');
+INSERT INTO `silexACL` VALUES (40,'almacennew','collection_printSticker','employee');
+INSERT INTO `silexACL` VALUES (41,'almacennew','department_getHasMistake','employee');
+INSERT INTO `silexACL` VALUES (42,'almacennew','deviceLog_add','employee');
+INSERT INTO `silexACL` VALUES (43,'almacennew','deviceProductionUser_getWorker','employee');
+INSERT INTO `silexACL` VALUES (44,'almacennew','deviceProduction_getnameDevice','employee');
+INSERT INTO `silexACL` VALUES (45,'almacennew','expeditionLoading_add','employee');
+INSERT INTO `silexACL` VALUES (46,'almacennew','expeditionPalletDel','employee');
+INSERT INTO `silexACL` VALUES (47,'almacennew','expeditionPalletList','employee');
+INSERT INTO `silexACL` VALUES (48,'almacennew','expeditionPalletPrintSet','employee');
+INSERT INTO `silexACL` VALUES (49,'almacennew','expeditionPalletView','employee');
+INSERT INTO `silexACL` VALUES (50,'almacennew','expeditionScanAdd','employee');
+INSERT INTO `silexACL` VALUES (51,'almacennew','expeditionScanDel','employee');
+INSERT INTO `silexACL` VALUES (52,'almacennew','expeditionScanList','employee');
+INSERT INTO `silexACL` VALUES (53,'almacennew','expeditionScanPut','employee');
+INSERT INTO `silexACL` VALUES (54,'almacennew','expeditionState_addByPallet','employee');
+INSERT INTO `silexACL` VALUES (55,'almacennew','expeditionTruckAdd','employee');
+INSERT INTO `silexACL` VALUES (56,'almacennew','expeditionTruckList','employee');
+INSERT INTO `silexACL` VALUES (57,'almacennew','expedition_getState','employee');
+INSERT INTO `silexACL` VALUES (58,'almacennew','expedition_scan','employee');
+INSERT INTO `silexACL` VALUES (59,'almacennew','faultsReview','employee');
+INSERT INTO `silexACL` VALUES (60,'almacennew','faultsReview_isChecked','employee');
+INSERT INTO `silexACL` VALUES (61,'almacennew','getItemUbication','employee');
+INSERT INTO `silexACL` VALUES (62,'almacennew','get_ItemPackingType','employee');
+INSERT INTO `silexACL` VALUES (63,'almacennew','itemDiary','employee');
+INSERT INTO `silexACL` VALUES (64,'almacennew','itemPlacementSupplyAiming','employee');
+INSERT INTO `silexACL` VALUES (65,'almacennew','itemPlacementSupplyCloseOrder','employee');
+INSERT INTO `silexACL` VALUES (66,'almacennew','itemPlacementSupplyGetOrder','employee');
+INSERT INTO `silexACL` VALUES (68,'almacennew','itemShelvingBuyerGet','employee');
+INSERT INTO `silexACL` VALUES (69,'almacennew','itemShelvingBuyerTask','employee');
+INSERT INTO `silexACL` VALUES (70,'almacennew','itemShelvingDelete','employee');
+INSERT INTO `silexACL` VALUES (71,'almacennew','itemShelvingList','employee');
+INSERT INTO `silexACL` VALUES (72,'almacennew','itemShelvingLog_get','employee');
+INSERT INTO `silexACL` VALUES (73,'almacennew','itemShelvingMake','employee');
+INSERT INTO `silexACL` VALUES (74,'almacennew','itemShelvingMakeEdit','employee');
+INSERT INTO `silexACL` VALUES (75,'almacennew','itemShelvingMake_multi','employee');
+INSERT INTO `silexACL` VALUES (76,'almacennew','itemShelvingPlacementSupplyAdd','employee');
+INSERT INTO `silexACL` VALUES (77,'almacennew','itemShelvingSaleSupplyAdd','employee');
+INSERT INTO `silexACL` VALUES (78,'almacennew','itemShelvingStarsUpdate','employee');
+INSERT INTO `silexACL` VALUES (79,'almacennew','itemShelvingTransfer','employee');
+INSERT INTO `silexACL` VALUES (80,'almacennew','itemShelving_addByClaim','employee');
+INSERT INTO `silexACL` VALUES (81,'almacennew','itemShelving_filterBuyer','employee');
+INSERT INTO `silexACL` VALUES (82,'almacennew','itemShelving_getSaleDate','employee');
+INSERT INTO `silexACL` VALUES (83,'almacennew','itemTrash','employee');
+INSERT INTO `silexACL` VALUES (84,'almacennew','item_card','employee');
+INSERT INTO `silexACL` VALUES (85,'almacennew','item_getSimilar','employee');
+INSERT INTO `silexACL` VALUES (86,'almacennew','item_placement_save','employee');
+INSERT INTO `silexACL` VALUES (87,'almacennew','item_saveReference','employee');
+INSERT INTO `silexACL` VALUES (88,'almacennew','item_updatePackingShelve','employee');
+INSERT INTO `silexACL` VALUES (89,'almacennew','machineWorker_add','employee');
+INSERT INTO `silexACL` VALUES (90,'almacennew','machineWorker_getHistorical','employee');
+INSERT INTO `silexACL` VALUES (91,'almacennew','machineWorker_update','employee');
+INSERT INTO `silexACL` VALUES (92,'almacennew','machineWorker_Worker','employee');
+INSERT INTO `silexACL` VALUES (93,'almacennew','machine_checkPlate','employee');
+INSERT INTO `silexACL` VALUES (94,'almacennew','machine_getWorkerPlate','employee');
+INSERT INTO `silexACL` VALUES (95,'almacennew','mistakeType','employee');
+INSERT INTO `silexACL` VALUES (96,'almacennew','printer_get','employee');
+INSERT INTO `silexACL` VALUES (97,'almacennew','qr_getCall','developer');
+INSERT INTO `silexACL` VALUES (98,'almacennew','saleMistakeAdd','employee');
+INSERT INTO `silexACL` VALUES (99,'almacennew','saleMove','employee');
+INSERT INTO `silexACL` VALUES (100,'almacennew','saleParking_add','employee');
+INSERT INTO `silexACL` VALUES (101,'almacennew','saleTrackingDel','employee');
+INSERT INTO `silexACL` VALUES (102,'almacennew','saleTrackingReplace','employee');
+INSERT INTO `silexACL` VALUES (103,'almacennew','saleTracking_add','employee');
+INSERT INTO `silexACL` VALUES (104,'almacennew','saleTracking_addPrevOK','employee');
+INSERT INTO `silexACL` VALUES (105,'almacennew','saleTracking_updateIsChecked','employee');
+INSERT INTO `silexACL` VALUES (106,'almacennew','sectorCollectionSaleGroup_add','employee');
+INSERT INTO `silexACL` VALUES (107,'almacennew','sectorCollection_get','employee');
+INSERT INTO `silexACL` VALUES (108,'almacennew','sectorCollection_getSale','employee');
+INSERT INTO `silexACL` VALUES (109,'almacennew','sectorCollection_new','employee');
+INSERT INTO `silexACL` VALUES (110,'almacennew','sector_get','employee');
+INSERT INTO `silexACL` VALUES (111,'almacennew','shelvingChange','employee');
+INSERT INTO `silexACL` VALUES (112,'almacennew','shelvingLog_get','employee');
+INSERT INTO `silexACL` VALUES (113,'almacennew','shelvingPark','employee');
+INSERT INTO `silexACL` VALUES (114,'almacennew','shelvingParking_get','employee');
+INSERT INTO `silexACL` VALUES (115,'almacennew','shelvingPriorityUpdate','employee');
+INSERT INTO `silexACL` VALUES (116,'almacennew','sip_getExtension','employee');
+INSERT INTO `silexACL` VALUES (117,'almacennew','ticketCollection_setUsedShelves','employee');
+INSERT INTO `silexACL` VALUES (118,'almacennew','ticketOrCollection_checkFullyControlled','employee');
+INSERT INTO `silexACL` VALUES (119,'almacennew','ticketToPrePrepare','employee');
+INSERT INTO `silexACL` VALUES (120,'almacennew','ticket_checkFullyControlled','employee');
+INSERT INTO `silexACL` VALUES (121,'almacennew','ticket_setState','employee');
+INSERT INTO `silexACL` VALUES (122,'almacennew','update_ItemPackingType','employee');
+INSERT INTO `silexACL` VALUES (123,'almacennew','workerMachinery_isRegistered','employee');
+INSERT INTO `silexACL` VALUES (124,'almacennew','workerMistakeType_get','employee');
+INSERT INTO `silexACL` VALUES (125,'almacennew','workerMistake_Add','coolerBoss');
+INSERT INTO `silexACL` VALUES (126,'almacennew','workerShelving_add','employee');
+INSERT INTO `silexACL` VALUES (127,'almacennew','workerShelving_delete','employee');
+INSERT INTO `silexACL` VALUES (128,'almacennew','worker_getFromHasMistake','employee');
+INSERT INTO `silexACL` VALUES (129,'almacennew','worker_getId','employee');
+INSERT INTO `silexACL` VALUES (130,'almacennew','worker_getPrinter','employee');
+INSERT INTO `silexACL` VALUES (131,'almacennew','worker_getSector','employee');
+INSERT INTO `silexACL` VALUES (132,'almacennew','worker_updatePrinter','employee');
+INSERT INTO `silexACL` VALUES (133,'almacennew','worker_updateSector','employee');
+INSERT INTO `silexACL` VALUES (134,'almacennew','itemShelving_updateFromSale','employee');
+INSERT INTO `silexACL` VALUES (135,'almacennew','collection_getUncheckedTicket','employee');
+INSERT INTO `silexACL` VALUES (136,'almacennew','itemShelving_return','employee');
+INSERT INTO `silexACL` VALUES (137,'almacennew','itemShelving_merge','employee');
+INSERT INTO `silexACL` VALUES (139,'delivery','get_expeditionsSummary','employee');
+INSERT INTO `silexACL` VALUES (140,'almacennew','cmrExpeditionPallet_add','employee');
+INSERT INTO `silexACL` VALUES (141,'delivery','route_getExpeditionSummary','employee');
+INSERT INTO `silexACL` VALUES (142,'almacennew','item_saveStems','employee');
+INSERT INTO `silexACL` VALUES (143,'almacennew','debug_add','employee');
+INSERT INTO `silexACL` VALUES (144,'almacennew','operator_getNumberOfWagons','employee');
+INSERT INTO `silexACL` VALUES (145,'almacennew','operator_add','employee');
+INSERT INTO `silexACL` VALUES (146,'almacennew','expeditionPallet_get','employee');
+INSERT INTO `silexACL` VALUES (147,'almacennew','worker_isF11Allowed','employee');
+INSERT INTO `silexACL` VALUES (148,'almacennew','train_get','employee');
+INSERT INTO `silexACL` VALUES (149,'almacennew','saleTracking_mark','employee');
+INSERT INTO `silexACL` VALUES (150,'almacennew','operator_updateItemPackingType','employee');
+INSERT INTO `silexACL` VALUES (151,'almacennew','operator_updateTrain','employee');
+INSERT INTO `silexACL` VALUES (152,'almacennew','operator_getTrain','employee');
+INSERT INTO `silexACL` VALUES (153,'almacennew','operator_getItemPackingType','employee');
+INSERT INTO `silexACL` VALUES (154,'almacennew','collection_assign','employee');
+INSERT INTO `silexACL` VALUES (155,'almacennew','itemPacking_get','employee');
+INSERT INTO `silexACL` VALUES (156,'almacennew','shelvingLog_add','employee');
+INSERT INTO `silexACL` VALUES (157,'almacennew','collection_get','employee');
+INSERT INTO `silexACL` VALUES (158,'delivery','get_routesFromExpedition','employee');
+INSERT INTO `silexACL` VALUES (160,'almacennew','expeditionMistakeType_get','employee');
+INSERT INTO `silexACL` VALUES (161,'almacennew','expeditionMistake_add','employee');
+INSERT INTO `silexACL` VALUES (162,'almacennew','itemShelving_addList','employee');
+INSERT INTO `silexACL` VALUES (163,'almacennew','cmrPallet_add','employee');
+INSERT INTO `silexACL` VALUES (164,'almacennew','ticket_isOutClosureZone','employee');
+INSERT INTO `silexACL` VALUES (165,'almacennew','itemShelving_selfConsumption','employee');
+INSERT INTO `silexACL` VALUES (166,'almacennew','ticket_printLabelPrevious','employee');
+INSERT INTO `silexACL` VALUES (167,'almacennew','travel_updatePacking','employee');
+INSERT INTO `silexACL` VALUES (168,'app','status','$everyone');
+
+INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (2,'Libre',2,0,'FREE',NULL,2,0,0,0,0,0,0,4,1,'notice');
+INSERT INTO `state` VALUES (3,'OK',3,0,'OK',3,28,1,0,0,0,1,1,3,0,'success');
+INSERT INTO `state` VALUES (4,'Impreso',4,0,'PRINTED',2,29,1,0,1,0,0,1,2,0,'success');
+INSERT INTO `state` VALUES (5,'Preparación',6,1,'ON_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning');
+INSERT INTO `state` VALUES (6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0,3,0,0,1,0,'warning');
+INSERT INTO `state` VALUES (7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0,3,0,0,1,0,'warning');
+INSERT INTO `state` VALUES (9,'Encajando',9,2,'PACKING',NULL,9,0,1,0,0,0,0,1,0,NULL);
+INSERT INTO `state` VALUES (10,'Encajado',10,2,'PACKED',NULL,10,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (11,'Facturado',0,3,'INVOICED',NULL,11,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0,2,0,0,1,0,'warning');
+INSERT INTO `state` VALUES (15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (20,'Asignado',4,0,'PICKER_DESIGNED',NULL,20,1,0,0,0,0,0,2,0,'success');
+INSERT INTO `state` VALUES (21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0,0,0,0,2,0,'success');
+INSERT INTO `state` VALUES (22,'Pte. Ampliar',2,0,'EXPANDABLE',NULL,22,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (23,'URGENTE',5,1,'LAST_CALL',NULL,23,1,0,1,0,0,0,4,1,'success');
+INSERT INTO `state` VALUES (24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0,0,3,1,'success');
+INSERT INTO `state` VALUES (25,'Embarcando',3,0,'BOARDING',5,25,1,0,0,0,0,0,3,0,'alert');
+INSERT INTO `state` VALUES (26,'Prep Previa',5,0,'PREVIOUS_PREPARATION',1,28,1,0,0,1,0,0,2,0,'warning');
+INSERT INTO `state` VALUES (27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0,0,0,0,2,0,'success');
+INSERT INTO `state` VALUES (28,'Previa OK',3,0,'OK PREVIOUS',3,28,1,0,1,1,1,1,3,0,'warning');
+INSERT INTO `state` VALUES (29,'Previa Impreso',4,0,'PRINTED PREVIOUS',2,29,1,0,1,0,0,1,2,0,'success');
+INSERT INTO `state` VALUES (30,'Embarcado',4,1,'BOARD',5,30,0,0,0,2,0,0,3,0,'success');
+INSERT INTO `state` VALUES (31,'Polizon Impreso',4,1,'PRINTED STOWAWAY',2,29,1,0,1,0,0,1,2,0,'success');
+INSERT INTO `state` VALUES (32,'Polizon OK',3,1,'OK STOWAWAY',3,31,1,0,0,1,1,1,3,0,'warning');
+INSERT INTO `state` VALUES (33,'Auto_Impreso',4,0,'PRINTED_AUTO',2,29,1,0,1,0,0,1,2,0,'success');
+INSERT INTO `state` VALUES (34,'Pte Pago',3,0,'WAITING_FOR_PAYMENT',NULL,34,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (35,'Semi-Encajado',9,2,'HALF_PACKED',NULL,10,0,1,0,0,0,0,1,0,NULL);
+INSERT INTO `state` VALUES (36,'Previa Revisando',3,0,'PREVIOUS_CONTROL',2,37,1,0,0,4,0,1,2,0,'warning');
+INSERT INTO `state` VALUES (37,'Previa Revisado',3,0,'PREVIOUS_CONTROLLED',2,29,1,0,1,0,0,1,2,0,'warning');
+INSERT INTO `state` VALUES (38,'Prep Cámara',6,1,'COOLER_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning');
+INSERT INTO `state` VALUES (41,'Prep Parcial',6,1,'PARTIAL_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning');
+
+INSERT INTO `ticketUpdateAction` VALUES (1,'Cambiar los precios en el ticket','renewPrices');
+INSERT INTO `ticketUpdateAction` VALUES (2,'Convertir en maná','mana');
+
+INSERT INTO `volumeConfig` VALUES (2.67,1.60,0.8,150,0.30,120,57,2.0,50,200,10,167.0);
+
+INSERT INTO `workCenter` VALUES (1,'Silla',20,859,1,'Av espioca 100',552703,NULL);
+INSERT INTO `workCenter` VALUES (2,'Mercaflor',19,NULL,NULL,NULL,NULL,NULL);
+INSERT INTO `workCenter` VALUES (3,'Marjales',26,20008,NULL,NULL,NULL,NULL);
+INSERT INTO `workCenter` VALUES (4,'VNH',NULL,NULL,NULL,NULL,NULL,NULL);
+INSERT INTO `workCenter` VALUES (5,'Madrid',28,2869,5,'Av constitución 3',554145,2.00);
+INSERT INTO `workCenter` VALUES (6,'Vilassar',88,88038,NULL,'Cami del Crist, 33',556412,NULL);
+INSERT INTO `workCenter` VALUES (7,'Tenerife',NULL,NULL,NULL,NULL,NULL,NULL);
+INSERT INTO `workCenter` VALUES (8,'Silla-Agrario',26,NULL,NULL,NULL,NULL,NULL);
+INSERT INTO `workCenter` VALUES (9,'Algemesi',20,1354,60,'Fenollars, 2',523549,NULL);
+INSERT INTO `workCenter` VALUES (10,'Rubi',88,NULL,84,'Av. de la Llana, 131',549722,NULL);
+
+INSERT INTO `workerTimeControlError` VALUES (1,'IS_NOT_ALLOWED_FUTURE','No se permite fichar a futuro');
+INSERT INTO `workerTimeControlError` VALUES (2,'INACTIVE_BUSINESS','No hay un contrato en vigor');
+INSERT INTO `workerTimeControlError` VALUES (3,'IS_NOT_ALLOWED_WORK','No está permitido trabajar');
+INSERT INTO `workerTimeControlError` VALUES (4,'ODD_WORKERTIMECONTROL','Fichadas impares');
+INSERT INTO `workerTimeControlError` VALUES (5,'DAY_MAX_TIME','Superado el tiempo máximo entre entrada y salida');
+INSERT INTO `workerTimeControlError` VALUES (6,'BREAK_DAY','Descanso diario');
+INSERT INTO `workerTimeControlError` VALUES (7,'BREAK_WEEK','Descanso semanal');
+INSERT INTO `workerTimeControlError` VALUES (8,'WRONG_DIRECTION','Dirección incorrecta');
+INSERT INTO `workerTimeControlError` VALUES (9,'UNDEFINED_ERROR','Error sin definir');
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
+USE `cache`;
+/*!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 */;
+
+INSERT INTO `cache` VALUES (1,'equalizator','00:19:00');
+INSERT INTO `cache` VALUES (2,'available','00:06:00');
+INSERT INTO `cache` VALUES (3,'stock','00:30:00');
+INSERT INTO `cache` VALUES (4,'last_buy','23:59:00');
+INSERT INTO `cache` VALUES (5,'weekly_sales','12:00:00');
+INSERT INTO `cache` VALUES (6,'bionic','00:06:00');
+INSERT INTO `cache` VALUES (7,'sales','00:04:00');
+INSERT INTO `cache` VALUES (8,'visible','00:04:00');
+INSERT INTO `cache` VALUES (9,'item_range','00:03:00');
+INSERT INTO `cache` VALUES (10,'barcodes','01:00:00');
+INSERT INTO `cache` VALUES (11,'prod_graphic','00:17:00');
+INSERT INTO `cache` VALUES (12,'ticketShipping','00:01:00');
+INSERT INTO `cache` VALUES (13,'availableNoRaids','00:06:00');
+INSERT INTO `cache` VALUES (14,'lastBuy','23:59:00');
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
+USE `hedera`;
+/*!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 */;
+
+INSERT INTO `browser` VALUES ('Chrome',49);
+INSERT INTO `browser` VALUES ('Edge',79);
+INSERT INTO `browser` VALUES ('Firefox',69);
+INSERT INTO `browser` VALUES ('Opera',36);
+INSERT INTO `browser` VALUES ('Safari',11);
+
+INSERT INTO `imageCollection` VALUES (1,'catalog','Artículo',3840,2160,'Item','image','vn','item','image',1,75);
+INSERT INTO `imageCollection` VALUES (4,'link','Enlace',200,200,'Link','image','hedera','link','image',1,9);
+INSERT INTO `imageCollection` VALUES (5,'news','Noticias',800,1200,'New','image','hedera','news','image',1,9);
+INSERT INTO `imageCollection` VALUES (6,'user','Usuario',800,1200,'VnUser','image','account','user','image',1,74);
+
+INSERT INTO `imageCollectionSize` VALUES (2,1,50,50,1);
+INSERT INTO `imageCollectionSize` VALUES (3,1,200,200,1);
+INSERT INTO `imageCollectionSize` VALUES (5,5,200,200,1);
+INSERT INTO `imageCollectionSize` VALUES (6,1,70,70,1);
+INSERT INTO `imageCollectionSize` VALUES (8,5,50,50,1);
+INSERT INTO `imageCollectionSize` VALUES (9,1,1600,900,0);
+INSERT INTO `imageCollectionSize` VALUES (13,6,160,160,1);
+INSERT INTO `imageCollectionSize` VALUES (14,6,520,520,1);
+INSERT INTO `imageCollectionSize` VALUES (15,6,1600,1600,1);
+INSERT INTO `imageCollectionSize` VALUES (16,1,500,500,1);
+
+INSERT INTO `language` VALUES ('ca','Català','Catalan',1);
+INSERT INTO `language` VALUES ('en','English','English',1);
+INSERT INTO `language` VALUES ('es','Español','Spanish',1);
+INSERT INTO `language` VALUES ('fr','Français','French',1);
+INSERT INTO `language` VALUES ('mn','Португалий','Mongolian',1);
+INSERT INTO `language` VALUES ('pt','Português','Portuguese',1);
+
+INSERT INTO `link` VALUES (16,'Printing server','Manage the CUPS printing server','http://printnatura.verdnatura.es','printer');
+INSERT INTO `link` VALUES (20,'Webmail','Verdnatura webmail','https://webmail.verdnatura.es/','mail');
+INSERT INTO `link` VALUES (23,'Verdnatura Beta','Trial version of the web page','https://test-shop.verdnatura.es/','vn');
+INSERT INTO `link` VALUES (25,'Shared folder','Shared folder','https://cdn.verdnatura.es/share','backup');
+INSERT INTO `link` VALUES (29,'phpMyAdmin','Manage MySQL database','https://pma.verdnatura.es/','pma');
+INSERT INTO `link` VALUES (30,'Nagios','Monitoring system','https://nagios.verdnatura.es/','nagios');
+INSERT INTO `link` VALUES (33,'Gitea','Version control system','https://gitea.verdnatura.es/','git');
+INSERT INTO `link` VALUES (34,'Wiknatura','Verdnatura wiki page','https://wiki.verdnatura.es/','wiki');
+INSERT INTO `link` VALUES (35,'phpLDAPadmin','Manage the LDAP database','https://pla.verdnatura.es/','pla');
+INSERT INTO `link` VALUES (36,'Applications','Access applications repository','https://cdn.verdnatura.es/vn-access','access');
+INSERT INTO `link` VALUES (37,'Jenkins','CI and CD system','https://jenkins.verdnatura.es','jenkins');
+INSERT INTO `link` VALUES (38,'osTicket','User service center','https://cau.verdnatura.es','osticket');
+INSERT INTO `link` VALUES (39,'Redmine','Flexible project management','https://redmine.verdnatura.es','redmine');
+INSERT INTO `link` VALUES (40,'Grafana','Analytics & monitoring solution','https://grafana.verdnatura.es','grafana');
+INSERT INTO `link` VALUES (41,'Rocket.Chat','Communications platform','https://chat.verdnatura.es','rocketchat');
+INSERT INTO `link` VALUES (42,'Salix','ERP software','https://salix.verdnatura.es','salix');
+INSERT INTO `link` VALUES (43,'Docker','Container management','https://docker.verdnatura.es','docker');
+INSERT INTO `link` VALUES (44,'Proxmox','Virtual environment','https://mox.verdnatura.es','proxmox');
+INSERT INTO `link` VALUES (45,'Shinobi','Network video recorder','https://shinobi.verdnatura.es','shinobi');
+INSERT INTO `link` VALUES (46,'DokuWiki','Internal documentation','https://doku.verdnatura.es','dokuwiki');
+
+INSERT INTO `location` VALUES (2,'39.2095886','-0.4173501','Valencia','Calle Fenollar, 2','46680','Algemesi','Valencia','963 242 100','es');
+INSERT INTO `location` VALUES (3,'40.4564969','-3.4875829','Madrid','Avenida de la Constitución, 3 - Nave E','28850','Torrejón de Ardoz','Madrid','963 242 100',NULL);
+INSERT INTO `location` VALUES (4,'41.4962045','2.3765504','Barcelona','Camí del crist, 33','08340','Vilassar de Mar','Barcelona','607 562 391','ca');
+INSERT INTO `location` VALUES (5,'52.2612312','4.7818154','Holland','Aalsmeer Flower Auction','1430 BA','Legmeerdijk 313','Aalsmeer','Nederland','nl');
+INSERT INTO `location` VALUES (6,'43.4375416','5.2261456','Marseille','ruben@verdnatura.es','13054','Marigname','Marseille','+33 781 533 900','fr');
+
+INSERT INTO `menu` VALUES (1,'Home','cms/home',6,NULL,1);
+INSERT INTO `menu` VALUES (2,'Orders',NULL,11,NULL,1);
+INSERT INTO `menu` VALUES (3,'Catalog','ecomerce/catalog',6,NULL,2);
+INSERT INTO `menu` VALUES (7,'Administration',NULL,1,NULL,2);
+INSERT INTO `menu` VALUES (8,'Users','admin/users',1,7,2);
+INSERT INTO `menu` VALUES (9,'Connections','admin/connections',1,7,2);
+INSERT INTO `menu` VALUES (11,'Agencies','agencies/packages',3,NULL,2);
+INSERT INTO `menu` VALUES (12,'News','news/news',1,7,3);
+INSERT INTO `menu` VALUES (15,'Photos','admin/photos',1,7,3);
+INSERT INTO `menu` VALUES (17,'Configuration',NULL,11,NULL,3);
+INSERT INTO `menu` VALUES (19,'Control panel','admin/links',1,7,1);
+INSERT INTO `menu` VALUES (21,'Basket','ecomerce/basket',11,NULL,1);
+INSERT INTO `menu` VALUES (22,'Last orders','ecomerce/orders',11,2,2);
+INSERT INTO `menu` VALUES (23,'Invoices','ecomerce/invoices',11,2,2);
+INSERT INTO `menu` VALUES (24,'Account','account/conf',11,17,1);
+INSERT INTO `menu` VALUES (25,'Addresses','account/address-list',11,17,2);
+INSERT INTO `menu` VALUES (26,'Shelves','reports/shelves',1,29,1);
+INSERT INTO `menu` VALUES (28,'Visits','admin/visits',1,7,2);
+INSERT INTO `menu` VALUES (29,'Reports',NULL,1,NULL,2);
+INSERT INTO `menu` VALUES (30,'Items','admin/items',1,7,3);
+INSERT INTO `menu` VALUES (31,'Pending orders','ecomerce/pending',11,2,1);
+
+INSERT INTO `message` VALUES (1,'ORDER_DATE_HOLIDAY','Orders for holidays are not possible');
+INSERT INTO `message` VALUES (2,'ORDER_EMPTY','The order is empty');
+INSERT INTO `message` VALUES (3,'ORDER_UNAVAILABLE','Some items are no longer available, please check the quantities highlighted in red');
+INSERT INTO `message` VALUES (4,'SURVEY_MAX_ONE_VOTE','Only one vote per survey is possible');
+INSERT INTO `message` VALUES (5,'ORDER_MAX_EXCEEDED','You have exceeded the maximum number of unconfirmed orders, please delete or confirm started orders');
+INSERT INTO `message` VALUES (6,'LOGIN_INCORRECT','Incorrect username or password. Case-sensitive.');
+INSERT INTO `message` VALUES (7,'ORDER_DATE_PAST','The order date must be today or later');
+INSERT INTO `message` VALUES (8,'ORDER_DATE_LAST','No more orders can be made for today, please postpone your order for tomorrow or later');
+INSERT INTO `message` VALUES (9,'ORDER_DATE_SUNDAY','Orders for Sunday cannot be confirmed');
+INSERT INTO `message` VALUES (10,'ORDER_DATE_SATURATED','We are overwhelmed with orders, please select another delivery or pick-up date');
+INSERT INTO `message` VALUES (11,'USER_DISCONNECTED','You have been disconnected from the server, please log in again');
+INSERT INTO `message` VALUES (12,'UNAUTH_ACTION','Action not allowed');
+INSERT INTO `message` VALUES (13,'ORDER_INVALID_AGENCY','The shipping agency is not valid');
+INSERT INTO `message` VALUES (14,'ORDER_EMPTY_ADDRESS','Please select a shipping address');
+INSERT INTO `message` VALUES (15,'ORDER_AMOUNT_ROUNDED','This item is sold in bundles, the quantity has been rounded');
+INSERT INTO `message` VALUES (17,'orderOutdated','The order configuration is incorrect, please reconfigure it to continue shopping');
+INSERT INTO `message` VALUES (18,'orderNotOwnedByUser','The order belongs to another user');
+INSERT INTO `message` VALUES (19,'orderConfirmed','The order has already been confirmed and cannot be modified');
+INSERT INTO `message` VALUES (20,'clientNotVerified','Incomplete tax data, please contact your sales representative');
+INSERT INTO `message` VALUES (21,'quantityLessThanMin','The quantity cannot be less than the minimum');
+
+INSERT INTO `metatag` VALUES (2,'title','Verdnatura Levante SL, mayorista de flores, plantas y complementos para floristería y decoración');
+INSERT INTO `metatag` VALUES (3,'description','Verdnatura Levante SL, mayorista de flores, plantas y complementos para floristería y decoración. Envío a toda España, pedidos por internet o por teléfono.');
+INSERT INTO `metatag` VALUES (4,'keywords','verdnatura, mayorista, floristería, flores, verdes, plantas, ramos, complementos, artificial, natural, decoración, rosas, helecho, fern, clavel, lilium, orquídea, tulipan, crisantemo, cala, gerbera, hiedra, eucaliptus, cinerea, aralia');
+INSERT INTO `metatag` VALUES (6,'revisit-after','15 days');
+INSERT INTO `metatag` VALUES (7,'rating','general');
+INSERT INTO `metatag` VALUES (8,'author','Juan Ferrer Toribio');
+INSERT INTO `metatag` VALUES (9,'owner','Verdnatura Levante S.L.');
+INSERT INTO `metatag` VALUES (10,'robots','index, follow');
+
+INSERT INTO `newsTag` VALUES ('course','Curso');
+INSERT INTO `newsTag` VALUES ('new','Noticia');
+INSERT INTO `newsTag` VALUES ('offer','Oferta');
+
+INSERT INTO `restPriv` VALUES (1,'tpv/transaction',2);
+INSERT INTO `restPriv` VALUES (3,'image/upload',1);
+INSERT INTO `restPriv` VALUES (5,'user/supplant',104);
+INSERT INTO `restPriv` VALUES (10,'misc/captcha',NULL);
+INSERT INTO `restPriv` VALUES (11,'core/log',NULL);
+INSERT INTO `restPriv` VALUES (14,'core/query',NULL);
+INSERT INTO `restPriv` VALUES (15,'user/recover-password',NULL);
+INSERT INTO `restPriv` VALUES (16,'user/restore-password',NULL);
+INSERT INTO `restPriv` VALUES (17,'dms/invoice',2);
+INSERT INTO `restPriv` VALUES (18,'image/thumb',NULL);
+INSERT INTO `restPriv` VALUES (19,'misc/contact',NULL);
+INSERT INTO `restPriv` VALUES (20,'misc/production',NULL);
+INSERT INTO `restPriv` VALUES (21,'tpv/confirm-post',NULL);
+INSERT INTO `restPriv` VALUES (22,'tpv/confirm-soap',NULL);
+INSERT INTO `restPriv` VALUES (23,'client/supplant',18);
+INSERT INTO `restPriv` VALUES (24,'client/supplant',35);
+INSERT INTO `restPriv` VALUES (25,'user/logout',NULL);
+
+INSERT INTO `social` VALUES (1,'Blog','https://blog.verdnatura.es/','blog.svg',0);
+INSERT INTO `social` VALUES (3,'Facebook','http://www.facebook.com/verdnatura','facebook.svg',2);
+INSERT INTO `social` VALUES (4,'YouTube','http://www.youtube.com/user/verdnatura','youtube.svg',2);
+INSERT INTO `social` VALUES (5,'Twitter','https://twitter.com/Verdnatura','twitter.svg',1);
+INSERT INTO `social` VALUES (6,'Instagram','https://www.instagram.com/verdnatura','instagram.svg',2);
+INSERT INTO `social` VALUES (7,'Linkedin','https://www.linkedin.com/company/verdnatura','linkedin.svg',1);
+INSERT INTO `social` VALUES (8,'Pinterest','https://es.pinterest.com/verdnatura/','pinterest.svg',1);
+
+INSERT INTO `tpvError` VALUES ('SIS0007','Error al desmontar el XML de entrada');
+INSERT INTO `tpvError` VALUES ('SIS0008','Error falta Ds_Merchant_MerchantCode');
+INSERT INTO `tpvError` VALUES ('SIS0009','Error de formato en Ds_Merchant_MerchantCode');
+INSERT INTO `tpvError` VALUES ('SIS0010','Error falta Ds_Merchant_Terminal');
+INSERT INTO `tpvError` VALUES ('SIS0011','Error de formato en Ds_Merchant_Terminal');
+INSERT INTO `tpvError` VALUES ('SIS0014','Error de formato en Ds_Merchant_Order');
+INSERT INTO `tpvError` VALUES ('SIS0015','Error falta Ds_Merchant_Currency');
+INSERT INTO `tpvError` VALUES ('SIS0016','Error de formato en Ds_Merchant_Currency');
+INSERT INTO `tpvError` VALUES ('SIS0017','Error no se admite operaciones en pesetas');
+INSERT INTO `tpvError` VALUES ('SIS0018','Error falta Ds_Merchant_Amount');
+INSERT INTO `tpvError` VALUES ('SIS0019','Error de formato en Ds_Merchant_Amount');
+INSERT INTO `tpvError` VALUES ('SIS0020','Error falta Ds_Merchant_MerchantSignature');
+INSERT INTO `tpvError` VALUES ('SIS0021','Error la Ds_Merchant_MerchantSignature viene vacía');
+INSERT INTO `tpvError` VALUES ('SIS0022','Error de formato en Ds_Merchant_TransactionType');
+INSERT INTO `tpvError` VALUES ('SIS0023','Error Ds_Merchant_TransactionType desconocido');
+INSERT INTO `tpvError` VALUES ('SIS0024','Error Ds_Merchant_ConsumerLanguage tiene más de 3 posiciones');
+INSERT INTO `tpvError` VALUES ('SIS0026','Error No existe el comercio / terminal enviado');
+INSERT INTO `tpvError` VALUES ('SIS0027','Error Moneda enviada por el comercio es diferente a la que tiene asignada para ese terminal');
+INSERT INTO `tpvError` VALUES ('SIS0028','Error Comercio / terminal está dado de baja');
+INSERT INTO `tpvError` VALUES ('SIS0030','Error en un pago con tarjeta ha llegado un tipo de operación no valido');
+INSERT INTO `tpvError` VALUES ('SIS0031','Método de pago no definido');
+INSERT INTO `tpvError` VALUES ('SIS0034','Error de acceso a la Base de Datos');
+INSERT INTO `tpvError` VALUES ('SIS0038','Error en java');
+INSERT INTO `tpvError` VALUES ('SIS0040','Error el comercio / terminal no tiene ningún método de pago asignado');
+INSERT INTO `tpvError` VALUES ('SIS0041','Error en el cálculo de la firma de datos del comercio');
+INSERT INTO `tpvError` VALUES ('SIS0042','La firma enviada no es correcta');
+INSERT INTO `tpvError` VALUES ('SIS0046','El BIN de la tarjeta no está dado de alta');
+INSERT INTO `tpvError` VALUES ('SIS0051','Error número de pedido repetido');
+INSERT INTO `tpvError` VALUES ('SIS0054','Error no existe operación sobre la que realizar la devolución');
+INSERT INTO `tpvError` VALUES ('SIS0055','Error no existe más de un pago con el mismo número de pedido');
+INSERT INTO `tpvError` VALUES ('SIS0056','La operación sobre la que se desea devolver no está autorizada');
+INSERT INTO `tpvError` VALUES ('SIS0057','El importe a devolver supera el permitido');
+INSERT INTO `tpvError` VALUES ('SIS0058','Inconsistencia de datos, en la validación de una confirmación');
+INSERT INTO `tpvError` VALUES ('SIS0059','Error no existe operación sobre la que realizar la devolución');
+INSERT INTO `tpvError` VALUES ('SIS0060','Ya existe una confirmación asociada a la preautorización');
+INSERT INTO `tpvError` VALUES ('SIS0061','La preautorización sobre la que se desea confirmar no está autorizada');
+INSERT INTO `tpvError` VALUES ('SIS0062','El importe a confirmar supera el permitido');
+INSERT INTO `tpvError` VALUES ('SIS0063','Error. Número de tarjeta no disponible');
+INSERT INTO `tpvError` VALUES ('SIS0064','Error. El número de tarjeta no puede tener más de 19 posiciones');
+INSERT INTO `tpvError` VALUES ('SIS0065','Error. El número de tarjeta no es numérico');
+INSERT INTO `tpvError` VALUES ('SIS0066','Error. Mes de caducidad no disponible');
+INSERT INTO `tpvError` VALUES ('SIS0067','Error. El mes de la caducidad no es numérico');
+INSERT INTO `tpvError` VALUES ('SIS0068','Error. El mes de la caducidad no es válido');
+INSERT INTO `tpvError` VALUES ('SIS0069','Error. Año de caducidad no disponible');
+INSERT INTO `tpvError` VALUES ('SIS0070','Error. El Año de la caducidad no es numérico');
+INSERT INTO `tpvError` VALUES ('SIS0071','Tarjeta caducada');
+INSERT INTO `tpvError` VALUES ('SIS0072','Operación no anulable');
+INSERT INTO `tpvError` VALUES ('SIS0074','Error falta Ds_Merchant_Order');
+INSERT INTO `tpvError` VALUES ('SIS0075','Error el Ds_Merchant_Order tiene menos de 4 posiciones o más de 12');
+INSERT INTO `tpvError` VALUES ('SIS0076','Error el Ds_Merchant_Order no tiene las cuatro primeras posiciones numéricas');
+INSERT INTO `tpvError` VALUES ('SIS0078','Método de pago no disponible');
+INSERT INTO `tpvError` VALUES ('SIS0079','Error al realizar el pago con tarjeta');
+INSERT INTO `tpvError` VALUES ('SIS0081','La sesión es nueva, se han perdido los datos almacenados');
+INSERT INTO `tpvError` VALUES ('SIS0089','El valor de Ds_Merchant_ExpiryDate no ocupa 4 posiciones');
+INSERT INTO `tpvError` VALUES ('SIS0092','El valor de Ds_Merchant_ExpiryDate es nulo');
+INSERT INTO `tpvError` VALUES ('SIS0093','Tarjeta no encontrada en la tabla de rangos');
+INSERT INTO `tpvError` VALUES ('SIS0112','Error. El tipo de transacción especificado en Ds_Merchant_Transaction_Type no esta permitido');
+INSERT INTO `tpvError` VALUES ('SIS0115','Error no existe operación sobre la que realizar el pago de la cuota');
+INSERT INTO `tpvError` VALUES ('SIS0116','La operación sobre la que se desea pagar una cuota no es una operación válida');
+INSERT INTO `tpvError` VALUES ('SIS0117','La operación sobre la que se desea pagar una cuota no está autorizada');
+INSERT INTO `tpvError` VALUES ('SIS0118','Se ha excedido el importe total de las cuotas');
+INSERT INTO `tpvError` VALUES ('SIS0119','Valor del campo Ds_Merchant_DateFrecuency no válido');
+INSERT INTO `tpvError` VALUES ('SIS0120','Valor del campo Ds_Merchant_CargeExpiryDate no válido');
+INSERT INTO `tpvError` VALUES ('SIS0121','Valor del campo Ds_Merchant_SumTotal no válido');
+INSERT INTO `tpvError` VALUES ('SIS0122','Valor del campo Ds_merchant_DateFrecuency o Ds_Merchant_SumTotal tiene formato incorrecto');
+INSERT INTO `tpvError` VALUES ('SIS0123','Se ha excedido la fecha tope para realizar transacciones');
+INSERT INTO `tpvError` VALUES ('SIS0124','No ha transcurrido la frecuencia mínima en un pago recurrente sucesivo');
+INSERT INTO `tpvError` VALUES ('SIS0132','La fecha de Confirmación de Autorización no puede superar en más de 7 días a la de Preautorización');
+INSERT INTO `tpvError` VALUES ('SIS0139','Error el pago recurrente inicial está duplicado SIS0142 Tiempo excedido para el pago');
+INSERT INTO `tpvError` VALUES ('SIS0216','Error Ds_Merchant_CVV2 tiene mas de 3/4 posiciones');
+INSERT INTO `tpvError` VALUES ('SIS0217','Error de formato en Ds_Merchant_CVV2');
+INSERT INTO `tpvError` VALUES ('SIS0221','Error el CVV2 es obligatorio');
+INSERT INTO `tpvError` VALUES ('SIS0222','Ya existe una anulación asociada a la preautorización');
+INSERT INTO `tpvError` VALUES ('SIS0223','La preautorización que se desea anular no está autorizada');
+INSERT INTO `tpvError` VALUES ('SIS0225','Error no existe operación sobre la que realizar la anulación');
+INSERT INTO `tpvError` VALUES ('SIS0226','Inconsistencia de datos, en la validación de una anulación');
+INSERT INTO `tpvError` VALUES ('SIS0227','Valor del campo Ds_Merchan_TransactionDate no válido');
+INSERT INTO `tpvError` VALUES ('SIS0252','El comercio no permite el envío de tarjeta');
+INSERT INTO `tpvError` VALUES ('SIS0253','La tarjeta no cumple el check-digit');
+INSERT INTO `tpvError` VALUES ('SIS0261','Operación detenida por superar el control de restricciones en la entrada al SIS');
+INSERT INTO `tpvError` VALUES ('SIS0274','Tipo de operación desconocida o no permitida por esta entrada al SIS');
+INSERT INTO `tpvError` VALUES ('SIS9915','A petición del usuario se ha cancelado el pago');
+
+INSERT INTO `tpvResponse` VALUES (101,'Tarjeta Caducada');
+INSERT INTO `tpvResponse` VALUES (102,'Tarjeta en excepción transitoria o bajo sospecha de fraude');
+INSERT INTO `tpvResponse` VALUES (104,'Operación no permitida para esa tarjeta o terminal');
+INSERT INTO `tpvResponse` VALUES (106,'Intentos de PIN excedidos');
+INSERT INTO `tpvResponse` VALUES (116,'Disponible Insuficiente');
+INSERT INTO `tpvResponse` VALUES (118,'Tarjeta no Registrada');
+INSERT INTO `tpvResponse` VALUES (125,'Tarjeta no efectiva');
+INSERT INTO `tpvResponse` VALUES (129,'Código de seguridad (CVV2/CVC2) incorrecto');
+INSERT INTO `tpvResponse` VALUES (180,'Tarjeta ajena al servicio');
+INSERT INTO `tpvResponse` VALUES (184,'Error en la autenticación del titular');
+INSERT INTO `tpvResponse` VALUES (190,'Denegación sin especificar motivo');
+INSERT INTO `tpvResponse` VALUES (191,'Fecha de caducidad errónea');
+INSERT INTO `tpvResponse` VALUES (202,'Tarjeta en excepción transitoria o bajo sospecha de fraude con retirada de tarjeta');
+INSERT INTO `tpvResponse` VALUES (904,'Comercio no registrado en FUC');
+INSERT INTO `tpvResponse` VALUES (909,'Error de sistema');
+INSERT INTO `tpvResponse` VALUES (912,'Emisor no Disponible');
+INSERT INTO `tpvResponse` VALUES (913,'Pedido repetido');
+INSERT INTO `tpvResponse` VALUES (944,'Sesión Incorrecta');
+INSERT INTO `tpvResponse` VALUES (950,'Operación de devolución no permitida');
+INSERT INTO `tpvResponse` VALUES (9064,'Número de posiciones de la tarjeta incorrecto');
+INSERT INTO `tpvResponse` VALUES (9078,'No existe método de pago válido para esa tarjeta');
+INSERT INTO `tpvResponse` VALUES (9093,'Tarjeta no existente');
+INSERT INTO `tpvResponse` VALUES (9094,'Rechazo servidores internacionales');
+INSERT INTO `tpvResponse` VALUES (9104,'A petición del usuario se ha cancelado el pago');
+INSERT INTO `tpvResponse` VALUES (9218,'El comercio no permite op. seguras por entrada /operaciones');
+INSERT INTO `tpvResponse` VALUES (9253,'Tarjeta no cumple el check-digit');
+INSERT INTO `tpvResponse` VALUES (9256,'El comercio no puede realizar preautorizaciones');
+INSERT INTO `tpvResponse` VALUES (9257,'Esta tarjeta no permite operativa de preautorizaciones');
+INSERT INTO `tpvResponse` VALUES (9261,'Operación detenida por superar el control de restricciones en la entrada al SIS');
+INSERT INTO `tpvResponse` VALUES (9912,'Emisor no Disponible');
+INSERT INTO `tpvResponse` VALUES (9913,'Error en la confirmación que el comercio envía al TPV Virtual (solo aplicable en la opción de sincronización SOAP)');
+INSERT INTO `tpvResponse` VALUES (9914,'Confirmación “KO” del comercio (solo aplicable en la opción de sincronización SOAP)');
+INSERT INTO `tpvResponse` VALUES (9915,'A petición del usuario se ha cancelado el pago');
+INSERT INTO `tpvResponse` VALUES (9928,'Anulación de autorización en diferido realizada por el SIS (proceso batch)');
+INSERT INTO `tpvResponse` VALUES (9929,'Anulación de autorización en diferido realizada por el comercio');
+INSERT INTO `tpvResponse` VALUES (9998,'Operación en proceso de solicitud de datos de tarjeta');
+INSERT INTO `tpvResponse` VALUES (9999,'Operación que ha sido redirigida al emisora autenticar');
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
+USE `sage`;
+/*!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 */;
+
+INSERT INTO `TiposIva` VALUES (2,0,'Operaciones no sujetas',0.0000000000,0.0000000000,0.0000000000,'','4770000020','','','','','','','95B21A93-5910-489D-83BB-C32788C9B19D','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (4,0,'I.V.A. 4%',0.0000000000,4.0000000000,0.0000000000,'4720000004','4770000004','','6310000000','','','','','9E6160D5-984E-4643-ACBC-1EBC3BF73360','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (5,0,'I.V.A. 4% y R.E. 0.5%',0.0000000000,4.0000000000,0.5000000000,'','4770000504','4770000405','','','','','','DBEFA562-63FB-4FFC-8171-64F0C6F065FF','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (6,0,'H.P. IVA 4% CEE',0.0000000000,4.0000000000,0.0000000000,'4721000004','4771000004','','','','','','','DD0ECBA8-2EF5-425E-911B-623580BADA77','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (7,0,'H.P. IVA 10% CEE',0.0000000000,10.0000000000,0.0000000000,'4721000011','4771000010','','','','','','','593208CD-6F28-4489-B6EC-907AD689EAC9','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (8,0,'H.P. IVA 21% CEE',0.0000000000,21.0000000000,0.0000000000,'4721000021','4771000021','','','','','','','27061852-9BC1-4C4F-9B6E-69970E208F23','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (10,0,'I.V.A. 10% Nacional',0.0000000000,10.0000000000,0.0000000000,'4720000011','4770000010','','6290000553','','','','','828A9D6F-5C01-4C3A-918A-B2E4482830D3','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (11,0,'I.V.A. 10% y R.E. 1,4%',0.0000000000,10.0000000000,1.4000000000,'','4770000101','4770000110','','','','','','C1F2D910-83A1-4191-A76C-8B3D7AB98348','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (16,0,'I.V.A. Adqui. servicios CEE',0.0000000000,21.0000000000,0.0000000000,'4721000015','4771000016','','','','','','','E3EDE961-CE8F-41D4-9E6C-D8BCD32275A1','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (18,0,'H.P. Iva Importación 0% ISP',0.0000000000,0.0000000000,0.0000000000,'4720000005','4770000005','','','','','','','27AD4158-2349-49C2-B53A-A4E0EFAC5D09','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (20,0,'I.V.A 0% Nacional',0.0000000000,0.0000000000,0.0000000000,'4720000000','','','','','','','','B90B0FBD-E513-4F04-9721-C873504E08DF','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (21,0,'I.V.A. 21%',0.0000000000,21.0000000000,0.0000000000,'4720000021','4770000021','4770000000','','','','','','BA8C4E28-DCFA-4F7B-AE4F-CA044626B55E','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (22,0,'IVA 10% importaciones',0.0000000000,10.0000000000,0.0000000000,'4722000010','','','','','','','','540450A8-4B41-4607-96D1-E7F296FB6933','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (26,0,'I.V.A. 21% y R.E. 5,2%',0.0000000000,21.0000000000,5.2000000000,'4720000021','4770000215','4770000521','631000000','','','','','2BC0765F-7739-49AE-A5F0-28B648B81677','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (90,0,'IVA 21% importaciones',0.0000000000,21.0000000000,0.0000000000,'4722000021','','','','','','','','EB675F91-5FF2-4E26-A31E-EEB674125945','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (91,0,'IVA 0% importaciones',0.0000000000,0.0000000000,0.0000000000,'4723000000','','','','','','','','5E5EFA56-2A99-4D54-A16B-5D818274CA18','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (92,0,'8.5% comp. ganadera o pesquera',0.0000000000,8.5000000000,0.0000000000,'4720000000','4770000000','477000000','631000000','','','','','','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (93,0,'12% com. agrícola o forestal',0.0000000000,12.0000000000,0.0000000000,'4720000012','','','','','','','','267B1DDB-247F-4A71-AB95-3349FEFC5F92','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (94,0,'10,5% com. ganadera o pesquera',0.0000000000,10.5000000000,0.0000000000,'4770000000','4720000000','631000000','477000000','','','','','','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (100,0,'HP IVA SOPORTADO 5%',0.0000000000,5.0000000000,0.0000000000,'4720000055','','','','','','','','3AD36CB2-4172-4CC9-9F87-2BF2B56AAC80','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (108,0,'I.V.A. 8%',0.0000000000,8.0000000000,0.0000000000,'4720000000','4770000000','477000000','631000000','','','','','','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (109,0,'I.V.A. 8% y R.E. 1%',0.0000000000,8.0000000000,1.0000000000,'4720000000','4770000000','477000000','631000000','','','','','','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (110,0,'HP IVA Devengado Exento CEE',0.0000000000,0.0000000000,0.0000000000,'','4771000000','','','','','','','C605BC32-E161-42FD-83F3-3A66B1FBE399','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (111,0,'H.P. Iva Devengado Exento Ser',0.0000000000,0.0000000000,0.0000000000,'','4771000001','','','','','','','F1AEC4DC-AFE5-498E-A713-2648FFB6DA32','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (112,0,'H.P. IVA Devengado en exportac',0.0000000000,0.0000000000,0.0000000000,'','4770000002','','','','','','','F980AE74-BF75-4F4C-927F-0CCCE0DB8D15','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (113,0,'HP DEVENGADO 21 ISP ',0.0000000000,21.0000000000,0.0000000000,'4720000006','4770000006','','','','','','','728D7A76-E936-438C-AF05-3CA38FE16EA5','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (114,0,'HP.IVA NO DEDUCIBLE 10%',0.0000000000,0.0000000000,0.0000000000,'4720000026','','','','','','','','','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (115,0,'H.P. IVA Soportado Impor 4% ',0.0000000000,4.0000000000,0.0000000000,'4722000004','','','','','','','','','','','','','','','','','',0);
+
+INSERT INTO `TiposTransacciones` VALUES (1,'Rég.general/Oper.interiores bienes y serv.corrien.','',0,'');
+INSERT INTO `TiposTransacciones` VALUES (2,'Régimen especial de bienes usados','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (3,'Régimen especial de obj. de arte y antigüedades','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (4,'Régimen especial agencias de viaje','',0,'');
+INSERT INTO `TiposTransacciones` VALUES (5,'Régimen especial determinación proporcional','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (6,'Oper.en rég.simplificado art.37.1.2º Rgto.IVA','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (7,'Oper.en rég.simplificado art.37.1.1º Rgto.IVA','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (8,'Oper.en rég.de agricultura, ganadería y pesca','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (9,'Oper.en rég.especial de recargo de equivalencia','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (10,'Entregas intracomunitarias','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (11,'Entregas intermediarias intracomunitarias','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (12,'Operaciones sujetas con derecho a devolución','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (13,'Prest. Serv. No sujetas derecho devolución','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (14,'Exportaciones definitivas','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (15,'Envíos definitivos a Canarias, Ceuta y Melilla','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (16,'Devoluciones en régimen de viajeros','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (17,'Operaciones con áreas exentas','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (18,'Operaciones exentas con derecho a deducción','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (19,'Operaciones exentas sin derecho a deducción','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (20,'Adquisic.intracomunitarias de bienes y serv.corr.','',-1,'P');
+INSERT INTO `TiposTransacciones` VALUES (21,'Adquisic.intracomunitarias de bienes de inversión','',-1,'P');
+INSERT INTO `TiposTransacciones` VALUES (22,'Adquisic.intermediarias intracomunitarias','',-1,'P');
+INSERT INTO `TiposTransacciones` VALUES (23,'Modif.autorizadas en quiebras y susp.de pagos','',0,'');
+INSERT INTO `TiposTransacciones` VALUES (24,'Entrega de bienes inmuebles no habituales','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (25,'Entrega de bienes de inversión','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (26,'Op.finan. y Entregas oro inversión, no habituales','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (27,'Inversión sujeto pasivo','',-1,'I');
+INSERT INTO `TiposTransacciones` VALUES (28,'Prestaciones intracomunitarias de servicios','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (29,'Adquisiciones intracomunitarias de servicios','',-1,'I');
+INSERT INTO `TiposTransacciones` VALUES (30,'Operaciones interiores de bienes de inversión','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (31,'Importaciones de bienes y servicios corrientes','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (32,'Importaciones de bienes de inversión','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (33,'Operaciones que generan inversión sujeto pasivo','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (35,'Compensaciones en rég.de agricultura, gan.y pesca','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (36,'Regularización de inversiones','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (37,'Operaciones exentas','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (38,'Operaciones no sujetas','',0,'');
+INSERT INTO `TiposTransacciones` VALUES (39,'Gastos devengados op interiores (País Vasco)','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (40,'Gastos Adq.intracom. bienes (País Vasco)','',-1,'P');
+INSERT INTO `TiposTransacciones` VALUES (42,'Gastos Adq.intermediarias intracom. (País Vasco)','',-1,'P');
+INSERT INTO `TiposTransacciones` VALUES (47,'Gastos Inversión sujeto pasivo (País Vasco)','',-1,'I');
+INSERT INTO `TiposTransacciones` VALUES (49,'Gastos Adq. intracom. servicios (País Vasco)','',-1,'I');
+INSERT INTO `TiposTransacciones` VALUES (51,'Gastos Importaciones (País Vasco)','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (53,'Adquisiciones a agencias de viajes en rég.especial','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (54,'Entregas intrac.posteriores a importaciones','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (55,'Entregas intrac.post.impor.con representante','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (56,'Import. bienes y serv. corrientes pdte. liquidar','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (57,'Import. bienes de inversión pdte. liquidar','R',0,'');
+INSERT INTO `TiposTransacciones` VALUES (58,'Servicios prestados por Internet desde España','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (59,'Servicios prestados por Internet fuera de España','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (60,'Régimen depósito distinto al aduanero','',0,'');
+INSERT INTO `TiposTransacciones` VALUES (61,'Adquisición de bienes de inversión con ISP','',-1,'I');
+INSERT INTO `TiposTransacciones` VALUES (62,'Prest. Serv. Interiores clientes comunit./extranj.','',0,'');
+INSERT INTO `TiposTransacciones` VALUES (63,'Prest. Serv. Ex. con derecho a deducc. comu./extr.','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (64,'Prest. Serv. Ex. sin derecho a deducc. comu./extr.','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (65,'Entregas No sujetas derecho devolución','E',0,'');
+INSERT INTO `TiposTransacciones` VALUES (66,'Operaciones exentas art. 25 ley 19/1994 (Canarias)','',0,'');
+INSERT INTO `TiposTransacciones` VALUES (67,'Entrega de bienes exenta \"Zona Especial Canaria\"','',0,'');
+INSERT INTO `TiposTransacciones` VALUES (68,'Prestac. servicios exenta \"Zona Especial Canaria\"','',0,'');
+
+INSERT INTO `TiposRetencion` VALUES (1,'RETENCION ESTIMACION OBJETIVA',1.0000000000,'4730000000','4751000000',NULL,NULL,NULL,'03811652-0F3A-44A1-AE1C-B19624525D7F');
+INSERT INTO `TiposRetencion` VALUES (2,'ACTIVIDADES AGRICOLAS O GANADERAS',2.0000000000,'4730000000','4751000000',NULL,NULL,NULL,'F3F91EF3-FED6-444D-B03C-75B639D13FB4');
+INSERT INTO `TiposRetencion` VALUES (9,'ACTIVIDADES PROFESIONALES 2 PRIMEROS AÑOS',9.0000000000,'4730000000','4751000000',NULL,NULL,NULL,'73F95642-E951-4C91-970A-60C503A4792B');
+INSERT INTO `TiposRetencion` VALUES (15,'ACTIVIDADES PROFESIONALES',15.0000000000,'4730000000','4751000000','6',NULL,NULL,'F6BDE0EE-3B01-4023-8FFF-A73AE9AC50D7');
+INSERT INTO `TiposRetencion` VALUES (19,'ARRENDAMIENTO Y SUBARRENDAMIENTO',19.0000000000,'4730000000','4751000000','8',NULL,NULL,'09B033AE-16E5-4057-8D4A-A7710C8A4FB9');
+
+INSERT INTO `taxType` VALUES (2,'nonTaxable',0);
+INSERT INTO `taxType` VALUES (4,'national4',0);
+INSERT INTO `taxType` VALUES (5,NULL,0);
+INSERT INTO `taxType` VALUES (6,NULL,1);
+INSERT INTO `taxType` VALUES (7,NULL,1);
+INSERT INTO `taxType` VALUES (8,NULL,1);
+INSERT INTO `taxType` VALUES (10,'national10',0);
+INSERT INTO `taxType` VALUES (11,NULL,0);
+INSERT INTO `taxType` VALUES (16,'CEEServices21',1);
+INSERT INTO `taxType` VALUES (18,NULL,0);
+INSERT INTO `taxType` VALUES (20,'national0',0);
+INSERT INTO `taxType` VALUES (21,'national21',0);
+INSERT INTO `taxType` VALUES (22,'import10',0);
+INSERT INTO `taxType` VALUES (26,NULL,0);
+INSERT INTO `taxType` VALUES (90,'import21',0);
+INSERT INTO `taxType` VALUES (91,NULL,0);
+INSERT INTO `taxType` VALUES (92,NULL,0);
+INSERT INTO `taxType` VALUES (93,NULL,0);
+INSERT INTO `taxType` VALUES (94,NULL,0);
+INSERT INTO `taxType` VALUES (100,NULL,0);
+INSERT INTO `taxType` VALUES (108,NULL,0);
+INSERT INTO `taxType` VALUES (109,NULL,0);
+INSERT INTO `taxType` VALUES (110,NULL,1);
+INSERT INTO `taxType` VALUES (111,NULL,0);
+INSERT INTO `taxType` VALUES (112,NULL,0);
+INSERT INTO `taxType` VALUES (113,'ISP21',0);
+INSERT INTO `taxType` VALUES (114,NULL,0);
+INSERT INTO `taxType` VALUES (115,'import4',0);
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql
new file mode 100644
index 000000000..3aea52588
--- /dev/null
+++ b/db/dump/.dump/privileges.sql
@@ -0,0 +1,2091 @@
+USE `mysql`;
+/*!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 */;
+
+/*!40000 ALTER TABLE `db` DISABLE KEYS */;
+INSERT IGNORE INTO `db` VALUES ('','tmp','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','postgresql','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','util','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vn2008','android','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','tmp','android','Y','Y','Y','Y','N','Y','N','N','N','N','Y','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','cache','salix','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','hedera','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','nst','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','postgresql','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','hedera','android','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','android','android','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','sage','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','pbx','android','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vn','android','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','cache','android','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vn2008','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','bi','android','Y','Y','Y','Y','N','Y','N','N','N','N','Y','Y','N','Y','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vn2008','hedera-web','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','srt','android','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','psico','android','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','account','android','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','edi','hedera-web','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','stock','hedera-web','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','hedera','hedera-web','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','salix','hedera-web','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','account','hedera-web','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','edi','android','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','util','hedera-web','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vn','hedera-web','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','Consumos','android','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vncontrol','android','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','salix','salix','Y','Y','Y','Y','Y','Y','N','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','N');
+INSERT IGNORE INTO `db` VALUES ('','vn','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','Y','N','N');
+INSERT IGNORE INTO `db` VALUES ('','pbx','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','edi','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','bs','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','managedesktop','salix','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','account','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','Y','N','N');
+INSERT IGNORE INTO `db` VALUES ('','mysql','salix','Y','N','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','psico','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','geo','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','tmp','guest','Y','Y','Y','Y','N','Y','N','N','N','N','Y','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','util','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','dipole','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','bi','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','sage','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','bs','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','util','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','stock','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','salix','sysadmin','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','pbx','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','.mysqlworkbench','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','hedera','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','account','sysadmin','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','cache','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vn2008','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vn','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','srt','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','sage','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','srt','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','psico','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','postgresql','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','edi','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vn2008','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','vn','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','edi','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','dipole','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','cache','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','bs','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','bi','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','util','grafana','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','mysql','developerBoss','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','rfid','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
+/*!40000 ALTER TABLE `db` ENABLE KEYS */;
+
+/*!40000 ALTER TABLE `tables_priv` DISABLE KEYS */;
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','itemTypeL10n','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','country','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','itemType','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myAddress','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','Insert,Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','visitUser','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','producer','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','tagL10n','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','config','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','originL10n','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','origin','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','entryEditor','entry','guillermo@10.5.1.4','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','social','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','image','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','guest','tblContadores','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','logistic','item_track','alexm@db-proxy2.static.verdnatura.es','2022-08-03 23:44:43','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','administrative','value','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','administrative','type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','value','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developerBoss','general_log','juan@10.5.1.1','0000-00-00 00:00:00','Select,Drop','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','dipole','employee','expedition_PrintOut','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','logistic','marketPlace','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','definitivo','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','manager','item_group','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','administrative','item_feature','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','item_feature','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','itemTag','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','itemCategoryL10n','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financialBoss','credit','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','guest','Tipos','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','producer','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','mdbVersion','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','province','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','mistakeType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','warehouse','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','account','itemTaxCountry','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','province','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myTpvTransaction','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myTicketState','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myTicketRow','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myTicket','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myOrderTicket','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myOrderRow','juan@db-proxy2.static.verdnatura.es','2022-08-03 23:44:43','Select,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myOrder','juan@db-proxy2.static.verdnatura.es','2022-08-03 23:44:43','Select,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myInvoice','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myClient','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myBasketItem','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myBasketDefaults','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','account','userPassword','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','mainAccountBank','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','itemCategory','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','psico','hr','answer','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ticketDms','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','employee','ekt','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','sage','administrative','taxType','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','psico','hr','fellow','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','address_type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','user','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','userPassword','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','roleRole','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','roleInherit','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','role','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','mailConfig','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','mailAliasAccount','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','mailAlias','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','accountConfig','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','employee','account','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','tpvMerchant','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','account','myUser','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','language','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','imageConfig','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','guest','Paises','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','guest','Tintas','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','item','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','agencyMode','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','inkL10n','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','ink','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','deliveryMethod','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','guest','reinos','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','collectionHotbed','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','hr','mailForward','juan@db-proxy1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','location','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','hr','mailAliasAccount','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','tag','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','news','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k012','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','buy_edi_k012','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','myMenu','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','myBasket','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','message','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','guest','myUser','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','guest','myRole','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','employee','followme','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','hr','account','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','salix','android','AccessToken','jenkins@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerBoss','itemTag','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','itemTag','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','buy_edi_k03','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','psico','hr','examQuestion','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','psico','hr','exam','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','manager','exchange','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','employee','supplier','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','dipole','employee','printer','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','manager','item_groupToOffer','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','dipole','coolerAssist','expedition_PrintOut','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','logistic','putOrder','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','logistic','supplyResponse','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','collectionWagonTicket','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','employee','blacklist','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','employee','cdr','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','employee','queue','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','employee','queueMember','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','employee','queuePhone','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','employee','schedule','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','employee','sip','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','browser','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','config','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','order','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select,Insert,Update,Delete','References');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','orderRowComponent','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','imageCollection','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','orderRow','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','link','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','shelf','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','shelfConfig','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','order_row','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','order_component','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','visitAccess','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','visitAgent','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','visit','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','userSession','z-developer@172.16.255.16','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','collectionWagon','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','marketing','news','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','newsTag','z-developer@www1.static.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','sage','employee','TiposIva','z-sysadmin@172.16.255.30','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','sage','employee','TiposRetencion','z-sysadmin@172.16.255.30','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','sage','employee','TiposTransacciones','z-sysadmin@172.16.255.30','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','bank_account_type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','salesPerson','item_groupToOffer','carlosap@172.16.5.232','2022-08-03 23:44:43','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','account','myTicketService','root@10.2.3.180','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','sage','administrative','movConta','carlosap@172.16.5.232','2022-08-03 23:44:43','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','mailConfig','jgallego@81.202.38.190','2022-08-03 23:44:43','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financial','account_conciliacion','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','accion_dits','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','config','juan@%','0000-00-00 00:00:00','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','util','account','config','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','transitoryDuaUnified','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','clientDied','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','hr','userPassword','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','hr','roleRole','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','hr','roleInherit','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','hr','role','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','hr','mailConfig','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','hr','mailAlias','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','tables_priv','$itBoss@10.0.2.69','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','event','$itBoss@10.0.2.68','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','proxies_priv','$itBoss@10.0.2.68','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','procs_priv','$itBoss@10.5.1.5','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','db','$itBoss@10.0.2.68','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','columns_priv','$itBoss@10.0.2.68','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','time','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','slow_log','$itBoss@10.0.2.68','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','user','$itBoss@10.0.2.68','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','proc','$itBoss@10.0.2.68','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financial','account_detail','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','account_detail_type','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','entryEditor','Compres','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Agencias','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','awb_component','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','developer','emailUser','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','agencia_descuadre','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','airline','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','airline','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','agency_warehouse','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','salesPerson','inter','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_state','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Articles','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','awb','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_component','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb_component','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_component_template','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb_component_type','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','awb_gestdoc','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb_recibida','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_role','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_unit','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financialBoss','balance_nest_tree','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','deliveryBoss','inter','juan@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Bancos','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','barcodes','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','barcodes','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','buyer','inter','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','employee','inter','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','agency','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','buySource','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','buy_edi','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','buy_edi_k04','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k03','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k04','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesAssistant','Clientes','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','v_empresa','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','v_empresa','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','chanel','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','v_empresa','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Clientes','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','V_edi_item_track','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionPlus','v_botanic_export','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','manager','v_botanic_export','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionPlus','v_Articles_botanical','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Colores','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Clientes','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','recibida_vencimiento','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','jerarquia','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerBusinessAgreement','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','tarifa_componentes','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','tarifa_componentes_series','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','Entradas','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','cl_main','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','cl_main','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','state','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','producer','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','officeBoss','ticket_observation','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Cajas','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','cmrConfig','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','awb_recibida','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','awb','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Compres','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','buy_edi','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','ACL','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Vehiculos_consumo','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','palletizer','cmr','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','Colores','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','state','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Consignatarios','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','artificialBoss','travel','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','price_fixed','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','printQueue','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','preservedBoss','travel','alexm@%','0000-00-00 00:00:00','Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','travel','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Cubos_Retorno','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','Cubos','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerAssistant','itemType','jgallego@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Cubos','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Cubos','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','Cubos_Retorno','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','artificialBoss','state','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','travel','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Bancos_poliza','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','cmr','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','edi_bucket_type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','edi_bucket','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','duaDismissed','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','edi_article','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','edi_bucket','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','edi_bucket_type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','time','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','operator','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','payment','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','edi_supplier','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','edi_supplier','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','travel','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Tramos','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Trabajadores','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','empresa','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','sectorType','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Tintas','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','Movimientos','juan@%','0000-00-00 00:00:00','Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','ticket_observation','juan@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas_dits','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','sale','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Entradas_orden','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','ticket_observation','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_turno','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','entrySource','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Tickets_turno','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Tickets_turno','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','expeditionScan','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Tickets_state','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Tickets','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Entradas','root@localhost','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Entradas','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','Tintas','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','filtros','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_kop','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','flight','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','zones','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','businessReasonEnd','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','businessCalendar','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','budgetNotes','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','specialLabels','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetDms','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budget','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','offerList','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','bookingPlanner','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetInvoiceIn','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','beach','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','business','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Movimientos_revisar','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Movimientos_mark','alexm@%','0000-00-00 00:00:00','Select,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Movimientos_componentes','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Movimientos_componentes','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Movimientos','juan@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','handmadeBoss','Movimientos','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','Movimientos','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Movimientos','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Movimientos','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Monedas','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','calendarHolidays','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','mandato','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financial','mandato','alexm@%','0000-00-00 00:00:00','Select,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','iva_group','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','greugeType','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceInIntrastat','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','greuge','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Intrastat','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Intrastat','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','integra2_province','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Grupos','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','dms','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','continent','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','artificialBoss','Movimientos_componentes','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Movimientos_componentes','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Movimientos_mark','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Movimientos_revisar','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','handmadeBoss','Reservas','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerBoss','bankEntity','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Ordenes','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','awb','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Origen','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','pago','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','awb','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Paises','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','salesAssistant','clientDied','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','payroll_categorias','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','payroll_centros','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','payroll_conceptos','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','Tintas','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','alertLevel','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','bankEntity','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','payroll_employee','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','sale','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','bankEntity','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','agencyMode','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Recibos','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','saleCloned','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','pay_met','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Permisos','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','shelving','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemShelvingStock','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','palletizer','cmrConfig','carlosap@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Proveedores','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','PreciosEspeciales','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','agencia_descuadre','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','price_fixed','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','iva_tipo','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','iva_codigo','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financial','pago','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Proveedores','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Proveedores_cargueras','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Proveedores_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','expedition','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Proveedores_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','recibida','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','recibida','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','adminOfficer','recibida_iva','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','recibida_intrastat','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','recibida_iva','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','recibida_vencimiento','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Recibos','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','officeBoss','bankEntity','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','agency','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','bankEntity','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','versiones','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','reference_rate','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','saleComponent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financial','Remesas','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','Reservas','alexm@%','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','cmr','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Rutas','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','address','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','address','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','accountingType','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemShelvingStock_byWarehouse','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Movimientos','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','Series','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','adminOfficer','Series','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financial','Recibos','alexm@%','0000-00-00 00:00:00','Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','price_fixed','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','accountingConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','buyer','salesByItemTypeDay','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesAssistant','state','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','bufferState','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','coolerAssist','state','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','absenceType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','artificialBoss','Entradas_Auto','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','Vehiculos_consumo','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','tblContadores','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','buyMark','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','calendar','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','calendarHolidays','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claim','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimEnd','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','claimRatio','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Cubos','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','cplusRectificationType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','cplusInvoiceType477','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','duaInvoiceIn','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','country','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','duaInvoiceIn','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financial','mandato_tipo','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','propertyNotes','juan@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','province','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','receipt','jgallego@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','receipt','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','visitUser','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','referenceRate','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','report','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','cache','productionBoss','available','guillermo@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','time','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','role','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','config__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','role','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','comparativeFilterType','guillermo@10.5.1.4','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','comparativeFilter','guillermo@10.5.1.4','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','route','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','company','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','expeditionStateType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','collectionHotbed','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','collectionColors','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','collection','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','cmr_list','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','collection','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','cmr','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','clientYoke','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','mysql','developer','roles_mapping','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketLastState','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionBoss','calendar','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','adminOfficer','pago','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','clientPhoneBook','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','saleGroupDetail','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','clientObservation','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','clientObservation','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','productionConfig','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionBoss','sale','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','packingSite','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionPlus','province','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionPlus','province','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','grafana','sip','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','clientCredit','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','artificialBoss','saleTracking','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','saleTracking','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','saleTracking','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','saleTracking','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','client','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','client','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','saleVolume','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','Proveedores_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','awb_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','Cubos','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','routesMonitor','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','sale','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','sale','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Delete','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','sale','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Delete','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','sale','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','zoneClosure','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','saleComponent','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','saleComponent','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','marketingBoss','saleGoal','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','saleGroup','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','saleGroupDetail','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','account_detail','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_component_type','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','employee','accion','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','volumeConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','currency','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerBoss','tag','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','currency','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','creditClassification','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','creditInsurance','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','currency','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerTimeControl','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','defaulter','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','deliveryMethod','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','deliveryMethod','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','v_compres','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','deviceProductionUser','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','department','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','deviceProductionConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','deviceProduction','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','deviceProduction','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionBoss','absenceType','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','deviceProductionConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','deviceProductionUser','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','disabilityGrade','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','duaInvoiceIn','alexm@%','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','dmsType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','duaEntry','alexm@%','0000-00-00 00:00:00','Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','duaEntry','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','dua','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','duaIntrastat','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','duaInvoiceIn','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','duaTax','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Tickets_turno','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','cl_main','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','agency','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','ektEntryAssign','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionBoss','itemShelving','root@localhost','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','propertyDms','juan@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerTimeControlConfig','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entry','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','businessType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entryLog','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','projectState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entrySplit__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entryType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','projectNotes','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','project','juan@10.5.1.1','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','productionConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','productionConfig','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','creditInsurance','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','cache','productionBoss','visible','guillermo@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','errorProduction__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','invoiceOut','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','coolerAssist','Tickets','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','packingSite','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','accessTokenConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','printQueueArgs','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','printQueue','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','printer','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','expedition','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','sector','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeLocation','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','wks','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entryObservation','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','itemShelvingList','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','cmrConfig','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','expeditionTruck','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','alertLevel','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','expeditionSticker','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','artificialBoss','entryObservation','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','dock','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','expeditionTruck','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','expeditionPallet','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','expense','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','expeditionScan','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','entryObservation','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeGroup','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','floramondoNotOfferDay__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','fuelType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeDMS','alexm@%','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','genericAllocation','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeComponent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppe','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','glsExpedition__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','postCode','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','pgcMaster','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemBarcode','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','host','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticket','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceIn','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','invoiceIn','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','invoiceIn','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','inventoryFailure','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','intrastat','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','inventoryFailure','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','inventoryFailureCause','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','invoiceCorrection','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceCorrectionDataSource','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','invoiceCorrectionType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','invoiceIn','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceInDueDay','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','invoiceInDueDay','alexm@%','0000-00-00 00:00:00','Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','invoiceInIntrastat__','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','invoiceInTax','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceInSage','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','invoiceInTax','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceInTax','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','invoiceOut','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','invoiceOut','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceOutExpense','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','item','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','invoiceOutSerial','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','invoiceOutTax','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','item','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','itemBarcode','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','itemBotanical','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemBotanicalWithGenus','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemCategory','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','pgcEqu','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','pgc','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','itemCost','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','itemConfig','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemConversor__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','itemCost','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','personalProtectionEquipment','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','payMethod','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','payment','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','payDem','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','itemPlacementSupplyList','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemPlacementSupplyList','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','itemPlacementSupply','alexm@%','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemPackingType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemPlacementSupply','alexm@%','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','itemPlacementSupplyList','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemPlacement__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','payDem','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','invoiceOut','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemRepo__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemSearch','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemShelving','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemShelvingLog','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketWeekly','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','itemShelvingLog','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','airport','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemShelvingSale','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','Tickets','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimEnd','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','itemTaxCountry','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workCenter','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','itemTaxCountry','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','itemTaxCountry','alexm@%','0000-00-00 00:00:00','Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','parking','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','packingSiteLog','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','dua','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','packingSite','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','packagingWithoutFreight','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemVerdecora__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','packagingWithFreight','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','packagingGifts','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','packagingConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','packaging','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','packageEquivalentItem','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','packageEquivalent','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','packageChecked','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','packageChecked','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','packageChecked','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','operator','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','operator','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','mail','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','Recibos','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','operator','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','mandate','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','occupationCode','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','observationType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','defaultViewConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','medicalCenter','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','medicalReview','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','noticeSubscription','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','noticeSubscription','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','noticeCategory','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','noticeCategory','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','mrwServiceWeekday','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','mrw','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','mrwService','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppePlan','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','accountingConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','buy','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','buy','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleGoal','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','packingSiteLog','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','Entradas','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','saleComponent','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','arcRead','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','clientProtected','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','invoiceOut','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','dua','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','duaEntry','alexm@%','0000-00-00 00:00:00','Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','expeditionTruck','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','moving','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machineDetail','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machineDms','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','vehicle','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','awb','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machine','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','buy','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_dits','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerTimeControlMail','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','coolerBoss','rotacion','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','PreciosEspeciales','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','movingState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','bufferType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','bufferState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','vehicle','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','buffer','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','bufferGroup','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','lastRFID','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','person__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','config','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','expedition','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','travel','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','itemPicker','buy','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_Auto','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','machine','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financialBoss','referenceCurrent','alexm@%','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','vehicleState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','vehicleEvent','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','cooler','Tintas','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','itemBotanical','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','cooler','Entradas','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','developer','signInLog','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketTracking','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','deviceProductionState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','deviceProductionState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','hr','inter','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','printServerQueue2__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','printServerQueue__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','artificialBoss','buy','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','Movimientos','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','buy','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','receipt','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','producer','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','link','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','link','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','delivery','vehicle','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','employee','upperStickers','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','province','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','XDiario','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','till','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financial','recovery','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','employee','photocell','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','supplyResponse','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','cache','customer','last_buy','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','client','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceInTax','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','workerTeam','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','profile_type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','profile_media','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','recovery','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','employee','buffer','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','professional_category','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','media_type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','media','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','labour_agreement','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','returnBuckets__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','journey','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','income_employee','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','incometype_employee','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hrBoss','income_employee','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','buyer','salesByWeek','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','routeGate__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','calendar_labour_type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','adminBoss','XDiario_ALL','alexm@%','0000-00-00 00:00:00','Select,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','rate','carlosap@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','employee','expeditionState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','salesPerson','clientAnnualConsumption','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','buyer','tarifa_componentes_series','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','buyer','tarifa_componentes','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','productionAssi','rutasBoard','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','logistic','rotacion','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','tarifa_componentes','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','tarifa_componentes_series','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','employee','expeditionLog','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','salesPerson','clientNewBorn','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','saleItemShelving__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesBoss','workerTeam','juan@10.5.1.2','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','employee','expedition','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemShelvingStock','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','saleParking__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','property','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','employee','config','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','vehicleEvent','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','vehicle','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','buyer','lastIndicators','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleComponent','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','itemBotanical','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','item','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','marketingBoss','salesPersonGoal','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hrBoss','journey','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','workerTimeControl','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','currentWorkersStats','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','ticketStateToday','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','shelving','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','shelving','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','shelving','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','supplierAccount','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerBoss','supplierAccount','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','supplierAccount','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','customer','supplier','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','state','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','state','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','stockBuyed','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','stowaway','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','supplier','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','supplierAccount','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','supplierAgencyTerm','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','supplierAgencyTerm','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','supplierExpense','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','marketingBoss','ticketService','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ticketService','jgallego@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','sendingServiceWeekday','jenkins@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','ticketRequest','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','ticketParking','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','taxCode','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','taxArea','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','taxClass','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','taxCode','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','taxCode','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','salesPersonEvolution','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','calendar_employee','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','ticket','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticket','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketCollection','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ticketDocumentation','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketDms','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','ektEntryAssign','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','intrastat','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','supplierAgencyTerm','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','entryConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','franceExpressConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','ticketLog','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketCollection','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','ticketDms','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketObservation','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','ticketPackaging','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketPackaging','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketParking','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketPackingList','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketParking','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketPreviousPreparingList','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ticketRefund','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketRequest','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','ticketService','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','ticketServiceType','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketStateToday','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','employee','claims_ratio','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','greugeType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','time','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketWeekly','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','till','juan@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','account','town','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','time','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerMana','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','defaulters','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','customer','travel','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','train','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','train','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','trainingCenter','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','trainingCourse','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','trainingCourseType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','travel','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','travelClonedWeekly','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','employee','facturacion_media_anual','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','travelObservation','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','bankPolicy','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','travelThermograph','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','tillConfig','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','till','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','till','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','vehicleState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','vehicleInvoiceIn','alexm@%','0000-00-00 00:00:00','Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','vehicleEvent','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','vehicleDms','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','vehicle','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','vehicle','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','vehicle','alexm@%','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Agencias','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','vehicleDms','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketState','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','vehicleInvoiceIn','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financialBoss','vehicleNotes','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','vehicleState','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','volumeConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','ticketTrackingState','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','warehouse','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','role','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workCenter','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientCredit','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','worker','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','workerAppTester','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','propertyGroup','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','worker','alexm@%','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerBusinessType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','workerDepartment','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','workerDepartment','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerDepartment','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerConfig__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','inventoryDiscrepancyDetail','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','sendingConfig','jenkins@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entryConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerIrpf','juan@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerJourney','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerLabour','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','workerMana','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','workerMana','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','ticketPackaging','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','entryConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','officeBoss','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerRelatives','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierPackaging','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerDocument','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceCorrection','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ink','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','zone','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','XDiario','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','XDiario','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','workerTimeControlMail','alexm@%','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerTimeControl','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','financial','Greuge_Evolution','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','officeBoss','Greuge_Evolution','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','claimManager','rotacion','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','sale','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','zonePromo__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','accountingConfig','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','accountingType','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','agencyMode','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','cache','employee','visible','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','productionConfig','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','cache','employee','available','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','logistic','ekt','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','ticketCollection','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientChain','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','VMPSettings','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimResponsible','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','packingSiteLog','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','recibida','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','util','grafana','debug','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','myOrder','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','mdbVersion','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientLog','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','calendar','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','campaign','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketService','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','report','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','buyer','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','defaulter','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','componentType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientManaCache','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceIn','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','deliveryInformation','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','bufferType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','grafana','role','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','supplyOffer','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketStateToday','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','routeComplement','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleVolume','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','component','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','train','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','ticketPalletized','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','autonomy','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','expeditionMistakeType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketParking','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemShelving','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','state','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','taxClass','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','salesByWeek','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceInDueDay','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','sectorProductivity','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','salesByclientSalesPerson','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','marketPlace','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','routeAction','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deviceProduction','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceOut','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','printer','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','mdbBranch','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','workerProductivity','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','config','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','userSession','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','receipt','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','buy','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','calendarHolidays','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','parking','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','role','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','errorLogApp','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','continent','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','lastRFID','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','farmingInvoiceIn','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','agencyMode','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','absenceType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleGroupDetail','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerMistakeType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','mdbVersionTree','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','expeditionTruck','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','routeConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimReason','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','log','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','failureLog','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','clientNewBorn','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','farming','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','order','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','packingSpeed','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','expense','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerLabour','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','orderRow','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','movingLog','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','warehouse','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','sector','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','salesPersonGoal','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','movingState','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimResult','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','routesMonitor','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','expeditionPallet','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','ventas','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','intrastat','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','printQueueArgs','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','grafana','Greuge_Evolution','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','host','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','country','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','waste','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketTracking','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemCategory','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleTracking','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','producer','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','cache','grafana','stock','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','grafana','user','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryMethod','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketCollection','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','lastHourProduction','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','warehouseAlias','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','zoneClosure','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','origin','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','referenceCurrent','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','thermograph','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','dms','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','dmsType','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','greenhouseBoss','property','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketLastState','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','guest','myAddress','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','tag','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemTag','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','handmadeBoss','Tipos','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','saleBuy','carlosap@10.5.1.6','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','orderTicket','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','negativeOrigin','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','route','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemPackingType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','expedition','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','zoneEstimatedDelivery','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','payMethod','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemCost','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','worker','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','travel','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','entry','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','department','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','grafana','rutasBoard','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','address','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerDistributionCategory','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','client','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','zone','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','packingSite','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemTaxCountry','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','workerLabourDataByMonth','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketPackaging','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','bufferFreeLength','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','salesByItemTypeDay','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','collection','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','project','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','inventoryDiscrepancy','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','ektSubAddress','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','item_track','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','putOrder','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','parking','juan@10.5.1.2','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenance','machine','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','calendarType','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','glsExpedition','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','clientType','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','expeditionMistake','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deviceProductionLog','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','integra2Province','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','vehicleState','juan@10.5.1.1','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','machineDetail','juan@10.5.1.1','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','machineDms','juan@10.5.1.1','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerJourney','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','productionError','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','professionalCategory','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','mdbApp','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','glsConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','clientContact','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','collectionVolumetry','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','administrative','item','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerIncome','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerBoss','tagAbbreviation','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','chronopostConfig','jenkins@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','chronopostSenderAddress','jenkins@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','chronopostServiceWeekday','jenkins@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','chronopostExpedition','root@localhost','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','sectorCollection','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','sendingService','jenkins@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','adminOfficer','tickets_gestdoc','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','flight','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','routeAction','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','bankErrorCode','jgallego@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','farming','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','farmingDms','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','farmingNotes','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','farmingInvoiceIn','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionBoss','routesMonitor','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','routeCommission','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','expeditionState','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerBoss','warehouse','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimBeginning','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','invoicing','vehiclePlateRegex','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','businessSchedule','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','clientRisk','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','businessCalendar','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','employee','item','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','vehicleNotes','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','vehicleDms','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','palletizerBoss','expeditionTruck','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','palletizerBoss','zoneEvent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','palletizerBoss','routesMonitor','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','propertyNotes','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','propertyDms','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','payment','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','payment','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','taxType','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','guest','autonomy','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionPlus','autonomy','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','routePalletized','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticBoss','warehouse','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','m3','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','Cajas','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','tagAbbreviation','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemImageQueue','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','marketingBoss','parking','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','sectorCollection','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplier','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','defaulter','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceInTaxBookingAccount','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','business','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','dock','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','item','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','clientAnnualConsumption','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','parking','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','bankEntityConfig','carlosap@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','shelving','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','duaEntry','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','fieldAcl','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','module','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','printConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','url','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','userConfigView','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimRedelivery','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientRisk','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','buyer','sale','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','chain','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','routesMonitor','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','cl_main','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','company','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','routeAction','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','ticket_observation','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','Tickets_turno','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','jerarquia','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','Impresoras','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','autoRadioLogCall','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','autoRadioConfig','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','Recibos','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','Rutas','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','Movimientos','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','state','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','route','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','routeComplement','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','deliveryMethod','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','Tickets','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','expeditionRoute_Monitor','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','expeditionScan','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','expeditionPallet','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','province','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','expeditionTruck','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','v_botanic_export','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','itemCost','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','deliveryAssistant','m3','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','ticketDms','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','time','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','v_Articles_botanical','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','workCenter','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','workerDepartment','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','zoneEvent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bi','deliveryAssistant','rotacion','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','agency','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','agencyMode','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','vehicle','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','vehicleEvent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','postCode','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','town','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claim','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierAccount','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerDepartment','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','pbx','grafana','cdr','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerTimeControlConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerMistake','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','putOrder','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleMistake','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deviceProductionUser','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','contactChannel','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deviceLog','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','vehicle','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','packaging','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','workerProductivityConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','antenna','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','cmr','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','accounting','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','creditClassification','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketLog','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','moving','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimDevelopment','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','expeditionLog','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','bs','grafana','compradores_evolution','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','currency','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimObservation','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','salesPreviousPreparated','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimState','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','company','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','buffer','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','greuge','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','item','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select,Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemShelving','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','negativeOrigin','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','Vehiculos_consumo','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','entryOrder','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','project','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','ink','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','remittance','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','vehicleConsumption','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','vehicleConsumption','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','accountReconciliation','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','accountDetail','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','accountDetail','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','accountDetailType','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','airline','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','airline','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','airport','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','deliveryNote','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','deliveryNoteDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','deliveryNoteState','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','awbComponent','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','awbComponent','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','awbComponent','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','awbComponentTemplate','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','awbComponentType','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','awbComponentType','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','awbDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','awbDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','awbDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','awbDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','awbInvoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','awbInvoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','awbRole','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','awbUnit','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financialBoss','balanceNestTree','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','ektK1','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','administrative','ektK1','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','ektK2','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','administrative','ektK2','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','ektK3','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','administrative','ektK3','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','buyer','ektK4','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','edi','administrative','ektK4','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','dmsStorageBox','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','company','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','warehousePickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','warehousePickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','warehousePickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','warehousePickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','component','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','config','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','componentType','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','machineDms','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','itemShelvingSale','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','tagAbbreviation','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','ticketTracking','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','item','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Update');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','ticketDms','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','agencyExtraCharge','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','sale_freightComponent','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','accounting','jgallego@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','accounting','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','machineDetail','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+/*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */;
+
+/*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */;
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','mailConfig','port','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','mailConfig','secure','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','mailConfig','host','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','employee','user','active','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','employee','user','role','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','employee','user','nickname','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','employee','user','name','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','employee','user','id','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','userSession','created','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','userSession','lastUpdate','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','userSession','userVisitFk','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','order','id','2022-08-03 23:44:43','References');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','config','testRestUri','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','config','restUri','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','config','defaultLang','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','employee','sip','extension','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','employee','config','id','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','employee','sip','user_id','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','tpvMerchant','description','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','tpvMerchant','companyFk','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','tpvMerchant','id','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','account','myUser','nickname','2022-08-03 23:44:43','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','account','myUser','email','2022-08-03 23:44:43','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','account','myUser','lang','2022-08-03 23:44:43','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myAddress','isActive','2022-08-03 23:44:43','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myAddress','id','2022-08-03 23:44:43','Insert');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myAddress','provinceFk','2022-08-03 23:44:43','Insert,Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myAddress','nickname','2022-08-03 23:44:43','Insert,Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myAddress','street','2022-08-03 23:44:43','Insert,Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myAddress','clientFk','2022-08-03 23:44:43','Insert');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myAddress','city','2022-08-03 23:44:43','Insert,Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myAddress','postalCode','2022-08-03 23:44:43','Insert,Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myClient','defaultAddressFk','2022-08-03 23:44:43','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','account','myClient','isToBeMailed','2022-08-03 23:44:43','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','guest','imageConfig','url','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','guest','Paises','Id','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','guest','Paises','Pais','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','guest','Tintas','Id_Tinta','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','guest','Tintas','name','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','guest','tblContadores','dbproduccion','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','guest','config','pdfsDir','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','guest','config','testDomain','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','guest','config','productionDomain','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','hedera','guest','config','defaultForm','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','guest','agencyMode','id','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','guest','agencyMode','deliveryMethodFk','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','guest','agencyMode','web','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','guest','agencyMode','agencyFk','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','guest','agencyMode','description','2022-08-03 23:44:43','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','guest','config','dbproduccion','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','role','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','email','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','user_id','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','extension','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','name','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','active','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','id','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','supplierFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','dated','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','invoiceNumber','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isExcludedFromAvailable','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','notes','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isConfirmed','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isOrdered','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isRaid','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','commission','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','created','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','evaNotes','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','travelFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','currencyFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','companyFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','gestDocFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','invoiceInFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isBlocked','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','loadPriority','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','kop','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','sub','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','pro','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','auction','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','invoiceAmount','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','buyerFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','typeFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','reference','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','observationEditorFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','clonedFrom','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','routeFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','name','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','beachFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','ticketPacked','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','ticketFree','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','ticketProduction','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','packages','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','note','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','dated','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','dockFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','m3','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','priority','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','etd','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','m3boxes','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','bufferFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','isPickingAllowed','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','productionBoss','routesMonitor','expeditionTruckFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','id','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','nickname','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','id','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','itemFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','ticketFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','concept','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','quantity','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','originalQuantity','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','discount','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','reserved','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','isPicked','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','isPriceFixed','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','created','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','isAdded','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','total','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','sale','editorFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','id','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','itemFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','ticketFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','concept','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','quantity','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','originalQuantity','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','discount','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','reserved','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','isPicked','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','isPriceFixed','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','created','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','isAdded','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','total','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','salesAssistant','sale','editorFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','deliveryAssistant','postCode','code','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','deliveryAssistant','postCode','townFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','deliveryAssistant','town','provinceFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','id','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','equivalent','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','stems','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','minPrice','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','isToPrint','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','family','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','box','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','category','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','doPhoto','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','image','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','inkFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','intrastatFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','hasMinPrice','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','created','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','comment','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','typeFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','generic','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','producerFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','description','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','density','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','relevancy','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','expenseFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','isActive','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','subName','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','tag5','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','value5','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','tag6','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','value6','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','tag7','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','value7','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','tag8','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','value8','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','tag9','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','value9','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','tag10','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','value10','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','minimum','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','upToDown','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','supplyResponseFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','hasKgPrice','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','isFloramondo','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','isFragile','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','numberOfItemsPerCask','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','embalageCode','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','quality','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','stemMultiplier','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','itemPackingTypeFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','packingOut','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','genericFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','packingShelve','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','isLaid','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','lastUsed','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','weightByPiece','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','editorFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','recycledPlastic','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','nonRecycledPlastic','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','minQuantity','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','item','size','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','item','originFk','0000-00-00 00:00:00','Select,Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','item','longName','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','item','name','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','id','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','warehouseFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','shipped','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','nickname','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','refFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','addressFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','workerFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','observations','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','isSigned','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','isLabeled','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','isPrinted','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','packages','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','location','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','hour','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','created','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','isBlocked','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','solution','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','routeFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','priority','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','hasPriority','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','companyFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','agencyModeFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','landed','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','isBoxed','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','isDeleted','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','zoneFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','zonePrice','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','zoneBonus','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','totalWithVat','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','totalWithoutVat','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','weight','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','clonedFrom','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','cmrFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','editorFk','0000-00-00 00:00:00','Update');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','config','truckLength','0000-00-00 00:00:00','Select');
+INSERT IGNORE INTO `columns_priv` VALUES ('','vn','production','item','isBoxPickingMode','0000-00-00 00:00:00','Update');
+/*!40000 ALTER TABLE `columns_priv` ENABLE KEYS */;
+
+/*!40000 ALTER TABLE `procs_priv` DISABLE KEYS */;
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','guest','myorder_getavailable','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','guest','myOrder_calcCatalogFull','PROCEDURE','juan@10.5.1.2','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myOrder_checkConfig','PROCEDURE','juan@10.5.1.2','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myOrder_calcCatalogFromItem','PROCEDURE','juan@10.5.1.2','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myOrder_getTax','PROCEDURE','juan@10.5.1.2','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','android','log_add','PROCEDURE','jenkins@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','employee','item_listAllocation','PROCEDURE','z-developer@www1.static.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','mytpvtransaction_end','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myticket_list','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myTicket_getServices','PROCEDURE','root@10.2.3.180','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myticket_getrows','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myticket_getpackages','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myTicket_get','PROCEDURE','z-sysadmin@172.16.255.34','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myorder_confirm','PROCEDURE','juan@10.5.1.2','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myorder_additem','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','guest','myOrder_configureForGuest','PROCEDURE','juan@10.5.1.2','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myOrder_create','PROCEDURE','juan@10.5.1.2','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana','zone_getaddresses','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','catalog_calcfrommyaddress','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','ext','buy_scan','PROCEDURE','juan@swarm-worker2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','guest','myUser_loginWithKey','PROCEDURE','jenkins@172.16.255.34','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','guest','myUser_login','PROCEDURE','jenkins@172.16.255.34','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','guest','myUser_hasRole','FUNCTION','jenkins@172.16.255.34','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','guest','myUser_getName','FUNCTION','jenkins@172.16.255.34','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','guest','myUser_getId','FUNCTION','jenkins@172.16.255.34','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','palletizerBoss','midnight','FUNCTION','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','account','myUser_logout','PROCEDURE','jenkins@172.16.255.34','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','entryEditor','getinventoryDate','FUNCTION','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana','zone_upcomingdeliveries','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','android','vn_now','FUNCTION','jenkins@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','entryEditor','entry_unlock','PROCEDURE','guillermo@10.5.1.4','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','agency','agencia_volume','PROCEDURE','root@10.1.4.166','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','account','zone_getAgency','PROCEDURE','juan@77.228.249.89','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','account','invoiceout_getpath','FUNCTION','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','employee','order_confirm','PROCEDURE','z-developer@www1.static.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myTpvTransaction_start','PROCEDURE','juan@77.227.99.220','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myticket_logaccess','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myorder_newwithdate','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myorder_newwithaddress','PROCEDURE','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myclient_getdebt','FUNCTION','root@pc-juan.dyn.verdnatura.es','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','hedera','account','myOrder_configure','PROCEDURE','juan@10.5.1.2','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','guest','myUser_hasRoleId','FUNCTION','jenkins@172.16.255.34','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','guest','myUser_checkLogin','FUNCTION','jenkins@172.16.255.34','Execute','2022-08-03 23:44:43');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','lang','FUNCTION','juan@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','grafana','firstdayofmonth','FUNCTION','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','financial','account_conciliacion_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','logistic','add_awb_component','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buy_getVolumeByEntry','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','productionAssi','agencyModeImbalance','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_getVolumeByEntry','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','entry_moveNotPrinted','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_getVolume','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockbuyedbyworker','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_getsplit','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','subordinategetlist','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_afterUpsert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','grafana','dayend','FUNCTION','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','srt','production','buffer_settypebyname','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buyUltimate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','financialBoss','balance_create','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buyUltimate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','barcodeToItem','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticket_splititempackingtype','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','entry_getCommission','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','deliveryAssistant','expeditionstate_addbypallet','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','buyer','buy_tarifas_entry','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','entryEditor','buy_tarifas','PROCEDURE','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','claimManager','buy_tarifas_entry','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','mail_insert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','entry_fixMisfit','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','employee','buy_tarifas_entry','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','VN_CURDATE','FUNCTION','juan@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','marketingBoss','clientTaxArea','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','clientTaxArea','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','client_checkBalance','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','addressTaxArea','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesPerson','client_getSalesPersonByTicket','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','pbx','developer','clientFromPhone','FUNCTION','juan@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','production','log_addWithUser','PROCEDURE','juan@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','balanceNestTree_addChild','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','balanceNestTree_delete','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','balanceNestTree_move','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','company_getSuppliersDebt','PROCEDURE','jgallego@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','bi','salesAssistant','defaultersFromDate','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','buy_updatepacking','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','buy_updategrouping','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','item_comparative','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','entryEditor','item_getVolume','FUNCTION','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','clientgetmana','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_scan','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','client_getSalesPersonByTicket','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','client_create','PROCEDURE','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','entryEditor','entry_isintrastat','FUNCTION','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','manager','collection_make','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','android','debugadd','PROCEDURE','jenkins@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','copyComponentsFromSaleList','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaEntryValueUpdate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaInvoiceInBooking','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelvinglog_get','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expedition_getstate','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','srt','production','expedition_scan','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','buyer','historico_absoluto','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','buyer','historico_multiple','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','client_getDebt','PROCEDURE','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','tx_commit','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','hrBoss','balance_create','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','cooler','buyultimate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','grafana','firstdayofyear','FUNCTION','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','claimManager','dayend','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','employee','log_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','srt','employee','moving_between','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','bi','financial','defaultersfromdate','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','getuser','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','hasanynegativebase','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','marketingBoss','hasanynegativebase','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','hassomenegativebase','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','administrative','accountshorttostandard','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','logistic','raidupdate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana','lastdayofweek','FUNCTION','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','artificialBoss','raidupdate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','marketingBoss','invoicefromclient','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoicefromclient','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoicefromticket','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoiceindueday_calculate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','invoiceindueday_calculate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','entry_splitbyshelving','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoiceintaxmakebydua','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','invoiceintax_getfromentries','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoiceintax_getfromentries','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','marketingBoss','invoiceoutbooking','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoiceoutbooking','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','clienttaxarea','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','invoicefromclient','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','hasanynegativebase','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','invoiceserial','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoiceserial','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','VN_CURTIME','FUNCTION','juan@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaTaxBooking','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','invoiceout_newfromclient','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoiceout_newfromticket','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','marketingBoss','invoiceserial','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','clientgetmana','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','packingsite_startcollection','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','invoiceoutbooking','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ticket_gettax','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','productionAssi','midnight','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','dipole','employee','expedition_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticketstateupdate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','coolerBoss','itempacking','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesPerson','ticket_clone','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','cache','employee','available_refresh','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','ticket_clone','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','coolerBoss','ticket_clone','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','payment_add','PROCEDURE','jgallego@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','timebusiness_calculatebyuser','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','itemsale_byweek','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','itemsale_byweek','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','timecontrol_calculatebyuser','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','ticket_clone','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','timecontrol_calculateall','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','manager','midnight','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','timebusiness_calculateall','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','cache','buyer','last_buy_refresh','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','supplierpackaging_reportsource','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','cache','buyer','stock_refresh','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','itemshelvingproblem','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','itemshelvingradar','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','cache','employee','visible_refresh','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','grafana','quarterfirstday','FUNCTION','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','workertimecontrol_sendmailbydepartment','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','agency','item_getStock','PROCEDURE','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','employee','debugadd','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','buyer','dayend','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','invoiceindueday_calculate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','invoiceintax_getfromentries','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_get','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','zone_getstate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','worker_gethierarchy','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','workertimecontrol_weekcheckbreak','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','ticket_split','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','buyer','add_awb_component','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','saletracking_new','PROCEDURE','alexm@pc325.algemesi.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ticketnotinvoicedbyclient','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','coolerBoss','workerjourney_replace','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','artificialBoss','workerjourney_replace','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','workerjourney_replace','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','item_getinfo','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','item_getlack','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','workerjourney_replace','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','item_getpackage','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','workerdisable','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','client_getDebt','FUNCTION','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','developer','ticket_add','PROCEDURE','jenkins@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','workercalendar_calculateyear','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','workercalendar_calculatebusiness','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticketparking_findskipped','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticketcollection_getnopacked','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','supplier_checkbalance','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','item_valuateinventory','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ledger_docompensation','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ledger_next','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoicein_booking','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','supplierpackaging_reportsource','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','logshow','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyerBoss','supplierpackaging_reportsource','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financialBoss','supplierexpenses','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana','firstdayofweek','FUNCTION','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockbuyed_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','mail_insert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaParcialMake','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','palletizerBoss','packingsite_startcollection','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','sale_calculatecomponent','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesPerson','manaspellersrequery','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','packageinvoicing','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','packinglistswitch','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','previoussticker_get','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','productioncontrol','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','productionsectorlist','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financialBoss','riskallclients','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','routemonitor_calculate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','developer','user_haspriv','FUNCTION','jgallego@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','salegroup_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','salepreparinglist','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','zone_getLanded','PROCEDURE','juan@10.5.1.2','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','saletracking_del','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','manager','ekt_getEntry','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaTax_doRecalc','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticketGetTotal','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','tickettoinvoicebyaddress','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','ticket_canmerge','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','tickettotalvolume','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','tickettotalvolumeboxes','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','subordinategetlist','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','entry_clone','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','guest','myuser_haspriv','FUNCTION','jgallego@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','coolerAssist','ticket_canmerge','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','ticket_cloneweekly','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','ticket_closebyticket','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','ticket_getfromfloramondo','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticket_get','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','artificialBoss','ticket_getfromfloramondo','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ticket_getfromfloramondo','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','ticket_getsplitlist','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','ticket_gettax','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','entryEditor','entry_lock','PROCEDURE','guillermo@10.5.1.4','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','developerBoss','role_syncPrivileges','PROCEDURE','juan@10.5.1.1','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','ticket_recalccomponents','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','entryDelivered','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','coolerBoss','ticket_splitpackingcomplete','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','guest','myuser_hasroutinepriv','FUNCTION','jgallego@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','productionAssi','timebusiness_calculateall','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','timecontrol_geterror','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','logistic','travel_weeklyclone','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_recalcPricesByBuy','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','handmadeBoss','confection_controlSource','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','bi','productionAssi','rutasanalyze','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','productionPlus','workerCreateExternal','PROCEDURE','juan@10.5.1.2','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','productionAssi','confection_controlSource','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','VN_NOW','FUNCTION','juan@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','VN_UNIX_TIMESTAMP','FUNCTION','juan@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','VN_UTC_DATE','FUNCTION','juan@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','VN_UTC_TIME','FUNCTION','juan@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','VN_UTC_TIMESTAMP','FUNCTION','juan@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_getsaledate','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','ticket_setState','PROCEDURE','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','invoicing','invoiceout_new','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','sale_replaceItem','PROCEDURE','jgallego@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','ledger_next','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','deliveryAssistant','workerjourney_replace','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','developerBoss','role_sync','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','deliveryAssistant','ticket_weightdeclaration','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','clientPackagingOverstock','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','clientPackagingOverstockReturn','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_filterbuyer','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','deliveryAssistant','dayend','FUNCTION','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','deliveryAssistant','routeproposal','FUNCTION','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','developer','user_hasroutinepriv','FUNCTION','jgallego@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','account','grafana','user_hasRole','FUNCTION','jgallego@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','time_generate','PROCEDURE','jenkins@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addbyclaim','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelvingtransfer','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addlist','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_selfconsumption','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','item_getsimilar','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelvingsale_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','collection_printsticker','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','deviceproductionuser_getworker','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','ticket_printlabelprevious','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','ticket_isoutclosurezone','FUNCTION','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','workermachinery_isregistered','FUNCTION','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','ticketstatetoday_setstate','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','device_checklogin','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','worker_getfromhasmistake','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','sectorcollection_new','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','sectorcollection_get','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','setparking','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','shelvingparking_get','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','machine_getworkerplate','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','saletracking_addprevok','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','sectorcollectionsalegroup_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','saletracking_updateischecked','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','saletracking_addpreparedsalegroup','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','travel_updatepacking','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','freelance_getinfo','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','company_getfiscaldata','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expedition_getfromroute','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','machineworker_gethistorical','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemplacementsupplyaiming','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionstate_addbypallet','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','srt','production','expeditionloading_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionpallet_list','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionpallet_printlabel','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionpallet_view','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionscan_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionscan_list','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionscan_put','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','cmrpallet_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemtrash','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','item_getbalance','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expedition_checkroute','FUNCTION','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','addnotefromdelivery','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','client_getSalesPerson','FUNCTION','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','buy_updatepacking','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','buy_updategrouping','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','srt','delivery','buffer_settypebyname','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expedition_getstate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','srt','delivery','expedition_scan','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_get','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelvinglog_get','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_getsaledate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_filterbuyer','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addbyclaim','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelvingtransfer','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addlist','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_selfconsumption','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','item_getsimilar','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelvingsale_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','collection_printsticker','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','deviceproductionuser_getworker','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','ticket_printlabelprevious','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','ticket_isoutclosurezone','FUNCTION','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','workermachinery_isregistered','FUNCTION','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','ticketstatetoday_setstate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','device_checklogin','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','worker_getfromhasmistake','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','sectorcollection_new','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','sectorcollection_get','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','setparking','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','shelvingparking_get','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','machine_getworkerplate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','saletracking_addprevok','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','sectorcollectionsalegroup_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','saletracking_updateischecked','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','saletracking_addpreparedsalegroup','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','travel_updatepacking','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','freelance_getinfo','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','company_getfiscaldata','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expedition_getfromroute','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','machineworker_gethistorical','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemplacementsupplyaiming','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionstate_addbypallet','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','srt','delivery','expeditionloading_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionpallet_list','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionpallet_printlabel','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionpallet_view','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionscan_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionscan_list','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionscan_put','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','cmrpallet_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemtrash','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','item_getbalance','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expedition_checkroute','FUNCTION','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','addnotefromdelivery','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemShelving_getinfo','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemShelving_getinfo','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','collection_get','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','item_comparative','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','sale_getBoxPickingList','PROCEDURE','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','worker_isInDepartment','FUNCTION','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','tx_rollback','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','tx_start','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_recalcPrices','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_recalcPricesByAwb','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_recalcPricesByEntry','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','hr','accountNumberToIban','FUNCTION','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','util','financial','accountNumberToIban','FUNCTION','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','supplier_statement','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','supplier_statement','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hrBoss','supplier_statement','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','XDiario_check','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','travel_getDetailFromContinent','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','entry_getTransfer','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','entry_getTransfer','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','intrastat_estimateNet','FUNCTION','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','artificialBoss','confection_controlSource','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','remittance_calc','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+/*!40000 ALTER TABLE `procs_priv` ENABLE KEYS */;
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
+USE `mysql`;
+/*!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 */;
+
+/*!40000 ALTER TABLE `global_priv` DISABLE KEYS */;
+INSERT IGNORE INTO `global_priv` VALUES ('','account','{\"access\": 0, \"is_role\": true,\"version_id\":100707}');
+INSERT IGNORE INTO `global_priv` VALUES ('','adminBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','adminOfficer','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','administrative','{\"access\": 0, \"is_role\": true, \"version_id\": 101106}');
+INSERT IGNORE INTO `global_priv` VALUES ('','agency','{\"access\": 0, \"max_questions\": 40000, \"max_updates\": 1000, \"max_connections\": 20000, \"max_user_connections\": 50, \"max_statement_time\": 0.000000, \"is_role\": true,\"version_id\":100707}');
+INSERT IGNORE INTO `global_priv` VALUES ('','android','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','artificialBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','assetManager','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','buyer','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','buyerAssistant','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','buyerBoss','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','claimManager','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','cooler','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','coolerAssist','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','coolerBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','customer','{\"access\": 0, \"max_questions\": 0, \"max_updates\": 30000, \"max_connections\": 300000, \"max_user_connections\": 400, \"max_statement_time\": 0.000000, \"is_role\": true,\"version_id\":100707}');
+INSERT IGNORE INTO `global_priv` VALUES ('','delivery','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','deliveryAssistant','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','deliveryBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','developer','{\"access\": 5909905728, \"is_role\": true, \"version_id\": 101106}');
+INSERT IGNORE INTO `global_priv` VALUES ('','developerBoss','{\"access\":33554432,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','employee','{\"access\": 0, \"is_role\": true, \"version_id\": 101106}');
+INSERT IGNORE INTO `global_priv` VALUES ('','entryEditor','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','ext','{\"access\": 0, \"is_role\": true, \"version_id\": 100707}');
+INSERT IGNORE INTO `global_priv` VALUES ('','financial','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','financialBoss','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','grafana','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','greenhouseBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','guest','{\"access\": 0, \"max_questions\": 40000, \"max_updates\": 1000, \"max_connections\": 150000, \"max_user_connections\": 200, \"max_statement_time\": 0.000000, \"is_role\": true, \"version_id\": 101106}');
+INSERT IGNORE INTO `global_priv` VALUES ('','handmadeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','hedera-web','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','hr','{\"access\": 0, \"is_role\": true, \"version_id\": 101106}');
+INSERT IGNORE INTO `global_priv` VALUES ('','hrBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','invoicing','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','itBoss','{\"access\": 541165846527, \"is_role\": true, \"version_id\": 100707}');
+INSERT IGNORE INTO `global_priv` VALUES ('','itManagement','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','itemPicker','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','logistic','{\"access\": 0, \"is_role\": true, \"version_id\": 101106}');
+INSERT IGNORE INTO `global_priv` VALUES ('','logisticAssist','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','logisticBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','maintenance','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBos','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','manager','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','marketing','{\"access\": 0, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','marketingBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','officeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','packager','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','palletizer','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','palletizerBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','preservedBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','production','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','productionAssi','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','productionBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','productionPlus','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','root','{\"access\": 549755781119, \"version_id\": 100705, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','salesAssistant','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','salesBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','salesPerson','{\"access\": 0, \"is_role\": true,\"version_id\":101106}');
+INSERT IGNORE INTO `global_priv` VALUES ('','salesTeamBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','salix','{\"access\":33555456,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','sysadmin','{\"access\": 201326592, \"is_role\": true, \"version_id\": 100707}');
+/*!40000 ALTER TABLE `global_priv` ENABLE KEYS */;
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
diff --git a/db/dump/structure.sql b/db/dump/.dump/structure.sql
similarity index 74%
rename from db/dump/structure.sql
rename to db/dump/.dump/structure.sql
index 08df0541c..db8d543b4 100644
--- a/db/dump/structure.sql
+++ b/db/dump/.dump/structure.sql
@@ -1,8 +1,8 @@
--- MariaDB dump 10.19 Distrib 10.5.19-MariaDB, for debian-linux-gnu (x86_64)
+-- MariaDB dump 10.19 Distrib 10.5.23-MariaDB, for debian-linux-gnu (x86_64)
--
--- Host: db2.static.verdnatura.es Database: account
+-- Host: db.verdnatura.es Database: account
-- ------------------------------------------------------
--- Server version 10.7.7-MariaDB-1:10.7.7+maria~deb11-log
+-- Server version 10.11.6-MariaDB-1:10.11.6+maria~deb12-log
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
@@ -39,94 +39,6 @@ CREATE TABLE `account` (
CONSTRAINT `account_ibfk_3` FOREIGN KEY (`id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Users allowed to have an account';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`account_beforeInsert`
- BEFORE INSERT ON `account`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`account_afterInsert`
- AFTER INSERT ON `account`
- FOR EACH ROW
-BEGIN
- INSERT IGNORE INTO userSync (`name`)
- SELECT `name` FROM `user` WHERE id = NEW.id;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`account_beforeUpdate`
- BEFORE UPDATE ON `account`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`account_afterDelete`
- AFTER DELETE ON `account`
- FOR EACH ROW
-BEGIN
- INSERT INTO userLog
- SET `action` = 'delete',
- `changedModel` = 'Account',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-
- INSERT IGNORE INTO userSync (`name`)
- SELECT `name` FROM `user` WHERE id = OLD.id;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `accountConfig`
@@ -145,7 +57,7 @@ CREATE TABLE `accountConfig` (
`warn` smallint(6) NOT NULL COMMENT 'Warn to change password when elapsed (seconds)',
`inact` smallint(6) NOT NULL COMMENT 'Maximum inactivity time (seconds)',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters for accounts';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters for accounts';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -208,7 +120,7 @@ CREATE TABLE `ldapConfig` (
`userDn` varchar(255) DEFAULT NULL COMMENT 'The base DN for users',
`groupDn` varchar(255) DEFAULT NULL COMMENT 'The base DN for groups',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='LDAP server configuration parameters';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='LDAP server configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -228,72 +140,8 @@ CREATE TABLE `mailAlias` (
UNIQUE KEY `alias` (`alias`),
KEY `mailAlias_fk_editor` (`editorFk`),
CONSTRAINT `mailAlias_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Mail aliases';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Mail aliases';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`mailAlias_beforeInsert`
- BEFORE INSERT ON `mailAlias`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`mailAlias_beforeUpdate`
- BEFORE UPDATE ON `mailAlias`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`mailAlias_afterDelete`
- AFTER DELETE ON `mailAlias`
- FOR EACH ROW
-BEGIN
- INSERT INTO userLog
- SET `action` = 'delete',
- `changedModel` = 'MailAlias',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `mailAliasAccount`
@@ -311,24 +159,41 @@ CREATE TABLE `mailAliasAccount` (
KEY `account` (`account`),
CONSTRAINT `account` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `mailAlias` FOREIGN KEY (`mailAlias`) REFERENCES `mailAlias` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Mail alias that is assigned to each account';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Mail alias that is assigned to each account';
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `mailClientAccess`
+-- Table structure for table `mailAliasAcl`
--
-DROP TABLE IF EXISTS `mailClientAccess`;
+DROP TABLE IF EXISTS `mailAliasAcl`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `mailClientAccess` (
+CREATE TABLE `mailAliasAcl` (
+ `mailAliasFk` int(10) unsigned NOT NULL,
+ `roleFk` int(10) unsigned NOT NULL,
+ KEY `mailAliasFk` (`mailAliasFk`),
+ KEY `roleFk` (`roleFk`),
+ CONSTRAINT `mailAliasAcl_ibfk_1` FOREIGN KEY (`mailAliasFk`) REFERENCES `mailAlias` (`id`),
+ CONSTRAINT `mailAliasAcl_ibfk_2` FOREIGN KEY (`roleFk`) REFERENCES `role` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `mailClientAccess__`
+--
+
+DROP TABLE IF EXISTS `mailClientAccess__`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `mailClientAccess__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`client` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`action` set('OK','REJECT') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT 'REJECT',
`description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mailFrom` (`client`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='@deprecated 2023-09-03';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -342,7 +207,7 @@ CREATE TABLE `mailConfig` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`domain` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -362,86 +227,22 @@ CREATE TABLE `mailForward` (
CONSTRAINT `mailForward_ibfk_1` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Mail forwarding';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`mailForward_beforeInsert`
- BEFORE INSERT ON `mailForward`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`mailForward_beforeUpdate`
- BEFORE UPDATE ON `mailForward`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`mailForward_afterDelete`
- AFTER DELETE ON `mailForward`
- FOR EACH ROW
-BEGIN
- INSERT INTO userLog
- SET `action` = 'delete',
- `changedModel` = 'MailForward',
- `changedModelId` = OLD.account,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
--- Table structure for table `mailSenderAccess`
+-- Table structure for table `mailSenderAccess__`
--
-DROP TABLE IF EXISTS `mailSenderAccess`;
+DROP TABLE IF EXISTS `mailSenderAccess__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `mailSenderAccess` (
+CREATE TABLE `mailSenderAccess__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sender` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`action` set('OK','REJECT') NOT NULL DEFAULT 'REJECT',
`description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mailFrom` (`sender`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='@deprecated 2023-09-03';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -494,76 +295,8 @@ CREATE TABLE `role` (
UNIQUE KEY `name` (`name`),
KEY `role_fk_editor` (`editorFk`),
CONSTRAINT `role_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Roles';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Roles';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`role_beforeInsert`
- BEFORE INSERT ON `role`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
- CALL role_checkName(NEW.`name`);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`role_beforeUpdate`
- BEFORE UPDATE ON `role`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
- IF !(NEW.`name` <=> OLD.`name`) THEN
- CALL role_checkName (NEW.`name`);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`role_afterDelete`
- AFTER DELETE ON `role`
- FOR EACH ROW
-BEGIN
- INSERT INTO roleLog
- SET `action` = 'delete',
- `changedModel` = 'Role',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `roleConfig`
@@ -580,7 +313,7 @@ CREATE TABLE `roleConfig` (
`userHost` varchar(255) NOT NULL,
`tplUser` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Role configuration parameters';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Role configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -602,72 +335,8 @@ CREATE TABLE `roleInherit` (
CONSTRAINT `roleInherit_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`),
CONSTRAINT `roleInherit_ibfk_1` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `roleInherit_ibfk_2` FOREIGN KEY (`inheritsFrom`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Role inheritance';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Role inheritance';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`roleInherit_beforeInsert`
- BEFORE INSERT ON `roleInherit`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`roleInherit_beforeUpdate`
- BEFORE UPDATE ON `roleInherit`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`roleInherit_afterDelete`
- AFTER DELETE ON `roleInherit`
- FOR EACH ROW
-BEGIN
- INSERT INTO roleLog
- SET `action` = 'delete',
- `changedModel` = 'RoleInherit',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `roleLog`
@@ -692,9 +361,8 @@ CREATE TABLE `roleLog` (
KEY `userFk` (`userFk`),
KEY `roleLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `roleLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `roleLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `roleLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -710,7 +378,7 @@ CREATE TABLE `roleRole` (
`inheritsFrom` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `role` (`role`,`inheritsFrom`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Calculated role inheritance';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Calculated role inheritance';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -727,8 +395,30 @@ CREATE TABLE `sambaConfig` (
`adUser` varchar(255) DEFAULT NULL COMMENT 'Active directory user',
`adPassword` varchar(255) DEFAULT NULL COMMENT 'Active directory password',
`verifyCert` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT 'Whether to verify server certificate',
+ `userDn` varchar(255) NOT NULL COMMENT 'Base DN for users without domain DN part',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters for accounts';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters for accounts';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `signInLog`
+--
+
+DROP TABLE IF EXISTS `signInLog`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `signInLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `token` varchar(255) NOT NULL,
+ `userFk` int(10) unsigned DEFAULT NULL,
+ `creationDate` timestamp NULL DEFAULT current_timestamp(),
+ `userName` varchar(30) NOT NULL,
+ `ip` varchar(100) NOT NULL,
+ `owner` tinyint(1) DEFAULT 1,
+ PRIMARY KEY (`id`),
+ KEY `userFk` (`userFk`),
+ CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -743,7 +433,7 @@ CREATE TABLE `user` (
`realm` varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`name` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`nickname` varchar(127) NOT NULL,
- `password` varchar(512) DEFAULT NULL,
+ `password` varchar(512) NOT NULL,
`role` int(10) unsigned NOT NULL DEFAULT 2,
`active` tinyint(1) NOT NULL DEFAULT 1,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
@@ -761,6 +451,7 @@ CREATE TABLE `user` (
`editorFk` int(10) unsigned DEFAULT NULL,
`passExpired` date DEFAULT NULL,
`twoFactor` enum('email') DEFAULT NULL COMMENT 'Two-factor auth type',
+ `username` varchar(30) GENERATED ALWAYS AS (`name`) VIRTUAL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
UNIQUE KEY `mail` (`email`),
@@ -771,142 +462,8 @@ CREATE TABLE `user` (
KEY `user_fk_editor` (`editorFk`),
CONSTRAINT `user_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`),
CONSTRAINT `user_ibfk_2` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global users';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global users';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`user_beforeInsert`
- BEFORE INSERT ON `user`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- CALL user_checkName(NEW.`name`);
-
- IF NEW.nickname = '' THEN
- SET NEW.nickname = NEW.`name`;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`user_afterInsert`
- AFTER INSERT ON `user`
- FOR EACH ROW
-BEGIN
- CALL hedera.image_ref('user', NEW.image);
-
- INSERT IGNORE INTO userSync SET `name` = NEW.`name`;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`user_beforeUpdate`
- BEFORE UPDATE ON `user`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF !(NEW.`name` <=> OLD.`name`) THEN
- CALL user_checkName (NEW.`name`);
- END IF;
-
- IF !(NEW.`password` <=> OLD.`password`) THEN
- SET NEW.lastPassChange = util.VN_NOW();
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`user_afterUpdate`
- AFTER UPDATE ON `user`
- FOR EACH ROW
-BEGIN
- IF !(NEW.image <=> OLD.image) THEN
- CALL hedera.image_unref('user', OLD.image);
- CALL hedera.image_ref('user', NEW.image);
- END IF;
-
- INSERT IGNORE INTO userSync SET `name` = NEW.`name`;
-
- IF !(OLD.`name` <=> NEW.`name`) THEN
- INSERT IGNORE INTO userSync SET `name` = OLD.`name`;
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `account`.`user_afterDelete`
- AFTER DELETE ON `user`
- FOR EACH ROW
-BEGIN
- INSERT INTO userLog
- SET `action` = 'delete',
- `changedModel` = 'User',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-
- CALL hedera.image_unref('user', OLD.image);
-
- INSERT IGNORE INTO userSync SET `name` = OLD.`name`;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `userConfig`
@@ -919,7 +476,7 @@ CREATE TABLE `userConfig` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`loginKey` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -945,9 +502,8 @@ CREATE TABLE `userLog` (
KEY `userFk` (`userFk`),
KEY `userLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `userLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -965,7 +521,7 @@ CREATE TABLE `userPassword` (
`nDigits` tinyint(3) unsigned NOT NULL COMMENT 'Minimum of digits',
`nPunct` tinyint(3) unsigned NOT NULL COMMENT 'Minimum of symbols',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Restrictions on user passwords';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Restrictions on user passwords';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -1018,7 +574,7 @@ BEGIN
SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey);
RETURN vSignature = @userSignature;
END IF;
-
+
RETURN FALSE;
END ;;
@@ -1047,7 +603,7 @@ BEGIN
* @return The user id
*/
DECLARE vUser INT DEFAULT NULL;
-
+
IF myUser_checkLogin()
THEN
SET vUser = @userId;
@@ -1055,7 +611,7 @@ BEGIN
SELECT id INTO vUser FROM user
WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1);
END IF;
-
+
RETURN vUser;
END ;;
DELIMITER ;
@@ -1090,7 +646,7 @@ BEGIN
ELSE
SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1);
END IF;
-
+
RETURN vUser;
END ;;
DELIMITER ;
@@ -1100,6 +656,35 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `myUser_hasPriv` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasPriv`(vChain VARCHAR(100),
+ vPrivilege ENUM('SELECT','INSERT','UPDATE','DELETE')
+) RETURNS tinyint(1)
+ READS SQL DATA
+BEGIN
+/**
+ * Search if my user has privileges on table or column
+ *
+ * @param vChain string passed with this syntax dbName.tableName[.columnName]
+ * @param vPrivilege privileges to check ('SELECT','INSERT','UPDATE','DELETE')
+ * @return vHasPrivilege
+ */
+ RETURN user_hasPriv(vChain, vPrivilege, myUser_getId());
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `myUser_hasRole` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -1152,6 +737,35 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `myUser_hasRoutinePriv` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasRoutinePriv`(vType ENUM('PROCEDURE', 'FUNCTION'),
+ vChain VARCHAR(100)
+) RETURNS tinyint(1)
+ READS SQL DATA
+BEGIN
+/**
+ * Search if my user has privileges on routines
+ *
+ * @param vType procedure or function
+ * @param vChain string passed with this syntax dbName.tableName
+ * @return vHasPrivilege
+ */
+ RETURN user_hasRoutinePriv(vType, vChain, myUser_getId());
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `passwordGenerate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -1185,10 +799,10 @@ BEGIN
DECLARE vDigitChars TEXT DEFAULT '1234567890';
DECLARE vPunctChars TEXT DEFAULT '!$%&()=.';
- SELECT length, nAlpha, nUpper, nDigits, nPunct
+ SELECT length, nAlpha, nUpper, nDigits, nPunct
INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword;
- WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha
+ WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha
OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO
SET vRandIndex = FLOOR((RAND() * 4) + 1);
@@ -1263,7 +877,7 @@ BEGIN
DECLARE vRole VARCHAR(255);
SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole
- FROM role r
+ FROM role r
JOIN user u ON u.role = r.id
JOIN roleConfig c
WHERE u.name = vUserName;
@@ -1290,16 +904,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `user_getNameFromId`(vSelf INT) RETUR
BEGIN
/**
* Gets user name from it's id.
- *
+ *
* @param vSelf The user id
* @return The user name
*/
DECLARE vName VARCHAR(30);
-
- SELECT `name` INTO vName
- FROM user
+
+ SELECT `name` INTO vName
+ FROM user
WHERE id = vSelf;
-
+
RETURN vName;
END ;;
DELIMITER ;
@@ -1309,6 +923,126 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `user_hasPriv` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `user_hasPriv`(vChain VARCHAR(100),
+ vPrivilege ENUM('SELECT','INSERT','UPDATE','DELETE'),
+ vUserFk INT
+) RETURNS tinyint(1)
+ READS SQL DATA
+BEGIN
+/**
+ * Search if the user has privileges on table or column
+ *
+ * @param vChain string passed with this syntax dbName.tableName[.columnName]
+ * @param vPrivilege privileges to check('SELECT','INSERT','UPDATE','DELETE')
+ * @param vUserFk user to check
+ * @return vHasPrivilege
+ */
+ DECLARE vHasPrivilege BOOL DEFAULT FALSE;
+ DECLARE vDb VARCHAR(50);
+ DECLARE vTableName VARCHAR(50);
+ DECLARE vColumnName VARCHAR(50);
+ DECLARE vPrivilegeFlag INT;
+ DECLARE vChainExists BOOL;
+
+ SET vDb = SUBSTRING_INDEX(vChain, '.', 1);
+ SET vChain = SUBSTRING(vChain, LENGTH(vDb) + 2);
+ IF LOCATE('.', vChain) > 0 THEN
+ SET vTableName = SUBSTRING_INDEX(vChain, '.', 1);
+ SET vColumnName = SUBSTRING(vChain, LENGTH(vTableName) + 2);
+ ELSE
+ SET vTableName = vChain;
+ END IF;
+
+ SELECT COUNT(*) INTO vChainExists
+ FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = vDb
+ AND TABLE_NAME = vTableName
+ AND (COLUMN_NAME = vColumnName OR vColumnName IS NULL)
+ LIMIT 1;
+
+ IF NOT vChainExists THEN
+ RETURN FALSE;
+ END IF;
+
+ CASE vPrivilege
+ WHEN 'Select' THEN SET vPrivilegeFlag = 1;
+ WHEN 'Insert' THEN SET vPrivilegeFlag = 2;
+ WHEN 'Update' THEN SET vPrivilegeFlag = 4;
+ WHEN 'Delete' THEN SET vPrivilegeFlag = 8;
+ ELSE BEGIN END;
+ END CASE;
+
+ DROP TEMPORARY TABLE IF EXISTS tRole;
+ CREATE TEMPORARY TABLE tRole
+ (INDEX (`name`))
+ ENGINE = MEMORY
+ SELECT r.`name`
+ FROM user u
+ JOIN roleRole rr ON rr.role = u.role
+ JOIN `role` r ON r.id = rr.inheritsFrom
+ WHERE u.id = vUserFk;
+
+ SELECT hasPrivilege INTO vHasPrivilege
+ FROM (SELECT JSON_VALUE(Priv, '$.access') & vPrivilegeFlag hasPrivilege
+ FROM mysql.global_priv gp
+ JOIN tRole tr ON CONCAT(tr.name) = gp.User
+ HAVING hasPrivilege
+ LIMIT 1)sub;
+
+ IF NOT vHasPrivilege THEN
+
+ SELECT sub.privilege = 'Y' INTO vHasPrivilege
+ FROM
+ (SELECT CASE vPrivilege
+ WHEN 'SELECT' THEN Select_priv
+ WHEN 'INSERT' THEN Insert_priv
+ WHEN 'UPDATE' THEN Update_priv
+ WHEN 'DELETE' THEN Delete_priv
+ END privilege
+ FROM mysql.db db
+ JOIN tRole tr ON tr.name = db.User
+ WHERE db.Db = vDb)sub;
+
+ END IF;
+
+ IF NOT vHasPrivilege THEN
+
+ SELECT TRUE INTO vHasPrivilege
+ FROM tRole tr
+ LEFT JOIN (
+ SELECT User, Table_priv privilege
+ FROM mysql.tables_priv
+ WHERE Db = vDb
+ AND Table_name = vTableName
+ UNION
+ SELECT User, Column_priv
+ FROM mysql.columns_priv
+ WHERE Db = vDb
+ AND Table_name = vTableName
+ AND Column_name = vColumnName
+ )sub ON sub.`User` = tr.name
+ WHERE sub.privilege = vPrivilege;
+ END IF;
+
+ DROP TEMPORARY TABLE tRole;
+
+ RETURN vHasPrivilege;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `user_hasRole` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -1371,7 +1105,7 @@ BEGIN
JOIN role r ON r.id = rr.inheritsFrom
WHERE u.`name` = vUser
AND r.id = vRoleId;
-
+
RETURN vHasRole;
END ;;
DELIMITER ;
@@ -1381,6 +1115,135 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `user_hasRoutinePriv` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `user_hasRoutinePriv`(vType ENUM('PROCEDURE', 'FUNCTION'),
+ vChain VARCHAR(100),
+ vUserFk INT
+) RETURNS tinyint(1)
+ READS SQL DATA
+BEGIN
+/**
+ * Search if the user has privileges on routines.
+ *
+ * @param vType procedure or function
+ * @param vChain string passed with this syntax dbName.tableName
+ * @param vUserFk user to ckeck
+ * @return vHasPrivilege
+ */
+ DECLARE vHasPrivilege BOOL DEFAULT FALSE;
+ DECLARE vDb VARCHAR(50);
+ DECLARE vObject VARCHAR(50);
+ DECLARE vChainExists BOOL;
+ DECLARE vExecutePriv INT DEFAULT 262144;
+ -- 262144 = CONV(1000000000000000000, 2, 10)
+ -- 1000000000000000000 execution permission expressed in binary base
+
+ SET vDb = SUBSTRING_INDEX(vChain, '.', 1);
+ SET vChain = SUBSTRING(vChain, LENGTH(vDb) + 2);
+ SET vObject = SUBSTRING_INDEX(vChain, '.', 1);
+
+ SELECT COUNT(*) INTO vChainExists
+ FROM mysql.proc
+ WHERE db = vDb
+ AND `name` = vObject
+ AND `type` = vType
+ LIMIT 1;
+
+ IF NOT vChainExists THEN
+ RETURN FALSE;
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tRole;
+ CREATE TEMPORARY TABLE tRole
+ (INDEX (`name`))
+ ENGINE = MEMORY
+ SELECT r.`name`
+ FROM user u
+ JOIN roleRole rr ON rr.role = u.role
+ JOIN `role` r ON r.id = rr.inheritsFrom
+ WHERE u.id = vUserFk;
+
+ SELECT TRUE INTO vHasPrivilege
+ FROM mysql.global_priv gp
+ JOIN tRole tr ON tr.name = gp.`User`
+ OR CONCAT('$', tr.name) = gp.`User`
+ WHERE JSON_VALUE(gp.Priv, '$.access') >= vExecutePriv
+ AND gp.Host = ''
+ LIMIT 1;
+
+ IF NOT vHasPrivilege THEN
+ SELECT TRUE INTO vHasPrivilege
+ FROM mysql.db db
+ JOIN tRole tr ON tr.name = db.`User`
+ WHERE db.Db = vDb
+ AND db.Execute_priv = 'Y';
+ END IF;
+
+ IF NOT vHasPrivilege THEN
+ SELECT TRUE INTO vHasPrivilege
+ FROM mysql.procs_priv pp
+ JOIN tRole tr ON tr.name = pp.`User`
+ WHERE pp.Db = vDb
+ AND pp.Routine_name = vObject
+ AND pp.Routine_type = vType
+ AND pp.Proc_priv = 'Execute'
+ LIMIT 1;
+ END IF;
+
+ DROP TEMPORARY TABLE tRole;
+ RETURN vHasPrivilege;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `account_enable` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `account_enable`(vSelf INT)
+BEGIN
+/**
+ * Enables an account and sets up email configuration.
+ */
+ UPDATE user
+ SET active = TRUE
+ WHERE id = vSelf;
+
+ INSERT IGNORE INTO account
+ SET id = vSelf;
+
+ INSERT IGNORE INTO mailAliasAccount (mailAlias, account)
+ SELECT id, vSelf
+ FROM mailAlias
+ WHERE alias = 'general';
+
+ INSERT IGNORE INTO mailForward (account, forwardTo)
+ SELECT vSelf, email
+ FROM user
+ WHERE id = vSelf;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myUser_login` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -1405,7 +1268,7 @@ BEGIN
AND password = MD5(vPassword)
AND active;
- IF vAuthIsOk
+ IF vAuthIsOk
THEN
CALL myUser_loginWithName (vUserName);
ELSE
@@ -1466,7 +1329,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_loginWithName`(vUserName VAR
BEGIN
/**
* Logs in using only the user name. This procedure is intended to be executed
- * by users with a high level of privileges so that normal users should not have
+ * by users with a high level of privileges so that normal users should not have
* execute permissions on it.
*
* @param vUserName The user name
@@ -1502,7 +1365,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_logout`()
BEGIN
/**
* Logouts the user.
- */
+ */
SET @userId = NULL;
SET @userName = NULL;
SET @userSignature = NULL;
@@ -1600,9 +1463,9 @@ BEGIN
SELECT COUNT(*) > 0 INTO vIsRoot
FROM tmp.role t
- JOIN role r ON r.id = t.id
+ JOIN role r ON r.id = t.id
WHERE r.`name` = 'root';
-
+
IF vIsRoot THEN
INSERT IGNORE INTO tmp.role (id)
SELECT id FROM role;
@@ -2321,7 +2184,7 @@ BEGIN
IF vChr REGEXP '[[:alpha:]]'
THEN
SET vNAlpha = vNAlpha+1;
-
+
IF vChr REGEXP '[A-Z]'
THEN
SET vNUpper = vNUpper+1;
@@ -2357,6 +2220,1914 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
+--
+-- Current Database: `bi`
+--
+
+CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
+
+USE `bi`;
+
+--
+-- Table structure for table `Equalizator`
+--
+
+DROP TABLE IF EXISTS `Equalizator`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `Equalizator` (
+ `Vista` int(11) NOT NULL,
+ `Pedido` int(11) DEFAULT NULL,
+ `Impreso` int(11) DEFAULT NULL,
+ `Encajado` int(11) DEFAULT NULL,
+ PRIMARY KEY (`Vista`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `Greuge_Evolution`
+--
+
+DROP TABLE IF EXISTS `Greuge_Evolution`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `Greuge_Evolution` (
+ `Id_Cliente` int(11) NOT NULL,
+ `Fecha` date NOT NULL,
+ `Greuge` decimal(10,2) NOT NULL DEFAULT 0.00,
+ `Ventas` decimal(10,2) NOT NULL DEFAULT 0.00,
+ `Fosil` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'greuge fósil, correspondiente a los clientes muertos',
+ `Recobro` decimal(10,2) NOT NULL DEFAULT 0.00,
+ PRIMARY KEY (`Id_Cliente`,`Fecha`),
+ KEY `greuge_evolution_idx1` (`Fecha`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacenamos la evolucion del greuge de los ultimos dias ';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `Greuge_comercial_recobro`
+--
+
+DROP TABLE IF EXISTS `Greuge_comercial_recobro`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `Greuge_comercial_recobro` (
+ `Id_Trabajador` int(11) NOT NULL,
+ `recobro` decimal(10,2) NOT NULL DEFAULT 0.00,
+ `peso_cartera` decimal(10,2) NOT NULL DEFAULT 0.00,
+ PRIMARY KEY (`Id_Trabajador`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `Greuges_comercial_detail`
+--
+
+DROP TABLE IF EXISTS `Greuges_comercial_detail`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `Greuges_comercial_detail` (
+ `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `Id_Trabajador` int(10) unsigned NOT NULL,
+ `Comentario` varchar(45) NOT NULL,
+ `Importe` decimal(10,2) NOT NULL,
+ `Fecha` datetime DEFAULT NULL,
+ PRIMARY KEY (`Id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=COMPACT;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `Ticket_Portes`
+--
+
+DROP TABLE IF EXISTS `Ticket_Portes`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `Ticket_Portes` (
+ `Id_Ticket` int(11) NOT NULL,
+ `rate` tinyint(4) NOT NULL COMMENT 'Tarifa',
+ `real_amount` double NOT NULL COMMENT 'Cantidad pactada con la agencia',
+ `payed_amount` double NOT NULL COMMENT 'Cantidad reflejada en el Ticket',
+ PRIMARY KEY (`Id_Ticket`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `XDiario_ALL`
+--
+
+DROP TABLE IF EXISTS `XDiario_ALL`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `XDiario_ALL` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `empresa_id` int(5) NOT NULL,
+ `SUBCTA` varchar(11) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `Eurodebe` double DEFAULT NULL,
+ `Eurohaber` double DEFAULT NULL,
+ `Fecha` date DEFAULT NULL,
+ `FECHA_EX` date DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `Cuenta` (`SUBCTA`),
+ KEY `empresa` (`empresa_id`),
+ KEY `Fecha` (`Fecha`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `analisis_grafico_simple`
+--
+
+DROP TABLE IF EXISTS `analisis_grafico_simple`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `analisis_grafico_simple` (
+ `Año` smallint(5) unsigned NOT NULL,
+ `Semana` tinyint(3) unsigned NOT NULL,
+ `Importe` double DEFAULT NULL,
+ UNIQUE KEY `Año` (`Año`,`Semana`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `analisis_grafico_ventas`
+--
+
+DROP TABLE IF EXISTS `analisis_grafico_ventas`;
+/*!50001 DROP VIEW IF EXISTS `analisis_grafico_ventas`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `analisis_grafico_ventas` AS SELECT
+ 1 AS `Año`,
+ 1 AS `Semana`,
+ 1 AS `Importe` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `analisis_ventas`
+--
+
+DROP TABLE IF EXISTS `analisis_ventas`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `analisis_ventas` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `Familia` varchar(30) NOT NULL,
+ `Reino` varchar(45) NOT NULL,
+ `Comercial` varchar(3) NOT NULL,
+ `Comprador` varchar(3) NOT NULL,
+ `Provincia` varchar(30) NOT NULL,
+ `almacen` varchar(20) NOT NULL,
+ `Año` smallint(5) unsigned NOT NULL,
+ `Mes` tinyint(3) unsigned NOT NULL,
+ `Semana` tinyint(3) unsigned NOT NULL,
+ `Vista` varchar(45) DEFAULT NULL,
+ `Importe` double NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `Año` (`Año`,`Semana`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `analisis_ventas_almacen_evolution`
+--
+
+DROP TABLE IF EXISTS `analisis_ventas_almacen_evolution`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `analisis_ventas_almacen_evolution` (
+ `Semana` int(11) NOT NULL,
+ `Almacen` varchar(20) NOT NULL,
+ `Ventas` int(11) NOT NULL,
+ `Año` int(11) NOT NULL,
+ `Periodo` int(11) NOT NULL,
+ UNIQUE KEY `Almacen` (`Almacen`,`Periodo`),
+ KEY `Periodo` (`Periodo`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `analisis_ventas_familia_evolution__`
+--
+
+DROP TABLE IF EXISTS `analisis_ventas_familia_evolution__`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `analisis_ventas_familia_evolution__` (
+ `semana` int(11) NOT NULL,
+ `familia` varchar(50) NOT NULL,
+ `ventas` int(11) NOT NULL,
+ `año` int(11) NOT NULL,
+ `periodo` int(11) NOT NULL,
+ `typeFk` smallint(5) unsigned DEFAULT NULL,
+ UNIQUE KEY `familia` (`familia`,`periodo`),
+ KEY `periodo` (`periodo`),
+ KEY `analisis_ventas_familia_evolution_FK` (`typeFk`),
+ CONSTRAINT `analisis_ventas_familia_evolution_FK` FOREIGN KEY (`typeFk`) REFERENCES `vn`.`itemType` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5196 Deprecated 2023-06-05';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `analisis_ventas_provincia_evolution`
+--
+
+DROP TABLE IF EXISTS `analisis_ventas_provincia_evolution`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `analisis_ventas_provincia_evolution` (
+ `semana` int(11) NOT NULL,
+ `provincia` varchar(30) NOT NULL,
+ `ventas` int(11) NOT NULL,
+ `año` int(11) NOT NULL,
+ `periodo` int(11) NOT NULL,
+ `countryCode` varchar(2) NOT NULL,
+ UNIQUE KEY `provincia` (`provincia`,`periodo`),
+ KEY `periodo` (`periodo`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `analisis_ventas_reino_evolution`
+--
+
+DROP TABLE IF EXISTS `analisis_ventas_reino_evolution`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `analisis_ventas_reino_evolution` (
+ `semana` int(11) NOT NULL,
+ `reino` varchar(20) NOT NULL,
+ `ventas` int(11) NOT NULL,
+ `año` int(11) NOT NULL,
+ `periodo` int(11) NOT NULL,
+ UNIQUE KEY `reino` (`reino`,`periodo`),
+ KEY `periodo` (`periodo`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `analisis_ventas_simple`
+--
+
+DROP TABLE IF EXISTS `analisis_ventas_simple`;
+/*!50001 DROP VIEW IF EXISTS `analisis_ventas_simple`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `analisis_ventas_simple` AS SELECT
+ 1 AS `Año`,
+ 1 AS `Semana`,
+ 1 AS `Importe` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `analisis_ventas_vendedor_evolution`
+--
+
+DROP TABLE IF EXISTS `analisis_ventas_vendedor_evolution`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `analisis_ventas_vendedor_evolution` (
+ `semana` int(11) NOT NULL,
+ `vendedor` varchar(3) NOT NULL,
+ `ventas` int(11) NOT NULL,
+ `año` int(11) NOT NULL,
+ `periodo` int(11) NOT NULL,
+ UNIQUE KEY `vendedor` (`vendedor`,`periodo`),
+ KEY `periodo` (`periodo`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `analisis_ventas_vista_evolution`
+--
+
+DROP TABLE IF EXISTS `analisis_ventas_vista_evolution`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `analisis_ventas_vista_evolution` (
+ `semana` int(11) NOT NULL,
+ `vista` varchar(45) NOT NULL,
+ `ventas` int(11) NOT NULL,
+ `año` int(11) NOT NULL,
+ `periodo` int(11) NOT NULL,
+ UNIQUE KEY `vista` (`vista`,`periodo`),
+ KEY `periodo` (`periodo`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `calidad_detalle`
+--
+
+DROP TABLE IF EXISTS `calidad_detalle`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `calidad_detalle` (
+ `Id_Cliente` int(11) NOT NULL,
+ `calidad_parametros_id` int(2) NOT NULL,
+ `valor` int(3) DEFAULT NULL,
+ PRIMARY KEY (`Id_Cliente`,`calidad_parametros_id`),
+ KEY `calidad_parametros_detalle_idx` (`calidad_parametros_id`),
+ CONSTRAINT `calidad_parametros_detalle` FOREIGN KEY (`calidad_parametros_id`) REFERENCES `calidad_parametros` (`calidad_parametros_id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `calidad_parametros`
+--
+
+DROP TABLE IF EXISTS `calidad_parametros`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `calidad_parametros` (
+ `calidad_parametros_id` int(2) NOT NULL,
+ `descripcion` varchar(45) NOT NULL,
+ PRIMARY KEY (`calidad_parametros_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `claims_ratio`
+--
+
+DROP TABLE IF EXISTS `claims_ratio`;
+/*!50001 DROP VIEW IF EXISTS `claims_ratio`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `claims_ratio` AS SELECT
+ 1 AS `Id_Cliente`,
+ 1 AS `Consumo`,
+ 1 AS `Reclamaciones`,
+ 1 AS `Ratio`,
+ 1 AS `recobro`,
+ 1 AS `inflacion` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `customerDebtInventory`
+--
+
+DROP TABLE IF EXISTS `customerDebtInventory`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `customerDebtInventory` (
+ `Id_Cliente` int(11) NOT NULL,
+ `Debt` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'CREATE TABLE bi.customerDebtInventory\n\nSELECT Id_Cliente, sum(Euros) as Debt\n\nFROM \n(\nSELECT Id_Cliente, Entregado as Euros\n\nFROM Recibos \n\nWHERE Fechacobro < ''2017-01-01\n''\nUNION ALL\n\nSELECT Id_Cliente, - Importe \nFROM Facturas\nWHERE Fecha < ''2017-01-01''\n) sub \nGROUP BY Id_Cliente',
+ PRIMARY KEY (`Id_Cliente`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `customerRiskOverdue`
+--
+
+DROP TABLE IF EXISTS `customerRiskOverdue`;
+/*!50001 DROP VIEW IF EXISTS `customerRiskOverdue`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `customerRiskOverdue` AS SELECT
+ 1 AS `customer_id`,
+ 1 AS `amount`,
+ 1 AS `company_id` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `defaulters`
+--
+
+DROP TABLE IF EXISTS `defaulters`;
+/*!50001 DROP VIEW IF EXISTS `defaulters`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `defaulters` AS SELECT
+ 1 AS `client`,
+ 1 AS `date`,
+ 1 AS `amount`,
+ 1 AS `defaulterSince`,
+ 1 AS `hasChanged`,
+ 1 AS `frozened` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `defaulting`
+--
+
+DROP TABLE IF EXISTS `defaulting`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `defaulting` (
+ `date` date NOT NULL,
+ `amount` double NOT NULL,
+ PRIMARY KEY (`date`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `f_tvc`
+--
+
+DROP TABLE IF EXISTS `f_tvc`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `f_tvc` (
+ `Id_Ticket` int(11) NOT NULL,
+ PRIMARY KEY (`Id_Ticket`),
+ CONSTRAINT `id_ticket_to_comisionantes` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn`.`ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacenamos la lista de tickets para agilizar la consulta. Corresponde a los clientes REAL y en los almacenes COMISIONANTES';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `facturacion_media_anual`
+--
+
+DROP TABLE IF EXISTS `facturacion_media_anual`;
+/*!50001 DROP VIEW IF EXISTS `facturacion_media_anual`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `facturacion_media_anual` AS SELECT
+ 1 AS `Id_Cliente`,
+ 1 AS `Consumo` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `last_Id_Cubo`
+--
+
+DROP TABLE IF EXISTS `last_Id_Cubo`;
+/*!50001 DROP VIEW IF EXISTS `last_Id_Cubo`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `last_Id_Cubo` AS SELECT
+ 1 AS `Id_Compra`,
+ 1 AS `Id_Article`,
+ 1 AS `warehouse_id`,
+ 1 AS `Id_Cubo`,
+ 1 AS `Packing` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `live_counter__`
+--
+
+DROP TABLE IF EXISTS `live_counter__`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `live_counter__` (
+ `odbc_date` timestamp NOT NULL DEFAULT current_timestamp(),
+ `amount` double NOT NULL,
+ PRIMARY KEY (`odbc_date`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `partitioning_information__`
+--
+
+DROP TABLE IF EXISTS `partitioning_information__`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `partitioning_information__` (
+ `schema_name` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `table_name` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `date_field` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `table_depending` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `execution_order` tinyint(3) unsigned NOT NULL,
+ PRIMARY KEY (`schema_name`,`table_name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `primer_pedido__`
+--
+
+DROP TABLE IF EXISTS `primer_pedido__`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `primer_pedido__` (
+ `Id_Cliente` int(11) NOT NULL,
+ `Id_Ticket` int(11) NOT NULL,
+ `month` tinyint(1) NOT NULL,
+ `year` smallint(2) NOT NULL,
+ `total` decimal(10,2) NOT NULL DEFAULT 0.00,
+ PRIMARY KEY (`Id_Cliente`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `rotacion`
+--
+
+DROP TABLE IF EXISTS `rotacion`;
+/*!50001 DROP VIEW IF EXISTS `rotacion`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `rotacion` AS SELECT
+ 1 AS `Id_Article`,
+ 1 AS `warehouse_id`,
+ 1 AS `total`,
+ 1 AS `rotacion`,
+ 1 AS `cm3`,
+ 1 AS `almacenaje`,
+ 1 AS `manipulacion`,
+ 1 AS `auxiliar`,
+ 1 AS `mermas`,
+ 1 AS `cm3reparto`,
+ 1 AS `grams` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `rutasBoard`
+--
+
+DROP TABLE IF EXISTS `rutasBoard`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `rutasBoard` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `Id_Ruta` int(10) unsigned NOT NULL DEFAULT 0,
+ `Id_Agencia` int(11) NOT NULL DEFAULT 0,
+ `km__` varchar(9) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ `Dia__` varchar(9) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ `Fecha` date NOT NULL,
+ `Terceros__` int(11) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ `Bultos` int(11) NOT NULL DEFAULT 0,
+ `Matricula__` varchar(10) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ `Tipo__` varchar(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ `year__` int(4) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ `month__` int(2) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ `warehouse_id__` smallint(5) unsigned DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ `coste_bulto__` decimal(10,2) unsigned DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ `teorico` decimal(10,2) NOT NULL DEFAULT 0.00,
+ `practico` decimal(10,2) NOT NULL DEFAULT 0.00,
+ `greuge` decimal(10,2) NOT NULL DEFAULT 0.00,
+ `m3__` decimal(10,1) unsigned DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `rutasBoard_Ruta` (`Id_Ruta`),
+ KEY `rutasBoard_ix1` (`year__`),
+ KEY `rutasBoard_ix2` (`month__`),
+ KEY `rutasBoard_ix3` (`warehouse_id__`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Se usa en https://grafana.verdnatura.es/d/c089276b-5ab5-430f-aa76-e5d8e0e7fe2e/analisis-de-volumen-y-rendimiento-por-agencia?orgId=1';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `tarifa_componentes`
+--
+
+DROP TABLE IF EXISTS `tarifa_componentes`;
+/*!50001 DROP VIEW IF EXISTS `tarifa_componentes`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `tarifa_componentes` AS SELECT
+ 1 AS `Id_Componente`,
+ 1 AS `Componente`,
+ 1 AS `tarifa_componentes_series_id`,
+ 1 AS `tarifa_class`,
+ 1 AS `tax`,
+ 1 AS `is_renewable`,
+ 1 AS `code` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `tarifa_componentes_series`
+--
+
+DROP TABLE IF EXISTS `tarifa_componentes_series`;
+/*!50001 DROP VIEW IF EXISTS `tarifa_componentes_series`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `tarifa_componentes_series` AS SELECT
+ 1 AS `tarifa_componentes_series_id`,
+ 1 AS `Serie`,
+ 1 AS `base`,
+ 1 AS `margen` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `tarifa_premisas__`
+--
+
+DROP TABLE IF EXISTS `tarifa_premisas__`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `tarifa_premisas__` (
+ `Id_Premisa` int(11) NOT NULL AUTO_INCREMENT,
+ `premisa` varchar(45) NOT NULL,
+ PRIMARY KEY (`Id_Premisa`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `tarifa_warehouse__`
+--
+
+DROP TABLE IF EXISTS `tarifa_warehouse__`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `tarifa_warehouse__` (
+ `Id_Tarifa_Warehouse` int(11) NOT NULL AUTO_INCREMENT,
+ `warehouse_id` int(11) NOT NULL,
+ `Id_Premisa` int(11) NOT NULL,
+ `Valor` double NOT NULL,
+ PRIMARY KEY (`Id_Tarifa_Warehouse`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06\nAlmacena los valores de gasto por almacen';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `v_ventas_contables`
+--
+
+DROP TABLE IF EXISTS `v_ventas_contables`;
+/*!50001 DROP VIEW IF EXISTS `v_ventas_contables`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `v_ventas_contables` AS SELECT
+ 1 AS `year`,
+ 1 AS `month`,
+ 1 AS `importe` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Dumping events for database 'bi'
+--
+
+--
+-- Dumping routines for database 'bi'
+--
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_evolution_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_evolution_add`()
+BEGIN
+ DECLARE vPreviousPeriod INT;
+ DECLARE vCurrentPeriod INT;
+ DECLARE vLastPeriod INT;
+ DECLARE vMinPeriod INT DEFAULT 201400;
+ DECLARE vMaxPeriod INT;
+ DECLARE vYear INT;
+ DECLARE vWeek INT;
+
+ SELECT t.period INTO vMaxPeriod
+ FROM vn.`time` t
+ WHERE t.dated = util.VN_CURDATE();
+
+ -- Almacen
+
+ SET vCurrentPeriod = IFNULL(vLastPeriod, vMinPeriod);
+
+ WHILE vCurrentPeriod < vMaxPeriod
+ DO
+ SELECT MAX(Periodo) INTO vPreviousPeriod
+ FROM analisis_ventas_almacen_evolution
+ WHERE Periodo < vMaxPeriod;
+
+ SELECT MIN(period) INTO vCurrentPeriod
+ FROM vn2008.time
+ WHERE period > vPreviousPeriod;
+
+ SET vYear = FLOOR(vCurrentPeriod / 100);
+ SET vWeek = vCurrentPeriod - (vYear * 100);
+
+ DELETE FROM analisis_ventas_almacen_evolution
+ WHERE Periodo = vCurrentPeriod;
+
+ REPLACE analisis_ventas_almacen_evolution(Almacen, Ventas, Semana,Año, Periodo)
+ SELECT Almacen, SUM(Ventas) AS Ventas, vWeek, vYear, vCurrentPeriod
+ FROM (
+ SELECT almacen, SUM(Importe) AS Ventas
+ FROM analisis_ventas
+ WHERE vYear = Año
+ AND vWeek = Semana
+ GROUP BY almacen
+ UNION ALL
+ SELECT almacen, - SUM(Importe) AS Ventas
+ FROM analisis_ventas
+ WHERE vYear - 1 = Año
+ AND vWeek = Semana
+ GROUP BY almacen
+ UNION ALL
+ SELECT Almacen, Ventas
+ FROM analisis_ventas_almacen_evolution
+ WHERE Periodo = vPreviousPeriod
+ ) sub
+ GROUP BY Almacen;
+ END WHILE;
+
+ -- Reino
+
+ SET vCurrentPeriod = vMinPeriod;
+
+ WHILE vCurrentPeriod < vMaxPeriod
+ DO
+ SELECT MAX(periodo) INTO vPreviousPeriod
+ FROM analisis_ventas_reino_evolution
+ WHERE periodo < vMaxPeriod;
+
+ SELECT MIN(period) INTO vCurrentPeriod
+ FROM vn2008.time
+ WHERE period > vPreviousPeriod;
+
+ SET vYear = FLOOR(vCurrentPeriod / 100);
+ SET vWeek = vCurrentPeriod - (vYear * 100);
+
+ DELETE FROM analisis_ventas_reino_evolution
+ WHERE Periodo = vCurrentPeriod;
+
+ REPLACE analisis_ventas_reino_evolution(reino, ventas, semana,año, periodo)
+ SELECT reino, SUM(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
+ FROM (
+ SELECT Reino, SUM(Importe) AS ventas
+ FROM analisis_ventas
+ WHERE vYear = Año
+ AND vWeek = Semana
+ GROUP BY Reino
+ UNION ALL
+ SELECT Reino, - SUM(Importe) AS ventas
+ FROM analisis_ventas
+ WHERE vYear - 1 = Año
+ AND vWeek = Semana
+ GROUP BY Reino
+ UNION ALL
+ SELECT reino, ventas
+ FROM analisis_ventas_reino_evolution
+ WHERE Periodo = vPreviousPeriod
+ ) sub
+ GROUP BY reino;
+ END WHILE;
+
+ -- Provincia
+
+ SET vCurrentPeriod = vMinPeriod;
+
+ WHILE vCurrentPeriod < vMaxPeriod
+ DO
+ SELECT MAX(periodo) INTO vPreviousPeriod
+ FROM analisis_ventas_provincia_evolution
+ WHERE periodo < vMaxPeriod;
+
+ SELECT MIN(period) INTO vCurrentPeriod
+ FROM vn2008.time
+ WHERE period > vPreviousPeriod;
+
+ SET vYear = FLOOR(vCurrentPeriod / 100);
+ SET vWeek = vCurrentPeriod - (vYear * 100);
+
+ DELETE FROM analisis_ventas_provincia_evolution
+ WHERE Periodo = vCurrentPeriod;
+
+ REPLACE analisis_ventas_provincia_evolution(provincia, countryCode, ventas, semana,año, periodo)
+ SELECT Provincia, code, SUM(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
+ FROM (
+ SELECT a.Provincia, c.code, SUM(a.Importe) AS ventas
+ FROM analisis_ventas a
+ JOIN vn.province p ON p.name= a.provincia
+ JOIN vn.country c ON c.id = p.countryFk
+ WHERE vYear = a.Año
+ AND vWeek = a.Semana
+ GROUP BY a.Provincia
+ UNION ALL
+ SELECT a.Provincia, c.code, - SUM(a.Importe) AS ventas
+ FROM analisis_ventas a
+ JOIN vn.province p ON p.name= a.provincia
+ JOIN vn.country c ON c.id = p.countryFk
+ WHERE vYear - 1 = a.Año
+ AND vWeek = a.Semana
+ GROUP BY a.Provincia
+ UNION ALL
+ SELECT a.provincia,a.countryCode, a.ventas
+ FROM analisis_ventas_provincia_evolution a
+ WHERE a.Periodo = vPreviousPeriod
+ ) sub
+ GROUP BY Provincia;
+
+
+ END WHILE;
+
+ -- Vista
+
+ SET vCurrentPeriod = vMinPeriod;
+
+ WHILE vCurrentPeriod < vMaxPeriod
+ DO
+ SELECT MAX(periodo) INTO vPreviousPeriod
+ FROM analisis_ventas_vista_evolution
+ WHERE periodo < vMaxPeriod;
+
+ SELECT MIN(period) INTO vCurrentPeriod
+ FROM vn2008.time
+ WHERE period > vPreviousPeriod;
+
+ SET vYear = FLOOR(vCurrentPeriod / 100);
+ SET vWeek = vCurrentPeriod - (vYear * 100);
+
+ DELETE FROM analisis_ventas_vista_evolution
+ WHERE Periodo = vCurrentPeriod;
+
+ REPLACE analisis_ventas_vista_evolution(vista, ventas, semana,año, periodo)
+ SELECT vista, SUM(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
+ FROM (
+ SELECT Vista, SUM(Importe) AS ventas
+ FROM analisis_ventas
+ WHERE vYear = Año
+ AND vWeek = Semana
+ GROUP BY Vista
+ UNION ALL
+ SELECT Vista, - SUM(Importe) AS ventas
+ FROM analisis_ventas
+ WHERE vYear - 1 = Año
+ AND vWeek = Semana
+ GROUP BY Vista
+ UNION ALL
+ SELECT vista, ventas
+ FROM analisis_ventas_vista_evolution
+ WHERE Periodo = vPreviousPeriod
+ ) sub
+ GROUP BY Vista;
+ END WHILE;
+
+ -- Vendedor
+
+ SET vCurrentPeriod = vMinPeriod;
+
+ WHILE vCurrentPeriod < vMaxPeriod
+ DO
+ SELECT MAX(periodo) INTO vPreviousPeriod
+ FROM analisis_ventas_vendedor_evolution
+ WHERE periodo < vMaxPeriod;
+
+ SELECT MIN(period) INTO vCurrentPeriod
+ FROM vn2008.time
+ WHERE period > vPreviousPeriod;
+
+ SET vYear = FLOOR(vCurrentPeriod / 100);
+ SET vWeek = vCurrentPeriod - (vYear * 100);
+
+ DELETE FROM analisis_ventas_vendedor_evolution
+ WHERE Periodo = vCurrentPeriod;
+
+ REPLACE analisis_ventas_vendedor_evolution(vendedor, ventas, semana,año, periodo)
+ SELECT Comercial AS vendedor, SUM(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
+ FROM (
+ SELECT Comercial, SUM(Importe) AS ventas
+ FROM analisis_ventas
+ WHERE vYear = Año
+ AND vWeek = Semana
+ GROUP BY Comercial
+ UNION ALL
+ SELECT Comercial, - SUM(Importe) AS ventas
+ FROM analisis_ventas
+ WHERE vYear - 1 = Año
+ AND vWeek = Semana
+ GROUP BY Comercial
+ UNION ALL
+ SELECT vendedor, ventas
+ FROM analisis_ventas_vendedor_evolution
+ WHERE Periodo = vPreviousPeriod
+ ) sub
+ GROUP BY vendedor;
+ END WHILE;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_simple` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_simple`()
+BEGIN
+/**
+ * Vacia y rellena la tabla 'analisis_grafico_simple' desde 'analisis_grafico_ventas'
+ */
+ TRUNCATE bi.analisis_grafico_simple;
+
+ INSERT INTO bi.analisis_grafico_simple
+ SELECT *
+ FROM bi.analisis_grafico_ventas;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_update` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_update`()
+BEGIN
+ DECLARE vLastMonth DATE;
+
+ SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE()));
+
+ DELETE FROM analisis_ventas
+ WHERE Año > YEAR(vLastMonth)
+ OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth));
+
+ INSERT INTO analisis_ventas (
+ Familia,
+ Reino,
+ Comercial,
+ Comprador,
+ Provincia,
+ almacen,
+ Año,
+ Mes,
+ Semana,
+ Vista,
+ Importe
+ )
+ SELECT
+ tp.Tipo AS Familia,
+ r.reino AS Reino,
+ tr.CodigoTrabajador AS Comercial,
+ tr2.CodigoTrabajador AS Comprador,
+ p.name AS Provincia,
+ w.name AS almacen,
+ tm.year AS Año,
+ tm.month AS Mes,
+ tm.week AS Semana,
+ dm.description AS Vista,
+ bt.importe AS Importe
+ FROM bs.ventas bt
+ LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id
+ LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id
+ LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente
+ LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador
+ LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador
+ JOIN vn2008.time tm ON tm.date = bt.fecha
+ JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento
+ LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
+ JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
+ LEFT JOIN vn.deliveryMethod dm ON dm.id = a.Vista
+ LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna
+ LEFT JOIN vn2008.province p ON p.province_id = cs.province_id
+ LEFT JOIN vn.warehouse w ON w.id = t.warehouse_id
+ WHERE bt.fecha >= vLastMonth AND r.mercancia;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `claim_ratio_routine` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `claim_ratio_routine`()
+BEGIN
+ DECLARE vMonthToRefund INT DEFAULT 4;
+
+ /*
+ * PAK 2015-11-20
+ * Se trata de añadir a la tabla Greuges todos los
+ * cargos que luego vamos a utilizar para calcular el recobro
+ */
+
+ -- Reclamaciones demasiado sensibles
+
+ INSERT INTO vn.greuge(shipped, clientFk, description,
+ amount, greugeTypeFk, ticketFk)
+ SELECT cm.Fecha
+ , cm.Id_Cliente
+ , concat('Claim ',cm.id,' : ', m.Concepte)
+ ,round( -1 * ((sensib -1)/4) * Cantidad *
+ Preu * (100 - Descuento) / 100, 2) AS Reclamaciones
+ , 4
+ , m.Id_Ticket
+ FROM vn2008.Movimientos m
+ JOIN vn2008.cl_act ca USING(Id_Movimiento)
+ JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
+ WHERE ca.cl_sol_id NOT IN (1,5)
+ AND ca.greuge = 0
+ AND cm.cl_est_id = 3;
+
+ -- Reclamaciones que pasan a Maná
+
+ INSERT INTO vn.greuge(shipped, clientFk, description,
+ amount, greugeTypeFk, ticketFk)
+ SELECT cm.Fecha
+ , cm.Id_Cliente
+ , concat('Claim_mana ',cm.id,' : ', m.Concepte)
+ ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2)
+ AS Reclamaciones
+ ,3
+ ,m.Id_Ticket
+ FROM vn2008.Movimientos m
+ JOIN vn2008.cl_act ca USING(Id_Movimiento)
+ JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
+ WHERE ca.cl_sol_id NOT IN (1,5)
+ AND ca.greuge = 0
+ AND cm.cl_est_id = 3
+ AND cm.mana;
+
+ -- Marcamos para no repetir
+ UPDATE vn2008.cl_act ca
+ JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
+ SET greuge = 1
+ WHERE ca.cl_sol_id NOT IN (1,5)
+ AND ca.greuge = 0
+ AND cm.cl_est_id = 3;
+
+ -- Recobros
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
+ CREATE TEMPORARY TABLE tmp.ticket_list
+ (PRIMARY KEY (Id_Ticket))
+ SELECT DISTINCT t.Id_Ticket
+ FROM vn2008.Movimientos_componentes mc
+ JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento
+ JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
+ JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket
+ JOIN vn.ticketTracking tt ON tt.id = ts.inter_id
+ JOIN vn2008.state s ON s.id = tt.stateFk
+ WHERE mc.Id_Componente = 17
+ AND mc.greuge = 0
+ AND t.Fecha >= '2016-10-01'
+ AND t.Fecha < util.VN_CURDATE()
+ AND s.alert_level >= 3;
+
+ DELETE g.*
+ FROM vn.greuge g
+ JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket
+ WHERE g.greugeTypeFk = 2;
+
+ INSERT INTO vn.greuge(clientFk, description, amount,shipped,
+ greugeTypeFk, ticketFk)
+ SELECT Id_Cliente
+ ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2)
+ AS dif
+ ,date(t.Fecha)
+ , 2
+ ,tt.Id_Ticket
+ FROM vn2008.Movimientos m
+ JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
+ JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket
+ JOIN vn2008.Movimientos_componentes mc
+ ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17
+ GROUP BY t.Id_Ticket
+ HAVING ABS(dif) > 1;
+
+ UPDATE vn2008.Movimientos_componentes mc
+ JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento
+ JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket
+ SET greuge = 1
+ WHERE Id_Componente = 17;
+
+ /*
+ * Recalculamos la ratio de las reclamaciones, que luego
+ * se va a utilizar en el recobro
+ */
+
+ REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro)
+ SELECT Id_Cliente, 0,0,0,0
+ FROM vn2008.Clientes;
+
+ REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro)
+ SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones,
+ round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0
+ FROM bi.facturacion_media_anual fm
+ LEFT JOIN(
+ SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) *
+ Cantidad * Preu * (100 - Descuento) / 100))
+ AS Reclamaciones
+ FROM vn2008.Movimientos m
+ JOIN vn2008.cl_act ca
+ ON ca.Id_Movimiento = m.Id_Movimiento
+ JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
+ WHERE ca.cl_sol_id NOT IN (1,5)
+ AND cm.cl_est_id = 3
+ AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, util.VN_CURDATE())
+ GROUP BY cm.Id_Cliente
+ ) claims ON claims.Id_Cliente = fm.Id_Cliente;
+
+
+ -- Calculamos el porcentaje del recobro para añadirlo al precio de venta
+ UPDATE bi.claims_ratio cr
+ JOIN (
+ SELECT clientFk Id_Cliente, IFNULL(SUM(amount), 0) AS Greuge
+ FROM vn.greuge
+ WHERE shipped <= util.VN_CURDATE()
+ GROUP BY clientFk
+ ) g ON g.Id_Cliente = cr.Id_Cliente
+ SET recobro = GREATEST(0,round(IFNULL(Greuge, 0) /
+ (IFNULL(Consumo, 0) * vMonthToRefund / 12 ) ,3));
+
+ -- Protección neonatos
+ UPDATE bi.claims_ratio cr
+ JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente
+ SET recobro = 0, Ratio = 0
+ WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,util.VN_CURDATE());
+
+ -- CLIENTE 7983, JULIAN SUAU
+ UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983;
+
+ -- CLIENTE 4358
+ UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358;
+
+ -- CLIENTE 5523, VERDECORA
+ UPDATE bi.claims_ratio SET recobro = GREATEST(0.12, recobro) WHERE Id_Cliente = 5523;
+
+ -- CLIENTE 15979, SERVEIS VETERINARIS
+ UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979;
+
+ -- CLIENTE 5189 i 8942, son de CSR i son el mateix client
+ UPDATE bi.claims_ratio cr
+ JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro
+ FROM bi.claims_ratio
+ WHERE Id_Cliente IN ( 5189,8942)
+ ) sub
+ SET cr.recobro = sub.recobro
+ WHERE Id_Cliente IN ( 5189,8942);
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `clean` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
+BEGIN
+ DECLARE vDateShort DATETIME;
+ DECLARE vDateLong DATETIME;
+ DECLARE vOneYearAgo DATETIME;
+
+ SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE());
+ SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE());
+ SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE());
+
+ DELETE FROM bi.Greuge_Evolution
+ WHERE (Fecha < vDateShort AND weekday(Fecha) != 1)
+ OR Fecha < vOneYearAgo;
+
+ DELETE FROM bi.defaulters WHERE `date` < vDateLong;
+ DELETE FROM bi.defaulting WHERE `date` < vDateLong;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `clean_launcher` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `clean_launcher`()
+BEGIN
+/**
+ * Borra registros de las principales tablas (excepto de "ticket").
+ */
+ CALL vn2008.clean(0);
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `comparativa_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `comparativa_add`()
+BEGIN
+ DECLARE lastCOMP INT; # Se trata de una variable para almacenar el ultimo valor del Periodo
+ DECLARE vMaxPeriod INT;
+ DECLARE vMaxWeek INT;
+
+ SELECT t.period, t.`week` INTO vMaxPeriod, vMaxWeek
+ FROM vn.`time` t
+ WHERE t.dated = util.VN_CURDATE();
+
+ SELECT MAX(Periodo) INTO lastCOMP FROM vn2008.Comparativa;
+ -- Fijaremos las ventas con más de un mes de antiguedad en la tabla Comparativa
+
+ IF lastCOMP < vMaxPeriod - 3 AND vMaxWeek > 3 THEN
+
+ REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price)
+ SELECT tm.period as Periodo, m.Id_Article, t.warehouse_id, sum(m.Cantidad), sum(v.importe)
+ FROM bs.ventas v
+ JOIN vn2008.time tm ON tm.date = v.fecha
+ JOIN vn2008.Movimientos m ON m.Id_Movimiento = v.Id_Movimiento
+ JOIN vn2008.Tipos tp ON tp.tipo_id = v.tipo_id
+ JOIN vn2008.reinos r ON r.id = tp.reino_id
+ JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
+ WHERE tm.period BETWEEN lastCOMP AND vMaxPeriod - 3
+ AND t.Id_Cliente NOT IN(400,200)
+ AND t.warehouse_id NOT IN (0,13)
+ GROUP BY m.Id_Article, Periodo, t.warehouse_id;
+
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `comparativa_add_manual` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `comparativa_add_manual`(IN vStarted DATE, IN vEnded DATE)
+BEGIN
+/**
+ * Recalcula la tabla Comparativa para dos valores dados
+ *
+ * @param vStarted fecha desde
+ * @param vEnded fecha hasta
+ */
+
+ DECLARE periodStart INT;
+ DECLARE periodEnd INT;
+
+ -- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar
+
+ SELECT t.period INTO periodStart
+ FROM vn.`time` t
+ WHERE t.dated = vStarted;
+
+ SELECT t.period INTO periodEnd
+ FROM vn.`time` t
+ WHERE t.dated = vEnded;
+
+ DELETE FROM vn2008.Comparativa
+ WHERE Periodo BETWEEN periodStart AND periodEnd;
+
+ INSERT INTO vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price)
+ SELECT tm.period as Periodo, m.Id_Article, t.warehouse_id, sum(m.Cantidad), sum(v.importe)
+ FROM bs.ventas v
+ JOIN vn2008.time tm ON tm.date = v.fecha
+ JOIN vn2008.Movimientos m ON m.Id_Movimiento = v.Id_Movimiento
+ JOIN vn2008.Tipos tp ON tp.tipo_id = v.tipo_id
+ JOIN vn2008.reinos r ON r.id = tp.reino_id
+ JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
+ WHERE tm.period BETWEEN periodStart AND periodEnd
+ AND t.Id_Cliente NOT IN(400,200)
+ AND t.warehouse_id NOT IN (0,13)
+ GROUP BY m.Id_Article, Periodo, t.warehouse_id;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `defaultersFromDate` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `defaultersFromDate`(IN vDate DATE)
+BEGIN
+
+ SELECT t1.*, c.Cliente, w.code AS workerCode, c.pay_met_id,c.Vencimiento
+ FROM (
+ -- Filtramos aquellos clientes cuyo saldo se ha incrementado de ayer a hoy
+ select * from(
+ select today.client, today.amount todayAmount, yesterday.amount yesterdayAmount, round(yesterday.amount - today.amount,2) as difference, defaulterSince
+ from
+ (select client, amount, defaulterSince
+ from defaulters
+ where date = vDate and hasChanged) today
+ join
+ (select client, amount
+ from defaulters
+ where date = TIMESTAMPADD(DAY,-1,vDate)) yesterday using(client)
+
+ having today.amount > 0 and difference <> 0
+ ) newDefaulters
+ )t1 left join vn2008.Clientes c ON t1.client = c.Id_Cliente
+ left join vn.worker w ON w.id = c.Id_Trabajador;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `defaulting` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `defaulting`(IN `vDate` DATE)
+BEGIN
+ DECLARE vDone BOOLEAN;
+ DECLARE vClient INT;
+ DECLARE vAmount INT;
+ DECLARE vDued DATE;
+ DECLARE vAmountInvoice DECIMAL(10,2);
+ DECLARE vGraceDays INT;
+ DECLARE defaulters CURSOR FOR
+ SELECT client, amount, graceDays FROM bi.defaulters d
+ JOIN vn2008.Clientes c ON c.Id_Cliente = d.client
+ JOIN vn2008.pay_met pm ON pm.id = c.pay_met_id
+ WHERE hasChanged AND date = vDate;
+
+ DECLARE invoices CURSOR FOR
+ SELECT dued Vencimiento, amount importe FROM vn.invoiceOut
+ WHERE issued >= '2016-01-01' AND clientFk = vClient ORDER BY issued DESC;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DELETE FROM bi.defaulters WHERE date = vDate;
+
+ INSERT INTO bi.defaulters(client, date, amount)
+ SELECT c.id, vDate, IFNULL(FLOOR(SUM(cro.amount)),0) AS amount
+ FROM vn.`client` c
+ LEFT JOIN bi.customerRiskOverdue cro ON c.id = cro.customer_id
+ GROUP BY c.id;
+
+ -- marcamos si ha cambiado y heredamos la fecha defaulterSince
+ UPDATE bi.defaulters d
+ LEFT JOIN (
+ SELECT * FROM(
+ SELECT client, amount , defaulterSince, frozened FROM bi.defaulters
+ WHERE date <= TIMESTAMPADD(DAY,-1, vDate)
+ ORDER BY date DESC
+ LIMIT 10000000000000000000) t GROUP BY client
+ ) yesterday using(client)
+ SET d.hasChanged = (IFNULL(d.amount,0) <> IFNULL(yesterday.amount,0)),
+ d.defaulterSince = yesterday.defaulterSince,
+ d.frozened = yesterday.frozened
+ WHERE d.date = vDate ;
+
+ OPEN defaulters;
+ defaulters: LOOP
+ SET vDone = FALSE;
+ SET vAmount = 0;
+ FETCH defaulters INTO vClient,vAmount, vGraceDays;
+ IF vDone THEN
+ LEAVE defaulters;
+ END IF;
+ OPEN invoices;
+ invoices:LOOP
+
+ FETCH invoices INTO vDued, vAmountInvoice;
+ IF vDone THEN
+ LEAVE invoices;
+ END IF;
+
+ IF TIMESTAMPADD(DAY, vGraceDays, vDued) <= vDate THEN
+ SET vAmount = vAmount - vAmountInvoice;
+ IF vAmount <= 0 THEN
+
+ UPDATE defaulters SET defaulterSince = vDued
+ WHERE client = vClient and date = vDate;
+
+ SET vAmount = 0;
+ LEAVE invoices;
+ END IF;
+ END IF;
+ END LOOP;
+ CLOSE invoices;
+ END LOOP;
+ CLOSE defaulters;
+
+ DELETE FROM defaulters
+ WHERE amount = 0
+ AND hasChanged = FALSE
+ AND `date` = vDate;
+
+ UPDATE defaulters d
+ JOIN vn.config ON TRUE
+ SET d.frozened = NULL
+ WHERE `date` = vDate
+ AND d.amount <= config.defaultersMaxAmount;
+
+ CALL vn.clientFreeze();
+
+ -- actualizamos defaulting
+ DELETE FROM bi.defaulting WHERE date = vDate;
+
+ INSERT INTO bi.defaulting(date, amount)
+ SELECT vDate, SUM(amount)
+ FROM bi.defaulters
+ WHERE date = vDate and amount > 0;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `defaulting_launcher` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `defaulting_launcher`()
+BEGIN
+/**
+ * Calcula la morosidad de los clientes.
+ */
+ CALL bi.defaulting(util.VN_CURDATE());
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `facturacion_media_anual_update` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `facturacion_media_anual_update`()
+BEGIN
+ TRUNCATE TABLE bs.clientAnnualConsumption;
+
+ REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo)
+ SELECT clientFk, avg(Facturacion)
+ FROM (
+ SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion
+ FROM vn.invoiceOut
+ WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE())
+ GROUP BY clientFk, year, month
+ ) vol
+ GROUP BY clientFk;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `greuge_dif_porte_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `greuge_dif_porte_add`()
+BEGIN
+ DECLARE datSTART DATETIME DEFAULT TIMESTAMPADD(DAY,-60,util.VN_CURDATE()); -- '2019-07-01'
+ DECLARE datEND DATETIME DEFAULT TIMESTAMPADD(DAY,-1,util.VN_CURDATE());
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.dp;
+
+ -- Agencias que no cobran por volumen
+ CREATE TEMPORARY TABLE tmp.dp
+ (PRIMARY KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT t.id ticketFk,
+ SUM((t.zonePrice - t.zoneBonus) * ebv.ratio) AS teorico,
+ 00000.00 as practico,
+ 00000.00 as greuge,
+ t.clientFk,
+ t.shipped
+ FROM
+ vn.ticket t
+ JOIN vn2008.Clientes cli ON cli.Id_cliente = t.clientFk
+ LEFT JOIN vn.expedition e ON e.ticketFk = t.id
+ JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
+ JOIN vn.zone z ON t.zoneFk = z.id
+ WHERE
+ t.shipped between datSTART AND datEND
+ AND cli.`real`
+ AND t.companyFk IN (442 , 567)
+ AND z.isVolumetric = FALSE
+ GROUP BY t.id;
+
+ -- Agencias que cobran por volumen
+ INSERT INTO tmp.dp
+ SELECT sv.ticketFk,
+ SUM(IFNULL(sv.freight,0)) AS teorico,
+ 00000.00 as practico,
+ 00000.00 as greuge,
+ sv.clientFk,
+ sv.shipped
+ FROM vn.saleVolume sv
+ JOIN vn.zone z ON z.id = sv.zoneFk
+ AND sv.shipped BETWEEN datSTART AND datEND
+ AND z.isVolumetric != FALSE
+ GROUP BY sv.ticketFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.dp_aux;
+
+ CREATE TEMPORARY TABLE tmp.dp_aux
+ (PRIMARY KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT dp.ticketFk, sum(Cantidad * Valor) as valor
+ FROM tmp.dp
+ JOIN vn2008.Movimientos m ON m.Id_Ticket = dp.ticketFk
+ JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento)
+ WHERE mc.Id_Componente = 15
+ GROUP BY dp.ticketFk;
+
+ UPDATE tmp.dp
+ JOIN tmp.dp_aux USING(ticketFk)
+ SET practico = IFNULL(valor,0);
+
+ DROP TEMPORARY TABLE tmp.dp_aux;
+
+ CREATE TEMPORARY TABLE tmp.dp_aux
+ (PRIMARY KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT dp.ticketFk, sum(g.amount) Importe
+ FROM tmp.dp
+ JOIN vn.greuge g ON g.ticketFk = dp.ticketFk
+ WHERE g.greugeTypeFk = 1 -- dif_porte
+ GROUP BY dp.ticketFk;
+
+ UPDATE tmp.dp
+ JOIN tmp.dp_aux USING(ticketFk)
+ SET greuge = IFNULL(Importe,0);
+
+ INSERT INTO vn.greuge (clientFk,description,amount,shipped,greugeTypeFk,ticketFk)
+ SELECT dp.clientFk
+ , concat('dif_porte ', dp.ticketFk)
+ , round(IFNULL(dp.teorico,0) - IFNULL(dp.practico,0) - IFNULL(dp.greuge,0),2) as Importe
+ , date(dp.shipped)
+ , 1
+ ,dp.ticketFk
+ FROM tmp.dp
+ JOIN vn.client c ON c.id = dp.clientFk
+ WHERE ABS(IFNULL(dp.teorico,0) - IFNULL(dp.practico,0) - IFNULL(dp.greuge,0)) > 1
+ AND c.isRelevant;
+
+ DROP TEMPORARY TABLE
+ tmp.dp,
+ tmp.dp_aux;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `Greuge_Evolution_Add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `Greuge_Evolution_Add`()
+BEGIN
+/*
+ Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente,
+ así como las ventas acumuladas en los ultimos 365 dias, para poder controlar
+ su evolucion.
+*/
+ DECLARE datFEC DATE;
+ DECLARE datFEC_TOMORROW DATE;
+ DECLARE datFEC_LASTYEAR DATE;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
+
+ GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT;
+ SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'));
+ CALL vn.mail_insert(
+ 'jgallego@verdnatura.es,pako@verdnatura.es',
+ 'noreply@verdnatura.es',
+ 'Greuge_Evolution_Add',
+ CONCAT('ERROR ', IFNULL(@errno, 0), ': ', ifnull(@text, 'texto'))
+ );
+
+ END;
+
+ SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
+
+ DELETE FROM bi.Greuge_Evolution WHERE Fecha >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE());
+
+ SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)),
+ TIMESTAMPADD(DAY,2,MAX(Fecha))
+ INTO datFEC,
+ datFEC_TOMORROW
+ FROM bi.Greuge_Evolution;
+
+ SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC);
+
+ DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC;
+
+ DROP TEMPORARY TABLE IF EXISTS maxInvoice;
+
+ CREATE TEMPORARY TABLE maxInvoice
+ (PRIMARY KEY (Id_Cliente))
+ ENGINE = MEMORY
+ SELECT DISTINCT clientFk Id_Cliente, max(issued) as maxFecha
+ FROM vn.invoiceOut
+ GROUP BY clientFk
+ HAVING maxFecha < timestampadd(month,-2,datFEC);
+
+ WHILE datFEC < util.VN_CURDATE() DO
+
+ REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil)
+
+ SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0
+ FROM (
+ SELECT clientFk Id_Cliente, sum(amount) as Greuge
+ FROM vn.greuge
+ where shipped <= datFEC
+ group by clientFk
+ ) sub
+ RIGHT JOIN
+
+ (
+
+ SELECT Id_Cliente, sum(Ventas) as Ventas
+ FROM
+ (
+
+ SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas
+ FROM bs.ventas
+ WHERE fecha = datFEC or fecha = datFEC_LASTYEAR
+
+ UNION ALL
+
+ SELECT Id_Cliente, Ventas
+ FROM bi.Greuge_Evolution
+ WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC)
+
+ ) sub
+ group by Id_Cliente
+
+ ) v using(Id_Cliente)
+ ;
+
+ -- Ahora calcularemos el greuge muerto
+ UPDATE bi.Greuge_Evolution ge
+ JOIN maxInvoice m using(Id_Cliente)
+ SET FOSIL = GREUGE
+ WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha);
+
+ -- Recobro
+ UPDATE bi.Greuge_Evolution ge
+ JOIN (
+ SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe
+ FROM vn2008.Tickets t
+ JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna
+ JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket
+ JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento
+ WHERE t.Fecha >= datFEC
+ AND t.Fecha < datFEC_TOMORROW
+ AND mc.Id_Componente = 17 -- Recobro
+ GROUP BY cs.Id_Cliente
+ ) sub using(Id_Cliente)
+ SET Recobro = Importe
+ WHERE ge.Fecha = datFEC;
+
+ SET datFEC = datFEC_TOMORROW;
+ SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW);
+ SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC);
+
+ END WHILE;
+
+ DROP TEMPORARY TABLE IF EXISTS maxInvoice;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `nigthlyAnalisisVentas` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `nigthlyAnalisisVentas`()
+BEGIN
+ CALL analisis_ventas_update;
+ CALL analisis_ventas_simple;
+ CALL analisis_ventas_evolution_add;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `rutasAnalyze` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `rutasAnalyze`(
+ vDatedFrom DATE,
+ vDatedTo DATE
+)
+BEGIN
+/**
+ * Analiza los costes de las rutas de reparto
+ * y lo almacena en la tabla bi.rutasBoard
+ */
+ DELETE FROM rutasBoard
+ WHERE Fecha BETWEEN vDatedFrom AND vDatedTo;
+
+ -- Rellenamos la tabla con los datos de las rutas VOLUMETRICAS, especialmente con los bultos "virtuales"
+ INSERT INTO rutasBoard(
+ Id_Ruta,
+ Id_Agencia,
+ Fecha,
+ bultos)
+ SELECT r.id,
+ r.agencyModeFk,
+ r.created,
+ SUM(sv.volume / ebv.m3)
+ FROM vn.route r
+ JOIN vn.ticket t ON t.routeFk = r.id
+ LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
+ JOIN vn.saleVolume sv ON sv.ticketFk = t.id
+ JOIN vn.expeditionBoxVol ebv ON ebv.code = 'transportBox'
+ WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ AND z.isVolumetric
+ GROUP BY r.id;
+
+ -- Rellenamos la tabla con los datos de las rutas NO VOLUMETRICAS, especialmente con los bultos "virtuales"
+ INSERT INTO rutasBoard(
+ Id_Ruta,
+ Id_Agencia,
+ Fecha,
+ Bultos)
+ SELECT r.id,
+ r.agencyModeFk,
+ r.created,
+ SUM(t.packages)
+ FROM vn.route r
+ JOIN vn.ticket t ON t.routeFk = r.id
+ LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
+ WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ AND NOT z.isVolumetric
+ GROUP BY r.id
+ ON DUPLICATE KEY UPDATE Bultos = Bultos + VALUES(Bultos);
+
+ -- Coste PRACTICO de cada bulto, de acuerdo con los componentes de tipo AGENCIA en cada linea de venta
+ UPDATE rutasBoard r
+ JOIN (
+ SELECT t.routeFk,
+ SUM(s.quantity * sc.value) totalPractice
+ FROM vn.route r
+ JOIN vn.ticket t ON t.routeFk = r.id
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.saleComponent sc ON sc.saleFk = s.id
+ JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk
+ WHERE ct.code = 'FREIGHT'
+ AND r.created BETWEEN vDatedFrom AND vDatedTo
+ GROUP BY r.id
+ ) sub ON sub.routeFk = r.Id_Ruta
+ SET r.practico = IFNULL(sub.totalPractice / r.Bultos, 0);
+
+ -- Coste TEORICO de una caja "virtual" para cada ruta, teniendo en cuenta que hay carros, pallets, etc
+ UPDATE rutasBoard r
+ JOIN (
+ SELECT t.routeFk,
+ SUM(t.zonePrice/ ebv.ratio) / COUNT(*) averageTheoreticalVolume
+ FROM vn.ticket t
+ JOIN vn.route r ON r.id = t.routeFk
+ JOIN vn.expedition e ON e.ticketFk = t.id
+ JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
+ JOIN vn.address ad ON ad.id = t.addressFk
+ JOIN vn.client c ON c.id = ad.clientFk
+ LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
+ WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ AND NOT z.isVolumetric
+ GROUP BY t.routeFk
+ ) sub ON r.Id_Ruta = sub.routeFk
+ SET r.teorico = IFNULL(sub.averageTheoreticalVolume, 0);
+
+ -- Coste VOLUMETRICO TEORICO de una caja "virtual" para cada ruta
+ UPDATE rutasBoard r
+ JOIN (
+ SELECT t.routeFk,
+ SUM(freight) averageTheoreticalVolume
+ FROM vn.ticket t
+ JOIN vn.route r ON r.id = t.routeFk
+ JOIN vn.saleVolume sf ON sf.ticketFk = t.id
+ JOIN vn.client c ON c.id = t.clientFk
+ JOIN vn.`zone` z ON z.id = t.zoneFk
+ WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ AND z.isVolumetric
+ GROUP BY t.routeFk
+ ) sub ON r.Id_Ruta = sub.routeFk
+ SET r.teorico = IFNULL(sub.averageTheoreticalVolume / r.Bultos, 0);
+
+ -- La diferencia entre el teorico y el practico se deberia de cobrar en greuges, cada noche
+ UPDATE rutasBoard r
+ JOIN (
+ SELECT t.routeFk,
+ SUM(g.amount) greuge
+ FROM vn.ticket t
+ JOIN vn.route r ON r.id = t.routeFk
+ JOIN vn.greuge g ON g.ticketFk = t.id
+ JOIN vn.greugeType gt ON gt.id = g.greugeTypeFk
+ WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ AND gt.code = 'freightDifference'
+ GROUP BY t.routeFk
+ ) sub ON r.Id_Ruta = sub.routeFk
+ SET r.greuge = sub.greuge / r.Bultos;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `rutasAnalyze_launcher` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `rutasAnalyze_launcher`()
+BEGIN
+/**
+ * Call rutasAnalyze
+ */
+ CALL rutasAnalyze(util.VN_CURDATE() - INTERVAL 30 DAY , util.VN_CURDATE());
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+
--
-- Current Database: `bs`
--
@@ -2365,6 +4136,21 @@ CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf
USE `bs`;
+--
+-- Temporary table structure for view `VentasPorCliente`
+--
+
+DROP TABLE IF EXISTS `VentasPorCliente`;
+/*!50001 DROP VIEW IF EXISTS `VentasPorCliente`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `VentasPorCliente` AS SELECT
+ 1 AS `Id_Cliente`,
+ 1 AS `VentaBasica`,
+ 1 AS `year`,
+ 1 AS `month` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Temporary table structure for view `bajasLaborales`
--
@@ -2445,13 +4231,13 @@ DROP TABLE IF EXISTS `clientDied`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientDied` (
- `id` int(11) NOT NULL DEFAULT 0,
- `clientName` varchar(50) NOT NULL,
+ `clientFk` int(11) NOT NULL DEFAULT 0,
+ `clientName__` varchar(50) NOT NULL COMMENT '@deprecated 2023-10-15',
`lastInvoiced` date DEFAULT NULL,
- `workerCode` varchar(3) NOT NULL,
- `Boss` varchar(3) NOT NULL,
- `Aviso` varchar(13) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- PRIMARY KEY (`id`)
+ `workerCode__` varchar(3) NOT NULL COMMENT '@deprecated 2023-10-15',
+ `Boss__` varchar(3) NOT NULL COMMENT '@deprecated 2023-10-15',
+ `warning` enum('first','second','third') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ PRIMARY KEY (`clientFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clientes que no han comprado en los ultimos 3 meses, se actualiza con proceso nocturno el 3 de cada mes';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -2469,7 +4255,7 @@ CREATE TABLE `clientDiedPeriod` (
PRIMARY KEY (`id`),
UNIQUE KEY `clientDiedPeriod_UN` (`countryFk`),
CONSTRAINT `clientDiedPeriod_FK` FOREIGN KEY (`countryFk`) REFERENCES `vn`.`country` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define lo que es un periodo para los clientes de los diferentes países';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define lo que es un periodo para los clientes de los diferentes países';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -2489,38 +4275,15 @@ CREATE TABLE `clientNewBorn` (
CONSTRAINT `clientNewBorn_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Listado de clientes que se consideran nuevos a efectos de cobrar la comision adicional del comercial';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `bs`.`clientNewBorn_BEFORE_UPDATE`
- BEFORE UPDATE ON `clientNewBorn`
- FOR EACH ROW
-BEGIN
- -- Si ha pasado un año o mas
- IF TIMESTAMPDIFF(YEAR,NEW.lastShipped, OLD.lastShipped) THEN
- SET NEW.firstShipped = NEW.lastShipped;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
--- Table structure for table `compradores`
+-- Table structure for table `compradores__`
--
-DROP TABLE IF EXISTS `compradores`;
+DROP TABLE IF EXISTS `compradores__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `compradores` (
+CREATE TABLE `compradores__` (
`Id_Trabajador` int(10) unsigned NOT NULL,
`año` int(4) NOT NULL,
`semana` int(2) NOT NULL,
@@ -2614,6 +4377,21 @@ CREATE TABLE `fondo_maniobra` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Temporary table structure for view `horasSilla`
+--
+
+DROP TABLE IF EXISTS `horasSilla`;
+/*!50001 DROP VIEW IF EXISTS `horasSilla`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `horasSilla` AS SELECT
+ 1 AS `Fecha`,
+ 1 AS `Departamento`,
+ 1 AS `Horas`,
+ 1 AS `Salarios` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `indicators`
--
@@ -2675,7 +4453,7 @@ CREATE TABLE `inventoryDiscrepancy` (
`alert` int(11) NOT NULL DEFAULT 0,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='This table collects the discrepancies between theorical inventory and located items';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='This table collects the discrepancies between theorical inventory and located items';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -2695,7 +4473,7 @@ CREATE TABLE `inventoryDiscrepancyDetail` (
`alert` int(11) DEFAULT NULL COMMENT 'alert level for this discrepancy',
PRIMARY KEY (`id`),
UNIQUE KEY `inventoryDiscrepancyDetail_UN` (`warehouseFk`,`itemFk`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Last discrepancies';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Last discrepancies';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -2752,7 +4530,7 @@ CREATE TABLE `m3` (
`dayName` varchar(12) DEFAULT NULL,
`euros` decimal(10,2) DEFAULT 0.00,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -2773,60 +4551,8 @@ CREATE TABLE `nightTask` (
`error` varchar(255) DEFAULT NULL,
`errorCode` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeInsert`
- BEFORE INSERT ON `nightTask`
- FOR EACH ROW
-BEGIN
-
- IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN
-
- CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED');
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeUpdate`
- BEFORE UPDATE ON `nightTask`
- FOR EACH ROW
-BEGIN
-
- IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN
-
- CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED');
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `nightTaskConfig`
@@ -2839,7 +4565,7 @@ CREATE TABLE `nightTaskConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`logMail` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -2876,7 +4602,7 @@ CREATE TABLE `payMethodClient` (
KEY `FkDateClientPayMethod` (`dated`,`clientFk`),
CONSTRAINT `FkClientPayMethod` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FkPayMethodClient` FOREIGN KEY (`payMethodFk`) REFERENCES `vn`.`payMethod` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -2894,7 +4620,7 @@ CREATE TABLE `payMethodClientEvolution` (
`amount` decimal(10,2) NOT NULL,
`equalizationTax` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -2974,17 +4700,17 @@ DROP TABLE IF EXISTS `salesByItemTypeDay`;
CREATE TABLE `salesByItemTypeDay` (
`itemTypeFk` smallint(5) unsigned NOT NULL,
`dated` date NOT NULL,
- `netSale` int(11) NOT NULL DEFAULT 0,
- `stems` int(11) NOT NULL DEFAULT 0,
- `references` int(11) NOT NULL DEFAULT 0,
- `trash` int(11) NOT NULL DEFAULT 0,
- `faults` int(11) NOT NULL DEFAULT 0,
- `claimed` decimal(10,2) NOT NULL DEFAULT 0.00,
- `accepted` decimal(10,2) NOT NULL DEFAULT 0.00,
- `sale` decimal(10,2) NOT NULL DEFAULT 0.00,
- `buy` decimal(10,2) NOT NULL DEFAULT 0.00,
- `costComponent` decimal(10,2) NOT NULL DEFAULT 0.00,
- `marginComponent` decimal(10,2) NOT NULL DEFAULT 0.00,
+ `netSale__` int(11) NOT NULL DEFAULT 0 COMMENT '@deprecated 2023-08-31, Mismo valor que campo sale',
+ `stems` int(11) NOT NULL DEFAULT 0 COMMENT 'Número de tallos vendidos',
+ `references` int(11) NOT NULL DEFAULT 0 COMMENT 'Número de artículos distintos por tipo vendidos',
+ `trash` int(11) NOT NULL DEFAULT 0 COMMENT 'Tallos basura',
+ `faults` int(11) NOT NULL DEFAULT 0 COMMENT 'Tallos faltas',
+ `claimed` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Valor total de reclamaciones',
+ `accepted` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Valor total de reclamaciones aceptadas',
+ `sale` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Ventas totales',
+ `buy` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Valor de compras totales',
+ `costComponent` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Suma de componentes que son valor de compra',
+ `marginComponent` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Suma de componentes que son márgen',
PRIMARY KEY (`itemTypeFk`,`dated`),
KEY `itemTypeSalesByweek_period_idx` (`dated`),
CONSTRAINT `itemTypeSalesByweek_itemTypeFk` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn`.`itemType` (`id`)
@@ -3051,7 +4777,7 @@ CREATE TABLE `salesMonthlySnapshot___` (
`newClientScore` decimal(10,3) DEFAULT NULL,
`teamBossPlus` decimal(10,3) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2022-11';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2022-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -3071,7 +4797,7 @@ CREATE TABLE `salesPersonEvolution` (
PRIMARY KEY (`id`),
KEY `salesPersonEvolution_salesPerson` (`salesPersonFk`),
CONSTRAINT `salesPersonEvolution_salesPerson` FOREIGN KEY (`salesPersonFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Evolución Comerciales';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Evolución Comerciales';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -3150,8 +4876,10 @@ CREATE TABLE `ventas_contables` (
`reino_id` int(10) unsigned NOT NULL,
`tipo_id` smallint(5) unsigned NOT NULL,
`empresa_id` int(4) NOT NULL,
- `gasto` varchar(10) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
- PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`)
+ `gasto` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`,`gasto`),
+ KEY `ventas_contables_expense_FK` (`gasto`),
+ CONSTRAINT `ventas_contables_expense_FK` FOREIGN KEY (`gasto`) REFERENCES `vn`.`expense` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -3196,7 +4924,7 @@ CREATE TABLE `workerLabourDataByMonth` (
`permanent` int(5) NOT NULL COMMENT 'Número de empleados fijos',
PRIMARY KEY (`id`),
KEY `workerLabourDataByMonth_graph_idx` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -3223,7 +4951,7 @@ CREATE TABLE `workerProductivity` (
CONSTRAINT `workerProductivity_FK_1` FOREIGN KEY (`stateFk`) REFERENCES `vn`.`state` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerProductivity_warehouseFk` FOREIGN KEY (`warehouseFk`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerProductivity_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -3238,7 +4966,7 @@ CREATE TABLE `workerProductivityConfig` (
`minSeconsPackager` int(11) DEFAULT NULL,
`minSeconsItemPicker` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -3250,14 +4978,14 @@ DELIMITER ;;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
-/*!50003 SET character_set_client = utf8mb4 */ ;;
-/*!50003 SET character_set_results = utf8mb4 */ ;;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;;
+/*!50003 SET character_set_client = utf8mb3 */ ;;
+/*!50003 SET character_set_results = utf8mb3 */ ;;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clientDied_recalc` ON SCHEDULE EVERY 1 DAY STARTS '2023-06-01 03:00:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO BEGIN
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clientDied_recalc` ON SCHEDULE EVERY 1 DAY STARTS '2023-06-01 03:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
DECLARE vDone INT DEFAULT FALSE;
DECLARE vCountryFk INT;
DECLARE vDays INT;
@@ -3295,7 +5023,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `inventoryDiscrepancy_launch` ON SCHEDULE EVERY 15 MINUTE STARTS '2023-07-18 00:00:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL bs.inventoryDiscrepancyDetail_replace() */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `inventoryDiscrepancy_launch` ON SCHEDULE EVERY 15 MINUTE STARTS '2023-07-18 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL bs.inventoryDiscrepancyDetail_replace() */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -3313,7 +5041,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2022-02-08 04:14:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL bs.nightTask_launchAll */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2022-02-08 04:14:00' ON COMPLETION PRESERVE ENABLE DO CALL bs.nightTask_launchAll */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -3341,11 +5069,11 @@ BEGIN
DECLARE vTramo VARCHAR(20);
DECLARE vHour INT;
-
+
SET vHour = HOUR(vDateTime) ;
-
+
SET vTramo =
- CASE
+ CASE
WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana'
WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde'
END ;
@@ -3373,7 +5101,7 @@ BEGIN
* Inserta en la tabla bancos_evolution los saldos acumulados de cada banco
*
* @param vStartingDate Fecha desde la cual se recalculan la tabla bs.bancos_evolution
- */
+ */
DECLARE vCurrentDate DATE;
DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, util.VN_CURDATE());
IF IFNULL(vStartingDate,0) < TIMESTAMPADD(YEAR, -5, util.VN_CURDATE()) THEN
@@ -3387,49 +5115,49 @@ BEGIN
SELECT vCurrentDate, Id_Banco, deuda
FROM bs.bancos_evolution
WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate);
-
+
WHILE vCurrentDate < vMaxDate DO
-- insertar solo el dia de ayer
INSERT INTO bs.bancos_evolution(Fecha ,Id_Banco, saldo)
- SELECT vCurrentDate, Id_Banco, SUM(saldo)
+ SELECT vCurrentDate, Id_Banco, SUM(saldo)
FROM (
SELECT Id_Banco ,saldo
FROM bs.bancos_evolution
WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior
UNION ALL
-
+
SELECT c.Id_Banco, IFNULL(SUM(Entrada),0) - IFNULL(SUM(Salida),0) as saldo
FROM vn2008.Cajas c
JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas
- JOIN vn.accountingType at2 ON at2.id = b.cash
+ JOIN vn.accountingType at2 ON at2.id = b.cash
WHERE at2.code IN ('wireTransfer','fundingLine')
AND Cajafecha = vCurrentDate
AND (Serie = 'MB' OR at2.code = 'fundingLine')
GROUP BY Id_Banco
- )sub
+ )sub
GROUP BY Id_Banco
ON DUPLICATE KEY UPDATE saldo = saldo + VALUES(saldo);
-
+
SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate);
END WHILE;
- -- Ahora actualizamos la quilla
+ -- Ahora actualizamos la quilla
UPDATE bs.bancos_evolution be
JOIN
(
SELECT bp.Id_Banco, - sum(bp.importe) as quilla, t.dated
- FROM vn.time t
+ FROM vn.time t
JOIN vn2008.Bancos_poliza bp ON t.dated between apertura AND IFNULL(cierre, t.dated)
WHERE t.dated BETWEEN vStartingDate AND vMaxDate
GROUP BY Id_Banco, t.dated
) sub ON be.Id_Banco = sub.Id_Banco AND sub.dated = be.Fecha
- SET be.quilla = sub.quilla;
+ SET be.quilla = sub.quilla;
-- pagos futuros no concilidados
INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo)
SELECT t.dated, p.id_banco, - importe
- FROM vn.time t
+ FROM vn.time t
join vn2008.pago p ON p.fecha <= t.dated
WHERE t.dated BETWEEN util.VN_CURDATE() AND vMaxDate
AND p.fecha BETWEEN util.VN_CURDATE() AND vMaxDate
@@ -3439,7 +5167,7 @@ BEGIN
-- cobros futuros
INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo)
SELECT t.dated, r.Id_Banco, SUM(Entregado)
- FROM vn.time t
+ FROM vn.time t
JOIN vn2008.Recibos r ON r.Fechacobro <= t.dated
WHERE r.Fechacobro > util.VN_CURDATE() AND r.Fechacobro <= vMaxDate
AND t.dated BETWEEN util.VN_CURDATE() AND vMaxDate
@@ -3449,10 +5177,10 @@ BEGIN
-- saldos de la tabla prevision
INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo)
SELECT t.dated, sp.Id_Banco, SUM(Importe)
- FROM vn.time t
+ FROM vn.time t
JOIN vn2008.Saldos_Prevision sp ON sp.Fecha <= t.dated
JOIN vn2008.Bancos b ON sp.Id_Banco = b.Id_Banco
- JOIN vn.accountingType at2 ON at2.id = b.cash
+ JOIN vn.accountingType at2 ON at2.id = b.cash
WHERE at2.code IN ('wireTransfer','fundingLine')
AND t.dated BETWEEN vStartingDate AND vMaxDate
GROUP BY t.dated, sp.Id_Banco
@@ -3466,12 +5194,12 @@ BEGIN
-- Deuda
UPDATE bs.bancos_evolution be
JOIN vn2008.Bancos b using(Id_Banco)
- JOIN vn.accountingType at2 ON at2.id = b.cash
+ JOIN vn.accountingType at2 ON at2.id = b.cash
SET be.deuda = IF(at2.code = 'fundingLine', be.saldo_aux, 0)
, be.saldo = IF(at2.code = 'fundingLine', 0, be.saldo_aux)
WHERE Fecha >= vStartingDate;
- -- Liquidez
+ -- Liquidez
update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate;
-- Disponibilidad
update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate;
@@ -3494,14 +5222,14 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE)
BEGIN
- SELECT
- workerName,
- id,
- name,
- CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount,
- CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount
+ SELECT
+ workerName,
+ id,
+ name,
+ CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount,
+ CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount
FROM (
- (SELECT
+ (SELECT
CONCAT(w.firstname, ' ', w.lastName) AS workerName,
c.id,
c.name,
@@ -3510,11 +5238,11 @@ BEGIN
FROM bs.ventas v
INNER JOIN vn.`client` c ON v.Id_Cliente = c.id
INNER JOIN vn.worker w ON c.salesPersonFk = w.id
- WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR)
+ WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR)
AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR)
GROUP BY w.id, v.Id_Cliente)
UNION ALL
- (SELECT
+ (SELECT
CONCAT(w.firstname, ' ', w.lastName) AS workerName,
c.id,
c.name,
@@ -3548,21 +5276,29 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`()
-BEGIN
-/**
- * Inserta en @bs.carteras.
- */
- DELETE FROM bs.carteras
- WHERE Año >= YEAR(util.VN_CURDATE()) - 1;
-
- INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso)
- SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso
- FROM vn.time t
- JOIN bs.ventas v on t.dated = v.fecha
- JOIN vn.client c on c.id = v.Id_Cliente
- JOIN vn.worker w ON w.id = c.salesPersonFk
- WHERE t.year >= YEAR(util.VN_CURDATE()) - 1
- GROUP BY w.code, t.year , t.month;
+BEGIN
+/**
+ * Inserta en la tabla @bs.carteras las ventas desde el año pasado
+ * agrupadas por trabajador, año y mes
+ */
+ DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1;
+
+ DELETE FROM bs.carteras WHERE Año >= vYear;
+
+ CALL util.time_generate(
+ MAKEDATE(vYear, 1),
+ (SELECT MAX(fecha) FROM ventas)
+ );
+
+ INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso)
+ SELECT t.`year`, t.`month`, w.code, SUM(v.importe)
+ FROM tmp.time t
+ JOIN ventas v on t.dated = v.fecha
+ JOIN vn.client c on c.id = v.Id_Cliente
+ JOIN vn.worker w ON w.id = c.salesPersonFk
+ GROUP BY w.code, t.`year`, t.`month`;
+
+ DROP TEMPORARY TABLE tmp.time;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -3581,18 +5317,14 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
- DECLARE vFourYearsAgo DATETIME;
- DECLARE vOneYearAgo DATETIME;
- DECLARE vTwoYearAgo DATETIME;
- DECLARE vThreeYearAgo DATETIME;
+ DECLARE vOneYearAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 1 YEAR;
+ DECLARE vTwoYearAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR;
+ DECLARE vThreeYearAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 3 YEAR;
+ DECLARE vFourYearsAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 4 YEAR;
+ DECLARE vEighteenMonths DATE DEFAULT util.VN_CURDATE() - INTERVAL 18 MONTH;
- SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE());
- SET vTwoYearAgo = TIMESTAMPADD(YEAR, -2,util.VN_CURDATE());
- SET vThreeYearAgo = TIMESTAMPADD(YEAR, -3,util.VN_CURDATE());
- SET vFourYearsAgo = TIMESTAMPADD(YEAR, -4,util.VN_CURDATE());
-
- DELETE FROM bs.clientNewBorn
+ DELETE FROM clientNewBorn
WHERE lastShipped < vOneYearAgo;
DELETE FROM ventas
@@ -3604,14 +5336,17 @@ BEGIN
DELETE FROM payMethodClientEvolution
WHERE dated < vFourYearsAgo;
- DELETE FROM bs.salesByclientSalesPerson
+ DELETE FROM salesByclientSalesPerson
WHERE dated < vFourYearsAgo;
- DELETE FROM bs.m3
+ DELETE FROM m3
WHERE fecha < vTwoYearAgo;
DELETE FROM salesByItemTypeDay
WHERE dated < vThreeYearAgo;
+
+ DELETE FROM waste
+ WHERE MAKEDATE(`year`, 1) + INTERVAL (`week` - 1) WEEK + INTERVAL 1 DAY < vEighteenMonths;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -3650,18 +5385,15 @@ BEGIN
SELECT c.id FROM vn.client c
JOIN vn.country co ON co.id = c.countryFk
WHERE co.code = vCountryCode
- ) sub ON sub.id = cd.id;
+ ) sub ON sub.id = cd.clientFk;
- INSERT INTO clientDied (id, clientName, lastInvoiced, workerCode, Boss, Aviso)
+ INSERT INTO clientDied (clientFk, lastInvoiced, warning)
SELECT c.id,
- c.name,
sub.lastShipped,
- w.code,
- b.code,
CASE
- WHEN lastShipped < vThridPeriod OR lastShipped IS NULL THEN 'Tercer Aviso'
- WHEN lastShipped < vSecondPeriod THEN 'Segundo Aviso'
- WHEN lastShipped < vFirstPeriod THEN 'Primer Aviso'
+ WHEN lastShipped < vThridPeriod OR lastShipped IS NULL THEN 'third'
+ WHEN lastShipped < vSecondPeriod THEN 'second'
+ WHEN lastShipped < vFirstPeriod THEN 'first'
END
FROM vn.client c
JOIN vn.country co ON co .id = c.countryFk
@@ -3710,16 +5442,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `clientNewBorn_recalc`()
BLOCK1: BEGIN
DECLARE vClientFk INT;
- DECLARE vShipped DATE;
+ DECLARE vShipped DATE;
DECLARE vPreviousShipped DATE;
- DECLARE vDone boolean;
- DECLARE cur cursor for
-
- SELECT clientFk, firstShipped
- FROM bs.clientNewBorn;
-
- DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE;
- SET vDone := FALSE;
+ DECLARE vDone boolean;
+ DECLARE cur cursor for
+
+ SELECT clientFk, firstShipped
+ FROM bs.clientNewBorn;
+
+ DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE;
+ SET vDone := FALSE;
DELETE FROM bs.clientNewBorn WHERE isModified = FALSE;
@@ -3731,7 +5463,7 @@ BLOCK1: BEGIN
WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null
GROUP BY c.id;
OPEN cur;
-
+
LOOP1: LOOP
SET vDone := FALSE;
FETCH cur INTO vClientFk, vShipped;
@@ -3742,37 +5474,37 @@ BLOCK1: BEGIN
END IF;
BLOCK2: BEGIN
- DECLARE vCurrentShipped DATE;
- DECLARE vDone2 boolean;
+ DECLARE vCurrentShipped DATE;
+ DECLARE vDone2 boolean;
DECLARE cur2 CURSOR FOR
- SELECT shipped
- FROM vn.ticket
+ SELECT shipped
+ FROM vn.ticket
WHERE clientFk = vClientFk AND shipped <= util.VN_CURDATE()
ORDER BY shipped DESC;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE;
SET vDone2 := FALSE;
OPEN cur2;
-
+
SET vPreviousShipped := vShipped;
LOOP2: LOOP
SET vDone2 := FALSE;
FETCH cur2 INTO vCurrentShipped;
-
+
IF DATEDIFF(vPreviousShipped,vCurrentShipped) > 365 THEN
- UPDATE bs.clientNewBorn
- SET firstShipped = vPreviousShipped
+ UPDATE bs.clientNewBorn
+ SET firstShipped = vPreviousShipped
WHERE clientFk= vClientFk;
-
+
CLOSE cur2;
- LEAVE LOOP2;
+ LEAVE LOOP2;
END IF;
-
+
SET vPreviousShipped := vCurrentShipped;
IF vDone2 THEN
- UPDATE bs.clientNewBorn
- SET firstShipped = vCurrentShipped
+ UPDATE bs.clientNewBorn
+ SET firstShipped = vCurrentShipped
WHERE clientFk= vClientFk;
CLOSE cur2;
LEAVE LOOP2;
@@ -3782,14 +5514,14 @@ BLOCK1: BEGIN
END BLOCK2;
END LOOP LOOP1;
- UPDATE bs.clientNewBorn cnb
+ UPDATE bs.clientNewBorn cnb
LEFT JOIN (SELECT DISTINCT t.clientFk
FROM vn.ticket t
JOIN vn.productionConfig pc
WHERE t.shipped BETWEEN util.VN_CURDATE() + INTERVAL -(`notBuyingMonths`) MONTH
AND util.VN_CURDATE() + INTERVAL -(`pc`.`rookieDays`) DAY) notRookie ON notRookie.clientFk = cnb.clientFk
- SET cnb.isRookie = ISNULL(notRookie.clientFk);
-
+ SET cnb.isRookie = ISNULL(notRookie.clientFk);
+
END BLOCK1 ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -3810,16 +5542,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `comercialesCompleto`(IN vWorker INT
BEGIN
DECLARE vAYearAgoStarted DATE DEFAULT DATE_FORMAT(TIMESTAMPADD(YEAR, - 1, vDate), '%Y-%m-01');
DECLARE vAYearAgoEnded DATE DEFAULT TIMESTAMPADD(YEAR, - 1, LAST_DAY(vDate));
-
+
CALL vn.worker_GetHierarchy(vWorker);
-
+
INSERT IGNORE INTO tmp.workerHierarchyList (workerFk)
SELECT wd2.workerFk
FROM vn.workerDepartment wd2
WHERE wd2.workerFk = vWorker;
-
+
-- Falta que en algunos casos solo tenga en cuenta los tipos afectados.
- SELECT
+ SELECT
c.Id_Cliente id_cliente,
c.Cliente cliente,
cr.recobro * 100 tarifa,
@@ -3827,16 +5559,16 @@ BEGIN
c.movil,
c.POBLACION poblacion,
p.`name` provincia,
- vn2008.red(f.futur) futur,
+ ROUND(f.futur, 2) futur,
c.Credito credito,
pm.`name` forma_pago,
- vn2008.red(c365 / 12) consumo_medio365,
- vn2008.red(c365) consumo365,
- vn2008.red(CmLy.peso) peso_mes_año_pasado,
- vn2008.red(CmLy.peso * 1.19) objetivo,
+ ROUND(c365 / 12, 2) consumo_medio365,
+ ROUND(c365, 2) consumo365,
+ ROUND(CmLy.peso, 2) peso_mes_año_pasado,
+ ROUND(CmLy.peso * 1.19, 2) objetivo,
tr.CodigoTrabajador,
- vn2008.red(mes_actual.consumo) consumoMes,
- vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo,
+ ROUND(mes_actual.consumo, 2) consumoMes,
+ ROUND(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0), 2) como_lo_llevo,
DATE(LastTicket) ultimo_ticket,
dead.muerto,
g.Greuge,
@@ -3844,9 +5576,9 @@ BEGIN
FROM
vn2008.Clientes c
LEFT JOIN
- (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge
- FROM vn2008.Greuges g
- JOIN vn.`client` c ON c.id = g.Id_Cliente
+ (SELECT g.clientFk Id_Cliente, CAST( SUM(g.amount) as DECIMAL(12,2)) AS Greuge
+ FROM vn.greuge g
+ JOIN vn.`client` c ON c.id = g.clientFk
LEFT JOIN vn.worker w ON c.salesPersonFk = w.id
WHERE (c.salesPersonFk = vWorker OR w.bossFk = vWorker)
GROUP BY Id_Cliente
@@ -3866,14 +5598,14 @@ BEGIN
WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate
GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente
LEFT JOIN
- (SELECT
+ (SELECT
Id_Cliente, SUM(importe) consumo
FROM
bs.ventas v
INNER JOIN vn2008.Clientes c USING (Id_Cliente)
LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador
WHERE
- (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
+ (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate))
GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente
LEFT JOIN
@@ -3905,9 +5637,9 @@ BEGIN
GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente
LEFT JOIN
(SELECT c.Id_Cliente,
- IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto
- FROM vn2008.Facturas f
- JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente
+ IF(MAX(io.issued) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto
+ FROM vn.invoiceOut io
+ JOIN vn2008.Clientes c ON c.Id_cliente = io.clientFk
LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador
WHERE (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente
@@ -3922,95 +5654,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `compradores_add` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_add`(IN vYear INT, IN vWeekFrom INT, IN vWeekTo INT)
-BEGIN
-/**
- * Sustituye los registros de "bs.compradores".
- *
- * @param vYear: año ventas
- * @param vWeekFrom: semana desde
- * @param vWeekTo: semana hasta
- */
- REPLACE bs.compradores
- SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision
- FROM bs.ventas v
- JOIN vn.time tm ON tm.dated = v.fecha
- JOIN vn.itemType it ON it.id = v.tipo_id
- WHERE tm.year = vYear
- AND tm.week BETWEEN vWeekFrom AND vWeekTo
- AND it.categoryFk != 6
- GROUP BY it.workerFk, tm.week;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `compradores_add_launcher` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_add_launcher`()
-BEGIN
-
- DECLARE vYear INT;
- DECLARE vWeek INT;
- DECLARE done BOOL DEFAULT FALSE;
-
- DECLARE rs CURSOR FOR
- SELECT year, week
- FROM vn.time
- WHERE dated <= util.VN_CURDATE()
- AND year = vYear
- AND week >= vWeek;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-
- SELECT MAX(año) INTO vYear
- FROM compradores;
-
- SELECT MAX(semana) INTO vWeek
- FROM compradores
- WHERE año = vYear;
-
- OPEN rs;
-
- FETCH rs INTO vYear, vWeek;
-
- WHILE NOT done DO
-
- CALL compradores_add(vYear, vWeek, vWeek);
-
- FETCH rs INTO vYear, vWeek;
-
- END WHILE;
-
- CLOSE rs;
-
- CALL compradores_evolution_add;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -4023,17 +5666,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_evolution_add`()
BEGIN
/**
* Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias
- *
+ *
*/
DECLARE vDated DATE;
DECLARE vCount INT DEFAULT 1;
- SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated
+ SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated
FROM compradores_evolution;
IF vDated IS NULL THEN
-
- SELECT MIN(dated) INTO vDated
+
+ SELECT MIN(dated) INTO vDated
FROM sale;
INSERT INTO compradores_evolution(
@@ -4054,7 +5697,7 @@ BEGIN
WHILE vDated < util.VN_CURDATE() DO
SET vCount = vCount + 1;
-
+
REPLACE compradores_evolution(
Id_Trabajador,
fecha,
@@ -4066,18 +5709,18 @@ BEGIN
SELECT Id_Trabajador, importe
FROM compradores_evolution
JOIN (
- SELECT DISTINCT it.workerFk
- FROM vn.itemType it
+ SELECT DISTINCT it.workerFk
+ FROM vn.itemType it
)sub2 ON sub2.workerFk = Id_Trabajador
- WHERE fecha = vDated - INTERVAL 1 DAY
+ WHERE fecha = vDated - INTERVAL 1 DAY
UNION ALL
- SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1)
+ SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1)
FROM sale s
JOIN vn.itemType it ON it.id = s.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
WHERE s.dated IN (vDated, vDated - INTERVAL 1 YEAR)
AND ic.merchandise
- )sub
+ )sub
GROUP BY Id_Trabajador;
SET vDated = vDated + INTERVAL 1 DAY;
@@ -4104,49 +5747,49 @@ BEGIN
* Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias
*/
DECLARE datFEC DATE DEFAULT '2015-01-01';
-
- SELECT TIMESTAMPADD(DAY,1,MAX(fecha))
- INTO datFEC
+
+ SELECT TIMESTAMPADD(DAY,1,MAX(fecha))
+ INTO datFEC
FROM bs.fondo_maniobra;
-
+
WHILE datFEC < util.VN_CURDATE() DO
-
+
IF DAY(datFEC) MOD 28 = 0 THEN -- esto solo sirve para no aburrirse mientras esperamos...
SELECT datFEC;
END IF;
-
+
REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo)
SELECT datFEC AS Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos
FROM (
SELECT SUM(io.amount) AS Facturas
FROM vn.invoiceOut io
- JOIN vn.client c ON io.clientFk = c.id
+ JOIN vn.client c ON io.clientFk = c.id
WHERE c.isRelevant
- AND io.companyFk <> 1381
+ AND io.companyFk <> 1381
AND io.issued BETWEEN '2011-01-01' AND datFEC
) fac
JOIN (
SELECT - SUM(r.amountPaid) AS Cobros
- FROM vn.receipt r
- JOIN vn.client c ON r.clientFk = c.id
- WHERE c.isRelevant
+ FROM vn.receipt r
+ JOIN vn.client c ON r.clientFk = c.id
+ WHERE c.isRelevant
AND r.companyFk <> 1381
AND r.payed BETWEEN '2011-01-01' AND datFEC
) cob
JOIN (
SELECT - SUM(id.amount) AS Recibidas
- FROM vn.invoiceIn ii
- JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk
+ FROM vn.invoiceIn ii
+ JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk
WHERE ii.companyFk <> 1381
AND ii.issued BETWEEN '2015-01-01' AND datFEC
) rec
JOIN (
SELECT SUM(p.amount) AS Pagos
- FROM vn.payment p
- WHERE p.companyFk <>1381
+ FROM vn.payment p
+ WHERE p.companyFk <>1381
AND p.received BETWEEN '2015-01-01' AND datFEC
) pag;
-
+
UPDATE bs.fondo_maniobra
JOIN (
SELECT AVG(fondo) AS media
@@ -4154,7 +5797,7 @@ BEGIN
WHERE fecha <= datFEC
) sub
SET fondo_medio = media WHERE fecha = datFEC;
-
+
SET datFEC = TIMESTAMPADD(DAY,1,datFEC);
END WHILE;
@@ -4178,7 +5821,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fruitsEvolution`()
BEGIN
-select Id_Cliente,
+select Id_Cliente,
Cliente, count(semana) as semanas, (w.code IS NOT NULL) isWorker
from (
select distinct v.Id_Cliente, c.name as Cliente, week(fecha, 3) as semana
@@ -4219,40 +5862,40 @@ BEGIN
-- Ventas totales del ultimo año
UPDATE indicators
- SET lastYearSales =
+ SET lastYearSales =
(SELECT SUM(importe + recargo)
FROM ventas v
JOIN vn2008.empresa e ON e.id = v.empresa_id
JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo
WHERE fecha BETWEEN oneYearBefore AND vDated
AND eg.grupo = 'Verdnatura'
- )
+ )
WHERE updated = vDated;
-
+
-- Greuge total acumulado
UPDATE indicators
- SET totalGreuge =
+ SET totalGreuge =
(SELECT SUM(amount)
FROM vn.greuge
WHERE shipped <= vDated
- )
+ )
WHERE updated = vDated;
-- Tasa de morosidad con respecto a las ventas del último mes
UPDATE indicators
- SET latePaymentRate =
- (SELECT SUM(amount)
- FROM bi.defaulters
+ SET latePaymentRate =
+ (SELECT SUM(amount)
+ FROM bi.defaulters
WHERE date = vDated AND amount > 0)
/
- (SELECT SUM(importe + recargo)
- FROM ventas
+ (SELECT SUM(importe + recargo)
+ FROM ventas
WHERE fecha BETWEEN oneMonthBefore AND vDated)
WHERE updated = vDated;
-- Número de trabajadores activos
UPDATE indicators
- SET countEmployee =
+ SET countEmployee =
(SELECT CAST(SUM(ct.hoursWeek) / 40 AS DECIMAL (10, 2))
FROM vn.business b
JOIN vn.calendarType ct ON ct.id = b.calendarTypeFk
@@ -4271,7 +5914,7 @@ BEGIN
-- Número de clientes que han comprado en los últimos 30 dias
UPDATE indicators
- SET lastMonthActiveClients =
+ SET lastMonthActiveClients =
(SELECT COUNT(DISTINCT t.clientFk)
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
@@ -4280,9 +5923,9 @@ BEGIN
-- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores
UPDATE indicators
- SET lastMonthLostClients =
+ SET lastMonthLostClients =
(SELECT COUNT(lm.clientFk)
- FROM
+ FROM
(SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
@@ -4299,9 +5942,9 @@ BEGIN
-- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores
UPDATE indicators
- SET lastMonthNewClients =
+ SET lastMonthNewClients =
(SELECT COUNT(cm.clientFk)
- FROM
+ FROM
(SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
@@ -4327,7 +5970,7 @@ BEGIN
-- Cálculo de las ventas agrupado por semanas
SELECT week INTO vWeek
- FROM vn.time
+ FROM vn.time
WHERE dated = vDated;
TRUNCATE salesByWeek;
@@ -4341,12 +5984,12 @@ BEGIN
-- Indicador Ventas semana actual
UPDATE indicators i
- JOIN salesByWeek s ON s.week= vWeek
+ JOIN salesByWeek s ON s.week= vWeek
AND s.year = YEAR(vDated)
SET i.thisWeekSales = s.sales
WHERE updated = vDated;
- -- Indicador ventas semana actual en el año pasado
+ -- Indicador ventas semana actual en el año pasado
UPDATE indicators i
JOIN salesByWeek s ON s.week = vWeek
AND s.year = YEAR(vDated)-1
@@ -4377,15 +6020,15 @@ BEGIN
SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01')
INTO vDated
FROM bs.indicators;
-
+
WHILE vDated < util.VN_CURDATE() DO
-
+
CALL indicatorsUpdate(vDated);
-
+
SELECT TIMESTAMPADD(DAY,1,MAX(updated))
INTO vDated
FROM bs.indicators;
-
+
END WHILE;
END ;;
@@ -4414,7 +6057,7 @@ BEGIN
DECLARE vCalc INT;
DECLARE vWarehouseFk INT;
- DECLARE cWarehouses CURSOR FOR
+ DECLARE cWarehouses CURSOR FOR
SELECT id
FROM vn.warehouse
WHERE isInventory;
@@ -4427,13 +6070,13 @@ BEGIN
read_loop: LOOP
SET vDone = FALSE;
FETCH cWarehouses INTO vWarehouseFk;
-
+
IF vDone THEN
LEAVE read_loop;
END IF;
-
+
CALL cache.visible_refresh(vCalc, FALSE, vWarehouseFk);
-
+
CREATE OR REPLACE TEMPORARY TABLE tVisible
SELECT itemFk, SUM(visible) totalVisible
FROM vn.itemShelving ish
@@ -4442,7 +6085,7 @@ BEGIN
JOIN vn.sector sc ON sc.id = p.sectorFk
WHERE sc.warehouseFk = vWarehouseFk
GROUP BY itemFk;
-
+
INSERT INTO inventoryDiscrepancyDetail(
warehouseFk,
itemFk,
@@ -4514,15 +6157,15 @@ BEGIN
DECLARE datSTART DATE;
DECLARE datEND DATE;
-
+
SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART
FROM bs.m3;
-
+
SET datEND = TIMESTAMPADD(DAY,-1,util.VN_CURDATE());
-
- DELETE FROM bs.m3
+
+ DELETE FROM bs.m3
WHERE fecha >= datSTART;
-
+
INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros)
SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(s.quantity * ic.cm3delivery) / 1000000 AS m3,
tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe)
@@ -4564,52 +6207,63 @@ BEGIN
DECLARE vClaimManaId INT;
DECLARE vManaBankId INT;
DECLARE vManaGreugeTypeId INT;
+ DECLARE vManaFromDays INT;
+ DECLARE vManaToDays INT;
- SELECT id INTO vManaId
+ SELECT id INTO vManaId
FROM vn.component WHERE code = 'mana';
-
- SELECT id INTO vManaAutoId
+
+ SELECT id INTO vManaAutoId
FROM vn.component WHERE code = 'autoMana';
-
+
SELECT id INTO vClaimManaId
FROM vn.component WHERE code = 'manaClaim';
-
- SELECT id INTO vManaBankId
- FROM vn.bank WHERE code = 'mana';
-
- SELECT id INTO vManaGreugeTypeId
+
+ SELECT id INTO vManaBankId
+ FROM vn.accounting WHERE code = 'mana';
+
+ SELECT id INTO vManaGreugeTypeId
FROM vn.greugeType WHERE code = 'mana';
- SELECT IFNULL(MAX(dated), '2016-01-01')
- INTO vFromDated
+ SELECT manaFromDays, manaToDays
+ INTO vManaFromDays, vManaToDays
+ FROM vn.salespersonConfig;
+
+ SELECT MAX(dated)
+ INTO vFromDated
FROM vn.clientManaCache;
- DELETE
- FROM vn.clientManaCache
- WHERE dated = vFromDated;
-
- SELECT IFNULL(MAX(dated), '2016-01-01')
- INTO vFromDated
+ DELETE
+ FROM vn.clientManaCache
+ WHERE dated = vFromDated;
+
+ SELECT MAX(dated)
+ INTO vFromDated
FROM vn.clientManaCache;
+
+ IF ISNULL(vFromDated) THEN
+ SELECT manaDateFrom
+ INTO vFromDated
+ FROM vn.salespersonConfig;
+ END IF;
- WHILE timestampadd(DAY,30,vFromDated) < util.VN_CURDATE() DO
-
+ WHILE vFromDated + INTERVAL vManaToDays DAY < util.VN_CURDATE() DO
SELECT
- timestampadd(DAY,30,vFromDated),
- timestampadd(DAY,-90,vFromDated)
- INTO
+ vFromDated + INTERVAL vManaToDays DAY,
+ vFromDated - INTERVAL vManaFromDays DAY
+ INTO
vToDated,
vForDeleteDated;
-
+
DELETE FROM vn.clientManaCache
WHERE dated <= vForDeleteDated;
INSERT INTO vn.clientManaCache(clientFk, mana, dated)
- SELECT
+ SELECT
Id_Cliente,
- cast(sum(mana) as decimal(10,2)) as mana,
- vToDated as dated
- FROM
+ SUM(mana),
+ vToDated
+ FROM
(
SELECT cs.Id_Cliente, Cantidad * Valor as mana
FROM vn2008.Tickets t
@@ -4617,21 +6271,20 @@ BEGIN
JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket
JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento
WHERE Id_Componente IN (vManaAutoId, vManaId, vClaimManaId)
- AND t.Fecha > vFromDated
+ AND t.Fecha > vFromDated
AND date(t.Fecha) <= vToDated
UNION ALL
SELECT r.Id_Cliente, - Entregado
FROM vn2008.Recibos r
WHERE Id_Banco = vManaBankId
- AND Fechacobro > vFromDated
+ AND Fechacobro > vFromDated
AND Fechacobro <= vToDated
-
UNION ALL
- SELECT g.Id_Cliente, g.Importe
- FROM vn2008.Greuges g
- WHERE Greuges_type_id = vManaGreugeTypeId
- AND Fecha > vFromDated
- AND Fecha <= vToDated
+ SELECT clientFk, amount
+ FROM vn.greuge
+ WHERE greugeTypeFk = vManaGreugeTypeId
+ AND shipped > vFromDated
+ AND shipped <= vToDated
UNION ALL
SELECT clientFk, mana
FROM vn.clientManaCache
@@ -4640,10 +6293,8 @@ BEGIN
GROUP BY Id_Cliente
HAVING Id_Cliente;
- SET vFromDated = vToDated;
-
+ SET vFromDated = vToDated;
END WHILE;
-
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4662,23 +6313,30 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellers_actualize`()
BEGIN
-/**
- * Recalcula el valor del campo con el modificador de precio
+/**
+ * Recalcula el valor del campo con el modificador de precio
* para el componente de maná automático.
*/
- UPDATE vn.workerMana wm
+ UPDATE vn.workerMana wm
JOIN (
- SELECT c.lastSalesPersonFk,
+ SELECT c.lastSalesPersonFk,
FLOOR(SUM(s.amount) / 12) amount
FROM salesByclientSalesPerson s
JOIN vn.client c ON c.id = s.clientFk
WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE()
GROUP BY c.lastSalesPersonFk
- )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk
+ )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk
JOIN vn.salespersonConfig spc
- SET wm.pricesModifierRate = GREATEST(
- spc.manaMinRate,
- LEAST(spc.manaMaxRate, ROUND( - wm.amount / avgPortfolioWeight.amount)));
+ SET wm.pricesModifierRate =
+ IFNULL(
+ GREATEST(
+ spc.manaMinRate,
+ LEAST(
+ spc.manaMaxRate,
+ ROUND( - wm.amount / avgPortfolioWeight.amount, 3)
+ )
+ )
+ ,0);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4696,86 +6354,82 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `nightTask_launchAll`()
-BEGIN
-/**
- * Runs all nightly tasks.
- */
- DECLARE vDone BOOL;
- DECLARE vError VARCHAR(255);
- DECLARE vErrorCode VARCHAR(255);
- DECLARE vNErrors INT DEFAULT 0;
- DECLARE vSchema VARCHAR(255);
- DECLARE vProcedure VARCHAR(255);
- DECLARE vLogMail VARCHAR(255);
- DECLARE vId INT;
-
- DECLARE rs CURSOR FOR
- SELECT id, `schema`, `procedure`
- FROM nightTask
- WHERE finished <= util.VN_CURDATE()
- OR finished IS NULL
- ORDER BY `order`;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET vDone = TRUE;
-
- SET max_sp_recursion_depth = 3;
- OPEN rs;
-
- myLoop: LOOP
- SET vDone = FALSE;
- FETCH rs INTO vId, vSchema, vProcedure;
-
- IF vDone THEN
- LEAVE myLoop;
- END IF;
-
- UPDATE nightTask
- SET `started` = util.VN_NOW(),
- `finished` = NULL,
- `error` = NULL,
- `errorCode` = NULL
- WHERE id = vId;
-
- SET vError = NULL;
- CALL nightTask_launchTask(
- vSchema,
- vProcedure,
- vError,
- vErrorCode
- );
-
- IF vError IS NOT NULL THEN
- SET vNErrors = vNErrors + 1;
-
- UPDATE nightTask
- SET `error` = vError,
- `errorCode` = vErrorCode
- WHERE id = vId;
- ELSE
- UPDATE nightTask
- SET finished = util.VN_NOW(),
- lastFinished = util.VN_NOW()
- WHERE id = vId;
- END IF;
- END LOOP;
-
- CLOSE rs;
-
- SELECT logMail INTO vLogMail
- FROM nightTaskConfig LIMIT 1;
-
- IF vNErrors > 0 AND vLogMail IS NOT NULL THEN
- CALL vn.mail_insert(
- vLogMail,
- NULL,
- 'Nightly task failed',
- CONCAT(
- vNErrors, ' procedures of nightly tasks have failed. ',
- 'Please, see `', SCHEMA() ,'`.`nightTask` table for more info.'
- )
- );
- END IF;
+BEGIN
+/**
+ * Runs all nightly tasks.
+ */
+ DECLARE vDone BOOL;
+ DECLARE vError VARCHAR(255);
+ DECLARE vErrorCode VARCHAR(255);
+ DECLARE vSchema VARCHAR(255);
+ DECLARE vProcedure VARCHAR(255);
+ DECLARE vLogMail VARCHAR(255);
+ DECLARE vNightTaskFk INT;
+
+ DECLARE vQueue CURSOR FOR
+ SELECT id, `schema`, `procedure`
+ FROM nightTask
+ WHERE finished <= util.VN_CURDATE()
+ OR finished IS NULL
+ ORDER BY `order`;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ SET max_sp_recursion_depth = 3;
+
+ SELECT logMail INTO vLogMail
+ FROM nightTaskConfig LIMIT 1;
+
+ OPEN vQueue;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ UPDATE nightTask
+ SET `started` = util.VN_NOW(),
+ `finished` = NULL,
+ `error` = NULL,
+ `errorCode` = NULL
+ WHERE id = vNightTaskFk;
+
+ SET vError = NULL;
+ CALL nightTask_launchTask(
+ vSchema,
+ vProcedure,
+ vError,
+ vErrorCode
+ );
+
+ IF vError IS NOT NULL THEN
+ IF vLogMail IS NOT NULL THEN
+ CALL vn.mail_insert(
+ vLogMail,
+ NULL,
+ CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'),
+ CONCAT(
+ '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break
+ 'See ', SCHEMA(), '.nightTask table for more info.'
+ )
+ );
+ END IF;
+
+ UPDATE nightTask
+ SET `error` = vError,
+ `errorCode` = vErrorCode
+ WHERE id = vNightTaskFk;
+ ELSE
+ UPDATE nightTask
+ SET finished = util.VN_NOW(),
+ lastFinished = util.VN_NOW()
+ WHERE id = vNightTaskFk;
+ END IF;
+ END LOOP;
+ CLOSE vQueue;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4814,7 +6468,7 @@ BEGIN
vError = MESSAGE_TEXT,
vErrorCode = RETURNED_SQLSTATE;
- CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`'));
+ CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`'));
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4833,22 +6487,22 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `payMethodClientAdd`()
BEGIN
- INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk)
+ INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk)
SELECT util.VN_CURDATE(), c.payMethodFk, c.id
- FROM vn.client c
+ FROM vn.client c
JOIN vn.payMethod p ON c.payMethodFk = p.id;
-
+
TRUNCATE `bs`.`payMethodClientEvolution` ;
-
+
INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax)
- SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo)
+ SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo)
FROM bs.payMethodClient p
- JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente
+ JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente
FROM bs.ventas v
WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient)
GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk
JOIN vn.payMethod pm ON p.payMethodFk = pm.id
- GROUP BY dated,payMethodFk;
+ GROUP BY dated,payMethodFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4868,12 +6522,12 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGraphic`(IN vItemFk INT, IN vTypeFk INT, IN vCategoryFk INT, IN vFromDate DATE,
IN vToDate DATE, IN vProducerFk INT)
BEGIN
-
+
DECLARE vFromDateLastYear DATE;
DECLARE vToDateLastYear DATE;
DECLARE vFromDateTwoYearsAgo DATE;
DECLARE vToDateTwoYearsAgo DATE;
-
+
SET vItemFk = IFNULL(vItemFk,0);
SET vTypeFk = IFNULL(vTypeFk, 0);
SET vCategoryFk = IFNULL(vCategoryFk,0);
@@ -4888,19 +6542,19 @@ BEGIN
SELECT s.quantity, CAST(v.importe AS DECIMAL(10,0)) importe, v.fecha
FROM bs.ventas v
- JOIN vn.sale s ON s.id = v.Id_Movimiento
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.sale s ON s.id = v.Id_Movimiento
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
WHERE vItemFk IN (i.id, 0)
AND vTypeFk IN (i.typeFk, 0)
AND vCategoryFk IN (it.categoryFk, 0)
AND vProducerFk IN (i.producerFk, 0)
AND (v.fecha BETWEEN vFromDate AND vToDate
OR v.fecha BETWEEN vFromDateLastYear AND vToDateLastYear
- OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo
+ OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo
);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4919,21 +6573,21 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME)
BEGIN
- DELETE FROM bs.salePersonEvolution
+ DELETE FROM bs.salePersonEvolution
WHERE dated <= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR);
-
-
+
+
INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk)
- SELECT fecha dated,
- CAST(SUM(importe) AS DECIMAL(10,2) ) amount,
+ SELECT fecha dated,
+ CAST(SUM(importe) AS DECIMAL(10,2) ) amount,
CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax ,
IFNULL(salesPersonFk,0) salesPersonFk
FROM bs.ventas v
- JOIN vn.client c ON v.Id_Cliente = c.id
+ JOIN vn.client c ON v.Id_Cliente = c.id
JOIN vn.company co ON co.id = v.empresa_id
WHERE co.code = "VNL" AND fecha >= vDateStart
GROUP BY v.fecha,c.salesPersonFk
- ORDER BY salesPersonFk,dated ASC;
+ ORDER BY salesPersonFk,dated ASC;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4955,7 +6609,7 @@ BEGIN
/**
* Agrupa las ventas por cliente/comercial/fecha en la tabla bs.salesByclientSalesPerson
* El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo
- *
+ *
* @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer
*/
@@ -4963,17 +6617,17 @@ BEGIN
SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH;
END IF;
- UPDATE salesByclientSalesPerson
+ UPDATE salesByclientSalesPerson
SET amount = 0,
equalizationTax = 0,
amountNewBorn = 0
WHERE dated BETWEEN vDatedFrom AND util.yesterday();
-
- INSERT INTO salesByclientSalesPerson(
- dated,
- salesPersonFk,
- clientFk,
- amount,
+
+ INSERT INTO salesByclientSalesPerson(
+ dated,
+ salesPersonFk,
+ clientFk,
+ amount,
equalizationTax)
SELECT s.dated,
c.salesPersonFk,
@@ -4982,7 +6636,7 @@ BEGIN
SUM(s.surcharge)
FROM sale s
JOIN vn.client c on s.clientFk = c.id
- WHERE s.dated BETWEEN vDatedFrom AND util.yesterday()
+ WHERE s.dated BETWEEN vDatedFrom AND util.yesterday()
GROUP BY s.dated, c.salesPersonFk, s.clientFk
ON DUPLICATE KEY UPDATE amount= VALUES(amount),
equalizationTax= VALUES(equalizationTax);
@@ -5024,11 +6678,10 @@ BEGIN
DELETE FROM salesByItemTypeDay
WHERE dated BETWEEN vDateStart AND vDateEnd;
- INSERT INTO salesByItemTypeDay (itemTypeFk, dated, `references`, netSale, stems)
+ INSERT INTO salesByItemTypeDay (itemTypeFk, dated, `references`, stems)
SELECT it.id itemTypeFk,
bs.dated,
COUNT(DISTINCT(i.id)) `references`,
- SUM(bs.amount) netSale,
SUM(i.stems * s.quantity) stems
FROM sale bs
JOIN vn.itemType it ON it.id = bs.typeFk
@@ -5156,8 +6809,8 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`()
-BEGIN
- CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE());
+BEGIN
+ CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -5177,35 +6830,35 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salesPersonEvolution_add`()
BEGIN
/**
- * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día.
+ * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día.
* Recalcula automáticamente los 3 últimos meses para comprobar si hay algún cambio.
*/
DECLARE vDated DATE;
DECLARE vCont INT DEFAULT 1;
- SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated
+ SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated
FROM salesPersonEvolution;
- DELETE FROM salesPersonEvolution
+ DELETE FROM salesPersonEvolution
WHERE dated >= vDated;
IF ISNULL(vDated) THEN
- SELECT MIN(dated) INTO vDated
+ SELECT MIN(dated) INTO vDated
FROM salesByclientSalesPerson;
-
+
INSERT INTO salesPersonEvolution(
- salesPersonFk,
- dated,
- amount,
- equalizationTax,
+ salesPersonFk,
+ dated,
+ amount,
+ equalizationTax,
amountNewBorn
)
- SELECT salesPersonFk,
- dated,
- amount,
- equalizationTax,
+ SELECT salesPersonFk,
+ dated,
+ amount,
+ equalizationTax,
amountNewBorn
- FROM salesByclientSalesPerson
+ FROM salesByclientSalesPerson
WHERE dated = vDated
GROUP BY salesPersonFk;
@@ -5213,21 +6866,21 @@ BEGIN
END IF;
WHILE vDated < util.VN_CURDATE() DO
-
+
SET vCont = vCont + 1;
REPLACE salesPersonEvolution(salesPersonFk, dated, amount)
SELECT salesPersonFk, vDated, amount
FROM(SELECT salesPersonFk, SUM(amount) amount
FROM(SELECT salesPersonFk, amount
- FROM salesPersonEvolution
+ FROM salesPersonEvolution
WHERE dated = vDated - INTERVAL 1 DAY
UNION ALL
- SELECT salesPersonFk, amount
- FROM salesByclientSalesPerson
+ SELECT salesPersonFk, amount
+ FROM salesByclientSalesPerson
WHERE dated = vDated
UNION ALL
SELECT salesPersonFk, - amount
- FROM salesByclientSalesPerson
+ FROM salesByclientSalesPerson
WHERE dated = vDated - INTERVAL 1 YEAR
)sub
GROUP BY salesPersonFk
@@ -5256,7 +6909,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `vendedores_add_launcher`()
BEGIN
CALL bs.salesByclientSalesPerson_add(util.VN_CURDATE()- INTERVAL 45 DAY);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -5280,7 +6933,7 @@ BEGIN
/**
* Añade las ventas que se realizaron entre
* vStarted y vEnded
-*
+*
* @param vStarted Fecha de inicio
* @param vEnded Fecha de finalizacion
*
@@ -5288,7 +6941,7 @@ BEGIN
DECLARE vStartingDate DATETIME;
DECLARE vEndingDate DATETIME;
- IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE())
+ IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE())
OR vEnded < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) THEN
CALL util.throw('fechaDemasiadoAntigua');
END IF;
@@ -5297,8 +6950,8 @@ BEGIN
SET vStartingDate = vStarted ;
SET vEndingDate = util.dayEnd(vStartingDate);
- DELETE
- FROM sale
+ DELETE
+ FROM sale
WHERE dated BETWEEN vStartingDate AND vEnded;
WHILE vEndingDate <= vEnded DO
@@ -5319,28 +6972,28 @@ BEGIN
JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.address a ON a.id = t.addressFk
+ JOIN vn.address a ON a.id = t.addressFk
JOIN vn.client cl ON cl.id = a.clientFk
WHERE t.shipped BETWEEN vStartingDate AND vEndingDate
AND s.quantity <> 0
AND s.discount <> 100
- AND ic.merchandise
+ AND ic.merchandise
GROUP BY sc.saleFk
HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0;
UPDATE sale s
JOIN (
- SELECT s.id,
+ SELECT s.id,
SUM(s.quantity * sc.value ) margen,
s.quantity * s.price * (100 - s.discount ) / 100 pvp
FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.saleComponent sc ON sc.saleFk = s.id
- JOIN vn.component c ON c.id = sc.componentFk
- JOIN vn.componentType ct ON ct.id = c.typeFk
+ JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk
WHERE t.shipped BETWEEN vStartingDate AND vEndingDate
AND ct.isMargin = TRUE
- GROUP BY s.id) sub ON sub.id = s.saleFk
+ GROUP BY s.id) sub ON sub.id = s.saleFk
SET s.margin = sub.margen + s.amount + s.surcharge - sub.pvp;
SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate);
@@ -5368,7 +7021,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_add_launcher`()
BEGIN
/**
* Añade las ventas a la tabla bs.sale que se realizaron desde hace un mes hasta hoy
- *
+ *
*/
DECLARE vCurDate DATE DEFAULT util.VN_CURDATE();
@@ -5414,9 +7067,9 @@ BEGIN
ENGINE = MEMORY
SELECT Id_Ticket
FROM vn2008.Tickets t
- JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura
- WHERE year(f.Fecha) = vYear
- AND month(f.Fecha) = vMonth;
+ JOIN vn.invoiceOut io ON io.`ref` = t.Factura
+ WHERE year(io.issued) = vYear
+ AND month(io.issued) = vMonth;
INSERT INTO bs.ventas_contables(year
, month
@@ -5438,12 +7091,12 @@ BEGIN
, tp.reino_id
, a.tipo_id
, t.empresa_id
- , 7000000000
+ , a.expenseFk
+ IF(e.empresa_grupo = e2.empresa_grupo
,1
,IF(e2.empresa_grupo,2,0)
- ) * 1000000
- + tp.reino_id * 10000 as Gasto
+ ) * 100000
+ + tp.reino_id * 1000 as Gasto
FROM vn2008.Movimientos m
JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket
JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna
@@ -5507,13 +7160,13 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add_launcher`()
BEGIN
-
+
/**
* Reemplaza las ventas contables del último año.
* Es el origen de datos para el balance de Entradas
*
**/
-
+
CALL bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())));
END ;;
@@ -5534,22 +7187,22 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT)
BEGIN
-
+
/**
* Muestra las ventas (€) de cada cliente
* dependiendo del año
*/
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
CREATE TEMPORARY TABLE tmp.ticket_list
(PRIMARY KEY (Id_Ticket))
SELECT Id_Ticket
FROM vn2008.Tickets t
- JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura
- WHERE year(f.Fecha) = vYear
- AND month(f.Fecha) = vMonth;
-
+ JOIN vn.invoiceOut io ON io.id = t.Factura
+ WHERE year(io.issued) = vYear
+ AND month(io.issued) = vMonth;
+
SELECT vYear Año,
vMonth Mes,
t.Id_Cliente,
@@ -5559,7 +7212,7 @@ BEGIN
IF(e2.empresa_grupo,2,0))
AS grupo,
t.empresa_id empresa
- FROM vn2008.Movimientos m
+ FROM vn2008.Movimientos m
JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna
JOIN vn2008.Clientes c ON c.Id_Cliente = cs.Id_Cliente
@@ -5573,9 +7226,9 @@ BEGIN
AND m.Descuento <> 100
AND a.tipo_id != 188
GROUP BY t.Id_Cliente, grupo,t.empresa_id;
-
+
DROP TEMPORARY TABLE tmp.ticket_list;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -5594,7 +7247,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `vivosMuertos`()
BEGIN
-
+
/**
* Devuelve el número de clientes nuevos y muertos,
* dependiendo de la fecha actual.
@@ -5605,9 +7258,9 @@ BEGIN
SET @datSTART = TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
SET @datEND = TIMESTAMPADD(DAY,-DAY(util.VN_CURDATE()),util.VN_CURDATE());
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos;
-
+
CREATE TEMPORARY TABLE tmp.VivosMuertos
SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto
FROM vn2008.Clientes c
@@ -5617,33 +7270,33 @@ BEGIN
WHERE date BETWEEN @datSTART
AND @datEND ) tm
LEFT JOIN
- (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra
- FROM vn2008.Facturas f
- JOIN vn2008.time tm ON tm.date = f.Fecha
- WHERE Fecha BETWEEN @datSTART
+ (SELECT DISTINCT tm.yearMonth, io.clientFk Id_Cliente , 1 as Compra
+ FROM vn.invoiceOut io
+ JOIN vn2008.time tm ON tm.date = io.issued
+ WHERE io.issued BETWEEN @datSTART
AND @datEND) f ON f.yearMonth = tm.yearMonth
AND f.Id_Cliente = c.Id_Cliente;
-
+
UPDATE tmp.VivosMuertos vm
JOIN
- (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente
- FROM vn2008.Facturas f
- JOIN vn2008.time tm ON tm.date = f.Fecha
- WHERE Fecha BETWEEN @datSTART AND @datEND
- GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth
+ (SELECT MIN(tm.yearMonth) firstMonth, io.clientFk Id_Cliente
+ FROM vn.invoiceOut io
+ JOIN vn2008.time tm ON tm.date = io.issued
+ WHERE io.issued BETWEEN @datSTART AND @datEND
+ GROUP BY io.clientFk) fm ON fm.firstMonth = vm.yearMonth
AND fm.Id_Cliente = vm.Id_Cliente
SET Nuevo = 1;
-
+
SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos;
-
+
UPDATE tmp.VivosMuertos vm
JOIN (
- SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente
- FROM vn2008.Facturas f
- JOIN vn2008.time tm ON tm.date = f.Fecha
- WHERE Fecha BETWEEN @datSTART AND @datEND
- GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth
+ SELECT MAX(tm.yearMonth) firstMonth, io.clientFk Id_Cliente
+ FROM vn.invoiceOut io
+ JOIN vn2008.time tm ON tm.date = io.issued
+ WHERE io.issued BETWEEN @datSTART AND @datEND
+ GROUP BY io.clientFk) fm ON fm.firstMonth = vm.yearMonth
AND fm.Id_Cliente = vm.Id_Cliente
SET Muerto = 1
@@ -5677,23 +7330,23 @@ BEGIN
INTO vWeek, vYear
FROM vn.time
WHERE dated = util.VN_CURDATE();
-
+
REPLACE bs.waste
SELECT *, 100 * mermas / total as porcentaje
FROM (
- SELECT buyer,
- year,
+ SELECT buyer,
+ year,
week,
family,
itemFk,
itemTypeFk,
- floor(sum(value)) as total,
- floor(sum(IF(clientTypeFk = 'loses', value, 0))) as mermas
- FROM vn.saleValue
+ floor(sum(value)) as total,
+ floor(sum(IF(typeFk = 'loses', value, 0))) as mermas
+ FROM vn.saleValue
where year = vYear and week = vWeek
-
+
GROUP BY family, itemFk
-
+
) sub
ORDER BY mermas DESC;
END ;;
@@ -5725,56 +7378,56 @@ BEGIN
DECLARE vDateEnded DATE;
DECLARE vCursor CURSOR FOR
- SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated)
+ SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated)
FROM vn.time t
WHERE t.dated BETWEEN vDateStarted AND vDateEnded
- GROUP BY year,month;
+ GROUP BY year,month;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
IF DAY(util.VN_CURDATE()) = 21 THEN
-
+
SELECT util.firstDayOfMonth(DATE_SUB(util.VN_CURDATE(), INTERVAL 12 MONTH)),
LAST_DAY(DATE_SUB(util.VN_CURDATE(), INTERVAL 1 MONTH))
- INTO vDateStarted,
+ INTO vDateStarted,
vDateEnded;
-
- DELETE FROM workerLabourDataByMonth
+
+ DELETE FROM workerLabourDataByMonth
WHERE CONCAT(`year`, '-',`month`, '-01') BETWEEN vDateStarted AND vDateEnded;
OPEN vCursor;
l: LOOP
SET vDone = FALSE;
-
+
FETCH vCursor INTO vFristDay, vLastDay;
-
+
IF vDone THEN
LEAVE l;
END IF;
-
+
-- Altas periodo
- INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
- SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
+ INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
+ SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
JOIN vn.worker w ON w.id = b.workerFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
LEFT JOIN (SELECT b.id, b.workerFk
FROM vn.business b
- LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl
+ LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl
ON wl.ended = DATE_SUB(b.started, INTERVAL 1 DAY) AND wl.workerFk = b.workerFk
- WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended
+ WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended
)sub ON sub.workerFk = b.workerFk
WHERE wc.payrollCenterFk IS NOT NULL
AND b.workCenterFk IS NOT NULL
AND b.started BETWEEN vFristDay AND vLastDay
AND sub.workerFk IS NULL
- AND NOT w.isFreelance;
+ AND NOT w.isFreelance;
-- Bajas periodo
- INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
- SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
+ INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
+ SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
@@ -5785,12 +7438,12 @@ BEGIN
AND b.ended BETWEEN vFristDay AND vLastDay
AND wl.started IS NULL
AND NOT w.isFreelance;
-
+
-- Anterior al periodo
SET vLastDay = LAST_DAY(DATE_SUB(vFristDay, INTERVAL 1 DAY));
- INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
- SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
+ INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
+ SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
@@ -5800,8 +7453,8 @@ BEGIN
AND NOT w.isFreelance;
-- Discapacidad
- INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
- SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
+ INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
+ SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
@@ -6005,7 +7658,7 @@ CREATE TABLE `cache` (
`lifetime` time NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -6029,7 +7682,7 @@ CREATE TABLE `cache_calc` (
KEY `cache_id` (`cache_id`),
KEY `cacheName` (`cacheName`),
KEY `expires` (`expires`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -6098,7 +7751,7 @@ CREATE TABLE `prod_graphic_source` (
`graphCategory` int(11) NOT NULL DEFAULT 0,
`Agencia` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -6167,7 +7820,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `cacheCalc_clean` ON SCHEDULE EVERY 30 MINUTE STARTS '2022-01-28 09:29:18' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO CALL cacheCalc_clean */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `cacheCalc_clean` ON SCHEDULE EVERY 30 MINUTE STARTS '2022-01-28 09:29:18' ON COMPLETION NOT PRESERVE ENABLE DO CALL cacheCalc_clean */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -6185,7 +7838,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `cache_clean` ON SCHEDULE EVERY 5 MINUTE STARTS '2022-01-28 09:29:18' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO CALL cache_clean */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `cache_clean` ON SCHEDULE EVERY 5 MINUTE STARTS '2022-01-28 09:29:18' ON COMPLETION NOT PRESERVE ENABLE DO CALL cache_clean */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -6210,7 +7863,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `addressFriendship_Update`()
BEGIN
- REPLACE cache.addressFriendship
+ REPLACE cache.addressFriendship
SELECT addressFk1, addressFk2, count(*) friendship
FROM
(
@@ -6221,7 +7874,7 @@ BEGIN
AND t2.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE())
AND t.addressFk != t2.addressFk) sub
GROUP BY addressFk1, addressFk2;
-
+
REPLACE cache.zoneAgencyFriendship
SELECT r.agencyModeFk, t.zoneFk, count(*) friendship
FROM vn.route r
@@ -6395,12 +8048,12 @@ BEGIN
FROM available a
LEFT JOIN tCalc c ON c.id = a.calc_id
WHERE c.id IS NULL;
-
+
DELETE a
FROM availableNoRaids a
LEFT JOIN tCalc c ON c.id = a.calc_id
WHERE c.id IS NULL;
-
+
DROP TEMPORARY TABLE tCalc;
END ;;
DELIMITER ;
@@ -6424,7 +8077,8 @@ proc: BEGIN
DECLARE vReserveDate DATETIME;
DECLARE vParams CHAR(100);
DECLARE vInventoryDate DATE;
- DECLARE vIsLogifloraDay BOOLEAN;
+ DECLARE vLifeScope DATE;
+ DECLARE vWarehouseFkInventory INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
@@ -6445,43 +8099,42 @@ proc: BEGIN
LEAVE proc;
END IF;
- -- Invoca al procedimiento que genera el stock virtual de Logiflora, si coincide con la peticion de refresco del disponible
- IF vn.isLogifloraDay(vDated, vWarehouse) THEN
- -- CALL edi.floramondo_offerRefresh;
- SET vIsLogifloraDay = TRUE;
- ELSE
- SET vIsLogifloraDay = FALSE;
- END IF;
-
-- Calcula algunos parámetros necesarios
SET vStartDate = TIMESTAMP(vDated, '00:00:00');
SELECT inventoried INTO vInventoryDate FROM vn.config;
+ SELECT DATE_SUB(vStartDate, INTERVAL MAX(life) DAY) INTO vLifeScope FROM vn.itemType;
SELECT SUBTIME(util.VN_NOW(), reserveTime) INTO vReserveDate
FROM hedera.orderConfig;
+ SELECT w.id INTO vWarehouseFkInventory
+ FROM vn.warehouse w
+ WHERE w.code = 'inv';
+
-- Calcula el ultimo dia de vida para cada producto
DROP TEMPORARY TABLE IF EXISTS itemRange;
CREATE TEMPORARY TABLE itemRange
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
- SELECT c.itemFk,
- IF(it.life IS NULL,
- NULL,
- TIMESTAMP(TIMESTAMPADD(DAY, it.life, c.landing), '23:59:59')) ended
- FROM (
- SELECT b.itemFk, MAX(t.landed) landing
- FROM vn.buy b
- JOIN vn.entry e ON b.entryFk = e.id
- JOIN vn.travel t ON t.id = e.travelFk
- JOIN vn.warehouse w ON w.id = t.warehouseInFk
- WHERE t.landed BETWEEN vInventoryDate AND vStartDate
- AND t.warehouseInFk = vWarehouse
- AND NOT e.isExcludedFromAvailable
- GROUP BY b.itemFk
- ) c
- JOIN vn.item i ON i.id = c.itemFk
+ SELECT i.id itemFk,
+ util.dayEnd(DATE_ADD(c.maxLanded, INTERVAL it.life DAY)) ended, it.life
+ FROM vn.item i
+ LEFT JOIN (
+ SELECT b.itemFk, MAX(t.landed) maxLanded
+ FROM vn.buy b
+ JOIN vn.entry e ON b.entryFk = e.id
+ JOIN vn.travel t ON t.id = e.travelFk
+ JOIN vn.warehouse w ON w.id = t.warehouseInFk
+ JOIN vn.item i ON i.id = b.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ WHERE t.landed BETWEEN vLifeScope AND vStartDate
+ AND t.warehouseInFk = vWarehouse
+ AND t.warehouseOutFk <> vWarehouseFkInventory
+ AND it.life
+ AND NOT e.isExcludedFromAvailable
+ GROUP BY b.itemFk
+ ) c ON i.id = c.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
- HAVING ended >= vStartDate OR ended IS NULL;
+ HAVING ended >= vStartDate OR life IS NULL;
-- Calcula el ATP
DELETE FROM available WHERE calc_id = vCalc;
@@ -6505,7 +8158,7 @@ proc: BEGIN
WHERE i.landed >= vStartDate
AND (ir.ended IS NULL OR i.landed <= ir.ended)
AND i.warehouseInFk = vWarehouse
- AND (ISNULL(wf.entryFk) OR vIsLogifloraDay)
+ AND ISNULL(wf.entryFk)
UNION ALL
SELECT i.itemFk, i.shipped, i.quantity
FROM vn.itemEntryOut i
@@ -6579,27 +8232,27 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT)
-BEGIN
- DECLARE v_cache_name VARCHAR(255);
- DECLARE v_params VARCHAR(255);
-
- -- Libera el bloqueo y actualiza la fecha de ultimo refresco.
-
- UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id
- SET
- cc.last_refresh = NOW(),
- cc.expires = ADDTIME(NOW(), c.lifetime),
- cc.connection_id = NULL
- WHERE cc.id = v_calc;
-
- SELECT c.name, ca.params INTO v_cache_name, v_params
- FROM cache c
- JOIN cache_calc ca ON c.id = ca.cache_id
- WHERE ca.id = v_calc;
-
- IF v_cache_name IS NOT NULL THEN
- DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, '')));
- END IF;
+BEGIN
+ DECLARE v_cache_name VARCHAR(255);
+ DECLARE v_params VARCHAR(255);
+
+ -- Libera el bloqueo y actualiza la fecha de ultimo refresco.
+
+ UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id
+ SET
+ cc.last_refresh = NOW(),
+ cc.expires = ADDTIME(NOW(), c.lifetime),
+ cc.connection_id = NULL
+ WHERE cc.id = v_calc;
+
+ SELECT c.name, ca.params INTO v_cache_name, v_params
+ FROM cache c
+ JOIN cache_calc ca ON c.id = ca.cache_id
+ WHERE ca.id = v_calc;
+
+ IF v_cache_name IS NOT NULL THEN
+ DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, '')));
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -6617,89 +8270,89 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100))
-proc: BEGIN
- DECLARE v_valid BOOL;
- DECLARE v_lock_id VARCHAR(100);
- DECLARE v_cache_id INT;
- DECLARE v_expires DATETIME;
- DECLARE v_clean_time DATETIME;
- DECLARE vLastRefresh DATETIME;
-
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- IF v_lock_id IS NOT NULL THEN
- DO RELEASE_LOCK(v_lock_id);
- END IF;
-
- RESIGNAL;
- END;
-
- SET v_params = IFNULL(v_params, '');
-
- -- Si el servidor se ha reiniciado invalida todos los calculos.
-
- SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid;
-
- IF !v_valid
- THEN
- DELETE FROM cache_calc;
- INSERT INTO cache_valid (valid) VALUES (TRUE);
- END IF;
-
- -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia.
-
- SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params);
-
- IF !GET_LOCK(v_lock_id, 30)
- THEN
- SET v_calc = NULL;
- SET v_refresh = FALSE;
- LEAVE proc;
- END IF;
-
- -- Comprueba si el calculo solicitado existe y esta actualizado.
-
- SELECT c.id, ca.id, ca.expires, ca.last_refresh
- INTO v_cache_id, v_calc, v_expires, vLastRefresh
- FROM cache c
- LEFT JOIN cache_calc ca
- ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci'
- WHERE c.name = v_cache_name COLLATE 'utf8_general_ci';
-
- -- Si existe una calculo valido libera el bloqueo y devuelve su identificador.
-
- IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE()
- THEN
- DO RELEASE_LOCK(v_lock_id);
- SET v_refresh = FALSE;
- LEAVE proc;
- END IF;
-
- -- Si el calculo no existe le crea una entrada en la tabla de calculos.
-
- IF v_calc IS NULL
- THEN
- INSERT INTO cache_calc SET
- cache_id = v_cache_id,
- cacheName = v_cache_name,
- params = v_params,
- last_refresh = NULL,
- expires = NULL,
- connection_id = CONNECTION_ID();
-
- SET v_calc = LAST_INSERT_ID();
- ELSE
- UPDATE cache_calc
- SET
- last_refresh = NULL,
- expires = NULL,
- connection_id = CONNECTION_ID()
- WHERE id = v_calc;
- END IF;
-
- -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador.
-
- SET v_refresh = TRUE;
+proc: BEGIN
+ DECLARE v_valid BOOL;
+ DECLARE v_lock_id VARCHAR(100);
+ DECLARE v_cache_id INT;
+ DECLARE v_expires DATETIME;
+ DECLARE v_clean_time DATETIME;
+ DECLARE vLastRefresh DATETIME;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ IF v_lock_id IS NOT NULL THEN
+ DO RELEASE_LOCK(v_lock_id);
+ END IF;
+
+ RESIGNAL;
+ END;
+
+ SET v_params = IFNULL(v_params, '');
+
+ -- Si el servidor se ha reiniciado invalida todos los calculos.
+
+ SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid;
+
+ IF !v_valid
+ THEN
+ DELETE FROM cache_calc;
+ INSERT INTO cache_valid (valid) VALUES (TRUE);
+ END IF;
+
+ -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia.
+
+ SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params);
+
+ IF !GET_LOCK(v_lock_id, 30)
+ THEN
+ SET v_calc = NULL;
+ SET v_refresh = FALSE;
+ LEAVE proc;
+ END IF;
+
+ -- Comprueba si el calculo solicitado existe y esta actualizado.
+
+ SELECT c.id, ca.id, ca.expires, ca.last_refresh
+ INTO v_cache_id, v_calc, v_expires, vLastRefresh
+ FROM cache c
+ LEFT JOIN cache_calc ca
+ ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci'
+ WHERE c.name = v_cache_name COLLATE 'utf8_general_ci';
+
+ -- Si existe una calculo valido libera el bloqueo y devuelve su identificador.
+
+ IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE()
+ THEN
+ DO RELEASE_LOCK(v_lock_id);
+ SET v_refresh = FALSE;
+ LEAVE proc;
+ END IF;
+
+ -- Si el calculo no existe le crea una entrada en la tabla de calculos.
+
+ IF v_calc IS NULL
+ THEN
+ INSERT INTO cache_calc SET
+ cache_id = v_cache_id,
+ cacheName = v_cache_name,
+ params = v_params,
+ last_refresh = NULL,
+ expires = NULL,
+ connection_id = CONNECTION_ID();
+
+ SET v_calc = LAST_INSERT_ID();
+ ELSE
+ UPDATE cache_calc
+ SET
+ last_refresh = NULL,
+ expires = NULL,
+ connection_id = CONNECTION_ID()
+ WHERE id = v_calc;
+ END IF;
+
+ -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador.
+
+ SET v_refresh = TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -6729,7 +8382,7 @@ proc: BEGIN
FROM cache c
JOIN cache_calc ca ON c.id = ca.cache_id
WHERE ca.id = v_calc;
-
+
DELETE FROM cache_calc WHERE id = v_calc;
IF v_cache_name IS NOT NULL THEN
@@ -6774,11 +8427,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
- DECLARE vDateShort DATETIME;
-
- SET vDateShort = TIMESTAMPADD(MONTH, -1, util.VN_CURDATE());
-
- DELETE FROM cache.departure_limit WHERE Fecha < vDateShort;
+ DELETE FROM cache.departure_limit WHERE Fecha < util.VN_CURDATE() - INTERVAL 1 MONTH;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -6825,7 +8474,7 @@ DECLARE rs CURSOR FOR
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
- SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60;
+ SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60;
OPEN rs;
@@ -6834,23 +8483,23 @@ DECLARE rs CURSOR FOR
WHILE NOT done DO
SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0);
-
+
SET inicioProd = rsDeparture - rsHoras;
-
+
IF inicioProd - resto < myTime THEN
-
+
SET done = TRUE;
-
+
ELSE
-
+
SET departureLimit = rsDeparture;
-
+
FETCH rs INTO rsDeparture, rsHoras , rsInicio;
-
+
-- SELECT rsDeparture, rsHoras , rsInicio;
-
+
END IF;
-
+
END WHILE;
SET departureLimit = IFNULL(departureLimit,24);
@@ -6895,7 +8544,7 @@ proc: BEGIN
DECLARE started DATE;
DECLARE ended DATE;
DECLARE vLastRefresh DATE;
-
+
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
CALL cache_calc_unlock (vCalc);
@@ -6945,14 +8594,14 @@ proc: BEGIN
DECLARE datEQ DATETIME;
DECLARE timDIF TIME;
DECLARE v_calc INT;
-
+
CALL cache_calc_start (v_calc, v_refresh, 'prod_graphic', wh_id);
-
+
IF !v_refresh
THEN
LEAVE proc;
END IF;
-
+
CALL vn2008.production_control_source(wh_id, 0);
DELETE FROM prod_graphic_source;
@@ -6970,8 +8619,8 @@ proc: BEGIN
WHERE Fecha = util.VN_CURDATE()
GROUP BY wh_id, graphCategory
;
-
-
+
+
CALL cache_calc_end (v_calc);
END ;;
DELIMITER ;
@@ -6992,11 +8641,11 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `stock_refresh`(v_refresh BOOL)
proc: BEGIN
/**
- * Crea o actualiza la cache con el disponible hasta el dÃa de
+ * Crea o actualiza la cache con el disponible hasta el día de
* ayer. Esta cache es usada como base para otros procedimientos
- * como el cáculo del visible o del ATP.
+ * como el cálculo del visible o del ATP.
*
- * @param v_refresh %TRUE para forzar el recálculo de la cache
+ * @param v_refresh %TRUE para forzar el recálculo de la cache
**/
DECLARE v_calc INT;
DECLARE v_date_inv DATE;
@@ -7016,23 +8665,23 @@ proc: BEGIN
LEAVE proc;
END IF;
- SET v_date_inv = (SELECT inventoried FROM vn.config LIMIT 1);
+ SET v_date_inv = vn.getInventoryDate();
SET vCURDATE = util.VN_CURDATE();
-
+
DELETE FROM stock;
-
+
INSERT INTO stock (item_id, warehouse_id, amount)
SELECT item_id, warehouse_id, SUM(amount) amount FROM
(
- SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount
+ SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount
FROM vn.itemTicketOut
WHERE shipped >= v_date_inv AND shipped < vCURDATE
UNION ALL
- SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount
+ SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount
FROM vn.itemEntryIn
WHERE landed >= v_date_inv AND landed < vCURDATE AND isVirtualStock is FALSE
UNION ALL
- SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount
+ SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount
FROM vn.itemEntryOut
WHERE shipped >= v_date_inv AND shipped < vCURDATE
) t
@@ -7062,12 +8711,12 @@ BEGIN
(INDEX (id))
ENGINE = MEMORY
SELECT id FROM cache_calc;
-
+
DELETE v
FROM visible v
LEFT JOIN tCalc c ON c.id = v.calc_id
WHERE c.id IS NULL;
-
+
DROP TEMPORARY TABLE tCalc;
END ;;
DELIMITER ;
@@ -7126,6 +8775,235 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
+--
+-- Current Database: `dipole`
+--
+
+CREATE DATABASE /*!32312 IF NOT EXISTS*/ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
+
+USE `dipole`;
+
+--
+-- Temporary table structure for view `expeditionControl`
+--
+
+DROP TABLE IF EXISTS `expeditionControl`;
+/*!50001 DROP VIEW IF EXISTS `expeditionControl`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `expeditionControl` AS SELECT
+ 1 AS `fecha`,
+ 1 AS `total`,
+ 1 AS `leidas` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `expedition_PrintOut`
+--
+
+DROP TABLE IF EXISTS `expedition_PrintOut`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `expedition_PrintOut` (
+ `expeditionFk` int(11) NOT NULL,
+ `ticketFk` int(11) NOT NULL,
+ `addressFk` int(11) NOT NULL,
+ `street` varchar(42) NOT NULL DEFAULT ' ',
+ `postalCode` varchar(10) NOT NULL DEFAULT ' ',
+ `city` varchar(100) NOT NULL DEFAULT ' ',
+ `shopName` varchar(100) NOT NULL DEFAULT ' ',
+ `isPrinted` int(11) NOT NULL DEFAULT 0,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `printerFk` tinyint(3) unsigned NOT NULL DEFAULT 0,
+ `routeFk` int(11) NOT NULL DEFAULT 0,
+ `parkingCode` varchar(8) NOT NULL DEFAULT ' ',
+ `truckName` varchar(25) NOT NULL DEFAULT ' ',
+ `clientFk` int(11) NOT NULL,
+ `phone` varchar(15) DEFAULT NULL,
+ `province` varchar(20) NOT NULL,
+ `agency` varchar(100) DEFAULT NULL,
+ `m3` decimal(10,3) DEFAULT 0.000,
+ `workerCode` varchar(25) DEFAULT NULL,
+ `itemFk` int(11) DEFAULT NULL,
+ `quantity` int(11) DEFAULT NULL,
+ `longName` varchar(30) DEFAULT NULL,
+ `shelvingFk` varchar(5) DEFAULT NULL,
+ `comments` varchar(100) DEFAULT NULL,
+ PRIMARY KEY (`expeditionFk`),
+ KEY `expedition_PrintOut_FK` (`printerFk`),
+ CONSTRAINT `expedition_PrintOut_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='listado de etiquetas a imprimir';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `expedition_Read`
+--
+
+DROP TABLE IF EXISTS `expedition_Read`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `expedition_Read` (
+ `expeditionFk` int(11) NOT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `readingPointFk` int(11) DEFAULT NULL,
+ PRIMARY KEY (`expeditionFk`),
+ KEY `expedition_Read_FK` (`readingPointFk`),
+ CONSTRAINT `expedition_Read_FK` FOREIGN KEY (`readingPointFk`) REFERENCES `readingPoint` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `printer`
+--
+
+DROP TABLE IF EXISTS `printer`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `printer` (
+ `id` tinyint(3) unsigned NOT NULL,
+ `description` varchar(50) NOT NULL,
+ PRIMARY KEY (`id`),
+ CONSTRAINT `printer_FK` FOREIGN KEY (`id`) REFERENCES `vn`.`printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `readingPoint`
+--
+
+DROP TABLE IF EXISTS `readingPoint`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `readingPoint` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(100) NOT NULL,
+ `IsCeluveyorDoor` tinyint(1) NOT NULL COMMENT 'define si esta la antena en la entrada del celuveyor y ha de generar un movimiento',
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Dumping events for database 'dipole'
+--
+
+--
+-- Dumping routines for database 'dipole'
+--
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `clean` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
+BEGIN
+ DECLARE vFromDated DATE;
+
+ SET vFromDated = TIMESTAMPADD(WEEK, -2, util.VN_CURDATE());
+
+ DELETE FROM dipole.expedition_PrintOut
+ WHERE created < vFromDated;
+
+ DELETE FROM dipole.expedition_Read
+ WHERE created < vFromDated;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_add`(vExpeditionFk INT, vPrinterFk INT, vIsPrinted BOOLEAN)
+BEGIN
+/** Insert records to print agency stickers and to inform sorter with new box
+ *
+ * param vExpeditionFk Id for vn.expedition
+ * param vPrinterFk Id for dipole.printer
+ * param vIsPrinted Value for field dipole.expedition_PrintOut.isPrinted
+ */
+ INSERT INTO dipole.expedition_PrintOut(expeditionFk,
+ ticketFk,
+ addressFk,
+ street,
+ postalCode,
+ city,
+ shopName,
+ printerFk,
+ routeFk,
+ parkingCode,
+ truckName,
+ clientFk,
+ phone,
+ province,
+ agency,
+ workerCode,
+ isPrinted)
+ SELECT e.id,
+ e.ticketFk,
+ t.addressFk ,
+ LEFT(a.street, 100),
+ a.postalCode ,
+ LEFT (CONCAT(IFNULL(rm.beachFk,''),' ',a.city), 13),
+ a.nickname,
+ vPrinterFk,
+ IFNULL(right(`t`.`routeFk`, 3),0),
+ if (@vVolume := vn.ticketTotalVolume(t.id) > 1.5, @vVolume, IFNULL( rm.beachFk, 0)),
+ LEFT(IFNULL(et.description ,replace(`z`.`name`, 'ZONA ', 'Z')),14) truckName,
+ t.clientFk ,
+ ifnull(c.mobile, ifnull(a.mobile, ifnull(c.phone, a.phone))),
+ LEFT(p.name, 20),
+ NULL,
+ w.code,
+ vIsPrinted
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.address a ON a.id = t.addressFk
+ JOIN vn.province p ON p.id = a.provinceFk
+ LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
+ LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ LEFT JOIN vn.beach b ON b.code = rm.beachFk
+ LEFT JOIN vn.`zone`z ON z.id = t.zoneFk
+ JOIN vn.agencyMode am ON t.agencyModeFk = am.id
+ JOIN vn.client c ON t.clientFk = c.id
+ JOIN vn.agency ag ON ag.id = am.agencyFk
+ JOIN vn.printer pr ON pr.id = vPrinterFk
+ JOIN vn.worker w ON w.id = e.workerFk
+ WHERE e.id = vExpeditionFk;
+
+ INSERT INTO srt.expedition (id,
+ width,
+ `length`,
+ height,
+ stateFk)
+ SELECT e.id,
+ p.width * 10,
+ p.`depth` * 10,
+ p.height * 10,
+ es.id
+ FROM vn.expedition e
+ LEFT JOIN vn.packaging p ON p.id = e.packagingFk
+ JOIN srt.expeditionState es ON es.description = 'PRINTED'
+ WHERE e.id = vExpeditionFk; -- En esa tabla las medidas van en milímetros
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+
--
-- Current Database: `edi`
--
@@ -7282,7 +9160,7 @@ CREATE TABLE `deliveryInformation` (
KEY `fgbSupplyResponse_idx3` (`LatestOrderDateTime`) USING BTREE,
KEY `deliveryInformation_updated_IDX` (`updated`) USING BTREE,
CONSTRAINT `fgbSupplyResponse` FOREIGN KEY (`supplyResponseID`) REFERENCES `supplyResponse` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7366,7 +9244,7 @@ CREATE TABLE `ekt` (
KEY `ekt_batchNumber` (`batchNumber`) USING BTREE,
KEY `ekt_vendorOrderNumber` (`vendorOrderNumber`) USING BTREE,
KEY `ekt_sub_IDX` (`sub`) USING BTREE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7386,6 +9264,61 @@ CREATE TABLE `ektConfig` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `ektK1`
+--
+
+DROP TABLE IF EXISTS `ektK1`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `ektK1` (
+ `id` smallint(6) unsigned NOT NULL,
+ `description` varchar(50) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Características negativas de los articulos de subasta';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `ektK2`
+--
+
+DROP TABLE IF EXISTS `ektK2`;
+/*!50001 DROP VIEW IF EXISTS `ektK2`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `ektK2` AS SELECT
+ 1 AS `id`,
+ 1 AS `description` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `ektK3`
+--
+
+DROP TABLE IF EXISTS `ektK3`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `ektK3` (
+ `id` smallint(6) unsigned NOT NULL,
+ `description` varchar(50) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Características fitosanitarias de los articulos de subasta';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `ektK4`
+--
+
+DROP TABLE IF EXISTS `ektK4`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `ektK4` (
+ `id` smallint(6) unsigned NOT NULL,
+ `description` varchar(50) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Características calidad de los articulos de subasta';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Temporary table structure for view `ektRecent`
--
@@ -7484,7 +9417,7 @@ CREATE TABLE `exchange` (
KEY `buy_edi_id` (`ektFk`),
CONSTRAINT `exchange_ibfk_1` FOREIGN KEY (`mailFk`) REFERENCES `mail` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `exchange_ibfk_2` FOREIGN KEY (`ektFk`) REFERENCES `ekt` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7503,7 +9436,7 @@ CREATE TABLE `exchangeConfig` (
PRIMARY KEY (`id`),
KEY `presale_id` (`presaleFk`),
CONSTRAINT `exchangeConfig_ibfk_1` FOREIGN KEY (`presaleFk`) REFERENCES `exchangeType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuration parameters';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7581,7 +9514,7 @@ CREATE TABLE `ftpConfig` (
`user` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`password` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuration parameters';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7693,28 +9626,6 @@ CREATE TABLE `item_feature` (
PRIMARY KEY (`item_id`,`presentation_order`,`entry_date`,`change_date_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='/tmp/floricode/florecompc2/FY130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `edi`.`item_feature_bi`
- BEFORE INSERT ON `item_feature`
- FOR EACH ROW
-BEGIN
- IF NEW.expiry_date = '0000-00-00' THEN
- SET NEW.expiry_date = NULL;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `item_free`
@@ -7759,11 +9670,13 @@ CREATE TABLE `item_groupToOffer` (
`itemTypeFk` smallint(5) unsigned NOT NULL,
`intrastatFk` int(8) unsigned zerofill NOT NULL,
`originFk` tinyint(2) unsigned NOT NULL DEFAULT 17,
- `expenseFk` varchar(10) DEFAULT '7001000000',
+ `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT '7001000000',
PRIMARY KEY (`group_code`),
KEY `item_groupToOffer_fk2_idx` (`itemTypeFk`),
KEY `item_groupToOffer_fk3_idx` (`intrastatFk`),
KEY `item_groupToOffer_fk4_idx` (`originFk`),
+ KEY `item_groupToOffer_expense_FK` (`expenseFk`),
+ CONSTRAINT `item_groupToOffer_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `vn`.`expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `item_groupToOffer_fk2` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn`.`itemType` (`id`),
CONSTRAINT `item_groupToOffer_fk3` FOREIGN KEY (`intrastatFk`) REFERENCES `vn`.`intrastat` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `item_groupToOffer_fk4` FOREIGN KEY (`originFk`) REFERENCES `vn`.`origin` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
@@ -7811,7 +9724,7 @@ CREATE TABLE `log` (
`fieldValue` varchar(100) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7834,7 +9747,7 @@ CREATE TABLE `mail` (
UNIQUE KEY `mail_id` (`messageId`),
KEY `sender_id` (`senderFk`),
CONSTRAINT `mail_ibfk_2` FOREIGN KEY (`senderFk`) REFERENCES `mailSender` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7850,7 +9763,7 @@ CREATE TABLE `mailSender` (
`kop` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mail` (`mail`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='List of allowed mailers';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='List of allowed mailers';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7903,7 +9816,7 @@ CREATE TABLE `offerRefreshConfig` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`dayRange` int(10) unsigned DEFAULT NULL COMMENT 'range of days to update the photos of an article in seconds',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7924,7 +9837,7 @@ CREATE TABLE `param` (
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`),
UNIQUE KEY `name` (`name`,`subname`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Parameters to capture of every exchange';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Parameters to capture of every exchange';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -7974,171 +9887,8 @@ CREATE TABLE `putOrder` (
KEY `supplyResponseID_idx` (`supplyResponseID`),
KEY `putOrder_FK` (`saleFk`),
CONSTRAINT `putOrder_FK` FOREIGN KEY (`saleFk`) REFERENCES `vn`.`sale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `edi`.`putOrder_BEFORE_INSERT`
- BEFORE INSERT ON `putOrder`
- FOR EACH ROW
-BEGIN
-
- DECLARE nextID INT;
-
- SELECT 1 + MAX(id) INTO nextID FROM putOrder ;
-
- SET NEW.orderTradelineItemID = nextID;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `edi`.`BEFORE UPDATE`
- BEFORE UPDATE ON `putOrder`
- FOR EACH ROW
-BEGIN
-
- DECLARE vError VARCHAR(100) DEFAULT 'Orderregel niet meer teruggevonden op basis van de orderps';
- DECLARE vVmpIdError INT DEFAULT 7;
- DECLARE vVmpFk INT;
- DECLARE vSupplyResponseNumberOfUnits INT;
-
- SELECT sr.vmpID INTO vVmpFk
- FROM edi.supplyResponse sr
- WHERE sr.id = NEW.supplyResponseID;
-
- IF NEW.OrderStatus = 3
- AND NOT (NEW.OrderStatus <=> OLD.OrderStatus)
- AND NEW.error = vError
- AND vVmpFk = vVmpIdError
-
- THEN
-
- SET NEW.OrderStatus = 2;
-
- END IF;
-
- -- Error de disponible menor de lo solicitado
- IF NEW.error LIKE 'error2602%' THEN
-
- SELECT NumberOfUnits INTO vSupplyResponseNumberOfUnits
- FROM edi.supplyResponse sr
- WHERE sr.ID = NEW.supplyResponseID;
-
- SET NEW.error = CONCAT('(',vSupplyResponseNumberOfUnits,') ', NEW.error);
-
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `edi`.`putOrder_AFTER_UPDATE`
- AFTER UPDATE ON `putOrder`
- FOR EACH ROW
-BEGIN
- DECLARE vSaleFk INT;
- DECLARE vOrderStatusDenied INT DEFAULT 3;
- DECLARE vOrderStatusOK INT DEFAULT 2;
- DECLARE vIsEktSender BOOLEAN;
-
- IF NEW.OrderStatus = vOrderStatusDenied AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN
-
- SELECT s.id INTO vSaleFk
- FROM vn.sale s
- JOIN vn.ticket t ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN deliveryInformation di ON di.ID = NEW.deliveryInformationID
- WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE()
- AND i.supplyResponseFk = NEW.supplyResponseID
- LIMIT 1;
-
- UPDATE vn.sale s
- JOIN vn.ticket t ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN deliveryInformation di ON di.ID = NEW.deliveryInformationID
- SET s.quantity = 0
- WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE()
- AND i.supplyResponseFk = NEW.supplyResponseID;
-
- INSERT INTO vn.mail (sender, `subject`, body)
- SELECT IF(u.id IS NOT NULL AND c.email IS NOT NULL,
- c.email,
- CONCAT(account.user_getNameFromId(c.salesPersonFk), '@verdnatura.es')
- ),
- 'Producto no disponible en Floramondo',
- CONCAT('El artículo ', s.concept, ' del ticket ', t.id , ' ha sido cancelado por Floramondo. ',
- ' Se ha actualizado la cantidad de ', OLD.quantity,' a 0. ',
- IF (u.id IS NOT NULL AND c.email IS NOT NULL ,
- CONCAT('https://shop.verdnatura.es/#!form=ecomerce%2Fticket&ticket=', t.id ),
- CONCAT('https://salix.verdnatura.es/#!/ticket/', t.id ,'/summary')))
- FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.`client` c ON c.id = t.clientFk
- LEFT JOIN account.user u ON u.id= c.salesPersonFk AND u.name IN ('ruben', 'ismaelalcolea')
- WHERE s.id = vSaleFk;
-
- END IF;
-
-
- IF NEW.OrderStatus = vOrderStatusOK AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN
-
- SELECT v.isEktSender INTO vIsEktSender
- FROM edi.VMPSettings v
- JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID
- WHERE sr.id = NEW.supplyResponseID;
-
- IF NOT vIsEktSender THEN
-
- CALL edi.ekt_add(NEW.id);
-
- END IF;
-
- IF NEW.barcode THEN
-
- INSERT IGNORE INTO vn.itemBarcode(itemFk, code)
- SELECT i.id, NEW.barcode
- FROM vn.item i
- WHERE i.supplyResponseFk = NEW.supplyResponseID;
-
- END IF;
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `specie`
@@ -8308,41 +10058,8 @@ CREATE TABLE `supplyResponse` (
KEY `supplyResponse_updated_IDX` (`updated`) USING BTREE,
CONSTRAINT `supplyResponse_fk2` FOREIGN KEY (`MarketPlaceID`) REFERENCES `marketPlace` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `supplyResponseputOrder_FK` FOREIGN KEY (`vmpID`) REFERENCES `VMPSettings` (`VMPID`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `edi`.`supplyResponse_AFTER_UPDATE`
- AFTER UPDATE ON `supplyResponse`
- FOR EACH ROW
-BEGIN
-
- UPDATE vn.buy b
- JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.travel tr ON tr.id = e.travelFk
- JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
- JOIN vn.item i ON i.id = b.itemFk
- JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID
- SET b.quantity = NEW.NumberOfItemsPerCask * NEW.NumberOfUnits,
- b.stickers = NEW.NumberOfUnits
- WHERE i.supplyResponseFk = NEW.ID
- AND am.name = 'LOGIFLORA'
- AND e.isRaid
- AND tr.landed >= util.VN_CURDATE();
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `supplyResponseLog`
@@ -8361,7 +10078,7 @@ CREATE TABLE `supplyResponseLog` (
PRIMARY KEY (`id`),
KEY `supplyResponseLog_FK` (`supplyResponseFk`),
CONSTRAINT `supplyResponseLog_FK` FOREIGN KEY (`supplyResponseFk`) REFERENCES `supplyResponse` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Esta tabla la utiliza la empresa LOGIFLORA. No kkear.';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Esta tabla la utiliza la empresa LOGIFLORA. No kkear.';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -8446,14 +10163,14 @@ DELIMITER ;;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
-/*!50003 SET character_set_client = utf8mb3 */ ;;
-/*!50003 SET character_set_results = utf8mb3 */ ;;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
+/*!50003 SET character_set_client = utf8mb4 */ ;;
+/*!50003 SET character_set_results = utf8mb4 */ ;;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `floramondo` ON SCHEDULE EVERY 6 MINUTE STARTS '2022-01-28 09:52:45' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO CALL edi.floramondo_offerRefresh() */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `floramondo` ON SCHEDULE EVERY 6 MINUTE STARTS '2022-01-28 09:52:45' ON COMPLETION NOT PRESERVE DISABLE DO CALL edi.floramondo_offerRefresh() */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -8478,7 +10195,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `imageName`(vPictureReference VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
-
+
SET vPictureReference = REPLACE(vPictureReference,'.','');
SET vPictureReference = REPLACE(vPictureReference,'/','');
@@ -8490,7 +10207,7 @@ BEGIN
SET vPictureReference = REPLACE(vPictureReference,'?','');
SET vPictureReference = REPLACE(vPictureReference,'=','');
-
+
RETURN vPictureReference;
END ;;
@@ -8546,27 +10263,27 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryInformation_Delete`()
BEGIN
-
+
DECLARE vID INT;
DECLARE vGap INT DEFAULT 100;
DECLARE vTope INT;
-
- SELECT MIN(ID), MAX(ID)
+
+ SELECT MIN(ID), MAX(ID)
INTO vID, vTope
FROM edi.deliveryInformation;
- WHILE vID <= vTope DO
-
+ WHILE vID <= vTope DO
+
SET vID = vID + vGap;
-
- DELETE
- FROM edi.deliveryInformation
+
+ DELETE
+ FROM edi.deliveryInformation
WHERE ID < vID
AND EarliestDespatchDateTime IS NULL;
-
+
END WHILE;
-
-
+
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -8585,15 +10302,15 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_add`(vPutOrderFk INT)
BEGIN
-
+
/**
* Añade ekt para las ordenes de compra de proveedores que no envian el ekt por email
- *
+ *
* @param vPutOrderFk PutOrderId de donde coger los datos
**/
-
- INSERT INTO edi.ekt(entryYear,
- deliveryNumber,
+
+ INSERT INTO edi.ekt(entryYear,
+ deliveryNumber,
fec,
hor,
item,
@@ -8633,17 +10350,17 @@ BEGIN
i.value10 s6,
p.id putOrderFk,
sr.Item_ArticleCode,
- sr.vmpID
+ sr.vmpID
FROM edi.putOrder p
- JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID
- JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID
- JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
- JOIN vn.item i ON i.supplyResponseFk = sr.ID
- JOIN vn.origin o ON o.id = i.originFk
+ JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID
+ JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID
+ JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
+ JOIN vn.item i ON i.supplyResponseFk = sr.ID
+ JOIN vn.origin o ON o.id = i.originFk
WHERE p.id = vPutOrderFk;
-
+
CALL edi.ekt_load(LAST_INSERT_ID());
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -8662,7 +10379,12 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_load`(IN `vSelf` INT)
proc:BEGIN
-
+/**
+ * Carga los datos esenciales para el sistema EKT.
+ * Inserta compras y ventas si es necesario.
+ *
+ * @param vSelf Id de ekt
+ */
DECLARE vRef INT;
DECLARE vBuy INT;
DECLARE vItem INT;
@@ -8670,68 +10392,67 @@ proc:BEGIN
DECLARE vPackage INT;
DECLARE vPutOrderFk INT;
DECLARE vIsLot BOOLEAN;
- DECLARE vForceToPacking INT DEFAULT 2;
- DECLARE vEntryFk INT;
- DECLARE vHasToChangePackagingFk BOOLEAN;
- DECLARE vIsFloramondoDirect BOOLEAN;
- DECLARE vTicketFk INT;
+ DECLARE vForceToPacking INT DEFAULT 2;
+ DECLARE vEntryFk INT;
+ DECLARE vHasToChangePackagingFk BOOLEAN;
+ DECLARE vIsFloramondoDirect BOOLEAN;
+ DECLARE vTicketFk INT;
DECLARE vHasItemGroup BOOL;
DECLARE vDescription VARCHAR(255);
DECLARE vSaleFk INT;
+ DECLARE vDefaultEntry INT;
-- Carga los datos necesarios del EKT
-
- SELECT e.ref, qty, package, putOrderFk MOD 1000000, i2.id , NOT ISNULL(eea.addressFk), NOT ISNULL(igto.group_code),
+ SELECT e.ref, qty, package, putOrderFk MOD 1000000, i2.id , NOT ISNULL(eea.addressFk), NOT ISNULL(igto.group_code),
CONCAT(e.`ref`, ' ', e.item, ' ', e.sub, ' EktFk:', e.id)
INTO vRef, vQty, vPackage, vPutOrderFk, vItem, vIsFloramondoDirect, vHasItemGroup, vDescription
- FROM edi.ekt e
- LEFT JOIN edi.item i ON e.ref = i.id
- LEFT JOIN edi.putOrder po ON po.id = e.putOrderFk
- LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID
+ FROM ekt e
+ LEFT JOIN item i ON e.ref = i.id
+ LEFT JOIN putOrder po ON po.id = e.putOrderFk
+ LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID
LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub
- LEFT JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id
+ LEFT JOIN item_groupToOffer igto ON igto.group_code = i.group_id
WHERE e.id = vSelf
LIMIT 1;
-
+
IF NOT vHasItemGroup THEN
-
CALL vn.mail_insert('logistica@verdnatura.es', 'nocontestar@verdnatura.es', 'Nuevo grupo en Floramondo', vDescription);
-
CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription);
-
LEAVE proc;
-
END IF;
+ SELECT defaultEntry INTO vDefaultEntry
+ FROM vn.entryConfig;
+
-- Asigna la entrada
- SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk;
-
+ SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk;
+
-- Inserta el cubo si no existe
IF vPackage = 800 THEN
-
+
SET vHasToChangePackagingFk = TRUE;
-
+
IF vItem THEN
-
+
SELECT vn.item_getPackage(vItem) INTO vPackage ;
-
+
ELSE
-
- SET vPackage = 8000 + vQty;
+
+ SET vPackage = 8000 + vQty;
INSERT IGNORE INTO vn.packaging(id, width, `depth`)
SELECT vPackage, vc.ccLength / vQty, vc.ccWidth
FROM vn.volumeConfig vc;
-
+
END IF;
-
+
ELSE
-
+
INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z)
SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10)
FROM bucket WHERE bucket_id = vPackage;
-
+
IF ROW_COUNT() > 0
THEN
INSERT INTO vn2008.mail SET
@@ -8740,35 +10461,30 @@ proc:BEGIN
`to` = 'ekt@verdnatura.es';
END IF;
END IF;
-
+
-- Si es una compra de Logiflora obtiene el articulo
IF vPutOrderFk THEN
-
SELECT i.id INTO vItem
- FROM edi.putOrder po
+ FROM putOrder po
JOIN vn.item i ON i.supplyResponseFk = po.supplyResponseID
WHERE po.id = vPutOrderFk
LIMIT 1;
-
END IF;
- INSERT IGNORE INTO item_track SET
- item_id = vRef;
-
- IF IFNULL(vItem,0) = 0 THEN
-
+ INSERT IGNORE INTO item_track
+ SET item_id = vRef;
+
+ IF vItem IS NULL THEN
-- Intenta obtener el artículo en base a los atributos holandeses
-
SELECT b.id, IFNULL(b.itemOriginalFk ,b.itemFk) INTO vBuy, vItem
- FROM edi.ekt e
- JOIN edi.item_track t ON t.item_id = e.ref
- LEFT JOIN edi.ekt l ON l.ref = e.ref
+ FROM ekt e
+ JOIN item_track t ON t.item_id = e.ref
+ LEFT JOIN ekt l ON l.ref = e.ref
LEFT JOIN vn.buy b ON b.ektFk = l.id
LEFT JOIN vn.item i ON i.id = b.itemFk
- JOIN vn2008.config cfg
WHERE e.id = vSelf
AND l.id != vSelf
- AND b.itemFk != cfg.generic_item
+ AND b.itemFk != vDefaultEntry
AND IF(t.s1, l.s1 = e.s1, TRUE)
AND IF(t.s2, l.s2 = e.s2, TRUE)
AND IF(t.s3, l.s3 = e.s3, TRUE)
@@ -8781,89 +10497,76 @@ proc:BEGIN
AND IF(t.pro, l.pro = e.pro, TRUE)
AND IF(t.package, l.package = e.package, TRUE)
AND IF(t.item, l.item = e.item, TRUE)
- AND i.isFloramondo = vIsFloramondoDirect
- ORDER BY l.now DESC, b.id ASC
+ AND i.isFloramondo = vIsFloramondoDirect
+ ORDER BY l.now DESC, b.id ASC
LIMIT 1;
END IF;
-
+
-- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo
- IF ISNULL(vItem) AND vIsFloramondoDirect THEN
-
- CALL edi.item_getNewByEkt(vSelf, vItem);
-
+ IF vItem IS NULL AND vIsFloramondoDirect THEN
+ CALL item_getNewByEkt(vSelf, vItem);
END IF;
+
+ INSERT INTO vn.buy (
+ entryFk,
+ ektFk,
+ buyingValue,
+ itemFk,
+ stickers,
+ packing,
+ `grouping`,
+ quantity,
+ groupingMode,
+ packagingFk,
+ weight)
+ SELECT vEntryFk,
+ vSelf,
+ (@t := IF(i.stems, i.stems, 1)) * e.pri / IFNULL(i.stemMultiplier, 1) buyingValue,
+ IFNULL(vItem, vDefaultEntry) itemFk,
+ e.qty stickers,
+ @pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing,
+ IFNULL(b.`grouping`, e.pac),
+ @pac * e.qty,
+ vForceToPacking,
+ IF(vHasToChangePackagingFk OR b.packagingFk IS NULL, vPackage, b.packagingFk),
+ (IFNULL(i.weightByPiece, 0) * @pac) / 1000
+ FROM ekt e
+ LEFT JOIN vn.buy b ON b.id = vBuy
+ LEFT JOIN vn.item i ON i.id = b.itemFk
+ LEFT JOIN vn.supplier s ON e.pro = s.id
+ WHERE e.id = vSelf
+ LIMIT 1;
- INSERT INTO vn.buy
- (
- entryFk
- ,ektFk
- ,buyingValue
- ,itemFk
- ,stickers
- ,packing
- ,`grouping`
- ,quantity
- ,groupingMode
- ,packageFk
- ,weight
- )
- SELECT
- vEntryFk
- ,vSelf
- ,(@t := IF(i.stems, i.stems, 1)) * e.pri / IFNULL(i.stemMultiplier, 1) buyingValue
- ,IFNULL(vItem, cfg.generic_item) itemFk
- ,e.qty stickers
- ,@pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing
- ,IFNULL(b.`grouping`, e.pac)
- ,@pac * e.qty
- ,vForceToPacking
- ,IF(vHasToChangePackagingFk OR ISNULL(b.packageFk), vPackage, b.packageFk)
- ,(IFNULL(i.weightByPiece,0) * @pac)/1000
- FROM edi.ekt e
- LEFT JOIN vn.buy b ON b.id = vBuy
- LEFT JOIN vn.item i ON i.id = b.itemFk
- LEFT JOIN vn.supplier s ON e.pro = s.id
- JOIN vn2008.config cfg
- WHERE e.id = vSelf
- LIMIT 1;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
-
- CREATE TEMPORARY TABLE tmp.buyRecalc
+ CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc
SELECT buy.id
- FROM vn.buy
+ FROM vn.buy
WHERE ektFk = vSelf;
CALL vn.buy_recalcPrices();
-- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy
IF vPutOrderFk THEN
-
REPLACE vn.saleBuy(saleFk, buyFk, workerFk)
SELECT po.saleFk, b.id, account.myUser_getId()
- FROM edi.putOrder po
+ FROM putOrder po
JOIN vn.buy b ON b.ektFk = vSelf
WHERE po.id = vPutOrderFk;
-
END IF;
+
-- Si es una compra directa en Floramondo hay que añadirlo al ticket
-
IF vIsFloramondoDirect THEN
-
SELECT t.id INTO vTicketFk
- FROM vn.ticket t
- JOIN vn.ektEntryAssign eea
- ON eea.addressFk = t.addressFk
+ FROM vn.ticket t
+ JOIN vn.ektEntryAssign eea ON eea.addressFk = t.addressFk
AND t.warehouseFk = eea.warehouseInFk
- JOIN edi.ekt e
- ON e.sub = eea.sub
+ JOIN ekt e ON e.sub = eea.sub
AND e.id = vSelf
- WHERE e.fec = t.shipped
- LIMIT 1;
-
- IF ISNULL(vTicketFk) THEN
-
+ WHERE e.fec = t.shipped
+ LIMIT 1;
+
+ IF vTicketFk IS NULL THEN
+ SET @clientFk = NULL;
INSERT INTO vn.ticket (
clientFk,
shipped,
@@ -8875,22 +10578,20 @@ proc:BEGIN
landed,
zoneFk,
zonePrice,
- zoneBonus
- )
- SELECT
- a.clientFk,
- e.fec,
- a.id,
- a.agencyModeFk,
- a.nickname,
- eea.warehouseInFk,
- c.id,
- e.fec,
- z.id,
- z.price,
- z.bonus
- FROM edi.ekt e
- JOIN vn.ektEntryAssign eea ON eea.sub = e.sub
+ zoneBonus)
+ SELECT @clientFk := a.clientFk,
+ e.fec,
+ a.id,
+ a.agencyModeFk,
+ a.nickname,
+ eea.warehouseInFk,
+ c.id,
+ e.fec,
+ z.id,
+ z.price,
+ z.bonus
+ FROM ekt e
+ JOIN vn.ektEntryAssign eea ON eea.sub = e.sub
JOIN vn.address a ON a.id = eea.addressFk
JOIN vn.company c ON c.code = 'VNL'
JOIN vn.`zone` z ON z.code = 'FLORAMONDO'
@@ -8899,39 +10600,36 @@ proc:BEGIN
SET vTicketFk = LAST_INSERT_ID();
- INSERT INTO vn.ticketLog
- SET originFk = vTicketFk,
- userFk = account.myUser_getId(),
- `action` = 'insert',
- description = CONCAT('EktLoad ha creado el ticket:', ' ', vTicketFk);
-
+ IF @clientFk IS NULL THEN
+ CALL util.throw(CONCAT("Ticket creation failed: ", vSelf));
+ END IF;
END IF;
INSERT INTO vn.sale (itemFk, ticketFk, concept, quantity, price)
SELECT vItem, vTicketFk, e.item, e.qty * e.pac, e.pri * ( 1 + fhc.floramondoMargin )
- FROM edi.ekt e
- JOIN edi.floraHollandConfig fhc
- WHERE e.id = vSelf;
+ FROM ekt e
+ JOIN floraHollandConfig fhc
+ WHERE e.id = vSelf;
SELECT LAST_INSERT_ID() INTO vSaleFk;
REPLACE vn.saleBuy(saleFk, buyFk, workerFk)
SELECT vSaleFk, b.id, account.myUser_getId()
FROM vn.buy b
- WHERE b.ektFk = vSelf;
+ WHERE b.ektFk = vSelf;
INSERT INTO vn.saleComponent(saleFk, componentFk, value)
SELECT vSaleFk, c.id, e.pri
- FROM edi.ekt e
+ FROM ekt e
JOIN vn.component c ON c.code = 'purchaseValue'
- WHERE e.id = vSelf;
+ WHERE e.id = vSelf;
INSERT INTO vn.saleComponent(saleFk, componentFk, value)
- SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin
- FROM edi.ekt e
- JOIN edi.floraHollandConfig fhc
+ SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin
+ FROM ekt e
+ JOIN floraHollandConfig fhc
JOIN vn.component c ON c.code = 'margin'
- WHERE e.id = vSelf;
+ WHERE e.id = vSelf;
END IF;
DROP TEMPORARY TABLE tmp.buyRecalc;
END ;;
@@ -9067,8 +10765,8 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_scan`(vBarcode VARCHAR(512))
BEGIN
/**
- * Busca transaciones a partir de un código de barras, las marca como escaneadas
- * y las devuelve.
+ * Busca transaciones a partir de un codigo de barras, las marca como escaneadas
+ * y las devuelve.
* Ver https://wiki.verdnatura.es/index.php/Ekt#Algoritmos_de_lectura
*
* @param vBarcode Código de compra de una etiqueta de subasta
@@ -9107,19 +10805,19 @@ BEGIN
ENGINE = MEMORY
SELECT id ektFk FROM ekt LIMIT 0;
- CASE
+ CASE
WHEN LENGTH(vBarcode) <= vFloridayBarcodeLength THEN
INSERT INTO tmp.ekt
- SELECT id
+ SELECT id
FROM edi.ektRecent e
WHERE e.cps = vBarcode
OR e.batchNumber = vBarcode;
WHEN LENGTH(vBarcode) = vFloramondoBarcodeLength THEN
INSERT INTO tmp.ekt
- SELECT e.id
+ SELECT e.id
FROM edi.ektRecent e
- WHERE e.pro = MID(vBarcode,2,6)
+ WHERE e.pro = MID(vBarcode,2,6)
AND CAST(e.ptd AS SIGNED) = MID(vBarcode,8,5);
ELSE
@@ -9134,11 +10832,11 @@ BEGIN
-- Clásico de subasta
-- Trade standard
-- Trade que construye como la subasta
- -- Trade como el anterior pero sin trade code
+ -- Trade como el anterior pero sin trade code
INSERT INTO tmp.ekt
SELECT id
FROM ekt
- WHERE fec = vFec
+ WHERE fec >= vFec - INTERVAL 1 DAY
AND ((
vKlo = vDefaultKlo
AND (klo = vKlo OR klo IS NULL OR klo = 0)
@@ -9147,7 +10845,7 @@ BEGIN
AND auction = vAuction
AND agj = vShortAgj)
)
- ORDER BY agj DESC
+ ORDER BY agj DESC, fec DESC
LIMIT 1;
SELECT COUNT(*) FROM tmp.ekt INTO vIsFound;
@@ -9155,9 +10853,9 @@ BEGIN
-- BatchNumber largo
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
- SELECT id
+ SELECT id
FROM edi.ektRecent e
- WHERE e.batchNumber
+ WHERE e.batchNumber
= LEFT(vBarcode,vUsefulAuctionLeftSegmentLength)
AND e.batchNumber > 0;
@@ -9167,7 +10865,7 @@ BEGIN
-- Order Number
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
- SELECT id
+ SELECT id
FROM edi.ektRecent e
WHERE e.putOrderFk = vBarcode;
@@ -9177,7 +10875,7 @@ BEGIN
-- deliveryNumber incrustado
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
- SELECT id
+ SELECT id
FROM edi.ektRecent e
WHERE e.deliveryNumber
= MID(vBarcode, 4, 13)
@@ -9188,7 +10886,7 @@ BEGIN
END CASE;
IF vIsFound THEN
- UPDATE ekt e
+ UPDATE ekt e
JOIN tmp.ekt t ON t.ektFk = e.id
SET e.scanned = TRUE;
END IF;
@@ -9209,524 +10907,524 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`()
-proc: BEGIN
- DECLARE vLanded DATETIME;
- DECLARE vDone INT DEFAULT FALSE;
- DECLARE vFreeId INT;
- DECLARE vSupplyResponseFk INT;
- DECLARE vLastInserted DATETIME;
- DECLARE vIsAuctionDay BOOLEAN;
- DECLARE vMaxNewItems INT DEFAULT 10000;
- DECLARE vStartingTime DATETIME;
- DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043';
- DECLARE vDayRange INT;
-
- DECLARE cur1 CURSOR FOR
- SELECT id
- FROM edi.item_free;
-
- DECLARE cur2 CURSOR FOR
- SELECT srId
- FROM itemToInsert;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- DECLARE EXIT HANDLER FOR SQLSTATE '45000'
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
- DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
- BEGIN
- DO RELEASE_LOCK('edi.floramondo_offerRefresh');
- SET @isTriggerDisabled = FALSE;
- RESIGNAL;
- END;
-
- IF 'test' = (SELECT environment FROM util.config) THEN
- LEAVE proc;
- END IF;
-
- IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN
- LEAVE proc;
- END IF;
-
- SELECT dayRange INTO vDayRange
- FROM offerRefreshConfig;
-
- IF vDayRange IS NULL THEN
- CALL util.throw("Variable vDayRange not declared");
- END IF;
-
- SET vStartingTime = util.VN_NOW();
-
- TRUNCATE edi.offerList;
-
- INSERT INTO edi.offerList(supplier, total)
- SELECT v.name, COUNT(DISTINCT sr.ID) total
- FROM edi.supplyResponse sr
- JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
- WHERE sr.NumberOfUnits > 0
- AND sr.EmbalageCode != 999
- GROUP BY sr.vmpID;
-
- UPDATE edi.offerList o
- JOIN (SELECT v.name, COUNT(*) total
- FROM edi.supplyOffer sr
- JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
- GROUP BY sr.vmpID) sub ON o.supplier = sub.name
- SET o.`filter` = sub.total;
-
- -- Elimina de la lista de items libres aquellos que ya existen
- DELETE itf.*
- FROM edi.item_free itf
- JOIN vn.item i ON i.id = itf.id;
-
- CREATE OR REPLACE TEMPORARY TABLE tmp
- (INDEX (`Item_ArticleCode`))
- ENGINE = MEMORY
- SELECT t.*
- FROM (
- SELECT *
- FROM edi.supplyOffer
- ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC,
- NumberOfUnits DESC LIMIT 10000000000000000000) t
- GROUP BY t.srId;
-
- CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`),
- INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`),
- INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`))
- ENGINE = MEMORY
- SELECT so.*,
- ev1.type_description s1Value,
- ev2.type_description s2Value,
- ev3.type_description s3Value,
- ev4.type_description s4Value,
- ev5.type_description s5Value,
- ev6.type_description s6Value,
- eif1.feature ef1,
- eif2.feature ef2,
- eif3.feature ef3,
- eif4.feature ef4,
- eif5.feature ef5,
- eif6.feature ef6
- FROM tmp so
- LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode
- AND eif1.presentation_order = 1
- AND eif1.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode
- AND eif2.presentation_order = 2
- AND eif2.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode
- AND eif3.presentation_order = 3
- AND eif3.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode
- AND eif4.presentation_order = 4
- AND eif4.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode
- AND eif5.presentation_order = 5
- AND eif5.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode
- AND eif6.presentation_order = 6
- AND eif6.expiry_date IS NULL
- LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature
- AND so.s1 = ev1.type_value
- LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature
- AND so.s2 = ev2.type_value
- LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature
- AND so.s3 = ev3.type_value
- LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature
- AND so.s4 = ev4.type_value
- LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature
- AND so.s5 = ev5.type_value
- LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature
- AND so.s6 = ev6.type_value
- ORDER BY Price;
-
- DROP TEMPORARY TABLE tmp;
-
- DELETE o
- FROM edi.offer o
- LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size'
- LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size'
- LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size'
- LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size'
- LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size'
- LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size'
- JOIN vn.floramondoConfig fc ON TRUE
- WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize)
- OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize)
- OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize)
- OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize)
- OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize)
- OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize);
-
- START TRANSACTION;
-
- -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos
- UPDATE IGNORE edi.offer o
- JOIN vn.item i
- ON i.name = o.product_name
- AND i.subname <=> o.company_name
- AND i.value5 <=> o.s1Value
- AND i.value6 <=> o.s2Value
- AND i.value7 <=> o.s3Value
- AND i.value8 <=> o.s4Value
- AND i.value9 <=> o.s5Value
- AND i.value10 <=> o.s6Value
- AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask
- AND i.EmbalageCode <=> o.EmbalageCode
- AND i.quality <=> o.Quality
- JOIN vn.itemType it ON it.id = i.typeFk
- LEFT JOIN vn.sale s ON s.itemFk = i.id
- LEFT JOIN vn.ticket t ON t.id = s.ticketFk
- AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK)
- LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
- LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID
- LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk
- AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK)
- SET i.supplyResponseFk = o.srID
- WHERE (sr.ID IS NULL
- OR sr.NumberOfUnits = 0
- OR di.LatestOrderDateTime < util.VN_NOW()
- OR di.ID IS NULL)
- AND it.isInventory
- AND t.id IS NULL
- AND po.id IS NULL;
-
- CREATE OR REPLACE TEMPORARY TABLE itemToInsert
- ENGINE = MEMORY
- SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk
- FROM edi.offer o
- LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId
- WHERE i.id IS NULL
- LIMIT vMaxNewItems;
-
- -- Reciclado de nº de item
- OPEN cur1;
- OPEN cur2;
-
- read_loop: LOOP
-
- FETCH cur2 INTO vSupplyResponseFk;
- FETCH cur1 INTO vFreeId;
-
- IF vDone THEN
- LEAVE read_loop;
- END IF;
-
- UPDATE itemToInsert
- SET itemFk = vFreeId
- WHERE srId = vSupplyResponseFk;
-
- END LOOP;
-
- CLOSE cur1;
- CLOSE cur2;
-
- -- Insertamos todos los items en Articles de la oferta
- INSERT INTO vn.item(id,
- `name`,
- longName,
- subName,
- expenceFk,
- typeFk,
- intrastatFk,
- originFk,
- supplyResponseFk,
- numberOfItemsPerCask,
- embalageCode,
- quality,
- isFloramondo)
- SELECT iti.itemFk,
- iti.product_name,
- iti.product_name,
- iti.company_name,
- iti.expenseFk,
- iti.itemTypeFk,
- iti.intrastatFk,
- iti.originFk,
- iti.`srId`,
- iti.NumberOfItemsPerCask,
- iti.EmbalageCode,
- iti.Quality,
- TRUE
- FROM itemToInsert iti;
-
- -- Inserta la foto de los articulos nuevos (prioridad alta)
- INSERT IGNORE INTO vn.itemImageQueue(itemFk, url)
- SELECT i.id, PictureReference
- FROM itemToInsert ii
- JOIN vn.item i ON i.supplyResponseFk = ii.srId
- WHERE PictureReference IS NOT NULL
- AND i.image IS NULL;
-
- INSERT INTO edi.`log`(tableName, fieldName,fieldValue)
- SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*)
- FROM vn.itemImageQueue
- WHERE attempts = 0;
-
- -- Inserta si se añadiesen tags nuevos
- INSERT IGNORE INTO vn.tag (name, ediTypeFk)
- SELECT description, type_id FROM edi.type;
-
- -- Desabilita el trigger para recalcular los tags al final
- SET @isTriggerDisabled = TRUE;
-
- -- Inserta los tags sólo en los articulos nuevos
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , ii.product_name, 1
- FROM itemToInsert ii
- JOIN vn.tag t ON t.`name` = 'Producto'
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT ii.product_name IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , ii.Quality, 3
- FROM itemToInsert ii
- JOIN vn.tag t ON t.`name` = 'Calidad'
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT ii.Quality IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , ii.company_name, 4
- FROM itemToInsert ii
- JOIN vn.tag t ON t.`name` = 'Productor'
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT ii.company_name IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s1Value, 5
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef1
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s1Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s2Value, 6
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef2
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s2Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s3Value, 7
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef3
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s3Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s4Value, 8
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef4
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s4Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s5Value, 9
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef5
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s5Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s6Value, 10
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef6
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s6Value IS NULL;
-
- INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11
- FROM itemToInsert ii
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- JOIN vn.tag t ON t.`name` = 'Color'
- LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode
- LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id
- AND tp.`description` = 'Hoofdkleur 1'
- LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value
- LEFT JOIN vn.itemInk ik ON ik.longName = i.longName
- WHERE ink.name IS NOT NULL
- OR ik.color IS NOT NULL;
-
- CREATE OR REPLACE TABLE tmp.item
- (PRIMARY KEY (id))
- SELECT i.id FROM vn.item i
- JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`;
-
- CALL vn.item_refreshTags();
-
- DROP TABLE tmp.item;
-
- SELECT MIN(LatestDeliveryDateTime) INTO vLanded
- FROM edi.supplyResponse sr
- JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID
- JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
- JOIN vn.floramondoConfig fc
- WHERE mp.isLatestOrderDateTimeRelevant
- AND di.LatestOrderDateTime > IF(
- fc.MaxLatestOrderHour > HOUR(util.VN_NOW()),
- util.VN_CURDATE(),
- util.VN_CURDATE() + INTERVAL 1 DAY);
-
- UPDATE vn.floramondoConfig
- SET nextLanded = vLanded
- WHERE vLanded IS NOT NULL;
-
- -- Elimina la oferta obsoleta
- UPDATE vn.buy b
- JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.travel tr ON tr.id = e.travelFk
- JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
- JOIN vn.item i ON i.id = b.itemFk
- LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID
- LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk
- SET b.quantity = 0
- WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW()
- OR i.supplyResponseFk IS NULL
- OR sr.NumberOfUnits = 0)
- AND am.name = 'LOGIFLORA'
- AND e.isRaid;
-
- -- Localiza las entradas de cada almacen
- UPDATE edi.warehouseFloramondo
- SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk);
-
- IF vLanded IS NOT NULL THEN
- -- Actualiza la oferta existente
- UPDATE vn.buy b
- JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
- JOIN vn.item i ON i.id = b.itemFk
- JOIN edi.offer o ON i.supplyResponseFk = o.`srId`
- SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask,
- b.buyingValue = o.price
- WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask
- OR b.buyingValue <> o.price);
-
- -- Inserta el resto
- SET vLastInserted := util.VN_NOW();
-
- -- Inserta la oferta
- INSERT INTO vn.buy (
- entryFk,
- itemFk,
- quantity,
- buyingValue,
- stickers,
- packing,
- `grouping`,
- groupingMode,
- packageFk,
- deliveryFk)
- SELECT wf.entryFk,
- i.id,
- o.NumberOfUnits * o.NumberOfItemsPerCask quantity,
- o.Price,
- o.NumberOfUnits etiquetas,
- o.NumberOfItemsPerCask packing,
- GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`,
- 2, -- Obliga al Packing
- o.embalageCode,
- o.diId
- FROM edi.offer o
- JOIN vn.item i ON i.supplyResponseFk = o.srId
- JOIN edi.warehouseFloramondo wf
- JOIN vn.packaging p ON p.id
- LIKE o.embalageCode
- LEFT JOIN vn.buy b ON b.itemFk = i.id
- AND b.entryFk = wf.entryFk
- WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL
-
- INSERT INTO vn.itemCost(
- itemFk,
- warehouseFk,
- cm3,
- cm3delivery)
- SELECT b.itemFk,
- wf.warehouseFk,
- @cm3 := vn.buy_getUnitVolume(b.id),
- IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3)
- FROM warehouseFloramondo wf
- JOIN vn.volumeConfig vc
- JOIN vn.buy b ON b.entryFk = wf.entryFk
- JOIN vn.item i ON i.id = b.itemFk
- LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk
- AND ic.warehouseFk = wf.warehouseFk
- WHERE (ic.cm3 IS NULL OR ic.cm3 = 0)
- ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3);
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc
- SELECT b.id
- FROM vn.buy b
- JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk
- WHERE b.created >= vLastInserted;
-
- CALL vn.buy_recalcPrices();
-
- UPDATE edi.offerList o
- JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total
- FROM vn.buy b
- JOIN vn.item i ON i.id = b.itemFk
- JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
- JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
- JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
- JOIN vn.warehouse w ON w.id = wf.warehouseFk
- WHERE w.name = 'VNH'
- AND b.quantity > 0
- GROUP BY sr.vmpID) sub ON o.supplier = sub.name
- SET o.vnh = sub.total;
-
- UPDATE edi.offerList o
- JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total
- FROM vn.buy b
- JOIN vn.item i ON i.id = b.itemFk
- JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
- JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
- JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
- JOIN vn.warehouse w ON w.id = wf.warehouseFk
- WHERE w.name = 'ALGEMESI'
- AND b.quantity > 0
- GROUP BY sr.vmpID) sub ON o.supplier = sub.name
- SET o.algemesi = sub.total;
- END IF;
-
- DROP TEMPORARY TABLE
- edi.offer,
- itemToInsert;
-
- SET @isTriggerDisabled = FALSE;
-
- COMMIT;
-
- -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias
- UPDATE vn.item i
- SET typeFk = 121
- WHERE i.longName LIKE 'Rosa Garden %'
- AND typeFk = 17;
-
- UPDATE vn.item i
- SET typeFk = 156
- WHERE i.longName LIKE 'Rosa ec %'
- AND typeFk = 17;
-
- -- Refresca las fotos de los items existentes que mostramos (prioridad baja)
- INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority)
- SELECT i.id, sr.PictureReference, 100
- FROM edi.supplyResponse sr
- JOIN vn.item i ON i.supplyResponseFk = sr.ID
- JOIN edi.supplyOffer so ON so.srId = sr.ID
- JOIN hedera.image i2 ON i2.name = i.image
- AND i2.collectionFk = 'catalog'
- WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange)
- AND sr.NumberOfUnits;
-
- INSERT INTO edi.`log`
- SET tableName = 'floramondo_offerRefresh',
- fieldName = 'Tiempo de proceso',
- fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime);
-
- DO RELEASE_LOCK('edi.floramondo_offerRefresh');
+proc: BEGIN
+ DECLARE vLanded DATETIME;
+ DECLARE vDone INT DEFAULT FALSE;
+ DECLARE vFreeId INT;
+ DECLARE vSupplyResponseFk INT;
+ DECLARE vLastInserted DATETIME;
+ DECLARE vIsAuctionDay BOOLEAN;
+ DECLARE vMaxNewItems INT DEFAULT 10000;
+ DECLARE vStartingTime DATETIME;
+ DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043';
+ DECLARE vDayRange INT;
+
+ DECLARE cur1 CURSOR FOR
+ SELECT id
+ FROM edi.item_free;
+
+ DECLARE cur2 CURSOR FOR
+ SELECT srId
+ FROM itemToInsert;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE EXIT HANDLER FOR SQLSTATE '45000'
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ DO RELEASE_LOCK('edi.floramondo_offerRefresh');
+ SET @isTriggerDisabled = FALSE;
+ RESIGNAL;
+ END;
+
+ IF 'test' = (SELECT environment FROM util.config) THEN
+ LEAVE proc;
+ END IF;
+
+ IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN
+ LEAVE proc;
+ END IF;
+
+ SELECT dayRange INTO vDayRange
+ FROM offerRefreshConfig;
+
+ IF vDayRange IS NULL THEN
+ CALL util.throw("Variable vDayRange not declared");
+ END IF;
+
+ SET vStartingTime = util.VN_NOW();
+
+ TRUNCATE edi.offerList;
+
+ INSERT INTO edi.offerList(supplier, total)
+ SELECT v.name, COUNT(DISTINCT sr.ID) total
+ FROM edi.supplyResponse sr
+ JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
+ WHERE sr.NumberOfUnits > 0
+ AND sr.EmbalageCode != 999
+ GROUP BY sr.vmpID;
+
+ UPDATE edi.offerList o
+ JOIN (SELECT v.name, COUNT(*) total
+ FROM edi.supplyOffer sr
+ JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
+ GROUP BY sr.vmpID) sub ON o.supplier = sub.name
+ SET o.`filter` = sub.total;
+
+ -- Elimina de la lista de items libres aquellos que ya existen
+ DELETE itf.*
+ FROM edi.item_free itf
+ JOIN vn.item i ON i.id = itf.id;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp
+ (INDEX (`Item_ArticleCode`))
+ ENGINE = MEMORY
+ SELECT t.*
+ FROM (
+ SELECT *
+ FROM edi.supplyOffer
+ ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC,
+ NumberOfUnits DESC LIMIT 10000000000000000000) t
+ GROUP BY t.srId;
+
+ CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`),
+ INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`),
+ INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`))
+ ENGINE = MEMORY
+ SELECT so.*,
+ ev1.type_description s1Value,
+ ev2.type_description s2Value,
+ ev3.type_description s3Value,
+ ev4.type_description s4Value,
+ ev5.type_description s5Value,
+ ev6.type_description s6Value,
+ eif1.feature ef1,
+ eif2.feature ef2,
+ eif3.feature ef3,
+ eif4.feature ef4,
+ eif5.feature ef5,
+ eif6.feature ef6
+ FROM tmp so
+ LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode
+ AND eif1.presentation_order = 1
+ AND eif1.expiry_date IS NULL
+ LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode
+ AND eif2.presentation_order = 2
+ AND eif2.expiry_date IS NULL
+ LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode
+ AND eif3.presentation_order = 3
+ AND eif3.expiry_date IS NULL
+ LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode
+ AND eif4.presentation_order = 4
+ AND eif4.expiry_date IS NULL
+ LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode
+ AND eif5.presentation_order = 5
+ AND eif5.expiry_date IS NULL
+ LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode
+ AND eif6.presentation_order = 6
+ AND eif6.expiry_date IS NULL
+ LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature
+ AND so.s1 = ev1.type_value
+ LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature
+ AND so.s2 = ev2.type_value
+ LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature
+ AND so.s3 = ev3.type_value
+ LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature
+ AND so.s4 = ev4.type_value
+ LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature
+ AND so.s5 = ev5.type_value
+ LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature
+ AND so.s6 = ev6.type_value
+ ORDER BY Price;
+
+ DROP TEMPORARY TABLE tmp;
+
+ DELETE o
+ FROM edi.offer o
+ LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size'
+ LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size'
+ LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size'
+ LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size'
+ LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size'
+ LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size'
+ JOIN vn.floramondoConfig fc ON TRUE
+ WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize)
+ OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize)
+ OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize)
+ OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize)
+ OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize)
+ OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize);
+
+ START TRANSACTION;
+
+ -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos
+ UPDATE IGNORE edi.offer o
+ JOIN vn.item i
+ ON i.name = o.product_name
+ AND i.subname <=> o.company_name
+ AND i.value5 <=> o.s1Value
+ AND i.value6 <=> o.s2Value
+ AND i.value7 <=> o.s3Value
+ AND i.value8 <=> o.s4Value
+ AND i.value9 <=> o.s5Value
+ AND i.value10 <=> o.s6Value
+ AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask
+ AND i.EmbalageCode <=> o.EmbalageCode
+ AND i.quality <=> o.Quality
+ JOIN vn.itemType it ON it.id = i.typeFk
+ LEFT JOIN vn.sale s ON s.itemFk = i.id
+ LEFT JOIN vn.ticket t ON t.id = s.ticketFk
+ AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK)
+ LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
+ LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID
+ LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk
+ AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK)
+ SET i.supplyResponseFk = o.srID
+ WHERE (sr.ID IS NULL
+ OR sr.NumberOfUnits = 0
+ OR di.LatestOrderDateTime < util.VN_NOW()
+ OR di.ID IS NULL)
+ AND it.isInventory
+ AND t.id IS NULL
+ AND po.id IS NULL;
+
+ CREATE OR REPLACE TEMPORARY TABLE itemToInsert
+ ENGINE = MEMORY
+ SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk
+ FROM edi.offer o
+ LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId
+ WHERE i.id IS NULL
+ LIMIT vMaxNewItems;
+
+ -- Reciclado de nº de item
+ OPEN cur1;
+ OPEN cur2;
+
+ read_loop: LOOP
+
+ FETCH cur2 INTO vSupplyResponseFk;
+ FETCH cur1 INTO vFreeId;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ UPDATE itemToInsert
+ SET itemFk = vFreeId
+ WHERE srId = vSupplyResponseFk;
+
+ END LOOP;
+
+ CLOSE cur1;
+ CLOSE cur2;
+
+ -- Insertamos todos los items en Articles de la oferta
+ INSERT INTO vn.item(id,
+ `name`,
+ longName,
+ subName,
+ expenseFk,
+ typeFk,
+ intrastatFk,
+ originFk,
+ supplyResponseFk,
+ numberOfItemsPerCask,
+ embalageCode,
+ quality,
+ isFloramondo)
+ SELECT iti.itemFk,
+ iti.product_name,
+ iti.product_name,
+ iti.company_name,
+ iti.expenseFk,
+ iti.itemTypeFk,
+ iti.intrastatFk,
+ iti.originFk,
+ iti.`srId`,
+ iti.NumberOfItemsPerCask,
+ iti.EmbalageCode,
+ iti.Quality,
+ TRUE
+ FROM itemToInsert iti;
+
+ -- Inserta la foto de los articulos nuevos (prioridad alta)
+ INSERT IGNORE INTO vn.itemImageQueue(itemFk, url)
+ SELECT i.id, PictureReference
+ FROM itemToInsert ii
+ JOIN vn.item i ON i.supplyResponseFk = ii.srId
+ WHERE PictureReference IS NOT NULL
+ AND i.image IS NULL;
+
+ INSERT INTO edi.`log`(tableName, fieldName,fieldValue)
+ SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*)
+ FROM vn.itemImageQueue
+ WHERE attempts = 0;
+
+ -- Inserta si se añadiesen tags nuevos
+ INSERT IGNORE INTO vn.tag (name, ediTypeFk)
+ SELECT description, type_id FROM edi.type;
+
+ -- Desabilita el trigger para recalcular los tags al final
+ SET @isTriggerDisabled = TRUE;
+
+ -- Inserta los tags sólo en los articulos nuevos
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id , ii.product_name, 1
+ FROM itemToInsert ii
+ JOIN vn.tag t ON t.`name` = 'Producto'
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ WHERE NOT ii.product_name IS NULL;
+
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id , ii.Quality, 3
+ FROM itemToInsert ii
+ JOIN vn.tag t ON t.`name` = 'Calidad'
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ WHERE NOT ii.Quality IS NULL;
+
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id , ii.company_name, 4
+ FROM itemToInsert ii
+ JOIN vn.tag t ON t.`name` = 'Productor'
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ WHERE NOT ii.company_name IS NULL;
+
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id , s1Value, 5
+ FROM itemToInsert ii
+ JOIN vn.tag t ON t.ediTypeFk = ii.ef1
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ WHERE NOT s1Value IS NULL;
+
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id , s2Value, 6
+ FROM itemToInsert ii
+ JOIN vn.tag t ON t.ediTypeFk = ii.ef2
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ WHERE NOT s2Value IS NULL;
+
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id , s3Value, 7
+ FROM itemToInsert ii
+ JOIN vn.tag t ON t.ediTypeFk = ii.ef3
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ WHERE NOT s3Value IS NULL;
+
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id , s4Value, 8
+ FROM itemToInsert ii
+ JOIN vn.tag t ON t.ediTypeFk = ii.ef4
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ WHERE NOT s4Value IS NULL;
+
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id , s5Value, 9
+ FROM itemToInsert ii
+ JOIN vn.tag t ON t.ediTypeFk = ii.ef5
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ WHERE NOT s5Value IS NULL;
+
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id , s6Value, 10
+ FROM itemToInsert ii
+ JOIN vn.tag t ON t.ediTypeFk = ii.ef6
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ WHERE NOT s6Value IS NULL;
+
+ INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11
+ FROM itemToInsert ii
+ JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
+ JOIN vn.tag t ON t.`name` = 'Color'
+ LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode
+ LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id
+ AND tp.`description` = 'Hoofdkleur 1'
+ LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value
+ LEFT JOIN vn.itemInk ik ON ik.longName = i.longName
+ WHERE ink.name IS NOT NULL
+ OR ik.color IS NOT NULL;
+
+ CREATE OR REPLACE TABLE tmp.item
+ (PRIMARY KEY (id))
+ SELECT i.id FROM vn.item i
+ JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`;
+
+ CALL vn.item_refreshTags();
+
+ DROP TABLE tmp.item;
+
+ SELECT MIN(LatestDeliveryDateTime) INTO vLanded
+ FROM edi.supplyResponse sr
+ JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID
+ JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
+ JOIN vn.floramondoConfig fc
+ WHERE mp.isLatestOrderDateTimeRelevant
+ AND di.LatestOrderDateTime > IF(
+ fc.MaxLatestOrderHour > HOUR(util.VN_NOW()),
+ util.VN_CURDATE(),
+ util.VN_CURDATE() + INTERVAL 1 DAY);
+
+ UPDATE vn.floramondoConfig
+ SET nextLanded = vLanded
+ WHERE vLanded IS NOT NULL;
+
+ -- Elimina la oferta obsoleta
+ UPDATE vn.buy b
+ JOIN vn.entry e ON e.id = b.entryFk
+ JOIN vn.travel tr ON tr.id = e.travelFk
+ JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
+ JOIN vn.item i ON i.id = b.itemFk
+ LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID
+ LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk
+ SET b.quantity = 0
+ WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW()
+ OR i.supplyResponseFk IS NULL
+ OR sr.NumberOfUnits = 0)
+ AND am.name = 'LOGIFLORA'
+ AND e.isRaid;
+
+ -- Localiza las entradas de cada almacen
+ UPDATE edi.warehouseFloramondo
+ SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk);
+
+ IF vLanded IS NOT NULL THEN
+ -- Actualiza la oferta existente
+ UPDATE vn.buy b
+ JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
+ JOIN vn.item i ON i.id = b.itemFk
+ JOIN edi.offer o ON i.supplyResponseFk = o.`srId`
+ SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask,
+ b.buyingValue = o.price
+ WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask
+ OR b.buyingValue <> o.price);
+
+ -- Inserta el resto
+ SET vLastInserted := util.VN_NOW();
+
+ -- Inserta la oferta
+ INSERT INTO vn.buy (
+ entryFk,
+ itemFk,
+ quantity,
+ buyingValue,
+ stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ packagingFk,
+ deliveryFk)
+ SELECT wf.entryFk,
+ i.id,
+ o.NumberOfUnits * o.NumberOfItemsPerCask quantity,
+ o.Price,
+ o.NumberOfUnits etiquetas,
+ o.NumberOfItemsPerCask packing,
+ GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`,
+ 2, -- Obliga al Packing
+ o.embalageCode,
+ o.diId
+ FROM edi.offer o
+ JOIN vn.item i ON i.supplyResponseFk = o.srId
+ JOIN edi.warehouseFloramondo wf
+ JOIN vn.packaging p ON p.id
+ LIKE o.embalageCode
+ LEFT JOIN vn.buy b ON b.itemFk = i.id
+ AND b.entryFk = wf.entryFk
+ WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL
+
+ INSERT INTO vn.itemCost(
+ itemFk,
+ warehouseFk,
+ cm3,
+ cm3delivery)
+ SELECT b.itemFk,
+ wf.warehouseFk,
+ @cm3 := vn.buy_getUnitVolume(b.id),
+ IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3)
+ FROM warehouseFloramondo wf
+ JOIN vn.volumeConfig vc
+ JOIN vn.buy b ON b.entryFk = wf.entryFk
+ JOIN vn.item i ON i.id = b.itemFk
+ LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk
+ AND ic.warehouseFk = wf.warehouseFk
+ WHERE (ic.cm3 IS NULL OR ic.cm3 = 0)
+ ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc
+ SELECT b.id
+ FROM vn.buy b
+ JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk
+ WHERE b.created >= vLastInserted;
+
+ CALL vn.buy_recalcPrices();
+
+ UPDATE edi.offerList o
+ JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total
+ FROM vn.buy b
+ JOIN vn.item i ON i.id = b.itemFk
+ JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
+ JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
+ JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
+ JOIN vn.warehouse w ON w.id = wf.warehouseFk
+ WHERE w.name = 'VNH'
+ AND b.quantity > 0
+ GROUP BY sr.vmpID) sub ON o.supplier = sub.name
+ SET o.vnh = sub.total;
+
+ UPDATE edi.offerList o
+ JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total
+ FROM vn.buy b
+ JOIN vn.item i ON i.id = b.itemFk
+ JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
+ JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
+ JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
+ JOIN vn.warehouse w ON w.id = wf.warehouseFk
+ WHERE w.name = 'ALGEMESI'
+ AND b.quantity > 0
+ GROUP BY sr.vmpID) sub ON o.supplier = sub.name
+ SET o.algemesi = sub.total;
+ END IF;
+
+ DROP TEMPORARY TABLE
+ edi.offer,
+ itemToInsert;
+
+ SET @isTriggerDisabled = FALSE;
+
+ COMMIT;
+
+ -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias
+ UPDATE vn.item i
+ SET typeFk = 121
+ WHERE i.longName LIKE 'Rosa Garden %'
+ AND typeFk = 17;
+
+ UPDATE vn.item i
+ SET typeFk = 156
+ WHERE i.longName LIKE 'Rosa ec %'
+ AND typeFk = 17;
+
+ -- Refresca las fotos de los items existentes que mostramos (prioridad baja)
+ INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority)
+ SELECT i.id, sr.PictureReference, 100
+ FROM edi.supplyResponse sr
+ JOIN vn.item i ON i.supplyResponseFk = sr.ID
+ JOIN edi.supplyOffer so ON so.srId = sr.ID
+ JOIN hedera.image i2 ON i2.name = i.image
+ AND i2.collectionFk = 'catalog'
+ WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange)
+ AND sr.NumberOfUnits;
+
+ INSERT INTO edi.`log`
+ SET tableName = 'floramondo_offerRefresh',
+ fieldName = 'Tiempo de proceso',
+ fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime);
+
+ DO RELEASE_LOCK('edi.floramondo_offerRefresh');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -9793,7 +11491,7 @@ BEGIN
/**
* Devuelve un número nuevo de item a partir de un registro de la tabla edi.ekt
- *
+ *
* @param vEktFk Identificador de la tabla edi.ekt
*/
@@ -9802,22 +11500,22 @@ BEGIN
SELECT MIN(id) id INTO vItemFk
FROM edi.item_free;
- DELETE FROM edi.item_free
+ DELETE FROM edi.item_free
WHERE id = vItemFk;
-
+
COMMIT;
-
+
IF ISNULL(vItemFk) THEN
SELECT MAX(i.id) + 1
INTO vItemFk
FROM vn.item i;
END IF;
-
+
INSERT INTO vn.item(id,
`name`,
longName,
subName,
- expenceFk,
+ expenseFk,
typeFk,
intrastatFk,
originFk,
@@ -9838,118 +11536,118 @@ BEGIN
least(IF((e.package = 800),((e.package * 10) + e.pac), e.package), IFNULL(idt.bucket_id, '999')) packageFk,
e.cat,
TRUE
- FROM edi.ekt e
- JOIN edi.item i ON i.id = e.`ref`
- JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id
- LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref`
+ FROM edi.ekt e
+ JOIN edi.item i ON i.id = e.`ref`
+ JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id
+ LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref`
WHERE e.id = vEktFk;
SET @isTriggerDisabled = TRUE;
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.item , 1
- FROM edi.ekt e
+ SELECT vItemFk, t.id , e.item , 1
+ FROM edi.ekt e
JOIN vn.tag t ON t.`name` = 'Producto'
WHERE e.id = vEktFk
AND NOT ISNULL(e.item);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.cat , 3
- FROM edi.ekt e
+ SELECT vItemFk, t.id , e.cat , 3
+ FROM edi.ekt e
JOIN vn.tag t ON t.`name` = 'Calidad'
WHERE e.id = vEktFk
AND NOT ISNULL(e.cat);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , s.company_name , 4
- FROM edi.ekt e
+ SELECT vItemFk, t.id , s.company_name , 4
+ FROM edi.ekt e
JOIN edi.supplier s ON s.supplier_id = e.pro
JOIN vn.tag t ON t.`name` = 'Productor'
WHERE e.id = vEktFk
AND NOT ISNULL(s.company_name);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s1, 5
+ SELECT vItemFk, t.id , e.s1, 5
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
- AND eif.presentation_order = 1
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ AND eif.presentation_order = 1
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s1 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s1);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s2, 6
+ SELECT vItemFk, t.id , e.s2, 6
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
- AND eif.presentation_order = 2
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ AND eif.presentation_order = 2
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s2 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s2);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s3, 7
+ SELECT vItemFk, t.id , e.s3, 7
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
- AND eif.presentation_order = 3
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ AND eif.presentation_order = 3
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s3 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s3);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s4, 8
+ SELECT vItemFk, t.id , e.s4, 8
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 4
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s4 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s4);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s5, 9
+ SELECT vItemFk, t.id , e.s5, 9
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 5
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s5 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s5);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s6, 10
+ SELECT vItemFk, t.id , e.s6, 10
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 6
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s6 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s6);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11
- FROM edi.ekt e
+ SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11
+ FROM edi.ekt e
JOIN vn.tag t ON t.`name` = 'Color'
- LEFT JOIN edi.feature f ON f.item_id = e.`ref`
+ LEFT JOIN edi.feature f ON f.item_id = e.`ref`
LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id AND tp.`description` = 'Hoofdkleur 1'
LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value
LEFT JOIN vn.itemInk ik ON ik.longName = e.item
WHERE e.id = vEktFk
- AND ( ink.name IS NOT NULL
+ AND ( ink.name IS NOT NULL
OR ik.color IS NOT NULL)
LIMIT 1;
@@ -10016,7 +11714,7 @@ BEGIN
sender = vSender,
senderFk = vSenderId,
messageId = vMessageId;
-
+
IF vIsDuplicated THEN
SELECT id INTO vSelf
FROM mail
@@ -10091,7 +11789,7 @@ CREATE TABLE `config` (
`dmsDir` varchar(255) DEFAULT NULL COMMENT 'Directory where documents are allocated',
PRIMARY KEY (`id`),
KEY `jwtkey_IX` (`jwtKey`) COMMENT 'Prueba de Ernesto 3.8.2020. MySQL se queja de no tener indices. Si, se que solo tiene un registro pero molesta para depurar otros.'
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10105,7 +11803,7 @@ CREATE TABLE `contact` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`recipient` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10124,7 +11822,7 @@ CREATE TABLE `image` (
PRIMARY KEY (`id`),
UNIQUE KEY `collection` (`collectionFk`,`name`),
CONSTRAINT `image_ibfk_1` FOREIGN KEY (`collectionFk`) REFERENCES `imageCollection` (`name`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10153,7 +11851,7 @@ CREATE TABLE `imageCollection` (
KEY `role_id_readRoleFk` (`readRoleFk`),
CONSTRAINT `role_id_readRoleFk` FOREIGN KEY (`readRoleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE,
CONSTRAINT `role_id_writeRoleFk` FOREIGN KEY (`writeRoleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10172,7 +11870,7 @@ CREATE TABLE `imageCollectionSize` (
PRIMARY KEY (`id`),
KEY `image_schema_id` (`collectionFk`),
CONSTRAINT `imageCollectionSize_ibfk_1` FOREIGN KEY (`collectionFk`) REFERENCES `imageCollection` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10188,7 +11886,7 @@ CREATE TABLE `imageConfig` (
`useXsendfile` tinyint(4) NOT NULL COMMENT 'Whether to use the apache module XSendfile',
`url` varchar(255) NOT NULL COMMENT 'Public URL where image are hosted',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Global image parameters';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Global image parameters';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10221,71 +11919,8 @@ CREATE TABLE `link` (
`link` varchar(255) NOT NULL,
`image` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`link_afterInsert`
- AFTER INSERT ON `link`
- FOR EACH ROW
-BEGIN
- CALL image_ref('link', NEW.image);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`link_afterUpdate`
- AFTER UPDATE ON `link`
- FOR EACH ROW
-BEGIN
- IF !(NEW.image <=> OLD.image) THEN
- CALL image_unref('link', OLD.image);
- CALL image_ref('link', NEW.image);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`link_afterDelete`
- AFTER DELETE ON `link`
- FOR EACH ROW
-BEGIN
- CALL image_unref('link', OLD.image);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `location`
@@ -10306,7 +11941,7 @@ CREATE TABLE `location` (
`phone` varchar(20) DEFAULT NULL,
`language` char(2) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10326,7 +11961,7 @@ CREATE TABLE `mailConfig` (
`user` varchar(50) DEFAULT NULL COMMENT 'SMTP user',
`password` varchar(100) DEFAULT NULL COMMENT 'SMTP password, base64 encoded',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10373,7 +12008,7 @@ CREATE TABLE `menu` (
KEY `group_id` (`roleFk`),
KEY `parent` (`parentFk`),
CONSTRAINT `menu_ibfk_1` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10389,7 +12024,7 @@ CREATE TABLE `message` (
`description` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10706,71 +12341,8 @@ CREATE TABLE `news` (
KEY `tag` (`tag`),
CONSTRAINT `news_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`account` (`id`) ON UPDATE CASCADE,
CONSTRAINT `news_ibfk_2` FOREIGN KEY (`tag`) REFERENCES `newsTag` (`name`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`news_afterInsert`
- AFTER INSERT ON `news`
- FOR EACH ROW
-BEGIN
- CALL image_ref('news', NEW.image);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`news_afterUpdate`
- AFTER UPDATE ON `news`
- FOR EACH ROW
-BEGIN
- IF !(NEW.image <=> OLD.image) THEN
- CALL image_unref('news', OLD.image);
- CALL image_ref('news', NEW.image);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`news_afterDelete`
- AFTER DELETE ON `news`
- FOR EACH ROW
-BEGIN
- CALL image_unref('news', OLD.image);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `newsTag`
@@ -10824,93 +12396,8 @@ CREATE TABLE `order` (
CONSTRAINT `order_ibfk_5` FOREIGN KEY (`address_id`) REFERENCES `vn`.`address` (`id`) ON UPDATE CASCADE,
CONSTRAINT `order_ibfk_8` FOREIGN KEY (`delivery_method_id`) REFERENCES `vn`.`deliveryMethod` (`id`) ON UPDATE CASCADE,
CONSTRAINT `order_ibfk_9` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agencyMode` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterInsert`
- AFTER INSERT ON `order`
- FOR EACH ROW
-BEGIN
- IF NEW.address_id = 2850 THEN
- -- Fallo que se insertan no se sabe como tickets en este cliente
- CALL vn.mail_insert(
- 'jgallego@verdnatura.es',
- 'noreply@verdnatura.es',
- 'Creada order al address 2850',
- CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id)
- );
-
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate`
- AFTER UPDATE ON `order`
- FOR EACH ROW
-BEGIN
- CALL stock.log_add('order', NEW.id, OLD.id);
-
- IF !(OLD.address_id <=> NEW.address_id)
- OR !(OLD.company_id <=> NEW.company_id)
- OR !(OLD.customer_id <=> NEW.customer_id) THEN
- CALL order_requestRecalc(NEW.id);
- END IF;
-
- IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN
- -- Fallo que se actualiza no se sabe como tickets en este cliente
- CALL vn.mail_insert(
- 'jgallego@verdnatura.es',
- 'noreply@verdnatura.es',
- 'Actualizada order al address 2850',
- CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id)
- );
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_beforeDelete`
- BEFORE DELETE ON `order`
- FOR EACH ROW
-BEGIN
- DELETE FROM orderRow WHERE orderFk = OLD.id;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `orderConfig`
@@ -10937,7 +12424,7 @@ CREATE TABLE `orderConfig` (
CONSTRAINT `orderConfig_ibfk_1` FOREIGN KEY (`employeeFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `orderConfig_ibfk_3` FOREIGN KEY (`guestAgencyFk`) REFERENCES `vn`.`agencyMode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `orderConfig_ibfk_4` FOREIGN KEY (`defaultAgencyFk`) REFERENCES `vn`.`agencyMode` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10952,7 +12439,7 @@ CREATE TABLE `orderRecalc` (
`orderFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `orderRecalc_ibfk_1` (`orderFk`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed orders to recalc it''s total';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed orders to recalc it''s total';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -10982,101 +12469,8 @@ CREATE TABLE `orderRow` (
CONSTRAINT `orderRow_ibfk_2` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE,
CONSTRAINT `orderRow_ibfk_3` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `orderRow_ibfk_4` FOREIGN KEY (`saleFk`) REFERENCES `vn`.`sale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`orderRow_beforeInsert`
- BEFORE INSERT ON `orderRow`
- FOR EACH ROW
-BEGIN
- DECLARE vIsFirst BOOL;
-
- SELECT (first_row_stamp IS NULL) INTO vIsFirst
- FROM `order`
- WHERE id = NEW.orderFk;
-
- IF vIsFirst THEN
- UPDATE `order` SET first_row_stamp = util.VN_NOW()
- WHERE id = NEW.orderFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterInsert`
- AFTER INSERT ON `orderRow`
- FOR EACH ROW
-BEGIN
- CALL stock.log_add('orderRow', NEW.id, NULL);
- CALL order_requestRecalc(NEW.orderFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterUpdate`
- AFTER UPDATE ON `orderRow`
- FOR EACH ROW
-BEGIN
- CALL stock.log_add('orderRow', NEW.id, OLD.id);
- CALL order_requestRecalc(OLD.orderFk);
- CALL order_requestRecalc(NEW.orderFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterDelete`
- AFTER DELETE ON `orderRow`
- FOR EACH ROW
-BEGIN
- CALL stock.log_add('orderRow', NULL, OLD.id);
- CALL order_requestRecalc(OLD.orderFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `orderRowComponent`
@@ -11157,7 +12551,7 @@ CREATE TABLE `restPriv` (
PRIMARY KEY (`id`),
KEY `role` (`role`),
CONSTRAINT `restPriv_ibfk_1` FOREIGN KEY (`role`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11203,7 +12597,7 @@ CREATE TABLE `shelfConfig` (
CONSTRAINT `shelfConfig_ibfk_1` FOREIGN KEY (`family`) REFERENCES `vn`.`itemType` (`id`),
CONSTRAINT `shelfConfig_ibfk_2` FOREIGN KEY (`shelf`) REFERENCES `shelf` (`id`) ON UPDATE CASCADE,
CONSTRAINT `shelfConfig_ibfk_3` FOREIGN KEY (`warehouse`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11221,7 +12615,7 @@ CREATE TABLE `social` (
`priority` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `priority` (`priority`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11235,7 +12629,7 @@ CREATE TABLE `survey` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`question` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11294,7 +12688,7 @@ CREATE TABLE `tpvConfig` (
PRIMARY KEY (`id`),
KEY `employee_id` (`employeeFk`),
CONSTRAINT `employee_id` FOREIGN KEY (`employeeFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Virtual TPV parameters';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Virtual TPV parameters';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11327,7 +12721,7 @@ CREATE TABLE `tpvImapConfig` (
`successFolder` varchar(150) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`errorFolder` varchar(150) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='IMAP configuration parameters for virtual TPV';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='IMAP configuration parameters for virtual TPV';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11407,10 +12801,11 @@ CREATE TABLE `tpvTransaction` (
KEY `user_id` (`clientFk`),
KEY `response` (`response`),
KEY `error_code` (`errorCode`),
+ KEY `tpvTransaction_status_IDX` (`status`,`receiptFk`) USING BTREE,
CONSTRAINT `receipt_id` FOREIGN KEY (`receiptFk`) REFERENCES `vn`.`receipt` (`Id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `tpvTransaction_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `tpvTransaction_ibfk_2` FOREIGN KEY (`merchantFk`) REFERENCES `tpvMerchant` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Transactions realized through the virtual TPV';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Transactions realized through the virtual TPV';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11445,7 +12840,7 @@ CREATE TABLE `visit` (
PRIMARY KEY (`id`),
KEY `firstAgent` (`firstAgentFk`),
CONSTRAINT `visit_ibfk_1` FOREIGN KEY (`firstAgentFk`) REFERENCES `visitAgent` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11465,7 +12860,7 @@ CREATE TABLE `visitAccess` (
KEY `visit_access_idx_agent` (`agentFk`),
KEY `stamp` (`stamp`),
CONSTRAINT `visitAccess_ibfk_1` FOREIGN KEY (`agentFk`) REFERENCES `visitAgent` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11490,7 +12885,7 @@ CREATE TABLE `visitAgent` (
KEY `firstAccess` (`firstAccessFk`),
CONSTRAINT `visitAgent_ibfk_1` FOREIGN KEY (`visitFk`) REFERENCES `visit` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `visitAgent_ibfk_2` FOREIGN KEY (`firstAccessFk`) REFERENCES `visitAccess` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11510,7 +12905,7 @@ CREATE TABLE `visitUser` (
KEY `date_time` (`stamp`),
KEY `user_id` (`userFk`),
CONSTRAINT `visitUser_ibfk_1` FOREIGN KEY (`accessFk`) REFERENCES `visitAccess` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11529,7 +12924,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `order_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2019-08-29 14:18:04' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL order_doRecalc */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `order_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2019-08-29 14:18:04' ON COMPLETION PRESERVE ENABLE DO CALL order_doRecalc */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -11593,7 +12988,7 @@ BEGIN
IF vCount = 0 THEN
RETURN FALSE;
- END IF;
+ END IF;
SELECT COUNT(*) > 0
INTO vHasRole
@@ -11674,14 +13069,14 @@ BEGIN
* @return tmp.ticketComponent
* @return tmp.ticketLot
* @return tmp.zoneGetShipped
- */
+ */
DECLARE vAgencyMode INT;
-
+
SELECT a.agencyModeFk
INTO vAgencyMode
FROM myClient c
JOIN vn.address a ON a.clientFk = c.id
- WHERE a.id = vAddress;
+ WHERE a.id = vAddress;
CALL vn.available_calc(vDelivery, vAddress, vAgencyMode);
@@ -11694,7 +13089,7 @@ BEGIN
JOIN tmp.availableCalc a ON a.calcFk = c.calc_id
WHERE c.available > 0
GROUP BY c.item_id;
-
+
CALL vn.catalog_calculate(vDelivery, vAddress, vAgencyMode);
DROP TEMPORARY TABLE tmp.item;
@@ -11796,7 +13191,7 @@ BEGIN
*/
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
- ENGINE = MEMORY
+ ENGINE = MEMORY
SELECT vSelf itemFk;
CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);
@@ -11836,7 +13231,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`(
vType INT,
vPrefix VARCHAR(255))
BEGIN
-
+
/**
* Gets visible items of the specified type at specified date.
*
@@ -11845,22 +13240,22 @@ BEGIN
* @param vType The type id
* @param vPrefix The article prefix to filter or %NULL for all
* @return tmp.itemVisible Visible items
- */
+ */
DECLARE vPrefixLen SMALLINT;
DECLARE vFilter VARCHAR(255) DEFAULT NULL;
- DECLARE vDateInv DATE DEFAULT vn2008.date_inv();
+ DECLARE vDateInv DATE DEFAULT vn.getInventoryDate();
DECLARE EXIT HANDLER FOR 1114
BEGIN
GET DIAGNOSTICS CONDITION 1
@message = MESSAGE_TEXT;
CALL vn.mail_insert(
- 'cau@verdnatura.es',
- NULL,
+ 'cau@verdnatura.es',
+ NULL,
CONCAT('hedera.item_getVisible error: ', @message),
CONCAT(
- 'warehouse: ', IFNULL(vWarehouse, ''),
- ', Fecha:', IFNULL(vDate, ''),
- ', tipo: ', IFNULL(vType,''),
+ 'warehouse: ', IFNULL(vWarehouse, ''),
+ ', Fecha:', IFNULL(vDate, ''),
+ ', tipo: ', IFNULL(vType,''),
', prefijo: ', IFNULL(vPrefix,'')));
RESIGNAL;
END;
@@ -11904,7 +13299,7 @@ BEGIN
SELECT m.itemFk, -m.quantity
FROM vn.sale m
JOIN vn.ticket t ON t.id = m.ticketFk
- JOIN vn.ticketState s ON s.ticket = t.id
+ JOIN vn.ticketState s ON s.ticketFk = t.id
WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE()
AND t.warehouseFk = vWarehouse
AND s.alertLevel = 3
@@ -11918,14 +13313,14 @@ BEGIN
ENGINE = MEMORY
SELECT *
FROM (
- SELECT b.itemFk, b.packageFk, b.packing
+ SELECT b.itemFk, b.packagingFk, b.packing
FROM vn.buy b
JOIN vn.entry e ON e.id = b.entryFk
JOIN vn.travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vDateInv AND vDate
AND NOT b.isIgnored
AND b.price2 >= 0
- AND b.packageFk IS NOT NULL
+ AND b.packagingFk IS NOT NULL
ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC
LIMIT 10000000000000000000
) t GROUP BY itemFk;
@@ -11939,13 +13334,13 @@ BEGIN
IF(p.depth > 0, p.depth, 0) depth, p.width, p.height,
CEIL(s.quantity / t.packing) etiquetas
FROM vn.item i
- JOIN `filter` f ON f.itemFk = i.id
+ JOIN `filter` f ON f.itemFk = i.id
JOIN currentStock s ON s.itemFk = i.id
LEFT JOIN tmp t ON t.itemFk = i.id
- LEFT JOIN vn.packaging p ON p.id = t.packageFk
+ LEFT JOIN vn.packaging p ON p.id = t.packagingFk
WHERE CEIL(s.quantity / t.packing) > 0
-- FIXME: Column Cubos.box not included in view vn.packaging
- /* AND p.box */;
+ /* AND p.box */ ;
DROP TEMPORARY TABLE
`filter`,
@@ -12416,15 +13811,15 @@ BEGIN
START TRANSACTION;
- SELECT a.agencyModeFk, a.id
+ SELECT a.agencyModeFk, a.id
INTO vAgencyMode, vAddressFk
- FROM vn.address a
+ FROM vn.address a
WHERE a.id = vAddressFk;
-
+
SELECT deliveryMethodFk INTO vDeliveryMethodId
FROM vn.agencyMode am
WHERE am.id = vAgencyMode;
-
+
IF vCompany IS NULL
THEN
SELECT defaultCompanyFk INTO vCompany
@@ -12442,7 +13837,7 @@ BEGIN
company_id = vCompany;
SET vSelf = LAST_INSERT_ID();
-
+
CALL order_checkConfig(vSelf);
COMMIT;
@@ -12488,15 +13883,15 @@ BEGIN
START TRANSACTION;
- SELECT a.agencyModeFk, a.id
+ SELECT a.agencyModeFk, a.id
INTO vAgencyMode, vAddress
FROM myClient c
JOIN vn.address a ON a.id = c.defaultAddressFk;
-
+
SELECT deliveryMethodFk INTO vDeliveryMethodId
FROM vn.agencyMode am
WHERE am.id = vAgencyMode;
-
+
IF vCompany IS NULL
THEN
SELECT defaultCompanyFk INTO vCompany
@@ -12514,7 +13909,7 @@ BEGIN
company_id = vCompany;
SET vSelf = LAST_INSERT_ID();
-
+
CALL order_checkConfig(vSelf);
COMMIT;
@@ -12697,7 +14092,7 @@ BEGIN
SELECT t.id ticketFk
FROM myTicket t
WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59');
-
+
CALL vn.ticketGetTotal(NULL);
SELECT v.id, IFNULL(v.landed, v.shipped) landed,
@@ -12837,6 +14232,7 @@ BEGIN
DECLARE vRow INT;
DECLARE vAdd INT;
DECLARE vAvailable INT;
+ DECLARE vMinQuantity INT;
DECLARE vDone BOOL;
DECLARE vGrouping INT;
DECLARE vRate INT;
@@ -12857,7 +14253,7 @@ BEGIN
ROLLBACK;
RESIGNAL;
END;
-
+
CALL order_calcCatalogFromItem(vSelf, vItem);
START TRANSACTION;
@@ -12867,15 +14263,23 @@ BEGIN
FROM tmp.zoneGetShipped
WHERE warehouseFk = vWarehouse;
- SELECT available INTO vAvailable
+ SELECT IFNULL(available, 0) INTO vAvailable
FROM tmp.ticketLot
WHERE warehouseFk = vWarehouse
AND itemFk = vItem;
- IF vAmount > IFNULL(vAvailable, 0) THEN
+ IF vAmount > vAvailable THEN
CALL util.throw ('ORDER_ROW_UNAVAILABLE');
END IF;
+ SELECT IFNULL(minQuantity, 0) INTO vMinQuantity
+ FROM vn.item
+ WHERE id = vItem;
+
+ IF vAmount < LEAST(vMinQuantity, vAvailable) THEN
+ CALL util.throw ('quantityLessThanMin');
+ END IF;
+
OPEN cur;
l: LOOP
@@ -12962,10 +14366,10 @@ BEGIN
CREATE TEMPORARY TABLE tmp.item
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
- SELECT itemFk FROM orderRow
+ SELECT itemFk FROM orderRow
WHERE orderFk = vSelf
GROUP BY itemFk;
-
+
CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode);
DROP TEMPORARY TABLE tmp.item;
@@ -13340,7 +14744,7 @@ BEGIN
END;
-- Carga los datos del pedido
- SELECT o.date_send, o.address_id, o.note, a.clientFk,
+ SELECT o.date_send, o.address_id, o.note, a.clientFk,
o.company_id, o.agency_id, c.isTaxDataChecked
INTO vDelivery, vAddress, vNotes, vClientId,
vCompanyId, vAgencyModeId, vIsTaxDataChecked
@@ -13390,23 +14794,29 @@ BEGIN
END IF;
-- Busca un ticket existente que coincida con los parametros
-
+ WITH tPrevia AS
+ (SELECT DISTINCT s.ticketFk
+ FROM vn.sale s
+ JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ WHERE t.shipped BETWEEN vShipment AND util.dayend(vShipment)
+ )
SELECT t.id INTO vTicket
FROM vn.ticket t
- LEFT JOIN vn.ticketState tls on tls.ticket = t.id
- JOIN `order` o
+ LEFT JOIN tPrevia tp ON tp.ticketFk = t.id
+ LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id
+ JOIN hedera.`order` o
ON o.address_id = t.addressFk
AND vWarehouse = t.warehouseFk
- -- AND o.agency_id = t.agencyModeFk
AND o.date_send = t.landed
- AND vShipment = DATE(t.shipped)
+ AND DATE(t.shipped) = vShipment
WHERE o.id = vSelf
AND t.refFk IS NULL
- AND IFNULL(tls.alertLevel,0) = 0
+ AND tp.ticketFk IS NULL
+ AND IFNULL(tls.alertLevel,0) = 0
LIMIT 1;
-- Crea el ticket en el caso de no existir uno adecuado
-
IF vTicket IS NULL
THEN
@@ -13428,7 +14838,7 @@ BEGIN
ELSE
INSERT INTO vn.ticketTracking
SET ticketFk = vTicket,
- workerFk = vUserId,
+ userFk = vUserId,
stateFk = TICKET_FREE;
END IF;
@@ -13442,7 +14852,7 @@ BEGIN
THEN
INSERT INTO vn.ticketObservation SET
ticketFk = vTicket,
- observationTypeFk = 4 /* salesperson */,
+ observationTypeFk = 4 /* salesperson */ ,
`description` = vNotes
ON DUPLICATE KEY UPDATE
`description` = CONCAT(VALUES(`description`),'. ', `description`);
@@ -13472,7 +14882,8 @@ BEGIN
IF vSale THEN
UPDATE vn.sale
- SET quantity = quantity + vAmount
+ SET quantity = quantity + vAmount,
+ originalQuantity = quantity
WHERE id = vSale;
SELECT s.quantity INTO vNewQuantity
@@ -13661,7 +15072,7 @@ BEGIN
INTO vDelivery, vAddress, vAgencyMode
FROM `order`
WHERE id = vSelf;
-
+
CALL vn.available_calc(vDelivery, vAddress, vAgencyMode);
DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable;
@@ -13703,7 +15114,7 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
CREATE TEMPORARY TABLE tmp.addressCompany
(INDEX (addressFk, companyFk))
- ENGINE = MEMORY
+ ENGINE = MEMORY
SELECT DISTINCT o.address_id addressFk, o.company_id companyFk
FROM tmp.`order` tmpOrder
JOIN hedera.`order` o ON o.id = tmpOrder.orderFk;
@@ -13738,7 +15149,7 @@ BEGIN
JOIN vn.taxClass tc ON tc.id = bp.taxClassFk
GROUP BY tmpOrder.orderFk, pgc.`code`, pgc.rate
HAVING taxableBase != 0;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount;
CREATE TEMPORARY TABLE tmp.orderAmount
(INDEX (orderFk))
@@ -13747,7 +15158,7 @@ BEGIN
SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax
FROM tmp.orderTax
GROUP BY orderFk, `code`;
-
+
DROP TEMPORARY TABLE tmp.addressTaxArea;
END ;;
DELIMITER ;
@@ -13817,7 +15228,7 @@ BEGIN
CREATE TEMPORARY TABLE tmp.`order`
ENGINE = MEMORY
SELECT vSelf orderFk;
-
+
CALL order_getTax;
SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0)
@@ -13908,7 +15319,7 @@ proc: BEGIN
FROM orderRow r
JOIN orderRowComponent c ON c.rowFk = r.id
WHERE r.orderFk = vSelf;
-
+
UPDATE orderRow r
LEFT JOIN tmp.ticketComponentPrice p
ON p.warehouseFk = r.warehouseFk
@@ -13933,7 +15344,7 @@ proc: BEGIN
ON t.id = c.componentFk
AND (t.classRate IS NULL OR t.classRate = r.rate)
WHERE r.orderFk = vSelf;
-
+
CALL vn.ticketCalculatePurge;
END IF;
@@ -14446,7 +15857,7 @@ p: BEGIN
FROM vn.`client` WHERE id = vCustomer;
SELECT account INTO vAccount
- FROM vn.bank WHERE id = vBank;
+ FROM vn.accounting WHERE id = vBank;
DELETE FROM vn.XDiario
WHERE SUBCTA = vSubaccount
@@ -14461,13 +15872,13 @@ p: BEGIN
AND DATE(FECHA) = vDate
AND EURODEBE = vAmount
LIMIT 1;
-
+
-- Actualiza la transaccion
UPDATE tpvTransaction
SET response = NULL, status = 'started'
WHERE id = vSelf;
-
+
COMMIT;
END ;;
DELIMITER ;
@@ -14500,7 +15911,7 @@ BEGIN
UPDATE userSession SET userVisitFk = vUserVisit
WHERE ssid = vSsid;
-
+
DELETE FROM userSession
WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, util.VN_NOW());
END ;;
@@ -14624,7 +16035,7 @@ BEGIN
UPDATE visitAgent SET firstAccessFk = vAccessId
WHERE id = vAgentId;
END IF;
-
+
-- Returns the visit info
SELECT vVisit visit, vAccessId access;
@@ -14655,46 +16066,6 @@ CREATE TABLE `blacklist` (
PRIMARY KEY (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Hangup input calls from this list';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`blacklist_beforeInsert`
- BEFORE INSERT ON `blacklist`
- FOR EACH ROW
-BEGIN
- CALL phone_isValid(NEW.phone);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`blacklist_berforeUpdate`
- BEFORE UPDATE ON `blacklist`
- FOR EACH ROW
-BEGIN
- CALL phone_isValid(NEW.phone);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `cdr`
@@ -14728,7 +16099,7 @@ CREATE TABLE `cdr` (
KEY `dstchannel` (`dst_channel`),
KEY `disposition` (`disposition`),
KEY `src` (`src`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -14770,7 +16141,7 @@ CREATE TABLE `config` (
`sundayFestive` tinyint(4) NOT NULL,
`countryPrefix` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -14787,46 +16158,6 @@ CREATE TABLE `followme` (
CONSTRAINT `followme_ibfk_1` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`followme_beforeInsert`
- BEFORE INSERT ON `followme`
- FOR EACH ROW
-BEGIN
- CALL pbx.phone_isValid(NEW.phone);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`followme_beforeUpdate`
- BEFORE UPDATE ON `followme`
- FOR EACH ROW
-BEGIN
- CALL pbx.phone_isValid(NEW.phone);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `followmeConf`
@@ -14859,7 +16190,7 @@ CREATE TABLE `followmeConfig` (
`declineCall` char(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`timeout` int(11) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -14894,48 +16225,8 @@ CREATE TABLE `queue` (
UNIQUE KEY `description` (`description`),
KEY `config` (`config`),
CONSTRAINT `queue_ibfk_1` FOREIGN KEY (`config`) REFERENCES `queueConfig` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queues';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queues';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`queue_beforeInsert`
- BEFORE INSERT ON `queue`
- FOR EACH ROW
-BEGIN
- CALL queue_isValid(NEW.`name`);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`queue_beforeUpdate`
- BEFORE UPDATE ON `queue`
- FOR EACH ROW
-BEGIN
- CALL queue_isValid(NEW.`name`);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `queueConf`
@@ -14971,7 +16262,7 @@ CREATE TABLE `queueConfig` (
`maxLen` int(10) unsigned NOT NULL,
`ringInUse` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Default values for queues configuration';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Default values for queues configuration';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -14990,7 +16281,7 @@ CREATE TABLE `queueMember` (
KEY `extension` (`extension`),
CONSTRAINT `queueMember_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `queueMember_ibfk_2` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue members';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue members';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -15022,48 +16313,8 @@ CREATE TABLE `queuePhone` (
PRIMARY KEY (`id`),
UNIQUE KEY `queue` (`queue`,`phone`),
CONSTRAINT `queuePhone_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`queuePhone_beforeInsert`
- BEFORE INSERT ON `queuePhone`
- FOR EACH ROW
-BEGIN
- CALL phone_isValid(NEW.phone);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`queuePhone_beforeUpdate`
- BEFORE UPDATE ON `queuePhone`
- FOR EACH ROW
-BEGIN
- CALL phone_isValid(NEW.phone);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `schedule`
@@ -15081,7 +16332,7 @@ CREATE TABLE `schedule` (
PRIMARY KEY (`id`),
KEY `queue` (`queue`),
CONSTRAINT `schedule_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -15102,96 +16353,6 @@ CREATE TABLE `sip` (
CONSTRAINT `sip_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='SIP accounts';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`sip_beforeInsert`
- BEFORE INSERT ON `sip`
- FOR EACH ROW
-BEGIN
- CALL sip_isValid(NEW.extension);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`sip_afterInsert`
- AFTER INSERT ON `sip`
- FOR EACH ROW
-BEGIN
- INSERT INTO sipReg
- SET userId = NEW.user_id;
-
- INSERT IGNORE INTO `account`.userSync (`name`)
- SELECT `name` FROM `account`.`user`
- WHERE id = NEW.user_id;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`sip_beforeUpdate`
- BEFORE UPDATE ON `sip`
- FOR EACH ROW
-BEGIN
- CALL sip_isValid(NEW.extension);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `pbx`.`sip_afterUpdate`
- AFTER UPDATE ON `sip`
- FOR EACH ROW
-BEGIN
- IF !(OLD.extension <=> NEW.extension)
- OR !(OLD.user_id <=> NEW.user_id) THEN
- INSERT IGNORE INTO `account`.userSync (`name`)
- SELECT `name` FROM `account`.`user`
- WHERE id = NEW.user_id;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `sipConf`
@@ -15204,6 +16365,7 @@ SET character_set_client = utf8;
/*!50001 CREATE VIEW `sipConf` AS SELECT
1 AS `id`,
1 AS `name`,
+ 1 AS `regexten`,
1 AS `callbackextension`,
1 AS `md5secret`,
1 AS `callerid`,
@@ -15214,10 +16376,12 @@ SET character_set_client = utf8;
1 AS `context`,
1 AS `incominglimit`,
1 AS `pickupgroup`,
- 1 AS `careinvite`,
+ 1 AS `directmedia`,
1 AS `insecure`,
1 AS `transport`,
1 AS `nat`,
+ 1 AS `disallow`,
+ 1 AS `allow`,
1 AS `ipaddr`,
1 AS `regseconds`,
1 AS `port`,
@@ -15244,11 +16408,9 @@ CREATE TABLE `sipConfig` (
`context` varchar(80) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`incomingLimit` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`pickupGroup` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- `careInvite` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `directMedia` enum('yes','no') DEFAULT NULL,
`insecure` varchar(45) NOT NULL,
`transport` varchar(255) DEFAULT NULL,
- `avpf` varchar(255) DEFAULT NULL,
- `icesupport` varchar(255) DEFAULT NULL,
`encryption` varchar(255) DEFAULT NULL,
`dtlsenable` varchar(255) DEFAULT NULL,
`dtlverify` varchar(255) DEFAULT NULL,
@@ -15256,8 +16418,11 @@ CREATE TABLE `sipConfig` (
`dtlsprivatekey` varchar(255) DEFAULT NULL,
`dtlssetup` varchar(255) DEFAULT NULL,
`nat` varchar(255) DEFAULT NULL,
+ `disallow` varchar(100) DEFAULT 'all',
+ `allow` varchar(100) DEFAULT 'g729;ilbc;gsm;ulaw;alaw',
+ `qualify` enum('yes','no') DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Default values for SIP accounts';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Default values for SIP accounts';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -15333,7 +16498,7 @@ BEGIN
WHILE vI < vLen
DO
SET vChr = SUBSTR(vPhone, vI + 1, 1);
-
+
IF vChr REGEXP '^[0-9]$'
THEN
SET vNewPhone = CONCAT(vNewPhone, vChr);
@@ -15341,7 +16506,7 @@ BEGIN
THEN
SET vNewPhone = CONCAT(vNewPhone, '00');
END IF;
-
+
SET vI = vI + 1;
END WHILE;
@@ -15440,18 +16605,18 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sip_getExtension`(vUserId INT(10))
BEGIN
-
+
/*
* Devuelve la extensión pbx del usuario
- *
- * @param vUserId Id del usuario
- *
+ *
+ * @param vUserId Id del usuario
+ *
*/
SELECT extension
- FROM sip s
+ FROM sip s
WHERE s.user_id = vUserId;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -15517,6 +16682,429 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
+--
+-- Current Database: `psico`
+--
+
+CREATE DATABASE /*!32312 IF NOT EXISTS*/ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
+
+USE `psico`;
+
+--
+-- Table structure for table `answer`
+--
+
+DROP TABLE IF EXISTS `answer`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `answer` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `text` varchar(155) NOT NULL,
+ `questionFk` int(11) NOT NULL,
+ `correct` tinyint(1) NOT NULL DEFAULT 0,
+ `order` int(11) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `answer_fk1_idx` (`questionFk`),
+ CONSTRAINT `answer_fk1` FOREIGN KEY (`questionFk`) REFERENCES `question` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `exam`
+--
+
+DROP TABLE IF EXISTS `exam`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `exam` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `duration` int(11) NOT NULL COMMENT 'minutos de duracion de la prueba',
+ `fellowFk` int(11) NOT NULL,
+ `examTypeFk` int(11) NOT NULL,
+ `started` datetime DEFAULT NULL,
+ `finished` datetime DEFAULT NULL,
+ `questionsCount` int(11) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `exam_fk1_idx` (`fellowFk`),
+ KEY `exam_fk2_idx` (`examTypeFk`),
+ CONSTRAINT `exam_fk1` FOREIGN KEY (`fellowFk`) REFERENCES `fellow` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `exam_fk2` FOREIGN KEY (`examTypeFk`) REFERENCES `examType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `examQuestion`
+--
+
+DROP TABLE IF EXISTS `examQuestion`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `examQuestion` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `examFk` int(11) NOT NULL,
+ `questionFk` int(11) NOT NULL,
+ `answerFk` int(11) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `examQuestion_fk1_idx` (`examFk`),
+ KEY `examQuestion_fk2_idx` (`questionFk`),
+ KEY `examQuestion_fk3_idx` (`answerFk`),
+ CONSTRAINT `examQuestion_fk1` FOREIGN KEY (`examFk`) REFERENCES `exam` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `examQuestion_fk2` FOREIGN KEY (`questionFk`) REFERENCES `question` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `examQuestion_fk3` FOREIGN KEY (`answerFk`) REFERENCES `answer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `examType`
+--
+
+DROP TABLE IF EXISTS `examType`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `examType` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `name` varchar(45) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `examView`
+--
+
+DROP TABLE IF EXISTS `examView`;
+/*!50001 DROP VIEW IF EXISTS `examView`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `examView` AS SELECT
+ 1 AS `text`,
+ 1 AS `examFk`,
+ 1 AS `questionFk`,
+ 1 AS `answerFk`,
+ 1 AS `id` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `fellow`
+--
+
+DROP TABLE IF EXISTS `fellow`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `fellow` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `name` varchar(45) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `question`
+--
+
+DROP TABLE IF EXISTS `question`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `question` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `text` varchar(155) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `randomOrder` int(11) DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `questionType`
+--
+
+DROP TABLE IF EXISTS `questionType`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `questionType` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `examTypeFk` int(11) NOT NULL,
+ `questionFk` int(11) NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `questionTypeFk1_idx` (`examTypeFk`),
+ KEY `questionTypeFk2_idx` (`questionFk`),
+ CONSTRAINT `questionTypeFk1` FOREIGN KEY (`examTypeFk`) REFERENCES `examType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
+ CONSTRAINT `questionTypeFk2` FOREIGN KEY (`questionFk`) REFERENCES `question` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `results`
+--
+
+DROP TABLE IF EXISTS `results`;
+/*!50001 DROP VIEW IF EXISTS `results`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `results` AS SELECT
+ 1 AS `examFk`,
+ 1 AS `aciertos`,
+ 1 AS `questionsCount`,
+ 1 AS `minutos`,
+ 1 AS `nota` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Dumping events for database 'psico'
+--
+
+--
+-- Dumping routines for database 'psico'
+--
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `answerSort` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `answerSort`()
+BEGIN
+
+ UPDATE answer
+ SET `order` = RAND() * 999999;
+
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `examNew` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `examNew`(vFellow VARCHAR(50), vType INT, vQuestionsNumber INT, OUT vExamFk INT)
+BEGIN
+
+ DECLARE done BOOL DEFAULT FALSE;
+ DECLARE vFellowFk INT;
+ DECLARE vQuestionFk INT;
+
+ DECLARE rs CURSOR FOR
+ SELECT q.id
+ FROM psico.question q
+ LEFT JOIN psico.questionType qt ON q.id = qt.questionFk
+ WHERE qt.examTypeFk = vType
+ ORDER BY randomOrder;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+ IF vQuestionsNumber = 0 THEN
+
+ SET vQuestionsNumber = 30;
+
+ END IF;
+
+ CALL psico.answerSort();
+
+ CALL psico.questionSort();
+
+ INSERT INTO psico.fellow(name) VALUES(vFellow);
+
+ SELECT MAX(id) INTO vFellowFk FROM psico.fellow;
+
+ INSERT INTO psico.exam(fellowFk, started, questionsCount,examTypeFk) VALUES(vFellowFk, util.VN_NOW(), vQuestionsNumber,vType);
+
+ SELECT MAX(id) INTO vExamFk FROM psico.exam;
+
+ OPEN rs;
+
+ FETCH rs INTO vQuestionFk;
+
+ WHILE NOT done AND vQuestionsNumber DO
+
+ INSERT INTO psico.examQuestion(examFk, questionFk)
+ VALUES (vExamFk, vQuestionFk);
+
+
+ FETCH rs INTO vQuestionFk;
+
+ SET vQuestionsNumber = vQuestionsNumber - 1;
+
+ END WHILE;
+
+ CLOSE rs;
+
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `getExamQuestions` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `getExamQuestions`(vExamFk INT)
+BEGIN
+
+SELECT p.text,p.examFk,p.questionFk,p.answerFk,p.id ,a.text AS answerText,a.correct, a.id AS answerFk
+FROM psico.examView as p
+INNER JOIN psico.answer as a ON p.questionFk = a.questionFk
+WHERE examFk = vExamFk;
+
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `getExamType` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `getExamType`()
+BEGIN
+
+SELECT id,name
+FROM psico.examType;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `questionSort` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `questionSort`()
+BEGIN
+
+ UPDATE question
+ SET randomOrder = RAND() * 999999;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+
+--
+-- Current Database: `rfid`
+--
+
+CREATE DATABASE /*!32312 IF NOT EXISTS*/ `rfid` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
+
+USE `rfid`;
+
+--
+-- Table structure for table `expedition_PrintOut`
+--
+
+DROP TABLE IF EXISTS `expedition_PrintOut`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `expedition_PrintOut` (
+ `expeditionFk` int(11) NOT NULL,
+ `ticketFk` int(11) NOT NULL,
+ `addressFk` int(11) NOT NULL,
+ `street` varchar(100) NOT NULL,
+ `postalCode` varchar(10) NOT NULL,
+ `city` varchar(100) NOT NULL,
+ `shopName` varchar(100) NOT NULL,
+ `isPrinted` tinyint(1) NOT NULL DEFAULT 0,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `printerFk` int(11) NOT NULL DEFAULT 1,
+ `routeFk` int(11) DEFAULT NULL,
+ `parkingCode` varchar(8) DEFAULT NULL,
+ `truckName` varchar(25) DEFAULT NULL,
+ PRIMARY KEY (`expeditionFk`),
+ KEY `expedition_PrintOut_FK` (`printerFk`),
+ CONSTRAINT `expedition_PrintOut_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `expedition_Read`
+--
+
+DROP TABLE IF EXISTS `expedition_Read`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `expedition_Read` (
+ `expeditionFk` int(11) NOT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `readingPointFk` int(11) DEFAULT NULL,
+ PRIMARY KEY (`expeditionFk`),
+ KEY `expedition_Read_FK` (`readingPointFk`),
+ CONSTRAINT `expedition_Read_FK` FOREIGN KEY (`readingPointFk`) REFERENCES `readingPoint` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `printer`
+--
+
+DROP TABLE IF EXISTS `printer`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `printer` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(50) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `readingPoint`
+--
+
+DROP TABLE IF EXISTS `readingPoint`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `readingPoint` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(100) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Dumping events for database 'rfid'
+--
+
+--
+-- Dumping routines for database 'rfid'
+--
+
--
-- Current Database: `sage`
--
@@ -15677,6 +17265,19 @@ CREATE TABLE `TiposTransacciones` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `accountingEntryError`
+--
+
+DROP TABLE IF EXISTS `accountingEntryError`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `accountingEntryError` (
+ `accountingEntryFk` int(10) unsigned NOT NULL,
+ PRIMARY KEY (`accountingEntryFk`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Listado de asientos presentes en Sage para notificar su error';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Temporary table structure for view `clientLastTwoMonths`
--
@@ -15837,7 +17438,7 @@ CREATE TABLE `config` (
`definitiveExportTransactionTypeFk` tinyint(4) DEFAULT NULL COMMENT 'Transacción Exportaciones definitivas',
`shipmentTransactionTypeFk` tinyint(4) DEFAULT NULL COMMENT 'Transacción Envíos definitivos a Canarias, Ceuta y Melilla',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -16032,30 +17633,8 @@ CREATE TABLE `movConta` (
KEY `ix_movconta` (`enlazadoSage`,`IdProcesoIME`),
KEY `movConta_IdProcesoIME` (`IdProcesoIME`),
KEY `movConta_Asiento2` (`Asiento`,`IdProcesoIME`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `sage`.`movConta_BEFORE_UPDATE`
- BEFORE UPDATE ON `movConta`
- FOR EACH ROW
-BEGIN
- IF NEW.enlazadoSage = TRUE THEN
- UPDATE vn.XDiario SET enlazadoSage = TRUE WHERE ASIEN = NEW.Asiento;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `movContaIVA`
@@ -16153,7 +17732,7 @@ CREATE TABLE `pgcToSage` (
`accountTaxInput` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`accountTaxOutput` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Tabla relaciona cuentas pgc con Código de IVA y Código de Transacción en Sage';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Tabla relaciona cuentas pgc con Código de IVA y Código de Transacción en Sage';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -16239,22 +17818,22 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `company_getCode`(vCompanyFk INT) RET
READS SQL DATA
BEGIN
/**
- * Devuelve la correspondencía del código de empresa de sage.
+ * Devuelve la correspondencía del código de empresa de sage.
* Tiene en cuenta el entorno
- *
+ *
* @param vSelf Id de empresa de verdnatura
* @return Código de empresa sage
*/
DECLARE vCompanySageFk INT(2);
-
- SELECT IF(c.environment = 'production',
- co.companyCode,
+
+ SELECT IF(c.environment = 'production',
+ co.companyCode,
co.companyCodeTest
) INTO vCompanySageFk
FROM util.config c
JOIN vn.company co
WHERE co.id = vCompanyFk;
-
+
RETURN vCompanySageFk;
END ;;
DELIMITER ;
@@ -16273,12 +17852,12 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `accountingMovements_add`(
- vYear INT,
+ vYear INT,
vCompanyFk INT
)
BEGIN
/**
- * Traslada la info de contabilidad generada en base a vn.XDiario a la tabla sage.movConta
+ * Traslada la info de contabilidad generada en base a vn.XDiario a la tabla sage.movConta
* para poder ejecutar posteriormente el proceso de importación de datos de SQL Server
* Solo traladará los asientos marcados con el campo vn.XDiario.enlazadoSage = FALSE
* @vYear Año contable del que se quiere trasladar la información
@@ -16295,7 +17874,6 @@ BEGIN
DECLARE vSerialDua VARCHAR(1) DEFAULT 'D';
DECLARE vInvoiceTypeInformativeCode VARCHAR(1);
DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2) ;
- DECLARE vBookEntries TEXT;
SELECT SiglaNacion INTO vCountryCanariasCode
FROM Naciones
@@ -16527,9 +18105,9 @@ BEGIN
LIMIT 10000000000000000000
) sub GROUP BY ASIEN
)sub2 ON sub2.ASIEN = x.ASIEN
- LEFT JOIN ( SELECT DISTINCT(account),cu.code
- FROM vn.bank b
- JOIN vn.currency cu ON cu.id = b.currencyFk
+ LEFT JOIN ( SELECT DISTINCT(a.account),cu.code
+ FROM vn.accounting a
+ JOIN vn.currency cu ON cu.id = a.currencyFk
WHERE cu.code <> 'EUR' -- no se informa cuando la divisa en EUR
)sub3 ON sub3.account = x.SUBCTA
WHERE x.enlazadoSage = FALSE
@@ -16594,8 +18172,8 @@ BEGIN
mci.FechaFacturaOriginal = x.FECHA_EX,
mci.SuFacturaNo = x.FACTURAEX,
mci.FechaOperacion = x.FECHA_OP,
- mci.ImporteFactura = mci.ImporteFactura +
- x.BASEEURO +
+ mci.ImporteFactura = mci.ImporteFactura +
+ x.BASEEURO +
CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2))
WHERE pm.description = 'HP Iva pendiente'
AND mci.enlazadoSage = FALSE
@@ -16614,7 +18192,7 @@ BEGIN
mci.CodigoIva2 = vTaxImportFk,
mci.IvaDeducible2 = TRUE,
mci.ImporteFactura = mci.ImporteFactura +
- x.BASEEURO +
+ x.BASEEURO +
CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2))
WHERE pm.description = 'HP Iva pendiente'
AND mci.enlazadoSage = FALSE
@@ -16632,8 +18210,8 @@ BEGIN
mci.CodigoTransaccion3 = vDuaTransactionFk ,
mci.CodigoIva3 = vTaxImportSuperReducedFk,
mci.IvaDeducible3 = TRUE,
- mci.ImporteFactura = mci.ImporteFactura +
- x.BASEEURO +
+ mci.ImporteFactura = mci.ImporteFactura +
+ x.BASEEURO +
CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2))
WHERE pm.description = 'HP Iva pendiente'
AND mci.enlazadoSage = FALSE
@@ -16667,14 +18245,14 @@ BEGIN
OR CodigoTransaccion2 = vTransactionExportFk
OR CodigoTransaccion3 = vTransactionExportFk
OR CodigoTransaccion4 = vTransactionExportFk)
- AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci,
+ AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci,
vCountryCeutaMelillaCode COLLATE utf8mb3_unicode_ci);
UPDATE movConta mc
SET CodigoDivisa = 'USD',
FactorCambio = TRUE,
- ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0,
- ImporteAsiento / ImporteDivisa,
+ ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0,
+ ImporteAsiento / ImporteDivisa,
ImporteCambio) AS DECIMAL( 10, 2)))
WHERE enlazadoSage = FALSE
AND (ImporteCambio <> 0 OR ImporteDivisa <> 0 OR FactorCambio);
@@ -16685,41 +18263,31 @@ BEGIN
AND importeDivisa > 0
AND ImporteAsiento < 0;
- -- Comprobación que los importes e ivas sean correctos, avisa vía CAU
- SELECT GROUP_CONCAT(Asiento ORDER BY Asiento ASC SEPARATOR ',') INTO vBookEntries
- FROM(SELECT sub.Asiento
- FROM (SELECT mc.Asiento, SUM(mc.ImporteAsiento) amount
- FROM movConta mc
- WHERE mc.enlazadoSage = FALSE
- GROUP BY mc.Asiento)sub
- JOIN (SELECT x.ASIEN, SUM(IFNULL(x.EURODEBE,0) + IFNULL(x.EUROHABER,0)) amount
- FROM vn.XDiario x
- WHERE x.enlazadoSage = FALSE
- GROUP BY ASIEN)sub2 ON sub2.ASIEN = sub.Asiento
- WHERE sub.amount <> sub2.amount
- UNION ALL
- SELECT sub.Asiento
- FROM (SELECT Asiento, SUM(BaseIva1 + BaseIva2 + BaseIva3 + BaseIva4) amountTaxableBase
- FROM movConta
- WHERE TipoFactura <> 'I'
- AND enlazadoSage = FALSE
- GROUP BY Asiento) sub
- JOIN (SELECT ASIEN, SUM(BASEEURO) amountTaxableBase
- FROM (SELECT ASIEN, SUM(BASEEURO) BASEEURO
- FROM vn.XDiario
- WHERE FACTURA
- AND auxiliar <> '*'
- AND enlazadoSage = FALSE
- GROUP BY FACTURA, ASIEN)sub3
- GROUP BY ASIEN) sub2 ON sub2.ASIEN = sub.Asiento
- WHERE sub.amountTaxableBase<>sub2.amountTaxableBase
- AND sub.amountTaxableBase/2 <> sub2.amountTaxableBase) sub;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `clean` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
+BEGIN
+/**
+ * Maintains tables over time by removing unnecessary data
+ */
+ DECLARE vTwoYearAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR;
+
+ DELETE FROM movConta WHERE FechaAsiento < vTwoYearAgo;
- IF vBookEntries IS NOT NULL THEN
- SELECT util.notification_send ("book-entries-imported-incorrectly",
- CONCAT('{"bookEntries":"', vBookEntries,'"}'),
- null);
- END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -16798,8 +18366,8 @@ BEGIN
IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla := IF(pr.Provincia IN ('CEUTA', 'MELILLA'), TRUE, FALSE), vCountryCeutaMelillaFk, IF (@isCanarias, vCountryCanariasCode, n.CodigoNacion)), n.CodigoNacion),
IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla, vCountryCeutaMelillaCode, IF (@isCanarias, vCountryCanariasCode, n.SiglaNacion)), n.SiglaNacion),
IF((c.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F'),
- IF(cu.code = 'ES',
- 1,
+ IF(cu.code = 'ES',
+ 1,
IF((cu.isUeeMember AND c.isVies), 2, 4)),
IFNULL(c.taxTypeSageFk,0),
IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci,
@@ -16865,6 +18433,81 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `importErrorNotification` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `importErrorNotification`()
+BEGIN
+/**
+ * Inserta notificaciones con los errores detectados durante la importación
+ *
+ */
+ DECLARE vBookEntries TEXT;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ SELECT GROUP_CONCAT(error SEPARATOR ' ') INTO vBookEntries
+ FROM(
+ SELECT CONCAT('- Importes: ', sub.Asiento) error
+ FROM (SELECT mc.Asiento, SUM(mc.ImporteAsiento) amount
+ FROM movConta mc
+ WHERE mc.enlazadoSage = FALSE
+ GROUP BY mc.Asiento)sub
+ JOIN (SELECT x.ASIEN, SUM(IFNULL(x.EURODEBE,0) + IFNULL(x.EUROHABER,0)) amount
+ FROM vn.XDiario x
+ WHERE x.enlazadoSage = FALSE
+ GROUP BY ASIEN)sub2 ON sub2.ASIEN = sub.Asiento
+ WHERE sub.amount <> sub2.amount
+ UNION ALL
+ SELECT CONCAT('- Base imponible: ', sub.Asiento)
+ FROM (SELECT Asiento, SUM(BaseIva1 + BaseIva2 + BaseIva3 + BaseIva4) amountTaxableBase
+ FROM movConta
+ WHERE TipoFactura <> 'I'
+ AND enlazadoSage = FALSE
+ GROUP BY Asiento) sub
+ JOIN (SELECT ASIEN, SUM(BASEEURO) amountTaxableBase
+ FROM (SELECT ASIEN, SUM(BASEEURO) BASEEURO
+ FROM vn.XDiario
+ WHERE FACTURA
+ AND auxiliar <> '*'
+ AND enlazadoSage = FALSE
+ GROUP BY FACTURA, ASIEN)sub3
+ GROUP BY ASIEN) sub2 ON sub2.ASIEN = sub.Asiento
+ WHERE sub.amountTaxableBase<>sub2.amountTaxableBase
+ AND sub.amountTaxableBase/2 <> sub2.amountTaxableBase
+ UNION ALL
+ SELECT CONCAT('- Factura Duplicada: ', mc.Asiento)
+ FROM accountingEntryError
+ )sub;
+
+ IF vBookEntries IS NOT NULL THEN
+ START TRANSACTION;
+
+ SELECT util.notification_send ("book-entries-imported-incorrectly",
+ CONCAT('{"bookEntries":"', vBookEntries,'"}'),
+ null);
+
+ TRUNCATE accountingEntryError;
+
+ COMMIT;
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceIn_add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -16881,6 +18524,7 @@ BEGIN
* @vInvoiceInFk Factura recibida
* @vXDiarioFk Id tabla XDiario
*/
+ DECLARE vInvoiceInOriginalFk INT;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vBase DOUBLE;
DECLARE vVat DOUBLE;
@@ -17053,7 +18697,7 @@ BEGIN
JOIN vn.XDiario x ON x.id = mci.id
JOIN vn.supplier s ON s.id = supplierFk
JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id
- JOIN vn.expence e ON e.id = iit.expenceFk
+ JOIN vn.expense e ON e.id = iit.expenseFk
JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk
LEFT JOIN tmp.invoiceDua id ON id.id = mci.id
JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase
@@ -17072,6 +18716,37 @@ BEGIN
AND e.name = 'Retenciones'
AND id.id IS NULL;
+ SELECT correctedFk INTO vInvoiceInOriginalFk
+ FROM vn.invoiceInCorrection
+ WHERE correctingFk = vInvoiceInFk;
+
+ IF vInvoiceInOriginalFk THEN
+
+ UPDATE movContaIVA mci
+ JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk
+ JOIN (SELECT issued,
+ SUM(sub.taxableBase) taxableBase,
+ SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat
+ FROM(SELECT issued,
+ SUM(iit.taxableBase) taxableBase,
+ ti.PorcentajeIva
+ FROM vn.invoiceIn i
+ JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id
+ JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
+ WHERE i.id = vInvoiceInOriginalFk
+ GROUP BY ti.CodigoIva)sub
+ )invoiceInOriginal
+ JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
+ SET mci.TipoRectificativa = iir.refundCategoryFk,
+ mci.ClaseAbonoRectificativas = iir.refundType,
+ mci.FechaFacturaOriginal = invoiceInOriginal.issued,
+ mci.FechaOperacion = invoiceInOriginal.issued,
+ mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase,
+ mci.CuotaIvaOriginal = invoiceInOriginal.vat,
+ mci.ClaveOperacionFactura = co.ClaveOperacionFactura_
+ WHERE mci.id = vXDiarioFk;
+
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -17091,10 +18766,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_manager`(vYear INT, vCompanyFk INT)
BEGIN
/**
- * Traslada la info de contabilidad relacionada con las facturas recibidas
- *
+ * Traslada la info de contabilidad relacionada con las facturas recibidas
+ *
* @vYear Año contable del que se quiere trasladar la información
- * @vCompany Empresa de la que se quiere trasladar datos
+ * @vCompany Empresa de la que se quiere trasladar datos
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceFk INT;
@@ -17106,22 +18781,22 @@ BEGIN
DECLARE vAccountTaxOutstanding VARCHAR(10);
DECLARE vInvoiceTypeSended VARCHAR(1);
DECLARE vCursor CURSOR FOR
- SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk,
+ SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk,
x.id XDiarioFk
- FROM vn.XDiario x
+ FROM vn.XDiario x
JOIN(SELECT DISTINCT(x.ASIEN)
FROM vn.XDiario x
LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id
LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id
- WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci)
- AND x.enlazadoSage = FALSE
+ WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci)
+ AND x.enlazadoSage = FALSE
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
- AND x.empresa_id = vCompanyFk
+ AND x.empresa_id = vCompanyFk
) sub ON sub.ASIEN = x.ASIEN
WHERE x.CLAVE IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE))
INTO vDatedFrom, vDatedTo;
@@ -17135,15 +18810,15 @@ BEGIN
SELECT codeSage INTO vInvoiceTypeSended
FROM invoiceType WHERE `code` ='sended';
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.invoiceDua;
CREATE TEMPORARY TABLE tmp.invoiceDua
- SELECT x.id
+ SELECT x.id
FROM vn.XDiario x
JOIN vn.company c ON c.id = x.empresa_id
JOIN (SELECT ASIEN
- FROM vn.XDiario x
- WHERE x.enlazadoSage = FALSE
+ FROM vn.XDiario x
+ WHERE x.enlazadoSage = FALSE
AND x.SUBCTA = vAccountTaxOutstanding COLLATE utf8mb3_unicode_ci
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
)sub ON sub.ASIEN = x.ASIEN
@@ -17156,12 +18831,12 @@ BEGIN
i.serial COLLATE utf8mb3_unicode_ci serial,
i.supplierFk,
i.issued,
- IF(expenceFkDeductible, FALSE, i.isVatDeductible) isVatDeductible,
+ IF(expenseFkDeductible, FALSE, i.isVatDeductible) isVatDeductible,
IF(c.code = 'EUR', '',c.`code`) currencyFk
FROM vn.invoiceIn i
JOIN vn.currency c ON c.id = i.currencyFk
WHERE i.bookEntried BETWEEN vDatedFrom AND vDatedTo
- UNION ALL
+ UNION ALL
SELECT d.id,
d.code,
vSerialDua COLLATE utf8mb3_unicode_ci,
@@ -17169,8 +18844,8 @@ BEGIN
d.issued,
FALSE,
'' -- EUROS
- FROM vn.dua d
- WHERE d.issued IS NOT NULL
+ FROM vn.dua d
+ WHERE d.issued IS NOT NULL
AND code IS NOT NULL;
OPEN vCursor;
@@ -17178,7 +18853,7 @@ BEGIN
l: LOOP
FETCH vCursor INTO vInvoiceFk, vXDiarioFk;
- IF vDone THEN
+ IF vDone THEN
LEAVE l;
END IF;
CALL invoiceIn_add(vInvoiceFk, vXDiarioFk);
@@ -17266,21 +18941,21 @@ BEGIN
JOIN (SELECT x.ASIEN, x.id
FROM vn.XDiario x
JOIN(SELECT DISTINCT(x.ASIEN) ASIEN
- FROM vn.XDiario x
+ FROM vn.XDiario x
JOIN (SELECT DISTINCT(ASIEN)
FROM vn.XDiario x
- WHERE SUBCTA LIKE '472%'
+ WHERE SUBCTA LIKE '472%'
AND x.enlazadoSage = FALSE
AND x.empresa_id = vCompanyFk
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
) sub ON sub.ASIEN = x.ASIEN
WHERE x.SUBCTA LIKE '477%'
)sub2 ON sub2.ASIEN = x.ASIEN
- WHERE x.CONTRA IS NOT NULL
+ WHERE x.CONTRA IS NOT NULL
AND x.SUBCTA LIKE '477%'
GROUP BY x.ASIEN
)sub3 ON sub3.ASIEN = x.ASIEN;
-
+
INSERT INTO movContaIVA
(`id`,
`CodigoDivisa`,
@@ -17351,9 +19026,9 @@ BEGIN
`FechaGrabacion`,
`Intracomunitaria`,
`moveData`)
- SELECT *
+ SELECT *
FROM tmp.movContaIVA;
-
+
DROP TEMPORARY TABLE tmp.movContaIVA;
END ;;
@@ -17375,10 +19050,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_add`(IN vInvoiceOutFk INT, IN vXDiarioFk INT)
BEGIN
/**
- * Traslada la info de contabilidad relacionada con las facturas emitidas
- *
+ * Traslada la info de contabilidad relacionada con las facturas emitidas
+ *
* @vYear Año contable del que se quiere trasladar la información
- * @vCompany Empresa de la que se quiere trasladar datos
+ * @vCompany Empresa de la que se quiere trasladar datos
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vMaxLengthName INT DEFAULT 35;
@@ -17398,12 +19073,12 @@ BEGIN
DECLARE vHasCustomsAccountingNote BOOL;
DECLARE vCursor CURSOR FOR
- SELECT oit.taxableBase,
- oit.vat,
- pgc.rate,
- pgc.mod347,
- pgcRE.rate,
- oitRE.vat,
+ SELECT oit.taxableBase,
+ oit.vat,
+ pgc.rate,
+ pgc.mod347,
+ pgcRE.rate,
+ oitRE.vat,
tc.transactionCode,
tc.taxCode,
tc.isIntracommunity,
@@ -17412,7 +19087,7 @@ BEGIN
JOIN vn.pgc ON pgc.code = oit.pgcFk
LEFT JOIN vn.pgcEqu e ON e.vatFk = oit.pgcFk
LEFT JOIN vn.pgcEqu eRE ON eRE.equFk = oit.pgcFk
- LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk
+ LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk
AND oitRE.pgcFk = e.equFk
LEFT JOIN vn.pgc pgcRE ON pgcRE.code = oitRE.pgcFk
LEFT JOIN vn.taxCode tc ON tc.code = pgc.code COLLATE 'utf8mb3_unicode_ci'
@@ -17428,12 +19103,12 @@ BEGIN
WHERE ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioFk);
SELECT codeSage INTO vInvoiceTypeSended
- FROM invoiceType
+ FROM invoiceType
WHERE code = IF(vHasCustomsAccountingNote, 'informative', 'sended');
-
+
DELETE FROM movContaIVA
WHERE id = vXDiarioFk;
-
+
INSERT INTO movContaIVA(id) VALUES (vXDiarioFk);
OPEN vCursor;
@@ -17450,13 +19125,13 @@ BEGIN
vIsIntracommunity,
vOperationCode;
- IF vDone THEN
+ IF vDone THEN
LEAVE l;
END IF;
SET vCounter = vCounter + 1;
-
- CASE vCounter
+
+ CASE vCounter
WHEN 1 THEN
UPDATE movContaIVA
SET BaseIva1 = vBase,
@@ -17497,7 +19172,7 @@ BEGIN
CodigoTransaccion4 = vTransactionCode,
CodigoIva4 = vTaxCode
WHERE id = vXDiarioFk;
- END CASE;
+ END CASE;
UPDATE movContaIVA
SET Exclusion347 = NOT vMod347,
@@ -17508,7 +19183,7 @@ BEGIN
END LOOP;
CLOSE vCursor;
-
+
UPDATE movContaIVA mci
JOIN vn.invoiceOut i ON i.id = vInvoiceOutFk
LEFT JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutFk
@@ -17533,25 +19208,25 @@ BEGIN
mci.MantenerAsiento = TRUE,
mci.FechaFacturaOriginal = x.FECHA_EX
WHERE mci.id = vXDiarioFk;
-
+
SELECT correctedFk INTO vInvoiceOutCorrectedFk
FROM vn.invoiceCorrection
WHERE correctingFk = vInvoiceOutFk;
-
- IF vInvoiceOutCorrectedFk THEN
+
+ IF vInvoiceOutCorrectedFk THEN
UPDATE movContaIVA mci
JOIN vn.invoiceOut i ON i.id = vInvoiceOutCorrectedFk
JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutCorrectedFk
- JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase,
+ JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase,
SUM(IF(IFNULL(e.vatFk, TRUE), iot.vat, 0)) vat,
SUM(IF(IFNULL(e.vatFk, TRUE), 0, iot.vat)) equ
FROM vn.invoiceOutTax iot
- LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk
+ LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk
WHERE iot.invoiceOutFk = vInvoiceOutCorrectedFk
) tax
JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
SET mci.TipoRectificativa = 2,
- mci.ClaseAbonoRectificativas = 1,
+ mci.ClaseAbonoRectificativas = 1,
mci.FechaFacturaOriginal = i.issued,
mci.FechaOperacion = i.issued,
mci.BaseImponibleOriginal = tax.taxableBase,
@@ -17582,10 +19257,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_manager`(vYear INT, vCompanyFk INT)
BEGIN
/**
- * Traslada la info de contabilidad relacionada con las facturas emitidas
- *
+ * Traslada la info de contabilidad relacionada con las facturas emitidas
+ *
* @vYear Año contable del que se quiere trasladar la información
- * @vCompany Empresa de la que se quiere trasladar datos
+ * @vCompany Empresa de la que se quiere trasladar datos
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceFk INT;
@@ -17602,7 +19277,7 @@ BEGIN
JOIN (SELECT x.ASIEN, CONCAT(x.SERIE, x.FACTURA) refFk
FROM vn.XDiario x
WHERE x.enlazadoSage = FALSE
- AND x.FACTURA
+ AND x.FACTURA
AND x.empresa_id = vCompanyFk
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
GROUP BY refFk
@@ -17611,19 +19286,19 @@ BEGIN
)sub2 ON sub2.refFk = i.ref;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE))
INTO vDatedFrom, vDatedTo;
-
+
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vInvoiceFk, vXDiarioFk;
- IF vDone THEN
+ IF vDone THEN
LEAVE l;
END IF;
-
+
CALL invoiceOut_add(vInvoiceFk, vXDiarioFk);
END LOOP;
@@ -17649,7 +19324,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `pgc_add`(vCompanyFk INT)
BEGIN
/**
- * Añade cuentas del plan general contable para exportarlos a Sage
+ * Añade cuentas del plan general contable para exportarlos a Sage
* @vCompanyFk Empresa de la que se quiere trasladar datos
*/
TRUNCATE TABLE planCuentasPGC;
@@ -17659,25 +19334,25 @@ BEGIN
CodigoCuenta,
Cuenta,
ClienteOProveedor)
- SELECT *
+ SELECT *
FROM (SELECT company_getCode(vCompanyFk) companyFk,
e.id accountFk,
UCASE(e.name),
''
- FROM vn.expence e
- UNION
+ FROM vn.expense e
+ UNION
SELECT company_getCode(vCompanyFk),
- b.account,
- UCASE(b.bank),
- ''
- FROM vn.bank b
- WHERE b.isActive
- AND b.`account`
- UNION
+ a.account,
+ UCASE(a.bank),
+ ''
+ FROM vn.accounting a
+ WHERE a.isActive
+ AND a.`account`
+ UNION
SELECT CodigoEmpresa,
CodigoCuenta,
Nombre,
- ClienteOProveedor
+ ClienteOProveedor
FROM clientesProveedores)sub
GROUP BY companyFk, accountFk;
END ;;
@@ -17714,7 +19389,7 @@ CREATE TABLE `ACL` (
KEY `model_ix` (`model`(255)) COMMENT 'ernesto 3.8.2020. Mysql pide indices',
KEY `property_ix` (`property`(255)),
KEY `accessType_ix` (`accessType`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -17817,7 +19492,7 @@ CREATE TABLE `accessTokenConfig` (
`courtesyTime` int(10) unsigned DEFAULT NULL,
`renewInterval` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -17864,7 +19539,7 @@ CREATE TABLE `fieldAcl` (
`actionType` set('insert','update','*') DEFAULT '*',
`role` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -17892,7 +19567,7 @@ CREATE TABLE `printConfig` (
`itRecipient` varchar(50) DEFAULT NULL COMMENT 'IT recipients for report mailing',
`incidencesEmail` varchar(50) DEFAULT NULL COMMENT 'CAU destinatary email',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Print service config';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Print service config';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -17924,7 +19599,7 @@ CREATE TABLE `userConfigView` (
`configuration` text DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUser_TableCode` (`userFk`,`tableCode`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -17943,7 +19618,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `accessToken_prune` ON SCHEDULE EVERY 1 DAY STARTS '2023-03-14 05:14:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL salix.accessToken_prune */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `accessToken_prune` ON SCHEDULE EVERY 1 DAY STARTS '2023-03-14 05:14:00' ON COMPLETION PRESERVE ENABLE DO CALL salix.accessToken_prune */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -17979,6 +19654,3554 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
+--
+-- Current Database: `srt`
+--
+
+CREATE DATABASE /*!32312 IF NOT EXISTS*/ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
+
+USE `srt`;
+
+--
+-- Table structure for table `antenna`
+--
+
+DROP TABLE IF EXISTS `antenna`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `antenna` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(100) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lector de codigos RFID en el sorter';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `buffer`
+--
+
+DROP TABLE IF EXISTS `buffer`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `buffer` (
+ `id` int(11) NOT NULL,
+ `x` int(11) DEFAULT NULL,
+ `y` int(11) DEFAULT NULL,
+ `size` int(11) DEFAULT NULL,
+ `length` int(11) DEFAULT NULL,
+ `stateFk` int(11) NOT NULL DEFAULT 1,
+ `typeFk` int(11) NOT NULL DEFAULT 0,
+ `isActive` tinyint(1) NOT NULL DEFAULT 1,
+ `code` varchar(3) DEFAULT NULL,
+ `stratus` int(11) NOT NULL COMMENT 'representa la altura del buffer',
+ `hasWorkerWaiting` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si hay un paletizador',
+ `reserve` varchar(100) DEFAULT NULL,
+ `routeFk` int(11) DEFAULT NULL COMMENT 'ruta que va a descargar por ahi',
+ `dayMinute` int(11) DEFAULT NULL COMMENT 'camion que va a descargar',
+ `lastUnloaded` datetime DEFAULT NULL COMMENT 'hora de la última descarga',
+ `hasStrapper` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'tiene una flejadora acoplada',
+ `typeDefaultFk` int(11) NOT NULL DEFAULT 1 COMMENT 'estado por defecto',
+ `motors` int(11) NOT NULL DEFAULT 1 COMMENT 'número de fotocélulas que corresponden con sectores de motor independientes',
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `code_UNIQUE` (`code`),
+ KEY `buffer_FK` (`stateFk`),
+ KEY `buffer_FK_1` (`typeFk`),
+ CONSTRAINT `buffer_FK` FOREIGN KEY (`stateFk`) REFERENCES `bufferState` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `buffer_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `bufferType` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `bufferDayMinute`
+--
+
+DROP TABLE IF EXISTS `bufferDayMinute`;
+/*!50001 DROP VIEW IF EXISTS `bufferDayMinute`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `bufferDayMinute` AS SELECT
+ 1 AS `bufferFk`,
+ 1 AS `expeditionFk`,
+ 1 AS `dayMinute`,
+ 1 AS `position`,
+ 1 AS `ETD`,
+ 1 AS `ticketFk`,
+ 1 AS `routeFk`,
+ 1 AS `zonaTicket`,
+ 1 AS `expeditionState` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `bufferFreeLength`
+--
+
+DROP TABLE IF EXISTS `bufferFreeLength`;
+/*!50001 DROP VIEW IF EXISTS `bufferFreeLength`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `bufferFreeLength` AS SELECT
+ 1 AS `bufferFk`,
+ 1 AS `bufferName`,
+ 1 AS `freeLength`,
+ 1 AS `saturacion`,
+ 1 AS `state`,
+ 1 AS `stateFk`,
+ 1 AS `typeFk`,
+ 1 AS `typeName`,
+ 1 AS `stock`,
+ 1 AS `RealFreeLength` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `bufferGroup`
+--
+
+DROP TABLE IF EXISTS `bufferGroup`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `bufferGroup` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `bufferFk` int(11) NOT NULL,
+ `group` int(11) NOT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `bufferGroup_UN` (`bufferFk`),
+ CONSTRAINT `bufferGroup_FK` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Agrupación de buffers que sirven de salida para las mismas rutas';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `bufferPool`
+--
+
+DROP TABLE IF EXISTS `bufferPool`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `bufferPool` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `bufferFk` int(11) NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `bufferPool_fk1_idx` (`bufferFk`),
+ CONSTRAINT `bufferPool_fk1` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla se almacen los buffers que se quieren utilizar como destino de las cajas que entran, para forzar el envio a los mismos.';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `bufferState`
+--
+
+DROP TABLE IF EXISTS `bufferState`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `bufferState` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(20) NOT NULL,
+ `isAvailable` tinyint(1) NOT NULL DEFAULT 0,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `bufferStock`
+--
+
+DROP TABLE IF EXISTS `bufferStock`;
+/*!50001 DROP VIEW IF EXISTS `bufferStock`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `bufferStock` AS SELECT
+ 1 AS `expeditionFk`,
+ 1 AS `bufferFk`,
+ 1 AS `position`,
+ 1 AS `dayMinute`,
+ 1 AS `eta`,
+ 1 AS `ticketFk`,
+ 1 AS `routeFk`,
+ 1 AS `zonaTicket`,
+ 1 AS `truck`,
+ 1 AS `expeditionState`,
+ 1 AS `hasWorkerWaiting`,
+ 1 AS `isActive`,
+ 1 AS `bufferTruck`,
+ 1 AS `typeName`,
+ 1 AS `routeBuffer` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `bufferType`
+--
+
+DROP TABLE IF EXISTS `bufferType`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `bufferType` (
+ `id` int(11) NOT NULL,
+ `typeName` varchar(100) NOT NULL,
+ `isTarget` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'puede recibir cajas',
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `config`
+--
+
+DROP TABLE IF EXISTS `config`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `config` (
+ `readingPointDelay` int(11) NOT NULL DEFAULT 5 COMMENT 'tiempo de espera de la antena para considerar la lectura como una nueva ',
+ `boxGap` int(11) NOT NULL COMMENT 'separacion teorica entre cajas en el buffer',
+ `freeLength` int(11) NOT NULL DEFAULT 1200 COMMENT 'espacio minimo para declarar el buffer no full',
+ `isRandomMoving` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'el movimiento aleatorio esta activado',
+ `bufferNoLabels` int(11) NOT NULL DEFAULT 22 COMMENT 'buffer destino para cajas sin etiqueta',
+ `bufferTwoLabels` int(11) NOT NULL DEFAULT 24 COMMENT 'buffer destino para cajas con 2 etiquetas o más',
+ `bufferWidthMargin` int(11) NOT NULL DEFAULT 100 COMMENT 'margen mínimo para que una caja pueda entrar en un buffer',
+ `bufferDefault` int(11) NOT NULL DEFAULT 26 COMMENT 'buffer por defecto si no se encuentra otro',
+ `bufferLength` int(11) NOT NULL DEFAULT 13000 COMMENT 'Longitud de los buffers, en mm',
+ `id` int(11) NOT NULL DEFAULT 1,
+ `maxBoxesInBuffer` int(11) NOT NULL DEFAULT 8 COMMENT 'max numero de cajas por buffer para declararlo full',
+ `isEnteringBlocked` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'bloquea la entrada de nuevas cajas al sorter',
+ `isAuto` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'deja el sorter en auto por un buffer',
+ `minBoxesToUnloading` int(11) NOT NULL DEFAULT 9 COMMENT 'num de cajas mínimo para generar una descarga',
+ `minutesBeforeTruckDeparture` int(11) NOT NULL DEFAULT 60 COMMENT 'minutos a descontar de la hora de partida del camion para descargar el sorter',
+ `groupingMode` enum('TRUCK','ROUTE','BUFFER','BUFFERGROUP') NOT NULL DEFAULT 'TRUCK',
+ `expedition_setDimensions` int(11) NOT NULL,
+ `lengthSensorSpacing` int(11) NOT NULL DEFAULT 0 COMMENT 'Separación entre sensores en milimetros - largo',
+ `widthSensorSpacing` int(11) NOT NULL DEFAULT 0 COMMENT 'Separación entre sensores en milimetros - ancho',
+ `enteringSecondsReserve` int(11) NOT NULL DEFAULT 0,
+ `lengthToFirstSensor` int(11) NOT NULL COMMENT 'Distancia a sumar en milímetros hasta primer sensor',
+ `widthToFirstSensor` int(11) NOT NULL COMMENT 'Distancia a sumar en milímetros hasta primer sensor ',
+ `movingMaxLife` int(11) NOT NULL DEFAULT 30 COMMENT 'Tiempo máximo (en minutos) que puede estar un registro en la tabla srt.moving',
+ `motorsMargin` int(11) DEFAULT 3 COMMENT 'margen de motores para considerar FULL el buffer',
+ `isBalanced` tinyint(1) NOT NULL DEFAULT 1,
+ `testMode` tinyint(1) NOT NULL DEFAULT 0,
+ `isAllowedUnloading` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Permite que se pueda cambiar el mode de los buffers a UNLOADING',
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `enteringLog`
+--
+
+DROP TABLE IF EXISTS `enteringLog`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `enteringLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `expeditionFk` int(11) DEFAULT NULL,
+ `expeditionOutFk` int(11) DEFAULT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `expedition`
+--
+
+DROP TABLE IF EXISTS `expedition`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `expedition` (
+ `id` int(11) NOT NULL,
+ `weight` decimal(10,2) DEFAULT NULL COMMENT 'peso en kg',
+ `width` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'ancho en milímetros',
+ `length` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'largo en milímetros',
+ `height` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'alto en milímetros',
+ `bufferFk` int(11) DEFAULT NULL COMMENT 'buffer',
+ `position` int(11) DEFAULT NULL COMMENT 'posicion con respecto al celuveyor',
+ `stateFk` int(11) NOT NULL DEFAULT 0,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `updated` datetime DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `expedition_fk_idx` (`bufferFk`),
+ KEY `expedition_fk2_idx` (`stateFk`),
+ CONSTRAINT `expedition_FK` FOREIGN KEY (`stateFk`) REFERENCES `expeditionState` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `expedition_FK_1` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla se almacenan los datos físicos y la posicion de cada caja en el sorter';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `expeditionLoading`
+--
+
+DROP TABLE IF EXISTS `expeditionLoading`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `expeditionLoading` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `expeditionFk` int(11) NOT NULL,
+ `bufferFk` int(11) NOT NULL DEFAULT 24,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `expeditionLoading_UN` (`expeditionFk`),
+ KEY `expeditionLoading_FK` (`bufferFk`),
+ CONSTRAINT `expeditionLoading_FK` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `expeditionLoading_FK_1` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena las expediciones que van a entrar al sorter por los buffers en modo loading';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `expeditionLog`
+--
+
+DROP TABLE IF EXISTS `expeditionLog`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `expeditionLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `expeditionFk` int(11) DEFAULT NULL,
+ `bufferFk` int(11) NOT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `action` varchar(3) NOT NULL,
+ `antennaFk` int(11) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `expeditionLog_FK_1` (`bufferFk`),
+ KEY `expeditionLog_FK_2` (`antennaFk`),
+ CONSTRAINT `expeditionLog_FK_1` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `expeditionLog_FK_2` FOREIGN KEY (`antennaFk`) REFERENCES `antenna` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `expeditionState`
+--
+
+DROP TABLE IF EXISTS `expeditionState`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `expeditionState` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(45) NOT NULL,
+ `isMovable` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Estados que correponden a cajas paradas en el sorter',
+ `isInside` tinyint(1) NOT NULL DEFAULT 0,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `expeditionVolume`
+--
+
+DROP TABLE IF EXISTS `expeditionVolume`;
+/*!50001 DROP VIEW IF EXISTS `expeditionVolume`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `expeditionVolume` AS SELECT
+ 1 AS `dayMinute`,
+ 1 AS `ETD`,
+ 1 AS `cajas`,
+ 1 AS `isReady`,
+ 1 AS `truck`,
+ 1 AS `zonaTicket`,
+ 1 AS `bufferTruck` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `failureLog`
+--
+
+DROP TABLE IF EXISTS `failureLog`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `failureLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(100) NOT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `lastRFID`
+--
+
+DROP TABLE IF EXISTS `lastRFID`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `lastRFID` (
+ `code` varchar(20) NOT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `antennaFk` int(11) NOT NULL,
+ `isConsulted` tinyint(1) NOT NULL DEFAULT 0,
+ `isChoosed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Es la lectura devuelta',
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `antennaPort` int(11) DEFAULT NULL COMMENT 'puerto al que esta conectada la antena en el switch',
+ `peakRssi` int(11) DEFAULT NULL COMMENT 'intensidad media de lectura',
+ `seenCount` int(11) DEFAULT NULL COMMENT 'número de veces que se ha leido el mismo código',
+ PRIMARY KEY (`id`),
+ KEY `lastRFID_antennaFk_IDX` (`antennaFk`) USING BTREE,
+ CONSTRAINT `lastRFID_FK` FOREIGN KEY (`antennaFk`) REFERENCES `antenna` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='last codes read by the antennas';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `moving`
+--
+
+DROP TABLE IF EXISTS `moving`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `moving` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `expeditionFk` int(11) DEFAULT NULL,
+ `bufferFromFk` int(11) DEFAULT NULL,
+ `bufferToFk` int(11) DEFAULT NULL,
+ `stateFk` int(11) NOT NULL DEFAULT 1,
+ `isColliding` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Define si el movimiento colisiona con los que ya estan en marcha',
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `moving_UN` (`expeditionFk`),
+ KEY `moving_fk1_idx` (`expeditionFk`),
+ KEY `moving_fk2_idx` (`bufferFromFk`),
+ KEY `moving_fk3_idx` (`bufferToFk`),
+ KEY `moving_FK` (`stateFk`),
+ CONSTRAINT `moving_FK` FOREIGN KEY (`stateFk`) REFERENCES `movingState` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `moving_FK_1` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `moving_fk2` FOREIGN KEY (`bufferFromFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `moving_fk3` FOREIGN KEY (`bufferToFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `movingLast`
+--
+
+DROP TABLE IF EXISTS `movingLast`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `movingLast` (
+ `id` int(11) NOT NULL,
+ `expeditionFk` int(11) DEFAULT NULL,
+ `bufferFromFk` int(11) DEFAULT NULL,
+ `bufferToFk` int(11) DEFAULT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `movingLog`
+--
+
+DROP TABLE IF EXISTS `movingLog`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `movingLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `expeditionFk` int(11) DEFAULT NULL,
+ `bufferFromFk` int(11) DEFAULT NULL,
+ `bufferToFk` int(11) DEFAULT NULL,
+ `stateFk` int(11) DEFAULT NULL,
+ `isColliding` tinyint(1) DEFAULT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `movingFk` int(11) NOT NULL,
+ `action` varchar(25) DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `movingState`
+--
+
+DROP TABLE IF EXISTS `movingState`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `movingState` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(20) NOT NULL,
+ `isInterfering` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'afecta al calculo de los posibles movimientos',
+ `isRedirectable` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'admite cambio de destino',
+ `isBeforeCelluveyor` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'define los estados que aún estan en el buffer origen',
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `photocell`
+--
+
+DROP TABLE IF EXISTS `photocell`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `photocell` (
+ `bufferFk` int(11) NOT NULL,
+ `position` int(11) NOT NULL COMMENT 'Posición relativa al celluveyor de dentro a fuera, siendo 1 la más cercana a este',
+ `isActive` tinyint(1) DEFAULT NULL,
+ PRIMARY KEY (`bufferFk`,`position`),
+ CONSTRAINT `photocell_FK` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `routePalletized`
+--
+
+DROP TABLE IF EXISTS `routePalletized`;
+/*!50001 DROP VIEW IF EXISTS `routePalletized`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `routePalletized` AS SELECT
+ 1 AS `routeFk`,
+ 1 AS `expediciones`,
+ 1 AS `paletizadas` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `routeVolume`
+--
+
+DROP TABLE IF EXISTS `routeVolume`;
+/*!50001 DROP VIEW IF EXISTS `routeVolume`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `routeVolume` AS SELECT
+ 1 AS `dayMinute`,
+ 1 AS `ETD`,
+ 1 AS `cajas`,
+ 1 AS `isReady`,
+ 1 AS `routeFk`,
+ 1 AS `zonaTicket`,
+ 1 AS `bufferTruck`,
+ 1 AS `routeBuffer` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `sorterLog`
+--
+
+DROP TABLE IF EXISTS `sorterLog`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `sorterLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `action` varchar(25) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `ticketPalletized`
+--
+
+DROP TABLE IF EXISTS `ticketPalletized`;
+/*!50001 DROP VIEW IF EXISTS `ticketPalletized`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `ticketPalletized` AS SELECT
+ 1 AS `ticketFk`,
+ 1 AS `routeFk`,
+ 1 AS `expediciones`,
+ 1 AS `paletizadas` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `upperStickers`
+--
+
+DROP TABLE IF EXISTS `upperStickers`;
+/*!50001 DROP VIEW IF EXISTS `upperStickers`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `upperStickers` AS SELECT
+ 1 AS `expeditionFk`,
+ 1 AS `expedition`,
+ 1 AS `ETD`,
+ 1 AS `ticketFk`,
+ 1 AS `routeFk`,
+ 1 AS `zonaTicket`,
+ 1 AS `truck`,
+ 1 AS `worker`,
+ 1 AS `labeler`,
+ 1 AS `expeditionCounter`,
+ 1 AS `m3`,
+ 1 AS `clientFk` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Dumping events for database 'srt'
+--
+/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
+/*!50106 DROP EVENT IF EXISTS `moving_clean` */;
+DELIMITER ;;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
+/*!50003 SET character_set_client = utf8mb3 */ ;;
+/*!50003 SET character_set_results = utf8mb3 */ ;;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
+/*!50003 SET @saved_time_zone = @@time_zone */ ;;
+/*!50003 SET time_zone = 'SYSTEM' */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `moving_clean` ON SCHEDULE EVERY 5 MINUTE STARTS '2022-01-21 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Llama a srt.moving_clean para que elimine y notifique de registr' DO BEGIN
+
+ CALL srt.moving_clean();
+
+END */ ;;
+/*!50003 SET time_zone = @saved_time_zone */ ;;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;;
+/*!50003 SET character_set_client = @saved_cs_client */ ;;
+/*!50003 SET character_set_results = @saved_cs_results */ ;;
+/*!50003 SET collation_connection = @saved_col_connection */ ;;
+DELIMITER ;
+/*!50106 SET TIME_ZONE= @save_time_zone */ ;
+
+--
+-- Dumping routines for database 'srt'
+--
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `bid` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `bid`(vCode VARCHAR(3)) RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+
+ /**
+ * Devuelve el identificador de vn.buffer a partir del código
+ *
+ * @param vCode código de vn.buffer
+ * @return Identificador de vn.buffer
+ *
+ */
+
+ DECLARE vNumber INT;
+ DECLARE vLetter VARCHAR(1);
+
+ IF LENGTH(vCode) < 3 THEN
+
+ SET vCode = CONCAT('0',vCode);
+
+ END IF;
+
+ SELECT LEFT(vCode,2), RIGHT(vCode,1) INTO vNumber, vLetter;
+
+ IF vLetter = 'A' THEN
+
+ RETURN vNumber * 2;
+
+ ELSE
+
+ RETURN VNumber * 2 + 1;
+
+ END IF;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `bufferPool_get` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `bufferPool_get`() RETURNS int(11)
+ READS SQL DATA
+BEGIN
+
+ /**
+ * Devuelve el primer bufferFk de la tabla srt.bufferPool
+ *
+ * @return Identificador de vn.buffer
+ *
+ */
+
+ DECLARE vBufferFk INT;
+
+ DECLARE vBufferPoolFk INT;
+
+ SELECT MIN(id) INTO vBufferPoolFk
+ FROM srt.bufferPool;
+
+ IF vBufferPoolFk THEN
+
+ SELECT bufferFk INTO vBufferFk
+ FROM srt.bufferPool
+ WHERE id = vBufferPoolFk;
+
+ DELETE
+ FROM srt.bufferPool
+ WHERE id = vBufferPoolFk;
+
+ ELSE
+
+ RETURN NULL;
+
+ END IF;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `buffer_get` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_get`(vExpeditionFk INT) RETURNS int(11)
+ READS SQL DATA
+BEGIN
+/**
+ * Devuelve el buffer destino para una expedición
+ *
+ * @param vExpeditionFk Identificador de srt.expedition
+ * @return Identificador de srt.buffer
+ */
+ DECLARE vBufferToFk INT;
+ DECLARE vBufferFromFk INT;
+ DECLARE vBufferGroup INT;
+ DECLARE vBufferStrapping INT;
+
+ SELECT IFNULL(rm.bufferFk, c.bufferDefault), IFNULL(e.bufferFk,0)
+ INTO vBufferToFk, vBufferFromFk
+ FROM srt.expedition e
+ LEFT JOIN vn.expedition e2 ON e2.id = e.id
+ LEFT JOIN vn.ticket t ON t.id = e2.ticketFk
+ LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
+ JOIN srt.config c
+ WHERE e.id = vExpeditionFk;
+
+ SELECT `group` INTO vBufferGroup
+ FROM srt.bufferGroup
+ WHERE bufferFk = vBufferToFk;
+
+ SELECT bg.bufferFk
+ INTO vBufferStrapping
+ FROM srt.bufferGroup bg
+ JOIN srt.buffer b ON b.id = bg.bufferFk
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ WHERE bt.typeName = 'STRAPPING'
+ AND bg.`group` = vBufferGroup
+ LIMIT 1;
+
+ IF vBufferGroup THEN
+ SELECT sub.bufferFk INTO vBufferToFk
+ FROM (
+ SELECT b.id bufferFk,
+ count(DISTINCT e.id) expeditions,
+ bs.description,
+ bt.typeName,
+ b.motors
+ FROM srt.buffer b
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ JOIN srt.bufferState bs ON bs.id = b.stateFk
+ JOIN srt.bufferGroup bg ON bg.bufferFk = b.id
+ LEFT JOIN srt.expedition e ON e.bufferFk = b.id
+ LEFT JOIN srt.moving m ON m.bufferFromFk = b.id
+ WHERE bg.`group` = vBufferGroup
+ AND b.id != vBufferFromFk
+ AND bt.isTarget
+ AND m.id IS NULL
+ GROUP BY b.id) sub
+ JOIN srt.config c
+ ORDER BY (sub.description = 'FREE') DESC,
+ (sub.typeName = ('STRAPPING')) DESC,
+ IF(c.isBalanced , sub.expeditions, -sub.expeditions),
+ ABS(sub.bufferFk - vBufferStrapping)
+ LIMIT 1;
+ END IF;
+
+ RETURN vBufferToFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `buffer_getRandom` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_getRandom`() RETURNS int(11)
+ READS SQL DATA
+BEGIN
+
+ /* Devuelve de forma aleatoria, uno de entre los buffers que tienen flejadora
+ *
+ */
+
+ DECLARE vBufferFk INT;
+
+ SELECT b.id INTO vBufferFk
+ FROM srt.buffer b
+ WHERE b.hasStrapper
+ ORDER BY RAND()
+ LIMIT 1;
+
+ RETURN vBufferFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `buffer_getState` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_getState`(vSelf INT) RETURNS varchar(20) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
+ READS SQL DATA
+BEGIN
+
+ /**
+ * Devuelve una cadena con el estado del buffer
+ *
+ */
+
+ DECLARE vState VARCHAR(20);
+
+ SELECT bs.description INTO vState
+ FROM srt.buffer b
+ JOIN srt.bufferState bs ON bs.id = b.stateFk
+ WHERE b.id = vSelf;
+
+ RETURN vState;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `buffer_getType` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_getType`(vSelf INT) RETURNS varchar(20) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
+ READS SQL DATA
+BEGIN
+
+ /**
+ * Devuelve una cadena con el tipo del buffer
+ *
+ */
+
+ DECLARE vType VARCHAR(20);
+
+ SELECT bt.typeName INTO vType
+ FROM srt.buffer b
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ WHERE b.id = vSelf;
+
+ RETURN vType;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `buffer_isFull` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_isFull`(vBufferFk INT) RETURNS tinyint(1)
+ READS SQL DATA
+BEGIN
+
+ /**
+ * Comprueba si un buffer está lleno
+ *
+ * @param vBufferFk Identificador de vn.buffer
+ *
+ */
+
+ DECLARE vBufferStock INT;
+ DECLARE vIsFull BOOL;
+
+ SELECT COUNT(*) INTO vBufferStock
+ FROM srt.expedition e
+ LEFT JOIN srt.moving m ON m.expeditionFk = e.id
+ WHERE e.bufferFk = vBufferFk
+ AND ISNULL(m.id);
+
+ SELECT vBufferStock + COUNT(*) INTO vBufferStock
+ FROM srt.moving m
+ WHERE m.bufferToFk = vBufferFk;
+
+ SELECT (vBufferStock >= maxBoxesInBuffer) INTO vIsFull
+ FROM srt.config;
+
+ RETURN vIsFull;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `dayMinute` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `dayMinute`(vDateTime DATETIME) RETURNS int(11)
+ READS SQL DATA
+BEGIN
+
+ /*
+ * Devuelve el numero de minutos absoluto diario
+ *
+ * @vDateTime Fecha a analizar
+ *
+ */
+
+ RETURN HOUR(vDateTime) * 60 + MINUTE(vDateTime);
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `expedition_check` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_general_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `expedition_check`(vExpeditionFk INT) RETURNS int(11)
+ READS SQL DATA
+BEGIN
+
+ /**
+ * Comprueba si existe una expedición, generando una aleatoria en caso contrario.
+ *
+ * @param vExpeditionFk Identificador de srt.expedition
+ *
+ */
+
+ DECLARE vExpeditionOutFk INT;
+ DECLARE vIsOnTheCelluveyor BOOL;
+
+ SELECT id INTO vExpeditionOutFk
+ FROM srt.expedition
+ WHERE id = vExpeditionFk;
+
+ SELECT COUNT(*) INTO vIsOnTheCelluveyor
+ FROM srt.moving m
+ JOIN srt.movingState ms ON ms.id = m.stateFk
+ WHERE m.expeditionFk = vExpeditionFk
+ AND ms.description != 'NEW';
+
+ IF ISNULL(vExpeditionOutFk) OR vIsOnTheCelluveyor THEN
+
+ SELECT LEAST(-1,MIN(id)- 1) INTO vExpeditionOutFk
+ FROM srt.expedition;
+
+ CASE vExpeditionFk
+
+ WHEN 0 THEN -- Genera una EXP que termine en 0
+
+ SET vExpeditionOutFk = CEIL((vExpeditionOutFk - 10) / 10) * 10;
+
+ WHEN 2 THEN -- Genera una EXP que termine en 2
+
+ SET vExpeditionOutFk = -2 + CEIL((vExpeditionOutFk - 10) / 10) * 10;
+
+ ELSE -- Genera una EXP que termine en 9
+
+ SET vExpeditionOutFk = -9 + CEIL((vExpeditionOutFk - 10) / 10) * 10;
+
+ END CASE;
+
+ INSERT INTO srt.expedition(id,stateFk,width,`length`, height)
+ SELECT vExpeditionOutFk, es.id , p.width * 10, p.`depth` *10, p.height * 10
+ FROM srt.expeditionState es
+ JOIN vn.packaging p ON p.id = '94'
+ WHERE es.description = 'ENTERING';
+
+ END IF;
+
+ RETURN vExpeditionOutFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `expedition_getDayMinute` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `expedition_getDayMinute`(vExpeditionFk INT) RETURNS int(11)
+ READS SQL DATA
+BEGIN
+
+ /**
+ * Devuelve el minuto absoluto ( un dia tiene 24 x 60 minutos ) de salida del camión
+ *
+ * @param vExpeditionFk Identificador de srt.expedition
+ *
+ * @return vDayMinute Minuto absoluto diario
+ */
+
+ DECLARE vDayMinute INT;
+
+ SELECT HOUR(IFNULL(et.ETD, z.`hour`)) * 60 + MINUTE(IFNULL(et.ETD, z.`hour`)) INTO vDayMinute
+ FROM vn.expedition e
+ JOIN vn.ticket t ON e.ticketFk = t.id
+ JOIN vn.`zone` z ON z.id = t.zoneFk
+ LEFT JOIN vn.route r ON r.id = t.routeFk
+ LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
+ LEFT JOIN vn.routesMonitor rm ON t.routeFk = rm.routeFk
+ LEFT JOIN vn.expeditionTruck et ON rm.expeditionTruckFk = et.id
+ WHERE e.id = vExpeditionFk;
+
+ RETURN vDayMinute;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buffer_getExpCount` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_getExpCount`(IN vBufferFk INT, OUT vExpCount INT)
+BEGIN
+/* Devuelve el número de expediciones de un buffer
+ *
+ * @param vBufferFk Identificador de srt.buffer
+ * @param vExpCount Número de expediciones
+ */
+ SELECT COUNT(*)
+ INTO vExpCount
+ FROM srt.expedition
+ WHERE bufferFk = vBufferFk;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buffer_getStateType` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_getStateType`(vBufferFk INT, OUT vStateFk INT, OUT vTypeFk INT)
+BEGIN
+
+ /**
+ * Devuelve el estado y el tipo de un buffer
+ *
+ * @param vBufferFk Identificador de srt.buffer
+ * @return vStateFk Identificador de srt.bufferState
+ * @return vTypeFk Identificador de srt.bufferType
+ *
+ */
+
+ SELECT b.stateFk, b.typeFk INTO vStateFk, vTypeFk
+ FROM srt.buffer b
+ WHERE b.id = vBufferFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buffer_giveBack` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_giveBack`(vSelf INT)
+BEGIN
+
+ /* Devuelve una caja al celluveyor *
+ *
+ * @param vSelf Identificador de srt.buffer
+ */
+
+ DECLARE vExpeditionFk INT;
+
+ SELECT e.id INTO vExpeditionFk
+ FROM srt.expedition e
+ WHERE e.bufferFk = vSelf
+ ORDER BY e.`position`
+ LIMIT 1;
+
+ IF vExpeditionFk THEN
+
+ CALL srt.expedition_relocate(vExpeditionFk, srt.buffer_get(vExpeditionFk));
+
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buffer_readPhotocell` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_readPhotocell`(vSelf INT, vNumber INT)
+BEGIN
+/**
+ * Establece el estado de un buffer en función del número de fotocélulas activas
+ *
+ * @param vSelf Identificador de srt.buffer
+ * @param vNumber Número de fotocélulas activas
+ */
+ DECLARE vIsFull BOOL;
+ DECLARE vBoxes INT;
+ DECLARE vMotors INT;
+ DECLARE vMargin INT;
+
+ SELECT ((COUNT(*) + vNumber + c.motorsMargin) >= b.motors AND b.motors > 1), COUNT(*), b.motors, c.motorsMargin
+ INTO vIsFull, vBoxes, vMotors, vMargin
+ FROM srt.buffer b
+ LEFT JOIN srt.moving m ON m.bufferToFk = b.id
+ JOIN srt.config c
+ WHERE b.id = vSelf;
+
+ IF vIsFull THEN
+ CALL srt.buffer_setStateType(vSelf, 'FULL', NULL);
+ ELSE
+ CALL srt.buffer_setStateType(vSelf, 'FREE', NULL);
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buffer_setEmpty` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setEmpty`(vBufferFk INT)
+BEGIN
+
+ /**
+ * Actualiza a NULL el valor bufferFk de las expediciones que esten en ese buffer
+ *
+ * @param vBufferFk Identificador de srt.buffer
+ *
+ */
+
+ UPDATE srt.expedition e
+ SET e.bufferFk = NULL
+ WHERE e.bufferFk = vBufferFk;
+
+ UPDATE srt.buffer b
+ SET b.typeFk = b.typeDefaultFk
+ WHERE b.id = vBufferFk;
+
+ CALL srt.buffer_setStateType(vBufferFk, 'FREE', NULL);
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buffer_setState` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setState`(vBufferFk INT(11), vStateFk INT(11))
+BEGIN
+
+ /**
+ * Cambia el estado de un buffer
+ *
+ * @param vBufferFk Identificador de srt.buffer
+ * @param vStateFk Identificador de srt.bufferState
+ *
+ */
+
+ UPDATE srt.buffer b
+ SET b.stateFk = vStateFk
+ WHERE b.id = vBufferFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buffer_setStateType` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setStateType`(vBufferFk INT, vState VARCHAR(25), vType VARCHAR(25))
+BEGIN
+
+ /**
+ * Cambia el estado y el tipo de un buffer
+ *
+ * @param vBufferFk Identificador del buffer
+ * @param vState Estado
+ * @param vType Tipo
+ *
+ */
+
+ DECLARE vBufferStateFk INT;
+ DECLARE vBufferTypeFk INT;
+
+ IF NOT ISNULL(vState) THEN
+
+ SELECT bs.id INTO vBufferStateFk
+ FROM srt.bufferState bs
+ WHERE bs.description = vState;
+
+ CALL srt.buffer_setState(vBufferFk, vBufferStateFk);
+
+ END IF;
+
+ IF NOT ISNULL(vType) THEN
+
+ IF vType = 'DEFAULT' THEN
+
+ SELECT b.typeDefaultFk INTO vBufferTypeFk
+ FROM srt.buffer b
+ WHERE b.id = vBufferFk;
+
+ ELSE
+
+ SELECT bt.id INTO vBufferTypeFk
+ FROM srt.bufferType bt
+ WHERE bt.typeName = vType;
+
+ END IF;
+
+ CALL srt.buffer_setType(vBufferFk, vBufferTypeFk);
+
+ IF vType = 'UNLOADING' THEN
+
+ UPDATE srt.buffer
+ SET lastUnloaded = util.VN_NOW()
+ WHERE id = vBufferFk;
+
+ END IF;
+
+ END IF;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buffer_setType` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setType`(vBufferFk INT(11), vTypeFk INT(11))
+BEGIN
+/**
+ * Cambia el tipo de un buffer, si está permitido
+ *
+ * @param vBufferFk Identificador de srt.buffer
+ * @param vTypeFk Identificador de srt.bufferType
+ *
+ */
+ UPDATE srt.buffer b
+ JOIN srt.config c
+ JOIN srt.bufferType bt ON bt.typeName = 'UNLOADING'
+ SET b.typeFk = vTypeFk
+ WHERE b.id = vBufferFk
+ AND (vTypeFk <> bt.id OR c.isAllowedUnloading);
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buffer_setTypeByName` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setTypeByName`(vBufferFk INT(11), vTypeName VARCHAR(100))
+BEGIN
+
+ /**
+ * Cambia el tipo de un buffer
+ *
+ * @param vBufferFk Identificador de srt.buffer
+ * @param vTypeName Nombre Identificador de srt.bufferType
+ *
+ */
+
+ DECLARE vTypeFk INT;
+
+ SELECT bt.id INTO vTypeFk
+ FROM srt.bufferType bt
+ WHERE bt.typeName = vTypeName;
+
+ UPDATE srt.buffer b
+ SET b.typeFk = vTypeFk
+ WHERE b.id = vBufferFk;
+
+ SELECT count(*)
+ FROM srt.buffer b
+ WHERE b.id = vBufferFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `clean` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
+BEGIN
+ DECLARE vLastDated DATE DEFAULT TIMESTAMPADD(WEEK,-2,util.VN_CURDATE());
+
+ DELETE FROM srt.lastRFID
+ WHERE created < vLastDated;
+
+ DELETE FROM srt.expedition
+ WHERE created < vLastDated;
+
+ DELETE FROM srt.moving;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expeditionLoading_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionLoading_add`(vExpeditionFk INT, vBufferFk INT)
+BEGIN
+
+ DECLARE vMessage VARCHAR(50) DEFAULT '';
+
+ IF (SELECT COUNT(*) FROM srt.buffer WHERE id = vBufferFk) = 0 THEN
+
+ SET vMessage = 'Buffer incorrecto';
+
+ END IF;
+
+ IF (SELECT COUNT(*) FROM srt.expedition WHERE id = vExpeditionFk) = 0 THEN
+
+ SET vMessage = 'Expedición no existe';
+
+ END IF;
+
+ IF LENGTH(vMessage) = 0 THEN
+
+ REPLACE srt.expeditionLoading (expeditionFk, bufferFk)
+ VALUES (vExpeditionFk, vBufferFk);
+
+ SET vMessage = 'Registro añadido';
+
+ END IF;
+
+ SELECT vMessage;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_arrived` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_arrived`(vExpeditionFk INT, vBufferFk INT, OUT vTypeFk INT)
+BEGIN
+/**
+ * La expedición ha entrado en un buffer, superando fc2
+ *
+ * @param vExpeditionFk Identificador de srt.expedition
+ * @param vBufferFk Identificador de srt.buffer
+ *
+ * @return vTypeFk Identificador de srt.bufferType
+ *
+ */
+ DECLARE vComingBoxes INT;
+ DECLARE vHasWorkerWaiting BOOL;
+ DECLARE vIsRandomMoving BOOL;
+ DECLARE vState VARCHAR(15);
+ DECLARE vType VARCHAR(15);
+ DECLARE visBufferWhithoutBoxesCount BOOL;
+
+ IF vBufferFk = 1 THEN
+ SET vBufferFk = 0;
+ END IF;
+
+ INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
+ VALUES(vExpeditionFk, vBufferFk, 'ARR');
+
+ SELECT COUNT(*) INTO vComingBoxes
+ FROM srt.moving m
+ WHERE m.bufferToFk = vBufferFk
+ AND m.expeditionFk != vExpeditionFk;
+
+ SELECT b.hasWorkerWaiting,
+ c.isRandomMoving ,
+ (bt.typeName = 'STRAPPING') OR vBufferFk IN (c.bufferNoLabels, c.bufferTwoLabels, c.bufferDefault)
+ INTO vHasWorkerWaiting,
+ vIsRandomMoving,
+ visBufferWhithoutBoxesCount
+ FROM srt.buffer b
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ JOIN srt.config c
+ WHERE b.id = vBufferFk
+ LIMIT 1;
+
+ SET vState = IF(srt.buffer_isFull(vBufferFk), 'FULL', 'FREE');
+
+ SET vType = IF(vHasWorkerWaiting
+ AND NOT vComingBoxes
+ AND NOT vIsRandomMoving
+ AND vState = 'FULL', 'UNLOADING', 'ACCUMULATION');
+
+ IF NOT visBufferWhithoutBoxesCount THEN
+ CALL srt.buffer_setStateType(vBufferFk,vState,vType);
+ END IF;
+
+ UPDATE srt.expedition e
+ JOIN srt.expeditionState es ON es.description = 'STORED'
+ SET e.bufferFk = IF(visBufferWhithoutBoxesCount,0,vBufferFk),
+ e.`position` = 0,
+ e.stateFk = es.id
+ WHERE e.id = vExpeditionFk;
+
+ UPDATE srt.expedition e
+ SET e.`position` = e.`position` + 1
+ WHERE e.bufferFk = vBufferFk
+ AND e.bufferFk > 0;
+
+ INSERT INTO srt.movingLog(expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, movingFk, `action`)
+ SELECT expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, id, 'ARRIVED'
+ FROM srt.moving
+ WHERE expeditionFk = vExpeditionFk
+ ORDER BY id DESC
+ LIMIT 1;
+
+ DELETE FROM srt.moving
+ WHERE expeditionFk = vExpeditionFk;
+
+ SELECT bt.id INTO vTypeFk
+ FROM srt.bufferType bt
+ JOIN srt.buffer b ON b.typeFk = bt.id
+ WHERE b.id = vBufferFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_bufferOut` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_bufferOut`(vBufferToFk INT)
+BEGIN
+
+ /**
+ * Selecciona y enruta las expediciones en el sorter hacia un buffer de salida, que sean de ese buffer
+ *
+ * @param vBufferToFk Identificador de srt.buffer
+ */
+
+ DECLARE vExpListFk INT;
+
+ DECLARE vExpBufFk INT;
+
+ DECLARE vDone INT DEFAULT FALSE;
+
+ DECLARE vExpList CURSOR FOR
+ SELECT bs.expeditionFk
+ FROM srt.bufferStock bs
+ JOIN srt.expedition e ON e.id = bs.expeditionFk
+ LEFT JOIN srt.moving m ON m.expeditionFk = bs.expeditionFk
+ WHERE bs.routeBuffer = vBufferToFk
+ AND ISNULL(m.expeditionFk)
+ AND bs.typeName = 'ACCUMULATION'
+ ORDER BY (vBufferToFk - e.bufferFk),
+ e.`position` ;
+
+ DECLARE vExpBuf CURSOR FOR
+ SELECT e.id
+ FROM srt.expedition e
+ JOIN srt.expedition e2 ON e2.bufferFk = e.bufferFk
+ LEFT JOIN srt.moving m ON m.expeditionFk = e.id
+ WHERE e2.id = vExpListFk
+ AND ISNULL(m.expeditionFk)
+ AND e.`position` <= e2.`position`
+ ORDER BY e.`position`;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vExpList;
+
+ FETCH vExpList INTO vExpListFk;
+
+ WHILE NOT vDone DO
+
+ OPEN vExpBuf;
+
+ FETCH vExpBuf INTO vExpBufFk;
+
+ WHILE NOT vDone DO
+
+ IF vExpBufFk = vExpListFk THEN
+
+ CALL srt.expedition_relocate(vExpListFk, vBufferToFk);
+
+ SET vDone = TRUE;
+
+ ELSE
+
+ CALL srt.expedition_relocate(vExpBufFk, NULL);
+
+ SET vDone = FALSE;
+
+ FETCH vExpBuf INTO vExpBufFk;
+
+ END IF;
+
+ END WHILE;
+
+ CLOSE vExpBuf;
+
+ SET vDone = FALSE;
+
+ FETCH vExpList INTO vExpListFk;
+
+ END WHILE;
+
+ CLOSE vExpList;
+
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_entering` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_entering`(vExpeditionFk INT, OUT vExpeditionOutFk INT )
+BEGIN
+
+ /**
+ * Una expedición llega a la entrada del celuveyor y comunica su ID
+ *
+ * @param vExpeditionFk Identificador de srt.expedition
+ *
+ * @return vExpeditionOutFk Identificador de srt.expedition
+ *
+ */
+
+ DECLARE vBufferFk INT DEFAULT NULL;
+
+ SET vExpeditionOutFk = srt.expedition_check(vExpeditionFk);
+
+ IF vExpeditionOutFk < 0 THEN
+
+ SELECT IF(vExpeditionOutFk MOD 10 = 0, c.bufferNoLabels, c.bufferTwoLabels)
+ INTO vBufferFk
+ FROM srt.config c;
+
+ END IF;
+
+ UPDATE srt.expedition e
+ SET e.bufferFk = 0
+ WHERE id = vExpeditionOutFk;
+
+ UPDATE srt.moving m
+ JOIN srt.movingState ms ON ms.description = 'NEW'
+ SET m.stateFk = ms.id
+ WHERE m.expeditionFk = vExpeditionOutFk;
+
+ IF (SELECT isAuto FROM srt.config) THEN
+
+ SELECT b.id INTO vBufferFk
+ FROM srt.buffer b
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ WHERE b.isActive
+ ORDER BY (bt.typeName = 'STRAPPING') DESC,
+ b.hasWorkerWaiting DESC,
+ srt.buffer_IsFull(b.id),
+ b.stateFk,
+ b.typeFk,
+ b.lastUnloaded,
+ b.id DESC
+ LIMIT 1;
+
+ END IF;
+/*
+ INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
+ VALUES(vExpeditionOutFk, 0, 'ENT');
+
+ INSERT INTO srt.enteringLog(expeditionFk , expeditionOutFk )
+ VALUES(vExpeditionFk, vExpeditionOutFk);
+*/
+ CALL srt.expedition_relocate(vExpeditionOutFk, vBufferFk);
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_get` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_get`(vAntennaFk INT, OUT vExpeditionOutFk INT )
+BEGIN
+
+ DECLARE vId INT;
+ DECLARE vCount INT;
+ DECLARE vCreatedMin DATETIME;
+ DECLARE vCreatedMax DATETIME;
+ DECLARE vSecondsScope INT DEFAULT 30;
+
+ START TRANSACTION;
+
+ SELECT count(DISTINCT lr.code) INTO vCount
+ FROM srt.lastRFID lr
+ WHERE lr.antennaFk = vAntennaFk
+ AND NOT isConsulted;
+
+ CASE vCount
+
+ WHEN 0 THEN
+
+ SET vExpeditionOutFk = srt.expedition_check(vCount);
+
+ WHEN 1 THEN
+
+ SELECT CAST(code AS DECIMAL(10,0)), lr.id
+ INTO vExpeditionOutFk, vId
+ FROM srt.lastRFID lr
+ WHERE lr.antennaFk = vAntennaFk
+ AND NOT isConsulted
+ ORDER BY lr.seenCount DESC, lr.peakRssi
+ LIMIT 1;
+
+ ELSE
+
+ -- Descartamos aquellas lecturas que se han producido unos segundos antes.
+ SELECT MIN(created), MAX(created) INTO vCreatedMin, vCreatedMax
+ FROM srt.lastRFID lr
+ WHERE lr.antennaFk = vAntennaFk
+ AND NOT isConsulted;
+
+ UPDATE srt.lastRFID lr
+ JOIN (SELECT id, code
+ FROM srt.lastRFID
+ WHERE created
+ BETWEEN TIMESTAMPADD(SECOND, - vSecondsScope, vCreatedMin)
+ AND TIMESTAMPADD(SECOND, -1, vCreatedMin)
+ AND isChoosed = 1#
+ ) sub ON sub.code = lr.code AND sub.id != lr.id
+ SET lr.isConsulted = TRUE
+ WHERE lr.created BETWEEN vCreatedMin AND vCreatedMax
+ AND lr.antennaFk = vAntennaFk;
+
+ SELECT CAST(code AS DECIMAL(10,0)), lr.id
+ INTO vExpeditionOutFk, vId
+ FROM srt.lastRFID lr
+ WHERE lr.antennaFk = vAntennaFk
+ AND NOT isConsulted
+ ORDER BY lr.peakRssi DESC, lr.seenCount DESC #
+ LIMIT 1;
+
+ END CASE;
+
+ UPDATE srt.lastRFID
+ SET isChoosed = TRUE
+ WHERE id = vId;
+
+ UPDATE srt.lastRFID
+ SET isConsulted = TRUE
+ WHERE antennaFk = vAntennaFk
+ AND NOT isConsulted;
+
+ COMMIT;
+
+ INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`, antennaFk) VALUES(vExpeditionOutFk, 0, 'DIM', vAntennaFk);
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_groupOut` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_groupOut`(vDayMinute INT, vBufferToFk INT)
+BEGIN
+
+ /**
+ * Selecciona y enruta las expediciones en el sorter hacia un buffer de salida, que sean de la hora pedida
+ *
+ * @param vDayMinute Minuto absoluto del dia
+ * @param vBufferToFk Identificador de srt.buffer
+ *
+ */
+
+ DECLARE vExpListFk INT;
+
+ DECLARE vExpBufFk INT;
+
+ DECLARE vDone INT DEFAULT FALSE;
+
+ DECLARE vExpList CURSOR FOR
+ SELECT bs.expeditionFk
+ FROM srt.bufferStock bs
+ JOIN srt.expedition e ON e.id = bs.expeditionFk
+ WHERE bs.dayMinute = vDayMinute
+ AND bs.expeditionState = 'STORED'
+ AND bs.isActive
+ AND bs.hasWorkerWaiting = FALSE
+ AND bs.typeName = 'ACCUMULATION'
+ ORDER BY (vBufferToFk - e.bufferFk),
+ e.`position`;
+
+ DECLARE vExpBuf CURSOR FOR
+ SELECT e.id
+ FROM srt.expedition e
+ JOIN srt.expedition e2 ON e2.bufferFk = e.bufferFk
+ JOIN srt.expeditionState es ON es.id = e.stateFk
+ WHERE e2.id = vExpListFk
+ AND e.`position` <= e2.`position`
+ AND es.description = 'STORED'
+ ORDER BY e.`position`;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vExpList;
+
+ FETCH vExpList INTO vExpListFk;
+
+ UPDATE srt.moving m
+ JOIN srt.movingState ms ON ms.id = m.stateFk
+ SET m.bufferToFk = vBufferToFk
+ WHERE m.expeditionFk = vExpListFk
+ AND ms.isRedirectable
+ AND m.bufferFromFk != vBufferToFk;
+
+ WHILE NOT vDone DO
+
+ OPEN vExpBuf;
+
+ FETCH vExpBuf INTO vExpBufFk;
+
+ WHILE NOT vDone DO
+
+ IF vExpBufFk = vExpListFk THEN
+
+ CALL srt.expedition_Relocate(vExpListFk, vBufferToFk);
+
+ SET vDone = TRUE;
+
+ ELSE
+
+ CALL srt.expedition_Relocate(vExpBufFk, NULL);
+
+ SET vDone = FALSE;
+
+ FETCH vExpBuf INTO vExpBufFk;
+
+ END IF;
+
+ END WHILE;
+
+ CLOSE vExpBuf;
+
+ SET vDone = FALSE;
+
+ FETCH vExpList INTO vExpListFk;
+
+ END WHILE;
+
+ CLOSE vExpList;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_in` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_in`(vBufferFk INT, OUT vExpeditionFk INT)
+proc:BEGIN
+
+ /**
+ * Ha entrado una caja en un buffer, por la zona de descarga.
+ *
+ * @param vBufferFk Identificador de srt.buffer
+ *
+ * @return vExpeditionFk Identificador de srt.expedition *
+ */
+
+ DECLARE vMaxPosition INT;
+ DECLARE vIsBufferFull BOOL;
+ DECLARE vBufferTypeFk INT;
+ DECLARE vBufferStateFk INT;
+
+ SELECT el.expeditionFk INTO vExpeditionFk
+ FROM srt.expeditionLoading el
+ WHERE el.bufferFk = vBufferFk
+ ORDER BY id
+ LIMIT 1;
+
+ IF vExpeditionFk THEN
+
+ DELETE FROM srt.expeditionLoading
+ WHERE expeditionFk = vExpeditionFk;
+
+ -- SET vExpeditionFk = srt.expedition_check(vExpeditionFk);
+
+ INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
+ VALUES(vExpeditionFk, vBufferFk, 'IN');
+
+ SELECT MAX(e.position) INTO vMaxPosition
+ FROM srt.expedition e
+ WHERE e.bufferFk = vBufferFk;
+
+ UPDATE srt.expedition e
+ JOIN srt.expeditionState es ON es.description = 'STORED'
+ SET e.bufferFk = vBufferFk,
+ e.`position` = IFNULL(vMaxPosition,0) + 1,
+ e.stateFk = es.id
+ WHERE e.id = vExpeditionFk;
+
+ SELECT bfl.freeLength < c.freeLength * 2 INTO vIsBufferFull
+ FROM srt.bufferFreeLength bfl
+ JOIN srt.config c
+ WHERE bfl.bufferFk = vBufferFk;
+
+ IF vIsBufferFull THEN
+
+ CALL srt.buffer_setStateType(vBufferFk, 'FREE','ACCUMULATION');
+
+ END IF;
+
+ END IF;
+
+
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_moving` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_moving`(vBufferFk INT)
+BEGIN
+
+ /**
+ * Una expedición ha entrado en el celuveyor desde un buffer
+ *
+ * @param vBufferFk Identificador de srt.buffer
+ *
+ */
+
+ DECLARE vExpeditionFk INT;
+ DECLARE vPosition INT;
+
+ SELECT min(`position`) INTO vPosition
+ FROM srt.expedition e
+ WHERE e.bufferFk = vBufferFk;
+
+ SELECT e.id INTO vExpeditionFk
+ FROM srt.expedition e
+ WHERE e.`position` = vPosition
+ AND e.bufferFk = vBufferFk
+ LIMIT 1;
+
+ INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
+ VALUES(vExpeditionFk, vBufferFk, 'MOV');
+
+ UPDATE srt.expedition e
+ JOIN srt.expeditionState es on es.description = 'MOVING'
+ JOIN srt.moving m ON m.expeditionFk = e.id
+ SET e.stateFk = es.id,
+ e.bufferFk = m.bufferToFk,
+ e.`position` = 0
+ WHERE e.id = vExpeditionFk;
+
+ SET @posicion := 0;
+
+ UPDATE srt.expedition e
+ SET e.`position` = @posicion := @posicion + 1
+ WHERE e.bufferFk = vBufferFk
+ AND e.id != vExpeditionFk
+ ORDER BY e.`position`;
+
+ CALL srt.buffer_setStateType(vBufferFk, 'FREE', NULL);
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_out` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_out`(vBufferFk INT, OUT vTypeFk INT)
+proc:BEGIN
+/**
+ * Una expedición ha salido de un buffer por el extremo distal
+ * Se ignorará en caso de que el buffer esté en modo ACCUMULATION
+ *
+ * @param vBufferFk Identificador de srt.buffer
+ *
+ * @return vTypeFk Identificador de srt.bufferType
+ */
+
+ DECLARE vMaxPosition INT;
+ DECLARE vIsFree BOOL;
+ DECLARE vExpeditionFk INT;
+ DECLARE vBufferType VARCHAR(15);
+
+ SELECT bt.typeName
+ INTO vBufferType
+ FROM srt.buffer b
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ WHERE b.id = vBufferFk;
+
+ IF vBufferType = 'ACCUMULATION' THEN
+ LEAVE proc;
+ END IF;
+
+ SELECT MAX(e.`position`) INTO vMaxPosition
+ FROM srt.expedition e
+ WHERE e.bufferFk = vBufferFk;
+
+ SELECT e.id INTO vExpeditionFk
+ FROM srt.expedition e
+ WHERE e.`position` = vMaxPosition
+ AND e.bufferFk = vBufferFk
+ LIMIT 1;
+
+ INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
+ VALUES(vExpeditionFk, vBufferFk, 'OUT');
+
+ UPDATE srt.expedition e
+ JOIN srt.expeditionState es ON es.description = 'OUT'
+ SET e.bufferFk = NULL,
+ e.`position` = NULL,
+ e.stateFk = es.id
+ WHERE e.id = vExpeditionFk;
+
+ SELECT (COUNT(*) = 0) INTO vIsFree
+ FROM srt.expedition e
+ JOIN srt.buffer b ON b.id = e.bufferFk
+ WHERE e.bufferFk = vBufferFk
+ AND e.`position` > 0;
+
+ IF vIsFree AND vBufferType NOT IN('LOADING','STRAPPING') THEN
+
+ UPDATE srt.buffer SET reserve = NULL, routeFk = NULL, dayMinute = NULL
+ WHERE id = vBufferFk;
+
+ CALL srt.buffer_setStateType(vBufferFk,'FREE','DEFAULT');
+
+ END IF;
+
+ SELECT b.typeFk INTO vTypeFk
+ FROM srt.buffer b
+ WHERE b.id = vBufferFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_outAll` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_outAll`(vBufferFk INT)
+BEGIN
+
+ /**
+ * Envia todas las expediciones al mismo buffer
+ *
+ * @param vBufferFk Identificador de vn.buffer
+ *
+ */
+
+ INSERT INTO srt.moving (expeditionFk, bufferFromFk, bufferToFk)
+ SELECT e.id, e.bufferFk, vBufferFk
+ FROM srt.expedition e
+ LEFT JOIN srt.moving m ON m.expeditionFk = e.id
+ WHERE e.bufferFk > 0
+ AND e.bufferFk != vBufferFk
+ AND ISNULL(m.expeditionFk);
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_relocate` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_relocate`(vExpeditionFk INT, vBufferToFk INT)
+proc:BEGIN
+
+ /**
+ * Asigna buffer destino nuevo para una expedición
+ *
+ * @param vExpeditionFk Identificacion de srt.expedition
+ *
+ * @param vBufferToFk Identificador de srt.buffer
+ *
+ */
+
+ DECLARE vBufferFromFk INT;
+
+ START TRANSACTION;
+
+ IF (SELECT COUNT(*) FROM srt.moving WHERE expeditionFk = vExpeditionFk) THEN
+
+ LEAVE proc;
+
+ END IF;
+
+ SELECT e.bufferFk INTO vBufferFromFk
+ FROM srt.expedition e
+ WHERE e.id = vExpeditionFk;
+
+ SET vBufferToFk = IFNULL(vBufferToFk, IFNULL(srt.bufferPool_get(), `srt`.`buffer_get`(vExpeditionFk)));
+
+ IF vBufferFromFk = vBufferToFk THEN
+
+ LEAVE proc;
+
+ END IF;
+
+ REPLACE srt.moving (expeditionFk,
+ bufferFromFk,
+ bufferToFk,
+ stateFk)
+ SELECT e.id,
+ e.bufferFk,
+ vBufferToFk,
+ ms.id
+ FROM srt.expedition e
+ JOIN srt.movingState ms ON ms.description = 'NEW'
+ LEFT JOIN srt.moving m ON m.expeditionFk
+ WHERE e.id = vExpeditionFk;
+
+ UPDATE srt.expedition e
+ JOIN srt.expeditionState es on es.description = 'ENTERING'
+ JOIN srt.moving m ON m.expeditionFk = e.id
+ SET e.stateFk = es.id
+ WHERE e.id = vExpeditionFk;
+
+ COMMIT;
+
+ IF srt.buffer_isFull(vBufferToFk) THEN
+
+ CALL srt.buffer_setStateType(vBufferToFk,'FULL', NULL);
+
+ END IF;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_reset` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_reset`()
+BEGIN
+
+ DELETE FROM srt.moving;
+ DELETE FROM srt.expedition;
+
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(3223666, NULL, 280.00, 900.00, 280.00, NULL, NULL, 1, '2021-08-25 11:32:16.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4634827, NULL, 320.01, 1008.00, 330.00, 10, 54, 5, '2021-07-15 10:28:21.0', '2021-08-27 14:16:32.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4634836, NULL, 310.01, 1110.00, 300.00, 2, 3, 5, '2021-07-15 10:31:45.0', '2021-08-27 12:07:46.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4634840, NULL, 300.01, 1000.00, 230.00, 13, 2, 5, '2021-07-15 10:32:13.0', '2021-08-27 13:03:48.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4634871, NULL, 320.01, 1080.00, 330.00, 2, 4, 5, '2021-07-15 10:36:30.0', '2021-08-27 12:07:46.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4634872, NULL, 300.00, 900.00, 250.00, 5, 1, 5, '2021-07-15 10:36:49.0', '2021-08-27 12:29:57.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4637714, NULL, 260.01, 520.00, 210.00, NULL, NULL, 1, '2021-07-16 09:43:46.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4637715, NULL, 260.01, 520.00, 210.00, NULL, NULL, 1, '2021-07-16 09:43:51.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4637716, NULL, 260.01, 520.00, 210.00, 9, 1, 4, '2021-07-16 09:43:55.0', '2021-08-27 12:08:33.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651292, NULL, 250.01, 1010.00, 150.00, NULL, NULL, 1, '2021-07-22 09:00:56.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651293, NULL, 300.01, 980.00, 160.00, 0, 1, 5, '2021-07-22 09:03:44.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651295, NULL, 490.01, 1180.00, 250.00, 0, 1, 5, '2021-07-22 09:07:08.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651298, NULL, 260.01, 1040.00, 240.00, 0, 1, 5, '2021-07-22 09:15:57.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651300, NULL, 490.01, 1180.00, 250.00, 0, 1, 5, '2021-07-22 09:17:06.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651302, NULL, 490.01, 1180.00, 250.00, NULL, NULL, 1, '2021-07-22 09:18:04.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651303, NULL, 370.01, 840.00, 180.00, 0, 1, 5, '2021-07-22 09:19:45.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651304, NULL, 260.01, 1040.00, 260.00, 0, 1, 5, '2021-07-22 09:21:07.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651305, NULL, 260.01, 1040.00, 260.00, 2, 7, 5, '2021-07-22 09:23:26.0', '2021-08-27 12:07:46.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651306, NULL, 260.01, 1040.00, 260.00, NULL, NULL, 6, '2021-07-22 09:23:26.0', '2021-08-27 10:01:00.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651307, NULL, 490.01, 1180.00, 250.00, 26, 30, 5, '2021-07-22 09:24:57.0', '2021-08-27 14:08:37.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651308, NULL, 330.01, 1000.00, 170.00, 0, 1, 5, '2021-07-22 09:27:08.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651309, NULL, 290.01, 940.00, 230.00, NULL, NULL, 1, '2021-07-22 09:29:12.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651310, NULL, 290.01, 940.00, 230.00, 10, 1, 5, '2021-07-22 09:30:55.0', '2021-08-27 14:16:32.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651311, NULL, 290.01, 940.00, 230.00, 0, 1, 5, '2021-07-22 09:30:55.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651313, NULL, 490.01, 1180.00, 250.00, NULL, NULL, 6, '2021-07-22 09:32:43.0', '2021-08-27 10:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651314, NULL, 300.00, 900.00, 150.00, 13, 3, 5, '2021-07-22 09:34:20.0', '2021-08-27 13:03:48.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651317, NULL, 330.01, 960.00, 300.00, 0, 1, 5, '2021-07-22 09:35:38.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651321, NULL, 490.01, 1180.00, 250.00, 0, 1, 5, '2021-07-22 09:38:58.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651326, NULL, 260.01, 1040.00, 240.00, 0, 1, 5, '2021-07-22 09:41:42.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651327, NULL, 330.01, 960.00, 300.00, 0, 1, 5, '2021-07-22 09:42:51.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651329, NULL, 300.00, 900.00, 150.00, NULL, NULL, 6, '2021-07-22 09:43:54.0', '2021-08-27 10:01:00.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651333, NULL, 300.01, 1000.00, 230.00, 16, 1, 5, '2021-07-22 09:45:50.0', '2021-08-27 14:16:34.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651335, NULL, 300.01, 1000.00, 230.00, NULL, NULL, 6, '2021-07-22 09:47:25.0', '2021-08-27 10:01:00.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651337, NULL, 330.01, 960.00, 300.00, NULL, NULL, 6, '2021-07-22 09:48:15.0', '2021-08-27 10:01:00.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651342, NULL, 490.01, 1180.00, 250.00, NULL, NULL, 6, '2021-07-22 09:50:56.0', '2021-08-27 10:11:00.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651343, NULL, 490.01, 1180.00, 260.00, 26, 31, 5, '2021-07-22 09:52:18.0', '2021-08-27 14:08:37.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651356, NULL, 290.01, 940.00, 230.00, NULL, NULL, 6, '2021-07-22 09:54:35.0', '2021-08-27 10:01:00.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4651357, NULL, 300.00, 900.00, 150.00, 0, 1, 5, '2021-07-22 09:54:40.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4682051, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:58:17.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4682052, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-16 08:58:17.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4682262, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:58:17.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4691609, NULL, 280.00, 900.00, 280.00, 17, 1, 5, '2021-08-10 09:43:05.0', '2021-08-27 14:16:27.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4691611, NULL, 280.00, 600.00, 700.00, NULL, NULL, 1, '2021-08-10 09:53:22.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4691612, NULL, 280.00, 500.00, 430.00, 6, 1, 4, '2021-08-10 09:56:31.0', '2021-08-27 14:16:33.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4691617, NULL, 280.00, 600.00, 700.00, NULL, NULL, 6, '2021-08-10 09:59:39.0', '2021-08-27 10:36:36.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4691618, NULL, 330.00, 590.00, 650.00, 18, 1, 5, '2021-08-10 10:02:48.0', '2021-08-27 12:22:15.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4691892, NULL, 280.00, 600.00, 800.00, NULL, NULL, 1, '2021-08-10 11:52:12.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4691895, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-10 11:52:56.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4691974, NULL, 330.00, 590.00, 1200.00, NULL, NULL, 1, '2021-08-10 12:18:20.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4691990, NULL, 330.00, 590.00, 1200.00, NULL, NULL, 1, '2021-08-10 12:23:34.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701752, NULL, 490.00, 1180.00, 260.00, 27, 43, 5, '2021-08-16 07:55:04.0', '2021-08-27 14:08:31.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701753, NULL, 490.00, 1180.00, 260.00, 27, 44, 5, '2021-08-16 08:15:21.0', '2021-08-27 14:08:31.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701754, NULL, 490.00, 1180.00, 260.00, 27, 42, 5, '2021-08-16 08:18:48.0', '2021-08-27 14:08:31.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701755, NULL, 490.00, 1180.00, 260.00, 27, 46, 5, '2021-08-16 08:18:52.0', '2021-08-27 14:08:31.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701756, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:26:38.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701757, NULL, 490.00, 1180.00, 260.00, 31, 1, 4, '2021-08-16 08:29:07.0', '2021-08-27 14:16:11.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701758, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:41:56.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701759, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 6, '2021-08-16 08:45:52.0', '2021-08-27 09:28:11.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701760, NULL, 490.00, 1180.00, 260.00, 27, 45, 5, '2021-08-16 08:45:54.0', '2021-08-27 14:08:31.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701761, NULL, 490.00, 1180.00, 260.00, 28, 44, 5, '2021-08-16 08:45:54.0', '2021-08-27 14:16:27.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701762, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:55:14.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701763, NULL, 490.00, 1180.00, 260.00, 26, 27, 5, '2021-08-16 08:58:17.0', '2021-08-27 14:08:37.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701764, NULL, 490.00, 1180.00, 260.00, 26, 26, 5, '2021-08-16 09:04:36.0', '2021-08-27 14:08:37.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4701765, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 6, '2021-08-16 09:06:22.0', '2021-08-27 12:44:44.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4704297, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-16 16:52:11.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4704312, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-16 16:55:02.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4704345, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-16 17:00:36.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4708347, NULL, 300.00, 900.00, 150.00, NULL, NULL, 1, '2021-08-18 11:38:42.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710866, NULL, 280.00, 600.00, 900.00, 0, 1, 5, '2021-08-19 07:40:52.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710867, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:44:27.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710868, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:45:47.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710869, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:48:06.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710870, NULL, 280.00, 600.00, 900.00, 0, 1, 5, '2021-08-19 07:50:36.0', '2021-08-27 13:08:45.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710871, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:53:33.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710872, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:56:13.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710873, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:58:42.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710874, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 08:00:10.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710875, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 08:02:33.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710876, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 08:05:59.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4710877, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 08:08:27.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4724421, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:33:31.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4724454, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:37:58.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4724463, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:39:45.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4724474, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:42:08.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4724484, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:43:21.0', '2021-08-27 08:41:01.0');
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4730464, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 09:57:17.0', NULL);
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4730467, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 10:04:06.0', NULL);
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4730472, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 10:27:15.0', NULL);
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4730473, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 10:27:27.0', NULL);
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4730474, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 10:30:13.0', NULL);
+ INSERT INTO srt.expedition
+ (id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
+ VALUES(4730476, NULL, 490.00, 1180.00, 260.00, 23, 1, 5, '2021-08-27 10:35:28.0', '2021-08-27 14:16:09.0');
+
+ UPDATE srt.expedition e
+ JOIN srt.expeditionState es ON es.description = 'PRINTED'
+ SET e.stateFk = es.id,
+ e.weight = NULL,
+ e.bufferFk = NULL,
+ e.`position` = NULL;
+
+ UPDATE srt.buffer b
+ JOIN srt.bufferState bs on bs.id = b.stateFk
+ SET stateFk = bs.id
+ WHERE bs.description = 'FREE';
+
+ UPDATE srt.config
+ SET isRandomMoving = FALSE;
+
+ SET @dm := (24 * 60) - 10;
+
+ UPDATE vn.expeditionTruck et
+ SET et.eta = timestampadd(MINUTE ,@dm := 1 + @dm,util.VN_CURDATE())
+ WHERE description LIKE 'PRU%' ;
+
+ DELETE FROM srt.movingLog ;
+
+ DELETE FROM srt.expeditionLog WHERE created < timestampadd(week,-1,util.VN_CURDATE());
+
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_routeOut` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_routeOut`(vRouteFk INT, vBufferToFk INT)
+BEGIN
+
+ /**
+ * Selecciona y enruta las expediciones en el sorter hacia un buffer de salida, que sean de la ruta pedida
+ *
+ * @param vRouteFk Identificador de vn.route
+ * @param vBufferToFk Identificador de srt.buffer
+ *
+ */
+
+ DECLARE vExpListFk INT;
+
+ DECLARE vExpBufFk INT;
+
+ DECLARE vDone INT DEFAULT FALSE;
+
+ DECLARE vExpList CURSOR FOR
+ SELECT bs.expeditionFk
+ FROM srt.bufferStock bs
+ JOIN srt.expedition e ON e.id = bs.expeditionFk
+ WHERE bs.routeFk = vRouteFk
+ AND bs.expeditionState = 'STORED'
+ AND bs.isActive
+ AND bs.hasWorkerWaiting = FALSE
+ ORDER BY (vBufferToFk - e.bufferFk),
+ e.`position` ;
+
+ DECLARE vExpBuf CURSOR FOR
+ SELECT e.id
+ FROM srt.expedition e
+ JOIN srt.expedition e2 ON e2.bufferFk = e.bufferFk
+ JOIN srt.expeditionState es ON es.id = e.stateFk
+ WHERE e2.id = vExpListFk
+ AND e.`position` <= e2.`position`
+ AND es.description = 'STORED'
+ ORDER BY e.`position`;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vExpList;
+
+ FETCH vExpList INTO vExpListFk;
+
+ WHILE NOT vDone DO
+
+ OPEN vExpBuf;
+
+ FETCH vExpBuf INTO vExpBufFk;
+
+ WHILE NOT vDone DO
+
+ IF vExpBufFk = vExpListFk THEN
+
+ CALL srt.expedition_relocate(vExpListFk, vBufferToFk);
+
+ SET vDone = TRUE;
+
+ ELSE
+
+ CALL srt.expedition_relocate(vExpBufFk, NULL);
+
+ SET vDone = FALSE;
+
+ FETCH vExpBuf INTO vExpBufFk;
+
+ END IF;
+
+ END WHILE;
+
+ CLOSE vExpBuf;
+
+ SET vDone = FALSE;
+
+ FETCH vExpList INTO vExpListFk;
+
+ END WHILE;
+
+ CLOSE vExpList;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_scan` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_scan`(vSelf INT)
+BEGIN
+
+ /* Actualiza el estado de una expedicion a OUT, al ser escaneada manualmente
+ *
+ * @param vSelf Identificador de srt.expedition
+ *
+ */
+
+ UPDATE srt.expedition e
+ JOIN srt.expeditionState es ON es.description = 'OUT'
+ SET e.stateFk = es.id,
+ e.`position` = NULL,
+ e.bufferFk = NULL
+ WHERE e.id = vSelf;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_setDimensions` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_setDimensions`(
+ vExpeditionFk INT,
+ vWeight DECIMAL(10,2),
+ vLength INT,
+ vWidth INT,
+ vHeight INT,
+ OUT vExpeditionOutFk INT)
+BEGIN
+/**
+ * Actualiza las dimensiones, peso y estado de una expedición
+ *
+ * @param vExpeditionFk Identificador de expedition
+ * @param vWeight Peso en kilos
+ * @param vLength Byte con el número de fotocélulas activadas a lo largo
+ * @param vWidth Byte con el número de fotocélulas activadas a lo ancho
+ * @param vHeight Altura de la caja en cm
+ * @return vExpeditionOutFk Identificador de expedition
+ */
+
+ DECLARE vWidthSensorsUsed INT;
+ DECLARE vLengthSensorsUsed INT;
+
+ SET vExpeditionOutFk = expedition_check(vExpeditionFk);
+
+ #primer bit a 1 a la izquierda - primer bit a 1 a la derecha
+ SET vWidthSensorsUsed = length(BIN(vWidth)) - LOG2(vWidth & -vWidth);
+ SET vLengthSensorsUsed = length(BIN(vLength)) - LOG2(vLength & -vLength);
+
+ UPDATE expedition e
+ JOIN expeditionState es ON es.`description` = 'WEIGHED'
+ JOIN config c
+ SET weight = IFNULL(vWeight, 0),
+ stateFk = es.id,
+ width = IFNULL(c.widthToFirstSensor + (c.widthSensorSpacing * vWidthSensorsUsed), 0),
+ `length` = IFNULL(c.lengthToFirstSensor + (c.lengthSensorSpacing * vLengthSensorsUsed), 0),
+ height = IFNULL(vHeight * 10, 0)
+ WHERE e.id = vExpeditionOutFk;
+
+ SET vExpeditionOutFk = vExpeditionFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_weighing` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_weighing`(vWeight DECIMAL(10,2), vExpeditionFk INT, OUT vExpeditionOutFk INT )
+BEGIN
+
+ /**
+ * Actualiza el peso de una expedición
+ *
+ * @param vWeight Peso en kilos
+ * @param vExpeditionFk Identificador de srt.expedition
+ *
+ * @return vExpeditionOutFk Identificador de srt.expedition
+ */
+
+ SET vExpeditionOutFk = srt.expedition_check(vExpeditionFk);
+
+ UPDATE srt.expedition e
+ JOIN srt.expeditionState es on es.description = 'WEIGHED'
+ SET weight = vWeight,
+ stateFk = es.id
+ WHERE e.id = vExpeditionOutFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `failureLog_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `failureLog_add`(vDescription VARCHAR(100))
+BEGIN
+
+ /* Añade un registro a srt.failureLog
+ *
+ * @param vDescription descripción del fallo
+ */
+
+ INSERT INTO srt.failureLog(description) VALUES(vDescription);
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `lastRFID_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `lastRFID_add`(vCode VARCHAR(20), vAntennaFk INT, vAntennaPortFk INT, vPeakRssi INT, vSeenCount INT)
+BEGIN
+
+ /* Insert a new record in lastRFID table
+ *
+ * @param vCode Char string read by the antenna
+ * @param vAntennaFk Identifier for srt.antenna table
+ */
+
+ INSERT INTO srt.lastRFID(code, antennaFk, antennaPort, peakRssi, seenCount)
+ VALUES(vCode, vAntennaFk, vAntennaPortFk , vPeakRssi , vSeenCount );
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `lastRFID_add_beta` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `lastRFID_add_beta`(vCode VARCHAR(20), vAntennaFk INT, vAntennaPortFk INT, vPeakRssi INT, vSeenCount INT)
+BEGIN
+
+ /* Insert a new record in lastRFID table
+ *
+ * @param vCode Char string read by the antenna
+ * @param vAntennaFk Identifier for srt.antenna table
+ */
+
+ INSERT INTO srt.lastRFID(code, antennaFk, antennaPort, peakRssi, seenCount)
+ VALUES(vCode, vAntennaFk, vAntennaPortFk , vPeakRssi , vSeenCount );
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `moving_between` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_between`(vBufferA INT, vBufferB INT)
+BEGIN
+
+ DECLARE vExpeditionFk INT;
+
+ SELECT e.id INTO vExpeditionFk
+ FROM srt.expedition e
+ LEFT JOIN srt.moving m ON m.expeditionFk = e.id
+ WHERE e.bufferFk = vBufferA
+ AND ISNULL(m.id)
+ ORDER BY e.`position`
+ LIMIT 1;
+
+ IF ISNULL(vExpeditionFk) THEN
+
+ SET vExpeditionFk = srt.expedition_check(0);
+
+ UPDATE srt.expedition
+ SET bufferFk = vBufferA, `position` = 1
+ WHERE id = vExpeditionFk;
+
+ END IF;
+
+ CALL `srt`.`expedition_Relocate`(vExpeditionFk, IFNULL(vBufferB,srt.buffer_get(vExpeditionFk)));
+
+ SELECT * FROM srt.moving m ORDER BY id;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `moving_clean` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_clean`()
+BEGIN
+/**
+ * Elimina movimientos por inactividad
+ *
+ */
+ DECLARE vExpeditionFk INT;
+ DECLARE vBufferToFk INT;
+ DECLARE vBufferFromFk INT;
+ DECLARE done BOOL DEFAULT FALSE;
+
+ DECLARE cur CURSOR FOR
+ SELECT m.expeditionFk, m.bufferToFk, m.bufferFromFk
+ FROM srt.moving m
+ JOIN srt.config c
+ JOIN (SELECT bufferFk, SUM(isActive) hasBox
+ FROM srt.photocell
+ GROUP BY bufferFk) sub ON sub.bufferFk = m.bufferFromFk
+ WHERE m.created < TIMESTAMPADD(MINUTE, - c.movingMaxLife , util.VN_NOW())
+ AND NOT sub.hasBox;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
+
+ OPEN cur;
+
+ bucle: LOOP
+
+ FETCH cur INTO vExpeditionFk, vBufferToFk, vBufferFromFk;
+
+ IF done THEN
+ LEAVE bucle;
+ END IF;
+
+ DELETE FROM srt.moving
+ WHERE expeditionFk = vExpeditionFk;
+
+ UPDATE srt.expedition e
+ JOIN srt.expeditionState es ON es.description = 'OUT'
+ SET
+ bufferFk = NULL,
+ `position` = NULL,
+ stateFk = es.id
+ WHERE e.id = vExpeditionFk;
+
+ UPDATE srt.expedition e
+ SET e.`position` = e.`position` - 1
+ WHERE e.bufferFk = vBufferFromFk
+ AND e.`position` > 0;
+
+ CALL vn.mail_insert(
+ 'pako@verdnatura.es, carles@verdnatura.es',
+ NULL,
+ CONCAT('Moving_clean. Expedition: ', vExpeditionFk, ' estaba parada'),
+ CONCAT('Expedition: ', vExpeditionFk,' vBufferToFk: ', vBufferToFk)
+ );
+
+ END LOOP bucle;
+
+ CLOSE cur;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `moving_CollidingSet` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_CollidingSet`()
+BEGIN
+
+
+ UPDATE srt.moving
+ SET isColliding = FALSE;
+
+ UPDATE srt.moving m1
+ JOIN srt.buffer sf1 ON sf1.id = m1.bufferFromFk
+ JOIN srt.buffer st1 ON st1.id = m1.bufferToFk
+ JOIN srt.movingState ms1 ON ms1.id = m1.stateFk
+ JOIN srt.moving m2
+ JOIN srt.buffer sf2 ON sf2.id = m2.bufferFromFk
+ JOIN srt.buffer st2 ON st2.id = m2.bufferToFk
+ JOIN srt.movingState ms2 ON ms2.id = m2.stateFk
+ SET m1.isColliding = TRUE
+ WHERE NOT ms1.isInterfering
+ AND ms2.isInterfering
+ AND (sf1.stratus = st2.stratus
+ OR
+ st1.stratus = sf2.stratus )
+ ;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `moving_delete` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_delete`(vExpeditionFk INT)
+BEGIN
+
+ /* Elimina un movimiento
+ *
+ * @param vExpeditionFk Identificador de srt.expedition
+ *
+ */
+
+ INSERT INTO srt.movingLog(expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, movingFk, `action`)
+ SELECT expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, id, 'DELETE'
+ FROM srt.moving
+ WHERE expeditionFk = vExpeditionFk;
+
+ DELETE FROM srt.moving
+ WHERE expeditionFk = vExpeditionFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `moving_groupOut` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_groupOut`()
+proc: BEGIN
+
+ DECLARE vDayMinute INT;
+ DECLARE vRouteFk INT;
+ DECLARE vBufferToFk INT;
+ DECLARE vBufferFromFk INT;
+ DECLARE vBufferGroupFk INT;
+ DECLARE vDone INT DEFAULT FALSE;
+ DECLARE cur1 CURSOR FOR
+ SELECT DISTINCT b.id
+ FROM srt.buffer b
+ JOIN srt.bufferState bs ON bs.id = b.stateFk
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ JOIN srt.bufferGroup bg ON bg.bufferFk = b.id
+ LEFT JOIN srt.moving m ON m.bufferToFk = b.id
+ WHERE bs.description = 'FREE'
+ AND b.isActive
+ AND bt.typeName = 'STRAPPING';
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ IF (SELECT (isAuto OR isRandomMoving) FROM srt.config) THEN
+
+ LEAVE proc;
+
+ END IF;
+
+ CASE (SELECT groupingMode FROM srt.config)
+
+ WHEN 'TRUCK' THEN
+
+ SELECT min(ev.dayMinute) INTO vDayMinute
+ FROM srt.expeditionVolume ev
+ WHERE ev.isReady
+ AND ev.dayMinute
+ AND ev.bufferTruck;
+
+ IF vDayMinute THEN
+
+ SELECT min(ev.bufferTruck) INTO vBufferToFk
+ FROM srt.expeditionVolume ev
+ WHERE ev.dayMinute = vDayMinute;
+
+ UPDATE srt.buffer
+ SET dayMinute = vDayMinute
+ WHERE id = vBufferToFk;
+
+ CALL srt.expedition_groupOut(vDayMinute,vBufferToFk);
+
+ END IF;
+
+ WHEN 'ROUTE' THEN
+
+ SELECT min(rv.dayMinute) INTO vDayMinute
+ FROM srt.routeVolume rv
+ LEFT JOIN srt.buffer b ON b.routeFk = rv.routeFk
+ WHERE rv.isReady
+ AND rv.dayMinute
+ AND rv.bufferTruck
+ AND ISNULL(b.id);
+
+ IF vDayMinute THEN
+
+ SELECT min(ev.bufferTruck) INTO vBufferToFk
+ FROM srt.expeditionVolume ev
+ WHERE ev.dayMinute = vDayMinute;
+
+ SELECT rv.routeFk INTO vRouteFk
+ FROM srt.routeVolume rv
+ WHERE rv.dayMinute = vDayMinute
+ AND rv.isReady
+ ORDER BY dayMinute, cajas DESC
+ LIMIT 1;
+
+ UPDATE srt.buffer
+ SET routeFk = vRouteFk
+ WHERE id = vBufferToFk;
+
+ CALL srt.expedition_routeOut(vRouteFk,vBufferToFk);
+
+ END IF;
+
+ WHEN 'BUFFER' THEN
+
+ SELECT rv.dayMinute, rv.routeBuffer
+ INTO vDayMinute, vBufferToFk
+ FROM srt.routeVolume rv
+ WHERE rv.isReady
+ AND rv.dayMinute
+ AND rv.routeBuffer
+ ORDER BY rv.dayMinute
+ LIMIT 1;
+
+ IF vDayMinute THEN
+
+ CALL srt.expedition_bufferOut(vBufferToFk);
+
+ END IF;
+
+ WHEN 'BUFFERGROUP' THEN
+
+ -- En el caso de que haya cajas en buffers auxiliares y los principales esten libres, reenvia cajas
+
+ OPEN cur1;
+
+ read_loop: LOOP
+
+ FETCH cur1 INTO vBufferToFk;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ SELECT bg.`group` INTO vBufferGroupFk
+ FROM srt.bufferGroup bg
+ WHERE bg.bufferFk = vBufferToFk;
+
+ SELECT MAX(e.bufferFk) INTO vBufferFromFk
+ FROM srt.expedition e
+ JOIN srt.expeditionState es ON es.id = e.stateFk
+ JOIN srt.bufferGroup bg ON bg.bufferFk = e.bufferFk
+ LEFT JOIN srt.moving m ON m.bufferToFk = e.bufferFk
+ LEFT JOIN srt.moving mo ON mo.bufferFromFk = e.bufferFk
+ JOIN srt.buffer b on b.id = e.bufferFk
+ JOIN srt.bufferType bt on bt.id = b.typeFk
+ WHERE bg.`group` = vBufferGroupFk
+ AND ISNULL(m.bufferToFk)
+ AND ISNULL(mo.id)
+ AND bt.typeName = 'ACCUMULATION';
+ IF vBufferFromFk THEN
+
+ CALL srt.buffer_giveBack(vBufferFromFk);
+
+ END IF;
+
+ END LOOP;
+
+ CLOSE cur1;
+
+ END CASE;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `moving_next` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_next`()
+BEGIN
+
+ DECLARE vExpeditionFk INT;
+ DECLARE vMovingFk INT;
+ DECLARE vSecondsFromLastRFIDReading INT;
+
+ CALL srt.randomMoving_Launch();
+
+ CALL srt.moving_GroupOut();
+
+ CALL srt.moving_CollidingSet();
+
+ SELECT TIME_TO_SEC((TIMEDIFF(util.VN_NOW(),MAX(lr.created))))
+ INTO vSecondsFromLastRFIDReading
+ FROM srt.lastRFID lr;
+
+
+ SELECT m.id INTO vMovingFk
+ FROM srt.moving m
+ JOIN srt.expedition e ON e.id = m.expeditionFk
+ JOIN srt.movingState ms ON ms.id = m.stateFk
+ JOIN srt.buffer b ON b.id = m.bufferToFk
+ JOIN srt.buffer b2 ON b2.id = m.bufferFromFk
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ JOIN srt.bufferState bs ON bs.id = b.stateFk
+ JOIN srt.config c
+ WHERE NOT ms.isInterfering
+ AND NOT m.isColliding
+ AND (c.isEnteringBlocked = FALSE OR m.bufferFromFk > 0)
+ AND (e.`position` = 1 OR m.bufferFromFk = 0)
+ AND (vSecondsFromLastRFIDReading > c.enteringSecondsReserve OR m.bufferFromFk = 0)
+ AND (bs.description != 'FULL' OR m.bufferFromFk = 0)
+ ORDER BY (m.bufferFromFk = 0) DESC,
+ m.bufferFromFk DESC
+ LIMIT 1;
+
+ SELECT m.expeditionFk
+ INTO vExpeditionFk
+ FROM moving m
+ WHERE m.id = vMovingFk;
+
+ IF vExpeditionFk THEN
+
+ SELECT m.expeditionFk,
+ m.bufferFromFk,
+ m.bufferToFk
+ FROM moving m
+ WHERE m.id = vMovingFk;
+
+ UPDATE expedition e
+ JOIN expeditionState es ON es.description = 'MOVING'
+ SET e.stateFk = es.id
+ WHERE e.id = vExpeditionFk;
+
+ UPDATE srt.moving m
+ JOIN srt.movingState ms ON ms.description = 'MOVING'
+ SET m.stateFk = ms.id
+ WHERE m.id = vMovingFk;
+
+ INSERT INTO srt.movingLog(expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, movingFk, `action`)
+ SELECT expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, id, 'NEXT'
+ FROM srt.moving
+ WHERE id = vMovingFk;
+
+ ELSE
+
+ SELECT 0 expeditionFk, 0 bufferFromFk, 0 bufferToFk;
+
+ END IF;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `photocell_setActive` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `photocell_setActive`(vBufferFk int, vPosition int, vIsActive bool)
+BEGIN
+ REPLACE srt.photocell VALUES (vbufferFk, vPosition, vIsActive);
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `randomMoving` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `randomMoving`(vBufferMin INT, vBufferMax INT)
+BEGIN
+ DECLARE vBufferOld INT DEFAULT 0;
+ DECLARE vBufferFk INT;
+ DECLARE vExpeditionFk INT;
+
+ SELECT e.id INTO vExpeditionFk
+ FROM srt.expedition e
+ LEFT JOIN srt.moving m ON m.expeditionFk = e.id
+ JOIN srt.buffer b ON b.id = e.bufferFk
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ WHERE e.bufferFk BETWEEN vBufferMin AND vBufferMax
+ AND m.id IS NULL
+ AND bt.typeName = 'ACCUMULATION'
+ AND b.isActive
+ ORDER BY e.`position`, e.updated
+ LIMIT 1;
+
+ SELECT IFNULL(e.bufferFk,0) INTO vBufferOld
+ FROM srt.expedition e
+ WHERE e.id = vExpeditionFk;
+
+ SELECT b.id INTO vBufferFk
+ FROM srt.buffer b
+ JOIN srt.bufferFreeLength bfl ON bfl.bufferFk = b.id
+ JOIN srt.bufferType bt ON bt.id = b.typeFk
+ JOIN srt.config c
+ LEFT JOIN srt.moving m ON m.bufferToFk = b.id
+ LEFT JOIN srt.moving m2 ON m2.bufferFromFk = b.id
+ WHERE ISNULL(m.bufferToFk)
+ AND ISNULL(m2.bufferFromFk)
+ AND b.id BETWEEN vBufferMin AND vBufferMax
+ AND b.id != vBufferOld
+ AND b.isActive
+ AND bt.typeName = 'ACCUMULATION'
+ AND bfl.freeLength > c.freeLength * 2
+ ORDER BY (b.id = floor(MINUTE(util.VN_NOW())/2)) DESC
+ LIMIT 1;
+
+ IF vBufferFk THEN
+
+ INSERT INTO srt.moving (expeditionFk, bufferFromFk, bufferToFk)
+ SELECT e.id, e.bufferFk, vBufferFk
+ FROM srt.expedition e
+ WHERE e.id = vExpeditionFk;
+
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `randomMoving_Launch` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `randomMoving_Launch`()
+BEGIN
+
+ DECLARE i INT DEFAULT 5;
+
+ IF (SELECT count(*) FROM srt.moving) < 5 AND (SELECT isRandomMoving FROM srt.config) THEN
+
+ WHILE i DO
+
+ SET i = i - 1;
+
+ -- CALL srt.randomMoving(22,35);
+ CALL srt.randomMoving(2,5);
+
+ END WHILE;
+
+ END IF;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `restart` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `restart`()
+BEGIN
+
+ /*
+ * Se ha pulsado el botón RESTART en la pantalla tàctil del sorter
+ */
+
+ DELETE FROM srt.moving
+ WHERE bufferFromFk = 0;
+
+ INSERT INTO srt.sorterLog(`action`) VALUES('RESTART');
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `start` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `start`()
+BEGIN
+
+ /*
+ * Se ha pulsado el botón START en la pantalla tàctil del sorter
+ */
+
+ INSERT INTO srt.sorterLog(`action`) VALUES('START');
+
+ UPDATE srt.config SET isEnteringBlocked = FALSE ;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `stop` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `stop`()
+BEGIN
+
+ /*
+ * Se ha pulsado el botón STOP en la pantalla tàctil del sorter
+ */
+
+ INSERT INTO srt.sorterLog(`action`) VALUES('STOP');
+
+ UPDATE srt.config SET isEnteringBlocked = TRUE;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `test` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `test`()
+BEGIN
+
+ SELECT 'procedimiento ejecutado con éxito';
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+
--
-- Current Database: `stock`
--
@@ -18012,67 +23235,6 @@ CREATE TABLE `inbound` (
KEY `isSync` (`isSync`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `stock`.`inbound_beforeInsert`
- BEFORE INSERT ON `inbound`
- FOR EACH ROW
-BEGIN
- SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE();
-
- CALL visible_log(
- NEW.isPicked,
- NEW.warehouseFk,
- NEW.itemFk,
- NEW.quantity
- );
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `stock`.`inbound_afterDelete`
- AFTER DELETE ON `inbound`
- FOR EACH ROW
-BEGIN
- UPDATE outbound o
- JOIN inboundPick ou ON ou.outboundFk = o.id
- SET o.lack = o.lack + ou.quantity,
- o.isSync = FALSE
- WHERE ou.inboundFk = OLD.id;
-
- DELETE FROM inboundPick
- WHERE inboundFk = OLD.id;
-
- CALL visible_log(
- OLD.isPicked,
- OLD.warehouseFk,
- OLD.itemFk,
- -OLD.quantity
- );
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `inboundPick`
@@ -18135,68 +23297,6 @@ CREATE TABLE `outbound` (
KEY `isSync` (`isSync`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `stock`.`outbound_beforeInsert`
- BEFORE INSERT ON `outbound`
- FOR EACH ROW
-BEGIN
- SET NEW.lack = NEW.quantity;
- SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE();
-
- CALL visible_log(
- NEW.isPicked,
- NEW.warehouseFk,
- NEW.itemFk,
- -NEW.quantity
- );
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `stock`.`outbound_afterDelete`
- AFTER DELETE ON `outbound`
- FOR EACH ROW
-BEGIN
- UPDATE inbound i
- JOIN inboundPick ou ON ou.inboundFk = i.id
- SET i.available = i.available + ou.quantity,
- i.isSync = FALSE
- WHERE ou.outboundFk = OLD.id;
-
- DELETE FROM inboundPick
- WHERE outboundFk = OLD.id;
-
- CALL visible_log(
- OLD.isPicked,
- OLD.warehouseFk,
- OLD.itemFk,
- OLD.quantity
- );
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `visible`
@@ -18229,7 +23329,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `log_clean` ON SCHEDULE EVERY 1 DAY STARTS '2022-01-28 09:29:18' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL log_clean */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `log_clean` ON SCHEDULE EVERY 1 DAY STARTS '2022-01-28 09:29:18' ON COMPLETION PRESERVE ENABLE DO CALL log_clean */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -18361,7 +23461,7 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
-
+
SET vSupplied = 0;
OPEN vPicks;
@@ -18377,7 +23477,7 @@ BEGIN
SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity);
SET vSupplied = vSupplied + vPickGranted;
CALL inbound_removePick(vSelf, vOutboundFk, vPickGranted, vPickQuantity);
-
+
UPDATE outbound
SET isSync = FALSE,
lack = lack + vPickGranted
@@ -18457,7 +23557,7 @@ BEGIN
END IF;
SET vSupplied = LEAST(vAvailable, vLack);
-
+
IF vSupplied > 0 THEN
SET vAvailable = vAvailable - vSupplied;
UPDATE outbound
@@ -18470,7 +23570,7 @@ BEGIN
SET vSupplied = vSupplied + vSuppliedFromRequest;
SET vAvailable = vAvailable - vSuppliedFromRequest;
END IF;
-
+
IF vSupplied > 0 THEN
CALL inbound_addPick(vSelf, vOutboundFk, vSupplied);
END IF;
@@ -18599,7 +23699,7 @@ BEGIN
DO RELEASE_LOCK('stock.log_sync');
RESIGNAL;
END;
-
+
IF !GET_LOCK('stock.log_sync', 30) THEN
CALL util.throw('Lock timeout exceeded');
END IF;
@@ -19070,7 +24170,7 @@ BEGIN
SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity);
SET vSupplied = vSupplied + vPickGranted;
CALL inbound_removePick(vInboundFk, vSelf, vPickGranted, vPickQuantity);
-
+
UPDATE inbound
SET isSync = FALSE,
available = available + vPickGranted
@@ -19213,6 +24313,84 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
+--
+-- Current Database: `tmp`
+--
+
+CREATE DATABASE /*!32312 IF NOT EXISTS*/ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
+
+USE `tmp`;
+
+--
+-- Dumping events for database 'tmp'
+--
+/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
+/*!50106 DROP EVENT IF EXISTS `clean` */;
+DELIMITER ;;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
+/*!50003 SET character_set_client = utf8mb3 */ ;;
+/*!50003 SET character_set_results = utf8mb3 */ ;;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
+/*!50003 SET @saved_time_zone = @@time_zone */ ;;
+/*!50003 SET time_zone = 'SYSTEM' */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clean` ON SCHEDULE EVERY 1 HOUR STARTS '2022-03-01 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL tmp.clean */ ;;
+/*!50003 SET time_zone = @saved_time_zone */ ;;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;;
+/*!50003 SET character_set_client = @saved_cs_client */ ;;
+/*!50003 SET character_set_results = @saved_cs_results */ ;;
+/*!50003 SET collation_connection = @saved_col_connection */ ;;
+DELIMITER ;
+/*!50106 SET TIME_ZONE= @save_time_zone */ ;
+
+--
+-- Dumping routines for database 'tmp'
+--
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `clean` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
+BEGIN
+ DECLARE vTableName VARCHAR(255);
+ DECLARE vDone BOOL;
+
+ DECLARE cur CURSOR FOR
+ SELECT TABLE_NAME
+ FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = 'tmp'
+ AND CREATE_TIME < TIMESTAMPADD(DAY, 1, util.VN_NOW());
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN cur;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH cur INTO vTableName;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL util.exec(CONCAT('DROP TABLE `tmp`.`', vTableName, '`'));
+ END LOOP;
+ CLOSE cur;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+
--
-- Current Database: `util`
--
@@ -19253,7 +24431,7 @@ CREATE TABLE `config` (
`mockTime` datetime DEFAULT NULL,
`mockEnabled` tinyint(3) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration table';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration table';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -19270,10 +24448,10 @@ CREATE TABLE `debug` (
`user` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`host` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`variable` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- `value` varchar(255) DEFAULT NULL,
+ `value` text DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `created` (`created`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Log de depuración';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Log de depuración';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -19290,7 +24468,7 @@ CREATE TABLE `eventLog` (
`error` varchar(1024) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Event scheduler error log';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Event scheduler error log';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -19352,7 +24530,7 @@ CREATE TABLE `notificationConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cleanDays` mediumint(9) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -19375,7 +24553,7 @@ CREATE TABLE `notificationQueue` (
KEY `status` (`status`),
CONSTRAINT `nnotificationQueue_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `notification` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `notificationQueue_ibfk_2` FOREIGN KEY (`authorFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -19395,7 +24573,7 @@ CREATE TABLE `notificationSubscription` (
KEY `notificationSubscription_ibfk_1` (`notificationFk`),
CONSTRAINT `notificationSubscription_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `notification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `notificationSubscription_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -19415,6 +24593,20 @@ CREATE TABLE `version` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `versionConfig`
+--
+
+DROP TABLE IF EXISTS `versionConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `versionConfig` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `realm` varchar(16) DEFAULT NULL COMMENT 'Data set on which the project runs',
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `versionLog`
--
@@ -19450,7 +24642,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `slowLog_prune` ON SCHEDULE EVERY 1 DAY STARTS '2021-10-08 00:00:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL util.slowLog_prune */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `slowLog_prune` ON SCHEDULE EVERY 1 DAY STARTS '2021-10-08 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL util.slowLog_prune */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -19464,6 +24656,75 @@ DELIMITER ;
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `accountNumberToIban` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `accountNumberToIban`(vAccount VARCHAR(20)
+) RETURNS varchar(4) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ DETERMINISTIC
+BEGIN
+/**
+* Calcula y genera el código IBAN correspondiente
+* a un número de cuenta bancaria español.
+*
+* @param vAccount Número de cuenta bancaria
+* @return vIban Código IBAN de 4 caracteres.
+*/
+ DECLARE vIban VARCHAR(4);
+
+ SELECT
+ CONCAT('ES',
+ RIGHT(
+ CONCAT(0,
+ 98-MOD(
+ CONCAT(
+ MOD(
+ CONCAT(
+ MOD(
+ CONCAT(
+ MOD(
+ SUBSTRING(vAccount, 1, 8),
+ 97
+ ),
+ SUBSTRING(vAccount,9,8)
+ ),
+ 97
+ ),
+ SUBSTRING(
+ CONCAT(vAccount, 142800),
+ 17,
+ 8
+ )
+ ),
+ 97
+ ),
+ SUBSTRING(
+ CONCAT(vAccount, 142800),
+ 25,
+ 2
+ )
+ ),
+ 97
+ )
+ ),
+ 2
+ )
+ ) INTO vIban;
+
+ RETURN vIban;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `accountShortToStandard` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -19510,11 +24771,11 @@ BEGIN
WHILE vI < vLen
DO
SET vSpaceIni = vI;
-
+
WHILE MID(vString, vI, 1) REGEXP '[[:space:]]' DO
SET vI = vI + 1;
END WHILE;
-
+
SET vWordIni = vI;
SET vI = vWordIni + 1;
@@ -19538,6 +24799,33 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `checkPrintableChars` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `checkPrintableChars`(vString VARCHAR(255)
+) RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+/**
+ * Validates whether the input string contains only printable characters
+ * and Spanish special characters (such as ¡, ÿ, etc.).
+ *
+ * @vString string to check
+ */
+ RETURN vString REGEXP '^[ -~¡-ÿ]*$';
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `crypt` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -19551,11 +24839,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `crypt`(vText VARCHAR(255), vKey VARC
BEGIN
DECLARE vResult VARCHAR(255);
-
+
CALL vn.crypt(vText, vKey, vResult);
RETURN vResult;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -19577,11 +24865,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `cryptOff`(vText VARCHAR(255), vKey V
BEGIN
DECLARE vResult VARCHAR(255);
-
+
CALL vn.cryptOff(vText, vKey, vResult);
RETURN vResult;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -19749,7 +25037,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hasDateOverlapped`(vSarted1 DATE, vEnded1 DATE, vSarted2 DATE, vEnded2 DATE) RETURNS tinyint(1)
DETERMINISTIC
-BEGIN
+BEGIN
RETURN GREATEST(vSarted1, vSarted2) <= LEAST(vEnded1,vEnded2);
@@ -19778,7 +25066,7 @@ BEGIN
*/
DECLARE vHashlen INT UNSIGNED;
DECLARE vOpad, vIpad TINYBLOB;
-
+
CASE vAlg
WHEN 224 THEN SET vHashlen = 64;
WHEN 256 THEN SET vHashlen = 64;
@@ -19786,16 +25074,16 @@ BEGIN
WHEN 512 THEN SET vHashlen = 128;
ELSE CALL throw ('WRONG_ALGORYTHM_IDENTIFICATOR_USED');
END CASE;
-
+
IF LENGTH(vKey) > vHashlen THEN
SET vKey = UNHEX(SHA2(vKey, vAlg));
END IF;
-
+
SET vKey = RPAD(vKey, vHashlen, 0x00);
-
+
SET vIpad = stringXor(vKey, 0x36);
SET vOpad = stringXor(vKey, 0x5C);
-
+
RETURN SHA2(CONCAT(vOpad, UNHEX(SHA2(CONCAT(vIpad, vMsg), vAlg))), vAlg);
END ;;
DELIMITER ;
@@ -19818,7 +25106,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `isLeapYear`(vYear INT) RETURNS tinyi
BEGIN
RETURN (DAYOFYEAR(CONCAT(vYear, "-02-29")) IS NOT NULL);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -19977,7 +25265,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `midnight`() RETURNS datetime
READS SQL DATA
BEGIN
-
+
RETURN TIMESTAMP(util.VN_CURDATE(), '23:59:59');
END ;;
@@ -20105,7 +25393,7 @@ BEGIN
* modo 3.
*/
DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100);
-
+
IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN
RETURN vYearWeek + 1;
ELSE
@@ -20211,16 +25499,16 @@ BEGIN
*/
DECLARE vLen, vPos INT UNSIGNED;
DECLARE vResult MEDIUMBLOB;
-
+
SET vLen = LENGTH(vString);
SET vPos = 1;
SET vResult = '';
-
+
WHILE vPos <= vLen DO
SET vResult = CONCAT(vResult, LPAD(HEX( ORD(SUBSTR(vString, vPos, 1)) ^ vConst), 2, '0'));
SET vPos = vPos + 1;
END WHILE;
-
+
RETURN UNHEX(vResult);
END ;;
DELIMITER ;
@@ -20491,11 +25779,11 @@ BEGIN
IF vYear = vCurYear THEN
RETURN 'curYear';
END IF;
-
+
IF vYear = vCurYear - 1 THEN
RETURN 'lastYear';
END IF;
-
+
IF vYear = vCurYear - 2 THEN
RETURN 'twoYearsAgo';
END IF;
@@ -20578,7 +25866,7 @@ BEGIN
* @param vValue Valor de la variable
*/
DECLARE vIndex INT DEFAULT INSTR(USER(), '@');
-
+
INSERT INTO debug SET
`connectionId` = CONNECTION_ID(),
`user` = LEFT(USER(), vIndex - 1),
@@ -20962,7 +26250,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `time_createTable` */;
+/*!50003 DROP PROCEDURE IF EXISTS `time_generate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@@ -20970,18 +26258,119 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `time_createTable`(vStarted DATE, vEnded DATE)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `time_generate`(vStarted DATE, vEnded DATE)
BEGIN
+/**
+ * Generate a temporary table between the days passed as parameters
+ *
+ * @param vStarted Start date
+ * @param vEnded End date
+ * @table tmp.time (dated, dayed, weeked, monthed, yeared)
+ */
DECLARE vCurrentDate DATE;
- DROP TEMPORARY TABLE IF EXISTS tmp.time;
- CREATE TEMPORARY TABLE tmp.time (dated DATE PRIMARY KEY) ENGINE = MEMORY;
- SET vCurrentDate = vStarted;
- WHILE vCurrentDate <= vEnded DO
- INSERT INTO tmp.time (dated) VALUES (vCurrentDate);
- SET vCurrentDate = DATE_ADD(vCurrentDate, INTERVAL 1 DAY);
- END WHILE;
+ CREATE OR REPLACE TEMPORARY TABLE tmp.time(
+ dated DATE PRIMARY KEY,
+ `day` INT,
+ `week` INT,
+ `month` INT,
+ `year` INT
+ ) ENGINE = MEMORY;
+ IF(vStarted > vEnded) THEN
+ CALL throw('The started cannot be later than the ended');
+ END IF;
+
+ SET vCurrentDate = vStarted;
+
+ WHILE vCurrentDate <= vEnded DO
+ INSERT INTO tmp.time
+ SET dated = vCurrentDate,
+ `day` = DAY(vCurrentDate),
+ `week` = WEEK(vCurrentDate),
+ `month` = MONTH(vCurrentDate),
+ `year` = YEAR(vCurrentDate);
+
+ SET vCurrentDate = vCurrentDate + INTERVAL 1 DAY;
+ END WHILE;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `tx_commit` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_commit`(isTx BOOL)
+BEGIN
+/**
+ * Confirma los cambios asociados a una transacción.
+ *
+ * @param isTx es true si existe transacción asociada
+*/
+ IF isTx THEN
+ COMMIT;
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `tx_rollback` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_rollback`(isTx BOOL)
+BEGIN
+/**
+ * Deshace los cambios asociados a una transacción.
+ *
+ * @param isTx es true si existe transacción asociada
+*/
+ IF isTx THEN
+ ROLLBACK;
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `tx_start` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_start`(isTx BOOL)
+BEGIN
+/**
+ * Inicia una transacción.
+ *
+ * @param isTx es true si existe transacción asociada
+*/
+ IF isTx THEN
+ START TRANSACTION;
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -21098,108 +26487,8 @@ CREATE TABLE `XDiario` (
KEY `XDiario` (`enlazado`),
KEY `enlazadoSage` (`enlazadoSage`),
CONSTRAINT `XDiarioCompany_Fk` FOREIGN KEY (`empresa_id`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`XDiario_beforeInsert`
- BEFORE INSERT ON `XDiario`
- FOR EACH ROW
-BEGIN
- IF NEW.SUBCTA <=> '' THEN
- SET NEW.SUBCTA = NULL;
- END IF;
- IF NEW.SUBCTA IS NOT NULL AND NOT LENGTH(NEW.SUBCTA) <=> 10 THEN
- CALL util.throw('INVALID_STRING_LENGTH');
- END IF;
- IF NEW.CONTRA <=> '' THEN
- SET NEW.CONTRA = NULL;
- END IF;
- IF NEW.CONTRA IS NOT NULL AND NOT LENGTH(NEW.CONTRA) <=> 10 THEN
- CALL util.throw('INVALID_STRING_LENGTH');
- END IF;
- CALL XDiario_checkDate(NEW.FECHA);
- CALL XDiario_checkDate(NEW.FECHA_EX);
- CALL XDiario_checkDate(NEW.FECHA_OP);
- CALL XDiario_checkDate(NEW.FECHA_RT);
- CALL XDiario_checkDate(NEW.FECREGCON);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`XDiario_beforeUpdate`
- BEFORE UPDATE ON `XDiario`
- FOR EACH ROW
-BEGIN
- IF NOT NEW.SUBCTA <=> OLD.SUBCTA THEN
- IF NEW.SUBCTA <=> '' THEN
- SET NEW.SUBCTA = NULL;
- END IF;
- IF NEW.SUBCTA IS NOT NULL AND NOT LENGTH(NEW.SUBCTA) <=> 10 THEN
- CALL util.throw('INVALID_STRING_LENGTH');
- END IF;
- END IF;
- IF NOT NEW.CONTRA <=> OLD.CONTRA THEN
- IF NEW.CONTRA <=> '' THEN
- SET NEW.CONTRA = NULL;
- END IF;
- IF NEW.CONTRA IS NOT NULL AND NOT LENGTH(NEW.CONTRA) <=> 10 THEN
- CALL util.throw('INVALID_STRING_LENGTH');
- END IF;
- END IF;
- IF NOT NEW.FECHA <=> OLD.FECHA THEN
- CALL XDiario_checkDate(NEW.FECHA);
- END IF;
- IF NOT NEW.FECHA_EX <=> OLD.FECHA_EX THEN
- CALL XDiario_checkDate(NEW.FECHA_EX);
- END IF;
- IF NOT NEW.FECHA_OP <=> OLD.FECHA_OP THEN
- CALL XDiario_checkDate(NEW.FECHA_OP);
- END IF;
- IF NOT NEW.FECHA_RT <=> OLD.FECHA_RT THEN
- CALL XDiario_checkDate(NEW.FECHA_RT);
- END IF;
- IF NOT NEW.FECREGCON <=> OLD.FECREGCON THEN
- CALL XDiario_checkDate(NEW.FECREGCON);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-
---
--- Temporary table structure for view `__coolerPathDetail`
---
-
-DROP TABLE IF EXISTS `__coolerPathDetail`;
-/*!50001 DROP VIEW IF EXISTS `__coolerPathDetail`*/;
-SET @saved_cs_client = @@character_set_client;
-SET character_set_client = utf8;
-/*!50001 CREATE VIEW `__coolerPathDetail` AS SELECT
- 1 AS `id`,
- 1 AS `coolerPathFk`,
- 1 AS `hallway` */;
-SET character_set_client = @saved_cs_client;
--
-- Table structure for table `absenceType`
@@ -21222,7 +26511,66 @@ CREATE TABLE `absenceType` (
`isNaturalDay` tinyint(1) DEFAULT 0 COMMENT 'Para el cálculo de los salarios de los repartidores',
`isCalculate` tinyint(1) DEFAULT 0 COMMENT 'Para el cálculo de los salarios de los repartidores',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `accountDetail`
+--
+
+DROP TABLE IF EXISTS `accountDetail`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `accountDetail` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `value` varchar(50) NOT NULL,
+ `accountDetailTypeFk` int(11) NOT NULL,
+ `supplierAccountFk` mediumint(8) unsigned NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `fk_account_detail_account_detail_type1_idx` (`accountDetailTypeFk`),
+ KEY `fk_account_detail_Proveedores_account1_idx` (`supplierAccountFk`),
+ CONSTRAINT `fk_account_detail_account_detail_type1` FOREIGN KEY (`accountDetailTypeFk`) REFERENCES `accountDetailType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `fk_account_detail_account_id_proveedores_account` FOREIGN KEY (`supplierAccountFk`) REFERENCES `supplierAccount` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `accountDetailType`
+--
+
+DROP TABLE IF EXISTS `accountDetailType`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `accountDetailType` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(255) DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `accountReconciliation`
+--
+
+DROP TABLE IF EXISTS `accountReconciliation`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `accountReconciliation` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `supplierAccountFk` mediumint(8) unsigned NOT NULL,
+ `operationDated` datetime NOT NULL,
+ `valueDated` datetime NOT NULL,
+ `amount` double NOT NULL,
+ `concept` varchar(255) DEFAULT NULL,
+ `debitCredit` smallint(6) NOT NULL,
+ `calculatedCode` varchar(255) DEFAULT NULL,
+ `created` timestamp NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `idaccount_conciliacion_UNIQUE` (`id`),
+ KEY `fg_accconciliacion_key1_idx` (`supplierAccountFk`),
+ KEY `index_id_calculated` (`calculatedCode`),
+ CONSTRAINT `fg_key1_accountconc` FOREIGN KEY (`supplierAccountFk`) REFERENCES `supplierAccount` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -21264,7 +26612,7 @@ CREATE TABLE `accountingConfig` (
`minDate` date NOT NULL,
`maxDate` date NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -21324,8 +26672,8 @@ CREATE TABLE `address` (
`isDefaultAddress` tinyint(1) NOT NULL DEFAULT 0,
`agencyModeFk` int(11) NOT NULL DEFAULT 2,
`isActive` tinyint(4) NOT NULL DEFAULT 1,
- `longitude` decimal(11,7) DEFAULT NULL,
- `latitude` decimal(11,7) DEFAULT NULL,
+ `longitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última longitud proporcionada por tabla delivery',
+ `latitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última latitud proporcionada por tabla delivery',
`isEqualizated` tinyint(1) DEFAULT NULL,
`customsAgentFk` int(11) DEFAULT NULL,
`incotermsFk` varchar(3) DEFAULT NULL,
@@ -21347,146 +26695,8 @@ CREATE TABLE `address` (
CONSTRAINT `address_ibfk_3` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE,
CONSTRAINT `address_ibfk_4` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `address_incotermsFk` FOREIGN KEY (`incotermsFk`) REFERENCES `incoterms` (`code`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`address_beforeInsert`
- BEFORE INSERT ON `address`
- FOR EACH ROW
-BEGIN
- DECLARE vIsEqualizated BOOL;
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF (NEW.phone <> '') THEN
- CALL pbx.phone_isValid(NEW.phone);
- END IF;
-
- IF (NEW.mobile <> '') THEN
- CALL pbx.phone_isValid(NEW.mobile);
- END IF;
-
- IF NEW.isEqualizated IS NULL THEN
- SELECT isEqualizated
- INTO vIsEqualizated
- FROM client
- WHERE id = NEW.clientFk;
-
- SET NEW.isEqualizated = vIsEqualizated;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`address_beforeUpdate`
- BEFORE UPDATE ON `address`
- FOR EACH ROW
-BEGIN
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN
- CALL pbx.phone_isValid(NEW.phone);
- END IF;
-
- IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN
- CALL pbx.phone_isValid(NEW.mobile);
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`address_afterUpdate`
- AFTER UPDATE ON `address`
- FOR EACH ROW
-BEGIN
- -- Recargos de equivalencia distintos implican facturacion por consignatario
- IF NEW.isEqualizated != OLD.isEqualizated THEN
- IF
- (SELECT COUNT(*) FROM
- (
- SELECT DISTINCT (isEqualizated = FALSE) as Equ
- FROM address
- WHERE clientFk = NEW.clientFk
- ) t1
- ) > 1
- THEN
- UPDATE client
- SET hasToInvoiceByAddress = TRUE
- WHERE id = NEW.clientFk;
- END IF;
- END IF;
- IF NEW.isDefaultAddress AND NEW.isActive = FALSE THEN
- CALL util.throw ('Cannot desactivate the default address');
- END IF;
-
- IF NOT (NEW.isEqualizated <=> OLD.isEqualizated) THEN
- INSERT IGNORE INTO ticketRecalc (ticketFk)
- SELECT id FROM ticket t
- WHERE t.addressFk = NEW.id
- AND t.refFk IS NULL;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`address_afterDelete`
- AFTER DELETE ON `address`
- FOR EACH ROW
-BEGIN
- INSERT INTO clientLog
- SET `action` = 'delete',
- `changedModel` = 'Address',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `addressFilter`
@@ -21513,7 +26723,7 @@ CREATE TABLE `addressFilter` (
CONSTRAINT `addressFilter_FK` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `addressFilter_FK_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `addressFilter_FK_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Establece los criterios para habilitar las compras directas a Logiflora';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Establece los criterios para habilitar las compras directas a Logiflora';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -21548,7 +26758,21 @@ CREATE TABLE `addressObservation` (
KEY `addressObservationFgn_idx` (`observationTypeFk`),
CONSTRAINT `addressFgn` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `addressObservationFgn` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Observaciones de los consignatarios';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Observaciones de los consignatarios';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `addressShortage`
+--
+
+DROP TABLE IF EXISTS `addressShortage`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `addressShortage` (
+ `addressFk` int(11) NOT NULL,
+ PRIMARY KEY (`addressFk`),
+ CONSTRAINT `addressShortage_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -21562,39 +26786,19 @@ CREATE TABLE `agency` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL,
`warehouseFk` smallint(5) unsigned DEFAULT NULL COMMENT 'A nulo si se puede enrutar desde todos los almacenes',
- `warehouseAliasFk` smallint(5) unsigned DEFAULT NULL,
+ `warehouseAliasFk__` smallint(5) unsigned DEFAULT NULL COMMENT '@deprecated 2024-01-23 refs #5167',
`isOwn` tinyint(1) NOT NULL DEFAULT 0,
`workCenterFk` int(11) DEFAULT NULL,
`isAnyVolumeAllowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Permite vender productos que tengan vn.itemType.IsUnconventionalSize = TRUE',
PRIMARY KEY (`id`),
KEY `warehouse_id` (`warehouseFk`),
- KEY `agencias_alias_idx` (`warehouseAliasFk`),
+ KEY `agencias_alias_idx` (`warehouseAliasFk__`),
KEY `agency_ibfk_3_idx` (`workCenterFk`),
- CONSTRAINT `agency_FK` FOREIGN KEY (`warehouseAliasFk`) REFERENCES `warehouseAlias` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `agency_FK` FOREIGN KEY (`warehouseAliasFk__`) REFERENCES `warehouseAlias__` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agency_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agency_ibfk_3` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`agency_afterInsert`
- AFTER INSERT ON `agency`
- FOR EACH ROW
-BEGIN
- INSERT INTO agencyMode(name,agencyFk) VALUES(NEW.name,NEW.id);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `agencyExtraCharge`
@@ -21648,7 +26852,7 @@ CREATE TABLE `agencyMode` (
KEY `agencyMode_code` (`code`),
CONSTRAINT `agencyMode_agencyFk` FOREIGN KEY (`agencyFk`) REFERENCES `agency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agencyMode_deliveryMethodFk` FOREIGN KEY (`deliveryMethodFk`) REFERENCES `deliveryMethod` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -21667,7 +26871,22 @@ CREATE TABLE `agencyModeItemType` (
KEY `agencyModeItemType_FK_1` (`itemTypeFk`),
CONSTRAINT `agencyModeItemType_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agencyModeItemType_FK_1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Combinaciones prohibidas entre agencyMode e itemType al calcular el catálogo de items';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Combinaciones prohibidas entre agencyMode e itemType al calcular el catálogo de items';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `agencyModePricePercentage`
+--
+
+DROP TABLE IF EXISTS `agencyModePricePercentage`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `agencyModePricePercentage` (
+ `agencyModeFk` int(11) NOT NULL,
+ `percentage` double NOT NULL,
+ PRIMARY KEY (`agencyModeFk`),
+ CONSTRAINT `agencyModePricePercentage_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -21697,13 +26916,43 @@ DROP TABLE IF EXISTS `agencyTermConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencyTermConfig` (
- `expenceFk` varchar(10) DEFAULT NULL,
+ `expenseFk` varchar(10) DEFAULT NULL,
`vatAccountSupported` varchar(15) DEFAULT NULL,
`vatPercentage` decimal(28,10) DEFAULT NULL,
- `transaction` varchar(50) DEFAULT NULL
+ `transaction` varchar(50) DEFAULT NULL,
+ KEY `agencyTermConfig_expense_FK` (`expenseFk`),
+ CONSTRAINT `agencyTermConfig_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `airline`
+--
+
+DROP TABLE IF EXISTS `airline`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `airline` (
+ `id` smallint(2) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(20) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `airport`
+--
+
+DROP TABLE IF EXISTS `airport`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `airport` (
+ `id` smallint(2) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(30) DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `alertLevel`
--
@@ -21764,7 +27013,7 @@ CREATE TABLE `arcRead` (
UNIQUE KEY `arcRead_ip_UN` (`ip`),
KEY `worker_printer_FK` (`printerFk`),
CONSTRAINT `worker_printer_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -21781,7 +27030,7 @@ CREATE TABLE `assignedTicketToWorker` (
PRIMARY KEY (`id`),
UNIQUE KEY `idWorker_UNIQUE` (`idWorker`),
UNIQUE KEY `idTicket_UNIQUE` (`idTicket`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla para relacionar un ticket con el sacador del altillo ';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla para relacionar un ticket con el sacador del altillo ';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -21834,7 +27083,7 @@ CREATE TABLE `autoRadioLogCall` (
PRIMARY KEY (`id`),
KEY `ticket_idx` (`ticketFk`),
CONSTRAINT `ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -21856,78 +27105,8 @@ CREATE TABLE `autonomy` (
KEY `autonomy_FK_1` (`geoFk`),
CONSTRAINT `autonomy_FK` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `autonomy_FK_1` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Comunidades autónomas o su equivalente en otros paises. Agrupación de provincias, en una categoria inferior a country.';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Comunidades autónomas o su equivalente en otros paises. Agrupación de provincias, en una categoria inferior a country.';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`autonomy_BI`
- BEFORE INSERT ON `autonomy`
- FOR EACH ROW
-BEGIN
-
- SET NEW.geoFk = zoneGeo_new('autonomy', NEW.`name`, (SELECT geoFk FROM country WHERE id = NEW.countryFk));
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`autonomy_BU`
- BEFORE UPDATE ON `autonomy`
- FOR EACH ROW
-BEGIN
- IF !(OLD.countryFk <=> NEW.countryFk) THEN
- CALL zoneGeo_setParent(NEW.geoFk,
- (SELECT geoFk FROM country WHERE id = NEW.countryFk));
- END IF;
-
- IF !(OLD.`name` <=> NEW.`name`) THEN
- UPDATE zoneGeo SET `name` = NEW.`name`
- WHERE id = NEW.geoFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`autonomy_AD`
- AFTER DELETE ON `autonomy`
- FOR EACH ROW
-BEGIN
- CALL zoneGeo_delete(OLD.geoFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `awb`
@@ -21977,35 +27156,160 @@ CREATE TABLE `awb` (
KEY `awb_FK_3` (`invoiceInPaletizedFk`),
CONSTRAINT `awbInvoiceIn` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `awb_FK` FOREIGN KEY (`docFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `awb_FK_1` FOREIGN KEY (`flightFk`) REFERENCES `vn2008`.`flight` (`flight_id`) ON UPDATE CASCADE,
+ CONSTRAINT `awb_FK_1` FOREIGN KEY (`flightFk`) REFERENCES `flight` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_FK_3` FOREIGN KEY (`invoiceInPaletizedFk`) REFERENCES `invoiceIn` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_ibfk_1` FOREIGN KEY (`taxFk`) REFERENCES `taxCode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_supplierFk` FOREIGN KEY (`transitoryFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`awb_bi`
- BEFORE INSERT ON `awb`
- FOR EACH ROW
-BEGIN
- SET NEW.year= year(util.VN_CURDATE());
+--
+-- Table structure for table `awbComponent`
+--
+DROP TABLE IF EXISTS `awbComponent`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `awbComponent` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `awbFk` smallint(11) unsigned DEFAULT NULL,
+ `supplierFk` int(11) NOT NULL,
+ `dated__` date NOT NULL,
+ `typeFk` mediumint(3) unsigned DEFAULT NULL,
+ `awbRoleFk` tinyint(1) unsigned NOT NULL DEFAULT 1,
+ `awbUnitFk` varchar(10) DEFAULT NULL,
+ `value` decimal(10,2) DEFAULT NULL,
+ `currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 2,
+ `invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `unique_idx` (`awbFk`,`supplierFk`,`typeFk`),
+ KEY `Id_Moneda` (`currencyFk`),
+ KEY `awb_component_fk` (`typeFk`),
+ KEY `awb_role_fk` (`awbRoleFk`),
+ KEY `awb_unit_fk` (`awbUnitFk`),
+ CONSTRAINT `Id_Monedafk` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON DELETE CASCADE,
+ CONSTRAINT `awb_component_` FOREIGN KEY (`typeFk`) REFERENCES `awbComponentType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `awb_role_fk` FOREIGN KEY (`awbRoleFk`) REFERENCES `awbRole` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `awb_unit_fk` FOREIGN KEY (`awbUnitFk`) REFERENCES `awbUnit` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
+--
+-- Table structure for table `awbComponentTemplate`
+--
+
+DROP TABLE IF EXISTS `awbComponentTemplate`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `awbComponentTemplate` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `freightFk` int(11) DEFAULT NULL,
+ `airportIn` varchar(3) DEFAULT NULL,
+ `airportOut` varchar(3) DEFAULT NULL,
+ `airlineFk` smallint(2) unsigned DEFAULT NULL,
+ `typeFk` mediumint(3) unsigned NOT NULL,
+ `dated` date NOT NULL,
+ `awbRoleFk` tinyint(1) unsigned NOT NULL,
+ `awbUnit` varchar(10) DEFAULT NULL,
+ `value` decimal(10,3) DEFAULT NULL,
+ `maxValue` decimal(10,2) unsigned DEFAULT NULL,
+ `minValue` decimal(10,2) unsigned DEFAULT NULL,
+ `currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 2,
+ `days` varchar(7) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `carguera_id_UNIQUE` (`freightFk`,`airportIn`,`airportOut`,`airlineFk`,`typeFk`,`dated`,`days`),
+ KEY `Id_Moneda` (`currencyFk`),
+ KEY `airline_idx` (`airlineFk`),
+ KEY `role_idx` (`awbRoleFk`),
+ KEY `awb_unit_fk1` (`awbUnit`),
+ KEY `awb_component_template_FK` (`typeFk`),
+ CONSTRAINT `Id_Moneda` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `awb_component_template_FK` FOREIGN KEY (`typeFk`) REFERENCES `awbComponentType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `awb_component_template_FK_1` FOREIGN KEY (`airlineFk`) REFERENCES `airline` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `awb_unit_fk1` FOREIGN KEY (`awbUnit`) REFERENCES `awbUnit` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `role_fk` FOREIGN KEY (`awbRoleFk`) REFERENCES `awbRole` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `awbComponentType`
+--
+
+DROP TABLE IF EXISTS `awbComponentType`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `awbComponentType` (
+ `id` mediumint(3) unsigned NOT NULL AUTO_INCREMENT,
+ `description` varchar(45) DEFAULT NULL,
+ `hasStems` tinyint(1) NOT NULL DEFAULT 1,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT=' ';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `awbDms`
+--
+
+DROP TABLE IF EXISTS `awbDms`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `awbDms` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `awbFk` smallint(11) unsigned NOT NULL,
+ `dmsFk` int(11) NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `awb_gestdoc_awb_fk` (`awbFk`),
+ KEY `awb_gestdoc_gestdoc_fk` (`dmsFk`),
+ CONSTRAINT `awb_gestdoc_awb_fk` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `awb_gestdoc_gestdoc_fk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `awbInvoiceIn`
+--
+
+DROP TABLE IF EXISTS `awbInvoiceIn`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `awbInvoiceIn` (
+ `awbFk` smallint(5) unsigned NOT NULL,
+ `invoiceInFk` mediumint(8) unsigned NOT NULL,
+ `sad` varchar(18) DEFAULT NULL,
+ PRIMARY KEY (`invoiceInFk`),
+ KEY `awb_id` (`awbFk`),
+ CONSTRAINT `awbInvoiceIn_ibfk_1` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `awbInvoiceIn_ibfk_2` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `awbRole`
+--
+
+DROP TABLE IF EXISTS `awbRole`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `awbRole` (
+ `id` tinyint(1) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(45) DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT=' ';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `awbUnit`
+--
+
+DROP TABLE IF EXISTS `awbUnit`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `awbUnit` (
+ `id` varchar(10) NOT NULL DEFAULT '',
+ `operation` varchar(45) DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='tipos de unidades';
+/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `awbVolume`
@@ -22022,23 +27326,24 @@ SET character_set_client = utf8;
SET character_set_client = @saved_cs_client;
--
--- Temporary table structure for view `bank`
+-- Table structure for table `balanceNestTree`
--
-DROP TABLE IF EXISTS `bank`;
-/*!50001 DROP VIEW IF EXISTS `bank`*/;
-SET @saved_cs_client = @@character_set_client;
-SET character_set_client = utf8;
-/*!50001 CREATE VIEW `bank` AS SELECT
- 1 AS `id`,
- 1 AS `bank`,
- 1 AS `account`,
- 1 AS `cash`,
- 1 AS `entityFk`,
- 1 AS `isActive`,
- 1 AS `currencyFk`,
- 1 AS `code` */;
-SET character_set_client = @saved_cs_client;
+DROP TABLE IF EXISTS `balanceNestTree`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `balanceNestTree` (
+ `lft` int(11) DEFAULT NULL,
+ `rgt` int(11) DEFAULT NULL,
+ `name` text DEFAULT NULL,
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `isSelected` tinyint(1) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `balanceNestTree_expense_FK` (`expenseFk`),
+ CONSTRAINT `balanceNestTree_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `bankEntity`
@@ -22055,50 +27360,8 @@ CREATE TABLE `bankEntity` (
PRIMARY KEY (`id`),
KEY `fg_entity1_idx` (`countryFk`),
CONSTRAINT `fg_entity1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Entidades bancarias ';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Entidades bancarias ';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`bankEntity_beforeInsert`
- BEFORE INSERT ON `bankEntity`
- FOR EACH ROW
-BEGIN
- CALL bankEntity_checkBic(NEW.bic);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`bankEntity_beforeUpdate`
- BEFORE UPDATE ON `bankEntity`
- FOR EACH ROW
-BEGIN
- IF NOT (NEW.bic <=> OLD.bic) THEN
- CALL bankEntity_checkBic(NEW.bic);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `bankEntityConfig`
@@ -22112,7 +27375,7 @@ CREATE TABLE `bankEntityConfig` (
`bicLength` tinyint(4) DEFAULT 11 COMMENT 'Tamaño del campo bic',
`defaultBankId` int(11) NOT NULL DEFAULT 3117 COMMENT 'Id del banco por defecto',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -22130,34 +27393,49 @@ CREATE TABLE `bankErrorCode` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Temporary table structure for view `bankPolicy`
+-- Table structure for table `bankPolicy`
--
DROP TABLE IF EXISTS `bankPolicy`;
-/*!50001 DROP VIEW IF EXISTS `bankPolicy`*/;
-SET @saved_cs_client = @@character_set_client;
-SET character_set_client = utf8;
-/*!50001 CREATE VIEW `bankPolicy` AS SELECT
- 1 AS `id`,
- 1 AS `ref`,
- 1 AS `amount`,
- 1 AS `balanceInterestDrawn`,
- 1 AS `commissionAvailableBalances`,
- 1 AS `openingCommission`,
- 1 AS `started`,
- 1 AS `ended`,
- 1 AS `bankFk`,
- 1 AS `companyFk`,
- 1 AS `supplierFk`,
- 1 AS `description`,
- 1 AS `hasGuarantee`,
- 1 AS `dmsFk`,
- 1 AS `notaryFk`,
- 1 AS `currencyFk`,
- 1 AS `amortizationTypeFk`,
- 1 AS `periodicityTypeFk`,
- 1 AS `insuranceExpired` */;
-SET character_set_client = @saved_cs_client;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `bankPolicy` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `ref` varchar(45) DEFAULT NULL,
+ `amount` double NOT NULL,
+ `committedFee` double DEFAULT NULL,
+ `nonCommittedFee` double DEFAULT NULL,
+ `annualFee` double DEFAULT NULL,
+ `started` date NOT NULL,
+ `ended` date DEFAULT NULL,
+ `accountingFk` int(11) NOT NULL,
+ `companyFk` int(10) unsigned NOT NULL DEFAULT 442,
+ `supplierFk` int(10) unsigned DEFAULT NULL,
+ `description` varchar(255) DEFAULT NULL,
+ `hasGuarantee` tinyint(1) NOT NULL DEFAULT 0,
+ `dmsFk` int(11) DEFAULT NULL,
+ `notaryFk` int(10) unsigned DEFAULT NULL,
+ `currencyFk` tinyint(3) unsigned DEFAULT 2,
+ `amortizationTypeFk` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `periodicityTypeFk` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `insuranceExpired` date DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `Id_Banco_Poliza_idx` (`accountingFk`),
+ KEY `Id_Poliza_Empresa_idx` (`companyFk`),
+ KEY `bankSupplierIdx1_idx` (`supplierFk`),
+ KEY `bankDmsIdx2_idx` (`dmsFk`),
+ KEY `bankNotaryIdx3_idx` (`notaryFk`),
+ KEY `asdf_idx` (`amortizationTypeFk`),
+ KEY `bankPeriodicityIdx4_idx` (`periodicityTypeFk`),
+ CONSTRAINT `Bancos_polizaCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `Bancos_poliza_notaryFk` FOREIGN KEY (`notaryFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `Bancos_poliza_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `Id_Banco_Poliza` FOREIGN KEY (`accountingFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `asdf` FOREIGN KEY (`amortizationTypeFk`) REFERENCES `amortizationType` (`code`) ON UPDATE CASCADE,
+ CONSTRAINT `bankDmsIdx2` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `bankPeriodicityIdx4` FOREIGN KEY (`periodicityTypeFk`) REFERENCES `periodicityType` (`code`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lineas de credito asociadas a cuentas corrientes';
+/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `beach`
@@ -22187,7 +27465,7 @@ CREATE TABLE `bionicConfig` (
`verdnaturaVolumeBox` int(11) NOT NULL,
`itemCarryBox` int(11) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -22214,17 +27492,17 @@ CREATE TABLE `bookingPlanner` (
CONSTRAINT `bookingPlanner_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `bookingPlanner_ibfk_2` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `bookingPlanner_ibfk_3` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `botanicExport`
+-- Table structure for table `botanicExport__`
--
-DROP TABLE IF EXISTS `botanicExport`;
+DROP TABLE IF EXISTS `botanicExport__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `botanicExport` (
+CREATE TABLE `botanicExport__` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`ediGenusFk` mediumint(8) unsigned NOT NULL,
`ediSpecieFk` mediumint(8) unsigned DEFAULT NULL,
@@ -22237,31 +27515,9 @@ CREATE TABLE `botanicExport` (
KEY `Id_Paises` (`countryFk__`),
KEY `botanicExport_ibfk_2_idx` (`ediGenusFk`),
KEY `botanicExport_ibfk_3_idx` (`ediSpecieFk`),
- CONSTRAINT `botanicExport_ibfk_1` FOREIGN KEY (`countryFk__`) REFERENCES `country` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Especifica los generos y especies prohibidos en paises';
+ CONSTRAINT `botanicExport___ibfk_1` FOREIGN KEY (`countryFk__`) REFERENCES `country` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #4419 Deprecated 2023-07-20';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`botanicExport_beforeInsert`
- BEFORE INSERT ON `botanicExport`
- FOR EACH ROW
-BEGIN
- IF (SELECT botanicExport_isUpdatable (NEW.ediGenusFk, NEW.ediSpecieFk, NEW.restriction) ) > 0 THEN
- CALL util.throw ('Datos duplicados');
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `budget`
@@ -22294,7 +27550,7 @@ CREATE TABLE `budget` (
CONSTRAINT `budget_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budget_FK_2` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budget_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Master de presupuestos de project';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Master de presupuestos de project';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -22313,7 +27569,7 @@ CREATE TABLE `budgetDms` (
KEY `budgetDms_FK_1` (`dmsFk`),
CONSTRAINT `budgetDms_FK` FOREIGN KEY (`budgetFk`) REFERENCES `budget` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budgetDms_FK_1` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Gestion documental de budget';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Gestion documental de budget';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -22334,7 +27590,7 @@ CREATE TABLE `budgetInvoiceIn` (
KEY `budgetInvoiceIn_FK_1` (`invoiceInFk`),
CONSTRAINT `budgetInvoiceIn_FK` FOREIGN KEY (`budgetFk`) REFERENCES `budget` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budgetInvoiceIn_FK_1` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Facturas relativas al presupuesto';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Facturas relativas al presupuesto';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -22355,34 +27611,8 @@ CREATE TABLE `budgetNotes` (
KEY `budgetNotes_FK_2` (`userFk`),
CONSTRAINT `budgetNotes_FK` FOREIGN KEY (`budgetFk`) REFERENCES `budget` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budgetNotes_FK_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Historico de budget';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Historico de budget';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`budgetNotes_BeforeInsert`
- BEFORE INSERT ON `budgetNotes`
- FOR EACH ROW
-BEGIN
-
- IF ISNULL(NEW.userFk) THEN
-
- SET NEW.userFk = account.myUser_getId();
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `budgetState`
@@ -22397,7 +27627,7 @@ CREATE TABLE `budgetState` (
`description` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `budgetState_UN` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -22422,7 +27652,7 @@ CREATE TABLE `business` (
`workerBusinessProfessionalCategoryFk` int(11) DEFAULT NULL,
`calendarTypeFk` int(11) DEFAULT 1,
`isHourlyLabor` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Contrato por horas',
- `workcenterFk` int(11) DEFAULT NULL,
+ `workcenterFk` int(11) NOT NULL DEFAULT 9,
`rate` int(11) DEFAULT NULL,
`workerBusinessCategoryFk` int(11) DEFAULT NULL,
`workerBusinessTypeFk` int(11) DEFAULT NULL,
@@ -22452,148 +27682,8 @@ CREATE TABLE `business` (
CONSTRAINT `business_workerBusinessCategoryFk` FOREIGN KEY (`workerBusinessCategoryFk`) REFERENCES `payrollCategories` (`id`) ON UPDATE CASCADE,
CONSTRAINT `business_workerBusinessTypeFk` FOREIGN KEY (`workerBusinessTypeFk`) REFERENCES `workerBusinessType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `business_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`business_beforeInsert`
- BEFORE INSERT ON `business`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.ended IS NULL THEN
- SET NEW.payedHolidays = 0;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`business_afterInsert`
- AFTER INSERT ON `business`
- FOR EACH ROW
-BEGIN
- CALL worker_updateBusiness(NEW.workerFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`business_beforeUpdate`
- BEFORE UPDATE ON `business`
- FOR EACH ROW
-BEGIN
- DECLARE isOverlapping BOOL;
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.ended IS NULL THEN
- SET NEW.payedHolidays = 0;
- END IF;
-
- IF !(OLD.started <=> NEW.started AND OLD.ended <=> NEW.ended) THEN
-
- SELECT COUNT(*) > 0 INTO isOverlapping
- FROM business b
- WHERE (util.hasDateOverlapped(
- NEW.started,
- IFNULL(NEW.ended, b.started),
- b.started,
- IFNULL(b.ended, NEW.started))
- OR (NEW.ended <=> NULL AND b.ended <=> NULL))
- AND b.id <> OLD.id
- AND workerFk = OLD.workerFk;
-
- IF isOverlapping THEN
- CALL util.throw ('IS_OVERLAPPING');
- END IF;
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`business_afterUpdate`
- AFTER UPDATE ON `business`
- FOR EACH ROW
-BEGIN
- CALL worker_updateBusiness(NEW.workerFk);
-
- IF NOT (OLD.workerFk <=> NEW.workerFk) THEN
- CALL worker_updateBusiness(OLD.workerFk);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`business_afterDelete`
- AFTER DELETE ON `business`
- FOR EACH ROW
-BEGIN
- INSERT INTO workerLog
- SET `action` = 'delete',
- `changedModel` = 'Business',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-
- CALL worker_updateBusiness(OLD.workerFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `businessCalendar`
@@ -22621,7 +27711,7 @@ CREATE TABLE `businessReasonEnd` (
`id` tinyint(3) NOT NULL AUTO_INCREMENT,
`reason` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -22641,7 +27731,7 @@ CREATE TABLE `businessSchedule` (
UNIQUE KEY `day_id` (`weekday`,`started`,`ended`,`businessFk`),
KEY `journey_business_id_idx` (`businessFk`),
CONSTRAINT `journey_business_id` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -22671,7 +27761,7 @@ CREATE TABLE `buy` (
`itemFk` int(11) NOT NULL DEFAULT 90,
`quantity` int(11) DEFAULT 0,
`dispatched` int(11) NOT NULL DEFAULT 0,
- `buyingValue` decimal(10,3) NOT NULL DEFAULT 0.000,
+ `buyingValue` decimal(10,4) NOT NULL DEFAULT 0.0000,
`freightValue` decimal(10,3) NOT NULL DEFAULT 0.000,
`isIgnored` tinyint(1) NOT NULL DEFAULT 0,
`stickers` int(11) NOT NULL DEFAULT 0,
@@ -22682,7 +27772,7 @@ CREATE TABLE `buy` (
`comissionValue` decimal(10,3) NOT NULL DEFAULT 0.000,
`packageValue` decimal(10,3) NOT NULL DEFAULT 0.000,
`location` varchar(5) DEFAULT NULL,
- `packageFk` varchar(10) DEFAULT '--',
+ `packagingFk` varchar(10) DEFAULT '--',
`price1` decimal(10,2) DEFAULT 0.00,
`price2` decimal(10,2) DEFAULT 0.00,
`price3` decimal(10,2) DEFAULT 0.00,
@@ -22698,9 +27788,10 @@ CREATE TABLE `buy` (
`deliveryFk` int(11) DEFAULT NULL,
`itemOriginalFk` int(11) DEFAULT NULL COMMENT 'Item original de la entrada',
`editorFk` int(10) unsigned DEFAULT NULL,
+ `packageFk` varchar(10) GENERATED ALWAYS AS (`packagingFk`) VIRTUAL,
PRIMARY KEY (`id`),
KEY `CompresId_Trabajador` (`workerFk`),
- KEY `Id_Cubo` (`packageFk`),
+ KEY `Id_Cubo` (`packagingFk`),
KEY `Id_Entrada` (`entryFk`),
KEY `container_id` (`containerFk`),
KEY `buy_edi_id` (`ektFk`),
@@ -22710,327 +27801,16 @@ CREATE TABLE `buy` (
KEY `buy_itemFk_IDX` (`itemFk`) USING BTREE,
KEY `buy_fk_editor` (`editorFk`),
CONSTRAINT `buy_FK` FOREIGN KEY (`itemOriginalFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT `buy_FK_1` FOREIGN KEY (`containerFk`) REFERENCES `vn2008`.`container` (`container_id`) ON UPDATE CASCADE,
+ CONSTRAINT `buy_FK_1` FOREIGN KEY (`containerFk`) REFERENCES `vn2008`.`container__` (`container_id`) ON UPDATE CASCADE,
CONSTRAINT `buy_ektFk` FOREIGN KEY (`ektFk`) REFERENCES `edi`.`ekt` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `buy_fk_4` FOREIGN KEY (`deliveryFk`) REFERENCES `edi`.`deliveryInformation` (`ID`) ON DELETE SET NULL ON UPDATE SET NULL,
CONSTRAINT `buy_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `buy_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `buy_ibfk_2` FOREIGN KEY (`packageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `buy_ibfk_2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
CONSTRAINT `buy_id` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `buy_itemfk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=DYNAMIC;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeInsert`
- BEFORE INSERT ON `buy`
- FOR EACH ROW
-trig: BEGIN
- DECLARE vWarehouse INT;
- DECLARE vLanding DATE;
- DECLARE vGrouping INT;
- DECLARE vGroupingMode TINYINT;
- DECLARE vGenericFk INT;
- DECLARE vGenericInDate BOOL;
-
- IF @isModeInventory THEN
- LEAVE trig;
- END IF;
-
- IF NEW.printedStickers <> 0 THEN
- CALL util.throw('it is not possible to create buy lines with printedstickers other than 0');
- END IF;
-
- SET NEW.editorFk = account.myUser_getId();
-
- CALL buy_checkGrouping(NEW.`grouping`);
-
- SELECT t.warehouseInFk, t.landed INTO vWarehouse, vLanding
- FROM entry e
- JOIN travel t ON t.id = e.travelFk
- WHERE e.id = NEW.entryFk;
-
- SELECT b.`grouping`, b.groupingMode INTO vGrouping, vGroupingMode
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed <= vLanding
- AND b.itemFk = NEW.itemFk
- AND !b.isIgnored
- ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC, b.id DESC
- LIMIT 1;
-
- IF NEW.`grouping` IS NULL THEN
- SET NEW.`grouping` = vGrouping;
- END IF;
-
- IF NEW.groupingMode IS NULL THEN
- SET NEW.groupingMode = vGroupingMode;
- END IF;
- -- Generics
- SELECT i.genericFk INTO vGenericFk
- FROM item i
- WHERE i.id = NEW.itemFk;
-
- IF vGenericFk THEN
- SELECT COUNT(*) INTO vGenericInDate
- FROM genericAllocation ga
- JOIN entry e ON e.id = NEW.entryFk
- JOIN travel tr on tr.id = e.travelFk
- WHERE ga.itemFk = vGenericFk
- AND tr.landed BETWEEN ga.startDated AND ga.endDated;
- IF vGenericInDate THEN
- SET NEW.itemOriginalFk = NEW.itemFk;
-
- SET NEW.itemFk = vGenericFk;
- END IF;
- END IF;
- IF NEW.quantity < 0 THEN
- SET NEW.isIgnored = TRUE;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_afterInsert`
- AFTER INSERT ON `buy`
- FOR EACH ROW
-trig: BEGIN
- IF @isModeInventory OR @isTriggerDisabled THEN
- LEAVE trig;
- END IF;
-
- CALL stock.log_add('buy', NEW.id, NULL);
-
- CALL buy_afterUpsert(NEW.id);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeUpdate`
- BEFORE UPDATE ON `buy`
- FOR EACH ROW
-trig:BEGIN
- DECLARE vGenericFk INT;
- DECLARE vGenericInDate BOOL;
- DECLARE vIsInventory BOOL;
- DECLARE vDefaultEntry INT;
-
- IF @isTriggerDisabled THEN
- LEAVE trig;
- END IF;
-
- SET NEW.editorFk = account.myUser_getId();
-
- SELECT defaultEntry INTO vDefaultEntry
- FROM entryConfig;
-
- IF (NOT OLD.entryFk <=> NEW.entryFk OR NOT OLD.printedStickers <=> NEW.printedStickers)
- AND NEW.printedStickers <> 0 THEN
- SELECT defaultEntry INTO vDefaultEntry
- FROM entryConfig;
-
- IF NEW.entryFk = vDefaultEntry THEN
- CALL util.throw('There can be no lines with printed labels on the default entry');
- END IF;
- END IF;
-
- IF NOT NEW.`grouping` <=> OLD.`grouping` THEN
- CALL buy_checkGrouping(NEW.`grouping`);
- END IF;
-
- -- Generics
- SELECT i.genericFk INTO vGenericFk
- FROM item i
- WHERE i.id = NEW.itemFk;
-
- IF vGenericFk THEN
- SELECT COUNT(*) INTO vGenericInDate
- FROM genericAllocation ga
- JOIN entry e ON e.id = NEW.entryFk
- JOIN travel tr on tr.id = e.travelFk
- WHERE ga.itemFk = vGenericFk
- AND tr.landed BETWEEN ga.startDated AND ga.endDated;
- IF vGenericInDate THEN
- SET NEW.itemOriginalFk = NEW.itemFk;
- SET NEW.itemFk = vGenericFk;
- END IF;
- END IF;
-
- SELECT COUNT(*) INTO vIsInventory
- FROM entry e
- JOIN supplier s ON s.id = e.supplierFk
- JOIN entryConfig ec ON ec.inventorySupplierFk = e.supplierFk
- WHERE e.id = NEW.entryFk;
-
- IF vIsInventory THEN
- IF NOT NEW.printedStickers <=> OLD.printedStickers THEN
- CALL util.throw("Stickers cannot be modified if they are inventory");
- END IF;
- END IF;
-
- IF NEW.quantity < 0 THEN
- SET NEW.isIgnored = TRUE;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_afterUpdate`
- AFTER UPDATE ON `buy`
- FOR EACH ROW
-trig: BEGIN
- DECLARE vLanded DATE;
- DECLARE vBuyerFk INT;
- DECLARE vIsBuyerToBeEmailed BOOL;
- DECLARE vItemName VARCHAR(50);
-
- IF @isModeInventory OR @isTriggerDisabled THEN
- LEAVE trig;
- END IF;
-
- IF !(NEW.id <=> OLD.id)
- OR !(NEW.entryFk <=> OLD.entryFk)
- OR !(NEW.itemFk <=> OLD.itemFk)
- OR !(NEW.quantity <=> OLD.quantity)
- OR !(NEW.created <=> OLD.created) THEN
- CALL stock.log_add('buy', NEW.id, OLD.id);
- END IF;
-
- CALL buy_afterUpsert(NEW.id);
-
- SELECT w.isBuyerToBeEmailed, t.landed
- INTO vIsBuyerToBeEmailed, vLanded
- FROM entry e
- JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseInFk
- WHERE e.id = NEW.entryFk;
-
- SELECT it.workerFk, i.longName
- INTO vBuyerFk, vItemName
- FROM itemCategory k
- JOIN itemType it ON it.categoryFk = k.id
- JOIN item i ON i.typeFk = it.id
- WHERE i.id = OLD.itemFk;
-
- IF vIsBuyerToBeEmailed AND
- vBuyerFk != account.myUser_getId() AND
- vLanded = util.VN_CURDATE() THEN
- IF !(NEW.itemFk <=> OLD.itemFk) OR
- !(NEW.quantity <=> OLD.quantity) OR
- !(NEW.packing <=> OLD.packing) OR
- !(NEW.grouping <=> OLD.grouping) OR
- !(NEW.packageFk <=> OLD.packageFk) OR
- !(NEW.weight <=> OLD.weight) THEN
- CALL vn.mail_insert(
- CONCAT(account.user_getNameFromId(vBuyerFk),'@verdnatura.es'),
- CONCAT(account.myUser_getName(),'@verdnatura.es'),
- CONCAT('E ', NEW.entryFk ,' Se ha modificado item ', NEW.itemFk, ' ', vItemName),
- 'Este email se ha generado automáticamente'
- );
- END IF;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeDelete`
- BEFORE DELETE ON buy
- FOR EACH ROW
-BEGIN
- IF OLD.printedStickers <> 0 THEN
- CALL util.throw("it is not possible to delete buys with printed labels ");
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_afterDelete`
- AFTER DELETE ON `buy`
- FOR EACH ROW
-trig: BEGIN
- DECLARE vValues VARCHAR(255);
-
- IF @isModeInventory OR @isTriggerDisabled THEN
- LEAVE trig;
- END IF;
-
- CALL stock.log_add('buy', NULL, OLD.id);
-
- INSERT INTO entryLog
- SET `action` = 'delete',
- `changedModel` = 'Buy',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `buyConfig`
@@ -23103,6 +27883,7 @@ CREATE TABLE `calendar` (
`businessFk` int(11) NOT NULL,
`dayOffTypeFk` int(11) NOT NULL,
`dated` date NOT NULL,
+ `editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `calendar_UN` (`businessFk`,`dated`),
KEY `calendar_employee_business_labour_id_idx` (`businessFk`),
@@ -23110,7 +27891,7 @@ CREATE TABLE `calendar` (
KEY `id_index` (`id`),
CONSTRAINT `calendar_FK` FOREIGN KEY (`dayOffTypeFk`) REFERENCES `absenceType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `calendar_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23134,7 +27915,7 @@ CREATE TABLE `calendarHolidays` (
CONSTRAINT `calendarHolidaysNameFk` FOREIGN KEY (`calendarHolidaysNameFk`) REFERENCES `calendarHolidaysName` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `calendarholidaystypeFk` FOREIGN KEY (`calendarHolidaysTypeFk`) REFERENCES `calendarHolidaysType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `workCenterFk` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23148,7 +27929,7 @@ CREATE TABLE `calendarHolidaysName` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23163,7 +27944,7 @@ CREATE TABLE `calendarHolidaysType` (
`name` varchar(50) NOT NULL,
`hexColour` char(7) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23180,7 +27961,7 @@ CREATE TABLE `calendarType` (
`isPartial` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `hours_labour_hours_labour_id_key` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23197,7 +27978,7 @@ CREATE TABLE `campaign` (
`scopeDays` int(11) NOT NULL DEFAULT 15,
PRIMARY KEY (`id`),
UNIQUE KEY `campaign_dated_uindex` (`dated`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23212,7 +27993,7 @@ CREATE TABLE `category` (
`description` varchar(45) NOT NULL,
`nick` varchar(3) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23230,7 +28011,7 @@ CREATE TABLE `chain` (
PRIMARY KEY (`id`),
KEY `chain_FK` (`componentFk`),
CONSTRAINT `chain_FK` FOREIGN KEY (`componentFk`) REFERENCES `component` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Grupos de clientes';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Grupos de clientes';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23254,7 +28035,7 @@ CREATE TABLE `chat` (
PRIMARY KEY (`id`),
KEY `chat_FK` (`senderFk`),
CONSTRAINT `chat_FK` FOREIGN KEY (`senderFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23271,7 +28052,7 @@ CREATE TABLE `chatConfig` (
`user` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23294,7 +28075,7 @@ CREATE TABLE `claim` (
`ticketFk` int(11) DEFAULT NULL,
`hasToPickUp` tinyint(1) NOT NULL,
`packages` smallint(10) unsigned DEFAULT 0 COMMENT 'packages received by the client',
- `rma` varchar(100) DEFAULT NULL,
+ `rma__` varchar(100) DEFAULT NULL,
`responsabilityRate` decimal(3,2) GENERATED ALWAYS AS ((5 - `responsibility`) / 4) VIRTUAL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
@@ -23307,72 +28088,8 @@ CREATE TABLE `claim` (
CONSTRAINT `claim_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `claim_ibfk_3` FOREIGN KEY (`claimStateFk`) REFERENCES `claimState` (`id`) ON UPDATE CASCADE,
CONSTRAINT `claim_ibfk_5` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Reclamaciones, tabla principal';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Reclamaciones, tabla principal';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claim_beforeInsert`
- BEFORE INSERT ON `claim`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claim_beforeUpdate`
- BEFORE UPDATE ON `claim`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claim_afterDelete`
- AFTER DELETE ON `claim`
- FOR EACH ROW
-BEGIN
- INSERT INTO claimLog
- SET `action` = 'delete',
- `changedModel` = 'Claim',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `claimBeginning`
@@ -23394,72 +28111,8 @@ CREATE TABLE `claimBeginning` (
CONSTRAINT `claimBeginning_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `claimBeginning_ibfk_7` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `claimBeginning_ibfk_8` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle de las reclamaciones';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle de las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimBeginning_beforeInsert`
- BEFORE INSERT ON `claimBeginning`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimBeginning_beforeUpdate`
- BEFORE UPDATE ON `claimBeginning`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimBeginning_afterDelete`
- AFTER DELETE ON `claimBeginning`
- FOR EACH ROW
-BEGIN
- INSERT INTO claimLog
- SET `action` = 'delete',
- `changedModel` = 'ClaimBeginning',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `claimConfig`
@@ -23489,7 +28142,7 @@ CREATE TABLE `claimDestination` (
PRIMARY KEY (`id`),
KEY `clSolAddressFk_idx` (`addressFk`),
CONSTRAINT `clSolAddressFk` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Solucion ofrecida a la reclamación';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Solucion ofrecida a la reclamación';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23526,72 +28179,8 @@ CREATE TABLE `claimDevelopment` (
CONSTRAINT `claimDevelopment_ibfk_7` FOREIGN KEY (`claimReasonFk`) REFERENCES `claimReason` (`id`) ON UPDATE CASCADE,
CONSTRAINT `claimDevelopment_ibfk_8` FOREIGN KEY (`claimResultFk`) REFERENCES `claimResult` (`id`) ON UPDATE CASCADE,
CONSTRAINT `claimDevelopment_ibfk_9` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Causas de las reclamaciones';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Causas de las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimDevelopment_beforeInsert`
- BEFORE INSERT ON `claimDevelopment`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimDevelopment_beforeUpdate`
- BEFORE UPDATE ON `claimDevelopment`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimDevelopment_afterDelete`
- AFTER DELETE ON `claimDevelopment`
- FOR EACH ROW
-BEGIN
- INSERT INTO claimLog
- SET `action` = 'delete',
- `changedModel` = 'ClaimDevelopment',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `claimDms`
@@ -23612,70 +28201,6 @@ CREATE TABLE `claimDms` (
CONSTRAINT `dmsFk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimDms_beforeInsert`
- BEFORE INSERT ON `claimDms`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimDms_beforeUpdate`
- BEFORE UPDATE ON `claimDms`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimDms_afterDelete`
- AFTER DELETE ON `claimDms`
- FOR EACH ROW
-BEGIN
- INSERT INTO claimLog
- SET `action` = 'delete',
- `changedModel` = 'ClaimDms',
- `changedModelId` = OLD.claimFk,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `claimEnd`
@@ -23702,72 +28227,8 @@ CREATE TABLE `claimEnd` (
CONSTRAINT `claimEnd_ibfk_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `claimEnd_ibfk_3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `claimEnd_ibfk_4` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Acciones en respuesta a las reclamaciones';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Acciones en respuesta a las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimEnd_beforeInsert`
- BEFORE INSERT ON `claimEnd`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimEnd_beforeUpdate`
- BEFORE UPDATE ON `claimEnd`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimEnd_afterDelete`
- AFTER DELETE ON `claimEnd`
- FOR EACH ROW
-BEGIN
- INSERT INTO claimLog
- SET `action` = 'delete',
- `changedModel` = 'ClaimEnd',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `claimLog`
@@ -23792,9 +28253,8 @@ CREATE TABLE `claimLog` (
KEY `userFk` (`userFk`),
KEY `claimLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `claimLog_claimLog` (`originFk`,`creationDate`),
- CONSTRAINT `claimOriginFk` FOREIGN KEY (`originFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `claimUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23819,72 +28279,8 @@ CREATE TABLE `claimObservation` (
CONSTRAINT `claimObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `claimObservation_ibfk_1` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `claimObservation_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a una reclamación';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a una reclamación';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimObservation_beforeInsert`
- BEFORE INSERT ON `claimObservation`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimObservation_beforeUpdate`
- BEFORE UPDATE ON `claimObservation`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimObservation_afterDelete`
- AFTER DELETE ON `claimObservation`
- FOR EACH ROW
-BEGIN
- INSERT INTO claimLog
- SET `action` = 'delete',
- `changedModel` = 'ClaimObservation',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `claimRatio`
@@ -23917,7 +28313,7 @@ CREATE TABLE `claimReason` (
`description` varchar(45) NOT NULL,
`isTired` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Motivos de las fallos';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Motivos de las fallos';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23931,7 +28327,7 @@ CREATE TABLE `claimRedelivery` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Método por el cual el cliente nos devuelve la mercancía';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Método por el cual el cliente nos devuelve la mercancía';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23945,8 +28341,10 @@ CREATE TABLE `claimResponsible` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
`responsability` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'if=1 >sensib >culpa',
- PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Responsables de las causas';
+ `code` varchar(3) NOT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `claimResponsible_UN` (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Responsables de las causas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23960,23 +28358,23 @@ CREATE TABLE `claimResult` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Consecuencias de los motivos';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Consecuencias de los motivos';
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `claimRma`
+-- Table structure for table `claimRma__`
--
-DROP TABLE IF EXISTS `claimRma`;
+DROP TABLE IF EXISTS `claimRma__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `claimRma` (
+CREATE TABLE `claimRma__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(100) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`workerFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='kkeada el 2024-02-26 por Pablo';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -23999,72 +28397,8 @@ CREATE TABLE `claimState` (
KEY `claimState_fk_editor` (`editorFk`),
CONSTRAINT `claimState_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `roleFgn` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Estados posibles de las reclamaciones';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Estados posibles de las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimState_beforeInsert`
- BEFORE INSERT ON `claimState`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimState_beforeUpdate`
- BEFORE UPDATE ON `claimState`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimState_afterDelete`
- AFTER DELETE ON `claimState`
- FOR EACH ROW
-BEGIN
- INSERT INTO claimLog
- SET `action` = 'delete',
- `changedModel` = 'ClaimState',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `client`
@@ -24078,7 +28412,7 @@ CREATE TABLE `client` (
`name` varchar(50) NOT NULL,
`defaultAddressFk` int(11) DEFAULT NULL,
`street` longtext DEFAULT NULL,
- `fi` varchar(14) DEFAULT NULL,
+ `fi` varchar(18) DEFAULT NULL,
`phone` varchar(15) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`dueDay` smallint(6) NOT NULL DEFAULT 5,
@@ -24094,7 +28428,7 @@ CREATE TABLE `client` (
`hasToInvoice` tinyint(1) NOT NULL DEFAULT 1,
`isFreezed` tinyint(1) NOT NULL DEFAULT 0,
`salesPersonFk` int(10) unsigned DEFAULT NULL,
- `credit` decimal(10,2) NOT NULL DEFAULT 0.00,
+ `credit` decimal(10,2) unsigned NOT NULL DEFAULT 0.00,
`countryFk` mediumint(8) unsigned NOT NULL DEFAULT 1,
`isActive` tinyint(1) NOT NULL DEFAULT 1,
`gestdocFk` int(11) DEFAULT NULL,
@@ -24109,7 +28443,7 @@ CREATE TABLE `client` (
`riskCalculated` date NOT NULL,
`hasCoreVnh` tinyint(1) DEFAULT 0,
`isRelevant` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Define los clientes cuyas ventas hay que tener en cuenta en los calculos estadisticos.',
- `clientTypeFk` int(11) NOT NULL DEFAULT 1,
+ `clientTypeFk__` int(11) NOT NULL DEFAULT 1 COMMENT '@deprecated 2024-02-20 refs #6784',
`creditInsurance` int(11) DEFAULT NULL,
`eypbc` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Email\\nYesterday\\nPurchases\\nBy\\nConsigna',
`hasToInvoiceByAddress` tinyint(1) DEFAULT 0,
@@ -24140,7 +28474,7 @@ CREATE TABLE `client` (
KEY `default_address` (`defaultAddressFk`),
KEY `Telefono` (`phone`),
KEY `movil` (`mobile`),
- KEY `tipos_de_cliente_idx` (`clientTypeFk`),
+ KEY `tipos_de_cliente_idx` (`clientTypeFk__`),
KEY `fk_Clientes_entity_idx` (`bankEntityFk`),
KEY `typeFk` (`typeFk`),
KEY `client_taxTypeSageFk_idx` (`taxTypeSageFk`),
@@ -24150,6 +28484,7 @@ CREATE TABLE `client` (
KEY `client_FK_3` (`transferorFk`),
KEY `codpos` (`postcode`),
KEY `client_fk_editor` (`editorFk`),
+ KEY `client_isTaxDataChecked_IDX` (`isTaxDataChecked`) USING BTREE,
CONSTRAINT `canal_nuevo_cliente` FOREIGN KEY (`contactChannelFk`) REFERENCES `contactChannel` (`id`) ON UPDATE CASCADE,
CONSTRAINT `client_FK` FOREIGN KEY (`businessTypeFk`) REFERENCES `businessType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `client_FK_1` FOREIGN KEY (`bankEntityFk`) REFERENCES `bankEntity` (`id`) ON UPDATE CASCADE,
@@ -24163,189 +28498,9 @@ CREATE TABLE `client` (
CONSTRAINT `client_ibfk_5` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE,
CONSTRAINT `client_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE,
CONSTRAINT `client_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
- CONSTRAINT `tipos_de_cliente` FOREIGN KEY (`clientTypeFk`) REFERENCES `clientType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `typeFk` FOREIGN KEY (`typeFk`) REFERENCES `clientType` (`code`) ON DELETE NO ACTION ON UPDATE NO ACTION
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`client_beforeInsert`
- BEFORE INSERT ON `client`
- FOR EACH ROW
-BEGIN
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF (NEW.phone <> '') THEN
- CALL pbx.phone_isValid(NEW.phone);
- END IF;
-
- IF (NEW.mobile <> '') THEN
- CALL pbx.phone_isValid(NEW.mobile);
- END IF;
-
- SET NEW.accountingAccount = 4300000000 + NEW.id;
-
- SET NEW.lastSalesPersonFk = NEW.salesPersonFk;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`client_beforeUpdate`
- BEFORE UPDATE ON `client`
- FOR EACH ROW
-BEGIN
- DECLARE vText VARCHAR(255) DEFAULT NULL;
- DECLARE vPayMethodFk INT;
-
- SET NEW.editorFk = account.myUser_getId();
-
- -- Comprueba que el formato de los teléfonos es válido
-
- IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN
- CALL pbx.phone_isValid(NEW.phone);
- END IF;
-
- IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN
- CALL pbx.phone_isValid(NEW.mobile);
- END IF;
-
- SELECT id INTO vPayMethodFk
- FROM vn.payMethod
- WHERE code = 'bankDraft';
-
- IF NEW.payMethodFk = vPayMethodFk AND NEW.dueDay = 0 THEN
- SET NEW.dueDay = 5;
- END IF;
-
- -- Avisar al comercial si ha llegado la documentación sepa/core
-
- IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN
- SET vText = 'Sepa de VNL';
- END IF;
-
- IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN
- SET vText = 'Core de VNL';
- END IF;
-
- IF vText IS NOT NULL
- THEN
- INSERT INTO mail(receiver, replyTo, `subject`, body)
- SELECT
- CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'),
- 'administracion@verdnatura.es',
- CONCAT('Cliente ', NEW.id),
- CONCAT('Recibida la documentación: ', vText)
- FROM worker w
- LEFT JOIN account.user u ON w.id = u.id AND u.active
- LEFT JOIN account.account ac ON ac.id = u.id
- WHERE w.id = NEW.salesPersonFk;
- END IF;
-
- IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN
- IF (SELECT COUNT(clientFk)
- FROM clientProtected
- WHERE clientFk = NEW.id
- ) > 0 THEN
- CALL util.throw("HAS_CLIENT_PROTECTED");
- END IF;
- END IF;
-
- IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN
- SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk);
- END IF;
-
- IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN
- SET NEW.isTaxDataChecked = 0;
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`client_afterUpdate`
- AFTER UPDATE ON `client`
- FOR EACH ROW
-BEGIN
- IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN
- UPDATE `address` SET isDefaultAddress = 0
- WHERE clientFk = NEW.id;
-
- UPDATE `address` SET isDefaultAddress = 1
- WHERE id = NEW.defaultAddressFk;
- END IF;
-
- IF NOT (NEW.provinceFk <=> OLD.provinceFk) OR NOT (NEW.isVies <=> OLD.isVies) THEN
- INSERT IGNORE INTO ticketRecalc (ticketFk)
- SELECT id FROM ticket t
- WHERE t.clientFk = NEW.id
- AND t.refFk IS NULL;
- END IF;
-
- IF NOT NEW.isActive THEN
- UPDATE account.`user`
- SET active = FALSE
- WHERE id = NEW.id;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`client_afterDelete`
- AFTER DELETE ON `client`
- FOR EACH ROW
-BEGIN
- INSERT INTO clientLog
- SET `action` = 'delete',
- `changedModel` = 'Client',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `clientChain`
@@ -24363,7 +28518,7 @@ CREATE TABLE `clientChain` (
KEY `clientChain_fk2_idx` (`chainFk`),
CONSTRAINT `clientChain_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientChain_fk2` FOREIGN KEY (`chainFk`) REFERENCES `chain` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -24390,7 +28545,7 @@ CREATE TABLE `clientConfig` (
KEY `clientNewConfigMandateType_FK` (`defaultMandateTypeFk`),
CONSTRAINT `clientNewConfigMandateType_FK` FOREIGN KEY (`defaultMandateTypeFk`) REFERENCES `mandateType` (`id`),
CONSTRAINT `clientNewConfigPayMethod_FK` FOREIGN KEY (`defaultPayMethodFk`) REFERENCES `payMethod` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -24407,7 +28562,7 @@ CREATE TABLE `clientConsumptionQueue` (
`printed` datetime DEFAULT NULL,
`status` varchar(50) DEFAULT '',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue for client consumption PDF mailing';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue for client consumption PDF mailing';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -24425,53 +28580,11 @@ CREATE TABLE `clientContact` (
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `clientContact_fk_editor` (`editorFk`),
+ KEY `clientContact_FK` (`clientFk`),
+ CONSTRAINT `clientContact_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientContact_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientContact_beforeInsert`
- BEFORE INSERT ON `clientContact`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientContact_afterDelete`
- AFTER DELETE ON `clientContact`
- FOR EACH ROW
-BEGIN
- INSERT INTO clientLog
- SET `action` = 'delete',
- `changedModel` = 'ClientContact',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `clientCredit`
@@ -24491,58 +28604,6 @@ CREATE TABLE `clientCredit` (
KEY `credit_ClienteFk` (`clientFk`),
CONSTRAINT `credit_ClienteFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `workers_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER clientCredit_AfterInsert
-AFTER INSERT
-ON clientCredit FOR EACH ROW
-BEGIN
-
- DECLARE vSender VARCHAR(50);
-
- SELECT u.name INTO vSender
- FROM account.`user` u
- WHERE u.id = NEW.workerFk;
-
- IF vSender IN ('juanvi','pepe') THEN
-
- CALL `vn`.`mail_insert`('pako@verdnatura.es',
- NULL,
- CONCAT('ClientCredit ',vSender, ' ', NEW.clientFk, ' ' , NEW.amount, ' €'),
- CONCAT('ClientCredit ',vSender, ' ', NEW.clientFk, ' ' , NEW.amount, ' €'));
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-
---
--- 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`),
- KEY `clientCreditLimit_FK_idx` (`roleFk`),
- CONSTRAINT `clientCreditLimit_FK` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -24566,70 +28627,6 @@ CREATE TABLE `clientDms` (
CONSTRAINT `fk_clientes_gestdoc_3` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientDms_beforeInsert`
- BEFORE INSERT ON `clientDms`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientDms_beforeUpdate`
- BEFORE UPDATE ON `clientDms`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientDms_afterDelete`
- AFTER DELETE ON `clientDms`
- FOR EACH ROW
-BEGIN
- INSERT INTO clientLog
- SET `action` = 'delete',
- `changedModel` = 'ClientDms',
- `changedModelId` = OLD.dmsFk,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `clientInforma`
@@ -24650,7 +28647,7 @@ CREATE TABLE `clientInforma` (
KEY `informaClientFk` (`clientFk`),
CONSTRAINT `informa_ClienteFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `informa_workers_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='información proporcionada por Informa, se actualiza desde el hook de client (salix)';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='información proporcionada por Informa, se actualiza desde el hook de client (salix)';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -24670,7 +28667,7 @@ CREATE TABLE `clientItemType` (
KEY `clientItemType_FK_1` (`itemTypeFk`),
CONSTRAINT `clientItemType_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientItemType_FK_1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='son familias de productos que se quieren sustraer a la oferta del cliente';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='son familias de productos que se quieren sustraer a la oferta del cliente';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -24696,9 +28693,8 @@ CREATE TABLE `clientLog` (
KEY `userFk` (`userFk`),
KEY `clientLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `clientLog_clientLog` (`originFk`,`creationDate`),
- CONSTRAINT `clientLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -24754,72 +28750,8 @@ CREATE TABLE `clientObservation` (
CONSTRAINT `clientObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `clientObservation_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientObservation_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a un ticket';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a un ticket';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientObservation_beforeInsert`
- BEFORE INSERT ON `clientObservation`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientObservation_beforeUpdate`
- BEFORE UPDATE ON `clientObservation`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientObservation_afterDelete`
- AFTER DELETE ON `clientObservation`
- FOR EACH ROW
-BEGIN
- INSERT INTO clientLog
- SET `action` = 'delete',
- `changedModel` = 'ClientObservation',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `clientPackagingGifts`
@@ -24861,11 +28793,8 @@ DROP TABLE IF EXISTS `clientProtected`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientProtected` (
`clientFk` int(11) NOT NULL,
- `workerFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`clientFk`),
- KEY `clientProtected_fk2_idx` (`workerFk`),
- CONSTRAINT `clientProtected_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `clientProtected_fk2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+ CONSTRAINT `clientProtected_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de clientes y comerciales que no se van a ver afectados por las desagsignaciones mensuales automaticas';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -24896,7 +28825,7 @@ DROP TABLE IF EXISTS `clientSample`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientSample` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `clientFk` int(10) unsigned NOT NULL,
+ `clientFk` int(11) NOT NULL,
`typeFk` int(10) unsigned NOT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp(),
`workerFk` int(10) unsigned NOT NULL,
@@ -24907,74 +28836,12 @@ CREATE TABLE `clientSample` (
PRIMARY KEY (`id`),
KEY `empresa_id` (`companyFk`),
KEY `clientSample_fk_editor` (`editorFk`),
+ KEY `clientSample_FK` (`clientFk`),
CONSTRAINT `clientSampleCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `clientSample_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientSample_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientSample_beforeInsert`
- BEFORE INSERT ON `clientSample`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientSample_beforeUpdate`
- BEFORE UPDATE ON `clientSample`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientSample_afterDelete`
- AFTER DELETE ON `clientSample`
- FOR EACH ROW
-BEGIN
- INSERT INTO clientLog
- SET `action` = 'delete',
- `changedModel` = 'ClientSample',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `clientSms`
@@ -24987,12 +28854,15 @@ CREATE TABLE `clientSms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`clientFk` int(11) NOT NULL,
`smsFk` mediumint(8) unsigned NOT NULL,
+ `ticketFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `clientSms_FK` (`clientFk`),
KEY `clientSms_FK_1` (`smsFk`),
+ KEY `clientSms_FK_2` (`ticketFk`),
CONSTRAINT `clientSms_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `clientSms_FK_1` FOREIGN KEY (`smsFk`) REFERENCES `sms` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ CONSTRAINT `clientSms_FK_1` FOREIGN KEY (`smsFk`) REFERENCES `sms` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `clientSms_FK_2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25003,13 +28873,13 @@ DROP TABLE IF EXISTS `clientType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientType` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
+ `id__` int(11) NOT NULL COMMENT '@deprecated 2024-02-20 refs #6784',
`code` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`type` varchar(45) NOT NULL,
`isCreatedAsServed` tinyint(1) DEFAULT 0,
- PRIMARY KEY (`id`),
+ PRIMARY KEY (`code`),
UNIQUE KEY `code_UNIQUE` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Establece categorias para poder agrupar las ventas';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Establece categorias para poder agrupar las ventas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25054,7 +28924,7 @@ DROP TABLE IF EXISTS `cmr`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cmr` (
`id` int(11) NOT NULL AUTO_INCREMENT,
- `ticketFk` int(11) DEFAULT NULL COMMENT 'refs #6092 @toDeprecate 2023-08-02',
+ `ticketFk__` int(11) DEFAULT NULL COMMENT '@deprecated 2023-10-20 refs #6092',
`truckPlate` varchar(30) DEFAULT NULL,
`observations` varchar(255) DEFAULT NULL,
`senderInstruccions` varchar(255) DEFAULT NULL,
@@ -25071,40 +28941,18 @@ CREATE TABLE `cmr` (
`landed` datetime DEFAULT NULL COMMENT 'Hora de llegada a destino',
`ead` datetime DEFAULT NULL COMMENT 'Estimated Arriving Date',
PRIMARY KEY (`id`),
- KEY `cmr_fk1_idx` (`ticketFk`),
+ KEY `cmr_fk1_idx` (`ticketFk__`),
KEY `cmr_fk2_idx` (`companyFk`),
KEY `cmr_fk3_idx` (`addressToFk`),
KEY `cm_fk4_idx` (`supplierFk`),
KEY `cmr_FK` (`addressFromFk`),
CONSTRAINT `cmrCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `cmr_FK` FOREIGN KEY (`addressFromFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`),
+ CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk__`) REFERENCES `ticket` (`id`),
CONSTRAINT `cmr_fk3` FOREIGN KEY (`addressToFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `cmr_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`cmr_beforeDelete`
- BEFORE DELETE ON `cmr`
- FOR EACH ROW
-BEGIN
- IF NOT (OLD.companyFk <=> NULL AND OLD.addressFromFk <=> NULL AND OLD.packagesList <=> NULL) THEN
- CALL util.throw("Can not delete cmr, fields required not empty");
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `cmrConfig`
@@ -25139,51 +28987,6 @@ CREATE TABLE `cmrPallet` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='relaciona los cmr con los pallets de expediciones';
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Temporary table structure for view `cmr_list`
---
-
-DROP TABLE IF EXISTS `cmr_list`;
-/*!50001 DROP VIEW IF EXISTS `cmr_list`*/;
-SET @saved_cs_client = @@character_set_client;
-SET character_set_client = utf8;
-/*!50001 CREATE VIEW `cmr_list` AS SELECT
- 1 AS `cmrFk`,
- 1 AS `ticketFk`,
- 1 AS `truckPlate`,
- 1 AS `observations`,
- 1 AS `senderInstruccions`,
- 1 AS `paymentInstruccions`,
- 1 AS `specialAgreements`,
- 1 AS `created`,
- 1 AS `packagesList`,
- 1 AS `clientName`,
- 1 AS `clientPostalCode`,
- 1 AS `clientStreet`,
- 1 AS `clientCity`,
- 1 AS `clientProvince`,
- 1 AS `clientCountry`,
- 1 AS `companyName`,
- 1 AS `companyStreet`,
- 1 AS `companyPostCode`,
- 1 AS `companyCity`,
- 1 AS `companyCountry`,
- 1 AS `warehouseAddress`,
- 1 AS `shipped`,
- 1 AS `clientOficialName`,
- 1 AS `supplierFk`,
- 1 AS `carrierName`,
- 1 AS `carrierStreet`,
- 1 AS `carrierPostCode`,
- 1 AS `carrierCity`,
- 1 AS `carrierCountry`,
- 1 AS `phone`,
- 1 AS `mobile`,
- 1 AS `addressFk`,
- 1 AS `stamp`,
- 1 AS `merchandiseDetail` */;
-SET character_set_client = @saved_cs_client;
-
--
-- Table structure for table `collection`
--
@@ -25215,56 +29018,8 @@ CREATE TABLE `collection` (
CONSTRAINT `collection_FK2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `collection_id2` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `ticketCollection` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE`
- BEFORE UPDATE ON `collection`
- FOR EACH ROW
-BEGIN
-
- DECLARE vStateFk INT;
- DECLARE vTotalLines INT;
- DECLARE vPickedLines INT;
-
- IF NEW.saleTotalCount <= NEW.salePickedCount
- AND (NEW.saleTotalCount != OLD.saleTotalCount
- OR NEW.salePickedCount != OLD.salePickedCount)
- THEN
-
- SELECT id INTO vStateFk
- FROM vn.state
- WHERE code = 'PREPARED';
-
- SET NEW.stateFk = vStateFk;
-
- END IF;
-
- IF NEW.saleTotalCount > NEW.salePickedCount
- AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN
-
- SELECT id INTO vStateFk
- FROM vn.state
- WHERE code = 'ON_PREPARATION';
-
- SET NEW.stateFk = vStateFk;
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `collectionColors`
@@ -25284,48 +29039,8 @@ CREATE TABLE `collectionColors` (
UNIQUE KEY `collectionColors_UN` (`shelve`,`wagon`,`trainFk`),
KEY `collectionColors_FK` (`trainFk`),
CONSTRAINT `collectionColors_FK` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los colores para las baldas de las colecciones';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los colores para las baldas de las colecciones';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER vn.collectionColors_beforeInsert
-BEFORE INSERT
-ON collectionColors FOR EACH ROW
-BEGIN
- CALL util.checkHex(NEW.rgb);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collectionColors_beforeUpdate`
- BEFORE UPDATE ON `collectionColors`
- FOR EACH ROW
-BEGIN
- CALL util.checkHex(NEW.rgb);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `collectionHotbed`
@@ -25339,7 +29054,7 @@ CREATE TABLE `collectionHotbed` (
`userFk` int(11) NOT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25362,7 +29077,7 @@ CREATE TABLE `collectionVolumetry` (
KEY `collectionVolumetry_FK_1` (`trainFk`),
CONSTRAINT `collectionVolumetry_FK` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON UPDATE CASCADE,
CONSTRAINT `collectionVolumetry_FK_1` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25374,14 +29089,14 @@ DROP TABLE IF EXISTS `collectionWagon`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collectionWagon` (
`collectionFk` int(11) NOT NULL,
- `wagonFk` int(11) NOT NULL,
+ `wagonFk` varchar(6) NOT NULL,
`position` int(11) unsigned NOT NULL,
PRIMARY KEY (`collectionFk`,`position`),
UNIQUE KEY `collectionWagon_unique` (`collectionFk`,`wagonFk`),
- KEY `collectionWagon_wagon` (`wagonFk`),
- CONSTRAINT `collectionWagon_collection` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `collectionWagon_wagon` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+ KEY `collectionWagon_FK_1` (`wagonFk`),
+ CONSTRAINT `collectionWagon_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `collectionWagon_collection` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25393,16 +29108,18 @@ DROP TABLE IF EXISTS `collectionWagonTicket`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collectionWagonTicket` (
`ticketFk` int(11) NOT NULL,
- `wagonFk` int(11) NOT NULL,
+ `wagonFk` varchar(6) NOT NULL,
`trayFk` int(11) unsigned NOT NULL,
- `side` set('L','R') DEFAULT NULL,
- PRIMARY KEY (`ticketFk`),
- KEY `collectionWagonTicket_wagon` (`wagonFk`),
+ `side` set('L','R') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `rgb` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'Color de la balda',
+ `height` int(11) DEFAULT NULL COMMENT 'altura de la balda',
+ PRIMARY KEY (`ticketFk`,`trayFk`),
KEY `collectionWagonTicket_tray` (`trayFk`),
- CONSTRAINT `collectionWagonTicket_ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `collectionWagonTicket_tray` FOREIGN KEY (`trayFk`) REFERENCES `wagonTypeTray` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `collectionWagonTicket_wagon` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+ KEY `collectionWagonTicket_FK_1` (`wagonFk`),
+ CONSTRAINT `collectionWagonTicket_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `collectionWagonTicket_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `collectionWagonTicket_tray` FOREIGN KEY (`trayFk`) REFERENCES `wagonTypeTray` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25458,7 +29175,7 @@ CREATE TABLE `company` (
`created` timestamp NOT NULL ON UPDATE current_timestamp(),
`clientFk` int(11) DEFAULT NULL,
`sage200Company` int(2) DEFAULT NULL,
- `supplierAccountFk` mediumint(8) unsigned DEFAULT NULL,
+ `supplierAccountFk` mediumint(8) unsigned DEFAULT NULL COMMENT 'Cuenta por defecto para ingresos desde este pais',
`isDefaulter` tinyint(4) NOT NULL DEFAULT 0,
`companyGroupFk` int(11) NOT NULL DEFAULT 1 COMMENT 'usado para calcular los greuges ',
`companyCode` int(2) DEFAULT NULL COMMENT 'Campo para movConta',
@@ -25479,7 +29196,7 @@ CREATE TABLE `company` (
CONSTRAINT `empresa_cliente` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `empresa_fk4` FOREIGN KEY (`supplierAccountFk`) REFERENCES `supplierAccount` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_empresa_grupo` FOREIGN KEY (`companyGroupFk`) REFERENCES `companyGroup` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25493,7 +29210,7 @@ CREATE TABLE `companyGroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25525,6 +29242,93 @@ SET character_set_client = utf8;
1 AS `footnotes` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `comparative`
+--
+
+DROP TABLE IF EXISTS `comparative`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `comparative` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `timePeriod` int(11) DEFAULT NULL,
+ `itemFk` int(11) DEFAULT NULL,
+ `warehouseFk` smallint(6) unsigned DEFAULT NULL,
+ `quantity` int(11) DEFAULT NULL,
+ `price` int(11) DEFAULT NULL,
+ `countryFk` mediumint(8) unsigned DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `comparative_unique` (`timePeriod`,`itemFk`,`warehouseFk`,`countryFk`),
+ KEY `comparativeItem_FK` (`itemFk`),
+ KEY `comparativeWarehouse_FK` (`warehouseFk`),
+ KEY `comparativeCountry_FK` (`countryFk`),
+ CONSTRAINT `comparativeCountry_FK` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`),
+ CONSTRAINT `comparativeItem_FK` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`),
+ CONSTRAINT `comparativeWarehouse_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `comparativeAddConfig`
+--
+
+DROP TABLE IF EXISTS `comparativeAddConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `comparativeAddConfig` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `period` int(10) unsigned DEFAULT NULL COMMENT 'The number of periods to be regressed for insertion in vn.comparative',
+ `week` int(10) unsigned DEFAULT NULL COMMENT 'The number of weeks to exceed for recalculating the last period',
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `comparativeConfig`
+--
+
+DROP TABLE IF EXISTS `comparativeConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `comparativeConfig` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `defaultDayRange` int(10) unsigned DEFAULT NULL COMMENT 'Rango de días predeterminado si no se especifica',
+ `weekRange` int(10) unsigned DEFAULT NULL COMMENT 'La cantidad de semanas que se restarán y sumarán',
+ `maxDayRange` int(10) unsigned DEFAULT NULL COMMENT 'El rango máximo de días antes de utilizar el rango de días predeterminado',
+ `minDayRange` int(10) unsigned DEFAULT NULL COMMENT 'El rango mínimo de días antes de utilizar el rango de días predeterminado',
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `comparativeFilter`
+--
+
+DROP TABLE IF EXISTS `comparativeFilter`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `comparativeFilter` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `userFk` int(10) unsigned NOT NULL,
+ `name` varchar(100) NOT NULL,
+ `buyer` int(11) DEFAULT NULL,
+ `itemFilter` varchar(255) DEFAULT NULL,
+ `isFloramondo` tinyint(4) DEFAULT NULL,
+ `warehouseFk` smallint(6) unsigned DEFAULT NULL,
+ `tintaFk` varchar(100) DEFAULT NULL,
+ `hasType` tinyint(1) DEFAULT 0,
+ `producerFilter` varchar(255) DEFAULT NULL,
+ `supplierFk` int(10) unsigned DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `comparativeFilter_FK` (`userFk`),
+ KEY `comparativeFilter_FK_1` (`warehouseFk`),
+ KEY `comparativeFilter_FK_2` (`supplierFk`),
+ CONSTRAINT `comparativeFilter_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`),
+ CONSTRAINT `comparativeFilter_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`),
+ CONSTRAINT `comparativeFilter_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `comparativeFilterType`
--
@@ -25560,7 +29364,7 @@ CREATE TABLE `component` (
KEY `series_componentes_idx` (`typeFk`),
KEY `comp` (`classRate`),
CONSTRAINT `serie_componente` FOREIGN KEY (`typeFk`) REFERENCES `componentType` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25578,7 +29382,7 @@ CREATE TABLE `componentType` (
`code` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `Serie_UNIQUE` (`type`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Permite organizar de forma ordenada los distintos componentes';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Permite organizar de forma ordenada los distintos componentes';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25592,7 +29396,7 @@ CREATE TABLE `confectionType` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25643,7 +29447,7 @@ CREATE TABLE `config` (
`mainWarehouseFk` smallint(6) unsigned NOT NULL DEFAULT 60,
PRIMARY KEY (`id`),
KEY `fechainv_idx` (`inventoried`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25657,7 +29461,7 @@ CREATE TABLE `contactChannel` (
`id` smallint(6) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Canal por el que nos ha conocido un cliente y se ha dado de';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Canal por el que nos ha conocido un cliente y se ha dado de';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25673,7 +29477,7 @@ CREATE TABLE `continent` (
`code` varchar(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `continent_name_uindex` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='World continents';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='World continents';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25699,7 +29503,7 @@ CREATE TABLE `conveyor` (
PRIMARY KEY (`id`),
KEY `conveyor_fk1_idx` (`typeFk`),
CONSTRAINT `conveyor_fk1` FOREIGN KEY (`typeFk`) REFERENCES `conveyorType` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25715,7 +29519,7 @@ CREATE TABLE `conveyorBuildingClass` (
`priority` int(11) NOT NULL DEFAULT 0,
`weightThreshold` int(11) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de caja para el montaje de pallets';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de caja para el montaje de pallets';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25733,7 +29537,7 @@ CREATE TABLE `conveyorConfig` (
`height` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `itemName_UNIQUE` (`itemName`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25796,7 +29600,24 @@ CREATE TABLE `conveyorType` (
`description` varchar(45) DEFAULT NULL,
`color` int(11) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `coolerPathDetail`
+--
+
+DROP TABLE IF EXISTS `coolerPathDetail`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `coolerPathDetail` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `coolerPathFk` int(11) NOT NULL DEFAULT 1,
+ `hallway` varchar(3) NOT NULL,
+ PRIMARY KEY (`coolerPathFk`,`hallway`),
+ UNIQUE KEY `cooler_path_detail_id_UNIQUE` (`id`),
+ CONSTRAINT `coolerPathDetail_FK` FOREIGN KEY (`coolerPathFk`) REFERENCES `vn2008`.`cooler_path__` (`cooler_path_id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25825,7 +29646,7 @@ CREATE TABLE `country` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`country` varchar(25) NOT NULL,
`CEE` tinyint(1) NOT NULL DEFAULT 1,
- `code` varchar(2) DEFAULT NULL,
+ `code` varchar(2) NOT NULL,
`currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 1,
`politicalCountryFk__` mediumint(8) unsigned DEFAULT NULL COMMENT 'Pais Real(apaño por culpa del España Exento)',
`geoFk` int(11) DEFAULT NULL,
@@ -25836,6 +29657,7 @@ CREATE TABLE `country` (
`a3Code` int(11) DEFAULT NULL COMMENT 'Código país para a3',
`isSocialNameUnique` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
+ UNIQUE KEY `country_unique` (`code`),
KEY `Id_Paisreal` (`politicalCountryFk__`),
KEY `currency_id_fk_idx` (`currencyFk`),
KEY `country_Ix4` (`country`),
@@ -25845,124 +29667,8 @@ CREATE TABLE `country` (
CONSTRAINT `country_FK` FOREIGN KEY (`politicalCountryFk__`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `country_FK_1` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE,
CONSTRAINT `currency_id_fk` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`country_beforeInsert`
- BEFORE INSERT ON `country`
- FOR EACH ROW
-BEGIN
- SET NEW.geoFk = zoneGeo_new('country', NEW.country, NULL);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`country_AFTER_INSERT`
- AFTER INSERT ON `country`
- FOR EACH ROW
-BEGIN
- UPDATE sage.Naciones
- SET countryFk = NEW.id
- WHERE Nacion = NEW.country;
-
- IF ROW_COUNT() = 0 THEN
- CALL mail_insert(
- 'cau@verdnatura.es',
- NULL,
- 'Actualizar tabla sage.Naciones',
- CONCAT('Se ha insertado un nuevo país en la tabla vn.conuntry. Para el correcto funcionamiento del sistema \n\t\t\t\tde contabilidad es necesario actualizar la columna sage.Naciones.countryFk con el valor del nuevo país. \n\t\t\t Hay que buscar el nuevo país: ', NEW.country, ' en la tabla sage.Naciones y actualizar el campo sage.Naciones.countryFk con el valor ', NEW.id)
- );
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`country_beforeUpdate`
- BEFORE UPDATE ON `country`
- FOR EACH ROW
-BEGIN
- -- IF !(OLD.geoFk <=> NEW.geoFk) THEN
- -- CALL zoneGeo_throwNotEditable;
- -- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`country_afterUpdate`
- AFTER UPDATE ON `country`
- FOR EACH ROW
-BEGIN
- IF !(OLD.country <=> NEW.country) THEN
- UPDATE zoneGeo SET `name` = NEW.country
- WHERE id = NEW.geoFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`country_afterDelete`
- AFTER DELETE ON `country`
- FOR EACH ROW
-BEGIN
- CALL zoneGeo_delete(OLD.geoFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `cplusCorrectingType`
@@ -25975,35 +29681,7 @@ CREATE TABLE `cplusCorrectingType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)REPERCUTIDO - DEVENGADO (477)';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26062,34 +29740,6 @@ CREATE TABLE `cplusTerIdNif` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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`
--
@@ -26106,34 +29756,8 @@ CREATE TABLE `creditClassification` (
KEY `creditClassifClientFk_idx` (`client`),
KEY `creditClassifdateEnd_idx` (`dateEnd`),
CONSTRAINT `creditClassifClientFk` FOREIGN KEY (`client`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`creditClassification_beforeUpdate`
- BEFORE UPDATE ON `creditClassification`
- FOR EACH ROW
-BEGIN
- IF NEW.client <> OLD.client THEN
- CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT');
- END IF;
- IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN
- UPDATE `client` c
- SET creditInsurance = NULL WHERE c.id = NEW.client;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `creditInsurance`
@@ -26154,53 +29778,8 @@ CREATE TABLE `creditInsurance` (
KEY `creditInsurance_creditClassificationFk` (`creditClassificationFk`),
CONSTRAINT `CreditInsurance_Fk1` FOREIGN KEY (`creditClassification`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `creditInsurance_creditClassificationFk` FOREIGN KEY (`creditClassificationFk`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalla los clientes que tienen seguro de credito';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalla los clientes que tienen seguro de credito';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`creditInsurance_beforeInsert`
- BEFORE INSERT ON `creditInsurance`
- FOR EACH ROW
-BEGIN
- IF NEW.creditClassificationFk THEN
- SET NEW.creditClassification = NEW.creditClassificationFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`creditInsurance_afterInsert`
- AFTER INSERT ON `creditInsurance`
- FOR EACH ROW
-BEGIN
- UPDATE `client` c
- JOIN vn.creditClassification cc ON cc.client = c.id
- SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `currency`
@@ -26235,7 +29814,7 @@ CREATE TABLE `customsAgent` (
`email` varchar(150) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `nif_UNIQUE` (`nif`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26290,7 +29869,7 @@ CREATE TABLE `delivery` (
PRIMARY KEY (`id`),
KEY `delivery_ticketFk_FK` (`ticketFk`),
CONSTRAINT `delivery_ticketFk_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Informa de los datos geográficos y temporales de las entregas de los repartidores';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Informa de los datos geográficos y temporales de las entregas de los repartidores';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26306,7 +29885,83 @@ CREATE TABLE `deliveryMethod` (
`code` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `deliveryNote`
+--
+
+DROP TABLE IF EXISTS `deliveryNote`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `deliveryNote` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `ref` varchar(45) DEFAULT NULL,
+ `note` varchar(150) DEFAULT NULL,
+ `shipped` date NOT NULL,
+ `landed` date DEFAULT NULL,
+ `amount` double DEFAULT NULL,
+ `supplierFk` int(10) unsigned NOT NULL,
+ `companyFk` int(10) unsigned NOT NULL,
+ `warehouseFk` smallint(6) unsigned NOT NULL,
+ `stateFk` int(11) NOT NULL,
+ `workerFk` int(10) unsigned NOT NULL COMMENT 'Id_Trabajador hace referencia a la persona que ha introducido el albarán',
+ `supervisorFk` int(10) unsigned NOT NULL,
+ `departmentFk` int(11) NOT NULL,
+ `invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
+ `farmingFk` int(10) unsigned DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `fk_albaran_Proveedores_idx` (`supplierFk`),
+ KEY `fk_albaran_empresa1_idx` (`companyFk`),
+ KEY `fk_albaran_warehouse1_idx` (`warehouseFk`),
+ KEY `fk_albaran_albaran_state1_idx` (`stateFk`),
+ KEY `fk_albaran_Trabajadores1_idx` (`workerFk`),
+ KEY `fk_albaran_Trabajadores2_idx` (`supervisorFk`),
+ KEY `fk_albaran_department1_idx` (`departmentFk`),
+ KEY `fk_albaran_recibida_idx` (`invoiceInFk`),
+ KEY `albaran_FK` (`farmingFk`),
+ CONSTRAINT `albaranCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `albaran_FK` FOREIGN KEY (`farmingFk`) REFERENCES `farming` (`id`),
+ CONSTRAINT `albaran_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `fk_albaran_Trabajadores1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `fk_albaran_Trabajadores2` FOREIGN KEY (`supervisorFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `fk_albaran_albaran_state1` FOREIGN KEY (`stateFk`) REFERENCES `deliveryNoteState` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `fk_albaran_recibida` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT `fk_albaran_warehouse1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `deliveryNoteDms`
+--
+
+DROP TABLE IF EXISTS `deliveryNoteDms`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `deliveryNoteDms` (
+ `dmsFk` int(11) NOT NULL,
+ `deliveryNoteFk` int(11) NOT NULL,
+ PRIMARY KEY (`dmsFk`,`deliveryNoteFk`),
+ KEY `fk_albaran_gestdoc_gestdoc1_idx` (`dmsFk`),
+ KEY `fk_albaran_gestdoc_albaran1_idx` (`deliveryNoteFk`),
+ CONSTRAINT `albaran_gestdoc_FK` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `fk_albaran_gestdoc_albaran1` FOREIGN KEY (`deliveryNoteFk`) REFERENCES `deliveryNote` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `deliveryNoteState`
+--
+
+DROP TABLE IF EXISTS `deliveryNoteState`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `deliveryNoteState` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `state` varchar(45) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26321,7 +29976,7 @@ CREATE TABLE `deliveryPoint` (
`name` varchar(45) NOT NULL,
`ubication` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26351,7 +30006,7 @@ CREATE TABLE `delivery_zip` (
KEY `postal_code_idx` (`postal_code`),
KEY `admin_name3_idx` (`admin_name3`),
KEY `admin_name2_idx` (`admin_name2`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26384,6 +30039,8 @@ CREATE TABLE `department` (
`hasToMistake` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si al departamento pueden serles puestos errores',
`clientFk` int(11) DEFAULT NULL COMMENT 'Cuenta de cliente que se utiliza para los compras de consumo departamental',
`twoFactor` enum('email') DEFAULT NULL COMMENT 'Default user two-factor auth type',
+ `pbxQueue` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `workerActivityTypeFk` varchar(20) DEFAULT NULL COMMENT 'Indica la actitividad que desempeña por defecto ese departamento',
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`),
KEY `fk_department_Trabajadores1_idx` (`workerFk`),
@@ -26391,111 +30048,15 @@ CREATE TABLE `department` (
KEY `lft_rgt_depth_idx` (`lft`,`rgt`,`depth`),
KEY `department_FK` (`clientFk`),
KEY `department_FK_1` (`parentFk`),
+ KEY `department_queue_FK` (`pbxQueue`),
+ KEY `department_workerActivityType_FK` (`workerActivityTypeFk`),
CONSTRAINT `department_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `department_FK_1` FOREIGN KEY (`parentFk`) REFERENCES `department` (`id`),
+ CONSTRAINT `department_queue_FK` FOREIGN KEY (`pbxQueue`) REFERENCES `pbx`.`queue` (`name`) ON UPDATE CASCADE,
+ CONSTRAINT `department_workerActivityType_FK` FOREIGN KEY (`workerActivityTypeFk`) REFERENCES `workerActivityType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_department_Trabajadores1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`department_beforeInsert`
- BEFORE INSERT ON `department`
- FOR EACH ROW
-BEGIN
- UPDATE vn.department_recalc SET isChanged = TRUE;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`department_afterUpdate`
- AFTER UPDATE ON `department`
- FOR EACH ROW
-BEGIN
- IF !(OLD.parentFk <=> NEW.parentFk) THEN
- UPDATE vn.department_recalc SET isChanged = TRUE;
- END IF;
-
- IF !(OLD.twoFactor <=> NEW.twoFactor) THEN
- UPDATE account.user u
- JOIN vn.workerDepartment wd ON wd.workerFk = u.id
- SET u.twoFactor = NEW.twoFactor
- WHERE wd.departmentFk = NEW.id;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`department_beforeDelete`
- BEFORE DELETE ON `department`
- FOR EACH ROW
-BEGIN
-
- UPDATE vn.business b
- JOIN vn.department d ON d.id = b.departmentFk
- SET b.departmentFk = d.parentFk
- WHERE b.departmentFk = OLD.id;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`department_afterDelete`
- AFTER DELETE ON `department`
- FOR EACH ROW
-BEGIN
-
- UPDATE vn.department_recalc SET isChanged = TRUE;
-
- UPDATE vn.business b
- JOIN vn.department d ON d.id = b.departmentFk
- SET b.departmentFk = d.parentFk
- WHERE b.departmentFk = OLD.id;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `departmentTree`
@@ -26521,7 +30082,7 @@ CREATE TABLE `department_recalc` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`isChanged` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26539,7 +30100,7 @@ CREATE TABLE `device` (
PRIMARY KEY (`id`),
KEY `device_fk1_idx` (`userFk`),
CONSTRAINT `device_fk1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26560,7 +30121,7 @@ CREATE TABLE `deviceLog` (
PRIMARY KEY (`id`),
KEY `deviceLog_FK` (`userFk`),
CONSTRAINT `deviceLog_FK` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26594,72 +30155,8 @@ CREATE TABLE `deviceProduction` (
CONSTRAINT `deviceProduction_FK` FOREIGN KEY (`stateFk`) REFERENCES `deviceProductionState` (`code`),
CONSTRAINT `deviceProduction_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `deviceProduction_CHECK` CHECK (`android_id` regexp '[A-Za-z0-9]{16,}' or `android_id` is null)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProduction_beforeInsert`
- BEFORE INSERT ON `deviceProduction`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProduction_beforeUpdate`
- BEFORE UPDATE ON `deviceProduction`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProduction_afterDelete`
- AFTER DELETE ON `deviceProduction`
- FOR EACH ROW
-BEGIN
- INSERT INTO deviceProductionLog
- SET `action` = 'delete',
- `changedModel` = 'DeviceProduction',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `deviceProductionConfig`
@@ -26673,33 +30170,8 @@ CREATE TABLE `deviceProductionConfig` (
`isAllUsersallowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Permite que cualquier usuario pueda loguearse',
`isTractorHuntingMode` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Habilita el modo cazador para usuarios que no se han logeado un tractor para sacar',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionConfig_afterUpdate`
- AFTER UPDATE ON `deviceProductionConfig`
- FOR EACH ROW
-BEGIN
- IF NEW.isAllUsersAllowed = 1 OR NEW.isAllUsersAllowed = -1 THEN
- SET @username := (SELECT account.myUser_getName());
- INSERT INTO vn.mail (receiver, subject, body)
- VALUES ('cau@verdnatura.es', 'Se ha activado la autenticación sin restricciones en la app',
- CONCAT('El usuario ', @username,' ha habilitado la opción para que todos los usuarios puedan acceder a la app sin restricciones'));
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `deviceProductionLog`
@@ -26724,9 +30196,8 @@ CREATE TABLE `deviceProductionLog` (
KEY `userFk` (`userFk`),
KEY `deviceProductionLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `deviceProductionLog_deviceProductionLog` (`originFk`,`creationDate`),
- CONSTRAINT `deviceProductionOriginFk` FOREIGN KEY (`originFk`) REFERENCES `deviceProduction` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `deviceProductionUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26744,46 +30215,6 @@ CREATE TABLE `deviceProductionModels` (
CONSTRAINT `deviceProductionModels_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionModels_beforeInsert`
- BEFORE INSERT ON `deviceProductionModels`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionModels_beforeUpdate`
- BEFORE UPDATE ON `deviceProductionModels`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `deviceProductionState`
@@ -26801,46 +30232,6 @@ CREATE TABLE `deviceProductionState` (
CONSTRAINT `deviceProductionState_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionState_beforeInsert`
- BEFORE INSERT ON `deviceProductionState`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionState_beforeUpdate`
- BEFORE UPDATE ON `deviceProductionState`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `deviceProductionUser`
@@ -26863,70 +30254,6 @@ CREATE TABLE `deviceProductionUser` (
CONSTRAINT `deviceProductionUser_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionUser_beforeInsert`
- BEFORE INSERT ON `deviceProductionUser`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionUser_beforeUpdate`
- BEFORE UPDATE ON `deviceProductionUser`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionUser_afterDelete`
- AFTER DELETE ON `deviceProductionUser`
- FOR EACH ROW
-BEGIN
- INSERT INTO deviceProductionLog
- SET `action` = 'delete',
- `changedModel` = 'DeviceProductionUser',
- `changedModelId` = OLD.deviceProductionFk,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `disabilityGrade`
@@ -26939,7 +30266,7 @@ CREATE TABLE `disabilityGrade` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Grados de discapacidad Modelo 145 IRPF',
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -26972,115 +30299,27 @@ CREATE TABLE `dms` (
CONSTRAINT `dms_dmsTypeFk` FOREIGN KEY (`dmsTypeFk`) REFERENCES `dmsType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `dms_warehouseFk` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `dms_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='document managment system';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='document managment system';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeInsert`
- BEFORE INSERT ON `dms`
- FOR EACH ROW
-BEGIN
- DECLARE vHardCopyNumber INT;
- DECLARE vDmsTypeCode INT;
- IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN
- CALL util.throw('this warehouse has not dms');
- END IF;
+--
+-- Table structure for table `dmsStorageBox`
+--
- IF NEW.hasFile THEN
- SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber
- FROM dms
- WHERE warehouseFk = NEW.warehouseFk;
-
- SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1);
- END IF;
-
- SELECT code INTO vDmsTypeCode
- FROM dmsType WHERE NEW.dmsTypeFk = id;
- IF (vDmsTypeCode ='ticket') THEN
- UPDATE ticket SET isSigned = 1 WHERE id = NEW.reference;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate`
- BEFORE UPDATE ON `dms`
- FOR EACH ROW
-BEGIN
- DECLARE vHardCopyNumber INT;
-
- IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL)
- OR
- (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN
-
- IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN
- SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi');
- END IF;
-
- SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber
- FROM dms
- WHERE warehouseFk = NEW.warehouseFk;
-
- SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1);
- END IF;
-
- IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN
-
- SET NEW.hasFile = 0;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeDelete`
- BEFORE DELETE ON `dms`
- FOR EACH ROW
-BEGIN
- DECLARE vCanNotBeDeleted INT;
- SELECT COUNT(*) INTO vCanNotBeDeleted
- FROM dmsType dt
- WHERE NOT (code <=> 'trash')
- AND dt.id = OLD.dmsTypeFk;
-
- IF vCanNotBeDeleted THEN
- CALL util.throw('A dms can not be deleted');
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
+DROP TABLE IF EXISTS `dmsStorageBox`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `dmsStorageBox` (
+ `id` int(11) NOT NULL,
+ `companyFk` int(10) unsigned NOT NULL,
+ `started` bigint(20) NOT NULL,
+ `ended` bigint(20) NOT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`id`,`companyFk`),
+ KEY `dmsStorageBox_company_FK` (`companyFk`),
+ CONSTRAINT `dmsStorageBox_company_FK` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Caja en la que se guardan la documentacion fisica de dms';
+/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `dmsType`
@@ -27091,18 +30330,19 @@ DROP TABLE IF EXISTS `dmsType`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dmsType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
+ `code` varchar(45) NOT NULL,
`name` varchar(45) NOT NULL,
- `path` varchar(255) NOT NULL,
+ `path__` varchar(255) NOT NULL COMMENT '@deprecated 2024-01-08 refs #6410',
`writeRoleFk` int(10) unsigned DEFAULT NULL,
`readRoleFk` int(10) unsigned DEFAULT NULL,
- `code` varchar(45) NOT NULL,
`monthToDelete` int(10) unsigned DEFAULT NULL COMMENT 'Meses en el pasado para ir borrando registros, dejar a null para no borrarlos nunca',
PRIMARY KEY (`id`),
+ UNIQUE KEY `dmsType_unique` (`code`),
KEY `readRoleFk` (`readRoleFk`),
KEY `writeRoleFk` (`writeRoleFk`),
CONSTRAINT `readRoleFk` FOREIGN KEY (`readRoleFk`) REFERENCES `account`.`role` (`id`),
CONSTRAINT `writeRoleFk` FOREIGN KEY (`writeRoleFk`) REFERENCES `account`.`role` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -27137,7 +30377,7 @@ CREATE TABLE `docuware` (
PRIMARY KEY (`id`),
KEY `docuware_FK` (`dmsTypeFk`),
CONSTRAINT `docuware_FK` FOREIGN KEY (`dmsTypeFk`) REFERENCES `dmsType` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -27152,7 +30392,21 @@ CREATE TABLE `docuwareConfig` (
`url` varchar(75) DEFAULT NULL,
`cookie` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `docuwareTablet`
+--
+
+DROP TABLE IF EXISTS `docuwareTablet`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `docuwareTablet` (
+ `tablet` varchar(100) NOT NULL,
+ `description` varchar(255) DEFAULT NULL,
+ PRIMARY KEY (`tablet`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -27165,7 +30419,7 @@ DROP TABLE IF EXISTS `dua`;
CREATE TABLE `dua` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(45) DEFAULT NULL,
- `awbFk` smallint(11) unsigned NOT NULL,
+ `awbFk__` smallint(11) unsigned DEFAULT NULL COMMENT '@Deprecated refs #5871 01/10/2023',
`issued` date DEFAULT NULL,
`operated` date DEFAULT NULL,
`booked` date DEFAULT NULL,
@@ -27176,13 +30430,12 @@ CREATE TABLE `dua` (
`ASIEN` double DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
- KEY `fk_awb_dua_awb_idx` (`awbFk`),
+ KEY `fk_awb_dua_awb_idx` (`awbFk__`),
KEY `fk_dua_gestdoc1_idx` (`gestdocFk`),
KEY `dua_fk4_idx` (`companyFk`),
CONSTRAINT `duaCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `dua_fk1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT `dua_fk2` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ CONSTRAINT `dua_fk1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -27223,7 +30476,7 @@ CREATE TABLE `duaIntrastat` (
KEY `duaIntrastat_fk2_idx` (`duaFk`),
CONSTRAINT `duaIntrastat_fk1` FOREIGN KEY (`intrastatFk`) REFERENCES `intrastat` (`id`) ON UPDATE CASCADE,
CONSTRAINT `duaIntrastat_fk2` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -27243,7 +30496,7 @@ CREATE TABLE `duaInvoiceIn` (
KEY `duaInvoiceIn_fk2_idx` (`invoiceInFk`),
CONSTRAINT `duaInvoiceIn_fk1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `duaInvoiceIn_fk2` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Facturas asociadas a la declaración aduanera, básicamente la del agente transitario';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Facturas asociadas a la declaración aduanera, básicamente la del agente transitario';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -27256,62 +30509,17 @@ DROP TABLE IF EXISTS `duaTax`;
CREATE TABLE `duaTax` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`duaFk` int(11) NOT NULL,
- `supplierFk` int(10) unsigned NOT NULL,
`taxClassFk` tinyint(3) unsigned NOT NULL,
`base` decimal(10,2) NOT NULL,
`rate` decimal(5,2) NOT NULL,
`tax` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_dua_tax_awb_dua1_idx` (`duaFk`),
- KEY `duaTax_fk2_idx` (`supplierFk`),
KEY `duaTax_fk3_idx` (`taxClassFk`),
CONSTRAINT `duaTax_fk1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `duaTax_fk3` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `duaTax_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ CONSTRAINT `duaTax_fk3` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`duaTax_BEFORE_INSERT`
- BEFORE INSERT ON `duaTax`
- FOR EACH ROW
-BEGIN
- SET NEW.rate = duaTax_getRate(NEW.duaFk, NEW.taxClassFk);
- SET NEW.tax = NEW.base * NEW.rate / 100;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`duaTax_BEFORE_UPDATE`
- BEFORE UPDATE ON `duaTax`
- FOR EACH ROW
-BEGIN
- SET NEW.rate = duaTax_getRate(NEW.duaFk, NEW.taxClassFk);
- SET NEW.tax = NEW.base * NEW.rate / 100;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `ediGenus`
@@ -27385,48 +30593,8 @@ CREATE TABLE `ektEntryAssign` (
UNIQUE KEY `ektEntryAssign_ix1` (`kop`,`sub`,`pro`),
KEY `ektEntryAssign_FK` (`addressFk`),
CONSTRAINT `ektEntryAssign_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='define las condiciones para asignar entradas a los ekt';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='define las condiciones para asignar entradas a los ekt';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ektEntryAssign_afterInsert
-AFTER INSERT
-ON ektEntryAssign FOR EACH ROW
- UPDATE entry SET reference = NEW.`ref` WHERE id = NEW.entryFk */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER vn.ektEntryAssign_afterUpdate
- AFTER UPDATE ON ektEntryAssign
- FOR EACH ROW
-BEGIN
- IF NOT(NEW.`ref` <=> OLD.`ref`) OR NOT(NEW.`entryFk` <=> OLD.`entryFk`) THEN
- UPDATE entry SET reference = NEW.`ref` WHERE id = NEW.entryFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `ektSubAddress`
@@ -27455,7 +30623,7 @@ CREATE TABLE `emergencyMedia` (
`name` varchar(45) DEFAULT NULL,
`value` varchar(45) DEFAULT NULL COMMENT 'Table to save all emergency phones',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -27550,190 +30718,8 @@ CREATE TABLE `entry` (
CONSTRAINT `entry_ibfk_6` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`) ON UPDATE CASCADE,
CONSTRAINT `entry_observationEditorFk` FOREIGN KEY (`observationEditorFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `entry_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='InnoDB free: 88064 kB; (`Id_Proveedor`) REFER `vn2008/Provee';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='InnoDB free: 88064 kB; (`Id_Proveedor`) REFER `vn2008/Provee';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_beforeInsert`
- BEFORE INSERT ON `entry`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
- CALL supplier_checkIsActive(NEW.supplierFk);
- SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
- SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk);
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_afterInsert`
- AFTER INSERT ON `entry`
- FOR EACH ROW
-BEGIN
- CALL travel_requestRecalc(NEW.travelFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_beforeUpdate`
- BEFORE UPDATE ON `entry`
- FOR EACH ROW
-BEGIN
- DECLARE vIsVirtual BOOL;
- DECLARE vPrintedCount INT;
- DECLARE vHasDistinctWarehouses BOOL;
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF !(NEW.travelFk <=> OLD.travelFk) THEN
- SELECT COUNT(*) > 0 INTO vIsVirtual
- FROM entryVirtual WHERE entryFk = NEW.id;
-
- SELECT !(o.warehouseInFk <=> n.warehouseInFk)
- OR !(o.warehouseOutFk <=> n.warehouseOutFk)
- INTO vHasDistinctWarehouses
- FROM travel o, travel n
- WHERE o.id = OLD.travelFk
- AND n.id = NEW.travelFk;
-
- IF vIsVirtual AND vHasDistinctWarehouses THEN
- SIGNAL SQLSTATE '45000'
- SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses';
- END IF;
-
- IF NEW.travelFk IS NULL THEN
- SELECT COUNT(*) INTO vPrintedCount
- FROM buy
- WHERE entryFk = OLD.id
- AND printedStickers > 0;
-
- IF vPrintedCount > 0 THEN
- SIGNAL SQLSTATE '45000'
- SET MESSAGE_TEXT = 'An entry that contains lines with printed labels cannot be deleted';
- END IF;
- END IF;
- END IF;
-
- IF NOT (NEW.supplierFk <=> OLD.supplierFk) THEN
- CALL supplier_checkIsActive(NEW.supplierFk);
- SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
- END IF;
-
- IF NOT (NEW.travelFk <=> OLD.travelFk)
- OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN
- SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_afterUpdate`
- AFTER UPDATE ON `entry`
- FOR EACH ROW
-BEGIN
- IF NOT(NEW.id <=> OLD.id)
- OR NOT(NEW.travelFk <=> OLD.travelFk)
- OR NOT(NEW.isRaid <=> OLD.isRaid) THEN
- CALL stock.log_add('entry', NEW.id, OLD.id);
- END IF;
-
- IF NOT (NEW.travelFk <=> OLD.travelFk) THEN
- CALL travel_requestRecalc(OLD.travelFk);
- CALL travel_requestRecalc(NEW.travelFk);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_beforeDelete`
- BEFORE DELETE ON `entry`
- FOR EACH ROW
-BEGIN
- DELETE FROM buy WHERE entryFk = OLD.id;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_afterDelete`
- AFTER DELETE ON `entry`
- FOR EACH ROW
-BEGIN
- INSERT INTO entryLog
- SET `action` = 'delete',
- `changedModel` = 'Entry',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-
- CALL travel_requestRecalc(OLD.travelFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `entryConfig`
@@ -27752,6 +30738,26 @@ CREATE TABLE `entryConfig` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `entryDms`
+--
+
+DROP TABLE IF EXISTS `entryDms`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `entryDms` (
+ `entryFk` int(11) NOT NULL,
+ `dmsFk` int(11) NOT NULL,
+ `editorFk` int(10) unsigned DEFAULT NULL,
+ PRIMARY KEY (`entryFk`,`dmsFk`),
+ KEY `gestdoc_id` (`dmsFk`),
+ KEY `entryDms_editor` (`editorFk`),
+ CONSTRAINT `entryDms_dms` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `entryDms_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
+ CONSTRAINT `entryDms_entry` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `entryLog`
--
@@ -27775,9 +30781,8 @@ CREATE TABLE `entryLog` (
KEY `entryLog_ibfk_2` (`userFk`),
KEY `entryLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `entryLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `entryLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `entryLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -27790,7 +30795,7 @@ DROP TABLE IF EXISTS `entryObservation`;
CREATE TABLE `entryObservation` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`entryFk` int(11) NOT NULL,
- `observationTypeFk` tinyint(3) unsigned DEFAULT NULL,
+ `observationTypeFk` tinyint(3) unsigned NOT NULL,
`description` text DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
@@ -27798,74 +30803,25 @@ CREATE TABLE `entryObservation` (
KEY `observationType_id_observationTypeFk` (`observationTypeFk`),
KEY `entryObservation_fk_editor` (`editorFk`),
CONSTRAINT `entryObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
- CONSTRAINT `entry_id_entryFk` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`),
+ CONSTRAINT `entry_id_entryFk` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `observationType_id_observationTypeFk` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `entryOrder`
+--
+
+DROP TABLE IF EXISTS `entryOrder`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `entryOrder` (
+ `entryFk` int(11) NOT NULL,
+ `order` int(11) NOT NULL DEFAULT 1 COMMENT '1.- Ordenar por articulo\n2.- Ordenar por compra\n',
+ PRIMARY KEY (`entryFk`),
+ CONSTRAINT `entradas_entradas_orden` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entryObservation_beforeInsert`
- BEFORE INSERT ON `entryObservation`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entryObservation_beforeUpdate`
- BEFORE UPDATE ON `entryObservation`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entryObservation_afterDelete`
- AFTER DELETE ON `entryObservation`
- FOR EACH ROW
-BEGIN
- INSERT INTO entryLog
- SET `action` = 'delete',
- `changedModel` = 'EntryObservation',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `entryType`
@@ -27926,7 +30882,7 @@ CREATE TABLE `envialiaCity` (
PRIMARY KEY (`id`),
KEY `agencyFk` (`agencyFk`),
KEY `postalCode` (`postalCode`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -27962,32 +30918,7 @@ CREATE TABLE `errorLogApp` (
`date` datetime DEFAULT NULL,
`workerFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Guarda un registro de errores e la app de almacén';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
---
--- Table structure for table `errorProduction`
---
-
-DROP TABLE IF EXISTS `errorProduction`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `errorProduction` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `userFk` int(11) DEFAULT NULL,
- `firstname` varchar(100) DEFAULT NULL,
- `lastname` varchar(100) DEFAULT NULL,
- `rol` varchar(100) DEFAULT NULL,
- `ticketNumber` int(11) DEFAULT NULL,
- `lineNumber` int(11) DEFAULT NULL,
- `error` int(11) DEFAULT NULL,
- `volume` double DEFAULT NULL,
- `hourStart` varchar(100) DEFAULT NULL,
- `hourEnd` varchar(100) DEFAULT NULL,
- `hourWorked` varchar(100) DEFAULT NULL,
- `dated` date DEFAULT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Guarda un registro de errores e la app de almacén';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -28011,7 +30942,53 @@ CREATE TABLE `erte` (
`saturday` tinyint(1) DEFAULT NULL,
`sunday` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Temporary table structure for view `especialPrice`
+--
+
+DROP TABLE IF EXISTS `especialPrice`;
+/*!50001 DROP VIEW IF EXISTS `especialPrice`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `especialPrice` AS SELECT
+ 1 AS `id`,
+ 1 AS `clientFk`,
+ 1 AS `itemFk`,
+ 1 AS `value` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Table structure for table `exchangeInsurance`
+--
+
+DROP TABLE IF EXISTS `exchangeInsurance`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `exchangeInsurance` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `amount` decimal(10,2) NOT NULL,
+ `dated` date NOT NULL,
+ `dueDated` date NOT NULL,
+ `entityFk` int(10) unsigned NOT NULL,
+ `ref` varchar(45) DEFAULT NULL,
+ `rate` decimal(10,4) NOT NULL,
+ `companyFk` int(10) unsigned NOT NULL DEFAULT 442,
+ `financialProductTypefk` varchar(2) NOT NULL DEFAULT 'SC',
+ `pago_sdccol` varchar(45) DEFAULT NULL,
+ `upperBarrier` decimal(10,2) DEFAULT NULL,
+ `lowerBarrier` decimal(10,2) DEFAULT NULL,
+ `strike` decimal(10,2) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `empresa_sdc_idx` (`companyFk`),
+ KEY `financial_type_fk_idx` (`financialProductTypefk`),
+ KEY `pago_sdc_entity_fk_idx` (`entityFk`),
+ CONSTRAINT `financial_type_fk` FOREIGN KEY (`financialProductTypefk`) REFERENCES `financialProductType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `pago_sdcCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `pago_sdc_entity_fk` FOREIGN KEY (`entityFk`) REFERENCES `bankEntity` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Seguros de cambio';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -28042,6 +31019,20 @@ SET character_set_client = utf8;
1 AS `rate` */;
SET character_set_client = @saved_cs_client;
+--
+-- Temporary table structure for view `exchangeInsuranceInPrevious`
+--
+
+DROP TABLE IF EXISTS `exchangeInsuranceInPrevious`;
+/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceInPrevious`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `exchangeInsuranceInPrevious` AS SELECT
+ 1 AS `dated`,
+ 1 AS `amount`,
+ 1 AS `rate` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Temporary table structure for view `exchangeInsuranceOut`
--
@@ -28056,6 +31047,25 @@ SET character_set_client = utf8;
1 AS `rate` */;
SET character_set_client = @saved_cs_client;
+--
+-- Temporary table structure for view `exchangeReportSource`
+--
+
+DROP TABLE IF EXISTS `exchangeReportSource`;
+/*!50001 DROP VIEW IF EXISTS `exchangeReportSource`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `exchangeReportSource` AS SELECT
+ 1 AS `dated`,
+ 1 AS `amountIn`,
+ 1 AS `rateIn`,
+ 1 AS `amountOut`,
+ 1 AS `rateOut`,
+ 1 AS `amountEntry`,
+ 1 AS `rateEntry`,
+ 1 AS `rateECB` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Temporary table structure for view `exchangeReportSourcePrevious`
--
@@ -28086,7 +31096,7 @@ CREATE TABLE `excuse` (
`txt` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
`date` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -28113,6 +31123,10 @@ CREATE TABLE `expedition` (
`hasNewRoute` tinyint(1) NOT NULL DEFAULT 0,
`isBox` int(11) GENERATED ALWAYS AS (`freightItemFk`) VIRTUAL COMMENT 'Columna virtual provisional para Salix',
`editorFk` int(10) unsigned DEFAULT NULL,
+ `packingSiteFk` int(11) DEFAULT NULL,
+ `monitorId` varchar(255) DEFAULT NULL,
+ `started` timestamp NOT NULL,
+ `ended` timestamp NOT NULL,
PRIMARY KEY (`id`),
KEY `index1` (`agencyModeFk`),
KEY `index2` (`freightItemFk`),
@@ -28123,131 +31137,17 @@ CREATE TABLE `expedition` (
KEY `workerFk` (`workerFk`),
KEY `expedition_FK` (`stateTypeFk`),
KEY `expedition_fk_editor` (`editorFk`),
+ KEY `expedition_FK_1` (`packingSiteFk`),
CONSTRAINT `expedition_FK` FOREIGN KEY (`stateTypeFk`) REFERENCES `expeditionStateType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `expedition_FK_1` FOREIGN KEY (`packingSiteFk`) REFERENCES `packingSite` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `expedition_fk1` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expedition_fk2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expedition_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expedition_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `expedition_ibfk_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`),
CONSTRAINT `expedition_itemPackingTypeFk` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expedition_beforeInsert`
- BEFORE INSERT ON `expedition`
- FOR EACH ROW
-BEGIN
- DECLARE intcounter INT;
- DECLARE vShipFk INT;
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.freightItemFk IS NOT NULL THEN
-
- UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk;
-
- SELECT IFNULL(MAX(counter),0) +1 INTO intcounter
- FROM expedition e
- INNER JOIN ticket t1 ON e.ticketFk = t1.id
- LEFT JOIN ticketState ts ON ts.ticket = t1.id
- INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped)
- AND t1.warehouseFk = t2.warehouseFk
- WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk
- AND t1.agencyModeFk = t2.agencyModeFk;
-
- SET NEW.`counter` = intcounter;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expedition_beforeUpdate`
- BEFORE UPDATE ON `expedition`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.counter <> OLD.counter THEN
- IF (SELECT COUNT(*) FROM expedition e
- INNER JOIN ticket t1 ON e.ticketFk = t1.id
- INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped)
- WHERE t1.id = NEW.ticketFk AND counter = NEW.counter) > 0 THEN
- SET NEW.id = NULL;
- END IF;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expedition_beforeDelete`
- BEFORE DELETE ON `expedition`
- FOR EACH ROW
-BEGIN
- UPDATE ticket t
- SET packages = (SELECT COUNT(counter)-1
- FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.freightItemFk)
- WHERE t.id = OLD.ticketFk;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expedition_afterDelete`
- AFTER DELETE ON `expedition`
- FOR EACH ROW
-BEGIN
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'Expedition',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `expeditionBoxVol`
@@ -28339,36 +31239,8 @@ CREATE TABLE `expeditionPallet` (
PRIMARY KEY (`id`),
KEY `expeditionPallet_fk1_idx` (`truckFk`),
CONSTRAINT `expeditionPallet_fk1` FOREIGN KEY (`truckFk`) REFERENCES `expeditionTruck` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionPallet_BEFORE_INSERT`
- BEFORE INSERT ON `expeditionPallet`
- FOR EACH ROW
-BEGIN
-
- DECLARE vNewPosition INT;
-
- SELECT MAX(position) + 1 INTO vNewPosition
- FROM vn.expeditionPallet
- WHERE truckFk = NEW.truckFk;
-
- SET NEW.position = IFNULL(vNewPosition,1);
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `expeditionPallet_Print`
@@ -28444,30 +31316,8 @@ CREATE TABLE `expeditionScan` (
CONSTRAINT `expeditionScan_fk1` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expeditionScan_fk2` FOREIGN KEY (`palletFk`) REFERENCES `expeditionPallet` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expeditionScan_fk3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionScan_BEFORE_INSERT`
- BEFORE INSERT ON `expeditionScan`
- FOR EACH ROW
-BEGIN
-
- SET NEW.workerFk = vn.getUser();
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `expeditionScan_Monitor`
@@ -28507,54 +31357,8 @@ CREATE TABLE `expeditionState` (
KEY `expeditionState_FK_1` (`typeFk`),
CONSTRAINT `expeditionState_FK` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expeditionState_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `expeditionStateType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Historico de estados de las expediciones';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Historico de estados de las expediciones';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER expeditionState_BeforeInsert
-BEFORE INSERT
-ON expeditionState FOR EACH ROW
-BEGIN
-
- SET NEW.userFk = account.myUser_getId();
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER expeditionState_AfterInsert
-AFTER INSERT
-ON expeditionState FOR EACH ROW
-BEGIN
-
- UPDATE vn.expedition e
- SET e.stateTypeFk = NEW.typeFk
- WHERE e.id = NEW.expeditionFk;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `expeditionStateType`
@@ -28568,7 +31372,7 @@ CREATE TABLE `expeditionStateType` (
`description` varchar(100) NOT NULL,
`code` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Posibles estados de una expedición';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Posibles estados de una expedición';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -28654,52 +31458,8 @@ CREATE TABLE `expeditionTruck` (
CONSTRAINT `expeditionTruck_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expeditionTruck_FK_2` FOREIGN KEY (`roadmapFk`) REFERENCES `roadmap` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expeditionTruck_FK_3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Distintas paradas que hacen los trocales';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Distintas paradas que hacen los trocales';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionTruck_BEFORE_INSERT`
- BEFORE INSERT ON `expeditionTruck`
- FOR EACH ROW
-BEGIN
-
- SET NEW.description = UCASE(NEW.description);
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionTruck_BEFORE_UPDATE`
- BEFORE UPDATE ON `expeditionTruck`
- FOR EACH ROW
-BEGIN
-
- SET NEW.description = UCASE(NEW.description);
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `expeditionTruck_Control`
@@ -28764,13 +31524,13 @@ SET character_set_client = utf8;
SET character_set_client = @saved_cs_client;
--
--- Table structure for table `expence`
+-- Table structure for table `expense`
--
-DROP TABLE IF EXISTS `expence`;
+DROP TABLE IF EXISTS `expense`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `expence` (
+CREATE TABLE `expense` (
`id` varchar(10) NOT NULL,
`name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`isWithheld` tinyint(4) NOT NULL DEFAULT 0,
@@ -28780,6 +31540,28 @@ CREATE TABLE `expence` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `expenseManual`
+--
+
+DROP TABLE IF EXISTS `expenseManual`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `expenseManual` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `year` int(4) NOT NULL,
+ `month` int(2) NOT NULL,
+ `amount` decimal(10,2) DEFAULT NULL,
+ `companyFk` int(10) unsigned DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `expenseManual_unique` (`expenseFk`,`year`,`month`,`companyFk`),
+ KEY `expenseManual_company_FK` (`companyFk`),
+ CONSTRAINT `expenseManual_company_FK` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `expenseManual_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Sirve para resumir los gastos que se ponen a mano en el contaplus';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `farming`
--
@@ -28802,7 +31584,7 @@ CREATE TABLE `farming` (
KEY `farmingCompany_Fk` (`companyFk`),
CONSTRAINT `farmingCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`),
CONSTRAINT `farming_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -28841,7 +31623,7 @@ CREATE TABLE `farmingInvoiceIn` (
KEY `farmingInvoiceIn_FK_1` (`farmingFk`),
CONSTRAINT `farmingInvoiceIn_FK` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`),
CONSTRAINT `farmingInvoiceIn_FK_1` FOREIGN KEY (`farmingFk`) REFERENCES `farming` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -28861,7 +31643,23 @@ CREATE TABLE `farmingNotes` (
KEY `farmingNotes_FK_1` (`farmingFk`),
CONSTRAINT `farmingNotes_FK` FOREIGN KEY (`id`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `farmingNotes_FK_1` FOREIGN KEY (`farmingFk`) REFERENCES `farming` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `financialProductType`
+--
+
+DROP TABLE IF EXISTS `financialProductType`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `financialProductType` (
+ `id` varchar(2) NOT NULL,
+ `description` varchar(45) NOT NULL,
+ `isAcumulattor` tinyint(4) NOT NULL DEFAULT 0,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `description_UNIQUE` (`description`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Distintos tipos de productos financieros: seguros de cambio, polizas de credito, acumuladores....';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -28877,6 +31675,25 @@ SET character_set_client = utf8;
1 AS `clientFk` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `flight`
+--
+
+DROP TABLE IF EXISTS `flight`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `flight` (
+ `id` varchar(10) NOT NULL,
+ `duration` tinyint(2) unsigned NOT NULL,
+ `flightPath` varchar(20) DEFAULT NULL,
+ `days` varchar(7) DEFAULT NULL,
+ `airlineFk` smallint(2) unsigned DEFAULT NULL,
+ `airportArrivalFk` varchar(3) NOT NULL,
+ `airportDepartureFk` varchar(3) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Temporary table structure for view `floraHollandBuyedItems`
--
@@ -28913,28 +31730,31 @@ CREATE TABLE `floramondoConfig` (
PRIMARY KEY (`id`),
KEY `floramondoConfigWarehouseIn_idx` (`warehouseInFk`),
CONSTRAINT `floramondoConfigWarehouseInFk` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `forecastedBalance`
+--
+
+DROP TABLE IF EXISTS `forecastedBalance`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `forecastedBalance` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `description` varchar(45) DEFAULT NULL,
+ `amount` double NOT NULL DEFAULT 0,
+ `dated` date NOT NULL,
+ `accountingFk` int(11) DEFAULT NULL,
+ `companyFk` int(10) unsigned NOT NULL DEFAULT 442,
+ PRIMARY KEY (`id`),
+ KEY `Fecha_indice` (`dated`),
+ KEY `banco_prevision_idx` (`accountingFk`),
+ KEY `empresa_prevision_idx` (`companyFk`),
+ CONSTRAINT `Saldos_PrevisionCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `banco_prevision` FOREIGN KEY (`accountingFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Aqui ponemos los gastos e ingresos pendientes de introducir ';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`floramondoConfig_AFTER_INSERT`
- AFTER INSERT ON `floramondoConfig`
- FOR EACH ROW
-BEGIN
- CALL util.throw ("Tabla config no permite añadir más registros");
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `franceExpressConfig`
@@ -28947,7 +31767,7 @@ CREATE TABLE `franceExpressConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`path` varchar(100) DEFAULT '\\\\server\\agencies\\franceexpress\\expeditions',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -28963,7 +31783,7 @@ CREATE TABLE `fuelType` (
`code` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -28978,7 +31798,7 @@ CREATE TABLE `gateArea` (
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29014,7 +31834,7 @@ CREATE TABLE `genericAllocation` (
KEY `genericAllocation_longName_IDX` (`longName`) USING BTREE,
KEY `genericAllocation_size_IDX` (`size`) USING BTREE,
CONSTRAINT `genericAllocation_FK` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena los filtros para asignar códigos genéricos a los items';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena los filtros para asignar códigos genéricos a los items';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29029,7 +31849,7 @@ CREATE TABLE `genus` (
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `genus_PK2` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29051,7 +31871,7 @@ CREATE TABLE `glsConfig` (
`weight` int(1) DEFAULT NULL,
`density` int(11) NOT NULL DEFAULT 42,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29081,7 +31901,7 @@ DROP TABLE IF EXISTS `greuge`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `greuge` (
`Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `clientFk` int(10) unsigned NOT NULL,
+ `clientFk` int(11) NOT NULL,
`description` varchar(45) NOT NULL,
`amount` decimal(10,2) NOT NULL,
`shipped` datetime NOT NULL DEFAULT current_timestamp(),
@@ -29099,96 +31919,11 @@ CREATE TABLE `greuge` (
KEY `greuge_fk_editor` (`editorFk`),
CONSTRAINT `Id_Ticket_Greuge_Ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `greuge_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `greuge_FK_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `greuge_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `greuges_type_fk` FOREIGN KEY (`greugeTypeFk`) REFERENCES `greugeType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=COMPACT;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=COMPACT;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`gregue_beforeInsert`
- BEFORE INSERT ON greuge
- FOR EACH ROW
-BEGIN
- IF NEW.userFk IS NULL THEN
- SET NEW.userFk = account.myUser_getId();
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`greuge_beforeInsert`
- BEFORE INSERT ON `greuge`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`greuge_beforeUpdate`
- BEFORE UPDATE ON `greuge`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`greuge_afterDelete`
- AFTER DELETE ON `greuge`
- FOR EACH ROW
-BEGIN
- INSERT INTO clientLog
- SET `action` = 'delete',
- `changedModel` = 'Greuge',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `greugeConfig`
@@ -29204,7 +31939,7 @@ CREATE TABLE `greugeConfig` (
`maxPercentToWrong` decimal(10,2) DEFAULT NULL COMMENT 'Porcentaje del precio del ticket que es considerado error',
`lastNotifyCheck` timestamp NULL DEFAULT NULL COMMENT 'Última ejecución del procedimiento que revisa los greuges anormales',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29219,7 +31954,7 @@ CREATE TABLE `greugeType` (
`name` varchar(45) NOT NULL,
`code` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29254,28 +31989,8 @@ CREATE TABLE `host` (
CONSTRAINT `configHost_FK_4` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `configHost_FK_5` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`),
CONSTRAINT `hostCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`host_beforeUpdate`
- BEFORE UPDATE ON `host`
- FOR EACH ROW
-BEGIN
- SET new.updated = util.VN_NOW();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `improvedGeneralLog`
@@ -29375,6 +32090,39 @@ SET character_set_client = utf8;
1 AS `name` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `integra2`
+--
+
+DROP TABLE IF EXISTS `integra2`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `integra2` (
+ `postCode` varchar(10) NOT NULL,
+ `frequency` decimal(10,2) NOT NULL,
+ `warehouseFk` smallint(6) unsigned NOT NULL,
+ PRIMARY KEY (`postCode`,`frequency`,`warehouseFk`),
+ KEY `postal_code` (`postCode`),
+ KEY `warehouse_id` (`warehouseFk`),
+ CONSTRAINT `integra2_warehouse_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `integra2Province`
+--
+
+DROP TABLE IF EXISTS `integra2Province`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `integra2Province` (
+ `provinceFk` smallint(6) unsigned NOT NULL,
+ `franchise` varchar(65) NOT NULL,
+ PRIMARY KEY (`provinceFk`),
+ CONSTRAINT `integra2_province_id` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `intrastat`
--
@@ -29393,6 +32141,30 @@ CREATE TABLE `intrastat` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `inventoryConfig`
+--
+
+DROP TABLE IF EXISTS `inventoryConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `inventoryConfig` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `maxRecentInventories` int(11) DEFAULT NULL COMMENT 'The maximum number of recent inventories to retain without deletion',
+ `daysInPastForInventory` int(11) DEFAULT NULL COMMENT 'The number of days in the past to consider for inventory calculations',
+ `warehouseOutFk` smallint(6) unsigned DEFAULT NULL COMMENT 'The identifier for the inventory output warehouse',
+ `agencyModeFk` int(11) DEFAULT NULL COMMENT 'The identifier for the default inventory agencyMode',
+ `supplierFk` int(10) unsigned DEFAULT NULL COMMENT 'The identifier for the default inventory supplier',
+ PRIMARY KEY (`id`),
+ KEY `inventoryConfig_supplier_FK` (`supplierFk`),
+ KEY `inventoryConfig_warehouse_FK` (`warehouseOutFk`),
+ KEY `inventoryConfig_agencyMode_FK` (`agencyModeFk`),
+ CONSTRAINT `inventoryConfig_agencyMode_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`),
+ CONSTRAINT `inventoryConfig_supplier_FK` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`),
+ CONSTRAINT `inventoryConfig_warehouse_FK_1` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `inventoryFailure`
--
@@ -29422,7 +32194,7 @@ CREATE TABLE `inventoryFailure` (
CONSTRAINT `inventoryFailure_fk3` FOREIGN KEY (`guiltyFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `inventoryFailure_fk4` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `inventoryFailure_fk5` FOREIGN KEY (`causeFk`) REFERENCES `inventoryFailureCause` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29436,7 +32208,7 @@ CREATE TABLE `inventoryFailureCause` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29450,18 +32222,18 @@ CREATE TABLE `invoiceCorrection` (
`correctingFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificativa',
`correctedFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificada',
`cplusRectificationTypeFk` int(10) unsigned NOT NULL,
- `cplusInvoiceType477Fk` int(10) unsigned NOT NULL,
+ `siiTypeInvoiceOutFk` int(10) unsigned NOT NULL,
`invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3,
PRIMARY KEY (`correctingFk`),
KEY `correctedFk_idx` (`correctedFk`),
KEY `invoiceCorrection_ibfk_1_idx` (`cplusRectificationTypeFk`),
- KEY `cplusInvoiceTyoeFk_idx` (`cplusInvoiceType477Fk`),
+ KEY `cplusInvoiceTyoeFk_idx` (`siiTypeInvoiceOutFk`),
KEY `invoiceCorrectionTypeFk_idx` (`invoiceCorrectionTypeFk`),
CONSTRAINT `corrected_fk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `correcting_fk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `cplusInvoiceTyoeFk` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `invoiceCorrectionType_Fk33` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `invoiceCorrection_ibfk_1` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE
+ CONSTRAINT `cplusRectificationType_FK` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceCorrectionType_FK` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `siiTypeInvoiceOut_FK` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Relacion entre las facturas rectificativas y las rectificadas.';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -29496,7 +32268,7 @@ CREATE TABLE `invoiceCorrectionType` (
`description` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `description_UNIQUE` (`description`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29520,15 +32292,15 @@ CREATE TABLE `invoiceIn` (
`docFk` int(11) DEFAULT NULL,
`booked` date DEFAULT NULL COMMENT 'Fecha de contabilizacion',
`operated` date DEFAULT NULL COMMENT 'Fecha de entrega de la mercancia o el suministro',
- `cplusInvoiceType472Fk` int(10) unsigned DEFAULT 1,
+ `siiTypeInvoiceInFk` int(10) unsigned DEFAULT 1,
`cplusRectificationTypeFk` int(10) unsigned DEFAULT 1,
`cplusSubjectOpFk` int(10) unsigned DEFAULT 1,
`cplusTaxBreakFk` int(10) unsigned DEFAULT 1,
- `cplusTrascendency472Fk` int(10) unsigned DEFAULT 1,
+ `siiTrascendencyInvoiceInFk` int(10) unsigned DEFAULT 1,
`bookEntried` date DEFAULT NULL COMMENT 'Fecha Asiento',
`isVatDeductible` tinyint(1) NOT NULL DEFAULT 1,
`withholdingSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipos de retención SAGE',
- `expenceFkDeductible` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `expenseFkDeductible` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `proveedor_id` (`supplierFk`),
@@ -29539,194 +32311,26 @@ CREATE TABLE `invoiceIn` (
KEY `fecha` (`issued`),
KEY `recibida_ibfk_3_idx` (`cplusSubjectOpFk`),
KEY `recibida_ibfk_4_idx` (`cplusTaxBreakFk`),
- KEY `recibida_ibfk_5_idx` (`cplusInvoiceType472Fk`),
+ KEY `recibida_ibfk_5_idx` (`siiTypeInvoiceInFk`),
KEY `recibida_ibfk_6` (`cplusRectificationTypeFk`),
- KEY `recibida_ibfk_7` (`cplusTrascendency472Fk`),
+ KEY `recibida_ibfk_7` (`siiTrascendencyInvoiceInFk`),
KEY `invoiceIn_withholdingFk_idx` (`withholdingSageFk`),
- KEY `invoiceIn_expenceFkDeductible_idx` (`expenceFkDeductible`),
+ KEY `invoiceIn_expenceFkDeductible_idx` (`expenseFkDeductible`),
KEY `invoiceIn_fk_editor` (`editorFk`),
KEY `invoiceIn_FK` (`currencyFk`),
CONSTRAINT `invoiceInCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_FK` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `invoiceIn_expenceFkDeductible` FOREIGN KEY (`expenceFkDeductible`) REFERENCES `expence` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceIn_expenceFkDeductible` FOREIGN KEY (`expenseFkDeductible`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `invoiceIn_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `invoiceIn_ibfk_5` FOREIGN KEY (`cplusInvoiceType472Fk`) REFERENCES `cplusInvoiceType472` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceIn_ibfk_5` FOREIGN KEY (`siiTypeInvoiceInFk`) REFERENCES `siiTypeInvoiceIn` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_ibfk_6` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `invoiceIn_ibfk_7` FOREIGN KEY (`cplusTrascendency472Fk`) REFERENCES `cplusTrascendency472` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceIn_ibfk_7` FOREIGN KEY (`siiTrascendencyInvoiceInFk`) REFERENCES `siiTrascendencyInvoiceIn` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_withholdingFk` FOREIGN KEY (`withholdingSageFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceIn_bi`
- BEFORE INSERT ON `invoiceIn`
- FOR EACH ROW
-BEGIN
- DECLARE vSerie CHAR(1) DEFAULT 'R';
- DECLARE vNumReceived INT;
- DECLARE vIssuingCountry, vhostCountry INT;
- DECLARE vActive TINYINT;
- DECLARE vWithholdingSageFk INT;
-
- SET NEW.editorFk = account.myUser_getId();
-
- SELECT withholdingSageFk INTO vWithholdingSageFk
- FROM vn.supplier
- WHERE id = NEW.supplierFk;
-
- SET NEW.withholdingSageFk = vWithholdingSageFk;
-
- SELECT countryFk, isActive INTO vIssuingCountry, vActive
- FROM vn.supplier
- WHERE id = NEW.supplierFk;
-
- SELECT countryFk INTO vhostCountry
- FROM vn.supplier
- WHERE id = NEW.companyFk;
-
- IF vActive = 0 THEN
- CALL util.throw('INACTIVE_PROVIDER');
- END IF;
-
- IF (SELECT COUNT(*) FROM vn.invoiceIn
- WHERE supplierRef = NEW.supplierRef
- AND supplierFk = NEW.supplierFk
- AND YEAR(issued) = YEAR(NEW.issued)
- ) THEN
- CALL util.throw('reference duplicated');
- END IF;
-
- SELECT CASE WHEN (SELECT account FROM vn.supplier where id = NEW.supplierFk) LIKE '___3______' THEN 'C'
- WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry
- where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'R'
- WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry
- where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E'
- WHEN (SELECT vIssuingCountry<>vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry
- where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W'
- END INTO vSerie;
-
- SET NEW.serial = IFNULL(vSerie,'R');
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceIn_bu`
- BEFORE UPDATE ON `invoiceIn`
- FOR EACH ROW
-BEGIN
-
- DECLARE vWithholdingSageFk INT;
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF (SELECT COUNT(*) FROM vn.invoiceIn
- WHERE supplierRef = NEW.supplierRef
- AND supplierFk = NEW.supplierFk
- AND YEAR(issued) = YEAR(NEW.issued)
- AND id <> NEW.id
- ) THEN
- CALL util.throw('reference duplicated');
- END IF;
-
- IF NEW.supplierFk != OLD.supplierFk THEN
- CALL supplier_checkIsActive(NEW.supplierFk);
- SELECT withholdingSageFk INTO vWithholdingSageFk
- FROM vn.supplier
- WHERE id = NEW.supplierFk;
- SET NEW.withholdingSageFk = vWithholdingSageFk;
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceIn_au`
- AFTER UPDATE ON `invoiceIn`
- FOR EACH ROW
-BEGIN
-
- IF NEW.issued != OLD.issued
- OR NEW.currencyFk != OLD.currencyFk THEN
-
- UPDATE invoiceInTax iit
- JOIN invoiceIn ii ON ii.id = iit.invoiceInFk
- LEFT JOIN referenceRate rr ON rr.dated = ii.issued
- AND rr.currencyFk = ii.currencyFk
- SET iit.taxableBase = IF(iit.foreignValue IS NULL, iit.taxableBase, iit.foreignValue / rr.value)
- WHERE ii.id = NEW.id;
-
- UPDATE invoiceInDueDay iidd
- JOIN invoiceIn ii ON ii.id = iidd.invoiceInFk
- LEFT JOIN referenceRate rr ON rr.dated = ii.issued
- AND rr.currencyFk = ii.currencyFk
- SET iidd.amount = IF(iidd.foreignValue IS NULL, iidd.amount, iidd.foreignValue / rr.value)
- WHERE ii.id = NEW.id;
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceIn_afterDelete`
- AFTER DELETE ON `invoiceIn`
- FOR EACH ROW
-BEGIN
- INSERT INTO invoiceInLog
- SET `action` = 'delete',
- `changedModel` = 'InvoiceIn',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `invoiceInConfig`
@@ -29741,10 +32345,37 @@ CREATE TABLE `invoiceInConfig` (
`retentionName` varchar(25) NOT NULL,
`sageWithholdingFk` smallint(6) NOT NULL,
`daysAgo` int(10) unsigned DEFAULT 45 COMMENT 'Días en el pasado para mostrar facturas en invoiceIn series en salix',
+ `taxRowLimit` int(11) DEFAULT 4 COMMENT 'Número máximo de líneas de IVA que puede tener una factura',
PRIMARY KEY (`id`),
KEY `invoiceInConfig_sageWithholdingFk` (`sageWithholdingFk`),
CONSTRAINT `invoiceInConfig_sageWithholdingFk` FOREIGN KEY (`sageWithholdingFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `invoiceInCorrection`
+--
+
+DROP TABLE IF EXISTS `invoiceInCorrection`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `invoiceInCorrection` (
+ `correctingFk` mediumint(8) unsigned NOT NULL COMMENT 'Factura rectificativa',
+ `correctedFk` mediumint(8) unsigned NOT NULL COMMENT 'Factura rectificada',
+ `cplusRectificationTypeFk` int(10) unsigned NOT NULL,
+ `siiTypeInvoiceOutFk` int(10) unsigned NOT NULL,
+ `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3,
+ PRIMARY KEY (`correctingFk`),
+ KEY `invoiceInCorrection_correctedFk` (`correctedFk`),
+ KEY `invoiceInCorrection_cplusRectificationTypeFk` (`cplusRectificationTypeFk`),
+ KEY `invoiceInCorrection_siiTypeInvoiceOut` (`siiTypeInvoiceOutFk`),
+ KEY `invoiceInCorrection_invoiceCorrectionTypeFk` (`invoiceCorrectionTypeFk`),
+ CONSTRAINT `invoiceInCorrection_correctedFk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `invoiceInCorrection_correctingFk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `invoiceInCorrection_cplusRectificationTypeFk` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceInCorrection_invoiceCorrectionTypeFk` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceInCorrection_siiTypeInvoiceOut` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29770,116 +32401,8 @@ CREATE TABLE `invoiceInDueDay` (
CONSTRAINT `invoiceInDueDay_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `invoiceInDueDay_ibfk_6` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInDueDay_ibfk_7` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceInDueDay_beforeInsert`
- BEFORE INSERT ON `invoiceInDueDay`
- FOR EACH ROW
-BEGIN
- DECLARE vIsNotified BOOLEAN;
-
- SET NEW.editorFk = account.myUser_getId();
-
- SELECT isNotified INTO vIsNotified
- FROM vn.invoiceIn ii
- JOIN vn.supplier s ON s.id = ii.supplierFk
- JOIN vn.payMethod pm ON pm.id = s.payMethodFk
- WHERE ii.id = NEW.invoiceInFk;
-
- IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified)
- THEN
- CALL mail_insert(
- 'begonya@verdnatura.es',
- 'begonya@verdnatura.es',
- 'Añadido vencimiento en el pasado',
- CONCAT(
- account.myUser_getName(), ' ha añadido un vencimiento de ',
- NEW.amount, '€ en una fecha pasada en la recibida ', NEW.invoiceInFk
- )
- );
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceInDueDay_beforeUpdate`
- BEFORE UPDATE ON `invoiceInDueDay`
- FOR EACH ROW
-BEGIN
- DECLARE vIsNotified BOOLEAN;
-
- SET NEW.editorFk = account.myUser_getId();
-
- SELECT isNotified INTO vIsNotified
- FROM vn.invoiceIn ii
- JOIN vn.supplier s ON s.id = ii.supplierFk
- JOIN vn.payMethod pm ON pm.id = s.payMethodFk
- WHERE ii.id = NEW.invoiceInFk;
-
- IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified)
- THEN
- CALL mail_insert(
- 'begonya@verdnatura.es',
- 'begonya@verdnatura.es',
- 'Añadido vencimiento en el pasado',
- CONCAT(
- account.myUser_getName(), ' ha añadido un vencimiento de ',
- NEW.amount,'€ en una fecha pasada en la recibida ',NEW.invoiceInFk
- )
- );
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceInDueDay_afterDelete`
- AFTER DELETE ON `invoiceInDueDay`
- FOR EACH ROW
-BEGIN
- INSERT INTO invoiceInLog
- SET `action` = 'delete',
- `changedModel` = 'InvoiceInDueDay',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `invoiceInIntrastat`
@@ -29903,7 +32426,7 @@ CREATE TABLE `invoiceInIntrastat` (
KEY `invoiceInIntrastat_FK` (`invoiceInFk`),
CONSTRAINT `invoiceInIntrastat_FK` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE,
CONSTRAINT `invoiceInIntrastat_ibfk_1` FOREIGN KEY (`intrastatFk`) REFERENCES `intrastat` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29929,9 +32452,8 @@ CREATE TABLE `invoiceInLog` (
KEY `userFk` (`userFk`),
KEY `invoiceInLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `invoiceInLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `invoiceInLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceInLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29948,7 +32470,7 @@ CREATE TABLE `invoiceInSage` (
`taxTypeSageFk` smallint(6) NOT NULL,
`transactionTypeSageFk` tinyint(4) NOT NULL,
`isService` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para diferenciar producto de servicio',
- `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`withholdingSageFk` smallint(6) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `invoiceInSafe_unique` (`taxClassFk`,`invoiceInSerialFk`,`isService`,`withholdingSageFk`),
@@ -29957,14 +32479,14 @@ CREATE TABLE `invoiceInSage` (
KEY `invoiceInSage_invoiceInSerialFk` (`invoiceInSerialFk`),
KEY `invoiceInSage_taxTypeSageFk` (`taxTypeSageFk`),
KEY `invoiceInSage_transactionTypeSageFk` (`transactionTypeSageFk`),
- KEY `invoiceInSage_idx` (`expenceFk`),
- CONSTRAINT `invoiceInSage_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE,
+ KEY `invoiceInSage_idx` (`expenseFk`),
+ CONSTRAINT `invoiceInSage_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_invoiceInSerialFk` FOREIGN KEY (`invoiceInSerialFk`) REFERENCES `invoiceInSerial` (`code`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_taxClassFk` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`code`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_withholdingSageFk` FOREIGN KEY (`withholdingSageFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Relaciones de entrelas series de facturas recibidas y sus tipo de IVA con código Iva y codigo de Transación en Sage. Para precontabilizadar facturas recibidas';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Relaciones de entrelas series de facturas recibidas y sus tipo de IVA con código Iva y codigo de Transación en Sage. Para precontabilizadar facturas recibidas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -29999,7 +32521,7 @@ CREATE TABLE `invoiceInTax` (
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`taxCodeFk` int(10) DEFAULT NULL,
`taxableBase` decimal(10,2) NOT NULL,
- `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`foreignValue` decimal(10,2) DEFAULT NULL,
`taxTypeSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipo de IVA SAGE',
`transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Tipo de transacción SAGE',
@@ -30010,79 +32532,15 @@ CREATE TABLE `invoiceInTax` (
KEY `recibida_iva_ibfk_2` (`taxCodeFk`),
KEY `recibida_iva_taxTypeSageFk` (`taxTypeSageFk`),
KEY `invoiceInTax_transactionTypeSageFk_idx` (`transactionTypeSageFk`),
- KEY `invoiceInTax_idx` (`expenceFk`),
+ KEY `invoiceInTax_idx` (`expenseFk`),
KEY `invoiceInTax_fk_editor` (`editorFk`),
- CONSTRAINT `invoiceInTax_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceInTax_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInTax_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `invoiceInTax_ibfk_5` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceInTax_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
CONSTRAINT `recibida_iva_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceInTax_beforeInsert`
- BEFORE INSERT ON `invoiceInTax`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceInTax_beforeUpdate`
- BEFORE UPDATE ON `invoiceInTax`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceInTax_afterDelete`
- AFTER DELETE ON `invoiceInTax`
- FOR EACH ROW
-BEGIN
- INSERT INTO invoiceInLog
- SET `action` = 'delete',
- `changedModel` = 'InvoiceInTax',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `invoiceInTaxBookingAccount`
@@ -30107,7 +32565,7 @@ CREATE TABLE `invoiceInTaxBookingAccount` (
CONSTRAINT `invoiceInTaxBookingAccount_fk1` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceInTaxBookingAccount_fk2` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInTaxBookingAccount_fk3` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -30130,135 +32588,30 @@ CREATE TABLE `invoiceOut` (
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`hasPdf` tinyint(3) unsigned NOT NULL DEFAULT 0,
`booked` date DEFAULT NULL,
- `cplusInvoiceType477Fk` int(10) unsigned NOT NULL DEFAULT 1,
+ `siiTypeInvoiceOutFk` int(10) unsigned NOT NULL DEFAULT 1,
`cplusTaxBreakFk` int(10) unsigned NOT NULL DEFAULT 1,
`cplusSubjectOpFk` int(10) unsigned NOT NULL DEFAULT 1,
- `cplusTrascendency477Fk` int(10) unsigned NOT NULL DEFAULT 1,
+ `siiTrascendencyInvoiceOutFk` int(10) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`,`ref`),
UNIQUE KEY `Id_Factura` (`ref`),
KEY `Id_Banco` (`bankFk`),
KEY `Id_Cliente` (`clientFk`),
KEY `empresa_id` (`companyFk`),
KEY `Fecha` (`issued`),
- KEY `Facturas_ibfk_2_idx` (`cplusInvoiceType477Fk`),
+ KEY `Facturas_ibfk_2_idx` (`siiTypeInvoiceOutFk`),
KEY `Facturas_ibfk_3_idx` (`cplusSubjectOpFk`),
KEY `Facturas_ibfk_4_idx` (`cplusTaxBreakFk`),
- KEY `Facturas_ibfk_5_idx` (`cplusTrascendency477Fk`),
+ KEY `Facturas_ibfk_5_idx` (`siiTrascendencyInvoiceOutFk`),
KEY `Facturas_idx_Vencimiento` (`dued`),
KEY `invoiceOut_serial` (`serial`),
- CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceOut_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceOut_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceOut_serial` FOREIGN KEY (`serial`) REFERENCES `invoiceOutSerial` (`code`),
CONSTRAINT `invoice_bank_id` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoice_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceOut_beforeInsert`
- BEFORE INSERT ON `invoiceOut`
- FOR EACH ROW
-BEGIN
- DECLARE vRef CHAR(10) ;
-
- IF YEAR(NEW.issued) <= 2021 THEN
-
- SELECT CONCAT(NEW.serial,
- IFNULL(RIGHT(MAX(i.ref), LENGTH(i.ref)-1) ,
- RPAD(CONCAT(c.sage200Company, RIGHT(YEAR(util.VN_CURDATE()), 2)), 7,'0')) + 1) INTO vRef
- FROM invoiceOut i
- LEFT JOIN company c ON c.id = i.companyFk
- WHERE i.serial = NEW.serial
- AND i.issued BETWEEN util.firstDayOfYear(NEW.issued) AND util.dayEnd(util.lastDayOfYear(NEW.issued))
- AND c.id = NEW.companyFk;
- ELSE
-
- SELECT CONCAT(NEW.serial,
- IFNULL(RIGHT(MAX(i.ref), LENGTH(i.ref)-1) ,
- RPAD(CONCAT(c.sage200Company, RIGHT(YEAR(util.VN_CURDATE()), 2)), 8,'0')) + 1) INTO vRef
- FROM invoiceOut i
- LEFT JOIN company c ON c.id = i.companyFk
- WHERE i.serial = NEW.serial
- AND i.issued BETWEEN util.firstDayOfYear(NEW.issued) AND util.dayEnd(util.lastDayOfYear(NEW.issued))
- AND c.id = NEW.companyFk;
- END IF;
-
- SET NEW.ref = vRef;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceOut_afterInsert`
- AFTER INSERT ON `invoiceOut`
- FOR EACH ROW
-BEGIN
- CALL clientRisk_update(NEW.clientFk, NEW.companyFk, NEW.amount);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceOut_beforeUpdate`
- BEFORE UPDATE ON `invoiceOut`
- FOR EACH ROW
-BEGIN
-CALL clientRisk_update (OLD.clientFk, OLD.companyFk, -OLD.amount);
-CALL clientRisk_update (NEW.clientFk, NEW.companyFk, NEW.amount);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`invoiceOut_beforeDelete`
- BEFORE DELETE ON `invoiceOut`
- FOR EACH ROW
-BEGIN
- CALL clientRisk_update (OLD.clientFk, OLD.companyFk, -OLD.amount);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `invoiceOutConfig`
@@ -30270,29 +32623,30 @@ DROP TABLE IF EXISTS `invoiceOutConfig`;
CREATE TABLE `invoiceOutConfig` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`parallelism` int(10) unsigned NOT NULL DEFAULT 1,
+ `refLen` tinyint(3) unsigned NOT NULL DEFAULT 5 COMMENT 'Invoice reference identifier length',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `invoiceOutExpence`
+-- Table structure for table `invoiceOutExpense`
--
-DROP TABLE IF EXISTS `invoiceOutExpence`;
+DROP TABLE IF EXISTS `invoiceOutExpense`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `invoiceOutExpence` (
+CREATE TABLE `invoiceOutExpense` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoiceOutFk` int(10) unsigned NOT NULL,
`amount` decimal(10,2) NOT NULL DEFAULT 0.00,
- `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `invoiceOutExpence_FK_1_idx` (`invoiceOutFk`),
- KEY `invoiceOutExpence_expenceFk_idx` (`expenceFk`),
+ KEY `invoiceOutExpence_expenceFk_idx` (`expenseFk`),
CONSTRAINT `invoiceOutExpence_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `invoiceOutExpence_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Desglosa la base imponible de una factura en funcion del tipo de gasto/venta';
+ CONSTRAINT `invoiceOutExpence_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Desglosa la base imponible de una factura en funcion del tipo de gasto/venta';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -30338,7 +32692,7 @@ CREATE TABLE `invoiceOutTax` (
KEY `pgcFk` (`pgcFk`),
CONSTRAINT `invoiceOutFk` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceOutTax_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -30354,15 +32708,17 @@ CREATE TABLE `invoiceOutTaxConfig` (
`taxTypeSageFk` smallint(6) DEFAULT NULL,
`transactionTypeSageFk` tinyint(4) DEFAULT NULL,
`isService` tinyint(1) DEFAULT 0,
- `expenceFk` varchar(10) DEFAULT NULL,
+ `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `invoiceOutTaxConfig_FK` (`taxClassCodeFk`),
KEY `invoiceOutTaxConfig_FK_1` (`taxTypeSageFk`),
KEY `invoiceOutTaxConfig_FK_2` (`transactionTypeSageFk`),
+ KEY `invoiceOutTaxConfig_expense_FK` (`expenseFk`),
CONSTRAINT `invoiceOutTaxConfig_FK` FOREIGN KEY (`taxClassCodeFk`) REFERENCES `taxClass` (`code`),
CONSTRAINT `invoiceOutTaxConfig_FK_1` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`),
- CONSTRAINT `invoiceOutTaxConfig_FK_2` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ CONSTRAINT `invoiceOutTaxConfig_FK_2` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`),
+ CONSTRAINT `invoiceOutTaxConfig_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -30397,7 +32753,7 @@ CREATE TABLE `item` (
`description` varchar(1000) DEFAULT NULL,
`density` int(11) NOT NULL DEFAULT 167 COMMENT 'Almacena la densidad en kg/m3 para el calculo de los portes, si no se especifica se pone por defecto la del tipo en un trigger',
`relevancy` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'La web ordena de forma descendiente por este campo para mostrar los artículos',
- `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '7001000000',
+ `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '7001000000',
`isActive` tinyint(1) NOT NULL DEFAULT 1,
`longName` varchar(50) DEFAULT NULL,
`subName` varchar(50) DEFAULT NULL,
@@ -30422,18 +32778,19 @@ CREATE TABLE `item` (
`numberOfItemsPerCask` int(11) DEFAULT NULL COMMENT 'Campo para Floramondo',
`embalageCode` int(11) DEFAULT NULL COMMENT 'Campo para Floramondo',
`quality` varchar(255) DEFAULT NULL COMMENT 'Campo para Floramondo',
- `stars` int(11) DEFAULT NULL,
`stemMultiplier` double NOT NULL DEFAULT 1 COMMENT 'este valor multiplica las unidades y divide los precios en el procedimiento edi.ekt_load',
`itemPackingTypeFk` varchar(1) DEFAULT NULL,
`packingOut` decimal(10,2) DEFAULT NULL COMMENT 'cantidad que cabe en una caja de verdnatura',
`genericFk` int(11) DEFAULT NULL COMMENT 'Item genérico',
- `packingShelve` int(11) DEFAULT NULL COMMENT 'unidades que caben en una bandeja, en el caso de los sacadores',
+ `packingShelve__` int(11) DEFAULT NULL COMMENT '@deprecated 2024-31-01',
`isLaid` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el producto se puede tumbar a efectos del transporte desde Holanda',
`lastUsed` datetime DEFAULT current_timestamp(),
`weightByPiece` int(10) unsigned DEFAULT NULL COMMENT 'peso por defecto para un articulo por tallo/unidad',
`editorFk` int(10) unsigned DEFAULT NULL,
`recycledPlastic` int(11) DEFAULT NULL,
`nonRecycledPlastic` int(11) DEFAULT NULL,
+ `minQuantity` int(10) unsigned DEFAULT NULL COMMENT 'Cantidad mínima para una línea de venta',
+ `isBoxPickingMode` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'FALSE: using item.packingOut TRUE: boxPicking using itemShelving.packing',
PRIMARY KEY (`id`),
UNIQUE KEY `item_supplyResponseFk_idx` (`supplyResponseFk`),
KEY `Color` (`inkFk`),
@@ -30451,159 +32808,19 @@ CREATE TABLE `item` (
KEY `item_size_IDX` (`size`) USING BTREE,
KEY `item_size_IDX2` (`longName`) USING BTREE,
KEY `item_lastUsed_IDX` (`lastUsed`) USING BTREE,
- KEY `item_expenceFk_idx` (`expenceFk`),
+ KEY `item_expenceFk_idx` (`expenseFk`),
KEY `item_fk_editor` (`editorFk`),
CONSTRAINT `item_FK` FOREIGN KEY (`genericFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `item_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `itemType` (`id`),
- CONSTRAINT `item_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `item_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `item_family` FOREIGN KEY (`family`) REFERENCES `itemFamily` (`code`) ON UPDATE CASCADE,
CONSTRAINT `item_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `item_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `origin` (`id`) ON UPDATE CASCADE,
CONSTRAINT `item_ibfk_2` FOREIGN KEY (`intrastatFk`) REFERENCES `intrastat` (`id`) ON UPDATE CASCADE,
CONSTRAINT `itemsupplyResponseFk` FOREIGN KEY (`supplyResponseFk`) REFERENCES `edi`.`supplyResponse` (`ID`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `producer_id` FOREIGN KEY (`producerFk`) REFERENCES `producer` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_beforeInsert`
- BEFORE INSERT ON `item`
- FOR EACH ROW
-BEGIN
- DECLARE vItemPackingType VARCHAR(1);
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.itemPackingTypeFk IS NULL THEN
- SELECT itemPackingTypeFk INTO vItemPackingType
- FROM vn.itemType it
- WHERE id = NEW.typeFk;
-
- SET NEW.itemPackingTypeFk = vItemPackingType;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_afterInsert`
- AFTER INSERT ON `item`
- FOR EACH ROW
-BEGIN
- CALL hedera.image_ref('catalog', NEW.image);
-
- INSERT INTO vn.itemTaxCountry(itemFk, countryFk) VALUES
- (NEW.id, 1),
- (NEW.id, 5);
-
- DELETE ifr.*
- FROM edi.item_free ifr
- WHERE ifr.id = NEW.id;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_beforeUpdate`
- BEFORE UPDATE ON `item`
- FOR EACH ROW
-BEGIN
- DECLARE vNewPackingShelve INT;
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF ISNULL(NEW.packingShelve) AND NOT ISNULL(NEW.packingOut) THEN
- SELECT NEW.packingOut * vc.shelveVolume / vc.standardFlowerBox
- INTO vNewPackingShelve
- FROM vn.volumeConfig vc;
-
- SET NEW.packingShelve = vNewPackingShelve;
- END IF;
-
- IF NEW.itemPackingTypeFk = '' THEN
- SET NEW.itemPackingTypeFk = NULL;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_afterUpdate`
- AFTER UPDATE ON `item`
- FOR EACH ROW
-BEGIN
- IF !(NEW.image <=> OLD.image) THEN
- CALL hedera.image_unref('catalog', OLD.image);
- CALL hedera.image_ref('catalog', NEW.image);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_afterDelete`
- AFTER DELETE ON `item`
- FOR EACH ROW
-BEGIN
- CALL hedera.image_unref('catalog', OLD.image);
-
- IF OLD.isFloramondo THEN
- INSERT IGNORE edi.item_free
- SET id = OLD.id;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `itemBarcode`
@@ -30624,72 +32841,8 @@ CREATE TABLE `itemBarcode` (
KEY `itemBarcode_fk_editor` (`editorFk`),
CONSTRAINT `itemBarcode_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `itemBarcode_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemBarcode_beforeInsert`
- BEFORE INSERT ON `itemBarcode`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemBarcode_beforeUpdate`
- BEFORE UPDATE ON `itemBarcode`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemBarcode_afterDelete`
- AFTER DELETE ON `itemBarcode`
- FOR EACH ROW
-BEGIN
- INSERT INTO itemLog
- SET `action` = 'delete',
- `changedModel` = 'ItemBarcode',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `itemBotanical`
@@ -30713,70 +32866,6 @@ CREATE TABLE `itemBotanical` (
CONSTRAINT `itemBotanical_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Sustituye a antiguo NomBotanic de Articles';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemBotanical_beforeInsert`
- BEFORE INSERT ON `itemBotanical`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemBotanical_beforeUpdate`
- BEFORE UPDATE ON `itemBotanical`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemBotanical_afterDelete`
- AFTER DELETE ON `itemBotanical`
- FOR EACH ROW
-BEGIN
- INSERT INTO itemLog
- SET `action` = 'delete',
- `changedModel` = 'ItemBotanical',
- `changedModelId` = OLD.itemFk,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `itemBotanicalWithGenus`
@@ -30816,31 +32905,8 @@ CREATE TABLE `itemCategory` (
KEY `itemCategoryDisplayIdx` (`display`),
KEY `itemCategory_FK` (`departmentFk`),
CONSTRAINT `itemCategory_FK` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemCategory_AFTER_INSERT`
- AFTER INSERT ON `itemCategory`
- FOR EACH ROW
-BEGIN
- CALL mail_insert('cau@verdnatura.es',
- NULL,
- CONCAT('Se ha añadido la familia: ', NEW.name),
- 'Hay que añadir la familia en el formulario gastos');
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `itemCategoryI18n`
@@ -30882,7 +32948,7 @@ CREATE TABLE `itemCleanLog` (
`itemDeleted` int(11) DEFAULT NULL COMMENT 'Indica la cantidad de items que ha eliminado',
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -30914,6 +32980,7 @@ CREATE TABLE `itemConfig` (
`validPriorities` varchar(50) NOT NULL DEFAULT '[1,2,3]',
`defaultPriority` int(11) NOT NULL DEFAULT 2,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
+ `downloadMaxAttempts` tinyint(3) DEFAULT NULL COMMENT 'Intentos máximos para que se borre',
PRIMARY KEY (`id`),
KEY `itemConfig_FK` (`defaultTag`),
CONSTRAINT `itemConfig_FK` FOREIGN KEY (`defaultTag`) REFERENCES `tag` (`id`)
@@ -30946,71 +33013,6 @@ CREATE TABLE `itemCost` (
CONSTRAINT `warehouse_id_rotaci` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena los valores de rotacion en los ultimos 365 dias';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemCost_beforeInsert`
- BEFORE INSERT ON `itemCost`
- FOR EACH ROW
-BEGIN
- IF NEW.itemFk IN (95, 98) THEN
- SET NEW.cm3 = 0;
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemCost_beforeUpdate`
- BEFORE UPDATE ON `itemCost`
- FOR EACH ROW
-BEGIN
- IF NEW.itemFk IN (95, 98) THEN
- SET NEW.cm3 = 0;
- END IF;
-
- IF !(NEW.cm3delivery <=> OLD.cm3delivery) THEN
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
- FROM vn.itemCost ic
- JOIN vn.sale s ON s.itemFk = ic.itemFk
- JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk
- JOIN vn.route r ON r.id = t.routeFk
- WHERE r.isOk = FALSE
- AND ic.itemFk = NEW.itemFk
- AND r.created >= util.VN_CURDATE()
- GROUP BY r.id;
- IF NEW.cm3Delivery = 0 AND NEW.warehouseFk = 60 THEN
- CALL mail_insert(
- 'jgallego@verdnatura.es',
- NULL,
- 'update cm3Delivery',
- CONCAT('articulo: ', NEW.itemFk));
- 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 */ ;
--
-- Temporary table structure for view `itemEntryIn`
@@ -31109,7 +33111,7 @@ CREATE TABLE `itemLabel` (
`price` decimal(10,2) DEFAULT NULL,
`labels` int(11) DEFAULT NULL COMMENT 'Tabla hecha para Ruben Espinosa, para sacar etiquetas en Holanda para un cliente.',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -31135,9 +33137,8 @@ CREATE TABLE `itemLog` (
KEY `itemLogUserFk_idx` (`userFk`),
KEY `itemLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `itemLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `itemLogItemFk` FOREIGN KEY (`originFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -31197,7 +33198,7 @@ CREATE TABLE `itemPlacementSupply` (
CONSTRAINT `itemPlacementSupply_fk2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemPlacementSupply_fk3` FOREIGN KEY (`repoUserFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemPlacementSupply_fk4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de nichos de picking que hay que reponer';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de nichos de picking que hay que reponer';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -31290,156 +33291,20 @@ CREATE TABLE `itemShelving` (
`packagingFk` varchar(10) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`isChecked` tinyint(1) DEFAULT NULL COMMENT 'Este valor cambia al escanear un carro. True: Existe. False: Nuevo. Null: No escaneado',
+ `buyFk` int(11) DEFAULT NULL,
+ `editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
+ UNIQUE KEY `itemShelving_UN` (`buyFk`,`shelvingFk`),
KEY `itemShelving_fk1_idx` (`itemFk`),
KEY `itemShelving_fk2_idx` (`shelvingFk`),
KEY `itemShelving_fk3_idx` (`packagingFk`),
KEY `itemShelving_fk3_idx1` (`userFk`),
+ CONSTRAINT `itemShelvingBuy_FK` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`),
CONSTRAINT `itemShelving_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemShelving_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla utilizada para localizar los artículos dentro de los carros. Usado para la gestión del almacén en el altillo ';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla utilizada para localizar los artículos dentro de los carros. Usado para la gestión del almacén en el altillo ';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_INSERT`
- BEFORE INSERT ON `itemShelving`
- FOR EACH ROW
-BEGIN
-
- SET NEW.userFk = account.myUser_getId();
-
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_AFTER_INSERT`
- AFTER INSERT ON `itemShelving`
- FOR EACH ROW
-INSERT INTO vn.itemShelvingLog( itemShelvingFk,
- workerFk,
- accion,
- itemFk,
- shelvingFk,
- visible,
- `grouping`,
- packing)
- VALUES( NEW.id,
- NEW.userFk,
- 'CREA REGISTRO',
- NEW.itemFk,
- NEW.shelvingFk,
- NEW.visible,
- NEW.`grouping`,
- NEW.packing
- ) */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_UPDATE`
- BEFORE UPDATE ON `itemShelving`
- FOR EACH ROW
-BEGIN
- IF NEW.userFk IS NULL THEN
- SET NEW.userFk = account.myUser_getId();
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_AFTER_UPDATE`
- AFTER UPDATE ON `itemShelving`
- FOR EACH ROW
-INSERT INTO vn.itemShelvingLog( itemShelvingFk,
- workerFk,
- accion,
- itemFk,
- shelvingFk,
- visible,
- `grouping`,
- packing)
- VALUES( NEW.id,
- account.myUser_getId(),
- 'CAMBIO',
- NEW.itemFk,
- NEW.shelvingFk,
- NEW.visible,
- NEW.`grouping`,
- NEW.packing
- ) */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_DELETE`
- BEFORE DELETE ON `itemShelving`
- FOR EACH ROW
-INSERT INTO vn.itemShelvingLog(itemShelvingFk,
- workerFk,
- accion,
- shelvingFk,
- itemFk)
- VALUES( OLD.id,
- account.myUser_getId(),
- 'ELIMINADO',
- OLD.shelvingFk,
- OLD.itemFk) */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `itemShelvingAvailable`
@@ -31521,7 +33386,7 @@ CREATE TABLE `itemShelvingLog` (
KEY `itemShelving_Log_FK` (`itemShelvingFk`),
KEY `itemShelvingLog_itemFk_IDX` (`itemFk`) USING BTREE,
KEY `itemShelvingLog_shelvingFk_IDX` (`shelvingFk`) USING BTREE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -31545,7 +33410,7 @@ CREATE TABLE `itemShelvingPlacementSupply` (
KEY `itemShelvingPlacementSupply_fk3_idx` (`userFk`),
CONSTRAINT `itemShelvingPlacementSupply_fk1` FOREIGN KEY (`itemShelvingFk`) REFERENCES `itemShelving` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemShelvingPlacementSupply_fk2` FOREIGN KEY (`itemPlacementSupplyFk`) REFERENCES `itemPlacementSupply` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle de los itemShelving afectados por las ordenes de reposicion de nicho';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle de los itemShelving afectados por las ordenes de reposicion de nicho';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -31586,6 +33451,7 @@ CREATE TABLE `itemShelvingSale` (
`quantity` decimal(10,0) NOT NULL DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`userFk` int(11) unsigned NOT NULL,
+ `isPicked` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `itemShelvingSale_fk1_idx` (`itemShelvingFk`),
KEY `itemShelvingSale_fk2_idx` (`saleFk`),
@@ -31593,32 +33459,8 @@ CREATE TABLE `itemShelvingSale` (
CONSTRAINT `itemShelvingSale_fk1` FOREIGN KEY (`itemShelvingFk`) REFERENCES `itemShelving` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemShelvingSale_fk2` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemShelvingSale_fk3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle del producto que se retira de los carros, relacionando la linea de movimiento correspondiente';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle del producto que se retira de los carros, relacionando la linea de movimiento correspondiente';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelvingSale_AFTER_INSERT`
- AFTER INSERT ON `itemShelvingSale`
- FOR EACH ROW
-BEGIN
-
- UPDATE vn.sale
- SET isPicked = TRUE
- WHERE id = NEW.saleFk;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `itemShelvingSaleSum`
@@ -31701,20 +33543,6 @@ SET character_set_client = utf8;
1 AS `removed` */;
SET character_set_client = @saved_cs_client;
---
--- Temporary table structure for view `itemShelvingStock_byWarehouse`
---
-
-DROP TABLE IF EXISTS `itemShelvingStock_byWarehouse`;
-/*!50001 DROP VIEW IF EXISTS `itemShelvingStock_byWarehouse`*/;
-SET @saved_cs_client = @@character_set_client;
-SET character_set_client = utf8;
-/*!50001 CREATE VIEW `itemShelvingStock_byWarehouse` AS SELECT
- 1 AS `itemFk`,
- 1 AS `visible`,
- 1 AS `warehouseFk` */;
-SET character_set_client = @saved_cs_client;
-
--
-- Table structure for table `itemTag`
--
@@ -31741,144 +33569,8 @@ CREATE TABLE `itemTag` (
CONSTRAINT `itemTagItemFk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemTagTagFk` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`) ON UPDATE CASCADE,
CONSTRAINT `itemTag_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_beforeInsert`
- BEFORE INSERT ON `itemTag`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
- SET NEW.intValue = itemTag_getIntValue(NEW.`value`);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_afterInsert`
- AFTER INSERT ON `itemTag`
- FOR EACH ROW
-trig: BEGIN
- IF @isTriggerDisabled THEN
- LEAVE trig;
- END IF;
-
- CALL item_refreshFromTags(NEW.itemFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_beforeUpdate`
- BEFORE UPDATE ON `itemTag`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF !(OLD.`value` <=> NEW.`value`)
- OR !(OLD.intValue <=> NEW.intValue) THEN
- SET NEW.intValue = itemTag_getIntValue(NEW.`value`);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_afterUpdate`
- AFTER UPDATE ON `itemTag`
- FOR EACH ROW
-trig: BEGIN
- DECLARE vItemFk INT;
- DECLARE visTriggerDisabled BOOL;
-
- SELECT isItemTagTriggerDisabled INTO visTriggerDisabled
- FROM vn.itemConfig;
-
- IF @isTriggerDisabled OR visTriggerDisabled THEN
- LEAVE trig;
- END IF;
-
- SET vItemFk = NEW.itemFk;
- DROP TEMPORARY TABLE IF EXISTS tmp.item;
- CREATE TEMPORARY TABLE tmp.item
- SELECT vItemFk id;
-
- CALL item_refreshTags();
- DROP TEMPORARY TABLE tmp.item;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_afterDelete`
- AFTER DELETE ON `itemTag`
- FOR EACH ROW
-trig: BEGIN
- INSERT INTO itemLog
- SET `action` = 'delete',
- `changedModel` = 'ItemTag',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-
- IF @isTriggerDisabled THEN
- LEAVE trig;
- END IF;
-
- CALL item_refreshFromTags(OLD.itemFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `itemTagged`
@@ -31915,72 +33607,31 @@ CREATE TABLE `itemTaxCountry` (
CONSTRAINT `itemFK_Article` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemTaxCountry_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `taxClassFK_Iva_Group` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define la clase de iva por artículo y pais';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define la clase de iva por artículo y pais';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTaxCountry_beforeInsert`
- BEFORE INSERT ON `itemTaxCountry`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTaxCountry_beforeUpdate`
- BEFORE UPDATE ON `itemTaxCountry`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTaxCountry_afterDelete`
- AFTER DELETE ON `itemTaxCountry`
- FOR EACH ROW
-BEGIN
- INSERT INTO itemLog
- SET `action` = 'delete',
- `changedModel` = 'ItemTaxCountry',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
+
+--
+-- Temporary table structure for view `itemTaxCountrySpain`
+--
+
+DROP TABLE IF EXISTS `itemTaxCountrySpain`;
+/*!50001 DROP VIEW IF EXISTS `itemTaxCountrySpain`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `itemTaxCountrySpain` AS SELECT
+ 1 AS `id`,
+ 1 AS `name`,
+ 1 AS `typeFk`,
+ 1 AS `stems`,
+ 1 AS `description`,
+ 1 AS `intrastatFk`,
+ 1 AS `expenseFk`,
+ 1 AS `comment`,
+ 1 AS `relevancy`,
+ 1 AS `image`,
+ 1 AS `generic`,
+ 1 AS `taxClassFk` */;
+SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `itemTicketOut`
@@ -32053,38 +33704,8 @@ CREATE TABLE `itemType` (
CONSTRAINT `itemType_ibfk_1` FOREIGN KEY (`categoryFk`) REFERENCES `itemCategory` (`id`) ON UPDATE CASCADE,
CONSTRAINT `temperatureFk` FOREIGN KEY (`temperatureFk`) REFERENCES `temperature` (`code`),
CONSTRAINT `warehouseFk5` FOREIGN KEY (`warehouseFk__`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Protege la tabla tipos de updates para los 4 parámetros de los compradores, en funcion del valor del campo CodigoRojo de tblContadores.';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Protege la tabla tipos de updates para los 4 parámetros de los compradores, en funcion del valor del campo CodigoRojo de tblContadores.';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemType_beforeUpdate`
- BEFORE UPDATE ON `itemType`
- FOR EACH ROW
-BEGIN
- IF NEW.itemPackingTypeFk = '' THEN
-
- SET NEW.itemPackingTypeFk = NULL;
-
- END IF;
-
- IF NEW.itemPackingTypeFk != OLD.itemPackingTypeFk THEN
- UPDATE vn.item
- SET itemPackingTypeFk = NEW.itemPackingTypeFk
- WHERE typeFk = NEW.id;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `itemTypeI18n`
@@ -32130,7 +33751,7 @@ CREATE TABLE `itemTypeRestriction` (
UNIQUE KEY `itemTypeRestriction_UN` (`itemTypeFk`,`dated`),
KEY `itemTypeRestriction_dated_IDX` (`dated`,`itemTypeFk`) USING BTREE,
CONSTRAINT `itemTypeRestriction_FK` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32151,7 +33772,7 @@ CREATE TABLE `itemTypeTag` (
KEY `itemTypeTagTag_idx` (`tagFk`),
CONSTRAINT `itemTypeTagTag` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `itemTypeTag_FK` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32327,30 +33948,8 @@ CREATE TABLE `machine` (
CONSTRAINT `machine_FK` FOREIGN KEY (`ppeFk`) REFERENCES `ppe` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `machine_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `machine_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Maquinaria industrial, vehículos y demás elementos amortizables';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Maquinaria industrial, vehículos y demás elementos amortizables';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`machine_BI`
- BEFORE INSERT ON `machine`
- FOR EACH ROW
-BEGIN
-
- SET NEW.workerFk = vn.getUser();
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `machineDetail`
@@ -32374,7 +33973,7 @@ CREATE TABLE `machineDetail` (
CONSTRAINT `machineDetail_FK` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `machineDetail_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `machineDetail_FK_2` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32393,7 +33992,7 @@ CREATE TABLE `machineDms` (
KEY `machineDms_FK` (`dmsFk`),
CONSTRAINT `machineDms_FK` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `machineDms_FK_1` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32414,7 +34013,7 @@ CREATE TABLE `machineWorker` (
KEY `machineWorker_FK` (`workerFk`),
CONSTRAINT `machineWorker_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `machineWorker_FK_1` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Registros horarios de vehículos de almacén por empleado';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Registros horarios de vehículos de almacén por empleado';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32428,7 +34027,7 @@ CREATE TABLE `machineWorkerConfig` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`maxHours` smallint(5) unsigned NOT NULL COMMENT 'Indicates how many hours a user record is reviewed to update or insert',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32459,34 +34058,8 @@ CREATE TABLE `mail` (
KEY `mail_FK` (`senderFk`),
CONSTRAINT `mail_FK` FOREIGN KEY (`senderFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `mail_FK_1` FOREIGN KEY (`recipientFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`mail_beforeInsert`
- BEFORE INSERT ON `mail`
- FOR EACH ROW
-BEGIN
-
- IF NEW.sender IS NOT NULL THEN
-
- SET NEW.receiver = NEW.sender;
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `mailTemplates`
@@ -32500,7 +34073,7 @@ CREATE TABLE `mailTemplates` (
`name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`attachmentPath` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32525,32 +34098,8 @@ CREATE TABLE `mandate` (
CONSTRAINT `mandateCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `mandato_fgkey1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `mandato_fgkey3` FOREIGN KEY (`mandateTypeFk`) REFERENCES `mandateType` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`mandate_beforeInsert`
- BEFORE INSERT ON `mandate`
- FOR EACH ROW
-BEGIN
- IF (NEW.code IS NULL) THEN
- SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT
- FROM information_schema.TABLES
- WHERE TABLE_SCHEMA='vn' and TABLE_NAME='mandate'));
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `mandateType`
@@ -32563,7 +34112,7 @@ CREATE TABLE `mandateType` (
`id` smallint(5) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32580,7 +34129,7 @@ CREATE TABLE `manuscript` (
`enabled` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32630,7 +34179,7 @@ CREATE TABLE `mdbConfig` (
`issueNumberRegex` varchar(255) NOT NULL,
`chatDestination` varchar(255) NOT NULL COMMENT 'User (@) or channel (#) to send the message',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters for Access';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters for Access';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32684,7 +34233,7 @@ CREATE TABLE `medicalCenter` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32709,7 +34258,7 @@ CREATE TABLE `medicalReview` (
KEY `frgnkWorker_idx` (`workerFk`),
CONSTRAINT `frgcenter` FOREIGN KEY (`centerFk`) REFERENCES `medicalCenter` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `frgnkWorker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32730,7 +34279,7 @@ CREATE TABLE `message` (
KEY `sender` (`sender`),
KEY `recipient` (`recipient`),
KEY `uuid` (`uuid`(8))
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32752,7 +34301,7 @@ CREATE TABLE `messageInbox` (
PRIMARY KEY (`id`),
KEY `uuid` (`uuid`(8)),
KEY `finalRecipient` (`finalRecipient`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32804,7 +34353,7 @@ CREATE TABLE `mistakeType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32824,7 +34373,7 @@ CREATE TABLE `mobileAppVersionControl` (
`versionBeta` varchar(45) DEFAULT NULL,
`isVersionBetaCritical` tinyint(1) DEFAULT 0,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla para llevar el control de las Versions de las aplicaciones móvil ';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla para llevar el control de las Versions de las aplicaciones móvil ';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32841,7 +34390,25 @@ CREATE TABLE `mrw` (
`shipped` date DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `mrwConfig`
+--
+
+DROP TABLE IF EXISTS `mrwConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `mrwConfig` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `url` varchar(100) DEFAULT NULL,
+ `user` varchar(100) DEFAULT NULL,
+ `password` varchar(100) DEFAULT NULL,
+ `franchiseCode` varchar(100) DEFAULT NULL,
+ `subscriberCode` varchar(100) DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32878,6 +34445,24 @@ CREATE TABLE `mrwServiceWeekday` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de los servicios en relación con el día de la semana para MRW';
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `negativeOrigin`
+--
+
+DROP TABLE IF EXISTS `negativeOrigin`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `negativeOrigin` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `itemFk` int(11) NOT NULL,
+ `type` enum('FALTAS','CONTENEDOR','ENTRADAS','OVERBOOKING') NOT NULL,
+ `dated` date DEFAULT curdate(),
+ `quantity` decimal(10,2) NOT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `unique_constraint` (`itemFk`,`type`,`dated`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Temporary table structure for view `newBornSales`
--
@@ -32911,7 +34496,7 @@ CREATE TABLE `noticeCategory` (
`requiredRole` int(11) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `keyName_UNIQUE` (`keyName`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32944,7 +34529,7 @@ CREATE TABLE `observationType` (
`code` varchar(45) NOT NULL,
`hasNewBornMessage` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica aquellos que deben de recibir un mensaje advirtiendo de un cliente nuevo',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -32970,67 +34555,29 @@ DROP TABLE IF EXISTS `operator`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `operator` (
`workerFk` int(10) unsigned NOT NULL,
- `numberOfWagons` int(11) DEFAULT 1,
+ `numberOfWagons` int(11) DEFAULT 2,
`trainFk` int(11) NOT NULL DEFAULT 1,
`itemPackingTypeFk` varchar(1) NOT NULL DEFAULT 'H',
`warehouseFk` smallint(6) unsigned NOT NULL DEFAULT 60,
`sectorFk` int(11) DEFAULT NULL,
`labelerFk` tinyint(3) unsigned DEFAULT NULL,
+ `linesLimit` int(11) DEFAULT 20 COMMENT 'Límite de lineas en una colección para la asignación de pedidos',
+ `volumeLimit` decimal(10,6) DEFAULT 0.500000 COMMENT 'Límite de volumen en una colección para la asignación de pedidos',
PRIMARY KEY (`workerFk`),
KEY `operator_FK` (`workerFk`),
KEY `operator_FK_1` (`trainFk`),
KEY `operator_FK_2` (`itemPackingTypeFk`),
KEY `operator_FK_3` (`warehouseFk`),
KEY `operator_FK_5` (`labelerFk`),
+ KEY `operator_FK_4` (`sectorFk`),
CONSTRAINT `operator_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `operator_FK_1` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE,
CONSTRAINT `operator_FK_2` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `operator_FK_3` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `operator_FK_4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE,
CONSTRAINT `operator_FK_5` FOREIGN KEY (`labelerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`operator_beforeInsert`
- BEFORE INSERT ON `operator`
- FOR EACH ROW
-BEGIN
- CALL vn.printer_checkSector(NEW.labelerFk, NEW.sectorFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`operator_beforeUpdate`
- BEFORE UPDATE ON `operator`
- FOR EACH ROW
-BEGIN
- IF NOT (NEW.labelerFk <=> OLD.labelerFk AND NEW.sectorFk <=> OLD.sectorFk) THEN
- CALL vn.printer_checkSector(NEW.labelerFk, NEW.sectorFk);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `operatorWorkerCode`
@@ -33082,7 +34629,7 @@ CREATE TABLE `origin` (
KEY `warehouse_id` (`warehouseFk`),
KEY `Id_Paises` (`countryFk`),
CONSTRAINT `origin_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33169,7 +34716,7 @@ CREATE TABLE `packageChecked` (
PRIMARY KEY (`id`),
UNIQUE KEY `entryFk_UNIQUE` (`itemFk`),
KEY `fkItem_idx` (`itemFk`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33244,46 +34791,6 @@ CREATE TABLE `packaging` (
CONSTRAINT `packaging_fk2` FOREIGN KEY (`freightItemFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`packaging_beforeInsert`
- BEFORE INSERT ON `packaging`
- FOR EACH ROW
-BEGIN
- SET NEW.value = packaging_calculate(NEW.isPackageReturnable, NEW.packagingReturnFk, NEW.base, NEW.price, NEW.upload);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`packaging_beforeUpdate`
- BEFORE UPDATE ON `packaging`
- FOR EACH ROW
-BEGIN
- SET NEW.value = packaging_calculate(NEW.isPackageReturnable, NEW.packagingReturnFk, NEW.base, NEW.price, NEW.upload);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `packagingConfig`
@@ -33300,8 +34807,14 @@ CREATE TABLE `packagingConfig` (
`palletPackaging` varchar(10) DEFAULT 'pallet USA',
`carryPackaging` varchar(10) DEFAULT 'cc',
`freightItemPackaging` int(11) DEFAULT 71,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Altura mínima para preparar pedidos en preparacion previa';
+ `defaultSmallPackageFk` varchar(10) NOT NULL DEFAULT '94p' COMMENT 'bulto pequeño',
+ `defaultBigPackageFk` varchar(10) NOT NULL DEFAULT '94m' COMMENT 'bulto grande',
+ PRIMARY KEY (`id`),
+ KEY `packagingConfig_FK` (`defaultSmallPackageFk`),
+ KEY `packagingConfig_FK_1` (`defaultBigPackageFk`),
+ CONSTRAINT `packagingConfig_FK` FOREIGN KEY (`defaultSmallPackageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `packagingConfig_FK_1` FOREIGN KEY (`defaultBigPackageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Altura mínima para preparar pedidos en preparacion previa';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33327,7 +34840,7 @@ CREATE TABLE `packagingGifts` (
CONSTRAINT `PackagingGifts_FK` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`),
CONSTRAINT `PackagingGifts_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`),
CONSTRAINT `PackagingGifts_FK_2` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33373,18 +34886,32 @@ CREATE TABLE `packingSite` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(10) DEFAULT NULL,
`hostFk` int(11) DEFAULT NULL,
+ `printerRfidFk` tinyint(3) unsigned DEFAULT NULL,
`printerFk` tinyint(3) unsigned DEFAULT NULL,
`collectionFk` int(11) DEFAULT NULL COMMENT 'Last collection packed on this site',
`monitorId` varchar(255) DEFAULT NULL,
+ `parkingFk` int(11) DEFAULT NULL,
+ `scannerFk` int(11) DEFAULT NULL,
+ `screenFk` int(11) DEFAULT NULL,
+ `editorFk` int(10) unsigned DEFAULT NULL,
+ `hasNewLabelMrwMethod` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `packingSite_UN` (`code`),
+ UNIQUE KEY `printerRfidFk` (`printerRfidFk`),
+ UNIQUE KEY `scannerFk` (`scannerFk`),
+ UNIQUE KEY `screenFk` (`screenFk`),
+ UNIQUE KEY `packingSite_UNI` (`hostFk`),
KEY `packingSite_FK_1` (`printerFk`),
- KEY `packingSite_FK` (`hostFk`),
KEY `packingSite_FK_2` (`collectionFk`),
+ KEY `packingSite_FK_3` (`parkingFk`),
CONSTRAINT `packingSite_FK` FOREIGN KEY (`hostFk`) REFERENCES `host` (`id`),
CONSTRAINT `packingSite_FK_1` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`),
- CONSTRAINT `packingSite_FK_2` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ CONSTRAINT `packingSite_FK_2` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT `packingSite_FK_3` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON DELETE CASCADE ON UPDATE SET NULL,
+ CONSTRAINT `packingSite_FK_4` FOREIGN KEY (`printerRfidFk`) REFERENCES `printer` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `packingSite_FK_5` FOREIGN KEY (`scannerFk`) REFERENCES `scanner` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `packingSite_FK_6` FOREIGN KEY (`screenFk`) REFERENCES `screen` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33418,7 +34945,34 @@ CREATE TABLE `packingSiteConfig` (
`shinobiGroupKey` varchar(255) NOT NULL,
`avgBoxingTime` int(3) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `packingSiteDeviceLog`
+--
+
+DROP TABLE IF EXISTS `packingSiteDeviceLog`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `packingSiteDeviceLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `originFk` int(11) DEFAULT NULL,
+ `userFk` int(10) unsigned DEFAULT NULL,
+ `action` set('insert','update','delete') NOT NULL,
+ `creationDate` timestamp NULL DEFAULT current_timestamp(),
+ `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `changedModel` enum('PackingSite') NOT NULL DEFAULT 'PackingSite',
+ `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
+ `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
+ `changedModelId` int(11) NOT NULL,
+ `changedModelValue` varchar(45) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `userFk` (`userFk`),
+ KEY `packingSiteDeviceLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
+ KEY `packingSiteDeviceLog_packingSiteDeviceLog` (`originFk`,`creationDate`),
+ CONSTRAINT `packingSiteDeviceLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33447,7 +35001,7 @@ CREATE TABLE `packingSiteLog` (
CONSTRAINT `packingSiteLog_FK_1` FOREIGN KEY (`printerModelFk`) REFERENCES `printerModel` (`code`) ON UPDATE CASCADE,
CONSTRAINT `packingSiteLog_FK_2` FOREIGN KEY (`packingSiteFk`) REFERENCES `packingSite` (`code`) ON UPDATE CASCADE,
CONSTRAINT `packingSiteLog_FK_4` FOREIGN KEY (`typeErrorFk`) REFERENCES `packingSiteTypeError` (`code`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33493,56 +35047,41 @@ CREATE TABLE `parking` (
`sectorFk` int(11) NOT NULL DEFAULT 2,
`code` varchar(8) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`pickingOrder` int(11) DEFAULT NULL,
+ `editorFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
KEY `parking_fk1_idx` (`sectorFk`),
CONSTRAINT `parking_fk1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla con los parkings del altillo';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla con los parkings del altillo';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`parking_BEFORE_INSERT`
- BEFORE INSERT ON `parking`
- FOR EACH ROW
-BEGIN
- -- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ;
+--
+-- Table structure for table `parkingLog`
+--
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`parking_BEFORE_UPDATE`
- BEFORE UPDATE ON `parking`
- FOR EACH ROW
-BEGIN
-
- -- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
+DROP TABLE IF EXISTS `parkingLog`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `parkingLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `originFk` int(11) DEFAULT NULL,
+ `userFk` int(10) unsigned DEFAULT NULL,
+ `action` set('insert','update','delete','select') NOT NULL,
+ `creationDate` timestamp NULL DEFAULT current_timestamp(),
+ `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `changedModel` enum('Parking','SaleGroup','SaleGroupDetail') NOT NULL DEFAULT 'Parking',
+ `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
+ `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
+ `changedModelId` int(11) NOT NULL,
+ `changedModelValue` varchar(45) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `logParkinguserFk` (`userFk`),
+ KEY `parkingLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
+ KEY `parkingLog_originFk` (`originFk`,`creationDate`),
+ CONSTRAINT `parkingOriginFk` FOREIGN KEY (`originFk`) REFERENCES `parking` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `parkingUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payDem`
@@ -33555,7 +35094,7 @@ CREATE TABLE `payDem` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`payDem` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33592,7 +35131,7 @@ CREATE TABLE `payMethod` (
`hasVerified` tinyint(1) DEFAULT 0,
`graceMonthsDisableChecked` int(11) unsigned NOT NULL DEFAULT 0 COMMENT 'Deshabilita la comprobación de los datos bancarios de todos aquellos proveedores que no hayan recibido un pago en los meses especificados',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33632,178 +35171,31 @@ CREATE TABLE `payment` (
CONSTRAINT `payment_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`),
CONSTRAINT `payment_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `payment_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `payment_beforeInsert` BEFORE INSERT ON `payment` FOR EACH ROW
-BEGIN
- DECLARE cuenta_banco,cuenta_proveedor DOUBLE;
- DECLARE vNewBookEntry INT;
- DECLARE bolCASH BOOLEAN;
- DECLARE isSupplierActive BOOLEAN;
- -- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH
- SELECT (at2.code = 'cash') INTO bolCASH
- FROM vn.bank b
- JOIN vn.accountingType at2 ON at2.id = b.cash
- WHERE b.id = NEW.bankFk;
+--
+-- Temporary table structure for view `paymentExchangeInsurance`
+--
- IF bolCASH THEN
-
- SELECT account INTO cuenta_banco
- FROM bank
- WHERE id = NEW.bankFk;
-
- SELECT account INTO cuenta_proveedor
- FROM supplier
- WHERE id = NEW.supplierFk;
-
- CALL vn.ledger_next(vNewBookEntry);
-
- INSERT INTO XDiario ( ASIEN,
- FECHA,
- SUBCTA,
- CONTRA,
- CONCEPTO,
- EURODEBE,
- EUROHABER,
- empresa_id)
- SELECT vNewBookEntry,
- NEW.received,
- SUBCTA,
- CONTRA,
- NEW.concept,
- EURODEBE,
- EUROHABER,
- NEW.companyFk
- FROM ( SELECT cuenta_banco SUBCTA,
- cuenta_proveedor CONTRA,
- 0 EURODEBE,
- NEW.amount + NEW.bankingFees EUROHABER
- UNION ALL
- SELECT cuenta_proveedor SUBCTA,
- cuenta_banco CONTRA,
- NEW.amount EURODEBE,
- 0 EUROHABER) gf;
-
- IF NEW.bankingFees <> 0 THEN
- INSERT INTO XDiario ( ASIEN,
- FECHA,
- SUBCTA,
- CONTRA,
- CONCEPTO,
- EURODEBE,
- EUROHABER,
- empresa_id)
- SELECT vNewBookEntry,
- NEW.received,
- IF(c.id = 1,6260000002,
- IF(CEE = 1,6260000003,6260000004)),
- cuenta_banco,
- NEW.concept,
- NEW.bankingFees,
- 0,
- NEW.companyFk
- FROM supplier s
- JOIN country c ON s.countryFk = c.id
- WHERE s.id = NEW.supplierFk;
- END IF;
- END IF;
-
- SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received);
-
- SELECT isActive INTO isSupplierActive
- FROM supplier
- WHERE id = NEW.supplierFk;
-
- IF isSupplierActive = FALSE THEN
- CALL util.throw('SUPPLIER_INACTIVE');
- END IF;
-
- IF ISNULL(NEW.workerFk) THEN
- SET NEW.workerFk = account.myUser_getId();
- END IF;
-
- END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`payment_afterInsert`
- AFTER INSERT ON `payment`
- FOR EACH ROW
-BEGIN
- DECLARE vIsPayMethodChecked BOOLEAN;
- DECLARE vEmail VARCHAR(150);
-
- SELECT isPayMethodChecked INTO vIsPayMethodChecked
- FROM supplier
- WHERE id = NEW.supplierFk;
-
-
- IF vIsPayMethodChecked = FALSE THEN
-
- SELECT notificationEmail INTO vEmail
- FROM department
- WHERE name = 'FINANZAS';
-
- CALL mail_insert(
- vEmail,
- NULL,
- 'Pago con método sin verificar',
- CONCAT(
- 'Se ha realizado el pago ',
- NEW.id,
- ' al proveedor ',
- NEW.supplierFk,
- ' con el método de pago sin verificar.'
- )
- );
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER payment_beforeUpdate BEFORE UPDATE ON payment FOR EACH ROW
-BEGIN
- IF ISNULL(NEW.workerFk) THEN
- SET NEW.workerFk = account.myUser_getId();
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
+DROP TABLE IF EXISTS `paymentExchangeInsurance`;
+/*!50001 DROP VIEW IF EXISTS `paymentExchangeInsurance`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `paymentExchangeInsurance` AS SELECT
+ 1 AS `id`,
+ 1 AS `amount`,
+ 1 AS `created`,
+ 1 AS `dueDay`,
+ 1 AS `entityFk`,
+ 1 AS `ref`,
+ 1 AS `rate`,
+ 1 AS `companyFk`,
+ 1 AS `financialProductTypefk`,
+ 1 AS `upperBarrier`,
+ 1 AS `lowerBarrier`,
+ 1 AS `strike` */;
+SET character_set_client = @saved_cs_client;
--
-- Table structure for table `payrollCategories`
@@ -33820,6 +35212,25 @@ CREATE TABLE `payrollCategories` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Temporary table structure for view `payrollCenter`
+--
+
+DROP TABLE IF EXISTS `payrollCenter`;
+/*!50001 DROP VIEW IF EXISTS `payrollCenter`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `payrollCenter` AS SELECT
+ 1 AS `codCenter`,
+ 1 AS `name`,
+ 1 AS `nss`,
+ 1 AS `street`,
+ 1 AS `city`,
+ 1 AS `postcode`,
+ 1 AS `companyFk`,
+ 1 AS `companyCode` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `pcs`
--
@@ -33834,7 +35245,7 @@ CREATE TABLE `pcs` (
`pallet` int(11) DEFAULT NULL,
`box` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33871,7 +35282,7 @@ CREATE TABLE `pedidosInternos` (
`idArticle` int(11) DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33929,13 +35340,13 @@ CREATE TABLE `pgc` (
`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,
+ `siiTrascendencyInvoiceOutFk` int(10) unsigned DEFAULT 1,
`isEqualizated` tinyint(1) DEFAULT 0,
PRIMARY KEY (`code`),
KEY `pgc_fk1_idx` (`cplusTaxBreakFk`),
- KEY `pgc_fk2_idx` (`cplusTrascendency477Fk`),
+ KEY `pgc_fk2_idx` (`siiTrascendencyInvoiceOutFk`),
CONSTRAINT `pgc_fk1` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `pgc_fk2` FOREIGN KEY (`cplusTrascendency477Fk`) REFERENCES `cplusTrascendency477` (`id`) ON UPDATE CASCADE
+ CONSTRAINT `pgc_fk2` FOREIGN KEY (`siiTrascendencyInvoiceOutFk`) REFERENCES `siiTrascendencyInvoiceOut` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Plan General Contable';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -34039,97 +35450,6 @@ CREATE TABLE `postCode` (
CONSTRAINT `postCodeTownFk` FOREIGN KEY (`townFk`) REFERENCES `town` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`postCode_beforeInsert`
- BEFORE INSERT ON `postCode`
- FOR EACH ROW
-BEGIN
- SET NEW.geoFk = zoneGeo_new('postCode', NEW.`code`,
- (SELECT geoFk FROM town WHERE id = NEW.townFk));
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`postCode_beforeUpdate`
- BEFORE UPDATE ON `postCode`
- FOR EACH ROW
-BEGIN
- -- IF !(OLD.geoFk <=> NEW.geoFk) THEN
- -- CALL zoneGeo_throwNotEditable;
- -- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`postCode_afterUpdate`
- AFTER UPDATE ON `postCode`
- FOR EACH ROW
-BEGIN
- IF !(OLD.townFk <=> NEW.townFk) THEN
- CALL zoneGeo_setParent(NEW.geoFk,
- (SELECT geoFk FROM town WHERE id = NEW.townFk));
- END IF;
-
- IF !(OLD.`code` <=> NEW.`code`) THEN
- UPDATE zoneGeo SET `name` = NEW.`code`
- WHERE id = NEW.geoFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`postCode_afterDelete`
- AFTER DELETE ON `postCode`
- FOR EACH ROW
-BEGIN
- CALL zoneGeo_delete(OLD.geoFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ppe`
@@ -34177,7 +35497,7 @@ CREATE TABLE `ppe` (
CONSTRAINT `ppe_fk5` FOREIGN KEY (`account`) REFERENCES `pgcMaster` (`code`) ON UPDATE CASCADE,
CONSTRAINT `ppe_fk6` FOREIGN KEY (`endowment`) REFERENCES `pgcMaster` (`code`) ON UPDATE CASCADE,
CONSTRAINT `ppe_fk7` FOREIGN KEY (`elementAccount`) REFERENCES `pgcMaster` (`code`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Property, plant & equipment\nInmvolizado, en español';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Property, plant & equipment\nInmvolizado, en español';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34197,7 +35517,7 @@ CREATE TABLE `ppeComponent` (
KEY `ppeComponent_fk2_idx` (`invoiceInFk`),
CONSTRAINT `ppeComponent_fk1` FOREIGN KEY (`ppeFk`) REFERENCES `ppe` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ppeComponent_fk2` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34216,7 +35536,7 @@ CREATE TABLE `ppeDMS` (
KEY `ppeDMS_fk2_idx` (`ppeFk`),
CONSTRAINT `ppeDMS_fk1` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ppeDMS_fk2` FOREIGN KEY (`ppeFk`) REFERENCES `ppe` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34230,7 +35550,7 @@ CREATE TABLE `ppeGroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de inmovilizado';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de inmovilizado';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34259,7 +35579,7 @@ CREATE TABLE `ppePlan` (
`rate` decimal(3,2) NOT NULL DEFAULT 1.00,
`days` int(11) NOT NULL DEFAULT 365,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Plan de amortizacion para la tabla ppe';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Plan de amortizacion para la tabla ppe';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34292,58 +35612,8 @@ CREATE TABLE `priceFixed` (
KEY `warehouse_id` (`warehouseFk`),
CONSTRAINT `priceFixed_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `priceFixed_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`priceFixed_beforeInsert`
- BEFORE INSERT ON `priceFixed`
- FOR EACH ROW
-BEGIN
- DECLARE vDated DATE;
- IF NEW.started > NEW.ended THEN
- SET vDated = NEW.started;
- SET NEW.started = NEW.ended;
- SET NEW.ended = vDated;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`priceFixed_beforeUpdate`
- BEFORE UPDATE ON `priceFixed`
- FOR EACH ROW
-BEGIN
- DECLARE vDated DATE;
- IF NEW.started > NEW.ended THEN
- SET vDated = NEW.started;
- SET NEW.started = NEW.ended;
- SET NEW.ended = vDated;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `printQueue`
@@ -34374,7 +35644,7 @@ CREATE TABLE `printQueue` (
CONSTRAINT `printQueue_printerFk` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON UPDATE CASCADE,
CONSTRAINT `printQueue_priorityFk` FOREIGN KEY (`priorityFk`) REFERENCES `queuePriority` (`id`) ON UPDATE CASCADE,
CONSTRAINT `printQueue_report` FOREIGN KEY (`reportFk`) REFERENCES `report` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34426,6 +35696,7 @@ CREATE TABLE `printer` (
`isLabeler` tinyint(1) DEFAULT 0 COMMENT 'Indica si es impresora de etiquetas',
`sectorFk` int(11) DEFAULT NULL,
`paperSizeFk` varchar(100) DEFAULT NULL,
+ `isRfid` tinyint(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `printer_UN` (`reference`),
UNIQUE KEY `printer_UN1` (`macWifi`),
@@ -34437,7 +35708,7 @@ CREATE TABLE `printer` (
CONSTRAINT `printer_FK` FOREIGN KEY (`modelFk`) REFERENCES `printerModel` (`code`) ON UPDATE CASCADE,
CONSTRAINT `printer_FK_1` FOREIGN KEY (`paperSizeFk`) REFERENCES `paperSize` (`code`),
CONSTRAINT `printer_sectorFk` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34482,7 +35753,7 @@ CREATE TABLE `producer` (
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34511,10 +35782,47 @@ CREATE TABLE `productionConfig` (
`pendingCollectionsAge` tinyint(3) unsigned DEFAULT 6,
`maxNotAssignedCollectionLifeTime` time NOT NULL DEFAULT '00:10:00' COMMENT 'Tiempo de vida de las colecciones sin asignar. Cuando se supera son eliminadas',
`maxProductionScopeDays` int(11) NOT NULL DEFAULT 1 COMMENT 'maximo numero de dias en F11',
- PRIMARY KEY (`id`)
+ `orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location',
+ `stockScopeDays` int(11) DEFAULT 1 COMMENT 'Días a futuro al revisar el stock',
+ `shortageAddressFk` int(11) DEFAULT NULL COMMENT 'Consignatario por defecto para añadir un item de alta',
+ `clientSelfConsumptionFk` int(11) DEFAULT NULL COMMENT 'Cliente para crear el ticket de autoconsumo',
+ `itemPreviousDefaultSize` int(11) DEFAULT NULL COMMENT 'Altura por defecto para los artículos de previa',
+ `addressSelfConsumptionFk` int(11) DEFAULT 2613 COMMENT 'Consignatario para crear el ticket de autoconsumo',
+ PRIMARY KEY (`id`),
+ KEY `productionConfig_FK` (`shortageAddressFk`),
+ KEY `productionConfig_FK_1` (`clientSelfConsumptionFk`),
+ KEY `productionConfig_FK_2` (`addressSelfConsumptionFk`),
+ CONSTRAINT `productionConfig_FK` FOREIGN KEY (`shortageAddressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `productionConfig_FK_1` FOREIGN KEY (`clientSelfConsumptionFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `productionConfig_FK_2` FOREIGN KEY (`addressSelfConsumptionFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los parámetros que condicionan la producción';
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `productionError`
+--
+
+DROP TABLE IF EXISTS `productionError`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `productionError` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `userFk` int(11) DEFAULT NULL,
+ `firstname` varchar(100) DEFAULT NULL,
+ `lastname` varchar(100) DEFAULT NULL,
+ `rol` varchar(100) DEFAULT NULL,
+ `ticketNumber` int(11) DEFAULT NULL,
+ `lineNumber` int(11) DEFAULT NULL,
+ `error` int(11) DEFAULT NULL,
+ `volume` double DEFAULT NULL,
+ `hourStart` varchar(100) DEFAULT NULL,
+ `hourEnd` varchar(100) DEFAULT NULL,
+ `hourWorked` varchar(100) DEFAULT NULL,
+ `dated` date DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Temporary table structure for view `productionVolume`
--
@@ -34556,9 +35864,11 @@ CREATE TABLE `professionalCategory` (
`name` varchar(50) NOT NULL,
`level` int(11) unsigned DEFAULT NULL,
`dayBreak` int(11) unsigned DEFAULT NULL,
+ `code` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`),
- UNIQUE KEY `prefessionalCategory_UN` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ UNIQUE KEY `prefessionalCategory_UN` (`name`),
+ UNIQUE KEY `code` (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34572,7 +35882,7 @@ CREATE TABLE `profileType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34604,7 +35914,7 @@ CREATE TABLE `project` (
CONSTRAINT `project_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `project_FK_1` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `project_FK_3` FOREIGN KEY (`stateFk`) REFERENCES `projectState` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla master de proyectos';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla master de proyectos';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34625,34 +35935,8 @@ CREATE TABLE `projectNotes` (
KEY `projectNotes_FK_1` (`userFk`),
CONSTRAINT `projectNotes_FK` FOREIGN KEY (`projectFk`) REFERENCES `project` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `projectNotes_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Historico de notas para project';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Historico de notas para project';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER projectNotes_BeforeInsert
-BEFORE INSERT
-ON projectNotes FOR EACH ROW
-BEGIN
-
- IF ISNULL(NEW.userFk) THEN
-
- SET NEW.userFk = account.myUser_getId();
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `projectState`
@@ -34668,6 +35952,24 @@ CREATE TABLE `projectState` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `promissoryNote`
+--
+
+DROP TABLE IF EXISTS `promissoryNote`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `promissoryNote` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `issued` timestamp NOT NULL DEFAULT current_timestamp(),
+ `Concept` varchar(50) DEFAULT NULL,
+ `paymentFk` int(10) unsigned DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `pago_id` (`paymentFk`),
+ CONSTRAINT `promissoryNote_ibfk_2` FOREIGN KEY (`paymentFk`) REFERENCES `payment` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `property`
--
@@ -34709,7 +36011,7 @@ CREATE TABLE `property` (
CONSTRAINT `propertySupplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `property_FK` FOREIGN KEY (`propertyGroupFk`) REFERENCES `propertyGroup` (`id`) ON UPDATE CASCADE,
CONSTRAINT `property_FK_1` FOREIGN KEY (`townFk`) REFERENCES `town` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34728,7 +36030,7 @@ CREATE TABLE `propertyDms` (
KEY `propertyDms_FK_1` (`propertyFk`),
CONSTRAINT `propertyDms_FK` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `propertyDms_FK_1` FOREIGN KEY (`propertyFk`) REFERENCES `property` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34742,7 +36044,7 @@ CREATE TABLE `propertyGroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34763,7 +36065,7 @@ CREATE TABLE `propertyNotes` (
KEY `propertyNotes_FK` (`propertyFk`),
CONSTRAINT `propertyNotes_FK` FOREIGN KEY (`propertyFk`) REFERENCES `property` (`id`),
CONSTRAINT `propertyNotes_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34782,115 +36084,17 @@ CREATE TABLE `province` (
`geoFk` int(11) DEFAULT NULL,
`autonomyFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
+ UNIQUE KEY `countryName_UN` (`countryFk`,`name`),
KEY `Paises_Id` (`countryFk`),
KEY `warehouse_Id` (`warehouseFk`),
KEY `provicne_zone_fk_idx` (`zoneFk`),
KEY `province_FK` (`autonomyFk`),
CONSTRAINT `province_FK` FOREIGN KEY (`autonomyFk`) REFERENCES `autonomy` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `province_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `province_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `vn2008`.`zones` (`zone_id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `province_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `vn2008`.`zones__` (`zone_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `warehouse_Id` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_beforeInsert`
- BEFORE INSERT ON `province`
- FOR EACH ROW
-BEGIN
-
- SET NEW.geoFk = zoneGeo_new('province', NEW.`name`,
- (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk));
-
- SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk);
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_beforeUpdate`
- BEFORE UPDATE ON `province`
- FOR EACH ROW
-BEGIN
-
- IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN
-
- SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk);
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate`
- AFTER UPDATE ON `province`
- FOR EACH ROW
-BEGIN
- IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN
- CALL zoneGeo_setParent(NEW.geoFk,
- (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk));
- END IF;
-
- IF !(OLD.`name` <=> NEW.`name`) THEN
- UPDATE zoneGeo SET `name` = NEW.`name`
- WHERE id = NEW.geoFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterDelete`
- AFTER DELETE ON `province`
- FOR EACH ROW
-BEGIN
- CALL zoneGeo_delete(OLD.geoFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `punchState`
@@ -34956,72 +36160,8 @@ CREATE TABLE `rate` (
KEY `rate_fk_editor` (`editorFk`),
CONSTRAINT `rate_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `tarifa_warehouse` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`rate_beforeInsert`
- BEFORE INSERT ON `rate`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`rate_beforeUpdate`
- BEFORE UPDATE ON `rate`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`rate_afterDelete`
- AFTER DELETE ON `rate`
- FOR EACH ROW
-BEGIN
- INSERT INTO rateLog
- SET `action` = 'delete',
- `changedModel` = 'Rate',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `rateConfig`
@@ -35063,7 +36203,6 @@ CREATE TABLE `rateLog` (
KEY `logRateuserFk` (`userFk`),
KEY `rateLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `rateLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `rateOriginFk` FOREIGN KEY (`originFk`) REFERENCES `rate` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `rateUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -35097,122 +36236,8 @@ CREATE TABLE `receipt` (
CONSTRAINT `receiptWorkerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `receipt_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `recibo_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert`
- BEFORE INSERT ON `receipt`
- FOR EACH ROW
-BEGIN
- DECLARE vIsAutoConciliated BOOLEAN;
-
- IF NEW.isConciliate = FALSE THEN
- SELECT isAutoConciliated INTO vIsAutoConciliated
- FROM accounting a
- JOIN accountingType at2 ON at2.id = a.accountingTypeFk
- WHERE a.id = NEW.bankFk;
-
- SET NEW.isConciliate = vIsAutoConciliated;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterInsert`
- AFTER INSERT ON `receipt`
- FOR EACH ROW
-CALL clientRisk_update(NEW.clientFk, NEW.companyFk, -NEW.amountPaid) */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeUpdate`
- BEFORE UPDATE ON `receipt`
- FOR EACH ROW
-BEGIN
- CALL clientRisk_update(OLD.clientFk, OLD.companyFk, OLD.amountPaid);
- CALL clientRisk_update(NEW.clientFk, NEW.companyFk, -NEW.amountPaid);
- SET NEW.workerFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate`
- AFTER UPDATE ON `receipt`
- FOR EACH ROW
-BEGIN
- IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN
- CALL mail_insert(
- 'finanzas@verdnatura.es',
- NULL,
- CONCAT('Cambios de recibos del cliente: ', NEW.clientFk),
- CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed)
- );
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeDelete`
- BEFORE DELETE ON `receipt`
- FOR EACH ROW
-CALL clientRisk_update(OLD.clientFk, OLD.companyFk, OLD.amountPaid) */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `recipe`
@@ -35237,7 +36262,7 @@ CREATE TABLE `recipe` (
KEY `recipe_ix_2` (`itemFk`),
KEY `recipe_FK` (`inkFk`),
CONSTRAINT `recipe_FK` FOREIGN KEY (`inkFk`) REFERENCES `ink` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35258,7 +36283,7 @@ CREATE TABLE `recipe_log` (
KEY `recipe_log_ix3` (`selected_ItemFk`),
CONSTRAINT `recipe_log_FK` FOREIGN KEY (`recipe_ItemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE,
CONSTRAINT `recipe_log_FK_1` FOREIGN KEY (`selected_ItemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena las decisiones tomadas al generar recetas';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena las decisiones tomadas al generar recetas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35282,72 +36307,8 @@ CREATE TABLE `recovery` (
CONSTRAINT `cliente333` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
CONSTRAINT `cliente_cliente` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
CONSTRAINT `recovery_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla apuntaremos los acuerdos de recobro semanal a ';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla apuntaremos los acuerdos de recobro semanal a ';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`recovery_beforeInsert`
- BEFORE INSERT ON `recovery`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`recovery_beforeUpdate`
- BEFORE UPDATE ON `recovery`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`recovery_afterDelete`
- AFTER DELETE ON `recovery`
- FOR EACH ROW
-BEGIN
- INSERT INTO clientLog
- SET `action` = 'delete',
- `changedModel` = 'Recovery',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `referenceCurrent`
@@ -35395,6 +36356,26 @@ CREATE TABLE `referenceRateConfig` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `remittance`
+--
+
+DROP TABLE IF EXISTS `remittance`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `remittance` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `dated` datetime DEFAULT NULL,
+ `accountingFk` int(11) DEFAULT 0,
+ `companyFk` int(10) unsigned NOT NULL DEFAULT 442,
+ PRIMARY KEY (`id`),
+ KEY `Id_Banco` (`accountingFk`),
+ KEY `empresa_id` (`companyFk`),
+ CONSTRAINT `RemesasCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `remittance_ibfk_2` FOREIGN KEY (`accountingFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `report`
--
@@ -35410,7 +36391,7 @@ CREATE TABLE `report` (
PRIMARY KEY (`id`),
KEY `report_FK` (`paperSizeFk`),
CONSTRAINT `report_FK` FOREIGN KEY (`paperSizeFk`) REFERENCES `paperSize` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35426,7 +36407,7 @@ CREATE TABLE `returnBuckets` (
`freightPackagingEmpty` double NOT NULL DEFAULT 0,
`freightPackagingFull` double NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35472,6 +36453,23 @@ SET character_set_client = utf8;
1 AS `hasLogin` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `roleCreditLimit`
+--
+
+DROP TABLE IF EXISTS `roleCreditLimit`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `roleCreditLimit` (
+ `id` int(11) NOT NULL,
+ `maxAmount` int(10) unsigned NOT NULL,
+ `roleFk` int(10) unsigned NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `clientCreditLimit_FK_idx` (`roleFk`),
+ CONSTRAINT `roleCreditLimit_FK` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `route`
--
@@ -35482,6 +36480,7 @@ DROP TABLE IF EXISTS `route`;
CREATE TABLE `route` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned DEFAULT NULL,
+ `firstEditorFk` int(10) unsigned NOT NULL COMMENT 'Usuario creador de la ruta',
`created` date NOT NULL,
`vehicleFk` int(10) unsigned DEFAULT NULL,
`agencyModeFk` int(11) DEFAULT NULL,
@@ -35518,172 +36517,8 @@ CREATE TABLE `route` (
CONSTRAINT `route_ibfk_1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `route_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `route_invoiceInFk` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_beforeInsert`
- BEFORE INSERT ON `route`
- FOR EACH ROW
-BEGIN
- DECLARE vDefaultAgencyModeFk INT;
-
- SET NEW.editorFk = account.myUser_getId();
-
- SET NEW.commissionWorkCenterFk = (
- SELECT IFNULL(b.workCenterFK, r.defaultWorkCenterFk)
- FROM vn.routeConfig r
- LEFT JOIN vn.business b ON b.workerFk = account.myUser_getId()
- AND NEW.created BETWEEN b.started AND IFNULL(b.ended, NEW.created));
-
- IF ISNULL(NEW.agencyModeFk) THEN
- SELECT r.agencyModeFk INTO vDefaultAgencyModeFk
- FROM routeDefaultAgencyMode r
- JOIN business b ON b.workCenterFk = r.workCenterFK
- JOIN worker w ON w.businessFk = b.id
- WHERE b.workerFk = account.myUser_getId();
-
- SET NEW.agencyModeFk = vDefaultAgencyModeFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterInsert`
- AFTER INSERT ON `route`
- FOR EACH ROW
-BEGIN
- CALL route_calcCommission(NEW.id);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_beforeUpdate`
- BEFORE UPDATE ON `route`
- FOR EACH ROW
-BEGIN
- DECLARE vKmMax INT;
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.isOk <> FALSE AND OLD.isOk = FALSE THEN
- SET NEW.m3 = ( SELECT SUM(litros)/1000
- FROM vn.saleVolume s
- JOIN vn.ticket t ON s.ticketFk = t.id
- WHERE t.routeFk = NEW.id);
- END IF;
-
- IF NEW.kmEnd < NEW.kmStart AND NEW.kmEnd <> 0 THEN
- CALL util.throw ('KmEnd menor que kmStart');
- END IF;
-
- SELECT kmMax INTO vKmMax
- FROM routeConfig rc;
-
- IF ((NEW.kmEnd - NEW.kmStart) > vKmMax) AND NEW.kmEnd <> 0 THEN
- CALL util.throw (CONCAT('The km can not exceed ', vKmMax));
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterUpdate`
- AFTER UPDATE ON `route`
- FOR EACH ROW
-BEGIN
- IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN
- -- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets
-
- -- Inserta el gestdoc en todos los tickets de la ruta
- INSERT INTO ticketDms(ticketFk,dmsFk)
- SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id
- ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk;
-
- -- Update del firmado
- UPDATE ticket t
- JOIN ticketDms tg ON t.id = tg.ticketFk
- SET isSigned = 1 WHERE t.routeFk = NEW.id;
- END IF;
-
- IF !(NEW.kmStart <=> OLD.kmStart)
- OR !(NEW.kmEnd <=> OLD.kmEnd)
- OR !(NEW.workerFk <=> OLD.workerFk)
- OR !(NEW.m3 <=> OLD.m3)
- OR !(NEW.agencyModeFk <=> OLD.agencyModeFk)THEN
- CALL route_calcCommission(NEW.id);
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterDelete`
- AFTER DELETE ON `route`
- FOR EACH ROW
-BEGIN
- INSERT INTO routeLog
- SET `action` = 'delete',
- `changedModel` = 'Route',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `routeAction`
@@ -35698,7 +36533,7 @@ CREATE TABLE `routeAction` (
`price` decimal(10,2) DEFAULT NULL,
`isMainlineDelivered` tinyint(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35712,6 +36547,7 @@ CREATE TABLE `routeCommission` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`routeFk` int(10) unsigned NOT NULL,
`workCenterFk` int(11) DEFAULT NULL,
+ `firstEditorFk` int(10) unsigned NOT NULL COMMENT 'Usuario creador de la ruta',
`km` decimal(5,2) DEFAULT NULL,
`m3` decimal(5,2) DEFAULT NULL,
`yearlyKm` decimal(5,2) DEFAULT NULL,
@@ -35722,9 +36558,10 @@ CREATE TABLE `routeCommission` (
PRIMARY KEY (`id`),
KEY `routeCommission_routeFk_idx` (`routeFk`),
KEY `routeCommission_workCenterFk_idx` (`workCenterFk`),
+ KEY `routeCommission_firstEditorFk` (`firstEditorFk`),
CONSTRAINT `routeCommission_routeFk` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `routeCommission_workCenterFk` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35745,7 +36582,7 @@ CREATE TABLE `routeComplement` (
KEY `fgn_routeActionFk_idx` (`routeActionFk`),
CONSTRAINT `fgn_routeActionFk` FOREIGN KEY (`routeActionFk`) REFERENCES `routeAction` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fgn_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35757,8 +36594,6 @@ DROP TABLE IF EXISTS `routeConfig`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeConfig` (
`id` int(10) unsigned NOT NULL,
- `kmRate` decimal(10,4) DEFAULT NULL,
- `kmTruckRate` decimal(10,4) DEFAULT NULL,
`m3Distribution` decimal(10,4) DEFAULT NULL,
`m3Management` decimal(10,2) DEFAULT NULL,
`m3Palletization` decimal(10,2) DEFAULT NULL,
@@ -35853,7 +36688,7 @@ CREATE TABLE `routeLog` (
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- `changedModel` enum('Route') NOT NULL DEFAULT 'Route',
+ `changedModel` enum('Route','RoutesMonitor') NOT NULL DEFAULT 'Route',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
@@ -35862,9 +36697,8 @@ CREATE TABLE `routeLog` (
KEY `userFk` (`userFk`),
KEY `routeLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `routeLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `routeLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `route` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `routeLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35896,7 +36730,7 @@ CREATE TABLE `routeMaster` (
PRIMARY KEY (`id`),
KEY `fk_rutas_warehouse_id_idx` (`warehouseFk`),
CONSTRAINT `routeMaster_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35927,9 +36761,27 @@ CREATE TABLE `routeUserPercentage__` (
PRIMARY KEY (`id`),
KEY `routeUserPercentageFk_idx` (`workerFk`),
CONSTRAINT `routeUserPercentageFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Temporary table structure for view `routesControl`
+--
+
+DROP TABLE IF EXISTS `routesControl`;
+/*!50001 DROP VIEW IF EXISTS `routesControl`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `routesControl` AS SELECT
+ 1 AS `routeFk`,
+ 1 AS `expeditions`,
+ 1 AS `scanned`,
+ 1 AS `pallets`,
+ 1 AS `lastScanned`,
+ 1 AS `description`,
+ 1 AS `eta` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `routesMonitor`
--
@@ -35955,34 +36807,21 @@ CREATE TABLE `routesMonitor` (
`m3boxes` decimal(10,1) DEFAULT NULL,
`bufferFk` int(11) DEFAULT NULL COMMENT 'Buffer del sorter por el que se quiere sacar esa ruta',
`isPickingAllowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Los tickets de esta ruta se pueden preparar',
+ `editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`routeFk`),
KEY `routesMonitor_FK` (`bufferFk`),
KEY `routesMonitor_FK_2` (`beachFk`),
KEY `routesMonitor_FK_1` (`dockFk`),
+ KEY `routesMonitor_FK_3` (`expeditionTruckFk`),
+ KEY `routesMonitor_fk_editor` (`editorFk`),
CONSTRAINT `routesMonitor_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `routesMonitor_FK_1` FOREIGN KEY (`dockFk`) REFERENCES `dock` (`code`) ON UPDATE CASCADE,
- CONSTRAINT `routesMonitor_FK_2` FOREIGN KEY (`beachFk`) REFERENCES `beach` (`code`) ON UPDATE CASCADE
+ CONSTRAINT `routesMonitor_FK_2` FOREIGN KEY (`beachFk`) REFERENCES `beach` (`code`) ON UPDATE CASCADE,
+ CONSTRAINT `routesMonitor_FK_3` FOREIGN KEY (`expeditionTruckFk`) REFERENCES `expeditionTruck` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `routesMonitor_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Temporary table structure for view `routesReduced`
---
-
-DROP TABLE IF EXISTS `routesReduced`;
-/*!50001 DROP VIEW IF EXISTS `routesReduced`*/;
-SET @saved_cs_client = @@character_set_client;
-SET character_set_client = utf8;
-/*!50001 CREATE VIEW `routesReduced` AS SELECT
- 1 AS `description`,
- 1 AS `name`,
- 1 AS `routeFk`,
- 1 AS `eta`,
- 1 AS `bufferFk`,
- 1 AS `beachFk`,
- 1 AS `itempackingTypeFk` */;
-SET character_set_client = @saved_cs_client;
-
--
-- Table structure for table `sale`
--
@@ -35996,7 +36835,7 @@ CREATE TABLE `sale` (
`ticketFk` int(11) NOT NULL,
`concept` varchar(50) DEFAULT NULL,
`quantity` decimal(10,2) NOT NULL DEFAULT 0.00,
- `originalQuantity` double(9,1) DEFAULT NULL,
+ `originalQuantity` double(9,1) DEFAULT NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity',
`price` decimal(10,2) NOT NULL DEFAULT 0.00,
`discount` tinyint(2) unsigned NOT NULL DEFAULT 0,
`priceFixed` decimal(10,2) NOT NULL DEFAULT 0.00,
@@ -36011,315 +36850,12 @@ CREATE TABLE `sale` (
KEY `Id_Ticket` (`ticketFk`),
KEY `itemFk_ticketFk` (`itemFk`,`ticketFk`),
KEY `sale_fk_editor` (`editorFk`),
+ KEY `sale_created_IDX` (`created`) USING BTREE,
CONSTRAINT `movement_ticket_id` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sale_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `sale_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sale_beforeInsert`
- BEFORE INSERT ON `sale`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sale_afterInsert`
- AFTER INSERT ON `sale`
- FOR EACH ROW
-BEGIN
- IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN
- CALL util.throw('Cannot insert a service item into a ticket');
- END IF;
-
- CALL stock.log_add('sale', NEW.id, NULL);
- CALL ticket_requestRecalc(NEW.ticketFk);
-
- IF NEW.quantity > 0 THEN
-
- UPDATE vn.collection c
- JOIN vn.ticketCollection tc ON tc.collectionFk = c.id
- AND tc.ticketFk = NEW.ticketFk
- JOIN vn.item i ON i.id = NEW.itemFk
- AND (c.itemPackingTypeFk = i.itemPackingTypeFk
- OR c.itemPackingTypeFk IS NULL)
- SET c.saleTotalCount = c.saleTotalCount + 1;
-
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
- FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.route r ON r.id = t.routeFk
- WHERE r.isOk = FALSE
- AND s.id = NEW.id
- AND r.created >= util.VN_CURDATE()
- GROUP BY r.id;
- END IF;
-
- IF NEW.quantity = 0 THEN
- CALL util.debugAdd('saleZeroQuantity',
- CONCAT('[', user(), ']', ' Inserted sale: ', NEW.id));
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sale_beforeUpdate`
- BEFORE UPDATE ON `sale`
- FOR EACH ROW
-BEGIN
-/*
- IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN
- CALL util.throw('Cannot insert a service item into a ticket');
- END IF;
-*/
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.discount > 100 THEN
- SET NEW.discount = 0;
- END IF;
-
- IF old.discount > 0 AND NEW.discount = 0 THEN
- INSERT INTO ticketLog
- SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert',
- description = CONCAT('Cambio de descuento del item :', ' ', new.itemFk, ' de ', old.discount ,' a 0 ');
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sale_afterUpdate`
- AFTER UPDATE ON `sale`
- FOR EACH ROW
-BEGIN
- DECLARE vIsToSendMail BOOL;
- DECLARE vUserRole VARCHAR(255);
-
- IF !(NEW.id <=> OLD.id)
- OR !(NEW.ticketFk <=> OLD.ticketFk)
- OR !(NEW.itemFk <=> OLD.itemFk)
- OR !(NEW.quantity <=> OLD.quantity)
- OR !(NEW.created <=> OLD.created)
- OR !(NEW.isPicked <=> OLD.isPicked) THEN
- CALL stock.log_add('sale', NEW.id, OLD.id);
- END IF;
-
- IF !(NEW.price <=> OLD.price)
- OR !(NEW.ticketFk <=> OLD.ticketFk)
- OR !(NEW.itemFk <=> OLD.itemFk)
- OR !(NEW.quantity <=> OLD.quantity)
- OR !(NEW.discount <=> OLD.discount) THEN
- CALL ticket_requestRecalc(NEW.ticketFk);
- CALL ticket_requestRecalc(OLD.ticketFk);
- END IF;
-
- IF !(OLD.ticketFk <=> NEW.ticketFk) THEN
- UPDATE ticketRequest SET ticketFk = NEW.ticketFk
- WHERE saleFk = NEW.id;
- END IF;
-
- SELECT account.myUser_getName() INTO vUserRole;
- SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole;
-
- IF !(OLD.quantity <=> NEW.quantity) THEN
- SELECT COUNT(*) INTO vIsToSendMail
- FROM ticketTracking tt
- JOIN vn.state s ON s.id = tt.stateFk
- WHERE s.code='PACKED'
- AND tt.ticketFk = OLD.ticketFk
- AND vUserRole IN ('salesPerson', 'salesTeamBoss')
- LIMIT 1;
-
- IF vIsToSendMail THEN
- CALL vn.mail_insert('jefesventas@verdnatura.es',
- 'noreply@verdnatura.es',
- CONCAT('Ticket ', OLD.ticketFk ,' modificada cantidad tras encajado'),
- CONCAT('Ticket ', OLD.ticketFk ,'. ',
- 'Modificada la catidad de ', OLD.quantity, ' a ' , NEW.quantity,
- ' del artículo ', OLD.itemFk, ' tras estado encajado del ticket. ',
- 'Este email se ha generado automáticamente' )
- );
- END IF;
- IF (OLD.quantity > NEW.quantity) THEN
- INSERT INTO saleComponent(saleFk, componentFk, value)
- SELECT NEW.id, cm.id, sc.value
- FROM saleComponent sc
- JOIN component cd ON cd.id = sc.componentFk
- JOIN component cm ON cm.code = 'mana'
- WHERE saleFk = NEW.id AND cd.code = 'lastUnitsDiscount'
- ON DUPLICATE KEY UPDATE value = sc.value + VALUES(value);
-
- DELETE sc.*
- FROM vn.saleComponent sc
- JOIN component c ON c.id = sc.componentFk
- WHERE saleFk = NEW.id AND c.code = 'lastUnitsDiscount';
- END IF;
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
- FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.route r ON r.id = t.routeFk
- WHERE r.isOk = FALSE
- AND s.id = NEW.id
- AND r.created >= util.VN_CURDATE()
- GROUP BY r.id;
- END IF;
-
- IF !(ABS(NEW.isPicked) <=> ABS(OLD.isPicked)) AND NEW.quantity > 0 THEN
- UPDATE vn.collection c
- JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk
- SET c.salePickedCount = c.salePickedCount + IF(NEW.isPicked != 0, 1, -1);
- END IF;
-
- IF !(NEW.quantity <=> OLD.quantity) AND (NEW.quantity = 0 OR OLD.quantity = 0) THEN
- UPDATE vn.collection c
- JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk
- SET c.saleTotalCount = c.saleTotalCount + IF(OLD.quantity = 0, 1, -1);
- END IF;
-
- IF NEW.quantity = 0 THEN
- CALL util.debugAdd('saleZeroQuantity',
- CONCAT('[', user(), ']', ' Updated sale: ', NEW.id));
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sale_BEFORE_DELETE`
- BEFORE DELETE ON `sale`
- FOR EACH ROW
-BEGIN
- IF OLD.quantity > 0 THEN
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
- FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.route r ON r.id = t.routeFk
- WHERE r.isOk = FALSE
- AND s.id = OLD.id
- AND r.created >= util.VN_CURDATE()
- GROUP BY r.id;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sale_afterDelete`
- AFTER DELETE ON `sale`
- FOR EACH ROW
-BEGIN
- DECLARE vIsToSendMail BOOL;
- DECLARE vUserRole VARCHAR(255);
-
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'Sale',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-
- CALL stock.log_add('sale', NULL, OLD.id);
- CALL ticket_requestRecalc(OLD.ticketFk);
-
- SELECT account.myUser_getName() INTO vUserRole;
- SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole;
-
- SELECT COUNT(*) INTO vIsToSendMail
- FROM ticketTracking tt
- JOIN vn.state s ON s.id = tt.stateFk
- WHERE s.code='PACKED'
- AND tt.ticketFk = OLD.ticketFk
- AND vUserRole IN ('salesPerson', 'salesBoss')
- LIMIT 1;
-
- IF vIsToSendMail THEN
- CALL vn.mail_insert('jefesventas@verdnatura.es',
- 'noreply@verdnatura.es',
- CONCAT('Ticket ', OLD.ticketFk ,' eliminado artículo tras encajado' ),
- CONCAT('Ticket ', OLD.ticketFk ,'. ',
- 'Eliminado artículo ', OLD.itemFk, ' tras estado encajado del ticket. Este email se ha generado automáticamente' )
- );
- END IF;
-
- IF OLD.quantity > 0 THEN
- UPDATE vn.collection c
- JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = OLD.ticketFk
- JOIN vn.item i ON i.id = OLD.itemFk
- AND (c.itemPackingTypeFk = i.itemPackingTypeFk
- OR ISNULL(c.itemPackingTypeFk))
- SET c.saleTotalCount = c.saleTotalCount - 1,
- c.salePickedCount = c.salePickedCount - ABS(OLD.isPicked);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `saleBuy`
@@ -36339,53 +36875,6 @@ CREATE TABLE `saleBuy` (
CONSTRAINT `saleBuy_FK_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`BEFORE_INSERT`
- BEFORE INSERT ON `saleBuy`
- FOR EACH ROW
-BEGIN
-
- SET NEW.workerFk = vn.getUser();
-
- END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleBuy_AI`
- AFTER INSERT ON `saleBuy`
- FOR EACH ROW
-BEGIN
-/* Activar de nuevo cuando volvamos a vender fruta y verdura
- *
- UPDATE vn.sale s
- SET s.concept = CONCAT(s.concept, ' Lote: ', NEW.buyFk)
- WHERE s.id = NEW.saleFk;
-*/
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `saleCloned`
@@ -36460,7 +36949,7 @@ CREATE TABLE `saleGoal` (
`goal` decimal(10,2) DEFAULT NULL,
`goalType` smallint(6) DEFAULT NULL COMMENT 'grado',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36473,11 +36962,21 @@ DROP TABLE IF EXISTS `saleGroup`;
CREATE TABLE `saleGroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
- `userFk` int(11) DEFAULT NULL,
+ `userFk` int(10) unsigned DEFAULT NULL,
`parkingFk` int(11) DEFAULT NULL,
`sectorFk` int(11) DEFAULT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='agrupa lineas de venta';
+ `ticketFk` int(11) DEFAULT NULL,
+ `editorFk` int(10) unsigned DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `saleGroup_FK` (`ticketFk`),
+ KEY `saleGroup_userFK` (`userFk`),
+ KEY `saleGroup_parkingFK` (`parkingFk`),
+ KEY `saleGroup_sectorFK` (`sectorFk`),
+ CONSTRAINT `saleGroup_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `saleGroup_parkingFK` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `saleGroup_sectorFK` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `saleGroup_userFK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='agrupa lineas de venta';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36492,27 +36991,30 @@ CREATE TABLE `saleGroupDetail` (
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`saleFk` int(11) NOT NULL,
`saleGroupFk` int(11) NOT NULL,
+ `editorFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
+ UNIQUE KEY `saleGroupDetail_UN` (`saleFk`),
KEY `saleGroupDetail_FK_1` (`saleGroupFk`),
- KEY `saleFk` (`saleFk`),
CONSTRAINT `saleGroupDetail_ibfk_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='relaciona sale y saleGroup';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='relaciona sale y saleGroup';
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Temporary table structure for view `saleLabel`
+-- Table structure for table `saleLabel`
--
DROP TABLE IF EXISTS `saleLabel`;
-/*!50001 DROP VIEW IF EXISTS `saleLabel`*/;
-SET @saved_cs_client = @@character_set_client;
-SET character_set_client = utf8;
-/*!50001 CREATE VIEW `saleLabel` AS SELECT
- 1 AS `saleFk`,
- 1 AS `label`,
- 1 AS `stem`,
- 1 AS `created` */;
-SET character_set_client = @saved_cs_client;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `saleLabel` (
+ `saleFk` int(11) NOT NULL,
+ `label` mediumint(8) unsigned NOT NULL,
+ `stem` mediumint(8) unsigned NOT NULL,
+ `created` timestamp NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`saleFk`),
+ CONSTRAINT `saleLabel_sale_FK` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `saleMistake`
@@ -36534,7 +37036,7 @@ CREATE TABLE `saleMistake` (
CONSTRAINT `saleMistake_fk1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleMistake_fk2` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleMistake_fk3` FOREIGN KEY (`typeFk`) REFERENCES `mistakeType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36630,37 +37132,8 @@ CREATE TABLE `saleTracking` (
CONSTRAINT `saleTracking_FK` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleTracking_FK_1` FOREIGN KEY (`actionFk__`) REFERENCES `ticketTrackingState__` (`id`) ON UPDATE CASCADE,
CONSTRAINT `saleTracking_FK_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleTracking_After_Insert`
- AFTER INSERT ON `saleTracking`
- FOR EACH ROW
-BEGIN
-
- IF NEW.isChecked THEN
-
- UPDATE vn.sale s
- SET s.isPicked = TRUE
- WHERE s.id = NEW.saleFk
- AND s.isPicked = 0;
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `saleValue`
@@ -36673,7 +37146,7 @@ SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleValue` AS SELECT
1 AS `warehouse`,
1 AS `client`,
- 1 AS `clientTypeFk`,
+ 1 AS `typeFk`,
1 AS `buyer`,
1 AS `itemTypeFk`,
1 AS `family`,
@@ -36831,8 +37304,11 @@ CREATE TABLE `salespersonConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`manaMaxRate` decimal(3,2) DEFAULT 0.05 COMMENT 'Valor máximo a recficar en una línea por el maná de un comercial',
`manaMinRate` decimal(3,2) DEFAULT -0.05 COMMENT 'Valor mínimo a recficar en una línea por el maná de un comercial',
+ `manaDateFrom` date NOT NULL DEFAULT '2023-01-01' COMMENT 'first date to count mana',
+ `manaFromDays` int(11) NOT NULL DEFAULT 90 COMMENT 'Range of days from mana calculation',
+ `manaToDays` int(11) NOT NULL DEFAULT 30 COMMENT 'Range of days to mana calculation',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36852,7 +37328,67 @@ CREATE TABLE `sample` (
`datepickerEnabled` tinyint(1) NOT NULL DEFAULT 0,
`model` varchar(25) DEFAULT NULL COMMENT 'Model name in plural',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `scanner`
+--
+
+DROP TABLE IF EXISTS `scanner`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `scanner` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `modelFk` varchar(50) NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `scanner_FK` (`modelFk`),
+ CONSTRAINT `scanner_FK` FOREIGN KEY (`modelFk`) REFERENCES `scannerModel` (`code`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `scannerModel`
+--
+
+DROP TABLE IF EXISTS `scannerModel`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `scannerModel` (
+ `code` varchar(50) NOT NULL,
+ PRIMARY KEY (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `screen`
+--
+
+DROP TABLE IF EXISTS `screen`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `screen` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `modelFk` varchar(50) NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `screen_FK` (`modelFk`),
+ CONSTRAINT `screen_FK` FOREIGN KEY (`modelFk`) REFERENCES `screenModel` (`code`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `screenModel`
+--
+
+DROP TABLE IF EXISTS `screenModel`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `screenModel` (
+ `code` varchar(50) NOT NULL,
+ PRIMARY KEY (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36866,9 +37402,7 @@ CREATE TABLE `sector` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL DEFAULT 1,
- `isPreviousPreparedByPacking` tinyint(4) NOT NULL DEFAULT 1,
`code` varchar(15) DEFAULT NULL,
- `isPreviousPrepared` tinyint(1) NOT NULL DEFAULT 0,
`isPackagingArea` tinyint(1) NOT NULL DEFAULT 0,
`reportFk` tinyint(3) unsigned DEFAULT NULL,
`sonFk` int(11) DEFAULT NULL,
@@ -36878,17 +37412,19 @@ CREATE TABLE `sector` (
`isHideForPickers` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'sector a ocultar a los sacadores',
`isReserve` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Sectores de reserva, como Albenfruit o Fuentes',
`mainPrinterFk` tinyint(3) unsigned DEFAULT NULL,
- PRIMARY KEY (`id`,`warehouseFk`),
+ `typeFk` int(10) unsigned NOT NULL DEFAULT 1,
+ PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
KEY `sector_fk1_idx` (`warehouseFk`),
KEY `sector_report` (`reportFk`),
KEY `sector_FK` (`sonFk`,`warehouseFk`),
KEY `sector_FK_1` (`mainPrinterFk`),
- CONSTRAINT `sector_FK` FOREIGN KEY (`sonFk`, `warehouseFk`) REFERENCES `sector` (`id`, `warehouseFk`) ON UPDATE CASCADE,
+ KEY `sectorType_FK` (`typeFk`),
+ CONSTRAINT `sectorType_FK` FOREIGN KEY (`typeFk`) REFERENCES `sectorType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `sector_FK_1` FOREIGN KEY (`mainPrinterFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sector_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sector_report` FOREIGN KEY (`reportFk`) REFERENCES `report` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36908,7 +37444,7 @@ CREATE TABLE `sectorCollection` (
KEY `sectorCollection_FK_2` (`sectorFk`),
CONSTRAINT `sectorCollection_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sectorCollection_FK_1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Las lineas de preparacion de pedidos por sectores se agrupan bajo el identificador de esta tabla';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Las lineas de preparacion de pedidos por sectores se agrupan bajo el identificador de esta tabla';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36929,7 +37465,7 @@ CREATE TABLE `sectorCollectionSaleGroup` (
CONSTRAINT `sectorCollectionSaleGroup_ibfk_1` FOREIGN KEY (`sectorCollectionFk`) REFERENCES `sectorCollection` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sectorCollectionSaleGroup_ibfk_2` FOREIGN KEY (`saleGroupFk`) REFERENCES `saleGroup` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sectorCollectionSaleGroup_ibfk_3` FOREIGN KEY (`saleGroupFk`) REFERENCES `saleGroup` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Relaciona las lineas de venta con la coleccion del sector';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Relaciona las lineas de venta con la coleccion del sector';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36952,7 +37488,21 @@ CREATE TABLE `sectorProductivity` (
`hourWorked` decimal(10,2) DEFAULT NULL,
`dated` date DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `sectorType`
+--
+
+DROP TABLE IF EXISTS `sectorType`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `sectorType` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `code` varchar(100) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36967,7 +37517,7 @@ CREATE TABLE `sendingConfig` (
`defaultWeight` int(11) NOT NULL DEFAULT 13,
`defaultPackages` int(11) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -36998,7 +37548,7 @@ CREATE TABLE `sendingServiceWeekday` (
`weekdays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL,
`params` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de parámetros por dia de SENDING';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de parámetros por dia de SENDING';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37022,89 +37572,6 @@ CREATE TABLE `sharingCart` (
CONSTRAINT `Trabajador_key` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sharingCart_beforeInsert`
- BEFORE INSERT ON `sharingCart`
- FOR EACH ROW
-BEGIN
- IF NEW.workerFk = NEW.workerSubstitute THEN
- CALL util.throw ('worker and workerSubstitute must be different');
- ELSE
- INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated)
- SELECT NEW.workerFk, NEW.workerSubstitute, dated
- FROM time
- WHERE dated BETWEEN NEW.started AND NEW.ended;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sharingCart_beforeUpdate`
- BEFORE UPDATE ON `sharingCart`
- FOR EACH ROW
-BEGIN
- IF NEW.workerFk = NEW.workerSubstitute THEN
- CALL util.throw ('worker and workerSubstitute must be different');
- ELSE
- DELETE sc FROM sharingCartDaily sc
- WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND
- sc.ownerFk = OLD.workerFk AND
- sc.substituteFk = OLD.workerSubstitute;
-
- INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated)
- SELECT NEW.workerFk, NEW.workerSubstitute, dated
- FROM time
- WHERE dated BETWEEN NEW.started AND NEW.ended;
-
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sharingCart_beforeDelete`
- BEFORE DELETE ON `sharingCart`
- FOR EACH ROW
-BEGIN
- DELETE sc FROM sharingCartDaily sc
- WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND
- sc.ownerFk = OLD.workerFk AND
- sc.substituteFk = OLD.workerSubstitute;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `sharingCartDaily`
@@ -37124,7 +37591,7 @@ CREATE TABLE `sharingCartDaily` (
KEY `sharingCartDailySubstitute_idx` (`substituteFk`),
CONSTRAINT `sharingCartDailySubstitute` FOREIGN KEY (`substituteFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sharingCartDailyWorker` FOREIGN KEY (`ownerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='para calcular las comisiones de las sustituciones de los comerciales';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='para calcular las comisiones de las sustituciones de los comerciales';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37147,48 +37614,6 @@ CREATE TABLE `sharingClient` (
CONSTRAINT `Trabajadores_key` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sharingClient_beforeInsert`
- BEFORE INSERT ON `sharingClient`
- FOR EACH ROW
-BEGIN
- SET NEW.ended = GREATEST(util.VN_CURDATE(),NEW.ended);
- SET NEW.started = GREATEST(util.VN_CURDATE(),NEW.started);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sharingClient_beforeUpdate`
- BEFORE UPDATE ON `sharingClient`
- FOR EACH ROW
-BEGIN
- SET NEW.ended = GREATEST(util.VN_CURDATE(),NEW.ended);
- SET NEW.started = GREATEST(util.VN_CURDATE(),NEW.started);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `shelving`
@@ -37208,6 +37633,7 @@ CREATE TABLE `shelving` (
`isSpam` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'señala las matrículas con producto que se puede llevar a la reserva',
`isRecyclable` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'las matrículas marcadas como reciclables se liberan cada noche desde vn.shelving_clean para poder volver a utilizarlas',
`editorFk` int(10) unsigned DEFAULT NULL,
+ `isMoving` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `shelving_UN` (`code`),
KEY `shelving_fk1_idx` (`parkingFk`),
@@ -37216,82 +37642,8 @@ CREATE TABLE `shelving` (
CONSTRAINT `shelving_fk1` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `shelving_fk2` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `shelving_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla usada para localizar el carro en el parking del altillo';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla usada para localizar el carro en el parking del altillo';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`shelving_beforeInsert`
- BEFORE INSERT ON `shelving`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.code = "" THEN
- CALL util.throw('NOT_EMPTY_CODE_ALLOWED');
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`shelving_BEFORE_UPDATE`
- BEFORE UPDATE ON `shelving`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.code = "" THEN
- CALL util.throw('NOT_EMPTY_CODE_ALLOWED');
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`shelving_afterDelete`
- AFTER DELETE ON `shelving`
- FOR EACH ROW
-BEGIN
- INSERT INTO shelvingLog
- SET `action` = 'delete',
- `changedModel` = 'Shelving',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `shelvingLog`
@@ -37316,9 +37668,68 @@ CREATE TABLE `shelvingLog` (
KEY `userFk` (`userFk`),
KEY `shelvingLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `shelvingLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `shelvingLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `shelving` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `shelvingLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `siiTrascendencyInvoiceIn`
+--
+
+DROP TABLE IF EXISTS `siiTrascendencyInvoiceIn`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `siiTrascendencyInvoiceIn` (
+ `id` int(10) unsigned NOT NULL,
+ `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clave de régimen especial o trascendencia en facturas recibidas en el suministro de inmediato';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `siiTrascendencyInvoiceOut`
+--
+
+DROP TABLE IF EXISTS `siiTrascendencyInvoiceOut`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `siiTrascendencyInvoiceOut` (
+ `id` int(10) unsigned NOT NULL,
+ `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clave de régimen especial o trascendencia en facturas expedidas del suministro de inmediato';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `siiTypeInvoiceIn`
+--
+
+DROP TABLE IF EXISTS `siiTypeInvoiceIn`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `siiTypeInvoiceIn` (
+ `id` int(10) unsigned NOT NULL,
+ `code` varchar(2) NOT NULL,
+ `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `code_UNIQUE` (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de Factura Recibidas en el suministro de inmediato';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `siiTypeInvoiceOut`
+--
+
+DROP TABLE IF EXISTS `siiTypeInvoiceOut`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `siiTypeInvoiceOut` (
+ `id` int(10) unsigned NOT NULL,
+ `code` varchar(2) NOT NULL,
+ `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `code_UNIQUE` (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de Factura Emitidas en el suministro de inmediato';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37335,7 +37746,7 @@ CREATE TABLE `silexACL` (
`role` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `module_UNIQUE` (`module`,`method`) USING BTREE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37429,7 +37840,7 @@ CREATE TABLE `sms` (
PRIMARY KEY (`id`),
KEY `sms_FK` (`senderFk`),
CONSTRAINT `sms_FK` FOREIGN KEY (`senderFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37445,7 +37856,7 @@ CREATE TABLE `smsConfig` (
`title` varchar(50) NOT NULL,
`apiKey` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='SMS configuration parameters';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='SMS configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37465,82 +37876,6 @@ CREATE TABLE `solunionCAP` (
CONSTRAINT `solunionCAP` FOREIGN KEY (`creditInsurance`) REFERENCES `creditInsurance` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!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 */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!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 */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!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 */ ;
--
-- Table structure for table `sorter`
@@ -37583,7 +37918,7 @@ CREATE TABLE `specialLabels` (
`isVisible` tinyint(1) NOT NULL DEFAULT 0,
`image` blob DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37604,7 +37939,7 @@ CREATE TABLE `specialPrice` (
KEY `Id_Cliente` (`clientFk`),
CONSTRAINT `sp_article_id` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE,
CONSTRAINT `sp_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37619,48 +37954,8 @@ CREATE TABLE `specie` (
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `specie_UN` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`specie_BEFORE_INSERT`
- BEFORE INSERT ON `specie`
- FOR EACH ROW
-BEGIN
- SET NEW.name = LCASE(NEW.name);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`specie_BEFORE_UPDATE`
- BEFORE UPDATE ON `specie`
- FOR EACH ROW
-BEGIN
- SET NEW.name = LCASE(NEW.name);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `specieGeoInvasive`
@@ -37682,7 +37977,25 @@ CREATE TABLE `specieGeoInvasive` (
CONSTRAINT `specieGeoInvasive_FK` FOREIGN KEY (`genusFk`) REFERENCES `genus` (`id`) ON UPDATE CASCADE,
CONSTRAINT `specieGeoInvasive_FK_1` FOREIGN KEY (`specieFk`) REFERENCES `specie` (`id`) ON UPDATE CASCADE,
CONSTRAINT `specieGeoInvasive_FK_2` FOREIGN KEY (`zoneGeofk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Esta tabla recoge las prohibiciones de comerciar con especies invasoras de acuerdo con el Catálogo de Especies Exóticas Invasoras publicado por el Estado Español';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Esta tabla recoge las prohibiciones de comerciar con especies invasoras de acuerdo con el Catálogo de Especies Exóticas Invasoras publicado por el Estado Español';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `split`
+--
+
+DROP TABLE IF EXISTS `split`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `split` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `ticketFk` int(11) DEFAULT NULL,
+ `entryFk` int(11) DEFAULT NULL,
+ `dated` datetime DEFAULT NULL,
+ `note` varchar(255) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `Id_Entrada` (`entryFk`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37704,7 +38017,27 @@ CREATE TABLE `splitFilter` (
KEY `splitFilter_FK_1` (`clientFk`),
CONSTRAINT `splitFilter_FK` FOREIGN KEY (`autonomyFk`) REFERENCES `autonomy` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `splitFilter_FK_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='define los clientes que tienen split y el nombre a mostrar en la etiqueta';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='define los clientes que tienen split y el nombre a mostrar en la etiqueta';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `splitLine`
+--
+
+DROP TABLE IF EXISTS `splitLine`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `splitLine` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `splitFk` int(11) NOT NULL,
+ `itemFk` int(11) DEFAULT NULL,
+ `buyFk` int(11) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `Id_Split` (`splitFk`),
+ KEY `Id_Compra` (`buyFk`),
+ CONSTRAINT `Id_Compra` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `splitLine_ibfk_1` FOREIGN KEY (`splitFk`) REFERENCES `split` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37724,7 +38057,7 @@ CREATE TABLE `starredModule` (
KEY `starred_moduleFk` (`moduleFk`),
CONSTRAINT `starred_moduleFk` FOREIGN KEY (`moduleFk`) REFERENCES `salix`.`module` (`code`) ON UPDATE CASCADE,
CONSTRAINT `starred_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37758,7 +38091,7 @@ CREATE TABLE `state` (
KEY `state_FK` (`nextStateFk`),
CONSTRAINT `state_FK` FOREIGN KEY (`nextStateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE,
CONSTRAINT `state_ibfk_1` FOREIGN KEY (`alertLevel`) REFERENCES `alertLevel` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37796,7 +38129,7 @@ CREATE TABLE `stockBuyed` (
PRIMARY KEY (`id`),
KEY `stockBuyed_user_idx` (`userFk`),
CONSTRAINT `stockBuyedUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -37824,7 +38157,7 @@ DROP TABLE IF EXISTS `supplier`;
CREATE TABLE `supplier` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
- `account` varchar(10) DEFAULT NULL,
+ `account` varchar(10) NOT NULL DEFAULT '4100000000' COMMENT 'Default accounting code for suppliers.',
`street` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`city` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`provinceFk` smallint(5) unsigned DEFAULT NULL,
@@ -37840,7 +38173,7 @@ CREATE TABLE `supplier` (
`payDay` tinyint(4) unsigned DEFAULT NULL,
`payDemFk` tinyint(3) unsigned NOT NULL DEFAULT 7,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
- `isSerious` tinyint(1) unsigned NOT NULL DEFAULT 1,
+ `isSerious` tinyint(1) unsigned NOT NULL DEFAULT 0,
`note` text CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`postcodeFk` int(11) unsigned DEFAULT NULL,
`postCode` char(8) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
@@ -37879,109 +38212,10 @@ CREATE TABLE `supplier` (
CONSTRAINT `supplier_transactionFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
CONSTRAINT `supplier_withholdingFk` FOREIGN KEY (`withholdingSageFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON UPDATE CASCADE,
CONSTRAINT `supplier_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `suppplier_supplierActivityFk` FOREIGN KEY (`supplierActivityFk`) REFERENCES `supplierActivity` (`code`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+ CONSTRAINT `suppplier_supplierActivityFk` FOREIGN KEY (`supplierActivityFk`) REFERENCES `supplierActivity` (`code`) ON UPDATE CASCADE,
+ CONSTRAINT `supplierAccountTooShort` CHECK (octet_length(`account`) = 10)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplier_beforeInsert`
- BEFORE INSERT ON `supplier`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplier_beforeUpdate`
- BEFORE UPDATE ON `supplier`
- FOR EACH ROW
-BEGIN
- DECLARE vHasChange BOOL;
- DECLARE vPayMethodChanged BOOL;
- DECLARE vPayMethodHasVerified BOOL;
- DECLARE vParams JSON;
- DECLARE vOldPayMethodName VARCHAR(20);
- DECLARE vNewPayMethodName VARCHAR(20);
-
- SET NEW.editorFk = account.myUser_getId();
-
- SELECT hasVerified INTO vPayMethodHasVerified
- FROM payMethod
- WHERE id = NEW.payMethodFk;
-
- SET vPayMethodChanged = NOT(NEW.payMethodFk <=> OLD.payMethodFk);
-
- IF vPayMethodChanged THEN
- SELECT name INTO vOldPayMethodName
- FROM payMethod
- WHERE id = OLD.payMethodFk;
- SELECT name INTO vNewPayMethodName
- FROM payMethod
- WHERE id = NEW.payMethodFk;
-
- SET vParams = JSON_OBJECT(
- 'name', NEW.name,
- 'oldPayMethod', vOldPayMethodName,
- 'newPayMethod', vNewPayMethodName
- );
- SELECT util.notification_send('supplier-pay-method-update', vParams, NULL) INTO @id;
- END IF;
-
- SET vHasChange = NOT(NEW.payDemFk <=> OLD.payDemFk AND NEW.payDay <=> OLD.payDay) OR vPayMethodChanged;
-
- IF vHasChange AND vPayMethodHasVerified THEN
- SET NEW.isPayMethodChecked = FALSE;
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplier_afterDelete`
- AFTER DELETE ON `supplier`
- FOR EACH ROW
-BEGIN
- INSERT INTO supplierLog
- SET `action` = 'delete',
- `changedModel` = 'Supplier',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `supplierAccount`
@@ -38002,80 +38236,20 @@ CREATE TABLE `supplierAccount` (
`accountingFk` int(11) DEFAULT NULL,
`beneficiary` varchar(50) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
+ `countryFk` mediumint(8) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_supplier_country` (`supplierFk`,`countryFk`),
KEY `fk_proveedores_proveedores_account_idx` (`supplierFk`),
KEY `fk_Proveedores_account_entity1_idx` (`bankEntityFk`),
KEY `fk_banco_prov_account_idx` (`accountingFk`),
KEY `supplierAccount_fk_editor` (`editorFk`),
+ KEY `fk_supplierAccount_country` (`countryFk`),
+ CONSTRAINT `fk_supplierAccount_country` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `supplierAccount_FK_1` FOREIGN KEY (`bankEntityFk`) REFERENCES `bankEntity` (`id`) ON UPDATE CASCADE,
CONSTRAINT `supplierAccount_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `supplierAccount_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplierAccount_beforeInsert`
- BEFORE INSERT ON `supplierAccount`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplierAccount_beforeUpdate`
- BEFORE UPDATE ON `supplierAccount`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplierAccount_afterDelete`
- AFTER DELETE ON `supplierAccount`
- FOR EACH ROW
-BEGIN
- INSERT INTO supplierLog
- SET `action` = 'delete',
- `changedModel` = 'SupplierAccount',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `supplierActivity`
@@ -38100,7 +38274,7 @@ DROP TABLE IF EXISTS `supplierAddress`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierAddress` (
`id` int(11) NOT NULL AUTO_INCREMENT,
- `supplierFk` int(11) DEFAULT NULL,
+ `supplierFk` int(10) unsigned DEFAULT NULL,
`nickname` varchar(40) DEFAULT NULL,
`street` varchar(255) DEFAULT NULL,
`provinceFk` smallint(6) unsigned DEFAULT NULL,
@@ -38112,74 +38286,12 @@ CREATE TABLE `supplierAddress` (
PRIMARY KEY (`id`),
KEY `supplierAddress_province_fk` (`provinceFk`),
KEY `supplierAddress_fk_editor` (`editorFk`),
+ KEY `supplierAddress_FK` (`supplierFk`),
+ CONSTRAINT `supplierAddress_FK` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `supplierAddress_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `supplierAddress_province_fk` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplierAddress_beforeInsert`
- BEFORE INSERT ON `supplierAddress`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplierAddress_beforeUpdate`
- BEFORE UPDATE ON `supplierAddress`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplierAddress_afterDelete`
- AFTER DELETE ON `supplierAddress`
- FOR EACH ROW
-BEGIN
- INSERT INTO supplierLog
- SET `action` = 'delete',
- `changedModel` = 'SupplierAddress',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `supplierAgencyTerm`
@@ -38226,72 +38338,8 @@ CREATE TABLE `supplierContact` (
KEY `supplierContact_supplierFk` (`supplierFk`),
CONSTRAINT `supplierContact_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `supplierContact_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplierContact_beforeInsert`
- BEFORE INSERT ON `supplierContact`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplierContact_beforeUpdate`
- BEFORE UPDATE ON `supplierContact`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplierContact_afterDelete`
- AFTER DELETE ON `supplierContact`
- FOR EACH ROW
-BEGIN
- INSERT INTO supplierLog
- SET `action` = 'delete',
- `changedModel` = 'SupplierContact',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `supplierDebtConfig`
@@ -38306,6 +38354,26 @@ CREATE TABLE `supplierDebtConfig` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `supplierDms`
+--
+
+DROP TABLE IF EXISTS `supplierDms`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `supplierDms` (
+ `supplierFk` int(10) unsigned NOT NULL,
+ `dmsFk` int(11) NOT NULL,
+ `editorFk` int(10) unsigned DEFAULT NULL,
+ PRIMARY KEY (`supplierFk`,`dmsFk`),
+ KEY `user_Fk` (`editorFk`),
+ KEY `dms_Fk` (`dmsFk`),
+ CONSTRAINT `dms_Fk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `supplier_Fk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `user_Fk` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `supplierExpense`
--
@@ -38336,7 +38404,7 @@ CREATE TABLE `supplierExpense` (
CONSTRAINT `pago_moneda` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `supplierExpenseCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `supplierExpense_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -38353,7 +38421,7 @@ CREATE TABLE `supplierLog` (
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- `changedModel` enum('Supplier','SupplierAddress','SupplierAccount','SupplierContact') NOT NULL DEFAULT 'Supplier',
+ `changedModel` enum('Supplier','SupplierAddress','SupplierAccount','SupplierContact','SupplierDms') NOT NULL DEFAULT 'Supplier',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
@@ -38362,9 +38430,8 @@ CREATE TABLE `supplierLog` (
KEY `supplierLog_ibfk_2` (`userFk`),
KEY `supplierLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `supplierLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `supplierLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `supplierLog_supplierFk` FOREIGN KEY (`originFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+ CONSTRAINT `supplierLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -38441,30 +38508,8 @@ CREATE TABLE `tag` (
PRIMARY KEY (`id`),
UNIQUE KEY `tagNameIdx` (`name`,`ediTypeFk`),
UNIQUE KEY `tagEdiTypeFkIdx` (`ediTypeFk`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Categorias para etiquetar los productos';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Categorias para etiquetar los productos';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`tag_BEFORE_INSERT`
- BEFORE INSERT ON `tag`
- FOR EACH ROW
-BEGIN
- IF NEW.ediTypeFk IS NULL AND (SELECT COUNT(*) FROM tag WHERE `name` = NEW.`name`) THEN
- CALL util.throw('name duplicated');
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `tagAbbreviation`
@@ -38539,7 +38584,7 @@ CREATE TABLE `taxClass` (
`code` varchar(1) NOT NULL DEFAULT 'R',
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -38588,7 +38633,7 @@ CREATE TABLE `taxCode` (
KEY `codigo` (`code`),
KEY `tipo_index` (`type`),
CONSTRAINT `taxCode_ibfk_1` FOREIGN KEY (`taxTypeFk`) REFERENCES `taxType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -38610,7 +38655,7 @@ CREATE TABLE `taxType` (
KEY `serie_id` (`serial`),
KEY `Id_Pais` (`countryFk`),
CONSTRAINT `taxType_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -38709,249 +38754,8 @@ CREATE TABLE `ticket` (
CONSTRAINT `ticket_ibfk_8` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`),
CONSTRAINT `ticket_ibfk_9` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `tickets_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_beforeInsert`
- BEFORE INSERT ON `ticket`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_afterInsert`
- AFTER INSERT ON `ticket`
- FOR EACH ROW
-BEGIN
-
- DECLARE vClientType VARCHAR(255);
- DECLARE vStateCode VARCHAR(255);
- DECLARE vTransferorFirstShipped DATE;
-
- -- Borrar cuando se cambie el insert ticket en la APP móvil
-
- SELECT typeFk INTO vClientType
- FROM vn.`client` WHERE id = NEW.clientFk;
-
- IF vClientType = 'loses' THEN
- SET vStateCode = 'DELIVERED';
- ELSE
- SET vStateCode = 'FREE';
- END IF;
-
- CALL ticket_setState(NEW.id, vStateCode);
-
- IF YEAR(NEW.shipped) > 2000 THEN
-
- SELECT cnb.firstShipped INTO vTransferorFirstShipped
- FROM bs.clientNewBorn cnb
- JOIN `client` c ON c.transferorFk = cnb.clientFk
- WHERE c.id = NEW.clientFk;
-
- INSERT INTO bs.clientNewBorn(clientFk, firstShipped, lastShipped)
- VALUES(NEW.clientFk, IFNULL(vTransferorFirstShipped, util.VN_CURDATE()), util.VN_CURDATE())
- ON DUPLICATE KEY UPDATE lastShipped = util.VN_CURDATE();
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_beforeUpdate`
- BEFORE UPDATE ON `ticket`
- FOR EACH ROW
-BEGIN
- DECLARE vNewTime TIME;
-
- SET NEW.editorFk = account.myUser_getId();
-
- IF !(NEW.routeFk <=> OLD.routeFk) THEN
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
- FROM vn.route r
- WHERE r.isOk = FALSE
- AND r.id IN (OLD.routeFk,NEW.routeFk)
- AND r.created >= util.VN_CURDATE()
- GROUP BY r.id;
- END IF;
-
- IF !(DATE(NEW.shipped) <=> DATE(OLD.shipped)) THEN
- IF YEAR(NEW.shipped) < 2000 THEN
- SIGNAL SQLSTATE '46000'
- SET MESSAGE_TEXT = 'Year cannot be lesser than 2000';
- END IF;
-
- IF YEAR(NEW.shipped) = 2000 THEN
- SET NEW.isDeleted = TRUE;
- END IF;
-
- END IF;
-
- IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
- FROM vn.ticket t
- JOIN vn.route r ON r.id = t.routeFk
- WHERE r.isOk = FALSE
- AND t.id = NEW.id
- AND r.created >= util.VN_CURDATE()
- GROUP BY r.id;
- SET NEW.shipped = DATE_FORMAT(NEW.shipped, '2000-%m-%d %T');
- SET NEW.landed = DATE_FORMAT(NEW.landed, '2000-%m-%d %T');
- SET NEW.routeFk = NULL;
- SET NEW.zoneFk = NULL;
- END IF;
-
- IF NEW.routeFk AND NEW.isDeleted THEN
- CALL util.throw ('This ticket is deleted');
- END IF;
-
- IF !(NEW.routeFk <=> OLD.routeFk) AND NEW.routeFk IS NOT NULL THEN
- SELECT MAX(TIME(shipped)) INTO vNewTime
- FROM vn.ticket
- WHERE routeFk = NEW.routeFk
- HAVING MAX(TIME(shipped)) > TIME(NEW.shipped);
-
- IF vNewTime THEN
- SET NEW.shipped = TIMESTAMP(DATE(NEW.shipped), vNewTime);
- END IF;
- INSERT IGNORE INTO zoneAgencyMode (agencyModeFk,zoneFk)
- SELECT r.agencyModeFk, NEW.zoneFk FROM route r
- WHERE r.id = NEW.routeFk;
-
- CALL vn.routeUpdateM3(NEW.routeFk);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_afterUpdate`
- AFTER UPDATE ON `ticket`
- FOR EACH ROW
-BEGIN
-
- IF !(NEW.id <=> OLD.id)
- OR !(NEW.warehouseFk <=> OLD.warehouseFk)
- OR !(NEW.shipped <=> OLD.shipped) THEN
- CALL stock.log_add('ticket', NEW.id, OLD.id);
- END IF;
-
- IF !(NEW.clientFk <=> OLD.clientFk)
- OR !(NEW.addressFk <=> OLD.addressFk)
- OR !(NEW.companyFk <=> OLD.companyFk) THEN
- CALL ticket_requestRecalc(NEW.id);
- END IF;
-
- IF NEW.routeFk <> OLD.routeFk THEN
- UPDATE expedition
- SET hasNewRoute = TRUE
- WHERE ticketFk = NEW.id;
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_beforeDelete`
- BEFORE DELETE ON `ticket`
- FOR EACH ROW
-BEGIN
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
- FROM vn.route r
- WHERE r.isOk = FALSE
- AND r.id = OLD.routeFk
- AND r.created >= util.VN_CURDATE()
- GROUP BY r.id;
-
- DELETE FROM sale WHERE ticketFk = OLD.id;
-
- DELETE FROM ticketDms WHERE ticketFk = OLD.id;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_afterDelete`
- AFTER DELETE ON `ticket`
- FOR EACH ROW
-BEGIN
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'Ticket',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ticketCollection`
@@ -38980,48 +38784,8 @@ CREATE TABLE `ticketCollection` (
CONSTRAINT `ticketCollection_FK` FOREIGN KEY (`smartTagFk`) REFERENCES `smartTag` (`code`) ON UPDATE CASCADE,
CONSTRAINT `ticketCollection_fk1` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketCollection_fk2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete
-AFTER DELETE
-ON ticketCollection FOR EACH ROW
-BEGIN
-
- DECLARE vSalesRemaining INT;
-
- SELECT count(*) INTO vSalesRemaining
- FROM vn.ticketCollection tc
- JOIN sale s ON s.ticketFk = tc.ticketFk
- WHERE collectionFk = OLD.collectionFk
- AND tc.id != OLD.id;
-
- IF NOT vSalesRemaining THEN
-
- DELETE FROM vn.collection WHERE id = OLD.collectionFk;
-
- ELSE
-
- UPDATE vn.collection
- SET saleTotalCount = vSalesRemaining
- WHERE id = OLD.collectionFk;
-
- END IF;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ticketConfig`
@@ -39038,7 +38802,7 @@ CREATE TABLE `ticketConfig` (
`packingDelay` int(11) DEFAULT 1 COMMENT 'Horas que marcará el retraso respecto hora de cierre web del ticket',
`daysForWarningClaim` int(11) NOT NULL DEFAULT 2 COMMENT 'dias restantes hasta que salte el aviso de reclamación fuera de plazo',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -39060,98 +38824,6 @@ CREATE TABLE `ticketDms` (
CONSTRAINT `ticketDms_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketDms_beforeInsert`
- BEFORE INSERT ON `ticketDms`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketDms_beforeUpdate`
- BEFORE UPDATE ON `ticketDms`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketDms_beforeDelete`
- BEFORE DELETE ON `ticketDms`
- FOR EACH ROW
-BEGIN
- UPDATE dms
- SET dmsTypeFk = (SELECT id
- FROM dmsType
- WHERE `code` = 'trash'
- )
- WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE)
- FROM ticketDms
- WHERE dmsFk = OLD.dmsFk
- ) ;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketDms_afterDelete`
- AFTER DELETE ON `ticketDms`
- FOR EACH ROW
-BEGIN
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'ticketDms',
- `changedModelId` = OLD.ticketFk,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ticketDocumentation`
@@ -39185,9 +38857,25 @@ CREATE TABLE `ticketDown` (
KEY `ticketDown_FK` (`collectionFk`),
CONSTRAINT `ticketDown_FK` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketDown_fk1` FOREIGN KEY (`selected`) REFERENCES `ticketDown_SelectionType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Cola de impresion para los tickets que se van a solicitar al altillo';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Cola de impresion para los tickets que se van a solicitar al altillo';
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Temporary table structure for view `ticketDownBuffer`
+--
+
+DROP TABLE IF EXISTS `ticketDownBuffer`;
+/*!50001 DROP VIEW IF EXISTS `ticketDownBuffer`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `ticketDownBuffer` AS SELECT
+ 1 AS `ticketFk`,
+ 1 AS `created`,
+ 1 AS `selected`,
+ 1 AS `sacador`,
+ 1 AS `parking` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `ticketDown_SelectionType`
--
@@ -39270,9 +38958,8 @@ CREATE TABLE `ticketLog` (
KEY `logTicketuserFk` (`userFk`),
KEY `ticketLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `ticketLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `ticketLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketLog_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -39339,72 +39026,8 @@ CREATE TABLE `ticketObservation` (
CONSTRAINT `ticketObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `ticketObservation_ibfk_1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketObservation_ibfk_2` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a un ticket';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a un ticket';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketObservation_beforeInsert`
- BEFORE INSERT ON `ticketObservation`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketObservation_beforeUpdate`
- BEFORE UPDATE ON `ticketObservation`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketObservation_afterDelete`
- AFTER DELETE ON `ticketObservation`
- FOR EACH ROW
-BEGIN
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'TicketObservation',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ticketPackage`
@@ -39446,74 +39069,8 @@ CREATE TABLE `ticketPackaging` (
CONSTRAINT `ticketPackaging_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticketPackaging_fk3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketPackaging_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketPackaging_BEFORE_INSERT`
- BEFORE INSERT ON `ticketPackaging`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
- SET NEW.workerFk = account.myUser_getId();
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketPackaging_beforeUpdate`
- BEFORE UPDATE ON `ticketPackaging`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketPackaging_afterDelete`
- AFTER DELETE ON `ticketPackaging`
- FOR EACH ROW
-BEGIN
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'TicketPackaging',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ticketPackagingStartingStock`
@@ -39578,30 +39135,8 @@ CREATE TABLE `ticketParking` (
KEY `ticketParking_fk1_idx` (`parkingFk`),
CONSTRAINT `ticketParking_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketParking_fk2` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena los distintos lugares donde puede estar aparcado cada uno de los prepedidos';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena los distintos lugares donde puede estar aparcado cada uno de los prepedidos';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketParking_BEFORE_INSERT`
- BEFORE INSERT ON `ticketParking`
- FOR EACH ROW
-BEGIN
-
- SET NEW.workerFk = vn.getUser();
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `ticketPreviousPreparingList`
@@ -39635,7 +39170,7 @@ CREATE TABLE `ticketRecalc` (
`ticketFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `ticketRecalc_ibfk_1` (`ticketFk`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed tickets to recalc its total';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed tickets to recalc its total';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -39657,74 +39192,8 @@ CREATE TABLE `ticketRefund` (
CONSTRAINT `ticketRefund_FK` FOREIGN KEY (`refundTicketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketRefund_FK_1` FOREIGN KEY (`originalTicketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticketRefund_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketRefund_beforeInsert`
- BEFORE INSERT ON `ticketRefund`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
- CALL ticketRefund_beforeUpsert(NEW.refundTicketFk, NEW.originalTicketFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketRefund_beforeUpdate`
- BEFORE UPDATE ON `ticketRefund`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
- CALL ticketRefund_beforeUpsert(NEW.refundTicketFk, NEW.originalTicketFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketRefund_afterDelete`
- AFTER DELETE ON `ticketRefund`
- FOR EACH ROW
-BEGIN
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'TicketRefund',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ticketRequest`
@@ -39770,96 +39239,8 @@ CREATE TABLE `ticketRequest` (
CONSTRAINT `fgnRequester` FOREIGN KEY (`requesterFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fgnTicket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketRequest_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeInsert`
- BEFORE INSERT ON `ticketRequest`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.ticketFk IS NULL THEN
- SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk);
- END IF;
-
- IF NEW.requesterFk IS NULL THEN
- SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode);
- END IF;
-
- IF NEW.attenderFk IS NULL THEN
- SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeUpdate`
- BEFORE UPDATE ON `ticketRequest`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF NEW.saleFk <> OLD.saleFk THEN
- SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk);
- END IF;
-
- IF NEW.salesPersonCode <> OLD.salesPersonCode THEN
- SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode);
- END IF;
-
- IF NEW.buyerCode <> OLD.buyerCode THEN
- SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketRequest_afterDelete`
- AFTER DELETE ON `ticketRequest`
- FOR EACH ROW
-BEGIN
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'TicketRequest',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ticketService`
@@ -39886,122 +39267,8 @@ CREATE TABLE `ticketService` (
CONSTRAINT `ticketServiceIvaGroup` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticketService_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `ticketService_ticketServiceType` FOREIGN KEY (`ticketServiceTypeFk`) REFERENCES `ticketServiceType` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Servicios asociadas a un ticket';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Servicios asociadas a un ticket';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketService_beforeInsert`
- BEFORE INSERT ON `ticketService`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketService_ai`
- AFTER INSERT ON `ticketService`
- FOR EACH ROW
-BEGIN
-
- CALL ticket_requestRecalc(NEW.ticketFk);
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketService_beforeUpdate`
- BEFORE UPDATE ON `ticketService`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketService_au`
- AFTER UPDATE ON `ticketService`
- FOR EACH ROW
-BEGIN
- IF !(NEW.price <=> OLD.price)
- OR !(NEW.ticketFk <=> OLD.ticketFk)
- OR !(NEW.quantity <=> OLD.quantity) THEN
- CALL ticket_requestRecalc(NEW.ticketFk);
- CALL ticket_requestRecalc(OLD.ticketFk);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketService_ad`
- AFTER DELETE ON `ticketService`
- FOR EACH ROW
-BEGIN
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'TicketService',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-
- CALL ticket_requestRecalc(OLD.ticketFk);
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ticketServiceType`
@@ -40013,21 +39280,21 @@ DROP TABLE IF EXISTS `ticketServiceType`;
CREATE TABLE `ticketServiceType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
- `expenceFk` varchar(10) NOT NULL DEFAULT '7050000000',
+ `expenseFk` varchar(10) NOT NULL DEFAULT '7050000000',
PRIMARY KEY (`id`),
- KEY `ticketServiceType_expenceFk_idx` (`expenceFk`),
- CONSTRAINT `ticketServiceType_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Lista de los posibles servicios a elegir';
+ KEY `ticketServiceType_expenceFk_idx` (`expenseFk`),
+ CONSTRAINT `ticketServiceType_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Lista de los posibles servicios a elegir';
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `ticketSms`
+-- Table structure for table `ticketSms__`
--
-DROP TABLE IF EXISTS `ticketSms`;
+DROP TABLE IF EXISTS `ticketSms__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `ticketSms` (
+CREATE TABLE `ticketSms__` (
`smsFk` mediumint(8) unsigned NOT NULL,
`ticketFk` int(11) DEFAULT NULL,
PRIMARY KEY (`smsFk`),
@@ -40048,14 +39315,12 @@ SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketState` AS SELECT
1 AS `updated`,
1 AS `stateFk`,
- 1 AS `workerFk`,
+ 1 AS `userFk`,
1 AS `ticketFk`,
1 AS `state`,
1 AS `productionOrder`,
1 AS `alertLevel`,
1 AS `code`,
- 1 AS `ticket`,
- 1 AS `worker`,
1 AS `isPreviousPreparable`,
1 AS `isPicked` */;
SET character_set_client = @saved_cs_client;
@@ -40069,16 +39334,45 @@ DROP TABLE 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 `ticketFk`,
1 AS `state`,
1 AS `productionOrder`,
1 AS `alertLevel`,
- 1 AS `worker`,
+ 1 AS `userFk`,
1 AS `code`,
1 AS `updated`,
1 AS `isPicked` */;
SET character_set_client = @saved_cs_client;
+--
+-- Temporary table structure for view `ticketToPrepare`
+--
+
+DROP TABLE IF EXISTS `ticketToPrepare`;
+/*!50001 DROP VIEW IF EXISTS `ticketToPrepare`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `ticketToPrepare` AS SELECT
+ 1 AS `Id_Ticket`,
+ 1 AS `Id_Movimiento`,
+ 1 AS `Id_Movimiento_mark`,
+ 1 AS `Id_Trabjador`,
+ 1 AS `Id_Article`,
+ 1 AS `Concepte`,
+ 1 AS `subName`,
+ 1 AS `Cantidad`,
+ 1 AS `original_quantity`,
+ 1 AS `Hora`,
+ 1 AS `Departure`,
+ 1 AS `Minuto`,
+ 1 AS `agency_id`,
+ 1 AS `warehouse_id`,
+ 1 AS `province_id`,
+ 1 AS `picked`,
+ 1 AS `zoneFk`,
+ 1 AS `sectorFk` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `ticketTracking`
--
@@ -40093,11 +39387,11 @@ CREATE TABLE `ticketTracking` (
`notes` varchar(255) DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
`ticketFk` int(11) DEFAULT NULL,
- `workerFk` int(11) DEFAULT NULL,
+ `userFk` int(10) unsigned DEFAULT NULL,
`supervisorFk` int(10) unsigned DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
- KEY `currante` (`workerFk`),
+ KEY `currante` (`userFk`),
KEY `responsable` (`supervisorFk`),
KEY `ticket` (`ticketFk`),
KEY `inter_state` (`stateFk`),
@@ -40106,171 +39400,11 @@ CREATE TABLE `ticketTracking` (
KEY `ticketTracking_created_IDX` (`created`) USING BTREE,
CONSTRAINT `inter_state` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE,
CONSTRAINT `responsable` FOREIGN KEY (`supervisorFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `ticketTracking_FK3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticketTracking_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `ticketTracking_ibfk_1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketTracking_beforeInsert`
- BEFORE INSERT ON `ticketTracking`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketTracking_afterInsert`
- AFTER INSERT ON `ticketTracking`
- FOR EACH ROW
-BEGIN
- DECLARE vNumTicketsPrepared INT;
-
- REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name)
- SELECT NEW.ticketFk, NEW.id, `name`
- FROM state
- WHERE id = NEW.stateFk;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketTracking_beforeUpdate`
- BEFORE UPDATE ON `ticketTracking`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketTracking_afterUpdate`
- AFTER UPDATE ON `ticketTracking`
- FOR EACH ROW
-BEGIN
- DECLARE vTicketFk INT;
- DECLARE vTicketTrackingFk INT;
- DECLARE vStateName VARCHAR(15);
-
- IF NEW.stateFk <> OLD.stateFk THEN
- REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name)
- SELECT NEW.ticketFk, NEW.id, `name`
- FROM state
- WHERE id = NEW.stateFk;
- END IF;
-
- IF NEW.ticketFk <> OLD.ticketFk THEN
- SELECT i.ticketFk, i.id, s.`name`
- INTO vTicketFk, vTicketTrackingFk, vStateName
- FROM ticketTracking i
- JOIN state s ON i.stateFk = s.id
- WHERE ticketFk = NEW.ticketFk
- ORDER BY created DESC
- LIMIT 1;
-
- IF vTicketFk > 0 THEN
- REPLACE INTO ticketLastState(ticketFk, ticketTrackingFk,name)
- VALUES(vTicketFk, vTicketTrackingFk, vStateName);
- END IF;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketTracking_afterDelete`
- AFTER DELETE ON `ticketTracking`
- FOR EACH ROW
-BEGIN
- DECLARE vTicketFk INT;
- DECLARE vTicketTrackingFk INT;
- DECLARE vStateName VARCHAR(15);
-
- DECLARE CONTINUE HANDLER FOR SQLSTATE '23000'
- BEGIN
- DELETE FROM vn.ticketLastState
- WHERE ticketFk = OLD.ticketFk;
- END;
-
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'TicketTracking',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-
- CALL util.debugAdd('deletedState',
- CONCAT('interFk: ', OLD.id,
- ' ticketFk: ', OLD.ticketFk,
- ' stateFk: ', OLD.stateFk));
-
- SELECT i.ticketFk, i.id, s.`name`
- INTO vTicketFk, vTicketTrackingFk, vStateName
- FROM ticketTracking i
- JOIN state s ON i.stateFk = s.id
- WHERE ticketFk = OLD.ticketFk
- ORDER BY created DESC
- LIMIT 1;
-
- IF vTicketFk > 0 THEN
- REPLACE INTO ticketLastState(ticketFk, ticketTrackingFk,name)
- VALUES(vTicketFk, vTicketTrackingFk, vStateName);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `ticketTrackingState__`
@@ -40283,7 +39417,7 @@ CREATE TABLE `ticketTrackingState__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`action` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -40313,7 +39447,7 @@ CREATE TABLE `ticketUpdateAction` (
`description` varchar(45) NOT NULL,
`code` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla pondremos las distintas opciones que se ofrecen al comecial o al cliente al cambiar alguno de los parametros básicos de un ticket';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla pondremos las distintas opciones que se ofrecen al comecial o al cliente al cambiar alguno de los parametros básicos de un ticket';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -40334,72 +39468,37 @@ CREATE TABLE `ticketWeekly` (
CONSTRAINT `Id_Ticket_fk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agencyModeFk` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `ticketWeekly_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketWeekly_beforeInsert`
- BEFORE INSERT ON `ticketWeekly`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketWeekly_beforeUpdate`
- BEFORE UPDATE ON `ticketWeekly`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticketWeekly_afterDelete`
- AFTER DELETE ON `ticketWeekly`
- FOR EACH ROW
-BEGIN
- INSERT INTO ticketLog
- SET `action` = 'delete',
- `changedModel` = 'TicketWeekly',
- `changedModelId` = OLD.ticketFk,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
+
+--
+-- Temporary table structure for view `ticketeToPreparePrepared`
+--
+
+DROP TABLE IF EXISTS `ticketeToPreparePrepared`;
+/*!50001 DROP VIEW IF EXISTS `ticketeToPreparePrepared`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `ticketeToPreparePrepared` AS SELECT
+ 1 AS `Id_Ticket`,
+ 1 AS `Id_Movimiento`,
+ 1 AS `Id_Movimiento_mark`,
+ 1 AS `Id_Trabjador`,
+ 1 AS `Id_Article`,
+ 1 AS `Concepte`,
+ 1 AS `subName`,
+ 1 AS `Cantidad`,
+ 1 AS `original_quantity`,
+ 1 AS `Hora`,
+ 1 AS `Departure`,
+ 1 AS `Minuto`,
+ 1 AS `agency_id`,
+ 1 AS `warehouse_id`,
+ 1 AS `province_id`,
+ 1 AS `picked`,
+ 1 AS `trabajador`,
+ 1 AS `sectorFk` */;
+SET character_set_client = @saved_cs_client;
--
-- Table structure for table `till`
@@ -40414,7 +39513,7 @@ CREATE TABLE `till` (
`isAccountable` tinyint(1) NOT NULL DEFAULT 0,
`serie` varchar(2) DEFAULT NULL,
`number` int(11) DEFAULT NULL,
- `concept` varchar(50) NOT NULL,
+ `concept` varchar(50) DEFAULT NULL,
`in` decimal(10,2) DEFAULT NULL,
`out` decimal(10,2) DEFAULT NULL,
`bankFk` int(11) DEFAULT 1,
@@ -40439,30 +39538,8 @@ CREATE TABLE `till` (
KEY `fk_Cajas_Proveedores_account1_idx` (`supplierAccountFk`),
CONSTRAINT `till_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `till_ibfk_3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`till_beforeInsert`
- BEFORE INSERT ON `till`
- FOR EACH ROW
-BEGIN
- IF NEW.concept IS NULL OR NEW.concept REGEXP '^[[:space:]]*$' THEN
- SET NEW.concept = 'SIN DETALLE';
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `tillConfig`
@@ -40504,47 +39581,6 @@ CREATE TABLE `time` (
KEY `yearMonth` (`yearMonth`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla de referencia para las semanas, años y meses';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`time_AFTER_UPDATE`
- AFTER UPDATE ON `time`
- FOR EACH ROW
-BEGIN
- /*INSERT INTO vn.mail SET
- `sender` = 'jgallego@verdnatura.es',
- `replyTo` = 'jgallego@verdnatura.es',
- `subject` = 'tabla time modificada',
- `body` = CONCAT(account.myUser_getName(), ' ha modificado la tabla time ',
- NEW.`dated`);*/
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-
---
--- Table structure for table `timeControlDevice`
---
-
-DROP TABLE IF EXISTS `timeControlDevice`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `timeControlDevice` (
- `id` int(10) NOT NULL AUTO_INCREMENT,
- `name` varchar(255) DEFAULT NULL,
- `key` varchar(255) DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `name_UNIQUE` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `town`
@@ -40562,99 +39598,8 @@ CREATE TABLE `town` (
KEY `name_idx` (`name`),
KEY `townProvinceFk` (`provinceFk`),
CONSTRAINT `townProvinceFk` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`town_beforeInsert`
- BEFORE INSERT ON `town`
- FOR EACH ROW
-BEGIN
- SET NEW.geoFk = zoneGeo_new('town', NEW.`name`,
- (SELECT geoFk FROM province WHERE id = NEW.provinceFk));
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`town_beforeUpdate`
- BEFORE UPDATE ON `town`
- FOR EACH ROW
-BEGIN
- -- IF !(OLD.geoFk <=> NEW.geoFk) THEN
- -- CALL zoneGeo_throwNotEditable;
- -- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`town_afterUpdate`
- AFTER UPDATE ON `town`
- FOR EACH ROW
-BEGIN
- IF !(OLD.provinceFk <=> NEW.provinceFk) THEN
- CALL zoneGeo_setParent(NEW.geoFk,
- (SELECT geoFk FROM province WHERE id = NEW.provinceFk));
- END IF;
-
- IF !(OLD.`name` <=> NEW.`name`) THEN
- UPDATE zoneGeo SET `name` = NEW.`name`
- WHERE id = NEW.geoFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`town_afterDelete`
- AFTER DELETE ON `town`
- FOR EACH ROW
-BEGIN
- CALL zoneGeo_delete(OLD.geoFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Temporary table structure for view `tr2`
@@ -40728,7 +39673,7 @@ CREATE TABLE `train` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define la configuración de los carros que se utilizan para sacar pedidos';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define la configuración de los carros que se utilizan para sacar pedidos';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -40742,7 +39687,7 @@ CREATE TABLE `trainingCenter` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -40771,7 +39716,7 @@ CREATE TABLE `trainingCourse` (
CONSTRAINT `frgnCenter` FOREIGN KEY (`centerFk`) REFERENCES `trainingCenter` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `frgnTrainingCourseType` FOREIGN KEY (`trainingCourseTypeFk`) REFERENCES `trainingCourseType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `frgnWorker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de trabajadores que han realizado una formación';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de trabajadores que han realizado una formación';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -40785,7 +39730,26 @@ CREATE TABLE `trainingCourseType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de las formaciones';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de las formaciones';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `transitoryDuaUnified`
+--
+
+DROP TABLE IF EXISTS `transitoryDuaUnified`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `transitoryDuaUnified` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `supplierFk` int(10) unsigned DEFAULT NULL,
+ `countryCodeFk` varchar(2) NOT NULL DEFAULT 'EC',
+ PRIMARY KEY (`id`),
+ KEY `transitoryDuaUnified_FK` (`supplierFk`),
+ KEY `transitoryDuaUnified_country_FK` (`countryCodeFk`),
+ CONSTRAINT `transitoryDuaUnified_FK` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `transitoryDuaUnified_country_FK` FOREIGN KEY (`countryCodeFk`) REFERENCES `country` (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Transitarios que al contabilizar sus entradas sólo generan un único DUA para todos los proveedores';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -40803,7 +39767,7 @@ CREATE TABLE `travel` (
`landingHour` time DEFAULT NULL,
`warehouseInFk` smallint(6) unsigned DEFAULT NULL,
`warehouseOutFk` smallint(6) unsigned DEFAULT NULL,
- `agencyFk` int(11) DEFAULT NULL,
+ `agencyFk__` smallint(5) unsigned NOT NULL COMMENT '@deprecated 2024-10-01 refs #6604',
`ref` varchar(20) DEFAULT NULL,
`isDelivered` tinyint(1) NOT NULL DEFAULT 0,
`isReceived` tinyint(1) NOT NULL DEFAULT 0,
@@ -40815,9 +39779,10 @@ CREATE TABLE `travel` (
`agencyModeFk` int(11) DEFAULT NULL,
`clonedFrom` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
+ `awbFk` smallint(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
- UNIQUE KEY `shipment_1` (`shipped`,`landed`,`warehouseInFk`,`warehouseOutFk`,`agencyFk`,`agencyModeFk`,`ref`),
- KEY `agency_id` (`agencyFk`),
+ UNIQUE KEY `shipment_1` (`shipped`,`landed`,`warehouseInFk`,`warehouseOutFk`,`agencyModeFk`,`ref`),
+ KEY `agency_id` (`agencyFk__`),
KEY `shipment` (`shipped`),
KEY `landing` (`landed`),
KEY `warehouse_landing` (`warehouseInFk`,`landed`),
@@ -40825,136 +39790,14 @@ CREATE TABLE `travel` (
KEY `travel_ibfk_4_idx` (`cargoSupplierFk`),
KEY `travel_FK` (`agencyModeFk`),
KEY `travel_fk_editor` (`editorFk`),
+ KEY `travel_FK_1` (`awbFk`),
CONSTRAINT `travel_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `travel_FK_1` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travel_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `travel_ibfk_1` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `travel_ibfk_2` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `travel_ibfk_3` FOREIGN KEY (`agencyFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=DYNAMIC;
+ CONSTRAINT `travel_ibfk_2` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`travel_beforeInsert`
- BEFORE INSERT ON `travel`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- CALL travel_checkDates(NEW.shipped, NEW.landed);
-
- -- Actualizar agencyFk y agencyModeFk
- IF NEW.agencyFk THEN
- SET NEW.agencyModeFk = NEW.agencyFk;
- END IF;
-
- IF NEW.agencyModeFk THEN
- SET NEW.agencyFk = NEW.agencyModeFk;
- END IF;
-
- CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`travel_beforeUpdate`
- BEFORE UPDATE ON `travel`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-
- IF NOT (NEW.landed <=> OLD.landed)
- OR NOT (NEW.shipped <=> OLD.shipped) THEN
- CALL travel_checkDates(NEW.shipped, NEW.landed);
- END IF;
-
- -- Actualizar agencyFk y agencyModeFk
- IF NOT (NEW.agencyFk <=> OLD.agencyFk)THEN
- SET NEW.agencyModeFk = NEW.agencyFk;
- END IF;
-
- IF NOT (NEW.agencyModeFk <=> OLD.agencyModeFk) THEN
- SET NEW.agencyFk = NEW.agencyModeFk;
- END IF;
-
- IF NOT (NEW.isReceived <=> OLD.isReceived) THEN
- CALL travel_checkPackaging(NEW.id);
- END IF;
-
- CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`travel_afterUpdate`
- AFTER UPDATE ON `travel`
- FOR EACH ROW
-BEGIN
- CALL stock.log_add('travel', NEW.id, OLD.id);
-
- IF !(NEW.shipped <=> OLD.shipped) THEN
- UPDATE entry
- SET commission = entry_getCommission(travelFk, currencyFk,supplierFk)
- WHERE travelFk = NEW.id;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`travel_afterDelete`
- AFTER DELETE ON `travel`
- FOR EACH ROW
-BEGIN
- INSERT INTO travelLog
- SET `action` = 'delete',
- `changedModel` = 'Travel',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `travelClonedWeekly`
@@ -40987,7 +39830,7 @@ CREATE TABLE `travelClonedWeekly` (
CONSTRAINT `travelClonedWeekly_FK_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travelClonedWeekly_FK_4` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travelClonedWeekly_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41038,9 +39881,8 @@ CREATE TABLE `travelLog` (
KEY `userFk` (`userFk`),
KEY `travelLog_changedModel` (`changedModel`,`changedModelId`,`originFk`),
KEY `travelLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41057,7 +39899,7 @@ CREATE TABLE `travelObservation` (
`description` text NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Observaciones de travel';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Observaciones de travel';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41103,72 +39945,8 @@ CREATE TABLE `travelThermograph` (
CONSTRAINT `travelThermographTravelFgn` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`),
CONSTRAINT `travelThermographWarehouseFgn` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE,
CONSTRAINT `travelThermograph_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Registra cada termografo que se ha introducido en cada travel';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Registra cada termografo que se ha introducido en cada travel';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`travelThermograph_beforeInsert`
- BEFORE INSERT ON `travelThermograph`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`travelThermograph_beforeUpdate`
- BEFORE UPDATE ON `travelThermograph`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`travelThermograph_afterDelete`
- AFTER DELETE ON `travelThermograph`
- FOR EACH ROW
-BEGIN
- INSERT INTO travelLog
- SET `action` = 'delete',
- `changedModel` = 'TravelThermograph',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `trolley`
@@ -41184,7 +39962,7 @@ CREATE TABLE `trolley` (
PRIMARY KEY (`id`),
KEY `trolley_FK` (`workerFk`),
CONSTRAINT `trolley_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41201,7 +39979,10 @@ CREATE TABLE `userConfig` (
`created` timestamp NULL DEFAULT current_timestamp(),
`updated` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`darkMode` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Salix interface dark mode',
- PRIMARY KEY (`userFk`)
+ `tabletFk` varchar(100) DEFAULT NULL,
+ PRIMARY KEY (`userFk`),
+ KEY `tabletFk` (`tabletFk`),
+ CONSTRAINT `userConfig_ibfk_1` FOREIGN KEY (`tabletFk`) REFERENCES `docuwareTablet` (`tablet`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de usuario en Salix';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -41227,7 +40008,6 @@ CREATE TABLE `userLog` (
PRIMARY KEY (`id`),
KEY `originFk` (`originFk`),
KEY `userFk` (`userFk`),
- CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -41291,6 +40071,11 @@ CREATE TABLE `vehicle` (
`ppeFk` int(11) DEFAULT NULL,
`countryCodeFk` varchar(2) DEFAULT 'ES',
`leasing` varchar(50) DEFAULT NULL COMMENT 'Id de arrendamiento',
+ `supplierFk` int(10) unsigned DEFAULT NULL COMMENT 'supplier from whom the vehicle was purchased',
+ `import` decimal(10,2) DEFAULT NULL,
+ `supplierCoolerFk` int(10) unsigned DEFAULT NULL,
+ `vin` varchar(50) DEFAULT NULL,
+ `bankPolicyFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `vehicle_UN` (`numberPlate`),
KEY `empresa_id` (`companyFk`),
@@ -41298,53 +40083,19 @@ CREATE TABLE `vehicle` (
KEY `vehicle_deliveryPointFk_idx` (`deliveryPointFk`),
KEY `vehicle_FK` (`fuelTypeFk`),
KEY `vehicle_FK_1` (`ppeFk`),
+ KEY `vehicle_supplierFk` (`supplierFk`),
+ KEY `vehicle_supplierCoolerFk` (`supplierCoolerFk`),
+ KEY `vehicle_bankPolicyFk` (`bankPolicyFk`),
CONSTRAINT `provinceFk` FOREIGN KEY (`warehouseFk`) REFERENCES `province` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `vehicleCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `vehicle_FK` FOREIGN KEY (`fuelTypeFk`) REFERENCES `fuelType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `vehicle_FK_1` FOREIGN KEY (`ppeFk`) REFERENCES `ppe` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT `vehicle_deliveryPointFk` FOREIGN KEY (`deliveryPointFk`) REFERENCES `deliveryPoint` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ CONSTRAINT `vehicle_bankPolicyFk` FOREIGN KEY (`bankPolicyFk`) REFERENCES `bankPolicy` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `vehicle_deliveryPointFk` FOREIGN KEY (`deliveryPointFk`) REFERENCES `deliveryPoint` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `vehicle_supplierCoolerFk` FOREIGN KEY (`supplierCoolerFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `vehicle_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`vehicle_beforeInsert`
- BEFORE INSERT ON `vehicle`
- FOR EACH ROW
-BEGIN
- CALL vehicle_checkNumberPlate(NEW.numberPlate, NEW.countryCodeFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`vehicle_beforeUpdate`
- BEFORE UPDATE ON `vehicle`
- FOR EACH ROW
-BEGIN
- CALL vehicle_checkNumberPlate(NEW.numberPlate, NEW.countryCodeFk);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `vehicleConfig`
@@ -41358,6 +40109,40 @@ CREATE TABLE `vehicleConfig` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `vehicleConsumption`
+--
+
+DROP TABLE IF EXISTS `vehicleConsumption`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `vehicleConsumption` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `vehicleFk` int(10) unsigned NOT NULL,
+ `dated` date NOT NULL,
+ `km` int(20) unsigned NOT NULL,
+ `liters` double unsigned NOT NULL,
+ `price` double unsigned NOT NULL,
+ `adblue` decimal(10,2) NOT NULL DEFAULT 0.00,
+ `tolls` double DEFAULT NULL,
+ `discount` double DEFAULT NULL,
+ `silla` int(11) NOT NULL DEFAULT 0 COMMENT 'indica si han repostado en la gasolinera de la rotonda',
+ `created` timestamp NULL DEFAULT current_timestamp(),
+ `others` double DEFAULT NULL,
+ `fuelTypeFk` varchar(45) DEFAULT NULL,
+ `supplierFk` int(10) unsigned DEFAULT NULL,
+ `liters100km` decimal(10,2) DEFAULT NULL COMMENT 'se rellena en Vehiculos_consumo_beforeInsert y son los litros consumidos a los 100 kilometros',
+ `gasoline` decimal(10,2) NOT NULL DEFAULT 0.00,
+ PRIMARY KEY (`id`,`vehicleFk`),
+ KEY `fk_Vehiculos_consumo_Vehiculos_idx` (`vehicleFk`),
+ KEY `fuelTypeFk_idx` (`fuelTypeFk`),
+ KEY `proveedoresFk_idx` (`supplierFk`),
+ CONSTRAINT `Vehiculos_consumo_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
+ CONSTRAINT `fk_Vehiculos_consumo_Vehiculos` FOREIGN KEY (`vehicleFk`) REFERENCES `vehicle` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `fuelTypeFk` FOREIGN KEY (`fuelTypeFk`) REFERENCES `fuelType` (`code`) ON DELETE NO ACTION ON UPDATE NO ACTION
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla apuntan el importe de los tickets de la gasolinera solred, con quien tenemos un contrato y nos facturan mensualmente';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `vehicleDms`
--
@@ -41374,7 +40159,7 @@ CREATE TABLE `vehicleDms` (
KEY `vehicleDms_FK_1` (`dmsFk`),
CONSTRAINT `vehicleDms_FK` FOREIGN KEY (`vehicleFk`) REFERENCES `vehicle` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `vehicleDms_FK_1` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Gestion documental de vehicle';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Gestion documental de vehicle';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41398,7 +40183,7 @@ CREATE TABLE `vehicleEvent` (
KEY `vehicleEvent_FK_1` (`userFk`),
CONSTRAINT `vehicleEvent_FK` FOREIGN KEY (`vehicleStateFk`) REFERENCES `vehicleState` (`id`),
CONSTRAINT `vehicleEvent_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41418,7 +40203,7 @@ CREATE TABLE `vehicleInvoiceIn` (
KEY `vehicleInvoiceIn_FK_1` (`invoiceInFk`),
CONSTRAINT `vehicleInvoiceIn_FK` FOREIGN KEY (`vehicleFk`) REFERENCES `vehicle` (`id`),
CONSTRAINT `vehicleInvoiceIn_FK_1` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41439,7 +40224,7 @@ CREATE TABLE `vehicleNotes` (
KEY `vehicleNotes_FK` (`vehicleFk`),
CONSTRAINT `vehicleNotes_FK` FOREIGN KEY (`vehicleFk`) REFERENCES `vehicle` (`id`),
CONSTRAINT `vehicleNotes_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41468,7 +40253,7 @@ CREATE TABLE `vehicleState` (
`state` varchar(100) NOT NULL,
`hasToNotify` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41486,8 +40271,11 @@ CREATE TABLE `viaexpressConfig` (
`password` varchar(100) NOT NULL,
`defaultWeight` decimal(10,2) NOT NULL,
`deliveryType` varchar(5) NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ `agencyModeFk` int(11) DEFAULT NULL COMMENT 'Indica el agencyMode que es interdia',
+ PRIMARY KEY (`id`),
+ KEY `viaexpressConfig_agencyMode_Fk` (`agencyModeFk`),
+ CONSTRAINT `viaexpressConfig_agencyMode_Fk` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41521,7 +40309,7 @@ DROP TABLE IF EXISTS `wagon`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wagon` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
+ `id` varchar(6) NOT NULL COMMENT '26 letras de alfabeto inglés',
`volume` int(11) NOT NULL DEFAULT 150 COMMENT 'Volumen en litros',
`plate` varchar(10) NOT NULL COMMENT 'Matrícula',
`typeFk` int(11) unsigned NOT NULL,
@@ -41529,7 +40317,7 @@ CREATE TABLE `wagon` (
PRIMARY KEY (`id`),
KEY `wagon_type` (`typeFk`),
CONSTRAINT `wagon_type` FOREIGN KEY (`typeFk`) REFERENCES `wagonType` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41563,7 +40351,7 @@ CREATE TABLE `wagonType` (
`divisible` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41616,11 +40404,11 @@ CREATE TABLE `wagonVolumetry` (
`lines` int(10) unsigned NOT NULL DEFAULT 1,
`liters` int(10) unsigned NOT NULL DEFAULT 0,
`height` int(10) unsigned NOT NULL DEFAULT 20,
- `wagonFk` int(11) NOT NULL,
+ `wagonFk` varchar(6) NOT NULL,
PRIMARY KEY (`id`),
- KEY `wagonVolumetry_FK` (`wagonFk`),
- CONSTRAINT `wagonVolumetry_FK` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ KEY `wagonVolumetry_FK_1` (`wagonFk`),
+ CONSTRAINT `wagonVolumetry_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41651,7 +40439,7 @@ CREATE TABLE `warehouse` (
`hasDms` tinyint(1) NOT NULL DEFAULT 0,
`pickUpAgencyModeFk` int(11) DEFAULT NULL,
`isBuyerToBeEmailed` tinyint(2) NOT NULL DEFAULT 0,
- `aliasFk` smallint(5) unsigned DEFAULT NULL,
+ `aliasFk__` smallint(5) unsigned DEFAULT NULL COMMENT '@deprecated 2024-01-23 refs #5167',
`labelReport` int(11) DEFAULT NULL,
`hasUbications` tinyint(1) NOT NULL DEFAULT 1,
`hasProduction` tinyint(1) NOT NULL DEFAULT 0,
@@ -41666,75 +40454,46 @@ CREATE TABLE `warehouse` (
UNIQUE KEY `name_UNIQUE` (`name`),
KEY `Id_Paises` (`countryFk`),
KEY `isComparativeIdx` (`isComparative`),
- KEY `warehouse_ibfk_1_idx` (`aliasFk`),
+ KEY `warehouse_ibfk_1_idx` (`aliasFk__`),
KEY `warehouse_FK` (`addressFk`),
KEY `warehouse_FK_1` (`pickUpAgencyModeFk`),
CONSTRAINT `warehouse_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `warehouse_FK_1` FOREIGN KEY (`pickUpAgencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `warehouse_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`),
- CONSTRAINT `warehouse_ibfk_2` FOREIGN KEY (`aliasFk`) REFERENCES `warehouseAlias` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+ CONSTRAINT `warehouse_ibfk_2` FOREIGN KEY (`aliasFk__`) REFERENCES `warehouseAlias__` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`warehouse_afterInsert`
- BEFORE UPDATE ON `warehouse`
- FOR EACH ROW
-BEGIN
- IF NEW.isFeedStock AND NEW.isInventory THEN
- CALL util.throw("isFeedStock and isInventory cannot both be true");
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`warehouse_afterUpdate`
- AFTER UPDATE ON `warehouse`
- FOR EACH ROW
-BEGIN
- IF NEW.isFeedStock IS TRUE AND OLD.isFeedStock IS FALSE THEN
- INSERT IGNORE INTO warehouseAlias(`name`) VALUES(NEW.`name`);
- INSERT IGNORE INTO warehouseJoined(warehouseFk, warehouseAliasFk)
- VALUES(NEW.id,LAST_INSERT_ID());
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
--- Table structure for table `warehouseAlias`
+-- Table structure for table `warehouseAlias__`
--
-DROP TABLE IF EXISTS `warehouseAlias`;
+DROP TABLE IF EXISTS `warehouseAlias__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `warehouseAlias` (
+CREATE TABLE `warehouseAlias__` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(15) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-01-23 refs #5167';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `warehousePickup`
+--
+
+DROP TABLE IF EXISTS `warehousePickup`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `warehousePickup` (
+ `warehouseFk` smallint(5) unsigned NOT NULL,
+ `agencyModeFk` int(11) DEFAULT NULL,
+ PRIMARY KEY (`warehouseFk`),
+ UNIQUE KEY `agency_id` (`agencyModeFk`,`warehouseFk`),
+ CONSTRAINT `warehousePickup_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `warehousePickup_ibfk_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Agencia de recogida para cada almacén';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41788,16 +40547,14 @@ CREATE TABLE `worker` (
`lastName` varchar(50) DEFAULT NULL,
`sub` int(11) unsigned DEFAULT NULL,
`photo` blob DEFAULT NULL,
- `phone` varchar(9) DEFAULT NULL,
+ `phone` varchar(15) DEFAULT NULL,
`mobileExtension` int(4) DEFAULT NULL,
- `userFk` int(10) unsigned DEFAULT NULL,
- `bossFk` int(11) NOT NULL DEFAULT 103,
+ `bossFk` int(10) unsigned DEFAULT 103,
`fiDueDate` datetime DEFAULT NULL,
`hasMachineryAuthorized` tinyint(2) DEFAULT 0,
`seniority` date DEFAULT NULL,
`isTodayRelative` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para el F11. Calcula los problemas de visiblidad en funcion del dia actual',
`isF11Allowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Usuario autorizado para abrir el F11',
- `sectorFk__` int(11) DEFAULT NULL COMMENT '@deprecated 2023-06-26',
`maritalStatus` enum('S','M') NOT NULL,
`labelerFk__` tinyint(3) unsigned DEFAULT NULL COMMENT '@deprecated 2023-06-26',
`originCountryFk` mediumint(8) unsigned DEFAULT NULL COMMENT 'País de origen',
@@ -41815,7 +40572,6 @@ CREATE TABLE `worker` (
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `CodigoTrabajador_UNIQUE` (`code`),
- UNIQUE KEY `user_id_UNIQUE` (`userFk`),
UNIQUE KEY `worker_business` (`businessFk`),
UNIQUE KEY `locker` (`locker`),
KEY `sub` (`sub`),
@@ -41827,75 +40583,49 @@ CREATE TABLE `worker` (
CONSTRAINT `worker_FK` FOREIGN KEY (`labelerFk__`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `worker_FK_1` FOREIGN KEY (`originCountryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `worker_FK_2` FOREIGN KEY (`educationLevelFk`) REFERENCES `educationLevel` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `worker_FK_3` FOREIGN KEY (`bossFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `worker_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `worker_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `worker_ibfk_1` FOREIGN KEY (`id`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `workerActivity`
+--
+
+DROP TABLE IF EXISTS `workerActivity`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `workerActivity` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `created` timestamp NULL DEFAULT current_timestamp(),
+ `model` enum('COM','ENT','TPV','ENC','LAB','ETI','APP') NOT NULL,
+ `workerFk` int(10) unsigned NOT NULL,
+ `event` enum('open','close','insert','delete','update','refresh') DEFAULT NULL,
+ `description` varchar(255) DEFAULT NULL,
+ `workerActivityTypeFk` varchar(20) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `fk_workerActivity_worker` (`workerFk`),
+ KEY `workerActivity_workerActivityType_FK` (`workerActivityTypeFk`),
+ CONSTRAINT `fk_workerActivity_worker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `workerActivity_workerActivityType_FK` FOREIGN KEY (`workerActivityTypeFk`) REFERENCES `workerActivityType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `workerActivityType`
+--
+
+DROP TABLE IF EXISTS `workerActivityType`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `workerActivityType` (
+ `code` varchar(20) NOT NULL,
+ `description` varchar(45) NOT NULL,
+ PRIMARY KEY (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`worker_beforeInsert`
- BEFORE INSERT ON `worker`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`worker_beforeUpdate`
- BEFORE UPDATE ON `worker`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`worker_afterDelete`
- AFTER DELETE ON `worker`
- FOR EACH ROW
-BEGIN
- INSERT INTO workerLog
- SET `action` = 'delete',
- `changedModel` = 'Worker',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `workerAppTester`
@@ -41929,7 +40659,7 @@ CREATE TABLE `workerBosses` (
KEY `fg_bossFk_worker_idx` (`bossFk`),
CONSTRAINT `fg_bossFk_worker` FOREIGN KEY (`bossFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fg_workerFk_worker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41947,7 +40677,7 @@ CREATE TABLE `workerBusinessAgreement` (
`started` date DEFAULT NULL,
`ended` date DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42019,7 +40749,7 @@ CREATE TABLE `workerConfig` (
KEY `workerConfig_FK_1` (`payMethodFk`),
CONSTRAINT `workerConfig_FK` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerConfig_FK_1` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42064,7 +40794,7 @@ CREATE TABLE `workerDistributionCategory` (
PRIMARY KEY (`id`),
KEY `workerDistributionCategory_workerFk_idx` (`workerFk`),
CONSTRAINT `workerDistributionCategory_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42087,72 +40817,8 @@ CREATE TABLE `workerDocument` (
CONSTRAINT `workerDocument_FK` FOREIGN KEY (`worker`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerDocument_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `workerDocument_ibfk_2` FOREIGN KEY (`document`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerDocument_beforeInsert`
- BEFORE INSERT ON `workerDocument`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerDocument_beforeUpdate`
- BEFORE UPDATE ON `workerDocument`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerDocument_afterDelete`
- AFTER DELETE ON `workerDocument`
- FOR EACH ROW
-BEGIN
- INSERT INTO workerLog
- SET `action` = 'delete',
- `changedModel` = 'WorkerDocument',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `workerEmergencyBoss`
@@ -42166,7 +40832,7 @@ CREATE TABLE `workerEmergencyBoss` (
`name` varchar(45) DEFAULT NULL,
`value` varchar(45) DEFAULT NULL COMMENT 'Table to save all responsible people phones',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42183,7 +40849,7 @@ CREATE TABLE `workerHourPrice` (
`nightInc` decimal(4,2) DEFAULT NULL,
`extraInc` decimal(4,2) DEFAULT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los acuerdos de los distintos convenios';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los acuerdos de los distintos convenios';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42206,70 +40872,8 @@ CREATE TABLE `workerIncome` (
KEY `income_employee_workerFk_idx` (`workerFk`),
CONSTRAINT `income_employeeId_incomeType` FOREIGN KEY (`incomeTypeFk`) REFERENCES `vn2008`.`payroll_conceptos` (`conceptoid`) ON UPDATE CASCADE,
CONSTRAINT `income_employee_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerIncome_afterInsert`
- AFTER INSERT ON `workerIncome`
- FOR EACH ROW
-BEGIN
- CALL worker_updateBalance(NEW.workerFk,NEW.credit,NEW.debit);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerIncome_afterUpdate`
- AFTER UPDATE ON `workerIncome`
- FOR EACH ROW
-BEGIN
- CALL worker_updateBalance(NEW.workerFk,-OLD.credit,-OLD.debit);
-
- CALL worker_updateBalance(NEW.workerFk,NEW.credit,NEW.debit);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerIncome_afterDelete`
- AFTER DELETE ON `workerIncome`
- FOR EACH ROW
-BEGIN
- CALL worker_updateBalance(OLD.workerFk,-OLD.credit,-OLD.debit);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `workerIrpf`
@@ -42331,7 +40935,7 @@ CREATE TABLE `workerJourney` (
KEY `workerJourney_businessFk` (`businessFk`),
CONSTRAINT `fk_workerJourney_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerJourney_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42366,7 +40970,7 @@ CREATE TABLE `workerLog` (
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text DEFAULT NULL,
- `changedModel` enum('Worker','Calendar','WorkerTimeControlMail','Business','WorkerDms') NOT NULL DEFAULT 'Worker',
+ `changedModel` enum('Worker','Calendar','WorkerTimeControlMail','Business','WorkerDms','WorkerTimeControl') NOT NULL DEFAULT 'Worker',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
@@ -42375,9 +40979,8 @@ CREATE TABLE `workerLog` (
KEY `userFk_idx` (`userFk`),
KEY `workerLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `workerLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `userFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
- CONSTRAINT `workerFk` FOREIGN KEY (`originFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+ CONSTRAINT `userFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42443,7 +41046,7 @@ CREATE TABLE `workerMistake` (
KEY `workerMistake_fk2_idx` (`workerMistakeTypeFk`),
CONSTRAINT `workerMistake_fk1` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `workerMistake_fk2` FOREIGN KEY (`workerMistakeTypeFk`) REFERENCES `workerMistakeType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42503,7 +41106,7 @@ CREATE TABLE `workerRelatives` (
KEY `workerRelatives_workerFk` (`workerFk`),
CONSTRAINT `workerRelatives_disabilityGradeFk` FOREIGN KEY (`disabilityGradeFk`) REFERENCES `disabilityGrade` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerRelatives_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `workerIrpf` (`workerFk`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Modelo 145 IRPF apartado 2 y 3';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Modelo 145 IRPF apartado 2 y 3';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42526,7 +41129,7 @@ CREATE TABLE `workerShelving` (
CONSTRAINT `workerShelving_FK` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `workerShelving_FK_1` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON UPDATE CASCADE,
CONSTRAINT `workerShelving_worker_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='utilizaremos el id para establecer la prioridad de los carros a asignar';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='utilizaremos el id para establecer la prioridad de los carros a asignar';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42582,7 +41185,7 @@ CREATE TABLE `workerTeam` (
KEY `user_idx` (`workerFk`),
KEY `team_idx` (`team`),
CONSTRAINT `user_team` FOREIGN KEY (`workerFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42609,41 +41212,22 @@ CREATE TABLE `workerTimeControl` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userFk` int(10) unsigned NOT NULL,
`timed` datetime NOT NULL,
+ `direction` enum('in','out','middle') DEFAULT 'middle',
`manual` tinyint(4) NOT NULL DEFAULT 0,
`order` int(11) DEFAULT NULL,
+ `device` varchar(255) DEFAULT NULL COMMENT 'Dispositivo en el que se ha fichado',
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
- `direction` enum('in','out','middle') DEFAULT 'middle',
`isSendMail` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Fichadas generadas autómaticamente con el procedimiento vn.workerTimeControl_sendMail',
+ `logExclude` tinyint(1) GENERATED ALWAYS AS (if(`manual`,0,1)) VIRTUAL,
+ `editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `userFk_Timed_uniq` (`userFk`,`timed`),
KEY `warehouseFkfk1_idx` (`warehouseFk`),
KEY `timed_idx` (`timed`),
CONSTRAINT `warehouseFk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerTimeControl_fk1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Fichadas';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Fichadas';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerTimeControl_AI`
- AFTER INSERT ON `workerTimeControl`
- FOR EACH ROW
-BEGIN
- IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN
- CALL util.throw('date in the future');
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `workerTimeControlConfig`
@@ -42677,8 +41261,27 @@ CREATE TABLE `workerTimeControlConfig` (
`longWeekDays` int(11) DEFAULT NULL COMMENT 'Días a tener en cuenta para calcular el descanso largo',
`teleworkingStart` int(11) DEFAULT NULL COMMENT 'Hora comienzo jornada de los teletrabajdores expresada en segundos',
`teleworkingStartBreakTime` int(11) DEFAULT NULL COMMENT 'Hora comienzo descanso de los teletrabjadores expresada en segundos',
+ `maxTimeToBreak` int(11) DEFAULT 3600,
+ `maxWorkShortCycle` int(10) unsigned DEFAULT 561600 COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal corto',
+ `maxWorkLongCycle` int(10) unsigned DEFAULT 950400 COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal largo',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='All values in seconds';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='All values in seconds';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `workerTimeControlError`
+--
+
+DROP TABLE IF EXISTS `workerTimeControlError`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `workerTimeControlError` (
+ `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
+ `code` char(35) NOT NULL,
+ `description` varchar(255) NOT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `code` (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42717,7 +41320,7 @@ CREATE TABLE `workerTimeControlMail` (
UNIQUE KEY `workerFk_UNIQUE` (`workerFk`,`year`,`week`),
KEY `workerFk_idx` (`workerFk`),
CONSTRAINT `workerTimeControlMail_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Guarda las respuestas de mail de los correos generados automáticamente por la procedimiento workerTimeControl_sendMail';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Guarda las respuestas de mail de los correos generados automáticamente por la procedimiento workerTimeControl_sendMail';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42743,7 +41346,7 @@ CREATE TABLE `workerTimeControlParams` (
`mailErrorFolder` varchar(45) NOT NULL,
`mailUser` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='All values in seconds';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='All values in seconds';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42773,7 +41376,7 @@ CREATE TABLE `workerTimeControlSchedule` (
`time` time DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `punique_trhf` (`time`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42841,30 +41444,8 @@ CREATE TABLE `workingHours` (
PRIMARY KEY (`id`),
KEY `user_working_hour_idx` (`userId`),
CONSTRAINT `user_working_hour` FOREIGN KEY (`userId`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena horas de Entrada y de Salida del personal';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena horas de Entrada y de Salida del personal';
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workingHoursBeforeInsert`
- BEFORE INSERT ON `workingHours`
- FOR EACH ROW
-BEGIN
- IF (SELECT COUNT(*) FROM workingHours WHERE userId = NEW.userId AND DATE(timeIn) = util.VN_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 */ ;
--
-- Table structure for table `zipConfig`
@@ -42893,7 +41474,7 @@ CREATE TABLE `zone` (
`hour` datetime NOT NULL,
`agencyModeFk` int(11) NOT NULL,
`travelingDays` int(11) NOT NULL DEFAULT 1,
- `price` double NOT NULL DEFAULT 0,
+ `price` double NOT NULL DEFAULT 0 CHECK (`price` > 0),
`bonus` double NOT NULL DEFAULT 0,
`isVolumetric` tinyint(1) NOT NULL DEFAULT 0,
`inflation` decimal(5,2) NOT NULL DEFAULT 1.00,
@@ -42907,72 +41488,8 @@ CREATE TABLE `zone` (
KEY `zone_fk_editor` (`editorFk`),
CONSTRAINT `fk_zone_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `zone_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zone_beforeInsert`
- BEFORE INSERT ON `zone`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zone_beforeUpdate`
- BEFORE UPDATE ON `zone`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zone_afterDelete`
- AFTER DELETE ON `zone`
- FOR EACH ROW
-BEGIN
- INSERT INTO zoneLog
- SET `action` = 'delete',
- `changedModel` = 'Zone',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `zoneAgencyMode`
@@ -42990,7 +41507,7 @@ CREATE TABLE `zoneAgencyMode` (
KEY `zoneAgencyMode_FK_1` (`zoneFk`),
CONSTRAINT `zoneAgencyMode_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneAgencyMode_FK_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='junta agencias con zonas para que al enrutar se puedan proponer tickets.';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='junta agencias con zonas para que al enrutar se puedan proponer tickets.';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -43020,7 +41537,7 @@ CREATE TABLE `zoneConfig` (
`scope` int(10) unsigned NOT NULL,
`forwardDays` int(10) NOT NULL DEFAULT 7 COMMENT 'days forward to show zone_upcomingDeliveries',
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -43033,13 +41550,12 @@ SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `zoneEstimatedDelivery` AS SELECT
1 AS `zoneFk`,
- 1 AS `hourTheoretical`,
- 1 AS `totalVolume`,
- 1 AS `remainingVolume`,
- 1 AS `speed`,
- 1 AS `hourEffective`,
- 1 AS `minutesLess`,
- 1 AS `etc` */;
+ 1 AS `zoneClosureHour`,
+ 1 AS `zoneHour`,
+ 1 AS `volume`,
+ 1 AS `hasToRecalcPrice`,
+ 1 AS `m3`,
+ 1 AS `minSpeed` */;
SET character_set_client = @saved_cs_client;
--
@@ -43068,72 +41584,8 @@ CREATE TABLE `zoneEvent` (
KEY `zoneEvent_fk_editor` (`editorFk`),
CONSTRAINT `zoneEvent_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneEvent_beforeInsert`
- BEFORE INSERT ON `zoneEvent`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneEvent_beforeUpdate`
- BEFORE UPDATE ON `zoneEvent`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneEvent_afterDelete`
- AFTER DELETE ON `zoneEvent`
- FOR EACH ROW
-BEGIN
- INSERT INTO zoneLog
- SET `action` = 'delete',
- `changedModel` = 'zoneEvent',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `zoneExclusion`
@@ -43155,76 +41607,8 @@ CREATE TABLE `zoneExclusion` (
KEY `zoneExclusion_fk_editor` (`editorFk`),
CONSTRAINT `zoneExclusion_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BI`
- BEFORE INSERT ON `zoneExclusion`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
- SET NEW.userFk = account.myUser_getId();
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BU`
- BEFORE UPDATE ON `zoneExclusion`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
- SET NEW.userFk = account.myUser_getId();
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_afterDelete`
- AFTER DELETE ON `zoneExclusion`
- FOR EACH ROW
-BEGIN
- INSERT INTO zoneLog
- SET `action` = 'delete',
- `changedModel` = 'zoneExclusion',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `zoneExclusionGeo`
@@ -43242,7 +41626,7 @@ CREATE TABLE `zoneExclusionGeo` (
KEY `zoneExclusionGeo2_FK_1` (`geoFk`),
CONSTRAINT `zoneExclusionGeo_FK` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE,
CONSTRAINT `zoneExclusionGeo_FK_1` FOREIGN KEY (`zoneExclusionFk`) REFERENCES `zoneExclusion` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -43262,7 +41646,7 @@ CREATE TABLE `zoneFilter` (
KEY `zoneFilter_FK_1` (`itemTypeFk`),
CONSTRAINT `zoneFilter_FK` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneFilter_FK_1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='recoge los parámetros para filtrar determinados productos según la zona';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='recoge los parámetros para filtrar determinados productos según la zona';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -43287,50 +41671,8 @@ CREATE TABLE `zoneGeo` (
KEY `name_idx` (`name`),
KEY `parentFk` (`parentFk`),
KEY `path` (`path`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneGeo_beforeInsert`
- BEFORE INSERT ON `zoneGeo`
- FOR EACH ROW
-BEGIN
- CALL zoneGeo_checkName(NEW.`name`);
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneGeo_beforeUpdate`
- BEFORE UPDATE ON `zoneGeo`
- FOR EACH ROW
-BEGIN
- IF !(OLD.`name` <=> NEW.`name`) THEN
- CALL zoneGeo_checkName(NEW.`name`);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `zoneGeoRecalc`
@@ -43343,7 +41685,7 @@ CREATE TABLE `zoneGeoRecalc` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`isChanged` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -43354,82 +41696,20 @@ DROP TABLE IF EXISTS `zoneIncluded`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneIncluded` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`zoneFk` int(11) NOT NULL,
`geoFk` int(11) NOT NULL,
`isIncluded` tinyint(1) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
- PRIMARY KEY (`zoneFk`,`geoFk`),
- KEY `geoFk_idx` (`geoFk`),
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `unique_zone_geo` (`zoneFk`,`geoFk`),
KEY `zoneIncluded_fk_editor` (`editorFk`),
- CONSTRAINT `zoneFk2` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `zoneGeoFk2` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ KEY `zoneIncluded_FK_2` (`geoFk`),
+ CONSTRAINT `zoneIncluded_FK_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `zoneIncluded_FK_2` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneIncluded_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneIncluded_beforeInsert`
- BEFORE INSERT ON `zoneIncluded`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneIncluded_beforeUpdate`
- BEFORE UPDATE ON `zoneIncluded`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneIncluded_afterDelete`
- AFTER DELETE ON `zoneIncluded`
- FOR EACH ROW
-BEGIN
- INSERT INTO zoneLog
- SET `action` = 'delete',
- `changedModel` = 'zoneIncluded',
- `changedModelId` = OLD.zoneFk,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `zoneItemType`
@@ -43473,9 +41753,8 @@ CREATE TABLE `zoneLog` (
KEY `userFk` (`userFk`),
KEY `zoneLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `zoneLog_originFk` (`originFk`,`creationDate`),
- CONSTRAINT `zoneLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -43497,72 +41776,8 @@ CREATE TABLE `zoneWarehouse` (
CONSTRAINT `zoneWarehouse_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `zoneWarehouse_fk_warehouse` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneWarehouse_beforeInsert`
- BEFORE INSERT ON `zoneWarehouse`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneWarehouse_beforeUpdate`
- BEFORE UPDATE ON `zoneWarehouse`
- FOR EACH ROW
-BEGIN
- SET NEW.editorFk = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneWarehouse_afterDelete`
- AFTER DELETE ON `zoneWarehouse`
- FOR EACH ROW
-BEGIN
- INSERT INTO zoneLog
- SET `action` = 'delete',
- `changedModel` = 'ZoneWarehouse',
- `changedModelId` = OLD.id,
- `userFk` = account.myUser_getId();
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Dumping events for database 'vn'
@@ -43580,7 +41795,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clientsDisable` ON SCHEDULE EVERY 1 MONTH STARTS '2023-06-01 00:00:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO BEGIN
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clientsDisable` ON SCHEDULE EVERY 1 MONTH STARTS '2023-06-01 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
UPDATE account.user u
JOIN client c ON c.id = u.id
JOIN clientType ct ON ct.id = c.typeFk
@@ -43591,8 +41806,8 @@ DELIMITER ;;
FROM client c
LEFT JOIN ticket t ON t.clientFk = c.id
WHERE c.salesPersonFk IS NOT NULL
- OR t.created > util.VN_CURDATE() - INTERVAL 2 MONTH
- OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH
+ OR t.created > util.VN_CURDATE() - INTERVAL 2 MONTH
+ OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH
);
END */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
@@ -43612,7 +41827,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`jgallego`@`%`*/ /*!50106 EVENT `client_unassignSalesPerson` ON SCHEDULE EVERY 1 DAY STARTS '2023-06-01 03:30:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL client_unassignSalesPerson */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `client_unassignSalesPerson` ON SCHEDULE EVERY 1 DAY STARTS '2023-06-01 03:30:00' ON COMPLETION PRESERVE ENABLE DO CALL client_unassignSalesPerson */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43630,7 +41845,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `collection_make` ON SCHEDULE EVERY 5 MINUTE STARTS '2022-09-15 00:00:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL vn.collection_make */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `collection_make` ON SCHEDULE EVERY 5 MINUTE STARTS '2022-09-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.collection_make */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43648,7 +41863,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL vn.department_doCalc */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43666,7 +41881,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `envialiaThreHoldChecker` ON SCHEDULE EVERY 1 DAY STARTS '2022-01-28 09:52:46' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO BEGIN
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `envialiaThreHoldChecker` ON SCHEDULE EVERY 1 DAY STARTS '2022-01-28 09:52:46' ON COMPLETION NOT PRESERVE ENABLE DO BEGIN
DECLARE vActualNumber BIGINT;
DECLARE vEndRange BIGINT;
DECLARE vIsAlreadyNotified BOOLEAN;
@@ -43712,7 +41927,28 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `greuge_notify` ON SCHEDULE EVERY 1 DAY STARTS '2023-01-01 00:07:00' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE COMMENT 'Notifies subscribed users of events in wrong greuges' DO CALL vn.greuge_notifyEvents() */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `greuge_notify` ON SCHEDULE EVERY 1 DAY STARTS '2023-01-01 00:07:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Notifies subscribed users of events in wrong greuges' DO CALL vn.greuge_notifyEvents() */ ;;
+/*!50003 SET time_zone = @saved_time_zone */ ;;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;;
+/*!50003 SET character_set_client = @saved_cs_client */ ;;
+/*!50003 SET character_set_results = @saved_cs_results */ ;;
+/*!50003 SET collation_connection = @saved_col_connection */ ;;
+/*!50106 DROP EVENT IF EXISTS `itemImageQueue_check` */;;
+DELIMITER ;;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
+/*!50003 SET character_set_client = utf8mb3 */ ;;
+/*!50003 SET character_set_results = utf8mb3 */ ;;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
+/*!50003 SET @saved_time_zone = @@time_zone */ ;;
+/*!50003 SET time_zone = 'SYSTEM' */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
+ DELETE FROM itemImageQueue
+ WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig);
+END */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43730,7 +41966,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `mysqlConnectionsSorter_kill` ON SCHEDULE EVERY 1 MINUTE STARTS '2021-10-28 09:56:27' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO CALL mysqlConnectionsSorter_kill() */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `mysqlConnectionsSorter_kill` ON SCHEDULE EVERY 1 MINUTE STARTS '2021-10-28 09:56:27' ON COMPLETION NOT PRESERVE ENABLE DO CALL mysqlConnectionsSorter_kill() */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43748,7 +41984,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2022-01-28 09:52:46' ON COMPLETION PRESERVE DISABLE ON SLAVE DO BEGIN
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2022-01-28 09:52:46' ON COMPLETION PRESERVE ENABLE DO BEGIN
DECLARE vCurrentCount INT;
DECLARE vCheckSum INT;
@@ -43857,25 +42093,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `route_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2021-07-08 07:32:23' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL route_doRecalc */ ;;
-/*!50003 SET time_zone = @saved_time_zone */ ;;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;;
-/*!50003 SET character_set_client = @saved_cs_client */ ;;
-/*!50003 SET character_set_results = @saved_cs_results */ ;;
-/*!50003 SET collation_connection = @saved_col_connection */ ;;
-/*!50106 DROP EVENT IF EXISTS `sale_checkWithoutComponents` */;;
-DELIMITER ;;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
-/*!50003 SET character_set_client = utf8mb4 */ ;;
-/*!50003 SET character_set_results = utf8mb4 */ ;;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
-/*!50003 SET @saved_time_zone = @@time_zone */ ;;
-/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `sale_checkWithoutComponents` ON SCHEDULE EVERY 10 MINUTE STARTS '2020-05-04 11:56:23' ON COMPLETION PRESERVE DISABLE ON SLAVE DO call sale_checkNoComponents(DATE_ADD(util.VN_NOW(), INTERVAL -10 MINUTE),DATE_ADD(util.VN_NOW(), INTERVAL -1 MINUTE)) */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `route_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2021-07-08 07:32:23' ON COMPLETION PRESERVE ENABLE DO CALL route_doRecalc */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43893,7 +42111,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `ticket_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2022-01-28 09:29:18' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL ticket_doRecalc */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `ticket_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2022-01-28 09:29:18' ON COMPLETION PRESERVE ENABLE DO CALL ticket_doRecalc */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43911,7 +42129,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `travel_doRecalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-05-17 10:52:29' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL travel_doRecalc */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `travel_doRecalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-05-17 10:52:29' ON COMPLETION PRESERVE ENABLE DO CALL travel_doRecalc */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43929,7 +42147,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `vehicle_notify` ON SCHEDULE EVERY 1 DAY STARTS '2022-01-01 00:07:00' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE COMMENT 'Notifies subscribed users of events in vehicles that are about t' DO CALL vn.vehicle_notifyEvents */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `vehicle_notify` ON SCHEDULE EVERY 1 DAY STARTS '2022-01-01 00:07:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Notifies subscribed users of events in vehicles that are about t' DO CALL vn.vehicle_notifyEvents */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43947,7 +42165,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `workerJourney_doRecalc` ON SCHEDULE EVERY 1 DAY STARTS '2023-07-22 04:00:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL workerJourney_replace(util.VN_CURDATE() - INTERVAL 1 WEEK, util.VN_CURDATE(), NULL) */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `workerJourney_doRecalc` ON SCHEDULE EVERY 1 DAY STARTS '2023-07-22 04:00:00' ON COMPLETION PRESERVE ENABLE DO CALL workerJourney_replace(util.VN_CURDATE() - INTERVAL 1 WEEK, util.VN_CURDATE(), NULL) */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43965,7 +42183,25 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `worker_updateChangedBusiness` ON SCHEDULE EVERY 1 DAY STARTS '2000-01-01 00:00:05' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO CALL worker_updateChangedBusiness */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `worker_updateChangedBusiness` ON SCHEDULE EVERY 1 DAY STARTS '2000-01-01 00:00:05' ON COMPLETION NOT PRESERVE ENABLE DO CALL worker_updateChangedBusiness */ ;;
+/*!50003 SET time_zone = @saved_time_zone */ ;;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;;
+/*!50003 SET character_set_client = @saved_cs_client */ ;;
+/*!50003 SET character_set_results = @saved_cs_results */ ;;
+/*!50003 SET collation_connection = @saved_col_connection */ ;;
+/*!50106 DROP EVENT IF EXISTS `zoneClosure_doRecalc` */;;
+DELIMITER ;;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
+/*!50003 SET character_set_client = utf8mb3 */ ;;
+/*!50003 SET character_set_results = utf8mb3 */ ;;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
+/*!50003 SET @saved_time_zone = @@time_zone */ ;;
+/*!50003 SET time_zone = 'SYSTEM' */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`salix`@`10.0.%.%`*/ /*!50106 EVENT `zoneClosure_doRecalc` ON SCHEDULE AT '2023-11-13 07:15:54' ON COMPLETION NOT PRESERVE DISABLE DO CALL zoneClosure_recalc */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -43983,7 +42219,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `zoneGeo_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-09-13 15:30:47' ON COMPLETION PRESERVE DISABLE ON SLAVE DO CALL vn.zoneGeo_doCalc */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `zoneGeo_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-09-13 15:30:47' ON COMPLETION PRESERVE ENABLE DO CALL vn.zoneGeo_doCalc */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -44058,7 +42294,7 @@ BEGIN
DECLARE vGeoFk INT;
SELECT p.geoFk INTO vGeoFk
- FROM address a
+ FROM address a
JOIN town t ON t.provinceFk = a.provinceFk
JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode
WHERE a.id = vSelf
@@ -44085,12 +42321,12 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `barcodeToItem`(vBarcode VARCHAR(22)) RETURNS int(11)
DETERMINISTIC
BEGIN
-
+
/**
* Obtiene el id del artículo
*
* @param vBarcode código de barras
- *
+ *
* return id del item
*/
@@ -44100,35 +42336,35 @@ BEGIN
FROM vn.item
WHERE id = vBarcode OR comment = vBarcode
LIMIT 1;
-
- IF vItemFk THEN
+
+ IF vItemFk THEN
RETURN vItemFk;
END IF;
- SELECT itemFk INTO vItemFk
- FROM buy
+ SELECT itemFk INTO vItemFk
+ FROM buy
WHERE id = vBarcode;
-
- IF vItemFk THEN
+
+ IF vItemFk THEN
RETURN vItemFk;
END IF;
-
- SELECT itemFk INTO vItemFk
- FROM itemBarcode
+
+ SELECT itemFk INTO vItemFk
+ FROM itemBarcode
WHERE code = vBarcode;
-
- IF vItemFk THEN
+
+ IF vItemFk THEN
RETURN vItemFk;
END IF;
- SELECT i.id INTO vItemFk
+ SELECT i.id INTO vItemFk
FROM vn.item i
WHERE i.name LIKE CONCAT('%',vBarcode,'%')
ORDER BY i.id ASC
LIMIT 1;
-
+
RETURN vItemFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -44136,42 +42372,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `botanicExport_isUpdatable` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` FUNCTION `botanicExport_isUpdatable`(vEdiGenusFk MEDIUMINT,
- vEdiSpecieFk MEDIUMINT,
- vRestriction MEDIUMINT) RETURNS int(11)
- DETERMINISTIC
-BEGIN
- DECLARE vIsUpdatable INTEGER;
- SELECT COUNT(*) INTO vIsUpdatable
- FROM botanicExport
- WHERE ediGenusFk = vEdiGenusFk
- AND (vEdiSpecieFk = ediSpecieFk OR IFNULL(vEdiSpecieFk,ediSpecieFk) IS NULL)
- AND vRestriction = restriction;
-RETURN vIsUpdatable;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `buy_getUnitVolume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `buy_getUnitVolume`(vSelf INT) RETURNS int(11)
DETERMINISTIC
@@ -44186,7 +42394,7 @@ BEGIN
DECLARE vPackaging VARCHAR(10);
DECLARE vPacking INT;
- SELECT itemFk, packageFk, packing
+ SELECT itemFk, packagingFk, packing
INTO vItem, vPackaging, vPacking
FROM buy
WHERE id = vSelf;
@@ -44220,7 +42428,7 @@ BEGIN
DECLARE vItem INT;
DECLARE vPackaging VARCHAR(10);
- SELECT itemFk, packageFk INTO vItem, vPackaging
+ SELECT itemFk, packagingFk INTO vItem, vPackaging
FROM buy
WHERE id = vSelf;
@@ -44249,16 +42457,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `catalog_componentReverse`(vWarehouse
DETERMINISTIC
BEGIN
/* Calcula los componentes para un cliente a partir de un coste y volumen
- * @param vWarehouse
+ * @param vWarehouse
* @param vCost Valor de coste del articulo
* @param vM3 m3 del articulo
- * @param vAddressFk
+ * @param vAddressFk
* @param vZoneFk
- * @return vRetailedPrice precio de venta sin iva
+ * @return vRetailedPrice precio de venta sin iva
* @return tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
*/
-
- DECLARE vBoxVolume BIGINT;
+
+ DECLARE vBoxVolume BIGINT;
DECLARE vCustomer INT;
DECLARE vComponentRecovery INT DEFAULT 17;
DECLARE vComponentMana INT DEFAULT 39;
@@ -44267,11 +42475,11 @@ BEGIN
DECLARE vComponentCost INT DEFAULT 28;
DECLARE vRetailedPrice DECIMAL(10,2);
DECLARE vItem INT DEFAULT 98;
-
+
SELECT volume INTO vBoxVolume
FROM vn.packaging
WHERE id = '94';
-
+
SELECT clientFk INTO vCustomer FROM address WHERE id = vAddressFk;
DROP TEMPORARY TABLE IF EXISTS tmp.catalog_component;
@@ -44295,7 +42503,7 @@ BEGIN
-- Margen
-- No se aplica margen, cau 12589
/* INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
- SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost
+ SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost
FROM vn.rate
WHERE dated <= util.VN_CURDATE()
AND warehouseFk = vWarehouse
@@ -44304,7 +42512,7 @@ BEGIN
*/
-- Recobro
INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
- SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3)
+ SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3)
FROM bi.claims_ratio
WHERE Id_Cliente = vCustomer AND recobro > 0.009;
@@ -44321,7 +42529,7 @@ BEGIN
ROUND(
vM3
* (z.price - z.bonus)
- * z.inflation
+ * z.inflation
/ vBoxVolume, 4
)
FROM zone z
@@ -44358,63 +42566,19 @@ BEGIN
* @return Mana del cliente
*/
DECLARE vMana DECIMAL(10,2);
- DECLARE vFromDated DATE;
- DECLARE vHasMana BOOLEAN;
- DECLARE vManaComponent INT;
- DECLARE vAutoManaComponent INT;
- DECLARE vManaBank INT;
- DECLARE vManaGreugeType INT;
- SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana';
- SELECT id INTO vManaBank FROM bank WHERE code = 'mana';
- SELECT id INTO vManaComponent FROM component WHERE code = 'mana';
- SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana';
+ CREATE OR REPLACE TEMPORARY TABLE tmp.client
+ SELECT vClient id;
- SELECT COUNT(*) INTO vHasMana
- FROM `client` c
- WHERE c.id = vClient AND c.typeFk = 'normal';
+ CALL client_getMana();
- IF NOT vHasMana THEN
- RETURN 0;
- END IF;
+ SET vMana = (SELECT mana
+ FROM tmp.clientMana);
- SELECT max(dated) INTO vFromDated
- FROM clientManaCache;
+ DROP TEMPORARY TABLE
+ tmp.client,
+ tmp.clientMana;
- SELECT sum(mana) INTO vMana
- FROM
- (
- SELECT mana
- FROM clientManaCache
- WHERE clientFk = vClient
- AND dated = vFromDated
- UNION ALL
- SELECT s.quantity * value
- FROM ticket t
- JOIN address a ON a.id = t.addressFk
- JOIN sale s on s.ticketFk = t.id
- JOIN saleComponent sc on sc.saleFk = s.id
- WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent)
- AND t.shipped > vFromDated
- AND t.shipped < TIMESTAMPADD(DAY,1,util.VN_CURDATE())
- AND a.clientFk = vClient
- UNION ALL
- SELECT - amountPaid
- FROM receipt r
- JOIN `client` c ON c.id = r.clientFk
- WHERE r.bankFk = vManaBank
- AND r.payed > vFromDated
- AND r.payed <= util.VN_CURDATE()
- AND c.id = vClient
- UNION ALL
- SELECT g.amount
- FROM greuge g
- JOIN `client` c ON c.id = g.clientFk
- WHERE g.greugeTypeFk = vManaGreugeType
- AND g.shipped > vFromDated
- AND g.shipped <= util.VN_CURDATE()
- AND c.id = vClient
- ) sub;
RETURN IFNULL(vMana,0);
END ;;
DELIMITER ;
@@ -44459,7 +42623,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `clientTaxArea`(vClientId INT, vCompa
READS SQL DATA
BEGIN
/**
-* Devuelve el area de un cliente,
+* Devuelve el area de un cliente,
* intracomunitario, extracomunitario o nacional.
*
* @param vClient Id del cliente
@@ -44492,33 +42656,37 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `client_getDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2)
READS SQL DATA
-BEGIN
-/**
- * Returns the risk of a customer.
- *
- * @param vClient client id
- * @param vDate date to check the risk
- * @return client risk
- */
- DECLARE vDebt DECIMAL(10,2);
- DECLARE vHasDebt BOOLEAN;
-
- SELECT COUNT(*) INTO vHasDebt
- FROM `client` c
- WHERE c.id = vClient AND c.typeFk = 'normal';
-
- IF NOT vHasDebt THEN
- RETURN 0;
- END IF;
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT);
- INSERT INTO tmp.clientGetDebt SET clientFk = vClient;
-
- CALL vn.client_getDebt(vDate);
-
- SELECT risk INTO vDebt FROM tmp.risk;
-
- RETURN vDebt;
+BEGIN
+/**
+ * Returns the risk of a customer.
+ *
+ * @param vClient client id
+ * @param vDate date to check the risk
+ * @return Client risk
+ */
+ DECLARE vDebt DECIMAL(10,2);
+ DECLARE vHasDebt BOOLEAN;
+
+ SELECT COUNT(*) INTO vHasDebt
+ FROM `client` c
+ WHERE c.id = vClient AND c.typeFk = 'normal';
+
+ IF NOT vHasDebt THEN
+ RETURN 0;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT);
+ INSERT INTO tmp.clientGetDebt SET clientFk = vClient;
+
+ CALL vn.client_getDebt(vDate);
+
+ SELECT risk INTO vDebt FROM tmp.risk;
+
+ DROP TEMPORARY TABLE
+ tmp.clientGetDebt,
+ tmp.risk;
+
+ RETURN vDebt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -44594,8 +42762,8 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `client_getSalesPerson`(vClientFk INT
DETERMINISTIC
BEGIN
/**
- * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo
- * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de
+ * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo
+ * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de
* sharingcart y tercero la de clientes.
*
* @param vClientFk El id del cliente
@@ -44633,29 +42801,29 @@ BEGIN
l: LOOP
SELECT workerSubstitute INTO vWorkerSubstituteFk
- FROM sharingCart
+ FROM sharingCart
WHERE util.VN_CURDATE() BETWEEN started AND ended
AND workerFk = vSalesPersonFk
ORDER BY id
LIMIT 1;
-
+
IF vWorkerSubstituteFk IS NULL THEN
LEAVE l;
END IF;
-
+
SELECT COUNT(*) > 0 INTO vLoop
FROM tmp.stack WHERE substitute = vWorkerSubstituteFk;
IF vLoop THEN
LEAVE l;
END IF;
-
+
INSERT INTO tmp.stack SET
substitute = vWorkerSubstituteFk;
-
+
SET vSalesPersonFk = vWorkerSubstituteFk;
END LOOP;
-
+
DROP TEMPORARY TABLE tmp.stack;
END IF;
@@ -44689,11 +42857,11 @@ BEGIN
**/
DECLARE vClientFk INT;
DECLARE vDated DATE;
-
+
SELECT clientFk, shipped
INTO vClientFk, vDated
FROM ticket WHERE id = vTicketFk;
-
+
RETURN client_getSalesPerson(vClientFk, vDated);
END ;;
DELIMITER ;
@@ -44724,12 +42892,12 @@ BEGIN
**/
DECLARE vWorkerCode CHAR(3);
DECLARE vSalesPersonFk INT;
-
+
SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated);
SELECT code
INTO vWorkerCode
- FROM worker
+ FROM worker
WHERE id = vSalesPersonFk;
RETURN vWorkerCode;
@@ -44762,11 +42930,11 @@ BEGIN
**/
DECLARE vClientFk INT;
DECLARE vDated DATE;
-
+
SELECT clientFk, shipped
INTO vClientFk, vDated
FROM ticket WHERE id = vTicketFk;
-
+
RETURN client_getSalesPersonCode(vClientFk, vDated);
END ;;
DELIMITER ;
@@ -44776,6 +42944,38 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `client_hasDifferentCountries` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `client_hasDifferentCountries`(vClientFk INT) RETURNS tinyint(1)
+ READS SQL DATA
+BEGIN
+/**
+ * Return if client have address in different countries.
+ *
+ * @param vClientFk The id client
+ * @return BOOL
+ **/
+ RETURN (SELECT COUNT(DISTINCT c.id) > 1
+ FROM `address` a
+ JOIN province p ON p.id = a.provinceFk
+ JOIN country c ON c.id = p.countryFk
+ WHERE a.clientFk = vClientFk
+ AND a.isActive);
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `collection_isPacked` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -44858,7 +43058,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `currentRate`(vCurrencyFk INT, vDated
BEGIN
DECLARE curRate DECIMAL(10,4);
-
+
SELECT value INTO curRate
FROM referenceRate
WHERE dated <= vDated
@@ -44889,23 +43089,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `deviceProductionUser_accessGranted`(
BEGIN
/*
* Comprueba si el usuario puede entrar en la aplicacion de almacen con ese movil
- *
+ *
* */
-
+
/*DECLARE vIsGranted BOOLEAN;
DECLARE vDeviceProductionFk INT(11) DEFAULT NULL;
- SELECT dp.id INTO vDeviceProductionFk
- FROM vn.deviceProduction dp
+ SELECT dp.id INTO vDeviceProductionFk
+ FROM vn.deviceProduction dp
WHERE dp.android_id = android_id;
IF vDeviceProductionFk THEN
-
- SELECT COUNT(*) INTO vIsGranted
- FROM vn.deviceProductionUser dpu
- WHERE dpu.userFk = vUserFK
+
+ SELECT COUNT(*) INTO vIsGranted
+ FROM vn.deviceProductionUser dpu
+ WHERE dpu.userFk = vUserFK
AND dpu.deviceProductionFk = vDeviceProductionFk;
-
+
RETURN vIsGranted;
END IF;*/
RETURN TRUE;
@@ -44925,27 +43125,25 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDua INT, vTaxClass INT) RETURNS decimal(5,2)
+CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDuaFk INT, vTaxClassFk INT) RETURNS decimal(5,2)
DETERMINISTIC
BEGIN
- DECLARE vCountryFk INTEGER;
-
- SELECT s.countryFk INTO vCountryFk
- FROM dua d
- JOIN supplier s ON s.id = d.companyFk
- WHERE d.id = vDua;
-
- RETURN (SELECT rate
- FROM
- (SELECT taxClassFk, rate
- FROM invoiceInTaxBookingAccount
- WHERE effectived <= util.VN_CURDATE()
- AND countryFk = vCountryFk
- AND taxClassFk = vTaxClass
- ORDER BY effectived DESC
- LIMIT 10000000000000000000
- ) ba1
- GROUP BY taxClassFk);
+/**
+ * Devuelve el rate para un Dua teniendo en cuenta la fecha de opreción del DUA
+ *
+ * @param vDuaFk Identificador de la tabla dua
+ * @param vTaxClassFk Identificador del IVA de la tabla invoiceInTaxBookingAccount
+ */
+ RETURN (
+ SELECT rate
+ FROM dua d
+ JOIN supplier s ON s.id = d.companyFk
+ JOIN invoiceInTaxBookingAccount iit ON iit.countryFk = s.countryFk
+ AND iit.taxClassFk = vTaxClassFk
+ AND iit.effectived <= IFNULL( d.operated, util.VN_CURDATE())
+ WHERE d.id = vDuaFk
+ ORDER BY effectived DESC
+ LIMIT 1);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -44966,24 +43164,24 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getEntry`(vEktFk INT) RETURNS in
READS SQL DATA
BEGIN
/**
- * Devuelve el numero de entrada para el ekt
- *
+ * Devuelve el numero de entrada para el ekt
+ *
* @param vEktFk Identificador de edi.ekt
- */
+ */
DECLARE vTravelFk INT;
DECLARE vEntryFk INT DEFAULT 0;
DECLARE vEntryAssignFk INT;
- SELECT ea.id
+ SELECT ea.id
INTO vEntryAssignFk
FROM edi.ekt e
- JOIN vn.ektEntryAssign ea ON
+ JOIN vn.ektEntryAssign ea ON
IFNULL(ea.sub, e.sub) <=> e.sub AND
IFNULL(ea.kop, e.kop) <=> e.kop AND
IFNULL(ea.pro, e.pro) <=> e.pro AND
IFNULL(ea.auction, e.auction) <=> e.auction
WHERE e.id = vEktFk
- ORDER BY
+ ORDER BY
IF(ea.sub,1,0) * 1000 +
IF(ea.kop,1,0) * 100 +
IF(ea.pro,1,0) * 10 +
@@ -44994,7 +43192,7 @@ BEGIN
IF vTravelFk THEN
- SELECT MAX(e.id)
+ SELECT MAX(e.id)
INTO vEntryFk
FROM vn.entry e
JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk
@@ -45009,13 +43207,13 @@ BEGIN
INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, reference, pro, auction)
SELECT vTravelFk, ea.supplierFk, ea.companyFk, cu.id, ea.kop, ea.sub, ea.ref, ea.pro, ea.auction
FROM vn.ektEntryAssign ea
- JOIN vn.currency cu ON cu.code = 'EUR'
+ JOIN vn.currency cu ON cu.code = 'EUR'
WHERE ea.id = vEntryAssignFk;
SET vEntryFk = LAST_INSERT_ID();
END IF;
- UPDATE vn.ektEntryAssign
+ UPDATE vn.ektEntryAssign
SET entryFk = vEntryFk
WHERE id = vEntryAssignFk;
@@ -45049,7 +43247,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getTravel`(vEntryAssignFk INT, v
BEGIN
/**
* Devuelve un vn.travel.id
- *
+ *
* @param vEntryAssignFk Identificador de vn.entryAssign
*/
DECLARE vTravelFk INT;
@@ -45110,36 +43308,36 @@ BEGIN
DECLARE vCurrentCommission INT;
DECLARE vIsCurrencyUsd INT;
DECLARE vLastEntryFk INT;
-
+
SELECT count(*) INTO vIsCurrencyUsd
FROM currency c
WHERE c.code = 'USD' AND id = vCurrencyFk;
-
+
IF NOT vIsCurrencyUsd THEN
-
+
SELECT e.id INTO vLastEntryFk
FROM vn.entry e
JOIN vn.travel tr ON tr.id = e.travelFk
WHERE e.supplierFk = vSupplierFk
ORDER BY tr.landed DESC
LIMIT 1;
-
+
IF vLastEntryFk THEN
-
+
SELECT commission INTO vCurrentCommission
FROM vn.entry
WHERE id = vLastEntryFk;
-
+
ELSE
-
+
SELECT commission INTO vCurrentCommission
FROM supplier s
WHERE s.id = vSupplierFk;
-
+
END IF;
-
+
RETURN vCurrentCommission;
-
+
ELSE
SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission
@@ -45148,11 +43346,11 @@ BEGIN
WHERE t.id = vTravelFk
ORDER BY r.`dated` DESC
LIMIT 1;
-
+
RETURN IFNULL(vCommission, 0);
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45203,10 +43401,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
-
+
/**
* Devuelve una entrada para Logiflora. Si no existe la crea.
- *
+ *
* @param vLanded Fecha de llegada al almacén
* @param vWarehouseFk Identificador de vn.warehouse
*/
@@ -45214,51 +43412,51 @@ BEGIN
DECLARE vTravelFk INT;
DECLARE vEntryFk INT;
DECLARE previousEntryFk INT;
-
+
SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk);
-
+
IF vLanded THEN
-
- SELECT IFNULL(MAX(id),0) INTO vEntryFk
+
+ SELECT IFNULL(MAX(id),0) INTO vEntryFk
FROM vn.entry
- WHERE travelFk = vTravelFk
+ WHERE travelFk = vTravelFk
AND isRaid;
IF NOT vEntryFk THEN
-
+
INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid)
SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE
FROM vn.supplier s
JOIN vn.company c ON c.code = 'VNL'
JOIN vn.currency cu ON cu.code = 'EUR'
WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN';
-
- SELECT MAX(id) INTO vEntryFk
+
+ SELECT MAX(id) INTO vEntryFk
FROM vn.entry
WHERE travelFk = vTravelFk;
-
+
END IF;
+
+ END IF;
- END IF;
-
- SELECT entryFk INTO previousEntryFk
+ SELECT entryFk INTO previousEntryFk
FROM edi.warehouseFloramondo wf
WHERE wf.warehouseFk = vWarehouseFk;
-
+
IF IFNULL(previousEntryFk,0) != vEntryFk THEN
-
- UPDATE buy b
- SET b.printedStickers = 0
+
+ UPDATE buy b
+ SET b.printedStickers = 0
WHERE entryFk = previousEntryFk;
DELETE FROM buy WHERE entryFk = previousEntryFk;
-
+
DELETE FROM entry WHERE id = previousEntryFk;
-
+
END IF;
-
+
RETURN vEntryFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45291,21 +43489,21 @@ BEGIN
SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id
INTO vIsUeeSupplier, vSupplierCountry
- FROM entry e
- JOIN supplier s ON s.id = e.supplierFk
- JOIN country c ON c.id = s.countryFk
+ FROM entry e
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN country c ON c.id = s.countryFk
LEFT JOIN province p ON p.id = s.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
WHERE e.id = vSelf;
-
+
SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id
INTO vIsUeeCompany, vCompanyCountry
- FROM entry e
- JOIN supplier s ON s.id = e.companyFk
- JOIN country c ON c.id = s.countryFk
+ FROM entry e
+ JOIN supplier s ON s.id = e.companyFk
+ JOIN country c ON c.id = s.countryFk
LEFT JOIN province p ON p.id = s.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
- WHERE e.id = vSelf;
+ WHERE e.id = vSelf;
RETURN vIsUeeCompany AND vIsUeeSupplier AND (vSupplierCountry <> vCompanyCountry);
@@ -45370,17 +43568,17 @@ BEGIN
DECLARE vHasDistinctRoutes BOOL;
SELECT t.routeFk INTO vRouteFk
- FROM vn.expedition e
+ FROM vn.expedition e
JOIN vn.ticket t ON e.ticketFk = t.id
WHERE e.id = vExpeditionFk;
-
+
SELECT COUNT(*) > 0 INTO vHasDistinctRoutes
FROM vn.expeditionScan es
JOIN vn.expedition e ON es.expeditionFk = e.id
JOIN vn.ticket t ON e.ticketFk = t.id
WHERE es.palletFk = vPalletFk
AND t.routeFk <> vRouteFk;
-
+
RETURN vHasDistinctRoutes;
END ;;
@@ -45441,27 +43639,27 @@ BEGIN
DECLARE vDeliveryType INTEGER DEFAULT 0;
DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
DECLARE vCode VARCHAR(45);
-
+
SELECT am.deliveryMethodFk
- INTO vDeliveryType
+ INTO vDeliveryType
FROM ticket t
JOIN agencyMode am ON am.id = t.agencyModeFk
WHERE t.id = vTicket;
-
+
CASE vDeliveryType
WHEN 1 THEN -- AGENCIAS
SET vCode = 'DELIVERED';
-
+
WHEN 2 THEN -- REPARTO
SET vCode = 'ON_DELIVERY';
-
+
ELSE -- MERCADO, OTROS
SELECT MIN(t.warehouseFk <> w.id) INTO isWaitingForPickUp
- FROM ticket t
+ FROM ticket t
LEFT JOIN warehouse w
ON w.pickUpagencyModeFk = t.agencyModeFk
WHERE t.id = vTicket;
-
+
IF isWaitingForPickUp THEN
SET vCode = 'WAITING_FOR_PICKUP';
ELSE
@@ -45491,28 +43689,28 @@ BEGIN
DECLARE vDeliveryType INTEGER DEFAULT 0;
DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
DECLARE vCode VARCHAR(45);
-
- SELECT
+
+ SELECT
a.Vista
- INTO vDeliveryType
+ INTO vDeliveryType
FROM vn2008.Tickets t
JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
WHERE Id_Ticket = vTicket;
-
+
CASE vDeliveryType
WHEN 1 THEN -- AGENCIAS
SET vCode = 'DELIVERED';
-
+
WHEN 2 THEN -- REPARTO
SET vCode = 'ON_DELIVERY';
-
+
ELSE -- MERCADO, OTROS
SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp
- FROM vn2008.Tickets t
- LEFT JOIN vn2008.warehouse_pickup w
+ FROM vn2008.Tickets t
+ LEFT JOIN vn2008.warehouse_pickup w
ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id
WHERE t.Id_Ticket = vTicket;
-
+
IF isWaitingForPickUp THEN
SET vCode = 'WAITING_FOR_PICKUP';
ELSE
@@ -45566,8 +43764,8 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getInventoryDate`() RETURNS date
DETERMINISTIC
-BEGIN
- RETURN vn2008.date_inv();
+BEGIN
+ RETURN (SELECT inventoried FROM config LIMIT 1);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45620,16 +43818,16 @@ BEGIN
DECLARE vReturn DATE;
DECLARE vDuaDate DATE;
DECLARE vDuaDateDay INT;
-
+
SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate;
IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN
- SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate);
+ SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate);
ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN
- SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate);
+ SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate);
END IF;
- IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN
+ IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN
IF util.isLeapYear(YEAR(vDuaDate)) THEN
SET vPayDay = 29;
ELSE
@@ -45637,7 +43835,7 @@ BEGIN
END IF;
END IF;
- SELECT DAY(vDuaDate) INTO vDuaDateDay;
+ SELECT DAY(vDuaDate) INTO vDuaDateDay;
RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay)));
END ;;
DELIMITER ;
@@ -45659,11 +43857,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getShipmentHour`(vTicket INT) RETURN
READS SQL DATA
BEGIN
DECLARE vShipmentHour INT;
-
+
SELECT HOUR(shipped) INTO vShipmentHour
FROM ticket
WHERE id = vTicket;
-
+
IF vShipmentHour = 0
THEN
DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
@@ -45678,11 +43876,11 @@ BEGIN
JOIN agencyMode am on am.id = t.agencyModeFk
JOIN address a on a.id = t.addressFk
WHERE t.id = vTicket;
-
- SELECT Hora INTO vShipmentHour
+
+ SELECT Hora INTO vShipmentHour
FROM tmp.production_buffer;
END IF;
-
+
RETURN vShipmentHour;
END ;;
DELIMITER ;
@@ -45707,12 +43905,12 @@ BEGIN
SELECT rate3 INTO price
FROM vn.priceFixed
- WHERE itemFk = vItemFk
+ WHERE itemFk = vItemFk
AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1;
- SELECT `value` INTO price
+ SELECT `value` INTO price
FROM vn.specialPrice
- WHERE itemFk = vItemFk
+ WHERE itemFk = vItemFk
AND clientFk = vClientFk ;
RETURN price;
END ;;
@@ -45736,7 +43934,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getTicketTrolleyLabelCount`(vTicket
BEGIN
DECLARE vLabelCount INT DEFAULT 0;
- SELECT labelCount INTO vLabelCount
+ SELECT labelCount INTO vLabelCount
FROM ticketTrolley
WHERE ticket = vTicket;
@@ -45803,48 +44001,83 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `hasAnyNegativeBase` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hasAnyNegativeBase`() RETURNS tinyint(1)
DETERMINISTIC
BEGIN
-/* Calcula si existe alguna base imponible negativa
-* Requiere la tabla temporal tmp.ticketToInvoice(id)
+/**
+* Calcula si existe alguna base imponible negativa
+* Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases()
*
* returns BOOLEAN
*/
+
DECLARE hasAnyNegativeBase BOOLEAN;
- DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
- CREATE TEMPORARY TABLE tmp.ticket
- (KEY (ticketFk))
- ENGINE = MEMORY
- SELECT id ticketFk
- FROM tmp.ticketToInvoice;
+ CALL getTaxBases();
- CALL ticket_getTax(NULL);
+ SELECT negative INTO hasAnyNegativeBase
+ FROM tmp.taxBases
+ LIMIT 1;
- SELECT COUNT(*) INTO hasAnyNegativeBase
- FROM(
- SELECT SUM(taxableBase) as taxableBase
- FROM tmp.ticketTax
- GROUP BY pgcFk
- HAVING taxableBase < 0
- ) t;
-
- DROP TEMPORARY TABLE tmp.ticketTax;
- DROP TEMPORARY TABLE tmp.ticket;
+ DROP TEMPORARY TABLE
+ tmp.ticketTax,
+ tmp.ticket,
+ tmp.taxBases;
RETURN hasAnyNegativeBase;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `hasAnyPositiveBase` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `hasAnyPositiveBase`() RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+
+/**
+* Calcula si existe alguna base imponible positiva
+* Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases()
+*
+* returns BOOLEAN
+*/
+
+ DECLARE hasAnyPositiveBase BOOLEAN;
+
+ CALL getTaxBases();
+
+ SELECT positive INTO hasAnyPositiveBase
+ FROM tmp.taxBases
+ LIMIT 1;
+
+ DROP TEMPORARY TABLE
+ tmp.ticketTax,
+ tmp.ticket,
+ tmp.taxBases;
+
+ RETURN hasAnyPositiveBase;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45866,17 +44099,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `hasItemsInSector`(vTicketFk INT, vSe
BEGIN
DECLARE vItemCount INT;
-
+
SELECT count(*) INTO vItemCount
- FROM vn.sale s
+ FROM vn.sale s
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
-
+
RETURN vItemCount;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45899,7 +44132,7 @@ BEGIN
DECLARE vCountry INT;
DECLARE hasSomeNegativeBase BOOLEAN;
- SELECT s.countryFk
+ SELECT s.countryFk
INTO vCountry
FROM supplier s
JOIN ticket t ON t.companyFk = s.id
@@ -45908,9 +44141,9 @@ BEGIN
SELECT COUNT(*) INTO hasSomeNegativeBase
FROM (
SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase
- FROM sale s
+ FROM sale s
JOIN item i ON i.id = s.itemFk
- JOIN itemTaxCountry itc
+ JOIN itemTaxCountry itc
ON itc.itemFk = i.id AND itc.countryFk = vCountry
WHERE s.ticketFk = vTicket
GROUP BY itc.taxClassFk
@@ -45926,6 +44159,49 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `intrastat_estimateNet` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `intrastat_estimateNet`(vSelf INT,
+ vStems INT
+) RETURNS double
+ DETERMINISTIC
+BEGIN
+/**
+* Calcula un valor neto estimado en función de
+* datos históricos de facturas intrastat.
+*
+* @param vSelf Id de intrastat
+* @param vStems Número de unidades
+* @return vNet
+*/
+ DECLARE vNet DOUBLE;
+
+ SELECT ROUND(vStems / (SUM(average) / COUNT(average)), 2) INTO vNet
+ FROM (
+ SELECT *, stems / net average
+ FROM invoiceInIntrastat
+ WHERE intrastatFk = vSelf
+ AND net
+ AND stems > 0
+ ORDER BY dated DESC
+ LIMIT 20
+ ) sub;
+
+ RETURN vNet/2;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `invoiceOutAmount` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -45940,14 +44216,14 @@ BEGIN
DECLARE totalAmount DECIMAL(10,2);
SELECT SUM(vat) INTO totalAmount
- FROM (
+ FROM (
SELECT iot.vat
FROM invoiceOutTax iot
JOIN invoiceOut io ON io.id = iot.invoiceOutFk
WHERE io.ref = vInvoiceRef
- UNION ALL
+ UNION ALL
SELECT ioe.amount
- FROM invoiceOutExpence ioe
+ FROM invoiceOutExpense ioe
JOIN invoiceOut io ON io.id = ioe.invoiceOutFk
WHERE io.ref = vInvoiceRef
) t1;
@@ -45976,23 +44252,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceOut_getMaxIssued`(vSerial VAR
READS SQL DATA
BEGIN
/**
- * Retorna la fecha a partir de la cual es válido emitir una factura
+ * Retorna la fecha a partir de la cual es válido emitir una factura
*
- * @param vSerial Serie de facturación
+ * @param vSerial Serie de facturación
* @param vCompanyFk Empresa factura emitida
* @param vYear Año contable
* @return vInvoiceOutIssued fecha factura válida
*/
DECLARE vInvoiceOutIssued DATE;
DECLARE vFirstDayOfYear DATE;
-
+
SET vFirstDayOfYear := MAKEDATE(vYear, 1);
- SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued
+ SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued
FROM invoiceOut io
WHERE io.serial = vSerial
AND io.companyFk = vCompanyFk
- AND io.issued BETWEEN vFirstDayOfYear
+ AND io.issued BETWEEN vFirstDayOfYear
AND util.lastDayOfYear(vFirstDayOfYear);
RETURN vInvoiceOutIssued;
@@ -46018,7 +44294,7 @@ BEGIN
DECLARE vIssued DATE;
DECLARE vSerial VARCHAR(15);
- SELECT issued, ref
+ SELECT issued, ref
INTO vIssued, vSerial
FROM invoiceOut WHERE id = vSelf;
@@ -46090,9 +44366,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceSerial`(vClientFk INT, vCompa
DETERMINISTIC
BEGIN
/**
- * Obtiene la serie de de una factura
+ * 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"]
@@ -46173,56 +44449,18 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `isLogifloraDay`(vShipped DATE, vWarehouse INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
-
+
DECLARE vIsLogifloraDay BOOLEAN;
SELECT COUNT(*) INTO vIsLogifloraDay
FROM edi.warehouseFloramondo wf
- JOIN vn.floramondoConfig fc
+ JOIN vn.floramondoConfig fc
WHERE wf.warehouseFk = vWarehouse
AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded))
AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded));
-
+
RETURN vIsLogifloraDay;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `isPalletHomogeneus` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` FUNCTION `isPalletHomogeneus`(vExpedition INT) RETURNS tinyint(1)
- READS SQL DATA
-BEGIN
- DECLARE vScanId INT;
- DECLARE vDistinctRoutesInThePallet INT;
-
- SELECT scan_id INTO vScanId
- FROM vn2008.scan_line
- WHERE code = vExpedition
- LIMIT 1;
-
- SELECT COUNT(*) INTO vDistinctRoutesInThePallet
- FROM (
- SELECT DISTINCT t.Id_Ruta
- FROM vn2008.scan_line sl
- JOIN vn2008.expeditions e ON e.expeditions_id = sl.code
- JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticket_id
- WHERE sl.scan_id = vScanId
- AND t.Id_Ruta
- ) t1;
-
- RETURN vDistinctRoutesInThePallet = 1;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46245,20 +44483,20 @@ BEGIN
DECLARE vPacking INTEGER DEFAULT 0;
DECLARE vItemFk INTEGER;
-
+
SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
-
- SELECT IFNULL(packing,0) INTO vPacking
- FROM vn.buy
+
+ SELECT IFNULL(packing,0) INTO vPacking
+ FROM vn.buy
WHERE id = CAST(vBarcode AS DECIMAL(18,0));
-
-
-
-
+
+
+
+
IF NOT vPacking THEN
CALL cache.last_buy_refresh(FALSE);
SELECT IFNULL(packing,1) INTO vPacking
- FROM
+ FROM
(SELECT packing , created
FROM vn.itemShelving
WHERE itemFk = vItemFk
@@ -46271,11 +44509,11 @@ BEGIN
) packings
ORDER BY created desc
LIMIT 1;
-
+
END IF;
-
+
RETURN vPacking;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46300,11 +44538,11 @@ BEGIN
DECLARE vColumn INT;
DECLARE vClosestParkingFk INT;
DECLARE vSectorFk INT;
-
+
SELECT p.column, sectorFk INTO vColumn, vSectorFk
FROM vn.parking p
WHERE p.id = vParkingFk;
-
+
SELECT itemShelvingFk INTO vClosestParkingFk
FROM
(
@@ -46314,12 +44552,12 @@ BEGIN
JOIN vn.itemPlacementSupplyList ipsl ON ipsl.sectorFk = ispss.sectorFk AND ipsl.itemFk = ispss.itemFk
WHERE p.sectorFk = vSectorFk
AND ipsl.saldo > 0
- ) sub
+ ) sub
ORDER BY distance
LIMIT 1;
-
+
RETURN vClosestParkingFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46341,17 +44579,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `itemsInSector_get`(vTicketFk INT, vS
BEGIN
DECLARE vItemCount INT;
-
+
SELECT count(*) INTO vItemCount
- FROM vn.sale s
+ FROM vn.sale s
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
-
+
RETURN vItemCount;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46424,29 +44662,29 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `item_getPackage`(vItemFk INT) RETURNS varchar(50) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
-
+
DECLARE vDiameter INT;
DECLARE vPackageFk VARCHAR(50);
DECLARE vCoeficient DOUBLE DEFAULT 1.08;
-
+
SELECT MAX(LEFT(value,3)) INTO vDiameter
- FROM vn.itemTag it
+ FROM vn.itemTag it
JOIN vn.tag t ON t.id = it.tagFk
WHERE it.itemFk = vItemFk
AND t.overwrite = 'diameter';
-
+
SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2)))
INTO vPackageFk
FROM vn.volumeConfig vc;
-
+
INSERT IGNORE INTO vn.packaging(id, width, `depth`)
- SELECT vPackageFk,
- FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)),
+ SELECT vPackageFk,
+ FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)),
FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter))
FROM vn.volumeConfig vc;
-
+
RETURN vPackageFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46483,7 +44721,7 @@ BEGIN
FROM packaging p
JOIN item i ON i.id = vSelf
WHERE p.id = vPackaging;
-
+
RETURN vVolume;
END ;;
@@ -46504,7 +44742,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `lastDayOfWeek`(vYear INT, vWeek INT) RETURNS date
DETERMINISTIC
-BEGIN
+BEGIN
/**
* Returns the date of the last day of the week
*
@@ -46543,16 +44781,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `machine_checkPlate`(vPlate VARCHAR(1
BEGIN
/**
* Comprueba si existe matrícula
- *
+ *
* @param vPlate matrícula del vehículo
* @return Devuelve TRUE en caso de que exista
- *
+ *
*/
-
+
IF (SELECT COUNT(*)
- FROM machine m
+ FROM machine m
WHERE m.plate = vPlate
- ) THEN
+ ) THEN
RETURN TRUE;
ELSE
RETURN FALSE;
@@ -46579,9 +44817,9 @@ BEGIN
DECLARE result INT;
DECLARE vSenderFk INT;
- SELECT id INTO vSenderFk
+ SELECT id INTO vSenderFk
FROM account.user WHERE `name` = account.myUser_getName();
-
+
RETURN (SELECT messageSendWithUser(vSenderFk, vRecipient, vMessage));
END ;;
DELIMITER ;
@@ -46608,9 +44846,9 @@ BEGIN
DECLARE vSendDate DATETIME DEFAULT util.VN_NOW();
DECLARE vSender VARCHAR(255) CHARSET utf8;
- SELECT `name` INTO vSender
+ SELECT `name` INTO vSender
FROM account.user WHERE id = vSenderFK;
-
+
SET vRecipient = LOWER(vRecipient);
DROP TEMPORARY TABLE IF EXISTS tRecipients;
@@ -46631,7 +44869,7 @@ BEGIN
IF vCount = 0 THEN
RETURN vCount;
- END IF;
+ END IF;
SET vUuid = UUID();
@@ -46642,7 +44880,7 @@ BEGIN
message = vMessage,
sendDate = vSendDate;
- INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate)
+ INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate)
SELECT vUuid, vSender, vRecipient, finalRecipient, vMessage, vSendDate
FROM tRecipients;
@@ -46676,32 +44914,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `nz` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` FUNCTION `nz`(vQuantity DOUBLE) RETURNS double
- DETERMINISTIC
-BEGIN
-
- DECLARE vResult DOUBLE;
-
- SET vResult = IFNULL(vQuantity,0);
-
- RETURN vResult;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `orderTotalVolume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -46716,7 +44928,7 @@ BEGIN
-- Devuelte el volumen total de la orden sumada
DECLARE vWarehouseId INTEGER;
DECLARE vVolume DECIMAL(10,3);
-
+
SELECT IFNULL(SUM(o.amount * ic.cm3delivery)/1000000,0) INTO vVolume
FROM hedera.orderRow o
JOIN item i ON i.id = o.itemFk
@@ -46793,7 +45005,7 @@ BEGIN
WHERE cb.id = packagingReturnFk;
SET vValue = IF (vAmount IS NULL,
- IFNULL(base,0),
+ IFNULL(base,0),
vAmount / IFNULL(upload, 0) + IFNULL(base, 0));
ELSE
SET vValue = IFNULL(price, 0) + IFNULL(base, 0);
@@ -46808,61 +45020,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `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 = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` FUNCTION `phytoPassport`(vRef VARCHAR(15)) RETURNS text CHARSET utf8mb3 COLLATE utf8mb3_general_ci
- DETERMINISTIC
-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.`code` = 'phytosanitaryPassport'
- 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 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `priceFixed_getRate2` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -46909,20 +45066,20 @@ BEGIN
DECLARE vRouteFk INT;
DECLARE vAddressFk INT;
-
+
DECLARE vLanded DATE;
DECLARE vZoneFk INT;
DECLARE vSignificativeFriendship INT DEFAULT 6;
DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10;
-
+
SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded
- FROM vn.ticket
+ FROM vn.ticket
WHERE id = vTicketFk;
-
+
-- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona
DROP TEMPORARY TABLE IF EXISTS tmp.route;
CREATE TEMPORARY TABLE tmp.route
- SELECT r.id routeFk,
+ SELECT r.id routeFk,
zf.friendship zoneFriendship
FROM vn.route r
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
@@ -46930,16 +45087,16 @@ BEGIN
AND zf.zoneFk = vZoneFk
AND r.created = vLanded
ORDER BY friendship;
-
+
-- Se eliminan aquellas que superan el volumen máximo
DELETE r.*
- FROM tmp.route r
+ FROM tmp.route r
JOIN (SELECT routeFk, sum(volume) volume
FROM vn.saleVolume
WHERE landed = vLanded
GROUP BY routeFk) sub ON sub.routeFk = r.routeFk
WHERE sub.volume > vVolumeMax;
-
+
-- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta
SELECT routeFk INTO vRouteFk
FROM
@@ -46951,7 +45108,7 @@ BEGIN
ORDER BY zoneFriendship DESC, friendshipSum DESC
) sub
LIMIT 1;
-
+
RETURN vRouteFk;
END ;;
DELIMITER ;
@@ -46976,9 +45133,9 @@ BEGIN
DECLARE vRouteFk INT;
DECLARE vAddressFk INT;
DECLARE vShipped DATETIME;
-
+
SELECT addressFk, date(shipped) INTO vAddressFk, vShipped
- FROM vn.ticket
+ FROM vn.ticket
WHERE id = vTicketFk;
SELECT routeFk INTO vRouteFk
@@ -46992,7 +45149,7 @@ BEGIN
ORDER BY friendshipSum DESC
) sub
LIMIT 1;
-
+
RETURN vRouteFk;
END ;;
DELIMITER ;
@@ -47016,20 +45173,20 @@ BEGIN
DECLARE vRouteFk INT;
DECLARE vAddressFk INT;
-
+
DECLARE vLanded DATE;
DECLARE vZoneFk INT;
DECLARE vSignificativeFriendship INT DEFAULT 6;
DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10;
-
+
SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded
- FROM vn.ticket
+ FROM vn.ticket
WHERE id = vTicketFk;
-
+
-- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona
DROP TEMPORARY TABLE IF EXISTS tmp.route;
CREATE TEMPORARY TABLE tmp.route
- SELECT r.id routeFk,
+ SELECT r.id routeFk,
zf.friendship zoneFriendship
FROM vn.route r
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
@@ -47037,16 +45194,16 @@ BEGIN
AND zf.zoneFk = vZoneFk
AND r.created = vLanded
ORDER BY friendship;
-
+
-- Se eliminan aquellas que superan el volumen máximo
DELETE r.*
- FROM tmp.route r
+ FROM tmp.route r
JOIN (SELECT routeFk, sum(volume) volume
FROM vn.saleVolume
WHERE landed = vLanded
GROUP BY routeFk) sub ON sub.routeFk = r.routeFk
WHERE sub.volume > vVolumeMax;
-
+
-- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta
SELECT routeFk INTO vRouteFk
FROM
@@ -47058,7 +45215,7 @@ BEGIN
ORDER BY zoneFriendship DESC, friendshipSum DESC
) sub
LIMIT 1;
-
+
RETURN vRouteFk;
END ;;
DELIMITER ;
@@ -47079,26 +45236,26 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `specie_IsForbidden`(vItemFk INT, vAddressFk INT) RETURNS tinyint(1)
READS SQL DATA
BEGIN
-
+
DECLARE vIsForbbiden BOOL;
DECLARE vLeft INT;
SELECT zg.lft INTO vLeft
- FROM vn.address a
- JOIN vn.zoneGeo zg ON zg.name = a.postalCode
+ FROM vn.address a
+ JOIN vn.zoneGeo zg ON zg.name = a.postalCode
WHERE a.id = vAddressFk;
-
+
SELECT sgi.isForbidden INTO vIsForbbiden
- FROM vn.specieGeoInvasive sgi
- JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk
+ FROM vn.specieGeoInvasive sgi
+ JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk
JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk)
WHERE vLeft BETWEEN zg.lft AND zg.rgt
AND ib.itemFk = vItemFk
- ORDER BY zg.`depth` DESC
+ ORDER BY zg.`depth` DESC
LIMIT 1;
RETURN IFNULL(vIsForbbiden, FALSE);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47118,7 +45275,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `testCIF`(vCIF VARCHAR(9)) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
-
+
DECLARE vLetraInicial VARCHAR(1);
DECLARE vLetraFinal VARCHAR(1);
DECLARE vParteNumerica VARCHAR(7);
@@ -47130,60 +45287,60 @@ BEGIN
SET vLetraInicial = SUBSTR(vCIF, 1, 1);
SET vLetraFinal = SUBSTR(vCIF, 9, 1);
SET vParteNumerica = SUBSTR(vCIF, 2, 7);
-
- WHILE i < 7 DO
-
+
+ WHILE i < 7 DO
+
SET i = i + 1;
-
+
SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0));
-
+
IF i MOD 2 THEN
-
+
SET vNumero = vNumero * 2;
SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10);
-
+
END IF;
-
+
SET vSuma = vSuma + vNumero;
-
+
END WHILE;
-
+
SET vSuma = vSuma MOD 10;
-
+
IF vSuma > 0 THEN
-
+
SET vSuma = 10 - vSuma;
-
+
END IF;
-
+
-- Comprobación de dígito de control
IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN
-
+
SET vResult = TRUE;
-
+
END IF;
-
+
IF vSuma = 0 THEN
-
+
SET vSuma = 10;
-
+
END IF;
-
+
IF CHAR(64 + vSuma) = vLetraFinal THEN
-
+
SET vResult = TRUE;
-
+
END IF;
-
+
-- Sólo se aceptan letras como caracter inicial
IF ASCII(vLetraInicial) < 65 OR ASCII(vLetraInicial) > 87 THEN -- Ha de ser entre la A y la W
-
+
SET vResult = FALSE;
-
+
END IF;
-
+
RETURN vResult;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47203,7 +45360,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `testNIE`(vNIE VARCHAR(9)) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
-
+
DECLARE vIndice INT;
DECLARE vNumero VARCHAR(7);
DECLARE vOperador VARCHAR(9);
@@ -47212,45 +45369,45 @@ BEGIN
DECLARE vLetraFinal VARCHAR(1);
DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE";
DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE;
-
+
SET vLetraInicial = SUBSTR(vNIE, 1, 1);
SET vLetraFinal = SUBSTR(vNIE, 9, 1);
SET vNumero = SUBSTR(vNIE, 2, 7);
CASE vLetraInicial
-
+
WHEN 'X' THEN
-
+
SET vOperador = "0";
-
+
WHEN 'Y' THEN
-
+
SET vOperador = "1";
-
+
WHEN 'Z' THEN
-
+
SET vOperador = "2";
-
+
ELSE
-
+
SET vLetraInicialEsIncorrecta = TRUE;
-
+
END CASE;
-
+
SET vOperador = CONCAT(vOperador, vNumero);
SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0));
SET vIndice = Round(vParteNumerica Mod 23, 0) + 1;
IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN
-
+
RETURN TRUE;
-
+
ELSE
-
+
RETURN FALSE;
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47275,23 +45432,23 @@ BEGIN
DECLARE vParteNumerica DECIMAL(8,0);
DECLARE vLetra VARCHAR(1);
DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE";
-
+
SET vLetra = SUBSTRING(vNIF, 9, 1);
-
+
SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0));
-
+
SET vIndice = Round(vParteNumerica MOD 23, 0) + 1;
-
+
If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then
-
+
RETURN TRUE;
-
+
ELSE
-
+
RETURN FALSE;
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47311,21 +45468,21 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticketCollection_getNoPacked`(vCollectionFk INT) RETURNS varchar(100) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
-
+
/*
* return message with tickets and collection if there is tickets of a collection without expeditions
- *
+ *
* @param vCollectionFk the collection to check
* @return an array with collection and tickets without expeditions
- *
+ *
*/
-
+
DECLARE vAnswer VARCHAR(100) DEFAULT '';
IF collection_isPacked(vCollectionFk) = FALSE THEN
SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer
FROM vn.ticketCollection tc
- LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk
+ LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk
WHERE tc.collectionFk = vCollectionFk
AND ISNULL(e.id);
END IF;
@@ -47371,9 +45528,9 @@ BEGIN
DROP TEMPORARY TABLE
tmp.ticket,
tmp.ticketTotal;
-
+
RETURN vTotal;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47393,7 +45550,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
DETERMINISTIC
BEGIN
-
+
DECLARE vRestTicketsMaxOrder INT;
DECLARE vRestTicketsMinOrder INT;
DECLARE vRestTicketsPacking INT;
@@ -47405,7 +45562,7 @@ BEGIN
DECLARE vExpeditionsCount INT;
DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE;
-SELECT `order`
+SELECT `order`
INTO PACKING_ORDER
FROM state
WHERE code = 'PACKING';
@@ -47413,10 +45570,10 @@ SELECT `order`
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
+ LEFT JOIN ticketState ts on ts.ticketFk = t.id
WHERE t.id = vTicketId;
-SELECT (ag.`name` = 'VN_VALENCIA')
+SELECT (ag.`name` = 'VN_VALENCIA')
INTO vIsValenciaPath
FROM vn2008.Rutas r
JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia
@@ -47430,19 +45587,19 @@ IF vIsValenciaPath THEN -- Rutas Valencia
FROM expedition e
JOIN ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vMyPath;
-
+
SELECT MAX(ts.productionOrder), MIN(ts.productionOrder)
INTO vRestTicketsMaxOrder, vRestTicketsMinOrder
FROM ticket t
- LEFT JOIN ticketState ts on t.id = ts.ticket
+ LEFT JOIN ticketState ts on t.id = ts.ticketFk
WHERE t.routeFk = vMyPath
AND t.warehouseFk = vMyWarehouse
AND t.id != vTicketid;
- SELECT COUNT(*)
+ SELECT COUNT(*)
INTO vRestTicketsPacking
FROM ticket t
- LEFT JOIN ticketState ts on t.id = ts.ticket
+ LEFT JOIN ticketState ts on t.id = ts.ticketFk
WHERE ts.productionOrder = PACKING_ORDER
AND t.routeFk = vMyPath
AND t.warehouseFk = vMyWarehouse
@@ -47494,9 +45651,9 @@ BEGIN
LEFT JOIN vn2008.movement_label l ON l.Id_Movimiento = s.id
WHERE ticketFk = vTicketFk
) sub;
-
+
RETURN IFNULL(vSplitCounter,'--');
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47545,21 +45702,21 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticketTotalVolumeBoxes`(vTicketId IN
DETERMINISTIC
BEGIN
-/*
+/*
* Devuelve el volumen estimado del ticket sumado, en cajas
*
* vTicketId Numero de ticket
- *
+ *
*/
DECLARE vVolumeBoxM3 DOUBLE;
DECLARE vTicketTotalVolumeBoxes DECIMAL(10,1);
DECLARE vVnBoxId VARCHAR(10) DEFAULT '94';
-
+
SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId;
-
+
SET vTicketTotalVolumeBoxes = ticketTotalVolume(vTicketId) / vVolumeBoxM3;
-
+
RETURN vTicketTotalVolumeBoxes;
END ;;
@@ -47584,7 +45741,7 @@ BEGIN
DECLARE vWarehouseFk INT;
SELECT warehouseFk INTO vWarehouseFk
- FROM ticket
+ FROM ticket
WHERE id = vTicketFk;
RETURN vWarehouseFk;
@@ -47607,18 +45764,18 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_CC_volume`(vTicketFk INT) RETURNS decimal(10,1)
READS SQL DATA
BEGIN
-
+
DECLARE vCC DECIMAL(10,1);
SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000)
INTO vCC
- FROM vn.saleVolume sv
- JOIN vn.sale s ON s.id = sv.saleFk
- JOIN vn.item i ON i.id = s.itemFk
+ FROM vn.saleVolume sv
+ JOIN vn.sale s ON s.id = sv.saleFk
+ JOIN vn.item i ON i.id = s.itemFk
JOIN vn.packaging p ON p.id = 'CC'
- JOIN vn.volumeConfig vc
+ JOIN vn.volumeConfig vc
WHERE sv.ticketFk = vTicketFk;
-
+
RETURN vCC;
END ;;
@@ -47640,44 +45797,44 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_get`(vParamFk INT) RETURNS int(11)
READS SQL DATA
proc:BEGIN
-
+
/* Devuelve el número de ticket o collection consultando en varias tablas posibles
- *
+ *
* @param vParamFk Número a validar
* @return vValidFk Identificador validado
*/
-
+
DECLARE vValidFk INT;
-- Tabla vn.saleGroup
SELECT s.ticketFk INTO vValidFk
FROM vn.sale s
JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
- JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
+ JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
WHERE sg.id = vParamFk
AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE())
LIMIT 1;
-
+
IF vValidFk THEN
-
+
RETURN vValidFk;
-
+
LEAVE proc;
-
+
END IF;
-- Tabla vn.collection
SELECT c.id INTO vValidFk
- FROM vn.collection c
+ FROM vn.collection c
WHERE c.id = vParamFk
AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
-
+
IF vValidFk THEN
-
+
RETURN vValidFk;
-
+
LEAVE proc;
-
+
END IF;
-- Tabla vn.ticket
@@ -47685,17 +45842,17 @@ proc:BEGIN
FROM vn.ticket t
WHERE t.id = vParamFk
AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
-
+
IF vValidFk THEN
-
+
RETURN vValidFk;
-
+
LEAVE proc;
-
+
END IF;
RETURN NULL;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47721,8 +45878,8 @@ BEGIN
* @vTicketFk Id del ticket a calcular
*/
DECLARE deliveryPrice DECIMAL (10,2);
-
- IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id
+
+ IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id
WHERE t.id = vTicketFk) THEN
SELECT SUM(sv.freight) INTO deliveryPrice
FROM vn.saleVolume sv
@@ -47733,7 +45890,7 @@ BEGIN
LEFT JOIN expedition e ON e.ticketFk = t.id
JOIN expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
WHERE t.id = vTicketFk;
-
+
END IF;
RETURN deliveryPrice;
END ;;
@@ -47757,16 +45914,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_getWeight`(vTicketFk INT) RET
BEGIN
/**
* Devuelve el peso total del ticket
- *
+ *
* @return Total peso
*/
-
+
DECLARE vWeight DECIMAL(10,3);
SELECT sum(weight) INTO vWeight
FROM saleVolume
WHERE ticketFk = vTicketFk;
-
+
RETURN vWeight;
END ;;
@@ -47788,15 +45945,15 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_HasUbication`(vTicketFk INT) RETURNS tinyint(1)
READS SQL DATA
BEGIN
-
+
DECLARE hasUbication BOOL;
SELECT COUNT(*) INTO hasUbication
FROM vn.ticket t
JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
- WHERE rm.beachFk
+ WHERE rm.beachFk
AND t.id = vTicketFk;
-
+
RETURN hasUbication;
END ;;
@@ -47884,7 +46041,7 @@ BEGIN
-- Inserta los asientos contables
SELECT account INTO vAccount
- FROM bank WHERE id = vBank;
+ FROM accounting WHERE id = vBank;
SELECT accountingAccount INTO vSubaccount
FROM `client` WHERE id = vClient;
@@ -47945,7 +46102,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `timeWorkerControl_getDirection`(vUse
READS SQL DATA
BEGIN
/**
- * Verifica la dirección de la fichada
+ * Verifica la dirección de la fichada
* @param vUserFk Identificador del trabajador
* @param vTimed Hora de la fichada
* @return Retorna sentido de la fichada 'in, out, middle'
@@ -47958,40 +46115,40 @@ BEGIN
DECLARE vDayStayMax INT;
DECLARE vTimedSeconds INT;
DECLARE vLastTimeIn INT;
-
+
SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds;
-
+
SELECT dayStayMax INTO vDayStayMax
FROM vn.workerTimeControlParams;
SELECT timed, direction INTO vNext,vNextDirection
- FROM vn.workerTimeControl
- WHERE userFk = vUserFk
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
AND direction IN ('in','out')
AND timed > vTimed
ORDER BY timed ASC
LIMIT 1;
-
+
SELECT timed, direction INTO vPrevious, vPreviousDirection
- FROM vn.workerTimeControl
- WHERE userFk = vUserFk
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
AND direction IN ('in','out')
AND timed < vTimed
ORDER BY timed DESC
- LIMIT 1;
-
- IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN
+ LIMIT 1;
+
+ IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN
RETURN 'middle';
END IF;
-
-
+
+
IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN
- IF vPreviousDirection = 'in' THEN
+ IF vPreviousDirection = 'in' THEN
RETURN 'out';
ELSE
SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn
- FROM vn.workerTimeControl
- WHERE userFk = vUserFk
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
AND direction ='in'
AND timed < vPrevious;
IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN
@@ -48045,11 +46202,11 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
-
+
/**
* Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén.
* Si no existe lo genera.
- *
+ *
* @param vLanded Fecha de llegada al almacén
* @param vWarehouseFk Identificador de vn.warehouse
*/
@@ -48057,8 +46214,8 @@ BEGIN
DECLARE vTravelFk INT;
IF vLanded THEN
-
- SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
+
+ SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
FROM vn.travel tr
JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
@@ -48069,14 +46226,14 @@ BEGIN
AND landed = vLanded;
IF NOT vTravelFk THEN
-
+
INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
- SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id
- FROM vn.warehouse wOut
+ SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id
+ FROM vn.warehouse wOut
JOIN vn.agencyMode am ON am.name = 'LOGIFLORA'
WHERE wOut.name = 'Holanda';
-
- SELECT MAX(tr.id) INTO vTravelFk
+
+ SELECT MAX(tr.id) INTO vTravelFk
FROM vn.travel tr
JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
@@ -48084,11 +46241,50 @@ BEGIN
AND wOut.name = 'Holanda'
AND landed = vLanded;
END IF;
-
+
END IF;
-
+
RETURN vTravelFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `travel_hasUniqueAwb` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `travel_hasUniqueAwb`(vSelf INT
+) RETURNS tinyint(1)
+ READS SQL DATA
+BEGIN
+/**
+ * Comprueba que el travel pasado tiene un AWB lógico,
+ * no se pueden tener varios AWB asociados al mismo DUA
+ *
+ * @param vSelf Id del travel
+ */
+ DECLARE vHasUniqueAwb BOOL DEFAULT TRUE;
+ SELECT NOT COUNT(t2.awbFk) INTO vHasUniqueAwb
+ FROM entry e
+ JOIN travel t ON t.id = e.travelFk
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN duaEntry de2 ON de2.duaFk = de.duaFk
+ JOIN entry e2 ON e2.id = de2.entryFk
+ JOIN travel t2 ON t2.id = e2.travelFk
+ WHERE t.id = vSelf
+ AND t2.awbFk <> t.awbFk;
+
+ RETURN vHasUniqueAwb;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48115,21 +46311,21 @@ BEGIN
DECLARE vChar INT;
SET vLength = length(vString);
-
+
WHILE vLength > 0 DO
-
+
SET vChar = MID(vString,vLength,1);
-
+
SET vSeed = vSeed + ASCII(vChar);
-
+
SET vLength = vLength - 1;
-
+
END WHILE;
SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000;
RETURN vCode;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48156,21 +46352,21 @@ BEGIN
DECLARE vChar INT;
SET vLength = length(vString);
-
+
WHILE vLength > 0 DO
-
+
SET vChar = MID(vString,vLength,1);
-
+
SET vSeed = vSeed + ASCII(vChar);
-
+
SET vLength = vLength - 1;
-
+
END WHILE;
SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000;
RETURN vCode;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48231,15 +46427,15 @@ BEGIN
* @param vTimeOut
* @return vNigthlyHours
*/
- DECLARE vNigthlyHours DECIMAL(5,2);
+ DECLARE vNigthlyHours DECIMAL(5,2);
DECLARE vSecondsPerHour INT(4) DEFAULT 3600;
-
+
SELECT GREATEST(0, TIMESTAMPDIFF(SECOND,
- IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours,
- CONCAT(DATE(vTimeIn), ' ', startNightlyHours),
+ IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours,
+ CONCAT(DATE(vTimeIn), ' ', startNightlyHours),
vTimeIn),
- IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours,
- CONCAT(DATE(vTimeOut), ' ', endNightlyHours),
+ IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours,
+ CONCAT(DATE(vTimeOut), ' ', endNightlyHours),
vTimeOut))) / vSecondsPerHour INTO vNigthlyHours
FROM vn.workerTimeControlConfig;
@@ -48252,144 +46448,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `workerTimeControl_add` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` FUNCTION `workerTimeControl_add`(vUserFk INT, vWarehouseFk INT, vTimed DATETIME, vIsManual BOOL) RETURNS int(11)
- DETERMINISTIC
-BEGIN
- DECLARE vDirection VARCHAR(6);
- DECLARE vLastIn DATETIME;
- DECLARE vDayStayMax INT;
- DECLARE vHasDirectionOut INT;
- DECLARE vLastInsertedId INT;
-
- SELECT dayStayMax INTO vDayStayMax
- FROM workerTimeControlParams;
-
- SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection;
-
- IF vDirection = 'out' THEN
-
- SELECT MAX(timed) INTO vLastIn
- FROM workerTimeControl
- WHERE userFk = vUserFk
- AND direction = 'in'
- AND timed < vTimed;
-
- UPDATE workerTimeControl wtc
- SET wtc.direction = 'middle'
- WHERE userFk = vUserFk
- AND direction = 'out'
- AND timed BETWEEN vLastIn AND vTimed;
-
- ELSE IF vDirection = 'in' THEN
-
- SELECT COUNT(*) INTO vHasDirectionOut
- FROM workerTimeControl wtc
- WHERE userFk = vUserFk
- AND direction = 'out'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
-
- UPDATE workerTimeControl wtc
- SET wtc.direction = IF (vHasDirectionOut,'middle','out')
- WHERE userFk = vUserFk
- AND direction = 'in'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
-
- END IF;
- END IF;
-
- INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual)
- VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual);
-
- SET vLastInsertedId = LAST_INSERT_ID();
-
- CALL workerTimeControlSOWP(vUserFk, vTimed);
-
- RETURN vLastInsertedId;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `workerTimeControl_addDirection` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` FUNCTION `workerTimeControl_addDirection`(vUserFk INT, vWarehouseFk INT, vTimed DATETIME, vIsManual BOOL) RETURNS int(11)
- DETERMINISTIC
-BEGIN
- DECLARE vDirection VARCHAR(6);
- DECLARE vLastIn DATETIME;
- DECLARE vDayStayMax INT;
- DECLARE vHasDirectionOut INT;
- DECLARE vLastInsertedId INT;
-
- SELECT dayStayMax INTO vDayStayMax
- FROM workerTimeControlParams;
-
- SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection;
-
- IF vDirection = 'out' THEN
-
- SELECT MAX(timed) INTO vLastIn
- FROM workerTimeControl
- WHERE userFk = vUserFk
- AND direction = 'in'
- AND timed < vTimed;
-
- UPDATE workerTimeControl wtc
- SET wtc.direction = 'middle'
- WHERE userFk = vUserFk
- AND direction = 'out'
- AND timed BETWEEN vLastIn AND vTimed;
-
- ELSE IF vDirection = 'in' THEN
-
- SELECT COUNT(*) INTO vHasDirectionOut
- FROM workerTimeControl wtc
- WHERE userFk = vUserFk
- AND direction = 'out'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
-
- UPDATE workerTimeControl wtc
- SET wtc.direction = IF (vHasDirectionOut,'middle','out')
- WHERE userFk = vUserFk
- AND direction = 'in'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
-
- END IF;
- END IF;
-
- INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual)
- VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual);
-
- SET vLastInsertedId = LAST_INSERT_ID();
-
- CALL workerTimeControlSOWP(vUserFk, vTimed);
-
- RETURN vLastInsertedId;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `worker_getCode` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -48475,6 +46533,45 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `worker_isInDepartment` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` FUNCTION `worker_isInDepartment`(vDepartmentCode VARCHAR(255)) RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Devuelve booleano si el trabajador conectado pertenece
+ * al departamento vDepartmentCode o a sus departamentos subordinados
+ *
+ * @param vDepartmentCode code del departamento que se desea comprobar.
+ * @return Devuelve verdadero si es jefe del empleado por escala jerárquica.
+ */
+ DECLARE vIsInDepartment BOOLEAN;
+ WITH RECURSIVE department AS (
+ SELECT d.id FROM vn.department d WHERE code = vDepartmentCode
+ UNION
+ SELECT d.id
+ FROM department ds
+ JOIN vn.department d ON ds.id = d.parentFk
+ )
+ SELECT COUNT(*) INTO vIsInDepartment FROM department ds
+ JOIN vn.workerDepartment wd ON wd.departmentFk = ds.id
+ WHERE wd.workerFk = account.myUser_getId();
+
+ RETURN vIsInDepartment;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `worker_isWorking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -48491,17 +46588,17 @@ BEGIN
* @return Devuelve TRUE en caso de que este trabajando. Si se encuentra en un descanso devolverá FALSE
*/
DECLARE vLastIn DATETIME ;
-
+
SELECT MAX(timed) INTO vLastIn
- FROM vn.workerTimeControl
+ FROM vn.workerTimeControl
WHERE userFk = vWorkerFk AND
direction = 'in';
- IF (SELECT MOD(COUNT(*),2)
- FROM vn.workerTimeControl
- WHERE userFk = vWorkerFk AND
+ IF (SELECT MOD(COUNT(*),2)
+ FROM vn.workerTimeControl
+ WHERE userFk = vWorkerFk AND
timed >= vLastIn
- ) THEN
+ ) THEN
RETURN TRUE;
ELSE
RETURN FALSE;
@@ -48595,7 +46692,7 @@ BEGIN
SET `type` = vType,
`name` = vName,
parentFk = vParentFk;
-
+
SET vSelf = LAST_INSERT_ID();
UPDATE zoneGeoRecalc SET isChanged = TRUE;
@@ -48619,7 +46716,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `addNoteFromDelivery`(idTicket INT,nota TEXT)
BEGIN
-
+
DECLARE observationTypeFk INT DEFAULT 3; /*3 = REPARTIDOR*/
INSERT INTO ticketObservation(ticketFk,observationTypeFk,description)
@@ -48647,23 +46744,23 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `addressTaxArea`()
READS SQL DATA
BEGIN
/**
- * Devuelve el taxArea para un conjunto de Consignatarios y empresas,
+ * Devuelve el taxArea para un conjunto de Consignatarios y empresas,
*
* @table tmp.addressCompany(addressFk, companyFk) valores a calcular
* @return tmp.addressTaxArea(addressFk,companyFk)
*/
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea;
CREATE TEMPORARY TABLE tmp.addressTaxArea
(PRIMARY KEY (addressFk, companyFk))
ENGINE = MEMORY
- SELECT CASE
- WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember)
- AND NOT (auSupplier.id <=> auClient.id) THEN
+ SELECT CASE
+ WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember)
+ AND NOT (auSupplier.id <=> auClient.id) THEN
'WORLD'
- WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN
+ WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN
'CEE'
- WHEN a.isEqualizated AND cClient.code = 'ES' THEN
+ WHEN a.isEqualizated AND cClient.code = 'ES' THEN
'EQU'
ELSE
'NATIONAL'
@@ -48704,27 +46801,27 @@ BEGIN
* @param vAddress id de la direccion
* @param vWarehouse id del warehouse
* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida
-*/
+*/
DECLARE vAgency INT;
DECLARE vShipped DATE;
DECLARE vLanded DATE DEFAULT util.VN_CURDATE();
SELECT agencyFk INTO vAgency FROM agencyMode WHERE id= vAgencyMode;
l: LOOP
-
+
CALL agencyHourGetShipped(vLanded,vAddress,vAgency);
- SELECT shipped INTO vShipped
+ SELECT shipped INTO vShipped
FROM tmp.agencyHourGetShipped
WHERE warehouseFk = vWarehouse LIMIT 1;
-
+
IF vShipped THEN
LEAVE l;
END IF;
-
+
SET vLanded = DATE_ADD(vLanded, INTERVAL +1 DAY);
-
+
END LOOP;
-
+
SELECT vShipped,vLanded;
END ;;
DELIMITER ;
@@ -48775,7 +46872,7 @@ BEGIN
LIMIT 1
) t
WHERE IF(vDated = util.VN_CURDATE(), t.maxHour > HOUR(util.VN_NOW()), TRUE) AND t.substractDay < 225;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48798,14 +46895,14 @@ BEGIN
* DEPRECATED usar zoneGetWarehouse
* Devuelve el listado de agencias disponibles para la fecha,
* dirección y warehouuse pasadas
- *
+ *
* @param vAddress no puede ser NULL
* @param vWarehouse warehouse donde comprobaremos las agencias y fecha
* @param vDate Fecha de recogida
* @table agencyModeWarehouseList Listado de agencias disponibles
*/
DECLARE vAgency INT;
- DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vCur CURSOR FOR
SELECT DISTINCT a.id
FROM agency a
@@ -48829,13 +46926,13 @@ BEGIN
PRIMARY KEY(id)
)
ENGINE = MEMORY;
-
+
OPEN vCur;
FETCH vCur INTO vAgency;
WHILE NOT vDone
DO
-
+
INSERT INTO tmp.agencyModeWarehouseList
SELECT am.id, am.name, am.description,am.deliveryMethodFk, TIMESTAMPADD(DAY, -ah.substractDay, vDate), w.name
FROM agencyHour ah
@@ -48864,7 +46961,7 @@ BEGIN
END WHILE;
CLOSE vCur;
-
+
SELECT * FROM tmp.agencyModeWarehouseList;
DROP TEMPORARY TABLE tmp.agencyModeWarehouseList;
END ;;
@@ -48890,9 +46987,9 @@ BEGIN
CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency);
SELECT * FROM tmp.agencyHourGetShipped;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48930,7 +47027,7 @@ BEGIN
DECLARE cWarehouses CURSOR FOR
SELECT warehouseFk, shipped FROM tmp.zoneGetShipped;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
@@ -48939,7 +47036,7 @@ BEGIN
CALL vn.zone_getShipped (vDate, vAddress, vAgencyMode, FALSE);
DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc;
- CREATE TEMPORARY TABLE tmp.availableCalc(
+ CREATE TEMPORARY TABLE tmp.availableCalc(
calcFk INT UNSIGNED,
PRIMARY KEY (calcFk)
)
@@ -48950,7 +47047,7 @@ BEGIN
l: LOOP
SET vDone = FALSE;
FETCH cWarehouses INTO vWarehouse, vShipment;
-
+
IF vDone THEN
LEAVE l;
END IF;
@@ -48971,6 +47068,267 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `balanceNestTree_addChild` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `balanceNestTree_addChild`(
+ vSelf INT,
+ vName VARCHAR(45)
+)
+BEGIN
+/**
+ * Agrega un nuevo nodo hijo a un nodo existente dentro de la estructura
+ * de árbol de vn.balanceNestTree.
+ *
+ * @param vSelf Identificador del nodo
+ * @param vName Nombre del nuevo nodo hijo
+ */
+ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree');
+ DECLARE vLeft INT;
+
+ CREATE OR REPLACE TEMPORARY TABLE tAux
+ SELECT 0 lft;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux
+ SET lft = (SELECT lft
+ FROM ', vTable,
+ ' WHERE id = ?)')
+ USING vSelf;
+
+ SELECT lft INTO vLeft FROM tAux;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable, '
+ SET rgt = rgt + 2
+ WHERE rgt > ?
+ ORDER BY rgt DESC')
+ USING vLeft;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable, '
+ SET lft = lft + 2
+ WHERE lft > ?
+ ORDER BY lft DESC')
+ USING vLeft;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'INSERT INTO ', vTable, ' (name, lft, rgt)
+ VALUES(?, ? + 1, ? + 2)')
+ USING vName,
+ vLeft,
+ vLeft;
+
+ DROP TEMPORARY TABLE tAux;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `balanceNestTree_delete` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `balanceNestTree_delete`(
+ vSelf INT
+)
+BEGIN
+/**
+ * Elimina un nodo dentro de la estructura de árbol de vn.balanceNestTree.
+ *
+ * @param vSelf Identificador del nodo
+ */
+ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree');
+ DECLARE vRight INT;
+ DECLARE vLeft INT;
+ DECLARE vWidth INT;
+
+ CREATE OR REPLACE TEMPORARY TABLE tAux
+ SELECT 0 rgt, 0 lft, 0 wdt;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux a
+ JOIN ', vTable, ' t
+ SET a.rgt = t.rgt,
+ a.lft = t.lft,
+ a.wdt = t.rgt - t.lft + 1
+ WHERE t.id = ?')
+ USING vSelf;
+
+ SELECT rgt, lft, wdt
+ INTO vRight, vLeft, vWidth
+ FROM tAux;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'DELETE FROM ', vTable,
+ ' WHERE lft BETWEEN ? AND ?')
+ USING vLeft, vRight;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ ' SET rgt = rgt - ?
+ WHERE rgt > ?
+ ORDER BY rgt')
+ USING vWidth,vRight;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ ' SET lft = lft - ?
+ WHERE lft > ?
+ ORDER BY lft')
+ USING vWidth, vRight;
+
+ DROP TEMPORARY TABLE tAux;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `balanceNestTree_move` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `balanceNestTree_move`(
+ vSelf INT,
+ vFather INT
+)
+BEGIN
+/**
+ * Mueve un nodo dentro de la estructura de árbol de vn.balanceNestTree.
+ *
+ * @param vSelf Identificador del nodo
+ * @param vFather Identificador del nuevo padre del nodo
+ */
+ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree');
+ DECLARE vRight INT;
+ DECLARE vLeft INT;
+ DECLARE vWidth INT;
+ DECLARE vFatherRight INT;
+ DECLARE vFatherLeft INT;
+ DECLARE vGap INT;
+
+ CREATE OR REPLACE TEMPORARY TABLE tAux
+ SELECT 0 rgt, 0 lft, 0 wdt, 0 frg, 0 flf;
+
+ -- Averiguamos el ancho de la rama
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux a
+ JOIN ', vTable, ' t
+ SET a.wdt = t.rgt - t.lft + 1
+ WHERE t.id = ?')
+ USING vSelf;
+
+ -- Averiguamos la posicion del nuevo padre
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux a
+ JOIN ', vTable, ' t
+ SET a.frg = t.rgt,
+ a.flf = t.lft
+ WHERE t.id = ?')
+ USING vFather;
+
+ SELECT wdt, frg, flf
+ INTO vWidth, vFatherRight, vFatherLeft
+ FROM tAux;
+
+ -- 1º Incrementamos los valores de todos los nodos a la derecha
+ -- del punto de inserción (vFatherRight) , para hacer sitio
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET rgt = rgt + ?
+ WHERE rgt >= ?
+ ORDER BY rgt DESC')
+ USING vWidth,
+ vFatherRight;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET lft = lft + ?
+ WHERE lft >= ?
+ ORDER BY lft DESC')
+ USING vWidth,
+ vFatherRight;
+
+ -- Es preciso recalcular los valores del nodo en el
+ -- caso de que estuviera a la derecha del nuevo padre
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux a
+ JOIN ', vTable, ' t
+ SET a.rgt = t.rgt,
+ a.lft = t.lft
+ WHERE t.id = ?')
+ USING vSelf;
+
+ SELECT lft, rgt, frg - lft
+ INTO vLeft, vRight, vGap
+ FROM tAux;
+
+ -- 2º Incrementamos el valor de todos los nodos a
+ -- trasladar hasta alcanzar su nueva posicion
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET lft = lft + ?
+ WHERE lft BETWEEN ? AND ?
+ ORDER BY lft DESC')
+ USING vGap,
+ vLeft,
+ vRight;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET rgt = rgt + ?
+ WHERE rgt BETWEEN ? AND ?
+ ORDER BY rgt DESC')
+ USING vGap,
+ vLeft,
+ vRight;
+
+ -- 3º Restaremos a todos los nodos resultantes, a la derecha
+ -- de la posicion arrancada el ancho de la rama escindida
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET lft = lft - ?
+ WHERE lft > ?
+ ORDER BY lft')
+ USING vWidth,
+ vLeft;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET rgt = rgt - ?
+ WHERE rgt > ?
+ ORDER BY rgt')
+ USING vWidth,
+ vRight;
+
+ DROP TEMPORARY TABLE tAux;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `bankEntity_checkBic` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -48983,7 +47341,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `bankEntity_checkBic`(vBic VARCHAR(2
BEGIN
/**
* If the bic length is Incorrect throw exception
- *
+ *
* @param vBic bic code
*/
@@ -48991,7 +47349,7 @@ BEGIN
SELECT bicLength INTO vConfigBicLenght
FROM vn.bankEntityConfig bec;
-
+
IF LENGTH(vBic) <> vConfigBicLenght THEN
CALL util.throw(CONCAT('bic must be of length ', vConfigBicLenght ));
END IF;
@@ -49018,17 +47376,15 @@ BEGIN
* Manda correo cuando caduca un seguro
* de los leasing
*
-*/
+*/
INSERT INTO mail (receiver,replyTo,subject,body)
SELECT 'administracion@verdnatura.es' receiver,
'noreply@verdnatura.es' replyTo,
- CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') subject,
- CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') body
- FROM vn.bankPolicy bp
- LEFT JOIN vn.supplier s
- ON s.id = bp.supplierFk
- LEFT JOIN vn.bank b
- ON b.id = bp.bankFk
+ CONCAT('El seguro de la poliza ',a.id,' ',a.bank,' ha finalizado.') subject,
+ CONCAT('El seguro de la poliza ',a.id,' ',a.bank,' ha finalizado.') body
+ FROM bankPolicy bp
+ LEFT JOIN supplier s ON s.id = bp.supplierFk
+ LEFT JOIN accounting a ON a.id = bp.accountingFk
WHERE bp.insuranceExpired = util.VN_CURDATE();
END ;;
DELIMITER ;
@@ -49072,13 +47428,16 @@ BEGIN
SELECT itemFk, buyFk, warehouseFk, landed landing
FROM tmp.buyUltimateFromInterval
WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
- AND landed <= vDated;
+ AND landed <= vDated
+ AND NOT isIgnored;
INSERT IGNORE INTO tmp.buyUltimate
SELECT itemFk, buyFk, warehouseFk, landed landing
FROM tmp.buyUltimateFromInterval
WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
- AND landed > vDated;
+ AND landed > vDated
+ ORDER BY isIgnored = FALSE DESC;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -49122,28 +47481,31 @@ BEGIN
SELECT itemFk,
warehouseFk,
buyFk,
- MAX(landed) landed
+ MAX(landed) landed,
+ isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
- t.landed
+ t.landed,
+ b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.price2 > 0
- AND b.quantity > 0
ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed)
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT
b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
- t.landed
+ t.landed,
+ b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
@@ -49153,12 +47515,13 @@ BEGIN
AND NOT b.isIgnored
GROUP BY itemFk, warehouseInFk;
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed)
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT
b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
- t.landed
+ t.landed,
+ b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
@@ -49167,17 +47530,19 @@ BEGIN
AND b.quantity = 0
GROUP BY itemFk, warehouseInFk;
- -- ItemOriginal
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed)
+ -- ItemOriginal
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
- MAX(landed) landed
+ MAX(landed) landed,
+ isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
- itemOriginalFk
+ itemOriginalFk,
+ b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
@@ -49191,12 +47556,13 @@ BEGIN
LIMIT 10000000000000000000) sub
GROUP BY itemOriginalFk, warehouseFk;
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed)
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT
b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
- t.landed
+ t.landed,
+ b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
@@ -49207,12 +47573,13 @@ BEGIN
AND itemOriginalFk
GROUP BY itemOriginalFk, warehouseInFk;
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed)
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT
b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
- t.landed
+ t.landed,
+ b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
@@ -49254,19 +47621,19 @@ BEGIN
DECLARE vIsFeedStock BOOL;
DECLARE vWeight DECIMAL(10,2);
DECLARE vPacking INT;
-
- SELECT b.entryFk,
- b.itemFk,
- i.packingOut,
- ic.merchandise,
+
+ SELECT b.entryFk,
+ b.itemFk,
+ i.packingOut,
+ ic.merchandise,
vc.standardFlowerBox,
b.weight,
- b.packing
- INTO
- vEntryFk,
- vItemFk,
- vPackingOut,
- vIsMerchandise,
+ b.packing
+ INTO
+ vEntryFk,
+ vItemFk,
+ vPackingOut,
+ vIsMerchandise,
vStandardFlowerBox,
vWeight,
vPacking
@@ -49274,7 +47641,7 @@ BEGIN
LEFT JOIN item i ON i.id = b.itemFk
LEFT JOIN itemType it ON it.id = i.typeFk
LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox
+ LEFT JOIN packaging p ON p.id = b.packagingFk AND NOT p.isBox
JOIN volumeConfig vc ON TRUE
WHERE b.id = vSelf;
@@ -49291,7 +47658,7 @@ BEGIN
warehouseFk = vWarehouse,
cm3 = buy_getUnitVolume(vSelf),
cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf));
-
+
IF vWeight AND vPacking THEN
UPDATE itemCost SET
grams = vWeight * 1000 / vPacking
@@ -49312,7 +47679,9 @@ BEGIN
WHERE b.id = vSelf;
END IF;
-
+ CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck
+ SELECT vSelf id;
+ CALL buy_checkItem();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -49348,6 +47717,47 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buy_checkItem` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_checkItem`()
+BEGIN
+/**
+ * Checks if the item has weightByPiece or size null on any buy.
+ *
+ * @param tmp.buysToCheck(id as INT).
+ */
+ DECLARE hasVolumetricAgency INT;
+
+ SELECT a.hasWeightVolumetric INTO hasVolumetricAgency
+ FROM entry e
+ JOIN travel t ON t.id = e.travelFk
+ JOIN agencyMode a ON a.id = t.agencyModeFk
+ JOIN buy b ON b.entryFk = e.id
+ JOIN item i ON i.id = b.itemFk
+ JOIN tmp.buysToCheck bt ON bt.id = b.id
+ WHERE (i.weightByPiece IS NULL OR i.`size` IS NULL)
+ AND a.hasWeightVolumetric
+ LIMIT 1;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.buysToCheck;
+
+ IF hasVolumetricAgency THEN
+ CALL util.throw('Some purchase line has an item without size or weight per stem in the volumetric agency.');
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_getSplit` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -49359,10 +47769,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getSplit`(vSelf INT, vDated DATE)
BEGIN
/**
- * Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de
- * las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen
+ * Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de
+ * las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen
* habilitada la venta de productos con stock virtual, aunque los productos pueden ser de cualquier tipo.
- *
+ *
* @param vSelf Identificador de vn.buy
* @param vDated Fecha de preparación de las ventas que queremos etiquetar
*/
@@ -49437,7 +47847,7 @@ BEGIN
WHILE vLabels >= vCounter DO
INSERT INTO tmp.split
SET
- id = vSaleFk,
+ id = vSaleFk,
labels = vLabels,
counter = vCounter;
@@ -49459,11 +47869,11 @@ BEGIN
-- Devuelve los splits creados
SELECT CONCAT(sp.counter,'/',sp.labels) labels,
COALESCE(sfc.nickname, sfa.nickname, a.nickname) destination,
- s.itemFk,
- i.longName,
- i.`size`,
- vn.ticketSplitCounter(t.id) counter,
- IF(sfa.id OR sfc.id,
+ s.itemFk,
+ i.longName,
+ i.`size`,
+ vn.ticketSplitCounter(t.id) counter,
+ IF(sfa.id OR sfc.id,
a.nickname,
CONCAT(a.id, ' ', p.`name`,' (', c.`code`,')')) destination2
FROM tmp.split sp
@@ -49488,14 +47898,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_getVolume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolume`()
BEGIN
@@ -49505,15 +47915,15 @@ BEGIN
*/
SELECT t.name Temp,
CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
- item_getVolume(b.itemFk, b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros ,
+ item_getVolume(b.itemFk, b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros ,
CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
- item_getVolume(b.itemFk, b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais
- FROM buy b
+ item_getVolume(b.itemFk, b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais
+ FROM buy b
JOIN tmp.buy tb ON tb.buyFk = b.id
JOIN volumeConfig vc
JOIN item i ON i.id = b.itemFk
JOIN itemType it ON it.id = i.typeFk
- LEFT JOIN temperature t ON t.code = it.temperatureFk
+ LEFT JOIN temperature t ON t.code = it.temperatureFk
GROUP BY Temp;
END ;;
DELIMITER ;
@@ -49533,21 +47943,21 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT)
BEGIN
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.buy;
CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
- INSERT INTO tmp.buy
+ INSERT INTO tmp.buy
SELECT b.id
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
WHERE t.landed = vDated
AND t.agencyModeFk IN (0, vAgencyFk);
CALL buy_getVolume();
DROP TEMPORARY TABLE tmp.buy;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -49566,19 +47976,19 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByEntry`(vEntryFk INT)
BEGIN
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.buy;
CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
-
- INSERT INTO tmp.buy
+
+ INSERT INTO tmp.buy
SELECT b.id
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
WHERE e.id = vEntryFk;
CALL buy_getVolume();
DROP TEMPORARY TABLE tmp.buy;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -49605,8 +48015,8 @@ BEGIN
DECLARE vLanded DATE;
DECLARE vWarehouseFk INT;
DECLARE vHasNotPrice BOOL;
- DECLARE vBuyingValue DECIMAL(10,3);
- DECLARE vPackageFk VARCHAR(10);
+ DECLARE vBuyingValue DECIMAL(10,4);
+ DECLARE vPackagingFk VARCHAR(10);
DECLARE vIsWarehouseFloramondo BOOL;
SELECT t.landed, t.warehouseInFk, (w.`name` = 'Floramondo')
@@ -49622,7 +48032,7 @@ BEGIN
UPDATE buy b
JOIN tmp.buyRecalc br ON br.id = b.id AND (@buyId := b.id)
- LEFT JOIN packaging p ON p.id = b.packageFk
+ LEFT JOIN packaging p ON p.id = b.packagingFk
JOIN item i ON i.id = b.itemFk
JOIN entry e ON e.id = b.entryFk
JOIN itemType it ON it.id = i.typeFk
@@ -49630,7 +48040,7 @@ BEGIN
JOIN agencyMode am ON am.id = tr.agencyModeFk
JOIN tmp.rate r
JOIN volumeConfig vc
- SET b.freightValue = @PF:= IFNULL(((am.m3 * @m3:= item_getVolume(b.itemFk, b.packageFk) / 1000000)
+ SET b.freightValue = @PF:= IFNULL(((am.m3 * @m3:= item_getVolume(b.itemFk, b.packagingFk) / 1000000)
/ b.packing) * IF(am.hasWeightVolumetric, GREATEST(b.weight / @m3 / vc.aerealVolumetricDensity, 1), 1), 0),
b.comissionValue = @CF:= ROUND(IFNULL(e.commission * b.buyingValue / 100, 0), 3),
b.packageValue = @EF:= IF(vIsWarehouseFloramondo, 0, IFNULL(ROUND(IF(p.isPackageReturnable, p.returnCost / b.packing , p.`value` / b.packing), 3),0)),
@@ -49638,8 +48048,8 @@ BEGIN
b.price2 = @t2:= round(@t3 * (1 + ((r.rate2 - r.rate3)/100)),2),
b.price2 = @t2:= IF(@t2 <= @t3,@t3 , @t2);
- SELECT (b.buyingValue = b.price2), b.buyingValue, b.packageFk
- INTO vHasNotPrice, vBuyingValue, vPackageFk
+ SELECT (b.buyingValue = b.price2), b.buyingValue, b.packagingFk
+ INTO vHasNotPrice, vBuyingValue, vPackagingFk
FROM vn.buy b
WHERE b.id = @buyId AND b.buyingValue <> 0.01;
@@ -49666,16 +48076,15 @@ BEGIN
* inserta en tmp.buyRecalc las compras de un awb
*
* @param awbFk
- */
+ */
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
SELECT b.id
- FROM buy b
+ FROM buy b
JOIN entry e ON e.id = b.entryFk
- JOIN duaEntry de ON de.entryFk = e.id
- JOIN dua d ON d.id = de.duaFk
- JOIN awb a ON a.id = d.awbFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN awb a ON a.id = t.awbFk
WHERE a.code = awbFk;
CALL buy_recalcPrices();
@@ -49703,7 +48112,7 @@ BEGIN
* Recalcula los precios de una compra
*
* @param vBuyFk
- */
+ */
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
@@ -49734,12 +48143,12 @@ BEGIN
* Recalcula los precios de una entrada
*
* @param vEntryFk
- */
+ */
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
SELECT b.id
- FROM buy b
+ FROM buy b
WHERE b.entryFk = vEntryFk;
CALL buy_recalcPrices();
@@ -49779,12 +48188,12 @@ BEGIN
LIMIT 0;
INSERT INTO tBuy(buyFk)
- SELECT b.id
+ SELECT b.id
FROM buy b
JOIN tmp.ekt t ON t.ektFk = b.ektFk
JOIN vn.entry en ON en.id = b.entryFk
JOIN vn.travel tr ON tr.id = en.travelFk
- JOIN vn.warehouse w ON w.id = tr.warehouseInFk
+ JOIN vn.warehouse w ON w.id = tr.warehouseInFk
JOIN vn.country c ON c.id = w.countryFk AND c.code = 'NL';
SELECT b.id buy, i.doPhoto do_photo, b.stickers - CAST(b.printedStickers AS INT) stickersToPrint
@@ -49850,7 +48259,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updatePacking`(vWarehouseFk INT, vItemFk INT, vPacking INT)
BEGIN
/**
- * Actualiza packing
+ * Actualiza packing
*
* @param vWarehouseFk warehouse del item
* @param vItemFk id del item
@@ -49860,8 +48269,8 @@ BEGIN
UPDATE buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
- SET b.packing = vPacking
- WHERE bu.warehouseFk = vWarehouseFk
+ SET b.packing = vPacking
+ WHERE bu.warehouseFk = vWarehouseFk
AND bu.itemFk = vItemFk;
DROP TEMPORARY TABLE tmp.buyUltimate;
@@ -49900,7 +48309,7 @@ BEGIN
*/
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
- ENGINE = MEMORY
+ ENGINE = MEMORY
SELECT vItemFk itemFk;
CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);
@@ -49922,7 +48331,7 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT)
-BEGIN
+BEGIN
/**
* Calcula los articulos disponibles y sus precios
*
@@ -49930,7 +48339,7 @@ BEGIN
* @param vLanded Fecha de recepcion de mercancia
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
- * @return tmp.ticketCalculateItem(itemFk, available, producer,
+ * @return tmp.ticketCalculateItem(itemFk, available, producer,
* item, size, stems, category, inkFk, image, origin, price)
* @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk)
* @return tmp.ticketComponent
@@ -49965,22 +48374,22 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
CREATE TEMPORARY TABLE tmp.ticketCalculateItem(
- itemFk INT(11) NOT NULL,
+ itemFk INT(11) NOT NULL,
available INT(11),
- producer VARCHAR(50),
- item VARCHAR(50),
- size INT(10) UNSIGNED,
- stems INT(11),
- category VARCHAR(3),
- inkFk VARCHAR(3),
+ producer VARCHAR(50),
+ item VARCHAR(50),
+ size INT(10) UNSIGNED,
+ stems INT(11),
+ category VARCHAR(3),
+ inkFk VARCHAR(3),
image VARCHAR(50),
- origin VARCHAR(3),
+ origin VARCHAR(3),
price DECIMAL(10,2),
priceKg DECIMAL(10,2),
`grouping` INT(10) UNSIGNED,
PRIMARY KEY `itemFk` (`itemFk`)
) ENGINE = MEMORY DEFAULT CHARSET=utf8;
-
+
OPEN cTravelTree;
l: LOOP
@@ -50002,20 +48411,20 @@ BEGIN
bu.buyFk,
vZoneFk
FROM `cache`.available a
- LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id
+ LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id
AND anr.calc_id = vAvailableNoRaidsCalc
JOIN tmp.item i ON i.itemFk = a.item_id
JOIN vn.item it ON it.id = i.itemFk
JOIN vn.`zone` z ON z.id = vZoneFk
- LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id
- LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk
- LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
+ LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id
+ LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk
+ LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed
FROM vn.addressFilter af
- JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed
- FROM vn.address ad
- JOIN vn.province p ON p.id = ad.provinceFk
+ JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed
+ FROM vn.address ad
+ JOIN vn.province p ON p.id = ad.provinceFk
WHERE ad.id = vAddressFk
) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk)
AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk)
@@ -50032,13 +48441,13 @@ BEGIN
JOIN vn.itemType itt ON itt.id = it.typeFk
JOIN vn.itemCategory itc on itc.id = itt.categoryFk
JOIN vn.address ad ON ad.id = vAddressFk
- LEFT JOIN vn.clientItemType cit
+ LEFT JOIN vn.clientItemType cit
ON cit.clientFk = ad.clientFk
AND cit.itemTypeFk = itt.id
- LEFT JOIN vn.zoneItemType zit
+ LEFT JOIN vn.zoneItemType zit
ON zit.zoneFk = vZoneFk
AND zit.itemTypeFk = itt.id
- LEFT JOIN vn.agencyModeItemType ait
+ LEFT JOIN vn.agencyModeItemType ait
ON ait.agencyModeFk = vAgencyModeFk
AND ait.itemTypeFk = itt.id
WHERE a.calc_id = vAvailableCalc
@@ -50131,7 +48540,7 @@ BEGIN
* Calcula los componentes de los articulos de tmp.ticketLot
*
* @param vZoneFk para calcular el transporte
- * @param vAddressFk Consignatario
+ * @param vAddressFk Consignatario
* @param vShipped dia de salida del pedido
* @param vWarehouseFk warehouse de salida del pedido
* @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk)
@@ -50145,7 +48554,7 @@ BEGIN
SELECT clientFk INTO vClientFK
FROM address
WHERE id = vAddressFk;
-
+
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate
(PRIMARY KEY (itemFk, warehouseFk))
ENGINE = MEMORY
@@ -50157,7 +48566,7 @@ BEGIN
IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing,
IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
ABS(IFNULL(pf.box, b.groupingMode)) groupingMode,
- tl.buyFk,
+ tl.buyFk,
i.typeFk,
IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping
FROM tmp.ticketLot tl
@@ -50165,7 +48574,7 @@ BEGIN
JOIN item i ON i.id = tl.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN specialPrice sp ON sp.itemFk = i.id
+ LEFT JOIN specialPrice sp ON sp.itemFk = i.id
AND sp.clientFk = vClientFk
LEFT JOIN (
SELECT * FROM (
@@ -50184,7 +48593,7 @@ BEGIN
LIMIT 10000000000000000000
) tpf
GROUP BY tpf.itemFk, tpf.warehouseFk
- ) pf ON pf.itemFk = tl.itemFk
+ ) pf ON pf.itemFk = tl.itemFk
AND pf.warehouseFk = tl.warehouseFk
WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01
AND ic.merchandise
@@ -50216,10 +48625,10 @@ BEGIN
FROM tmp.ticketComponent tc
JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk
GROUP BY tc.itemFk, warehouseFk;
-
+
-- RECOBRO
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
- SELECT tcb.warehouseFk, tcb.itemFk, c2.id,
+ SELECT tcb.warehouseFk, tcb.itemFk, c2.id,
ROUND(tcb.base *
LEAST(
MAX(GREATEST(IFNULL(cr.priceIncreasing,0),
@@ -50247,32 +48656,32 @@ BEGIN
SELECT tcb.warehouseFk,
tcb.itemFk,
c2.id,
- ROUND(base * (0.01 + wm.pricesModifierRate), 3) manaAuto
+ ROUND(base * wm.pricesModifierRate, 3) manaAuto
FROM tmp.ticketComponentBase tcb
JOIN `client` c on c.id = vClientFk
- JOIN workerMana wm ON c.salesPersonFk = wm.workerFk
+ JOIN workerMana wm ON c.salesPersonFk = wm.workerFk
JOIN vn.component c2 ON c2.code = 'autoMana'
WHERE wm.isPricesModifierActivated
HAVING manaAuto <> 0;
-
+
-- Precios especiales
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk,
tcb.itemFk,
c2.id,
GREATEST(
- IFNULL(ROUND(tcb.base * c2.tax, 4), 0),
+ IFNULL(ROUND(tcb.base * c2.tax, 4), 0),
IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3
) cost
FROM tmp.ticketComponentBase tcb
JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount'
- JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk
+ JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk
LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
JOIN vn.item i ON i.id = tcb.itemFk
WHERE sp.value IS NULL
AND i.supplyResponseFk IS NULL;
- -- Individual
+ -- Individual
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk,
tcb.itemFk,
@@ -50283,10 +48692,10 @@ BEGIN
JOIN vn.client c ON c.id = vClientFk
JOIN vn.businessType bt ON bt.code = c.businessTypeFk
WHERE bt.code = 'individual';
-
+
-- Venta por paquetes
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
- SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3
+ SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3
FROM tmp.ticketComponentCalculate tcc
JOIN vn.component c2 ON c2.code = 'salePerPackage'
JOIN buy b ON b.id = tcc.buyFk
@@ -50298,7 +48707,7 @@ BEGIN
SELECT vZoneFk id;
CALL zone_getOptionsForShipment(vShipped, TRUE);
-
+
-- Reparto
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFK,
@@ -50312,7 +48721,7 @@ BEGIN
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN vn.volumeConfig vc
JOIN vn.component c2 ON c2.code = 'delivery'
- LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk
+ LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk
AND ic.itemFk = tcc.itemFk
HAVING cost <> 0;
@@ -50365,9 +48774,9 @@ BEGIN
CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price,
CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg
FROM tmp.ticketComponentCalculate tcc
- JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
+ JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
AND tcs.warehouseFk = tcc.warehouseFk
- WHERE IFNULL(tcs.classRate, 1) = 1
+ WHERE IFNULL(tcs.classRate, 1) = 1
AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0)
GROUP BY tcs.warehouseFk, tcs.itemFk;
@@ -50404,7 +48813,7 @@ BEGIN
SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000
) t
GROUP BY itemFk, warehouseFk, `grouping`;
-
+
DROP TEMPORARY TABLE
tmp.ticketComponentCalculate,
tmp.ticketComponentSum,
@@ -50429,7 +48838,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPrepare`()
BEGIN
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
CREATE TEMPORARY TABLE tmp.ticketComponent (
`warehouseFk` INT UNSIGNED NOT NULL,
@@ -50439,9 +48848,9 @@ BEGIN
INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)
)ENGINE=MEMORY DEFAULT CHARSET=utf8;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice;
- CREATE TEMPORARY TABLE tmp.ticketComponentPrice (
+ CREATE TEMPORARY TABLE tmp.ticketComponentPrice (
`warehouseFk` INT UNSIGNED NOT NULL,
`itemFk` INT NOT NULL,
`rate` INT NOT NULL,
@@ -50450,7 +48859,7 @@ BEGIN
`priceKg` DECIMAL(10,4),
INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC)
- )ENGINE=MEMORY DEFAULT CHARSET=utf8;
+ )ENGINE=MEMORY DEFAULT CHARSET=utf8;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -50469,7 +48878,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPurge`()
BEGIN
- DROP TEMPORARY TABLE
+ DROP TEMPORARY TABLE
tmp.ticketComponentPrice,
tmp.ticketComponent,
tmp.ticketLot;
@@ -50491,180 +48900,226 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
- DECLARE vDateShort DATETIME;
- DECLARE vOneYearAgo DATE;
- DECLARE vFourYearsAgo DATE;
- DECLARE vFiveYearsAgo DATE;
- DECLARE v18Month DATE;
- DECLARE v26Month DATE;
- DECLARE v3Month DATE;
+/**
+ * Purges outdated data to optimize performance.
+ * Exercise caution when executing.
+ */
+ DECLARE v2Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 MONTH;
+ DECLARE v3Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 3 MONTH;
+ DECLARE v18Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 18 MONTH;
+ DECLARE v26Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 26 MONTH;
+ DECLARE v1Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 1 YEAR;
+ DECLARE v2Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR;
+ DECLARE v4Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 4 YEAR;
+ DECLARE v5Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 5 YEAR;
DECLARE vTrashId VARCHAR(15);
- DECLARE v5Years DATE;
+ DECLARE vCompanyBlk INT;
- SET vDateShort = util.VN_CURDATE() - INTERVAL 2 MONTH;
- SET vOneYearAgo = util.VN_CURDATE() - INTERVAL 1 YEAR;
- SET vFourYearsAgo = util.VN_CURDATE() - INTERVAL 4 YEAR;
- SET vFiveYearsAgo = util.VN_CURDATE() - INTERVAL 5 YEAR;
- SET v18Month = util.VN_CURDATE() - INTERVAL 18 MONTH;
- SET v26Month = util.VN_CURDATE() - INTERVAL 26 MONTH;
- SET v3Month = util.VN_CURDATE() - INTERVAL 3 MONTH;
- SET v5Years = util.VN_CURDATE() - INTERVAL 5 YEAR;
-
- DELETE FROM ticketParking WHERE created < vDateShort;
- DELETE FROM routesMonitor WHERE dated < vDateShort;
- DELETE FROM workerTimeControlLog WHERE created < vDateShort;
- DELETE FROM `message` WHERE sendDate < vDateShort;
- DELETE FROM messageInbox WHERE sendDate < vDateShort;
- DELETE FROM messageInbox WHERE sendDate < vDateShort;
- DELETE FROM workerTimeControl WHERE timed < vFourYearsAgo;
+ DELETE FROM workerActivity WHERE created < v2Years;
+ DELETE FROM ticketParking WHERE created < v2Months;
+ DELETE FROM routesMonitor WHERE dated < v2Months;
+ DELETE FROM workerTimeControlLog WHERE created < v2Months;
+ DELETE FROM `message` WHERE sendDate < v2Months;
+ DELETE FROM messageInbox WHERE sendDate < v2Months;
+ DELETE FROM messageInbox WHERE sendDate < v2Months;
+ DELETE FROM workerTimeControl WHERE timed < v4Years;
DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0;
- DELETE FROM ticketDown WHERE created < TIMESTAMPADD(DAY,-1,util.VN_CURDATE());
- DELETE FROM entryLog WHERE creationDate < vDateShort;
- DELETE IGNORE FROM expedition WHERE created < v26Month;
- DELETE FROM sms WHERE created < v18Month;
- DELETE FROM saleTracking WHERE created < vOneYearAgo;
- DELETE FROM ticketTracking WHERE created < v18Month;
- DELETE tobs FROM ticketObservation tobs
- JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
- DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo;
- DELETE FROM sharingCart where ended < vDateShort;
- DELETE FROM sharingClient where ended < vDateShort;
+ DELETE FROM ticketDown WHERE created < util.yesterday();
+ DELETE FROM entryLog WHERE creationDate < v2Months;
+ DELETE IGNORE FROM expedition WHERE created < v26Months;
+ DELETE FROM sms WHERE created < v18Months;
+ DELETE FROM saleTracking WHERE created < v1Years;
+ DELETE FROM ticketTracking WHERE created < v18Months;
+ DELETE tobs FROM ticketObservation tobs
+ JOIN ticket t ON tobs.ticketFk = t.id
+ WHERE t.shipped < v5Years;
+ DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < v1Years;
+ DELETE FROM sharingCart where ended < v2Months;
+ DELETE FROM sharingClient where ended < v2Months;
DELETE tw.* FROM ticketWeekly tw
- LEFT JOIN sale s ON s.ticketFk = tw.ticketFk WHERE s.itemFk IS NULL;
- DELETE FROM claim WHERE ticketCreated < vFourYearsAgo;
- DELETE FROM message WHERE sendDate < vDateShort;
- -- Robert ubicacion anterior de trevelLog comentario para debug
- DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Month;
+ LEFT JOIN sale s ON s.ticketFk = tw.ticketFk
+ LEFT JOIN ticketRequest tr ON tr.ticketFk = tw.ticketFk
+ LEFT JOIN ticketService ts ON ts.ticketFk = tw.ticketFk
+ WHERE s.id IS NULL
+ AND tr.id IS NULL
+ AND ts.id IS NULL;
+ DELETE FROM claim WHERE ticketCreated < v4Years;
+ -- Robert ubicacion anterior de travelLog comentario para debug
+ DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Months;
DELETE bm
FROM buyMark bm
JOIN buy b ON b.id = bm.id
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
- WHERE t.landed <= vDateShort;
- DELETE b FROM vn.buy b
- JOIN vn.entryConfig e ON e.defaultEntry = b.entryFk
- WHERE b.created < vDateShort;
- DELETE FROM vn.itemShelvingLog WHERE created < vDateShort;
- DELETE FROM vn.stockBuyed WHERE creationDate < vDateShort;
- DELETE FROM vn.itemCleanLog WHERE created < util.VN_NOW() - INTERVAL 1 YEAR;
- DELETE FROM printQueue WHERE statusCode = 'printed' AND created < vDateShort;
- DELETE FROM ticketLog WHERE creationDate <= vFiveYearsAgo;
+ WHERE t.landed <= v2Months;
+ DELETE b FROM buy b
+ JOIN entryConfig e ON e.defaultEntry = b.entryFk
+ WHERE b.created < v2Months;
+ DELETE FROM itemShelvingLog WHERE created < v2Months;
+ DELETE FROM stockBuyed WHERE creationDate < v2Months;
+ DELETE FROM itemCleanLog WHERE created < util.VN_NOW() - INTERVAL 1 YEAR;
+ DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months;
+ DELETE FROM ticketLog WHERE creationDate <= v5Years;
-- Equipos duplicados
DELETE w.*
FROM workerTeam w
- JOIN (SELECT id, team, workerFk, COUNT(*) - 1 as duplicated
+ JOIN (
+ SELECT id, team, workerFk, COUNT(*) - 1 duplicated
FROM workerTeam
GROUP BY team,workerFk
HAVING duplicated
- ) d ON d.team = w.team AND d.workerFk = w.workerFk AND d.id != w.id;
+ ) d ON d.team = w.team
+ AND d.workerFk = w.workerFk
+ AND d.id <> w.id;
DELETE sc
FROM saleComponent sc
JOIN sale s ON s.id= sc.saleFk
JOIN ticket t ON t.id= s.ticketFk
- WHERE t.shipped < v18Month;
+ WHERE t.shipped < v18Months;
DELETE c
- FROM vn.claim c
- JOIN vn.claimState cs ON cs.id = c.claimStateFk
- WHERE cs.description = "Anulado" AND
- c.created < vDateShort;
- DELETE
- FROM vn.expeditionTruck
- WHERE eta < v3Month;
+ FROM claim c
+ JOIN claimState cs ON cs.id = c.claimStateFk
+ WHERE cs.description = 'Anulado'
+ AND c.created < v2Months;
- -- borrar travels sin entradas
- DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete;
- CREATE TEMPORARY TABLE tmp.thermographToDelete
+ DELETE FROM expeditionTruck WHERE eta < v3Months;
+ DELETE FROM XDiario WHERE FECHA < v3Months OR FECHA IS NULL;
+
+ -- Borrar travels sin entradas
+ CREATE OR REPLACE TEMPORARY TABLE tThermographToDelete
SELECT th.id,th.dmsFk
- FROM vn.travel t
- LEFT JOIN vn.entry e ON e.travelFk = t.id
- JOIN vn.travelThermograph th ON th.travelFk = t.id
- WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL;
+ FROM travel t
+ LEFT JOIN entry e ON e.travelFk = t.id
+ JOIN travelThermograph th ON th.travelFk = t.id
+ WHERE t.shipped < v3Months
+ AND e.travelFk IS NULL;
SELECT dt.id INTO vTrashId
- FROM vn.dmsType dt
+ FROM dmsType dt
WHERE dt.code = 'trash';
- UPDATE tmp.thermographToDelete th
- JOIN vn.dms d ON d.id = th.dmsFk
+ UPDATE tThermographToDelete th
+ JOIN dms d ON d.id = th.dmsFk
SET d.dmsTypeFk = vTrashId;
DELETE th
- FROM tmp.thermographToDelete tmp
- JOIN vn.travelThermograph th ON th.id = tmp.id;
+ FROM tThermographToDelete tmp
+ JOIN travelThermograph th ON th.id = tmp.id;
DELETE t
- FROM vn.travel t
- LEFT JOIN vn.entry e ON e.travelFk = t.id
- WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL;
-
+ FROM travel t
+ LEFT JOIN entry e ON e.travelFk = t.id
+ WHERE t.shipped < v3Months AND e.travelFk IS NULL;
+
UPDATE dms d
- JOIN dmsType dt ON dt.id = d.dmsTypeFk
- SET d.dmsTypeFk = vTrashId
- WHERE created < TIMESTAMPADD(MONTH, -dt.monthToDelete, util.VN_CURDATE());
-
+ JOIN dmsType dt ON dt.id = d.dmsTypeFk
+ SET d.dmsTypeFk = vTrashId
+ WHERE created < util.VN_CURDATE() - INTERVAL dt.monthToDelete MONTH;
+
-- borrar entradas sin compras
- DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete;
- CREATE TEMPORARY TABLE tmp.entryToDelete
+ CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete
SELECT e.*
- FROM vn.entry e
- LEFT JOIN vn.buy b ON b.entryFk = e.id
- JOIN vn.entryConfig ec ON e.id != ec.defaultEntry
- WHERE e.dated < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND b.entryFK IS NULL;
+ FROM entry e
+ LEFT JOIN buy b ON b.entryFk = e.id
+ JOIN entryConfig ec ON e.id <> ec.defaultEntry
+ WHERE e.dated < v3Months
+ AND b.entryFK IS NULL;
DELETE e
- FROM vn.entry e
- JOIN tmp.entryToDelete tmp ON tmp.id = e.id;
+ FROM entry e
+ JOIN tEntryToDelete tmp ON tmp.id = e.id;
-- borrar de route registros menores a 4 años
- DROP TEMPORARY TABLE IF EXISTS tmp.routeToDelete;
- CREATE TEMPORARY TABLE tmp.routeToDelete
+ CREATE OR REPLACE TEMPORARY TABLE tRouteToDelete
SELECT *
- FROM vn.route r
- WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE());
+ FROM route r
+ WHERE created < v4Years;
- UPDATE tmp.routeToDelete tmp
- JOIN vn.dms d ON d.id = tmp.gestdocFk
+ UPDATE tRouteToDelete tmp
+ JOIN dms d ON d.id = tmp.gestdocFk
SET d.dmsTypeFk = vTrashId;
DELETE r
- FROM tmp.routeToDelete tmp
- JOIN vn.route r ON r.id = tmp.id;
+ FROM tRouteToDelete tmp
+ JOIN route r ON r.id = tmp.id;
-- borrar registros de dua y awb menores a 2 años
- DROP TEMPORARY TABLE IF EXISTS tmp.duaToDelete;
- CREATE TEMPORARY TABLE tmp.duaToDelete
+ CREATE OR REPLACE TEMPORARY TABLE tDuaToDelete
SELECT *
- FROM vn.dua
- WHERE operated < TIMESTAMPADD(YEAR,-2,CURDATE());
+ FROM dua
+ WHERE operated < v2Years;
- UPDATE tmp.duaToDelete tm
- JOIN vn.dms d ON d.id = tm.gestdocFk
+ UPDATE tDuaToDelete tm
+ JOIN dms d ON d.id = tm.gestdocFk
SET d.dmsTypeFk = vTrashId;
DELETE d
- FROM tmp.duaToDelete tmp
- JOIN vn.dua d ON d.id = tmp.id;
+ FROM tDuaToDelete tmp
+ JOIN dua d ON d.id = tmp.id;
- DELETE FROM vn.awb WHERE created < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
+ DELETE a
+ FROM awb a
+ LEFT JOIN travel t ON t.awbFk = a.id
+ WHERE a.created < v2Years
+ AND t.id IS NULL;
-- Borra los registros de collection y ticketcollection
- DELETE FROM vn.collection WHERE created < vDateShort;
+ DELETE FROM collection WHERE created < v2Months;
+ DELETE FROM travelLog WHERE creationDate < v3Months;
- DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete;
- DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete;
- DROP TEMPORARY TABLE IF EXISTS tmp.duaToDelete;
-
- DELETE FROM travelLog WHERE creationDate < v3Month;
-
- CALL shelving_clean;
+ CALL shelving_clean();
DELETE FROM chat WHERE dated < v5Years;
+ DELETE tt FROM ticketTracking tt
+ JOIN ticket t ON tt.ticketFk = t.id
+ WHERE t.shipped <= v2Months;
- DELETE tt FROM ticketTracking tt JOIN vn.ticket t ON tt.ticketFk = t.id
- WHERE t.shipped <= vDateShort;
+ DELETE FROM mail WHERE creationDate < v2Months;
+ DELETE FROM split WHERE dated < v18Months;
+ DELETE FROM remittance WHERE dated < v18Months;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTicketDelete
+ SELECT DISTINCT tl.originFk ticketFk
+ FROM ticketLog tl
+ JOIN (
+ SELECT MAX(tl.id)ids
+ FROM ticket t
+ JOIN ticketLog tl ON tl.originFk = t.id
+ LEFT JOIN ticketWeekly tw ON tw.ticketFk = t.id
+ WHERE t.shipped BETWEEN '2000-01-01' AND '2000-12-31'
+ AND t.isDeleted
+ AND tw.ticketFk IS NULL
+ GROUP BY t.id
+ ) sub ON sub.ids = tl.id
+ WHERE tl.creationDate <= v2Months;
+ DELETE t
+ FROM ticket t
+ JOIN tTicketDelete tmp ON tmp.ticketFk = t.id;
+ DELETE sl
+ FROM saleLabel sl
+ JOIN sale s ON s.id = sl.saleFk
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE t.shipped < v2Months;
+
+ -- Tickets Nulos PAK 11/10/2016
+ SELECT id INTO vCompanyBlk FROM company WHERE code = 'BLK';
+ UPDATE ticket
+ SET companyFk = vCompanyBlk
+ WHERE clientFk = (SELECT id FROM client WHERE name = 'AUTOCONSUMO')
+ AND companyFk <> vCompanyBlk;
+
+ DROP TEMPORARY TABLE tTicketDelete,
+ tThermographToDelete,
+ tEntryToDelete,
+ tDuaToDelete,
+ tRouteToDelete;
+
+ -- Other schemas
+ DELETE FROM hedera.`order` WHERE date_send < v18Months;
+ DELETE FROM pbx.cdr WHERE call_date < v18Months;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -50805,21 +49260,21 @@ BEGIN
*/
DECLARE vClientDebt DOUBLE;
-
+
SELECT vn.client_getDebt(vClientFk, util.VN_CURDATE()) INTO vClientDebt;
-
+
INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
VALUES (vClientFk, 'Saldo pendiente', vClientDebt, util.VN_CURDATE(), 5);
-
+
CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE);
-
+
INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
SELECT vClientFk, 'Liquidación cliente', sum(amount), util.VN_CURDATE(), 5
FROM vn.greuge
WHERE clientFk = vClientFk;
-
- UPDATE vn.client
- SET salesPersonFk = NULL
+
+ UPDATE vn.client
+ SET salesPersonFk = NULL
WHERE id = vClientFk;
END ;;
@@ -50856,6 +49311,7 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
CREATE TEMPORARY TABLE tmp.clientGetDebt
+ (INDEX (clientFk))
SELECT clientFk
FROM bs.defaulter
WHERE created = util.VN_CURDATE()
@@ -50909,33 +49365,33 @@ BEGIN
DECLARE vIssued DATETIME;
DECLARE vBalance DOUBLE DEFAULT 0.00;
DECLARE cur CURSOR FOR
- SELECT
- created,
- issued,
+ SELECT
+ created,
+ issued,
ROUND(amount, 2) AS balance
FROM invoiceOut
- WHERE clientFk = vClientFk AND companyFk = vCompanyFk
- UNION ALL
- SELECT
- created,
- payed,
+ WHERE clientFk = vClientFk AND companyFk = vCompanyFk
+ UNION ALL
+ SELECT
+ created,
+ payed,
ROUND(-1 * amountPaid, 2) AS balance
- FROM receipt
+ FROM receipt
WHERE clientFk = vClientFk AND companyFk = vCompanyFk
ORDER BY issued, created;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
OPEN cur;
-
+
proc: LOOP
SET vDone = FALSE;
-
+
FETCH cur INTO vCreated, vIssued, vBalance;
IF vDate IS NULL THEN
SET vDate=vIssued;
END IF;
-
+
IF vDone THEN
LEAVE proc;
END IF;
@@ -50947,66 +49403,66 @@ BEGIN
SET vDone = TRUE;
END IF;
END LOOP;
-
+
CLOSE cur;
-
- SELECT
- issued,
- CAST(debtOut AS DECIMAL(10,2)) debtOut,
+
+ SELECT
+ issued,
+ CAST(debtOut AS DECIMAL(10,2)) debtOut,
CAST(debtIn AS DECIMAL(10,2)) debtIn,
- ref,
- companyFk,
+ ref,
+ companyFk,
priority
FROM
- (SELECT
- NULL AS issued,
- SUM(amountUnpaid) AS debtOut,
- NULL AS debtIn,
- 'Saldo Anterior' AS ref,
+ (SELECT
+ NULL AS issued,
+ SUM(amountUnpaid) AS debtOut,
+ NULL AS debtIn,
+ 'Saldo Anterior' AS ref,
companyFk,
- 0 as priority
- FROM
- (SELECT SUM(amount) AS amountUnpaid, companyFk, 0
+ 0 as priority
+ FROM
+ (SELECT SUM(amount) AS amountUnpaid, companyFk, 0
FROM invoiceOut
- WHERE clientFk = vClientFK
- AND issued < vDate
- GROUP BY companyFk
-
- UNION ALL
-
- SELECT SUM(-1 * amountPaid), companyFk, 0
- FROM receipt
- WHERE clientFk = vClientFK
- AND payed < vDate
- GROUP BY companyFk) AS transactions
- GROUP BY companyFk
-
- UNION ALL
-
- SELECT
- issued,
- amount as debtOut,
- NULL AS debtIn,
+ WHERE clientFk = vClientFK
+ AND issued < vDate
+ GROUP BY companyFk
+
+ UNION ALL
+
+ SELECT SUM(-1 * amountPaid), companyFk, 0
+ FROM receipt
+ WHERE clientFk = vClientFK
+ AND payed < vDate
+ GROUP BY companyFk) AS transactions
+ GROUP BY companyFk
+
+ UNION ALL
+
+ SELECT
+ issued,
+ amount as debtOut,
+ NULL AS debtIn,
ref,
companyFk,
- 1
- FROM invoiceOut
- WHERE clientFk = vClientFK
+ 1
+ FROM invoiceOut
+ WHERE clientFk = vClientFK
AND issued >= vDate
- UNION ALL
-
- SELECT
- r.payed,
- NULL as debtOut,
- r.amountPaid,
- r.invoiceFk,
+ UNION ALL
+
+ SELECT
+ r.payed,
+ NULL as debtOut,
+ r.amountPaid,
+ r.invoiceFk,
r.companyFk,
- 0
+ 0
FROM receipt r
- WHERE r.clientFk = vClientFK
- AND r.payed >= vDate) t
- INNER JOIN `client` c ON c.id = vClientFK
- HAVING debtOut <> 0 OR debtIn <> 0
+ WHERE r.clientFk = vClientFK
+ AND r.payed >= vDate) t
+ INNER JOIN `client` c ON c.id = vClientFK
+ HAVING debtOut <> 0 OR debtIn <> 0
ORDER BY issued, priority DESC, debtIn;
END ;;
DELIMITER ;
@@ -51064,13 +49520,13 @@ BEGIN
WHERE id = vClientFk;
ELSE
-
+
SELECT id INTO vOwner
FROM vn.worker
WHERE code = vWorkerCode COLLATE utf8_general_ci;
END IF;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.clientList;
CREATE TEMPORARY TABLE tmp.clientList
SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) monthSale
@@ -51082,7 +49538,7 @@ BEGIN
AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())
AND c.id != vClientFk
HAVING monthSale > 100;
-
+
SELECT SUM(monthSale) INTO vTotalSale
FROM tmp.clientList;
@@ -51093,7 +49549,7 @@ BEGIN
SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk;
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -51283,16 +49739,16 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
CREATE TEMPORARY TABLE tmp.clientGetDebt
- SELECT cd.id as clientFk
+ SELECT cd.clientFk
FROM bs.clientDied cd
- LEFT JOIN clientProtected cp ON cp.clientFk = cd.id
- JOIN client c ON c.id = cd.id
+ LEFT JOIN clientProtected cp ON cp.clientFk = cd.clientFk
+ JOIN client c ON c.id = cd.clientFk
JOIN province p ON p.id = c.provinceFk
- LEFT JOIN autonomy a ON a.id = p.autonomyFk
+ LEFT JOIN autonomy a ON a.id = p.autonomyFk
JOIN country co ON co.id = p.countryFk
- WHERE cd.Aviso = 'TERCER AVISO'
+ WHERE cd.warning = 'third'
AND cp.clientFk IS NULL
- AND co.code NOT IN ('PT')
+ AND co.code NOT IN ('PT')
AND a.name <> 'Canarias'
AND c.salesPersonFk IS NOT NULL;
@@ -51398,12 +49854,12 @@ BEGIN
SELECT lc.companyFk,
c.id,
0,
- - (NZ(lc.credit) - NZ(lc.debit))
+ - (IFNULL(lc.credit, 0) - IFNULL(lc.debit, 0))
FROM tmp.ledgerComparative lc
JOIN client c ON c.accountingAccount = lc.account
WHERE lc.`date` BETWEEN vDateFrom AND vDateTo
)sub
- GROUP BY companyFk, clientFk
+ GROUP BY companyFk, clientFk
) sub1 ON sub1.clientFk = c.id
JOIN supplier s ON s.id = sub1.companyFk
JOIN company co ON co.id = sub1.companyFk
@@ -51536,18 +49992,19 @@ BEGIN
* Calculates the risk for active clients
*
* @table tmp.clientGetDebt(clientFk)
- * @param vDate maximum date of records
+ * @param vDate Maximum date of records
* @return tmp.risk
*/
DECLARE vStarted DATETIME;
DECLARE vEnded DATETIME;
- SELECT TIMESTAMPADD(MONTH, -riskScope, util.VN_CURDATE()) INTO vStarted FROM clientConfig;
- SET vEnded = TIMESTAMP(IFNULL(vDate, util.VN_CURDATE()), '23:59:59');
+ SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted
+ FROM clientConfig;
- DROP TEMPORARY TABLE IF EXISTS tClientRisk;
- CREATE TEMPORARY TABLE tClientRisk
+ SET vEnded = util.dayEnd(IFNULL(vDate, util.VN_CURDATE()));
+
+ CREATE OR REPLACE TEMPORARY TABLE tClientRisk
ENGINE = MEMORY
SELECT cr.clientFk, SUM(cr.amount) amount
FROM clientRisk cr
@@ -51570,12 +50027,14 @@ BEGIN
GROUP BY t.clientFk;
INSERT INTO tClientRisk
- SELECT t.clientFk, totalWithVat
+ SELECT t.clientFk, SUM(totalWithVat)
FROM ticket t
JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk
WHERE refFk IS NULL
- AND shipped BETWEEN vStarted AND vEnded;
+ AND shipped BETWEEN vStarted AND vEnded
+ GROUP BY t.clientFk;
+ -- refs #6351 BUG: No cambiar a CREATE OR REPLACE
DROP TEMPORARY TABLE IF EXISTS tmp.risk;
CREATE TEMPORARY TABLE tmp.risk
(PRIMARY KEY (clientFk))
@@ -51594,6 +50053,76 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `client_getMana` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `client_getMana`()
+BEGIN
+/**
+ * Devuelve el mana de los clientes de la tabla tmp.client(id)
+ * @return tmp.clientMana(id, mana)
+ *
+ */
+ DECLARE vFromDated DATE;
+
+ DELETE tc FROM tmp.client tc
+ JOIN client c ON c.id = tc.id
+ WHERE c.typeFk <> 'normal';
+
+ SELECT MAX(dated) INTO vFromDated
+ FROM clientManaCache;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.clientMana
+ SELECT id, SUM(mana) mana
+ FROM
+ (
+ SELECT tc.id, cmc.mana
+ FROM clientManaCache cmc
+ JOIN tmp.client tc ON tc.id = cmc.clientFk
+ WHERE cmc.dated = vFromDated
+ UNION ALL
+ SELECT tc.id, s.quantity * value
+ FROM ticket t
+ JOIN address a ON a.id = t.addressFk
+ JOIN tmp.client tc ON tc.id = a.clientFk
+ JOIN sale s on s.ticketFk = t.id
+ JOIN saleComponent sc on sc.saleFk = s.id
+ JOIN component comp ON sc.componentFk = comp.id
+ JOIN componentType ct ON ct.id = comp.typeFk AND ct.code = 'mana'
+ WHERE t.shipped > vFromDated
+ AND t.shipped < util.tomorrow()
+ UNION ALL
+ SELECT tc.id, -amountPaid
+ FROM receipt r
+ JOIN `client` c ON c.id = r.clientFk
+ JOIN tmp.client tc ON tc.id = c.id
+ JOIN accounting a ON r.bankFk = a.id
+ AND a.code = 'mana'
+ WHERE r.payed > vFromDated
+ AND r.payed <= util.VN_CURDATE()
+ UNION ALL
+ SELECT tc.id, g.amount
+ FROM greuge g
+ JOIN `client` c ON c.id = g.clientFk
+ JOIN tmp.client tc ON tc.id = c.id
+ JOIN greugeType gt ON gt.id = g.greugeTypeFk AND gt.code = 'mana'
+ WHERE g.shipped > vFromDated
+ AND g.shipped <= util.VN_CURDATE()
+ ) sub
+ GROUP BY id;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `client_RandomList` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -51608,9 +50137,9 @@ BEGIN
DECLARE i INT DEFAULT 0;
DECLARE c INT DEFAULT 0;
DECLARE maxClientFk INT;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.client;
-
+
CREATE TEMPORARY TABLE tmp.`client`
(id INT AUTO_INCREMENT,
clientFk INT,
@@ -51618,40 +50147,40 @@ BEGIN
PRIMARY KEY(id),
UNIQUE KEY clientFk (clientFk))
ENGINE = MEMORY;
-
+
INSERT INTO tmp.client(clientFk)
SELECT DISTINCT clientFk
FROM vn.invoiceOut
WHERE issued > TIMESTAMPADD(MONTH, -2, util.VN_CURDATE());
-
+
SELECT max(id) INTO maxClientFk
FROM tmp.client;
-
-
+
+
WHILE i < vNumber DO
-
+
SET i = i + 1;
-
+
WHILE c = 0 DO
-
+
SELECT id INTO c
FROM tmp.client
WHERE id = floor(RAND() * maxClientFk) + 1
AND isSelected = FALSE
LIMIT 1;
-
+
END WHILE;
-
+
-- SELECT i, maxClientFk, c;
-
- UPDATE tmp.client
- SET isSelected = TRUE
+
+ UPDATE tmp.client
+ SET isSelected = TRUE
WHERE id = c;
-
+
SET c = 0;
-
+
END WHILE;
-
+
SELECT c.id, c.name FROM tmp.client tc
JOIN vn.client c ON c.id = tc.clientFk
WHERE isSelected
@@ -51695,13 +50224,13 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tClientList
SELECT c.id clientFk
FROM bs.clientDied cd
- JOIN client c ON c.id = cd.id
+ JOIN client c ON c.id = cd.clientFk
LEFT JOIN clientProtected cp ON cp.clientFk = c.id
LEFT JOIN salesPersonProtected sp ON sp.salesPersonFk = c.salesPersonFk
JOIN province p ON p.id = c.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
JOIN country co ON co.id = p.countryFk
- WHERE cd.Aviso = 'TERCER AVISO'
+ WHERE cd.warning = 'third'
AND cp.clientFk IS NULL
AND sp.salesPersonFk IS NULL
AND a.name <> 'Canarias'
@@ -51780,127 +50309,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `cmr_getByTicket` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `cmr_getByTicket`(vTicketFk INT)
-BEGIN
-
- DECLARE vLanded DATE;
-
- SELECT DATE_ADD(util.VN_CURDATE(), INTERVAL landingDays DAY) INTO vLanded
- FROM vn.cmrConfig;
-
- IF vTicketFk THEN
-
- IF (SELECT count(ticketFk) FROM vn.cmr WHERE ticketFk = vTicketFk) THEN
-
- SELECT id FROM vn.cmr WHERE ticketFk = vTicketFk;
-
- ELSE
-
- INSERT INTO vn.cmr(ticketFk, companyFk, addressFromFk, addressToFk, ead)
- SELECT vTicketFk, t.companyFk, a.id, t.addressFk, vLanded
- FROM vn.ticket t
- JOIN vn.warehouse w ON w.id = t.warehouseFk
- JOIN vn.address a ON a.id = w.addressFk
- WHERE t.id = vTicketFk;
-
- SELECT LAST_INSERT_ID();
-
- END IF;
-
- ELSE
-
- INSERT INTO vn.cmr(ead) VALUES(vLanded);
-
- SELECT LAST_INSERT_ID();
-
- END IF;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `cmr_sendOverview` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `cmr_sendOverview`()
-BEGIN
-/**
- * Insert the monthly CMR summary in vn.mail on the 5th of each month.
- */
-
- SET SESSION group_concat_max_len = 1000000;
--- IF (DAY(util.VN_CURDATE()) = 5) THEN
- INSERT INTO
- vn.mail (receiver,
- replyTo,
- subject,
- body)
- SELECT
- c2.email,
- 'cmr@verdnatura.es',
- 'Resumen CMR',
- CONCAT('
-
Resumen Mensual CMR
-
-
-
- Estimado cliente,
- A continuación le enviamos el resumen menual de CMR ',UPPER(MONTHNAME(util.VN_CURDATE() - INTERVAL 1 MONTH)),' ', YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH), '.
- Le rogamos que nos devuelva el resumen firmado a cmr@verdnatura.es
-
-
-
-
-
CMR
-
Ticket
-
'
- , GROUP_CONCAT('
', c.id, '
', c.ticketFk, '
' ORDER BY c.id SEPARATOR '' ),
- '
-
-
- Saludos cordiales, Dpto administración.
-
')
- FROM vn.cmr c
- JOIN vn.address a ON c.addressToFk = a.id
- JOIN vn.client c2 ON a.clientFk = c2.id
- WHERE c.state = 'Pending'
- AND MONTH(c.created) = MONTH(util.VN_CURDATE() - INTERVAL 1 MONTH)
- AND YEAR(c.created) = YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH)
- AND c2.email IS NOT NULL -- No cogemos los CMRs dirigidos a 'Verdnatura'
- GROUP BY c2.id;
-
- -- Actualizamos el estado a 'Enviado'
- UPDATE vn.cmr c
- SET c.state = 'Sent'
- WHERE c.state = 'Pending'
- AND MONTH(c.created) = MONTH(util.VN_CURDATE() - INTERVAL 1 MONTH)
- AND YEAR(c.created) = YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH);
--- END IF;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collectionPlacement_get` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -51924,9 +50332,7 @@ BEGIN
DECLARE vWarehouseFk INT;
DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW());
- DROP TEMPORARY TABLE IF EXISTS tSale;
-
- CREATE TEMPORARY TABLE tSale
+ CREATE OR REPLACE TEMPORARY TABLE tSale
(INDEX(ticketFk), INDEX(saleFk), INDEX(itemFk))
ENGINE = MEMORY
SELECT s.ticketFk, s.id saleFk, s.itemFk, s.quantity
@@ -51947,8 +50353,7 @@ BEGIN
CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
- DROP TEMPORARY TABLE IF EXISTS tGrouping;
- CREATE TEMPORARY TABLE tGrouping
+ CREATE OR REPLACE TEMPORARY TABLE tGrouping
(INDEX(itemFk))
ENGINE = MEMORY
SELECT b.itemFk,
@@ -51962,8 +50367,7 @@ BEGIN
WHERE lb.warehouse_id = vWarehouseFk
GROUP BY b.itemFk;
- DROP TEMPORARY TABLE IF EXISTS tSalePlacementList;
- CREATE TEMPORARY TABLE tSalePlacementList
+ CREATE OR REPLACE TEMPORARY TABLE tSalePlacementList
(INDEX(saleFk), INDEX(`order`))
ENGINE = MEMORY
SELECT ts.saleFk,
@@ -51984,9 +50388,9 @@ BEGIN
ish.created,
ish.visible,
IFNULL(
- IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`),
+ IF(st.code = 'previousByPacking', ish.packing, g.`grouping`),
1) `grouping`,
- sc.isPreviousPrepared,
+ st.code = 'previousPrepared' isPreviousPrepared,
iss.id itemShelvingSaleFk,
ts.ticketFk,
iss.id,
@@ -52003,6 +50407,7 @@ BEGIN
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
+ JOIN sectorType st ON st.id = sc.typeFk
JOIN warehouse w ON w.id = sc.warehouseFk
LEFT JOIN tGrouping g ON g.itemFk = ts.itemFk
LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk
@@ -52015,8 +50420,7 @@ BEGIN
AND NOT sc.isHideForPickers
HAVING (iss.id AND st.saleFk) OR salePreviousPrepared IS NULL;
- DROP TEMPORARY TABLE IF EXISTS tSalePlacementList2;
- CREATE TEMPORARY TABLE tSalePlacementList2
+ CREATE OR REPLACE TEMPORARY TABLE tSalePlacementList2
(INDEX(saleFk), INDEX(olderPriority))
ENGINE = MEMORY
SELECT saleFk, priority olderPriority
@@ -52102,15 +50506,15 @@ BEGIN
DATE_FORMAT(util.VN_NOW(), '%H:%i' ),
' ',
i.name
- ) INTO vConcept
+ ) INTO vConcept
FROM item i
WHERE i.id = vItemFk;
SELECT name INTO vItemName FROM item WHERE id = vBarccodeFk;
- SELECT CONCAT('Añadido articulo ',
+ SELECT CONCAT('Añadido articulo ',
vItemName,
- ' cantidad:',
+ ' cantidad:',
vQuantity
) INTO vDescription;
@@ -52146,75 +50550,91 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`(vUserFk INT, OUT vCollectionFk INT)
-proc:BEGIN
-/* Comprueba si existen colecciones libres que se ajustan al perfil del usuario
- * y le asigna la más antigua.
- * Añade un registro al semillero de colecciones
- */
- DECLARE vHasTooMuchCollections BOOL;
- DECLARE vLockTime INT DEFAULT 15;
-
- -- Si hay colecciones sin terminar, sale del proceso
- CALL vn.collection_get(vUserFk);
-
- SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0
- INTO vHasTooMuchCollections
- FROM tCollection
- JOIN vn.productionConfig pc ;
-
- DROP TEMPORARY TABLE tCollection;
-
- IF vHasTooMuchCollections THEN
- CALL util.throw('Hay colecciones pendientes');
- LEAVE proc;
- END IF;
-
- IF NOT GET_LOCK('collection_assign',vLockTime) THEN
- LEAVE proc;
- END IF;
-
- -- Se eliminan las colecciones sin asignar que estan obsoletas
- INSERT INTO ticketTracking(stateFk, ticketFk)
- SELECT s.id, tc.ticketFk
- FROM vn.collection c
- JOIN vn.ticketCollection tc ON tc.collectionFk = c.id
- JOIN vn.state s ON s.code = 'PRINTED_AUTO'
- JOIN vn.productionConfig pc
- WHERE c.workerFk IS NULL
- AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
-
- DELETE c.*
- FROM vn.collection c
- JOIN vn.productionConfig pc
- WHERE c.workerFk IS NULL
- AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
-
- -- Se a�ade registro al semillero
- INSERT INTO vn.collectionHotbed(userFk)
- VALUES(vUserFk);
-
- -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion
- SELECT MIN(c.id)
- INTO vCollectionFk
- FROM vn.collection c
- JOIN vn.operator o
- ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL)
- AND o.numberOfWagons = c.wagons
- AND o.trainFk = c.trainFk
- AND o.warehouseFk = c.warehouseFk
- AND c.workerFk IS NULL
- WHERE o.workerFk = vUserFk;
-
- IF vCollectionFk IS NULL THEN
- CALL vn.collection_new(vUserFk, vCollectionFk);
- END IF;
-
- UPDATE vn.collection
- SET workerFk = vUserFk
- WHERE id = vCollectionFk;
-
- DO RELEASE_LOCK('collection_assign');
+CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`(
+ vUserFk INT,
+ OUT vCollectionFk INT
+)
+proc:BEGIN
+/**
+ * Comprueba si existen colecciones libres que se ajustan
+ * al perfil del usuario y le asigna la más antigua.
+ * Añade un registro al semillero de colecciones.
+ *
+ * @param vUserFk Id de usuario
+ * @param vCollectionFk Id de colección
+ */
+ DECLARE vHasTooMuchCollections BOOL;
+ DECLARE vLockTime INT DEFAULT 15;
+
+ -- Si hay colecciones sin terminar, sale del proceso
+ CALL collection_get(vUserFk);
+
+ SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0
+ INTO vHasTooMuchCollections
+ FROM tCollection
+ JOIN productionConfig pc ;
+
+ DROP TEMPORARY TABLE tCollection;
+
+ IF vHasTooMuchCollections THEN
+ CALL util.throw('Hay colecciones pendientes');
+ LEAVE proc;
+ END IF;
+
+ IF NOT GET_LOCK('collection_assign',vLockTime) THEN
+ LEAVE proc;
+ END IF;
+
+ -- Se eliminan las colecciones sin asignar que estan obsoletas
+ INSERT INTO ticketTracking(stateFk, ticketFk)
+ SELECT s.id, tc.ticketFk
+ FROM `collection` c
+ JOIN ticketCollection tc ON tc.collectionFk = c.id
+ JOIN `state` s ON s.code = 'PRINTED_AUTO'
+ JOIN productionConfig pc
+ WHERE c.workerFk IS NULL
+ AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
+
+ DELETE c.*
+ FROM `collection` c
+ JOIN productionConfig pc
+ WHERE c.workerFk IS NULL
+ AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
+
+ -- Se añade registro al semillero
+ INSERT INTO collectionHotbed(userFk)
+ VALUES(vUserFk);
+
+ -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion
+ SELECT MIN(c.id)
+ INTO vCollectionFk
+ FROM `collection` c
+ JOIN operator o
+ ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL)
+ AND o.numberOfWagons = c.wagons
+ AND o.trainFk = c.trainFk
+ AND o.warehouseFk = c.warehouseFk
+ AND c.workerFk IS NULL
+ AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL)
+ JOIN (
+ SELECT tc.collectionFk, SUM(sv.volume) volume
+ FROM ticketCollection tc
+ JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk
+ WHERE sv.shipped >= util.VN_CURDATE()
+ GROUP BY tc.collectionFk
+ ) sub ON sub.collectionFk = c.id
+ AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL)
+ WHERE o.workerFk = vUserFk;
+
+ IF vCollectionFk IS NULL THEN
+ CALL collection_new(vUserFk, vCollectionFk);
+ END IF;
+
+ UPDATE `collection`
+ SET workerFk = vUserFk
+ WHERE id = vCollectionFk;
+
+ DO RELEASE_LOCK('collection_assign');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -52245,18 +50665,18 @@ BEGIN
SELECT c.id collectionFk,
date(c.created) created,
COUNT(DISTINCT tc.ticketFk) ticketTotalCount
- FROM collection c
- JOIN ticketCollection tc ON tc.collectionFk = c.id
- JOIN sale s ON s.ticketFk = tc.ticketFk
+ FROM collection c
+ JOIN ticketCollection tc ON tc.collectionFk = c.id
+ JOIN sale s ON s.ticketFk = tc.ticketFk
JOIN ticketState ts ON ts.ticketFk = tc.ticketFk
JOIN state s2 ON s2.id = ts.stateFk
JOIN productionConfig pc
JOIN vn.state ss on ss.code = 'PREPARED'
LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id
- WHERE c.workerFk = vWorkerFk
+ WHERE c.workerFk = vWorkerFk
AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge
AND s.quantity != 0
- AND s2.order < pc.pendingCollectionsOrder
+ AND s2.order < pc.pendingCollectionsOrder
GROUP BY c.id
HAVING COUNT(*) > COUNT(DISTINCT st.id);
@@ -52283,15 +50703,15 @@ BEGIN
* Selecciona los tickets de una colección/ticket
* @param vParamFk ticketFk/collectionFk
* @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones
- */
+ */
DECLARE vItemPackingTypeFk VARCHAR(1);
-- Si los sacadores son los de pruebas, pinta los colores
SELECT itemPackingTypeFk INTO vItemPackingTypeFk
- FROM vn.collection
+ FROM vn.collection
WHERE id = vParamFk;
- SELECT t.id ticketFk,
+ SELECT t.id ticketFk,
IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`,
am.name agencyName,
t.warehouseFk,
@@ -52301,20 +50721,20 @@ BEGIN
FROM vn.ticket t
LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21
- LEFT JOIN vn.collectionColors cc
- ON cc.wagon = tc.wagon
- AND cc.shelve = tc.`level`
+ LEFT JOIN vn.collectionColors cc
+ ON cc.wagon = tc.wagon
+ AND cc.shelve = tc.`level`
AND cc.trainFk = c2.trainFk -- PAK 23/12/21
- LEFT JOIN vn.zone z ON z.id = t.zoneFk
+ LEFT JOIN vn.zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
- LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
+ LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
AND tob.observationTypeFk = 1
- WHERE t.id = vParamFk
+ WHERE t.id = vParamFk
AND t.shipped >= util.yesterday()
UNION ALL
- SELECT t.id ticketFk,
+ SELECT t.id ticketFk,
IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`,
am.name agencyName,
t.warehouseFk,
@@ -52324,15 +50744,15 @@ BEGIN
FROM vn.ticket t
JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21
- LEFT JOIN vn.collectionColors cc
- ON cc.wagon = tc.wagon
- AND cc.shelve = tc.`level`
+ LEFT JOIN vn.collectionColors cc
+ ON cc.wagon = tc.wagon
+ AND cc.shelve = tc.`level`
AND cc.trainFk = c2.trainFk -- PAK 23/12/21
- LEFT JOIN vn.zone z ON z.id = t.zoneFk
+ LEFT JOIN vn.zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
- LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
+ LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
AND tob.observationTypeFk = 1
WHERE tc.collectionFk = vParamFk;
@@ -52453,14 +50873,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_new` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET collation_connection = utf8mb4_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_new`(vUserFk INT, OUT vCollectionFk INT)
proc:BEGIN
@@ -52472,6 +50892,10 @@ proc:BEGIN
DECLARE vWarehouseFk INT;
DECLARE vWagons INT;
DECLARE vTrainFk INT;
+ DECLARE vLinesLimit INT DEFAULT NULL;
+ DECLARE vTicketLines INT;
+ DECLARE vVolumeLimit DECIMAL DEFAULT NULL;
+ DECLARE vTicketVolume DECIMAL;
DECLARE vMaxTickets INT;
DECLARE vStateFk VARCHAR(45);
DECLARE vFirstTicketFk INT;
@@ -52487,12 +50911,11 @@ proc:BEGIN
DECLARE vLockName VARCHAR(215);
DECLARE vLockTime INT DEFAULT 15;
DECLARE vFreeWagonFk INT;
- DECLARE cur1 CURSOR FOR
- SELECT ticketFk
+ DECLARE c1 CURSOR FOR
+ SELECT ticketFk, `lines`, m3
FROM tmp.productionBuffer
WHERE ticketFk <> vFirstTicketFk
- ORDER BY
- HH,
+ ORDER BY HH,
mm,
productionOrder DESC,
m3 DESC,
@@ -52504,32 +50927,34 @@ proc:BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- SELECT
- pc.ticketTrolleyMax * o.numberOfWagons,
- pc.hasUniqueCollectionTime,
- w.code,
- o.warehouseFk,
- o.itemPackingTypeFk,
- st.code,
- CONCAT('collection_new', o.warehouseFk, ':',o.itemPackingTypeFk),
- o.numberOfWagons,
- o.trainFk
- INTO
- vMaxTickets,
- vHasUniqueCollectionTime,
- vWorkerCode,
- vWarehouseFk,
- vItemPackingTypeFk,
- vStateFk,
- vLockName,
- vWagons,
- vTrainFk
+ SELECT pc.ticketTrolleyMax * o.numberOfWagons,
+ pc.hasUniqueCollectionTime,
+ w.code,
+ o.warehouseFk,
+ o.itemPackingTypeFk,
+ st.code,
+ CONCAT('collection_new', o.warehouseFk, ':',o.itemPackingTypeFk),
+ o.numberOfWagons,
+ o.trainFk,
+ o.linesLimit,
+ o.volumeLimit
+ INTO vMaxTickets,
+ vHasUniqueCollectionTime,
+ vWorkerCode,
+ vWarehouseFk,
+ vItemPackingTypeFk,
+ vStateFk,
+ vLockName,
+ vWagons,
+ vTrainFk,
+ vLinesLimit,
+ vVolumeLimit
FROM productionConfig pc
JOIN worker w ON w.id = vUserFk
JOIN state st ON st.`code` = 'ON_PREPARATION'
JOIN operator o ON o.workerFk = vUserFk;
- IF NOT GET_LOCK(vLockName,vLockTime) THEN
+ IF NOT GET_LOCK(vLockName, vLockTime) THEN
LEAVE proc;
END IF;
@@ -52585,16 +51010,16 @@ proc:BEGIN
SELECT COUNT(*) INTO vHasAssignedTickets
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
- WHERE s.code = 'PICKER_DESIGNED'
- AND pb.workerCode = vWorkerCode;
+ WHERE s.code = 'PICKER_DESIGNED'
+ AND pb.workerCode = vWorkerCode;
-- Se dejan en la tabla tmp.productionBuffer sólo aquellos tickets adecuados
IF vHasAssignedTickets THEN
DELETE pb.*
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
- WHERE s.code <> 'PICKER_DESIGNED'
- OR pb.workerCode <> vWorkerCode;
+ WHERE s.code <> 'PICKER_DESIGNED'
+ OR pb.workerCode <> vWorkerCode;
ELSE
DELETE pb.*
FROM tmp.productionBuffer pb
@@ -52603,23 +51028,32 @@ proc:BEGIN
JOIN agency a ON a.id = am.agencyFk
JOIN productionConfig pc
WHERE pb.shipped <> util.VN_CURDATE()
- OR (pb.ubicacion IS NULL AND a.isOwn = TRUE)
- OR (s.isPreparable = FALSE AND s.isPrintable = FALSE)
+ OR (pb.ubicacion IS NULL AND a.isOwn)
+ OR (NOT s.isPreparable AND NOT s.isPrintable)
OR pb.collectionH IS NOT NULL
OR pb.collectionV IS NOT NULL
OR pb.collectionN IS NOT NULL
- OR (pb.H = 0 AND pb.V > 0 AND vItemPackingTypeFk = 'H')
- OR (pb.V = 0 AND vItemPackingTypeFk = 'V')
+ OR (NOT pb.H AND pb.V > 0 AND vItemPackingTypeFk = 'H')
+ OR (NOT pb.V AND vItemPackingTypeFk = 'V')
OR (pc.isPreviousPreparationRequired AND pb.previousWithoutParking)
- OR LENGTH(pb.problem) > 0;
+ OR LENGTH(pb.problem) > 0
+ OR (pb.lines >= vLinesLimit AND vLinesLimit IS NOT NULL)
+ OR (pb.m3 >= vVolumeLimit AND vVolumeLimit IS NOT NULL);
END IF;
-- Es importante que el primer ticket se coja en todos los casos
- SELECT ticketFk, HH, mm
- INTO vFirstTicketFk, vHour, vMinute
- FROM tmp.productionBuffer
- ORDER BY
+ SELECT ticketFk,
HH,
+ mm,
+ `lines`,
+ m3
+ INTO vFirstTicketFk,
+ vHour,
+ vMinute,
+ vTicketLines,
+ vTicketVolume
+ FROM tmp.productionBuffer
+ ORDER BY HH,
mm,
productionOrder DESC,
m3 DESC,
@@ -52631,90 +51065,104 @@ proc:BEGIN
-- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede
IF vHasUniqueCollectionTime THEN
- DELETE
- FROM tmp.productionBuffer
+ DELETE FROM tmp.productionBuffer
WHERE HH <> vHour
OR mm <> vMinute;
END IF;
SET vTicketFk = vFirstTicketFk;
+ SET @lines = 0;
+ SET @volume = 0;
- OPEN cur1;
-
+ OPEN c1;
read_loop: LOOP
SET vDone = FALSE;
- CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk);
+ -- Buscamos un ticket que cumpla con los requisitos en el listado
+ IF ((vTicketLines + @lines) <= vLinesLimit OR vLinesLimit IS NULL)
+ AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN
- DROP TEMPORARY TABLE tmp.ticketIPT;
+ CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk);
+ DROP TEMPORARY TABLE tmp.ticketIPT;
- UPDATE tmp.productionBuffer pb
- JOIN (SELECT @litros:= SUM(litros) liters, COUNT(*) `lines`, MAX(i.`size`) height
- FROM saleVolume sv
- JOIN sale s ON s.id = sv.saleFk
- JOIN item i ON i.id = s.itemFk
- WHERE sv.ticketFk = vTicketFk ) sub
- SET pb.liters = sub.liters, pb.`lines` = sub.`lines`, pb.height = sub.height
- WHERE pb.ticketFk = vTicketFk;
+ UPDATE tmp.productionBuffer pb
+ JOIN (
+ SELECT SUM(litros) liters,
+ @lines:= COUNT(*) + @lines,
+ COUNT(*) `lines`,
+ MAX(i.`size`) height,
+ @volume := SUM(sv.volume) + @volume volume
+ FROM saleVolume sv
+ JOIN sale s ON s.id = sv.saleFk
+ JOIN item i ON i.id = s.itemFk
+ WHERE sv.ticketFk = vTicketFk
+ ) sub
+ SET pb.liters = sub.liters,
+ pb.`lines` = sub.`lines`,
+ pb.height = sub.height
+ WHERE pb.ticketFk = vTicketFk;
- UPDATE tTrain tt
- JOIN tmp.productionBuffer pb ON pb.ticketFk = vTicketFk
- SET tt.ticketFk = pb.ticketFk
- WHERE tt.liters >= pb.liters
- AND tt.`lines` >= pb.`lines`
- AND (tt.height >= pb.height OR vItemPackingTypeFk <> 'V')
- AND tt.ticketFk IS NULL
- ORDER BY
- wagon,
- shelve,
- tt.liters,
- tt.`lines`,
- tt.height
- LIMIT 1;
-
- -- Si no le encuentra una balda adecuada, intentamos darle un carro entero
- -- si queda alguno libre
-
- IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
- SELECT tt.wagon
- INTO vFreeWagonFk
- FROM tTrain tt
- LEFT JOIN (SELECT DISTINCT wagon
- FROM tTrain
- WHERE ticketFk IS NOT NULL
- ) nn ON nn.wagon = tt.wagon
- WHERE nn.wagon IS NULL
- ORDER BY wagon
+ UPDATE tTrain tt
+ JOIN tmp.productionBuffer pb ON pb.ticketFk = vTicketFk
+ SET tt.ticketFk = pb.ticketFk
+ WHERE tt.liters >= pb.liters
+ AND tt.`lines` >= pb.`lines`
+ AND (tt.height >= pb.height OR vItemPackingTypeFk <> 'V')
+ AND tt.ticketFk IS NULL
+ ORDER BY wagon,
+ shelve,
+ tt.liters,
+ tt.`lines`,
+ tt.height
LIMIT 1;
- IF vFreeWagonFk THEN
- UPDATE tTrain
- SET ticketFk = vFirstTicketFk
- WHERE wagon = vFreeWagonFk;
-
- -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo
- DELETE tt.*
+ -- Si no le encuentra una balda adecuada, intentamos darle un carro entero si queda alguno libre
+ IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
+ SELECT tt.wagon
+ INTO vFreeWagonFk
FROM tTrain tt
- LEFT JOIN (SELECT DISTINCT wagon
- FROM tTrain
+ LEFT JOIN (
+ SELECT DISTINCT wagon
+ FROM tTrain
+ WHERE ticketFk IS NOT NULL
+ ) nn ON nn.wagon = tt.wagon
+ WHERE nn.wagon IS NULL
+ ORDER BY wagon
+ LIMIT 1;
+
+ IF vFreeWagonFk THEN
+ UPDATE tTrain
+ SET ticketFk = vFirstTicketFk
+ WHERE wagon = vFreeWagonFk;
+
+ -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo
+ DELETE tt.*
+ FROM tTrain tt
+ LEFT JOIN (
+ SELECT DISTINCT wagon
+ FROM tTrain
WHERE ticketFk IS NOT NULL
- ) nn ON nn.wagon = tt.wagon
- WHERE nn.wagon IS NULL;
+ ) nn ON nn.wagon = tt.wagon
+ WHERE nn.wagon IS NULL;
+ END IF;
END IF;
- END IF;
- FETCH cur1 INTO vTicketFk;
-
- IF vDone OR NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk IS NULL) THEN
- LEAVE read_loop;
+ FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume;
+ IF vDone OR NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk IS NULL) THEN
+ LEAVE read_loop;
+ END IF;
+ ELSE
+ FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume;
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
END IF;
END LOOP;
-
- CLOSE cur1;
+ CLOSE c1;
IF (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
UPDATE collection c
- JOIN state st ON st.code = 'ON_PREPARATION'
+ JOIN state st ON st.code = 'ON_PREPARATION'
SET c.stateFk = st.id
WHERE c.id = vCollectionFk;
@@ -52726,7 +51174,6 @@ proc:BEGIN
ORDER BY tt.wagon, tt.shelve;
-- Actualiza el estado de los tickets
-
CALL collection_setState(vCollectionFk, vStateFk);
-- Aviso para la preparacion previa
@@ -52737,24 +51184,23 @@ proc:BEGIN
CALL sales_mergeByCollection(vCollectionFk);
- UPDATE collection c
- JOIN (SELECT count(*) saleTotalCount ,
- sum(s.isPicked != 0) salePickedCount
- FROM ticketCollection tc
- JOIN sale s ON s.ticketFk = tc.ticketFk
- WHERE tc.collectionFk = vCollectionFk
- AND s.quantity > 0
+ UPDATE `collection` c
+ JOIN (
+ SELECT COUNT(*) saleTotalCount,
+ SUM(s.isPicked <> 0) salePickedCount
+ FROM ticketCollection tc
+ JOIN sale s ON s.ticketFk = tc.ticketFk
+ WHERE tc.collectionFk = vCollectionFk
+ AND s.quantity > 0
) sub
SET c.saleTotalCount = sub.saleTotalCount,
c.salePickedCount = sub.salePickedCount
WHERE c.id = vCollectionFk;
ELSE
-
- -- CALL util.throw('No ha sido posible obtener colección');
- DELETE FROM collection WHERE id = vCollectionFk;
- SET vCollectionFk = NULL;
-
+ DELETE FROM `collection`
+ WHERE id = vCollectionFk;
+ SET vCollectionFk = NULL;
END IF;
DO RELEASE_LOCK(vLockName);
@@ -52864,7 +51310,7 @@ BEGIN
DECLARE vDone INT DEFAULT FALSE;
DECLARE vCursor CURSOR FOR
SELECT DISTINCT ticketFk
- FROM ticketCollection tc
+ FROM ticketCollection tc
WHERE tc.collectionFk = vSelf;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
@@ -52911,25 +51357,25 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getFiscaldata`(workerFk INT)
BEGIN
-
+
DECLARE vCompanyFk INT;
-
- SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk)
+
+ SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk)
INTO vCompanyFk
FROM vn.routeConfig rc
LEFT JOIN userConfig uc ON uc.userFk = workerFk;
-
-
+
+
SELECT
s.name AS name ,
s.NIF AS nif ,
s.street AS street ,
s.city AS city ,
- s.postCode AS postCode
-
- FROM vn.company c
+ s.postCode AS postCode
+
+ FROM vn.company c
JOIN vn.worker w ON w.id = c.workerManagerFk
- JOIN vn.supplier s ON s.id = c.id
+ JOIN vn.supplier s ON s.id = c.id
WHERE c.id = vCompanyFk;
END ;;
DELIMITER ;
@@ -52938,14 +51384,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `company_getSuppliersDebt` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET collation_connection = utf8mb4_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getSuppliersDebt`(vSelf INT, vMonthsAgo INT)
BEGIN
@@ -52955,81 +51401,81 @@ BEGIN
* @param vSelf company id
* @param vMonthAgo time interval to be consulted
*/
- DECLARE vStartingDate DATETIME DEFAULT TIMESTAMPADD (MONTH,- vMonthsAgo,util.VN_CURDATE());
- DECLARE vCurrencyEuroFk INT;
- DECLARE vStartDate DATE;
- DECLARE vInvalidBalances DOUBLE;
+ DECLARE vStartingDate DATETIME DEFAULT TIMESTAMPADD (MONTH,- vMonthsAgo,util.VN_CURDATE());
+ DECLARE vCurrencyEuroFk INT;
+ DECLARE vStartDate DATE;
+ DECLARE vInvalidBalances DOUBLE;
- SELECT dated, invalidBalances INTO vStartDate, vInvalidBalances FROM supplierDebtConfig;
- SELECT id INTO vCurrencyEuroFk FROM currency WHERE code = 'EUR';
+ SELECT dated, invalidBalances INTO vStartDate, vInvalidBalances FROM supplierDebtConfig;
+ SELECT id INTO vCurrencyEuroFk FROM currency WHERE code = 'EUR';
- DROP TEMPORARY TABLE IF EXISTS tOpeningBalances;
- CREATE TEMPORARY TABLE tOpeningBalances (
- supplierFk INT NOT NULL,
- companyFk INT NOT NULL,
- openingBalances DOUBLE NOT NULL,
- closingBalances DOUBLE NOT NULL,
- currencyFk INT NOT NULL,
- PRIMARY KEY (supplierFk, companyFk, currencyFk)
- ) ENGINE = MEMORY;
+ DROP TEMPORARY TABLE IF EXISTS tOpeningBalances;
+ CREATE TEMPORARY TABLE tOpeningBalances (
+ supplierFk INT NOT NULL,
+ companyFk INT NOT NULL,
+ openingBalances DOUBLE NOT NULL,
+ closingBalances DOUBLE NOT NULL,
+ currencyFk INT NOT NULL,
+ PRIMARY KEY (supplierFk, companyFk, currencyFk)
+ ) ENGINE = MEMORY;
- -- Calculates the opening and closing balance for each supplier
- INSERT INTO tOpeningBalances
- SELECT supplierFk,
- companyFk,
- SUM(amount * isBeforeStarting) AS openingBalances,
- SUM(amount) closingBalances,
- currencyFk
- FROM (
- SELECT p.supplierFk,
+ -- Calculates the opening and closing balance for each supplier
+ INSERT INTO tOpeningBalances
+ SELECT supplierFk,
+ companyFk,
+ SUM(amount * isBeforeStarting) AS openingBalances,
+ SUM(amount) closingBalances,
+ currencyFk
+ FROM (
+ SELECT p.supplierFk,
p.companyFk,
IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount,
p.dueDated < vStartingDate isBeforeStarting,
p.currencyFk
- FROM payment p
- WHERE p.received > vStartDate
- AND p.companyFk = vSelf
- UNION ALL
- SELECT r.supplierFk,
+ FROM payment p
+ WHERE p.received > vStartDate
+ AND p.companyFk = vSelf
+ UNION ALL
+ SELECT r.supplierFk,
r.companyFk,
- IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue) AS Total,
rv.dueDated < vStartingDate isBeforeStarting,
- r.currencyFk
- FROM invoiceIn r
- INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk
- WHERE r.issued > vStartDate
- AND r.isBooked
- AND r.companyFk = vSelf
- ) sub GROUP BY companyFk, supplierFk, currencyFk;
+ r.currencyFk
+ FROM invoiceIn r
+ INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk
+ WHERE r.issued > vStartDate
+ AND r.isBooked
+ AND r.companyFk = vSelf
+ ) sub GROUP BY companyFk, supplierFk, currencyFk;
- DROP TEMPORARY TABLE IF EXISTS tPendingDuedates;
- CREATE TEMPORARY TABLE tPendingDuedates (
- id INT auto_increment,
+ DROP TEMPORARY TABLE IF EXISTS tPendingDuedates;
+ CREATE TEMPORARY TABLE tPendingDuedates (
+ id INT auto_increment,
expirationId INT,
- dated DATE,
- supplierFk INT NOT NULL,
- companyFk INT NOT NULL,
- amount DECIMAL(10, 2) NOT NULL,
- currencyFk INT NOT NULL,
- pending DECIMAL(10, 2) DEFAULT 0,
- balance DECIMAL(10, 2) DEFAULT 0,
- endingBalance DECIMAL(10, 2) DEFAULT 0,
- isPayment BOOLEAN,
- isReconciled BOOLEAN,
- PRIMARY KEY (id),
- INDEX (supplierFk, companyFk, currencyFk)
- ) ENGINE = MEMORY;
+ dated DATE,
+ supplierFk INT NOT NULL,
+ companyFk INT NOT NULL,
+ amount DECIMAL(10, 2) NOT NULL,
+ currencyFk INT NOT NULL,
+ pending DECIMAL(10, 2) DEFAULT 0,
+ balance DECIMAL(10, 2) DEFAULT 0,
+ endingBalance DECIMAL(10, 2) DEFAULT 0,
+ isPayment BOOLEAN,
+ isReconciled BOOLEAN,
+ PRIMARY KEY (id),
+ INDEX (supplierFk, companyFk, currencyFk)
+ ) ENGINE = MEMORY;
- INSERT INTO tPendingDuedates (
- expirationId,
- dated,
- supplierFk,
- companyFk,
- amount,
- currencyFk,
- isPayment,
- isReconciled
- )SELECT p.id,
+ INSERT INTO tPendingDuedates (
+ expirationId,
+ dated,
+ supplierFk,
+ companyFk,
+ amount,
+ currencyFk,
+ isPayment,
+ isReconciled
+ )SELECT p.id,
p.dueDated,
p.supplierFk,
p.companyFk,
@@ -53048,80 +51494,80 @@ BEGIN
-IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue),
r.currencyFk,
FALSE isPayment,
- TRUE
- FROM invoiceIn r
+ TRUE
+ FROM invoiceIn r
LEFT JOIN tOpeningBalances si ON r.companyFk = si.companyFk
AND r.supplierFk = si.supplierFk
- AND r.currencyFk = si.currencyFk
+ AND r.currencyFk = si.currencyFk
JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk
WHERE rv.dueDated >= vStartingDate
AND (si.closingBalances IS NULL OR si.closingBalances <> 0)
AND r.isBooked
AND r.companyFk = vSelf
ORDER BY supplierFk, companyFk, companyFk, dueDated, isPayment DESC, id;
- -- Now, we calculate the outstanding amount for each receipt in descending order
- SET @risk := 0.0;
- SET @supplier := 0.0;
- SET @company := 0.0;
- SET @moneda := 0.0;
- SET @pending := 0.0;
- SET @day := util.VN_CURDATE();
+ -- Now, we calculate the outstanding amount for each receipt in descending order
+ SET @risk := 0.0;
+ SET @supplier := 0.0;
+ SET @company := 0.0;
+ SET @moneda := 0.0;
+ SET @pending := 0.0;
+ SET @day := util.VN_CURDATE();
- UPDATE tPendingDuedates vp
- LEFT JOIN tOpeningBalances si ON vp.companyFk = si.companyFk
- AND vp.supplierFk = si.supplierFk
- AND vp.currencyFk = si.currencyFk
- SET vp.balance = @risk := (
- IF (
- @company <> vp.companyFk
- OR @supplier <> vp.supplierFk
- OR @moneda <> vp.currencyFk,
- IFNULL(si.openingBalances, 0),
- @risk
- ) +
- vp.amount
- ),
- -- if there is a change of company or supplier or currency, the balance is reset
- vp.pending = @pending := IF (
- @company <> vp.companyFk
- OR @supplier <> vp.supplierFk
- OR @moneda <> vp.currencyFk
- OR @day <> vp.dated,
- vp.amount * (NOT vp.isPayment),
- @pending + vp.amount
- ),
- vp.companyFk = @company := vp.companyFk,
- vp.supplierFk = @supplier := vp.supplierFk,
- vp.currencyFk = @moneda := vp.currencyFk,
- vp.dated = @day := vp.dated,
- vp.balance = @risk,
- vp.pending = @pending;
+ UPDATE tPendingDuedates vp
+ LEFT JOIN tOpeningBalances si ON vp.companyFk = si.companyFk
+ AND vp.supplierFk = si.supplierFk
+ AND vp.currencyFk = si.currencyFk
+ SET vp.balance = @risk := (
+ IF (
+ @company <> vp.companyFk
+ OR @supplier <> vp.supplierFk
+ OR @moneda <> vp.currencyFk,
+ IFNULL(si.openingBalances, 0),
+ @risk
+ ) +
+ vp.amount
+ ),
+ -- if there is a change of company or supplier or currency, the balance is reset
+ vp.pending = @pending := IF (
+ @company <> vp.companyFk
+ OR @supplier <> vp.supplierFk
+ OR @moneda <> vp.currencyFk
+ OR @day <> vp.dated,
+ vp.amount * (NOT vp.isPayment),
+ @pending + vp.amount
+ ),
+ vp.companyFk = @company := vp.companyFk,
+ vp.supplierFk = @supplier := vp.supplierFk,
+ vp.currencyFk = @moneda := vp.currencyFk,
+ vp.dated = @day := vp.dated,
+ vp.balance = @risk,
+ vp.pending = @pending;
- CREATE OR REPLACE TEMPORARY TABLE tRowsToDelete ENGINE = MEMORY
- SELECT expirationId,
- dated,
- supplierFk,
- companyFk,
- currencyFk,
- balance
- FROM tPendingDuedates
- WHERE balance < vInvalidBalances
- AND balance > - vInvalidBalances;
+ CREATE OR REPLACE TEMPORARY TABLE tRowsToDelete ENGINE = MEMORY
+ SELECT expirationId,
+ dated,
+ supplierFk,
+ companyFk,
+ currencyFk,
+ balance
+ FROM tPendingDuedates
+ WHERE balance < vInvalidBalances
+ AND balance > - vInvalidBalances;
- DELETE vp.*
- FROM tPendingDuedates vp
- JOIN tRowsToDelete rd ON (
- vp.dated < rd.dated
- OR (vp.dated = rd.dated AND vp.expirationId <= rd.expirationId)
- )
- AND vp.supplierFk = rd.supplierFk
- AND vp.companyFk = rd.companyFk
- AND vp.currencyFk = rd.currencyFk
- WHERE vp.isPayment = FALSE;
+ DELETE vp.*
+ FROM tPendingDuedates vp
+ JOIN tRowsToDelete rd ON (
+ vp.dated < rd.dated
+ OR (vp.dated = rd.dated AND vp.expirationId <= rd.expirationId)
+ )
+ AND vp.supplierFk = rd.supplierFk
+ AND vp.companyFk = rd.companyFk
+ AND vp.currencyFk = rd.currencyFk
+ WHERE vp.isPayment = FALSE;
- SELECT vp.expirationId,
- vp.dated,
- vp.supplierFk,
+ SELECT vp.expirationId,
+ vp.dated,
+ vp.supplierFk,
vp.companyFk,
vp.currencyFk,
vp.amount,
@@ -53131,16 +51577,208 @@ BEGIN
vp.isPayment,
vp.isReconciled,
vp.endingBalance,
- cr.amount clientRiskAmount
- FROM tPendingDuedates vp
- LEFT JOIN supplier s ON s.id = vp.supplierFk
- LEFT JOIN client c ON c.fi = s.nif
- LEFT JOIN clientRisk cr ON cr.clientFk = c.id
- AND cr.companyFk = vp.companyFk;
+ cr.amount clientRiskAmount,
+ co.CEE
+ FROM tPendingDuedates vp
+ LEFT JOIN supplier s ON s.id = vp.supplierFk
+ LEFT JOIN client c ON c.fi = s.nif
+ LEFT JOIN clientRisk cr ON cr.clientFk = c.id
+ LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id
+ LEFT JOIN bankEntity be ON be.id = sa.bankEntityFk
+ LEFT JOIN country co ON co.id = be.countryFk
+ AND cr.companyFk = vp.companyFk;
- DROP TEMPORARY TABLE tOpeningBalances;
- DROP TEMPORARY TABLE tPendingDuedates;
- DROP TEMPORARY TABLE tRowsToDelete;
+ DROP TEMPORARY TABLE tOpeningBalances;
+ DROP TEMPORARY TABLE tPendingDuedates;
+ DROP TEMPORARY TABLE tRowsToDelete;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `comparative_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `comparative_add`()
+BEGIN
+/**
+ * Inserts sales records less than one month old in comparative.
+ */
+ DECLARE vMaxPeriod INT;
+ DECLARE vPeriod INT;
+ DECLARE vWeek INT;
+ DECLARE vConfigPeriod INT;
+ DECLARE vConfigWeek INT;
+
+ SELECT period, week INTO vConfigPeriod, vConfigWeek
+ FROM comparativeAddConfig;
+
+ SELECT IFNULL(MAX(timePeriod), 0) INTO vMaxPeriod
+ FROM comparative;
+
+ SELECT period - vConfigPeriod,
+ week
+ INTO vPeriod,
+ vWeek
+ FROM `time`
+ WHERE dated = util.VN_CURDATE();
+
+ IF vMaxPeriod < vPeriod AND vWeek > vConfigWeek THEN
+ DELETE FROM comparative WHERE timePeriod BETWEEN vMaxPeriod AND vPeriod;
+
+ INSERT INTO comparative(
+ timePeriod,
+ itemFk,
+ warehouseFk,
+ quantity,
+ price,
+ countryFk
+ )
+ SELECT tm.period,
+ s.itemFk,
+ t.warehouseFk,
+ sum(s.quantity),
+ sum(v.importe),
+ p.countryFk
+ FROM bs.ventas v
+ JOIN time tm ON tm.dated = v.fecha
+ JOIN sale s ON s.id = v.Id_Movimiento
+ JOIN itemType tp ON tp.id = v.tipo_id
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN client c ON c.id = t.clientFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ JOIN address ad ON ad.id = t.addressFk
+ LEFT JOIN province p ON p.id = ad.provinceFk
+ WHERE tm.period BETWEEN vMaxPeriod AND vPeriod
+ AND c.typeFk <> 'loses'
+ AND NOT w.code = 'inv'
+ GROUP BY p.countryFk, s.itemFk, tm.period, t.warehouseFk;
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `confection_controlSource` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `confection_controlSource`(
+ vDated DATE,
+ vScopeDays INT,
+ vMaxAlertLevel INT,
+ vWarehouseFk INT
+)
+BEGIN
+/**
+ * Obtiene la información para el control de confección,
+ * ya sean tickets y/o entradas.
+ *
+ * @param vDated Fecha a calcular
+ * @param vScopeDays Número de días desde hoy en adelante que entran en el cálculo.
+ * @param vMaxAlertLevel Id nivel de alerta
+ * @param vWarehouseFk Id de almacén
+ */
+ DECLARE vEndingDate DATETIME DEFAULT util.dayEnd(vDated) + INTERVAL vScopeDays DAY;
+
+ SELECT t.shipped,
+ t.id ticketFk,
+ s.id saleFk,
+ s.quantity,
+ s.concept,
+ ABS(s.reserved) isReserved,
+ i.category,
+ it.name itemType,
+ t.nickname,
+ wh.name warehouse,
+ t.warehouseFk warehouseFk,
+ a.provinceFk,
+ am.agencyFk,
+ ct.description,
+ stock.visible,
+ stock.available
+ FROM ticket t
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN warehouse wh ON wh.id = t.warehouseFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN confectionType ct ON ct.id = it.making
+ JOIN `address` a on a.id = t.addressFk
+ LEFT JOIN ticketState tls on tls.ticketFk = t.id
+ LEFT JOIN
+ (
+ SELECT item_id,
+ SUM(visible) visible,
+ SUM(available) available
+ FROM (
+ SELECT a.item_id,
+ 0 visible,
+ a.available
+ FROM cache.cache_calc cc
+ LEFT JOIN cache.available a ON a.calc_id = cc.id
+ WHERE cc.cache_id IN ('visible', 'available')
+ AND cc.params = CONCAT(vWarehouseFk, "/", util.VN_CURDATE())
+ UNION ALL
+ SELECT v.item_id,
+ v.visible,
+ 0
+ FROM cache.cache_calc cc
+ LEFT JOIN cache.visible v ON v.calc_id = cc.id
+ WHERE cc.cacheName IN ('visible', 'available')
+ AND cc.params = vWarehouseFk
+ ) sub
+ GROUP BY item_id
+ ) stock ON stock.item_id = s.itemFk
+ WHERE it.making
+ AND tls.alertLevel < vMaxAlertLevel
+ AND wh.hasConfectionTeam
+ AND t.shipped BETWEEN vDated AND vEndingDate
+ AND s.quantity > 0
+ UNION ALL
+ SELECT tr.shipped,
+ e.id,
+ NULL,
+ b.quantity,
+ i.name,
+ NULL,
+ i.category,
+ NULL,
+ whi.name,
+ who.name,
+ NULL,
+ NULL,
+ NULL,
+ ct.description,
+ NULL,
+ NULL
+ FROM buy b
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN warehouse whi ON whi.id = tr.warehouseInFk
+ JOIN warehouse who ON who.id = tr.warehouseOutFk
+ JOIN item i ON i.id = b.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN confectionType ct ON ct.id = it.making
+ WHERE who.hasConfectionTeam
+ AND it.making
+ AND tr.shipped BETWEEN vDated AND vEndingDate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -53160,7 +51798,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME)
BEGIN
-
+
DECLARE startingMinute INT;
TRUNCATE vn.conveyorExpedition;
@@ -53177,23 +51815,23 @@ BEGIN
conveyorBuildingClassFk)
SELECT e.id,
e.created,
- 10 * p.depth as depth,
+ 10 * p.depth as depth,
10 * p.width as width,
10 * p.height as height,
IFNULL(t.routeFk,am.agencyFk) routeFk,
hour(e.created) * 60 + minute(e.created),
IFNULL(et.description , a.name),
IFNULL(t.routeFk,am.agencyFk) criterion,
- IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass)
+ IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass)
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.packaging p ON p.id = e.packagingFk
LEFT JOIN vn.zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
- LEFT JOIN vn.agency a ON a.id = am.agencyFk
- LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
- LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
- JOIN vn.packagingConfig pc
+ LEFT JOIN vn.agency a ON a.id = am.agencyFk
+ LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
+ LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ JOIN vn.packagingConfig pc
WHERE t.warehouseFk IN (60,1,44)
AND e.created BETWEEN vStarted AND vEnded
AND p.height < 140
@@ -53202,8 +51840,8 @@ BEGIN
SELECT MIN(productionMinute) INTO startingMinute
FROM vn.conveyorExpedition ce ;
-
- UPDATE vn.conveyorExpedition
+
+ UPDATE vn.conveyorExpedition
SET productionMinute = productionMinute - startingMinute;
END ;;
@@ -53272,7 +51910,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `createPedidoInterno`(vItemFk INT,vQuantity INT)
BEGIN
-
+
UPDATE vn.item SET upToDown = vQuantity WHERE id = vItemFk;
END ;;
@@ -53295,52 +51933,52 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `crypt`(vText VARCHAR(255), vKey VAR
BEGIN
DECLARE vEncryptedText VARCHAR(255) DEFAULT '';
-
+
DECLARE vKeyLength INT;
DECLARE vKeyPosition INT DEFAULT 1;
DECLARE vKeyChar VARCHAR(1);
-
+
DECLARE vTextLength INT;
DECLARE vTextPosition INT DEFAULT 1;
DECLARE vTextChar VARCHAR(1);
-
+
DECLARE vEncryptedChar VARCHAR(1);
DECLARE vEncryptedCharPosition INT;
-
+
DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz';
DECLARE vChainTextPosition INT;
DECLARE vChainKeyPosition INT;
DECLARE vChainLength INT;
-
+
DECLARE vInvalidadChars VARCHAR(255) DEFAULT '';
-
- SET vTextLength = LENGTH(vText);
+
+ SET vTextLength = LENGTH(vText);
SET vKeyLength = LENGTH(vKey);
SET vChainLength = LENGTH(vChain);
-
+
WHILE vTextPosition <= vTextLength DO
-
+
SET vTextChar = MID(vText,vTextPosition,1);
SET vKeyChar = MID(vKey,vKeyPosition,1);
-
+
SET vChainTextPosition = LOCATE(vTextChar, vChain);
SET vInvalidadChars = IF(vChainTextPosition, vInvalidadChars, CONCAT(vInvalidadChars,vTextChar));
SET vChainKeyPosition = LOCATE(vKeyChar, vChain);
SET vEncryptedCharPosition = vChainTextPosition + vChainKeyPosition;
-
+
IF vEncryptedCharPosition > vChainLength THEN
-
+
SET vEncryptedCharPosition = vEncryptedCharPosition - vChainLength;
-
+
END IF;
-
+
SET vEncryptedChar = MID(vChain, vEncryptedCharPosition,1);
-
+
SET vEncryptedText = CONCAT(vEncryptedText, vEncryptedChar);
-
+
SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1);
SET vTextPosition = vTextPosition + 1;
-
+
END WHILE;
SET vResult = IF(LENGTH(vInvalidadChars), CONCAT('Caracteres no válidos: ',vInvalidadChars),vEncryptedText);
@@ -53365,49 +52003,49 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cryptOff`(vText VARCHAR(255), vKey
BEGIN
DECLARE vUncryptedText VARCHAR(255) DEFAULT '';
-
+
DECLARE vKeyLength INT;
DECLARE vKeyPosition INT DEFAULT 1;
DECLARE vKeyChar VARCHAR(1);
-
+
DECLARE vTextLength INT;
DECLARE vTextPosition INT DEFAULT 1;
DECLARE vTextChar VARCHAR(1);
-
+
DECLARE vUncryptedChar VARCHAR(1);
DECLARE vUncryptedCharPosition INT;
-
+
DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz';
DECLARE vChainTextPosition INT;
DECLARE vChainKeyPosition INT;
DECLARE vChainLength INT;
-
- SET vTextLength = LENGTH(vText);
+
+ SET vTextLength = LENGTH(vText);
SET vKeyLength = LENGTH(vKey);
SET vChainLength = LENGTH(vChain);
-
+
WHILE vTextPosition <= vTextLength DO
-
+
SET vTextChar = MID(vText,vTextPosition,1);
SET vKeyChar = MID(vKey,vKeyPosition,1);
-
+
SET vChainTextPosition = LOCATE(vTextChar, vChain);
SET vChainKeyPosition = LOCATE(vKeyChar, vChain);
SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition;
-
+
IF vUncryptedCharPosition < 1 THEN
-
+
SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength;
-
+
END IF;
-
+
SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1);
-
+
SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar);
-
+
SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1);
SET vTextPosition = vTextPosition + 1;
-
+
END WHILE;
SET vResult = vUncryptedText;
@@ -53503,7 +52141,7 @@ BEGIN
OR (vSelf IS NOT NULL AND parentFk = vSelf);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
SET vSons = 0;
OPEN vChildren;
@@ -53514,11 +52152,11 @@ BEGIN
IF vDone THEN
LEAVE myLoop;
END IF;
-
+
SET vIndex = vIndex + 1;
SET vLft = vIndex;
SET vSons = vSons + 1;
-
+
CALL department_calcTreeRec(
vChildFk,
CONCAT(vPath, vChildFk, '/'),
@@ -53573,7 +52211,7 @@ proc: BEGIN
SELECT isChanged INTO vIsChanged
FROM department_recalc;
-
+
IF vIsChanged THEN
UPDATE department_recalc SET isChanged = FALSE;
CALL vn.department_calcTree;
@@ -53598,17 +52236,17 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `department_getHasMistake`()
BEGIN
-
+
/**
* Obtiene los sectores a los cuales les ponemos errores
*
*/
-
+
SELECT id, name
FROM department
WHERE hasToMistake <> FALSE;
-
-
+
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -53667,19 +52305,19 @@ BEGIN
FROM department g
JOIN tChilds c ON c.id = g.id
WHERE g.parentFk IS NOT NULL;
-
+
INSERT IGNORE INTO tNodes
SELECT id FROM tParents;
-
+
IF ROW_COUNT() = 0 THEN
LEAVE myLoop;
END IF;
-
+
DELETE FROM tChilds;
INSERT INTO tChilds
SELECT id FROM tParents;
END LOOP;
-
+
DROP TEMPORARY TABLE
tChilds,
tParents;
@@ -53746,12 +52384,12 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProductionUser_exists`(vUserFk INT)
BEGIN
-
+
/* SELECT COUNT(*) AS UserExists
- FROM vn.deviceProductionUser dpu
+ FROM vn.deviceProductionUser dpu
WHERE dpu.userFk = vUserFk;*/
SELECT TRUE;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -53823,10 +52461,10 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `device_checkLogin`(vUserFk INT, vAndroidID VARCHAR(50))
BEGIN
-
+
/*
* Comprueba si está registrado el dispositivo mediante su androidId
- *
+ *
* @param vUSerFk el id del user
* @param vAndroidID es el identificador android_id del dispositivo
*/
@@ -53838,20 +52476,20 @@ BEGIN
SELECT dpc.isAllUsersallowed INTO vIsAllUsersAllowed
FROM vn.deviceProductionConfig dpc;
- IF NOT vIsAllUsersAllowed THEN
-
+ IF NOT vIsAllUsersAllowed THEN
+
SELECT COUNT(*) INTO vIsDepartment
- FROM vn.workerDepartment dp
+ FROM vn.workerDepartment dp
JOIN department d ON d.id = dp.departmentFk
WHERE dp.workerFk = vUserFk AND d.hasToCheckLogin;
-
+
IF vIsDepartment THEN
SELECT COUNT(*) INTO vIsAuthorized
- FROM vn.deviceProductionUser dpu
+ FROM vn.deviceProductionUser dpu
JOIN vn.deviceProduction dp ON dp.id = dpu.deviceProductionFk
WHERE dpu.userFk = vUserFk
AND dp.android_id = vAndroidID;
-
+
IF NOT vIsAuthorized THEN
SET vMessage = 'Usuario no autorizado';
END IF;
@@ -53881,15 +52519,15 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaEntryValueUpdate`(vDuaFk INT)
BEGIN
UPDATE duaEntry de
- JOIN
+ JOIN
( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total
FROM buy b
JOIN duaEntry de ON de.entryFk = b.entryFk
WHERE duaFk = vDuaFk
GROUP BY b.entryFk
) sub ON sub.entryFk = de.entryFk
-
- LEFT JOIN
+
+ LEFT JOIN
(SELECT e.id, sum(iit.taxableBase) as euros
FROM entry e
JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk
@@ -53897,11 +52535,11 @@ BEGIN
WHERE de.duaFk = vDuaFk
GROUP BY e.id
) sub2 ON sub2.id = de.entryFk
-
+
SET de.value = sub.total,
de.euroValue = sub2.euros
WHERE duaFk = vDuaFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -53920,18 +52558,22 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT)
BEGIN
-
+/**
+ * Genera el asiento de un DUA y marca las entradas como confirmadas
+ *
+ * @param vDuaFk Id del dua a recalcular
+ */
DECLARE done BOOL DEFAULT FALSE;
DECLARE vInvoiceFk INT;
- DECLARE vASIEN BIGINT DEFAULT 0;
- DECLARE vCounter INT DEFAULT 0;
+ DECLARE vASIEN BIGINT DEFAULT 0;
+ DECLARE vCounter INT DEFAULT 0;
DECLARE rs CURSOR FOR
- SELECT e.invoiceInFk
+ SELECT DISTINCT e.invoiceInFk
FROM entry e
JOIN duaEntry de ON de.entryFk = e.id
- JOIN invoiceIn ii ON ii.id = e.invoiceInFk
- WHERE de.duaFk = vDuaFk
+ JOIN invoiceIn ii ON ii.id = e.invoiceInFk
+ WHERE de.duaFk = vDuaFk
AND de.customsValue
AND ii.isBooked = FALSE;
@@ -53941,17 +52583,17 @@ BEGIN
UPDATE invoiceIn ii
JOIN entry e ON e.invoiceInFk = ii.id
- JOIN duaEntry de ON de.entryFk = e.id
- JOIN dua d ON d.id = de.duaFk
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN dua d ON d.id = de.duaFk
SET ii.isBooked = TRUE,
ii.booked = IFNULL(ii.booked,d.booked),
ii.operated = IFNULL(ii.operated,d.operated),
- ii.issued = IFNULL(ii.issued,d.issued),
- ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried),
- e.isConfirmed = TRUE
+ ii.issued = IFNULL(ii.issued,d.issued),
+ ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried),
+ e.isConfirmed = TRUE
WHERE d.id = vDuaFk;
- SELECT IFNULL(ASIEN,0) INTO vASIEN
+ SELECT IFNULL(ASIEN,0) INTO vASIEN
FROM dua
WHERE id = vDuaFk;
@@ -53961,29 +52603,29 @@ BEGIN
CALL invoiceIn_booking(vInvoiceFk);
- IF vCounter > 0 OR vASIEN > 0 THEN
+ IF vCounter > 0 OR vASIEN > 0 THEN
- UPDATE vn2008.XDiario x
- JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN
- SET x.ASIEN = vASIEN;
+ UPDATE XDiario x
+ JOIN ledgerConfig lc ON lc.lastBookEntry = x.ASIEN
+ SET x.ASIEN = vASIEN;
- ELSE
+ ELSE
- SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig;
+ SELECT lastBookEntry INTO vASIEN FROM ledgerConfig;
END IF;
- SET vCounter = vCounter + 1;
+ SET vCounter = vCounter + 1;
FETCH rs INTO vInvoiceFk;
END WHILE;
- CLOSE rs;
+ CLOSE rs;
- UPDATE dua
- SET ASIEN = vASIEN
- WHERE id = vDuaFk;
+ UPDATE dua
+ SET ASIEN = vASIEN
+ WHERE id = vDuaFk;
END ;;
DELIMITER ;
@@ -54006,18 +52648,18 @@ BEGIN
DECLARE vNewDuaFk INT;
- INSERT INTO dua(awbFk,companyFk)
- SELECT awbFk,companyFk
+ INSERT INTO dua(companyFk)
+ SELECT companyFk
FROM dua
WHERE id = vDuaFk;
-
+
SELECT LAST_INSERT_ID() INTO vNewDuaFk;
-
+
INSERT INTO duaEntry(duaFk, entryFk, value, customsValue)
SELECT vNewDuaFk, entryFk, value, value - customsValue
FROM duaEntry
WHERE duaFk = vDuaFk
- AND value != customsValue;
+ AND value != customsValue;
END ;;
DELIMITER ;
@@ -54041,11 +52683,11 @@ BEGIN
DECLARE vBookDated DATE;
DECLARE vDiff DECIMAL(10,2);
DECLARE vApunte BIGINT;
-
+
SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE()) INTO vBookNumber, vBookDated
- FROM dua
+ FROM dua
WHERE id = vDuaFk;
-
+
IF vBookNumber IS NULL OR NOT vBookNumber THEN
CALL ledger_next(vBookNumber);
END IF;
@@ -54056,14 +52698,14 @@ BEGIN
ASIEN,
FECHA,
SUBCTA,
- CONCEPTO,
+ CONCEPTO,
EUROHABER,
SERIE,
empresa_id,
CLAVE,
FACTURA)
- SELECT
+ SELECT
vBookNumber,
d.bookEntried,
'4700000999',
@@ -54076,20 +52718,20 @@ BEGIN
FROM duaTax dt
JOIN dua d ON d.id = dt.duaFk
WHERE dt.duaFk = vDuaFk;
-
+
-- Apuntes por tipo de IVA y proveedor
-
+
INSERT INTO XDiario(
ASIEN,
FECHA,
SUBCTA,
- CONTRA,
+ CONTRA,
EURODEBE,
BASEEURO,
- CONCEPTO,
- FACTURA,
+ CONCEPTO,
+ FACTURA,
IVA,
- AUXILIAR,
+ AUXILIAR,
SERIE,
FECHA_EX,
FECHA_OP,
@@ -54109,17 +52751,17 @@ BEGIN
FECREGCON
)
- SELECT
+ SELECT
vBookNumber ASIEN,
vBookDated FECHA,
tr.account SUBCTA,
'4330002067' CONTRA,
sum(dt.tax) EURODEBE,
- sum(dt.base) BASEEURO,
+ sum(dt.base) BASEEURO,
CONCAT('DUA nº',d.code) CONCEPTO,
d.id FACTURA,
dt.rate IVA,
- '*' AUXILIAR,
+ '*' AUXILIAR,
'D' SERIE,
d.issued FECHA_EX,
d.operated FECHA_OP,
@@ -54146,10 +52788,10 @@ BEGIN
WHERE ta.effectived <= vBookDated
AND taxAreaFk = 'WORLD'
ORDER BY ta.effectived DESC
- LIMIT 10000000000000000000
+ LIMIT 10000000000000000000
) tba
GROUP BY rate
- ) tr ON tr.rate = dt.rate
+ ) tr ON tr.rate = dt.rate
JOIN supplier s ON s.id = d.companyFk
JOIN country c ON c.id = s.countryFk
WHERE d.id = vDuaFk
@@ -54158,16 +52800,16 @@ BEGIN
SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte
FROM XDiario
WHERE ASIEN = vBookNumber;
-
+
UPDATE XDiario
SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA,
- EURODEBE = EURODEBE - vDiff
+ EURODEBE = EURODEBE - vDiff
WHERE id = vApunte;
UPDATE dua
SET ASIEN = vBookNumber
WHERE id = vDuaFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -54188,48 +52830,53 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTax_doRecalc`(vDuaFk INT)
BEGIN
/**
* Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry
- *
+ *
* @param vDuaFk Id del dua a recalcular
-**/
+ */
DELETE FROM duaTax
WHERE duaFk = vDuaFk;
-
- INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base)
- SELECT vDuaFk, supplierFk, taxClassFk, sum(sub.Base) as Base
+
+ INSERT INTO duaTax(duaFk, taxClassFk, base)
+ SELECT vDuaFk, taxClassFk, SUM(sub.totalBase)
FROM intrastat ist
JOIN
- (SELECT
- e.supplierFk,
- i.intrastatFk,
- CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) * di.amount/ tei.Base AS DECIMAL(10,2)) as Base
- FROM buy b
+ (SELECT i.intrastatFk,
+ CAST(SUM(b.quantity *
+ b.buyingValue *
+ de.customsValue /
+ de.value)
+ * di.totalAmount /
+ bi.totalAmount AS DECIMAL(10,2)
+ ) totalBase
+ FROM buy b
JOIN item i ON i.id = b.itemFk
JOIN entry e ON e.id = b.entryFk
JOIN duaEntry de ON de.entryFk = e.id
- JOIN
- (
- SELECT i.intrastatFk,
- CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) AS DECIMAL(10,2)) as Base
- FROM buy b
- JOIN item i ON i.id = b.itemFk
- JOIN entry e ON e.id = b.entryFk
- JOIN duaEntry de ON de.entryFk = e.id
- WHERE de.duaFk = vDuaFk
- GROUP BY i.intrastatFk
-
- ) tei ON tei.intrastatFk = i.intrastatFk
- JOIN
- (
- SELECT intrastatFk, sum(amount) as amount
- FROM duaIntrastat
- WHERE duaFk = vDuaFk
- GROUP BY intrastatFK
- ) di ON di.intrastatFk = i.intrastatFk
+ JOIN(
+ SELECT i.intrastatFk,
+ CAST(SUM(b.quantity *
+ b.buyingValue *
+ de.customsValue /
+ de.value) AS DECIMAL(10,2)
+ ) totalAmount
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN entry e ON e.id = b.entryFk
+ JOIN duaEntry de ON de.entryFk = e.id
+ WHERE de.duaFk = vDuaFk
+ GROUP BY i.intrastatFk
+ ) bi ON bi.intrastatFk = i.intrastatFk
+ JOIN(
+ SELECT intrastatFk, SUM(amount) totalAmount
+ FROM duaIntrastat
+ WHERE duaFk = vDuaFk
+ GROUP BY intrastatFK
+ ) di ON di.intrastatFk = i.intrastatFk
WHERE de.duaFk = vDuaFk
- GROUP BY e.supplierFk, i.intrastatFk
- HAVING Base
- ) sub ON ist.id = sub.intrastatFk
- GROUP BY ist.taxClassFk, sub.supplierFk;
+ GROUP BY i.intrastatFk
+ HAVING totalBase
+ )sub ON ist.id = sub.intrastatFk
+ GROUP BY ist.taxClassFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -54248,13 +52895,13 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ediTables_Update`()
BEGIN
-
- INSERT IGNORE INTO vn.genus(name)
+
+ INSERT IGNORE INTO vn.genus(name)
SELECT latin_genus_name
FROM edi.genus ;
- INSERT IGNORE INTO vn.specie(name)
- SELECT LCASE(latin_species_name)
+ INSERT IGNORE INTO vn.specie(name)
+ SELECT LCASE(latin_species_name)
FROM edi.specie ;
END ;;
DELIMITER ;
@@ -54294,71 +52941,71 @@ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
-
+
SET done = FALSE;
SET vEntryFk = 0;
-
+
FETCH cur1 INTO vId;
-
+
IF done THEN
LEAVE read_loop;
END IF;
-
+
SELECT IFNULL(e.id,0) INTO vEntryFk
FROM vn.entry e
JOIN vn.travel tr ON tr.id = e.travelFk
- JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
+ JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
AND ea.warehouseInFk = tr.warehouseInFk
AND ea.agencyModeFk = tr.agencyModeFk
AND ea.supplierFk = e.supplierFk
WHERE ea.id = vId
AND tr.landed = vLanded
LIMIT 1;
-
+
IF NOT vEntryFk THEN
-
+
SELECT IFNULL(e.id,0) INTO vEntryFk
FROM vn.entry e
JOIN vn.travel tr ON tr.id = e.travelFk
- JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
+ JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
AND ea.warehouseInFk = tr.warehouseInFk
AND ea.agencyModeFk = tr.agencyModeFk
WHERE ea.id = vId
AND tr.landed = vLanded
AND ea.supplierFk IS NULL
LIMIT 1;
-
+
END IF;
-
+
IF NOT vEntryFk THEN
-
+
SET vTravelFk = 0;
-
- SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
+
+ SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
FROM vn.travel tr
- JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
+ JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
AND ea.warehouseInFk = tr.warehouseInFk
AND ea.agencyModeFk = tr.agencyModeFk
WHERE ea.id = vId
AND tr.landed = vLanded;
-
+
IF NOT vTravelFk THEN
-
+
INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
SELECT vLanded, vLanded, warehouseInFk, warehouseOutFk, agencyModeFk
- FROM vn.ektEntryAssign
+ FROM vn.ektEntryAssign
WHERE id = vId;
-
- SELECT MAX(tr.id) INTO vTravelFk
+
+ SELECT MAX(tr.id) INTO vTravelFk
FROM vn.travel tr
- JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
+ JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
AND ea.warehouseInFk = tr.warehouseInFk
- AND ea.agencyModeFk = tr.agencyFk
+ AND ea.agencyModeFk = tr.agencyModeFk
WHERE ea.id = vId
AND tr.landed = vLanded;
-
+
END IF;
-
+
INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk)
SELECT vTravelFk, IFNULL(ea.supplierFk,s.id), c.id, cu.id
FROM vn.supplier s
@@ -54366,13 +53013,13 @@ OPEN cur1;
JOIN vn.currency cu ON cu.code = 'EUR'
JOIN vn.ektEntryAssign ea ON ea.id = vId
WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN';
-
- SELECT MAX(id) INTO vEntryFk
+
+ SELECT MAX(id) INTO vEntryFk
FROM vn.entry
WHERE travelFk = vTravelFk;
-
+
END IF;
-
+
UPDATE vn.ektEntryAssign
SET entryFk = vEntryFk
WHERE id = vId;
@@ -54380,7 +53027,7 @@ OPEN cur1;
END LOOP;
CLOSE cur1;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -54400,18 +53047,18 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `energyMeter_record`(vInput INT, vActiveTime INT)
BEGIN
DECLARE vConsumption INT;
-
+
SELECT consumption INTO vConsumption
FROM energyInput
WHERE input = vInput;
- INSERT INTO vn.energyMeter
- SET
- `input` = vInput,
- `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'),
+ INSERT INTO vn.energyMeter
+ SET
+ `input` = vInput,
+ `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'),
`activeTime` = vActiveTime,
`consumption` = CAST(IFNULL((vConsumption / 3600) * vActiveTime, 0) AS DECIMAL(10,2))
- ON DUPLICATE KEY UPDATE
+ ON DUPLICATE KEY UPDATE
`activeTime` = `activeTime` + vActiveTime,
`consumption` = `consumption` + CAST(VALUES(`consumption`) AS DECIMAL(10,2));
END ;;
@@ -54434,28 +53081,28 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entryDelivered`(vDated DATE, vEntry
BEGIN
DECLARE vTravelFk INT;
-
+
SELECT travelFk INTO vTravelFk
- FROM vn.entry
+ FROM vn.entry
WHERE id = vEntryFk;
-
+
IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN
-
+
UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated
WHERE id = vTravelFk;
-
+
ELSE
-
+
INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, ref, isDelivered, isReceived)
SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyModeFk, CONCAT(account.myUser_getName(),' ', vEntryFk), TRUE, TRUE
FROM vn.travel WHERE id = vTravelFk;
-
+
SELECT LAST_INSERT_ID() INTO vTravelFk;
-
- UPDATE vn.entry
- SET travelFk = vTravelFk
+
+ UPDATE vn.entry
+ SET travelFk = vTravelFk
WHERE id = vEntryFk;
-
+
END IF;
END ;;
@@ -54481,29 +53128,29 @@ BEGIN
DECLARE vEntry INT;
DECLARE vBucket VARCHAR(10);
DECLARE vSupplierFk INT;
-
+
SET vSupplierFk = IF (vLandingWarehouse = 1, 850, 963);
-- seleccionamos travel
SELECT t.id, e.id INTO vTravel, vEntry
FROM travel t LEFT JOIN entry e ON t.id = e.travelFk
- WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse
+ WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse
AND t.warehouseInFk = vLandingWarehouse AND t.agencyModeFk IS NULL AND e.supplierFk = vSupplierFk
- LIMIT 1;
-
+ LIMIT 1;
+
-- creamos el travel si es necesario
IF IFNULL(vTravel, FALSE) = FALSE THEN
INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk)
VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse);
SELECT LAST_INSERT_ID() INTO vTravel;
END IF;
-
+
-- creamos la Entrada si es necesario
IF IFNULL(vEntry, FALSE) = FALSE THEN
INSERT INTO entry (supplierFk, travelFk)
VALUES (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL'
SELECT LAST_INSERT_ID() INTO vEntry;
END IF;
-
+
-- creamos el cubo si es necesario
SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1;
IF vBucket IS NULL THEN
@@ -54513,7 +53160,7 @@ BEGIN
SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1;
END IF;
- INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3)
+ INSERT INTO buy(itemFk,quantity, entryFk, packagingFk, packing, stickers, buyingValue, price2, price3)
SELECT itemFk,
quantity,
vEntry,
@@ -54532,20 +53179,20 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_checkPackaging` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_checkPackaging`(vEntryFk INT)
BEGIN
/**
* Comprueba que los campos package y packaging no sean nulos
- *
+ *
* @param vEntryFk Id de entrada
*/
DECLARE vpackageOrPackingNull INT;
@@ -54553,7 +53200,7 @@ BEGIN
SELECT count(*) INTO vpackageOrPackingNull
FROM buy b
WHERE b.entryFk = vEntryFk
- AND (b.packing IS NULL OR b.packageFk IS NULL);
+ AND (b.packing IS NULL OR b.packagingFk IS NULL);
IF vpackageOrPackingNull THEN
CALL util.throw("packageOrPackingNull");
@@ -54629,7 +53276,8 @@ BEGIN
commission,
currencyFk,
companyFk,
- clonedFrom
+ clonedFrom,
+ typeFk
)
SELECT IFNULL(vTravelFk, travelFk),
supplierFk,
@@ -54639,7 +53287,8 @@ BEGIN
commission,
currencyFk,
companyFk,
- vSelf
+ vSelf,
+ typeFk
FROM entry
WHERE id = vSelf;
@@ -54716,7 +53365,7 @@ BEGIN
containerFk,
comissionValue,
packageValue,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -54739,7 +53388,7 @@ BEGIN
containerFk,
comissionValue,
packageValue,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -54797,7 +53446,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -54817,7 +53466,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -54847,7 +53496,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_getRate`(vSelf INT)
BEGIN
/**
- * Prepara una tabla con las tarifas aplicables en funcion de la fecha
+ * Prepara una tabla con las tarifas aplicables en funcion de la fecha
* y el almacén
*
* @param vSelf Id de la tabla entry
@@ -54857,7 +53506,7 @@ BEGIN
DECLARE vWarehouseFk INT;
SELECT t.landed, t.warehouseInFk INTO vDated, vWarehouseFk
- FROM entry e
+ FROM entry e
JOIN travel t ON t.id = e.travelFk
WHERE e.id = vSelf;
@@ -54870,6 +53519,225 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `entry_getTransfer` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_getTransfer`(
+ vSelf INT
+)
+BEGIN
+/**
+ * Retorna los artículos trasladables a partir de una entrada.
+ *
+ * @param vSelf Id de entrada
+ */
+ DECLARE vDateShipped DATE;
+ DECLARE vDateLanded DATE;
+ DECLARE vWarehouseIn INT;
+ DECLARE vWarehouseOut INT;
+ DECLARE vCalcVisible INT;
+ DECLARE vInventoryDate DATE DEFAULT getInventoryDate();
+
+ SELECT shipped, landed, warehouseInFk, warehouseOutFk
+ INTO vDateShipped, vDateLanded, vWarehouseIn, vWarehouseOut
+ FROM travel t
+ JOIN entry e ON e.travelFk = t.id
+ WHERE e.id = vSelf;
+
+ CALL rate_getPrices(vDateShipped, vWarehouseIn);
+
+ -- Traslado en almacen origen
+ CREATE OR REPLACE TEMPORARY TABLE tBuy
+ (PRIMARY KEY (itemFk), INDEX(buyFk))
+ ENGINE = MEMORY
+ SELECT *
+ FROM (
+ SELECT b.itemFk, b.id buyFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vInventoryDate AND vDateShipped
+ AND NOT b.isIgnored
+ AND b.price2 >= 0
+ ORDER BY (vWarehouseOut = t.warehouseInFk) DESC, t.landed DESC
+ LIMIT 10000000000000000000
+ ) sub
+ GROUP BY itemFk;
+
+ IF vDateShipped >= util.VN_CURDATE() THEN
+ CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseOut);
+
+ CREATE OR REPLACE TEMPORARY TABLE tItem (
+ `itemFk` int(10) unsigned NOT NULL,
+ `visible` int(11) NOT NULL DEFAULT 0,
+ `available` int(11) NOT NULL DEFAULT 0,
+ `visibleLanding` int(11) NOT NULL DEFAULT 0,
+ `availableLanding` int(11) NOT NULL DEFAULT 0,
+ UNIQUE INDEX i USING HASH (itemFk)
+ ) ENGINE = MEMORY;
+
+ INSERT INTO tItem(itemFk, visible)
+ SELECT item_id itemFk, visible
+ FROM `cache`.visible
+ WHERE calc_id = vCalcVisible
+ AND visible;
+
+ CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseIn);
+
+ INSERT INTO tItem(itemFk, visibleLanding)
+ SELECT item_id, `visible`
+ FROM `cache`.`visible` v
+ WHERE v.calc_id = vCalcVisible
+ AND v.`visible`
+ ON DUPLICATE KEY UPDATE visibleLanding = v.`visible`;
+
+ CALL vn2008.availableTraslate(vWarehouseOut, vDateShipped, NULL);
+
+ INSERT INTO tItem(itemFk, available)
+ SELECT a.item_id, a.available
+ FROM vn2008.availableTraslate a
+ WHERE a.available
+ ON DUPLICATE KEY UPDATE available = a.available;
+
+ CALL vn2008.availableTraslate(vWarehouseIn, vDateLanded, vWarehouseOut);
+
+ INSERT INTO tItem(itemFk, availableLanding)
+ SELECT a.item_id, a.available
+ FROM vn2008.availableTraslate a
+ WHERE a.available
+ ON DUPLICATE KEY UPDATE availableLanding = a.available;
+ ELSE
+ CALL item_getStock(vWarehouseOut, vDateShipped, NULL);
+
+ CREATE OR REPLACE TEMPORARY TABLE tItem
+ (UNIQUE INDEX i USING HASH (itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk,
+ `visible`,
+ available,
+ 0 visibleLanding,
+ 0 availableLanding
+ FROM tmp.itemList;
+ END IF;
+
+ CALL buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded);
+
+ CREATE OR REPLACE TEMPORARY TABLE tTransfer
+ ENGINE = MEMORY
+ SELECT it.code `type`,
+ it.categoryFk,
+ i.typeFk,
+ i.id itemFk,
+ i.name item,
+ i.`size`,
+ i.category,
+ i.inkFk,
+ o.code originCode,
+ b2.quantity,
+ i.stems,
+ CAST(ti.visible AS DECIMAL(10,0)) vis1,
+ CAST(ti.available AS DECIMAL(10,0)) ava1,
+ CAST(ti.visibleLanding AS DECIMAL(10,0)) vis2,
+ CAST(ti.availableLanding AS DECIMAL(10,0)) ava2,
+ COALESCE(b2.`grouping`, b.`grouping`) `grouping`,
+ COALESCE(b2.packing, b.packing) packing,
+ COALESCE(b3.groupingMode, b2.groupingMode, b.groupingMode) package,
+ IFNULL(p.name, s.nickname) productor,
+ TRUE tinta,
+ b.packagingFk,
+ b2.id buyFk,
+ b2.stickers,
+ b.ektFk,
+ it.workerFk,
+ pa.volume,
+ IFNULL(pa.width, 0) width,
+ IFNULL(pa.`depth`, 0) `depth`,
+ IFNULL(pa.height, 0) height,
+ IFNULL(b.buyingValue, 0) buyingValue,
+ IFNULL(b.comissionValue, 0) comissionValue,
+ IFNULL(b.freightValue, 0) freightValue,
+ am.m3,
+ e.commission,
+ pa.isPackageReturnable,
+ IFNULL(pa2.value, pa.value) `value`,
+ r.rate3 r3,
+ r.rate2 r2,
+ it.promo,
+ b.`grouping` groupingOrigin,
+ b.packing packingOrigin,
+ b.id buyFkOrigin,
+ pa.returnCost,
+ b.weight
+ FROM item i
+ JOIN tItem ti ON ti.itemFk = i.id
+ LEFT JOIN producer p ON p.id = i.producerFk
+ LEFT JOIN itemType it ON it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN tBuy lb ON lb.itemFk = i.id
+ LEFT JOIN buy b ON b.id = lb.buyFk
+ LEFT JOIN packaging pa ON pa.id = b.packagingFk
+ LEFT JOIN entry e2 ON e2.id = b.entryFk
+ LEFT JOIN supplier s ON s.id = e2.supplierFk
+ LEFT JOIN entry e ON e.id = vSelf
+ LEFT JOIN travel tr ON tr.id = e.travelFk
+ LEFT JOIN agencyMode am ON am.id = tr.agencyModeFk
+ LEFT JOIN buy b2 ON b2.itemFk = i.id
+ AND b2.entryFk = vSelf
+ LEFT JOIN packaging pa2 ON pa2.id = b.packagingFk
+ LEFT JOIN tmp.rate r ON TRUE
+ LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id
+ LEFT JOIN buy b3 ON b3.id = bufi.buyFk
+ WHERE ic.display
+ AND NOT e.isRaid
+ AND (ti.visible OR ti.available)
+ ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name;
+
+ CREATE INDEX tIndex USING HASH ON tTransfer (itemFk);
+
+ SELECT *,
+ quantity - MOD(quantity , `grouping`) subQuantity,
+ MOD(quantity, `grouping`) soll,
+ ROUND((IF(volume > 0,volume, width * `depth` *
+ IF(height = 0, `size` + 10, height))) /
+ packing, 0) cm3,
+ buyingValue + comissionValue + freightValue cost,
+ @carriage := ROUND((IF(volume > 0, volume, width * `depth` *
+ IF(height = 0, `size` + 10, height))) *
+ m3 / 1000000 / Packing, 3) carriage,
+ @comission := ROUND((buyingValue + comissionValue + freightValue) *
+ commission / 100, 3) commission,
+ ROUND(@packaging := (returnCost + IF(isPackageReturnable, 0, value))
+ / packing, 3) packaging,
+ @cost := IFNULL((buyingValue + comissionValue + freightValue), 0) +
+ IFNULL(@packaging, 0) +
+ IFNULL(@carriage, 0) +
+ IFNULL(@comission, 0) expense,
+ @rate3 := ROUND(@cost / ( (100 - r3 - promo) / 100), 2) rate3,
+ ROUND(@rate3 * (1 + ((r2 - r3)/100)), 2) rate2,
+ FALSE selected
+ FROM tTransfer;
+
+ DROP TEMPORARY TABLE IF EXISTS
+ tTransfer,
+ tItem,
+ tBuy,
+ tmp.buyUltimateFromInterval,
+ tmp.rate,
+ tmp.itemList;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_lock` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -54915,6 +53783,7 @@ BEGIN
*
* @param vSelf Identificador de entry
* @param vDays Número de dias a futuro que se quiere la nueva entrada
+ * @param vChangeEntry Si se modifica la entrada original
*
* @return vNewEntryFk Identificador de la nueva entrada
*/
@@ -54922,8 +53791,12 @@ BEGIN
DECLARE vTravelFk INT;
DECLARE vInvoiceAmountOldEntryFk DECIMAL(10,2);
DECLARE vInvoiceAmountNewEntry DECIMAL(10,2);
+ DECLARE vIsOrdered BOOL;
+ DECLARE vIsConfirmed BOOL;
+ DECLARE vInvoiceNumber VARCHAR(50);
+ DECLARE vTypeFk VARCHAR(100);
- SELECT travelFk INTO vTravelFk
+ SELECT travelFk, isOrdered, isConfirmed, invoiceNumber, typeFk INTO vTravelFk, vIsOrdered, vIsConfirmed, vInvoiceNumber, vTypeFk
FROM entry
WHERE id = vSelf;
@@ -54932,7 +53805,11 @@ BEGIN
UPDATE entry e
SET e.travelFk = vNewTravelFk,
- e.evaNotes = CONCAT('No impresas de: ', vSelf, ' ', IFNULL(e.evaNotes,''))
+ e.evaNotes = CONCAT('No impresas de: ', vSelf, ' ', IFNULL(e.evaNotes,'')),
+ e.isOrdered = vIsOrdered,
+ e.isConfirmed = vIsConfirmed,
+ e.invoiceNumber = vInvoiceNumber,
+ e.typeFk = vTypeFk
WHERE e.id = vNewEntryFk;
IF vChangeEntry THEN
@@ -54955,7 +53832,7 @@ BEGIN
containerFk,
comissionValue,
packageValue,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -54976,7 +53853,7 @@ BEGIN
containerFk,
comissionValue,
packageValue,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -54987,7 +53864,7 @@ BEGIN
FROM buy b
WHERE b.entryFk = vSelf
AND b.printedStickers != b.stickers;
-
+
IF vChangeEntry THEN
UPDATE buy
SET stickers = printedStickers,
@@ -54999,7 +53876,7 @@ BEGIN
FROM item i
WHERE i.description = 'MISFIT'
LIMIT 1;
-
+
INSERT INTO buy(entryFk,
itemFk,
quantity,
@@ -55014,7 +53891,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55033,7 +53910,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55066,7 +53943,7 @@ BEGIN
UPDATE entry
SET gestDocFk = (SELECT gestDocFk FROM entry WHERE id = vSelf LIMIT 1)
WHERE id = vNewEntryFk;
-
+
INSERT INTO duaEntry (duaFk, entryFk)
SELECT duaFk, vNewEntryFk FROM duaEntry WHERE entryFk = vSelf LIMIT 1;
END ;;
@@ -55140,12 +54017,12 @@ BEGIN
*/
DECLARE v_done BOOL DEFAULT FALSE;
DECLARE vEntryFk INTEGER;
-
+
DECLARE vCur CURSOR FOR
SELECT id FROM tmp.recalcEntryCommision;
DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET v_done = TRUE;
+ SET v_done = TRUE;
OPEN vCur;
@@ -55156,7 +54033,7 @@ BEGIN
IF v_done THEN
LEAVE l;
END IF;
-
+
CALL vn2008.buy_tarifas_entry(vEntryFk);
END LOOP;
@@ -55181,7 +54058,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitByShelving`(vShelvingFk
BEGIN
/**
* Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula
- *
+ *
* @param vShelvingFk Identificador de vn.shelving
* @param vFromEntryFk Entrada origen
* @param vToEntryFk Entrada destino
@@ -55191,49 +54068,49 @@ BEGIN
DECLARE vBuyStickers INT;
DECLARE vDone BOOLEAN DEFAULT FALSE;
- DECLARE cur CURSOR FOR
+ DECLARE cur CURSOR FOR
SELECT bb.id buyFk,
FLOOR(ish.visible / ish.packing) ishStickers,
bb.stickers buyStickers
FROM vn.itemShelving ish
- JOIN (SELECT b.id, b.itemFk, b.stickers
- FROM vn.buy b
+ JOIN (SELECT b.id, b.itemFk, b.stickers
+ FROM vn.buy b
WHERE b.entryFk = vFromEntryFk
ORDER BY b.stickers DESC
- LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
+ LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
AND bb.stickers >= FLOOR(ish.visible / ish.packing)
WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci
GROUP BY ish.id;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
- -- Cantidades de la matrícula que exceden la de las entradas
- SELECT ish.itemFk,
- i.longName,
+
+ -- Cantidades de la matrícula que exceden la de las entradas
+ SELECT ish.itemFk,
+ i.longName,
FLOOR(ish.visible / ish.packing) AS etiEnMatricula,
bb.stickers etiEnEntrada
FROM vn.itemShelving ish
- JOIN vn.item i ON i.id = ish.itemFk
- LEFT JOIN (SELECT b.id, b.itemFk, b.stickers
- FROM vn.buy b
+ JOIN vn.item i ON i.id = ish.itemFk
+ LEFT JOIN (SELECT b.id, b.itemFk, b.stickers
+ FROM vn.buy b
WHERE b.entryFk = vFromEntryFk
ORDER BY b.stickers DESC
LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci
AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing)
GROUP BY ish.id;
-
+
OPEN cur;
read_loop: LOOP
SET vDone = FALSE;
-
+
FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers;
-
+
IF vDone THEN
LEAVE read_loop;
END IF;
-
+
IF vIshStickers = vBuyStickers THEN
UPDATE vn.buy
SET entryFk = vToEntryFk
@@ -55241,9 +54118,9 @@ BEGIN
ELSE
UPDATE vn.buy
SET stickers = stickers - vIshStickers,
- quantity = stickers * packing
+ quantity = stickers * packing
WHERE id = vBuyFk;
-
+
INSERT INTO vn.buy(entryFk,
itemFk,
quantity,
@@ -55258,7 +54135,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55285,7 +54162,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55323,16 +54200,16 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitMisfit`(vSelf INT)
BEGIN
-
+
/* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original
* a la nueva
*/
-
+
DECLARE vNewEntryFk INT;
DECLARE vBuyFk INT;
SELECT MAX(b.id) INTO vBuyFk
- FROM vn.buy b
+ FROM vn.buy b
JOIN vn.item i ON i.id = b.itemFk
WHERE b.entryFk = vSelf
AND i.description = 'MISFIT';
@@ -55341,17 +54218,17 @@ BEGIN
SELECT supplierFk, dated, travelFk, currencyFk, companyFk
FROM vn.entry e
WHERE e.id = vSelf;
+
+ SET vNewEntryFk = LAST_INSERT_ID();
- SET vNewEntryFk = LAST_INSERT_ID();
-
- UPDATE vn.buy b
+ UPDATE vn.buy b
SET b.entryFk = vNewEntryFk
WHERE b.entryFk = vSelf
AND b.id > vBuyFk;
-
+
SELECT vNewEntryFk;
-
-
+
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -55374,7 +54251,7 @@ BEGIN
* Unlock the indicated entry
* @vSelf params entry id
*/
- UPDATE `entry`
+ UPDATE `entry`
SET lockerUserFk = NULL,
locked = NULL
WHERE id = vSelf;
@@ -55405,21 +54282,21 @@ BEGIN
DECLARE vComission INT;
CREATE OR REPLACE TEMPORARY TABLE tmp.recalcEntryCommision
- SELECT e.id
+ SELECT e.id
FROM vn.entry e
JOIN vn.travel t ON t.id = e.travelFk
- JOIN vn.warehouse w ON w.id = t.warehouseInFk
+ JOIN vn.warehouse w ON w.id = t.warehouseInFk
WHERE t.shipped >= util.VN_CURDATE()
AND e.currencyFk = vCurrency;
SET vComission = currency_getCommission(vCurrency);
- UPDATE vn.entry e
+ UPDATE vn.entry e
JOIN tmp.recalcEntryCommision tmp ON tmp.id = e.id
SET e.commission = vComission;
- SELECT `name` INTO vCurrencyName
- FROM currency
+ SELECT `name` INTO vCurrencyName
+ FROM currency
WHERE id = vCurrency;
CALL entry_recalc();
@@ -55438,246 +54315,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `errorProduction_add` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_add`(
- vAction VARCHAR(25),
- vDatedFrom DATETIME,
- vDatedTo DATETIME)
-BEGIN
-/**
- * Rellena la tabla vn.errorProduction
- *
- * @param vAction Accion que se quiere añadir
- * @param vDatedFrom Fecha desde
- * @param vDatedTo Fecha hasta
- */
- DECLARE vDepartment VARCHAR(255);
-
- CASE
- WHEN vAction = 'SACAR' THEN
- SET vDepartment = 'Sacadores';
- WHEN vAction = 'ENCAJAR' THEN
- SET vDepartment = 'Encajadores';
- WHEN vAction = 'CONTROLAR' THEN
- SET vDepartment = 'Revisadores';
- END CASE;
-
- IF (vDepartment = 'Encajadores') THEN
- CREATE OR REPLACE TEMPORARY TABLE total
- ENGINE = MEMORY
- SELECT e.workerFk,
- COUNT(DISTINCT t.id) ticketCount,
- COUNT(s.id) lineCount
- FROM expedition e
- JOIN ticket t ON e.ticketFk = t.id
- JOIN sale s ON s.ticketFk = t.id
- WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
- GROUP BY e.workerFk;
- ELSE
- CREATE OR REPLACE TEMPORARY TABLE total
- ENGINE = MEMORY
- SELECT st.workerFk,
- COUNT(DISTINCT t.id) ticketCount,
- COUNT(s.id) lineCount
- FROM saleTracking st
- JOIN `state` s2 ON s2.id = st.stateFk
- JOIN sale s ON s.id = st.saleFk
- JOIN ticket t ON s.ticketFk = t.id
- WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo)
- AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED')
- GROUP BY st.workerFk;
- END IF;
-
- CALL timeControl_calculateAll(vDatedFrom, vDatedTo);
-
- CREATE OR REPLACE TEMPORARY TABLE errorsByClaim
- ENGINE = MEMORY
- SELECT COUNT(c.ticketFk) errors,
- cd.workerFk
- FROM claimDevelopment cd
- JOIN claim c ON cd.claimFk = c.id
- JOIN ticket t ON c.ticketFk = t.id
- JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
- WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
- AND cr.description = vDepartment
- GROUP BY cd.workerFk;
-
- CREATE OR REPLACE TEMPORARY TABLE volume
- ENGINE = MEMORY
- SELECT SUM(w.volume) volume,
- w.workerFk
- FROM bs.workerProductivity w
- WHERE w.dated BETWEEN vDatedFrom AND vDatedTo
- GROUP BY w.workerFk;
-
- CREATE OR REPLACE TEMPORARY TABLE errorsByChecker
- ENGINE = MEMORY
- SELECT sub1.workerFk, COUNT(id) errors
- FROM (
- SELECT st.workerFk,
- t.id
- FROM saleMistake sm
- JOIN saleTracking st ON sm.saleFk = st.saleFk
- JOIN `state` s2 ON s2.id = st.stateFk
- JOIN sale s ON s.id = sm.saleFk
- JOIN ticket t on t.id = s.ticketFk
- WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo)
- AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED')
- ) sub1
- GROUP BY sub1.workerFk;
-
- CREATE OR REPLACE TEMPORARY TABLE expeditionErrors
- ENGINE = MEMORY
- SELECT COUNT(t.id) errors,
- e.workerFk
- FROM vn.expeditionMistake pm
- JOIN vn.expedition e ON e.id = pm.expeditionFk
- JOIN vn.ticket t ON t.id = e.ticketFk
- WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
- GROUP BY e.workerFk;
-
- IF (vDepartment = 'Sacadores') THEN
-
- INSERT INTO errorProduction(userFk,
- firstname,
- lastname,
- rol,
- ticketNumber,
- lineNumber,
- error,
- volume,
- hourStart,
- hourEnd,
- hourWorked,
- dated)
- SELECT w.id,
- w.firstName,
- w.lastName,
- vDepartment,
- t.ticketCount totalTickets,
- t.lineCount,
- IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) errors,
- IF(vDepartment = 'Revisadores', NULL, v.volume) volume,
- SUBSTRING(tc.timed, 1, 5) hourStart,
- SUBSTRING(tc.timed, LENGTH(tc.timed)-4, 5) hourEnd,
- IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked,
- vDatedFrom dated
- FROM total t
- LEFT JOIN worker w ON w.id = t.workerFk
- LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk
- LEFT JOIN errorsByClaim ec ON ec.workerFk = t.workerFk
- LEFT JOIN volume v ON v.workerFk = t.workerFk
- LEFT JOIN errorsByChecker ec2 ON ec2.workerFk = t.workerFk
- JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores
- FROM vn.collection c
- JOIN vn.state s ON s.id = c.stateFk
- JOIN vn.train tn ON tn.id = c.trainFk
- JOIN vn.worker w ON w.id = c.workerFk
- WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id
- GROUP BY w.id;
-
- CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores
- ENGINE = MEMORY
- SELECT COUNT(c.ticketFk) errors,
- tt.workerFk
- FROM claimDevelopment cd
- JOIN claim c ON cd.claimFk = c.id
- JOIN ticket t ON c.ticketFk = t.id
- JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
- JOIN ticketTracking tt ON tt.ticketFk = t.id
- JOIN `state` s ON s.id = tt.stateFk
- WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
- AND cr.description = 'Revisadores'
- AND s.code = 'ON_PREPARATION'
- GROUP BY workerFk;
-
- UPDATE errorProduction ep
- JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk
- SET ep.error = ep.error + ipe.errors
- WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores';
-
- DROP TEMPORARY TABLE itemPickerErrors;
- ELSE
- INSERT INTO errorProduction(userFk,
- firstname,
- lastname,
- rol,
- ticketNumber,
- lineNumber,
- error,
- volume,
- hourStart,
- hourEnd,
- hourWorked,
- dated)
- SELECT w.id,
- w.firstName,
- w.lastName,
- vDepartment,
- t.ticketCount totalTickets,
- t.lineCount,
- IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) + IFNULL(pe.errors,0) errors,
- IF(vDepartment = 'Revisadores', NULL, v.volume) volume,
- SUBSTRING(tc.timed, 1, 5) hourStart,
- SUBSTRING(tc.timed, LENGTH(tc.timed)-4, 5) hourEnd,
- IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked,
- vDatedFrom dated
- FROM total t
- LEFT JOIN worker w ON w.id = t.workerFk
- LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk
- LEFT JOIN errorsByClaim ec ON ec.workerFk = t.workerFk
- LEFT JOIN volume v ON v.workerFk = t.workerFk
- LEFT JOIN errorsByChecker ec2 ON ec2.workerFk = t.workerFk
- LEFT JOIN expeditionErrors pe ON pe.workerFk = t.workerFk
- GROUP BY w.id;
- END IF;
-
- DROP TEMPORARY TABLE total,
- errorsByClaim,
- volume,
- errorsByChecker,
- expeditionErrors;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `errorProduction_addLauncher` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_addLauncher`()
-BEGIN
- DECLARE vDatedFrom DATETIME;
- DECLARE vDatedTo DATETIME;
-
- SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo;
-
- CALL vn.errorProduction_add('SACAR', vDatedFrom, vDatedTo);
- CALL vn.errorProduction_add('ENCAJAR', vDatedFrom, vDatedTo);
- CALL vn.errorProduction_add('CONTROLAR', vDatedFrom, vDatedTo);
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionGetFromRoute` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -55695,7 +54332,7 @@ BEGIN
DECLARE vRouteFk INT DEFAULT 0;
SELECT t.routeFk INTO vRouteFk
- FROM vn.expedition exp
+ FROM vn.expedition exp
INNER JOIN ticket t on t.id = exp.ticketFk
WHERE exp.id = vExpeditionFk;
@@ -55898,14 +54535,14 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT)
BEGIN
/**
- * Calls the report_print procedure and passes it
+ * Calls the report_print procedure and passes it
* the necessary parameters for printing.
*
* @param vSelf expeditioPallet id.
*/
DECLARE vPrinterFk INT;
DECLARE vUserFk INT DEFAULT account.myUser_getId();
-
+
SELECT o.labelerFk INTO vPrinterFk
FROM operator o
WHERE o.workerFk = vUserFk;
@@ -55972,22 +54609,22 @@ BEGIN
DECLARE vTotal INT DEFAULT 0;
IF vPalletFk = 0 THEN -- Nuevo pallet
-
- INSERT INTO vn.expeditionPallet(truckFk)
+
+ INSERT INTO vn.expeditionPallet(truckFk)
VALUES(vTruckFk);
-
+
SELECT LAST_INSERT_ID() INTO vPalletFk;
-
+
END IF;
-
+
SELECT COUNT(expeditionFk) INTO vTotal FROM vn.expeditionScan WHERE palletFk = vPalletFk;
-
+
IF vTotal <> 0 THEN
- SELECT expeditionFk,
+ SELECT expeditionFk,
palletFk
- FROM vn.expeditionScan
+ FROM vn.expeditionScan
WHERE palletFk = vPalletFk;
- ELSE
+ ELSE
SELECT 0 expeditionFk,vPalletFk palletFk;
END IF;
END ;;
@@ -56060,12 +54697,12 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT)
BEGIN
-
- REPLACE vn.expeditionScan(expeditionFk, palletFk)
+
+ REPLACE vn.expeditionScan(expeditionFk, palletFk)
VALUES(vExpeditionFk, vPalletFk);
-
+
SELECT LAST_INSERT_ID() INTO vPalletFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -56084,32 +54721,32 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_add`(vParam INT, vStateCode VARCHAR(100))
BEGIN
-
+
/**
* Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro
- *
+ *
* @param vParam Identificador de vn.expedition o de vn.route
* @param vStateCode Corresponde a vn.expeditionStateType.code
*/
-
+
IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN
-
+
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT e.id, est.id
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.expeditionStateType est ON est.code = vStateCode
WHERE t.routeFk = vParam;
-
+
ELSE
-
+
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT vParam, est.id
FROM vn.expeditionStateType est
WHERE est.code = vStateCode;
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -56141,7 +54778,7 @@ BEGIN
SELECT e.id, est.id
FROM vn.expedition e
JOIN vn.expeditionStateType est ON est.code = vStateCode
- JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.addressFk = vAdressFk AND t.routeFk = vRouteFk;
END ;;
@@ -56162,14 +54799,14 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByExpedition`(vExpeditionFk INT, vStateCode VARCHAR(100))
BEGIN
-
+
/**
* Inserta nuevos registros en la tabla vn.expeditionState
- *
+ *
* @param vExpeditionFk Identificador de vn.expedition
* @param vStateCode Corresponde a vn.expeditionStateType.code
*/
-
+
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT vExpeditionFk, est.id
FROM vn.expeditionStateType est
@@ -56195,7 +54832,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByPallet`(vPalle
BEGIN
/**
* Inserta nuevos registros en la tabla vn.expeditionState
- *
+ *
* @param vPalletFk Identificador de vn.expedition
* @param vStateCode Corresponde a vn.expeditionStateType.code
*/
@@ -56212,7 +54849,7 @@ BEGIN
IF NOT hasExpeditions THEN
DROP TEMPORARY TABLE tExpeditionScan;
- CALL util.throw('palletDoesNotExist');
+ CALL util.throw('palletDoesNotExist');
END IF;
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
@@ -56237,21 +54874,21 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByRoute`(vRouteFk INT, vStateCode VARCHAR(100))
BEGIN
-
+
/**
* Inserta nuevos registros en la tabla vn.expeditionState, por rutas
- *
+ *
* @param vRouteFk Identificador de vn.route
* @param vStateCode Corresponde a vn.expeditionStateType.code
*/
-
+
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT e.id, est.id
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.expeditionStateType est ON est.code = vStateCode
WHERE t.routeFk = vRouteFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -56293,8 +54930,8 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_List`()
BEGIN
- SELECT id truckFk,
- eta,
+ SELECT id truckFk,
+ eta,
description Destino
FROM expeditionTruck
WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
@@ -56338,7 +54975,7 @@ BEGIN
JOIN address a ON t.addressFk = a.id
JOIN route r ON r.id = t.routeFk
LEFT JOIN warehouse w ON t.warehouseFk = w.id
- LEFT JOIN (SELECT sub.ticketFk,
+ LEFT JOIN (SELECT sub.ticketFk,
CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeConcat
FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items
FROM ticket t
@@ -56369,7 +55006,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_getState`(vExpeditionFk INT)
BEGIN
-
+
DECLARE vTicketsPendientes INT;
DECLARE vEtiquetasTotales INT;
DECLARE vEtiquetasEscaneadas INT;
@@ -56379,24 +55016,24 @@ BEGIN
FROM vn.ticket t
JOIN vn.expedition e ON e.ticketFk = t.id
WHERE e.id = vExpeditionFk;
-
+
SELECT COUNT(*) INTO vTicketsPendientes
FROM vn.ticket t
LEFT JOIN vn.expedition e ON e.ticketFk = t.id
WHERE t.routeFk = vRouteFk
AND ISNULL(e.id);
-
+
SELECT COUNT(*) INTO vEtiquetasTotales
- FROM vn.expedition e
+ FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vRouteFk;
-
+
SELECT COUNT(*) INTO vEtiquetasEscaneadas
- FROM vn.expeditionScan es
+ FROM vn.expeditionScan es
JOIN vn.expedition e ON e.id = es.expeditionFk
- JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vRouteFk;
-
+
SELECT e.ticketFk ticket,
t.nickname cliente,
a.city ciudad,
@@ -56410,17 +55047,17 @@ BEGIN
vTicketsPendientes AS ticketsPendientes,
vEtiquetasTotales AS etiquetasTotales,
vEtiquetasEscaneadas AS etiquetasEscaneadas
- FROM vn.expedition e
- JOIN vn.ticket t ON t.id = e.ticketFk
- JOIN vn.address a ON a.id = t.addressFk
- JOIN vn.province p ON p.id = a.provinceFk
- JOIN vn.`zone`z ON z.id = t.zoneFk
- LEFT JOIN vn.route r ON r.id = t.routeFk
- LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
- LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
- LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.address a ON a.id = t.addressFk
+ JOIN vn.province p ON p.id = a.provinceFk
+ JOIN vn.`zone`z ON z.id = t.zoneFk
+ LEFT JOIN vn.route r ON r.id = t.routeFk
+ LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
+ LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
+ LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
WHERE e.id = vExpeditionFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -56439,12 +55076,12 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_StateGet`(vExpeditionFk INT)
BEGIN
-
+
/* Devuelve una "ficha" con todos los datos relativos a la expedición
- *
- * param vExpeditionFk
+ *
+ * param vExpeditionFk
*/
-
+
DECLARE vTicketsPendientes INT;
DECLARE vEtiquetasTotales INT;
DECLARE vEtiquetasEscaneadas INT;
@@ -56455,34 +55092,34 @@ BEGIN
FROM vn.ticket t
JOIN vn.expedition e ON e.ticketFk = t.id
WHERE e.id = vExpeditionFk;
-
+
SELECT COUNT(*) INTO vTicketsPendientes
FROM vn.ticket t
LEFT JOIN vn.expedition e ON e.ticketFk = t.id
WHERE t.routeFk = vRouteFk
AND ISNULL(e.id);
-
+
SELECT COUNT(*) INTO vEtiquetasTotales
- FROM vn.expedition e
+ FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vRouteFk;
-
+
SELECT COUNT(*) INTO vEtiquetasEscaneadas
- FROM vn.expeditionScan es
+ FROM vn.expeditionScan es
JOIN vn.expedition e ON e.id = es.expeditionFk
- JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vRouteFk;
-
+
SELECT COUNT(*) INTO vEtiquetasLeidasSorter
- FROM srt.expedition e
+ FROM srt.expedition e
JOIN vn.expedition ve ON ve.id = e.id
LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id
- JOIN vn.ticket t ON t.id = ve.ticketFk
+ JOIN vn.ticket t ON t.id = ve.ticketFk
WHERE t.routeFk = vRouteFk
AND e.created != e.updated
- AND ISNULL(es.expeditionFk);
-
-
+ AND ISNULL(es.expeditionFk);
+
+
SELECT e.ticketFk ticket,
t.nickname cliente,
a.city ciudad,
@@ -56497,17 +55134,17 @@ BEGIN
vEtiquetasTotales AS etiquetasTotales,
vEtiquetasEscaneadas AS etiquetasEscaneadas,
vEtiquetasLeidasSorter AS etiquetasSorter
- FROM vn.expedition e
- JOIN vn.ticket t ON t.id = e.ticketFk
- JOIN vn.address a ON a.id = t.addressFk
- JOIN vn.province p ON p.id = a.provinceFk
- JOIN vn.`zone`z ON z.id = t.zoneFk
- LEFT JOIN vn.route r ON r.id = t.routeFk
- LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
- LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
- LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.address a ON a.id = t.addressFk
+ JOIN vn.province p ON p.id = a.provinceFk
+ JOIN vn.`zone`z ON z.id = t.zoneFk
+ LEFT JOIN vn.route r ON r.id = t.routeFk
+ LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
+ LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
+ LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
WHERE e.id = vExpeditionFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -56543,147 +55180,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `fustControl` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControl`(vFromDated DATE, vToDated DATE)
-BEGIN
-
- DECLARE vSijsnerClientFk INT DEFAULT 19752;
-
- DECLARE vDateStart DATETIME;
- DECLARE vDateEnd DATETIME;
-
- SET vDateStart = vFromDated;
- SET vDateEnd = util.Dayend(vToDated);
-
- SELECT p.id FustCode,
- CAST(sent.stucks AS DECIMAL(10,0)) FH,
- CAST(tp.stucks AS DECIMAL(10,0)) Tickets,
- CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner,
- CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo
- FROM vn.packaging p
- LEFT JOIN (
- SELECT FustCode, sum(fustQuantity) stucks
- FROM (
- SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity
- FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.warehouse w ON w.id = t.warehouseFk
- JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk
- JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk
- JOIN vn.buy b ON b.id = lb.buy_id
- JOIN vn.packaging p ON p.id = b.packageFk
- LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id
- JOIN vn.address a ON a.id = t.addressFk
- JOIN vn.province p2 ON p2.id = a.provinceFk
- JOIN vn.country c ON c.id = p2.countryFk
- WHERE t.shipped BETWEEN vDateStart AND vDateEnd
- AND wa.name = 'VNH'
- AND p.isPackageReturnable
- AND c.country = 'FRANCIA') sub
- GROUP BY FustCode) sent ON sent.FustCode = p.id
- LEFT JOIN (
- SELECT FustCode, sum(quantity) stucks
- FROM (
- SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity
- FROM vn.ticketPackaging tp
- JOIN vn.ticket t ON t.id = tp.ticketFk
- JOIN vn.warehouse w ON w.id = t.warehouseFk
- JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk
- JOIN vn.packaging p ON p.id = tp.packagingFk
- LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id
- JOIN vn.address a ON a.id = t.addressFk
- JOIN vn.province p2 ON p2.id = a.provinceFk
- JOIN vn.country c ON c.id = p2.countryFk
- WHERE t.shipped BETWEEN vDateStart AND vDateEnd
- AND wa.name = 'VNH'
- AND p.isPackageReturnable
- AND c.country = 'FRANCIA'
- AND t.clientFk != vSijsnerClientFk
- AND tp.quantity > 0) sub
- GROUP BY FustCode) tp ON tp.FustCode = p.id
- LEFT JOIN (
- SELECT FustCode, sum(quantity) stucks
- FROM (
- SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity
- FROM vn.ticketPackaging tp
- JOIN vn.ticket t ON t.id = tp.ticketFk
- JOIN vn.warehouse w ON w.id = t.warehouseFk
- JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk
- JOIN vn.packaging p ON p.id = tp.packagingFk
- LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id
- WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd )
- AND wa.name = 'VNH'
- AND p.isPackageReturnable
- AND t.clientFk = vSijsnerClientFk) sub
- GROUP BY FustCode) sj ON sj.FustCode = p.id
- WHERE sent.stucks
- OR tp.stucks
- OR sj.stucks;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `fustControlDetail` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControlDetail`(vFromDated DATE, vToDated DATE)
-BEGIN
-
- DECLARE vSijsnerClientFk INT DEFAULT 19752;
-
- DECLARE vDateStart DATETIME;
- DECLARE vDateEnd DATETIME;
-
- SET vDateStart = vFromDated;
- SET vDateEnd = util.Dayend(vToDated);
-
- SELECT a.nickname shopName,
- a.city ,
- IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode,
- tp.quantity,
- tp.ticketFk,
- CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange
- FROM vn.ticketPackaging tp
- JOIN vn.ticket t ON t.id = tp.ticketFk
- JOIN vn.warehouse w ON w.id = t.warehouseFk
- JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk
- JOIN vn.packaging p ON p.id = tp.packagingFk
- LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id
- JOIN vn.address a ON a.id = t.addressFk
- JOIN vn.province p2 ON p2.id = a.provinceFk
- JOIN vn.country c ON c.id = p2.countryFk
- WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated)
- AND wa.name = 'VNH'
- AND p.isPackageReturnable
- AND c.country = 'FRANCIA'
- AND t.clientFk != vSijsnerClientFk
- AND tp.quantity > 0;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `fv_pca` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -56701,8 +55197,8 @@ DECLARE vTicketFk INT;
DECLARE vSaleFk INT;
DECLARE vClonTicket INT DEFAULT 0;
-DECLARE cur1 CURSOR FOR
-SELECT s.ticketFk, s.id
+DECLARE cur1 CURSOR FOR
+SELECT s.ticketFk, s.id
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.item i ON i.id = s.itemFk
@@ -56718,17 +55214,17 @@ OPEN cur1;
FETCH cur1 INTO vTicketFk, vSaleFk;
WHILE done = 0 DO
-
+
SELECT t.id INTO vClonTicket
FROM vn.ticket t
JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped)
WHERE t.warehouseFk = 44
LIMIT 1;
-
+
SELECT vTicketFk, vClonTicket;
-
+
IF vClonTicket = 0 THEN
-
+
INSERT INTO ticket (
clientFk,
shipped,
@@ -56756,12 +55252,12 @@ FETCH cur1 INTO vTicketFk, vSaleFk;
zonePrice,
zoneBonus,
routeFk
-
+
FROM ticket
WHERE id = vTicketFk;
SET vClonTicket = LAST_INSERT_ID();
-
+
SELECT 'lstID', vClonTicket;
/*
INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
@@ -56771,20 +55267,20 @@ FETCH cur1 INTO vTicketFk, vSaleFk;
WHERE t.id = vClonTicket;
*/
INSERT INTO ticketLog
- SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert',
+ SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert',
description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk);
-
+
END IF;
-
+
UPDATE vn.sale
SET ticketFk = vClonTicket
WHERE id = vSaleFk;
SET vClonTicket = 0;
-
+
SET done = 0;
FETCH cur1 INTO vTicketFk, vSaleFk;
-
+
END WHILE;
CLOSE cur1;
@@ -56809,14 +55305,14 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `getDayExpeditions`()
BEGIN
- SELECT
- e.expeditions_id as expeditionFk,
- date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate,
- e.ticket_id as ticketFk,
+ SELECT
+ e.id as expeditionFk,
+ date_format(e.created,'%Y-%m-%d') as expeditionDate,
+ e.ticketFk,
t.routeFk as routeFk
- FROM vn2008.expeditions e
- INNER JOIN vn.ticket t ON t.id = e.ticket_id
- WHERE DATE(odbc_date) = util.VN_CURDATE();
+ FROM expedition e
+ INNER JOIN ticket t ON t.id = e.ticketFk
+ WHERE DATE(e.created) = util.VN_CURDATE();
END ;;
DELIMITER ;
@@ -56862,6 +55358,51 @@ BEGIN
SELECT id,name as description,upToDown as quantity FROM vn.item WHERE upToDown;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `getTaxBases` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `getTaxBases`()
+BEGIN
+/**
+* Calcula y devuelve en número de bases imponibles postivas y negativas
+* Requiere la tabla temporal tmp.ticketToInvoice(id)
+*
+* returns tmp.taxBases
+*/
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
+ (KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT id ticketFk
+ FROM tmp.ticketToInvoice;
+
+ CALL ticket_getTax(NULL);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.taxBases;
+ CREATE TEMPORARY TABLE tmp.taxBases
+ ENGINE = MEMORY
+ SELECT
+ SUM(taxableBase > 0) as positive,
+ SUM(taxableBase < 0) as negative
+ FROM(
+ SELECT SUM(taxableBase) taxableBase
+ FROM tmp.ticketTax
+ GROUP BY pgcFk
+ ) t;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -56887,7 +55428,7 @@ BEGIN
SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL yearsToDelete YEAR) INTO vDated
FROM vn.greugeConfig;
-
+
INSERT INTO vn.greuge(clientFk, description, amount, shipped, created, greugeTypeFk)
SELECT clientFk, 'Suma agrupada', SUM(amount), MAX(shipped), MAX(created), greugeTypeFk
FROM vn.greuge
@@ -57005,8 +55546,8 @@ DECLARE done BOOL DEFAULT FALSE;
DECLARE vTicketFk INT;
DECLARE rs CURSOR FOR
- SELECT id FROM vn.ticket
- WHERE shipped = util.yesterday()
+ SELECT id FROM vn.ticket
+ WHERE shipped = util.yesterday()
AND clientFk = 400
AND warehouseFk IN (1,44);
@@ -57017,13 +55558,13 @@ OPEN rs;
FETCH rs INTO vTicketFk;
WHILE NOT done DO
-
+
INSERT INTO vn.inventoryFailure(dated, itemFk, quantity, value, warehouseFk, throwerFk)
- SELECT t.shipped,
- s.itemFk,
- s.quantity,
+ SELECT t.shipped,
+ s.itemFk,
+ s.quantity,
b.buyingValue + b.freightValue + b.packageValue + b.comissionValue,
- t.warehouseFk,
+ t.warehouseFk,
w.id
FROM vn.ticket t
JOIN vn.sale s ON s.ticketFk = t.id
@@ -57034,7 +55575,7 @@ WHILE NOT done DO
AND s.quantity > 0;
FETCH rs INTO vTicketFk;
-
+
END WHILE;
@@ -57059,184 +55600,177 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `inventoryMake`(vDate DATE, vWh INT)
-proc: BEGIN
+CREATE DEFINER=`root`@`localhost` PROCEDURE `inventoryMake`(vInventoryDate DATE)
+BEGIN
/**
-* Recalcula los inventarios de todos los almacenes, si vWh = 0
+* Recalculate the inventories
*
-* @param vDate Fecha de los nuevos inventarios
-* @param vWh almacen al cual hacer el inventario
+* @param vInventoryDate date for the new inventory
*/
-
DECLARE vDone BOOL;
DECLARE vEntryFk INT;
DECLARE vTravelFk INT;
DECLARE vDateLastInventory DATE;
- DECLARE vDateYesterday DATETIME DEFAULT vDate - INTERVAL 1 SECOND;
+ DECLARE vDateYesterday DATETIME DEFAULT vInventoryDate - INTERVAL 1 SECOND;
DECLARE vWarehouseOutFkInventory INT;
DECLARE vInventorySupplierFk INT;
DECLARE vAgencyModeFkInventory INT;
+ DECLARE vMaxRecentInventories INT;
+ DECLARE vWarehouseFk INT;
DECLARE cWarehouses CURSOR FOR
SELECT id
FROM warehouse
- WHERE isInventory
- AND vWh IN (0,id);
+ WHERE isInventory;
+
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ SELECT inventorySupplierFk INTO vInventorySupplierFk FROM entryConfig LIMIT 1;
+ SELECT inventoried INTO vDateLastInventory FROM config LIMIT 1;
+ SELECT maxRecentInventories,
+ warehouseOutFk,
+ agencyModeFk
+ INTO vMaxRecentInventories,
+ vWarehouseOutFkInventory,
+ vAgencyModeFkInventory
+ FROM inventoryConfig
+ LIMIT 1;
+
+ IF vDateLastInventory IS NULL
+ OR vInventorySupplierFk IS NULL
+ OR vMaxRecentInventories IS NULL
+ OR vInventoryDate IS NULL
+ OR vWarehouseOutFkInventory IS NULL
+ OR vAgencyModeFkInventory IS NULL THEN
+ CALL util.throw('Some config parameters are not set');
+ END IF;
+
+ START TRANSACTION;
+
OPEN cWarehouses;
+ -- Environment variable to disable the triggers of the affected tables
SET @isModeInventory := TRUE;
l: LOOP
-
SET vDone = FALSE;
- FETCH cWarehouses INTO vWh;
+ SET vEntryFk = NULL;
+ SET vTravelFk = NULL;
+
+ FETCH cWarehouses INTO vWarehouseFk;
IF vDone THEN
LEAVE l;
END IF;
- SELECT w.id INTO vWarehouseOutFkInventory
- FROM warehouse w
- WHERE w.code = 'inv';
-
- SELECT inventorySupplierFk INTO vInventorySupplierFk
- FROM entryConfig;
-
- SELECT am.id INTO vAgencyModeFkInventory
- FROM agencyMode am
- where code = 'inv';
-
- SELECT MAX(landed) INTO vDateLastInventory
- FROM travel tr
- JOIN entry e ON e.travelFk = tr.id
- JOIN buy b ON b.entryFk = e.id
- WHERE warehouseOutFk = vWarehouseOutFkInventory
- AND landed < vDate
- AND e.supplierFk = vInventorySupplierFk
- AND warehouseInFk = vWh
- AND NOT isRaid;
-
- IF vDateLastInventory IS NULL THEN
- SELECT inventoried INTO vDateLastInventory FROM config;
- END IF;
-
- -- Generamos travel, si no existe.
- SET vTravelFK = 0;
-
+ -- Generate travel, if it does not exist
SELECT id INTO vTravelFk
FROM travel
WHERE warehouseOutFk = vWarehouseOutFkInventory
- AND warehouseInFk = vWh
- AND landed = vDate
+ AND warehouseInFk = vWarehouseFk
+ AND landed = vInventoryDate
AND agencyModeFk = vAgencyModeFkInventory
AND ref = 'inventario'
LIMIT 1;
- IF NOT vTravelFK THEN
-
- INSERT INTO travel SET
- warehouseOutFk = vWarehouseOutFkInventory,
- warehouseInFk = vWh,
- shipped = vDate,
- landed = vDate,
- agencyModeFk = vAgencyModeFkInventory,
- ref = 'inventario',
- isDelivered = TRUE,
- isReceived = TRUE;
+ IF vTravelFk IS NULL THEN
+ INSERT INTO travel
+ SET warehouseOutFk = vWarehouseOutFkInventory,
+ warehouseInFk = vWarehouseFk,
+ shipped = vInventoryDate,
+ landed = vInventoryDate,
+ agencyModeFk = vAgencyModeFkInventory,
+ ref = 'inventario',
+ isDelivered = TRUE,
+ isReceived = TRUE;
SELECT LAST_INSERT_ID() INTO vTravelFk;
-
END IF;
- -- Generamos entrada si no existe, o la vaciamos.
- SET vEntryFk = 0;
-
+ -- Generate an entry if it does not exist, or we empty it
SELECT id INTO vEntryFk
FROM entry
WHERE supplierFk = vInventorySupplierFk
AND travelFk = vTravelFk;
- IF NOT vEntryFk THEN
-
- INSERT INTO entry SET
- supplierFk = vInventorySupplierFk,
- isConfirmed = TRUE,
- isOrdered = TRUE,
- travelFk = vTravelFk;
+ IF vEntryFk IS NULL THEN
+ INSERT INTO entry
+ SET supplierFk = vInventorySupplierFk,
+ isConfirmed = TRUE,
+ isOrdered = TRUE,
+ travelFk = vTravelFk;
SELECT LAST_INSERT_ID() INTO vEntryFk;
-
ELSE
-
DELETE FROM buy WHERE entryFk = vEntryFk;
-
END IF;
- -- Preparamos tabla auxilar
- CREATE OR REPLACE TEMPORARY TABLE tmp.inventory (
- itemFk INT(11) NOT NULL PRIMARY KEY,
- quantity int(11) DEFAULT '0',
- buyingValue decimal(10,3) DEFAULT '0.000',
- freightValue decimal(10,3) DEFAULT '0.000',
- packing int(11) DEFAULT '0',
- `grouping` smallint(5) unsigned NOT NULL DEFAULT '1',
- groupingMode tinyint(4) NOT NULL DEFAULT 0 ,
- comissionValue decimal(10,3) DEFAULT '0.000',
- packageValue decimal(10,3) DEFAULT '0.000',
- packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--',
- price1 decimal(10,2) DEFAULT '0.00',
- price2 decimal(10,2) DEFAULT '0.00',
- price3 decimal(10,2) DEFAULT '0.00',
- minPrice decimal(10,2) DEFAULT '0.00',
- producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
- INDEX (itemFK)) ENGINE = MEMORY;
+ -- Prepare the auxiliary table
+ CREATE OR REPLACE TEMPORARY TABLE tInventory (
+ itemFk INT(11) NOT NULL PRIMARY KEY,
+ quantity int(11) DEFAULT '0',
+ buyingValue decimal(10,4) DEFAULT '0.0000',
+ freightValue decimal(10,3) DEFAULT '0.000',
+ packing int(11) DEFAULT '0',
+ `grouping` smallint(5) unsigned NOT NULL DEFAULT '1',
+ groupingMode tinyint(4) NOT NULL DEFAULT 0 ,
+ comissionValue decimal(10,3) DEFAULT '0.000',
+ packageValue decimal(10,3) DEFAULT '0.000',
+ packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--',
+ price1 decimal(10,2) DEFAULT '0.00',
+ price2 decimal(10,2) DEFAULT '0.00',
+ price3 decimal(10,2) DEFAULT '0.00',
+ minPrice decimal(10,2) DEFAULT '0.00',
+ producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
+ INDEX (itemFK)
+ ) ENGINE = MEMORY;
- -- Compras
- INSERT INTO tmp.inventory(itemFk,quantity)
+ -- Buys
+ INSERT INTO tInventory(itemFk, quantity)
SELECT b.itemFk, SUM(b.quantity)
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel tr ON tr.id = e.travelFk
- WHERE tr.warehouseInFk = vWh
- AND tr.landed BETWEEN vDateLastInventory
- AND vDateYesterday
+ WHERE tr.warehouseInFk = vWarehouseFk
+ AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday
AND NOT isRaid
GROUP BY b.itemFk;
- SELECT vDateLastInventory , vDateYesterday;
- -- Traslados
- INSERT INTO tmp.inventory(itemFk, quantity)
+ -- Transfers
+ INSERT INTO tInventory(itemFk, quantity)
SELECT itemFk, quantityOut
- FROM (
+ FROM (
SELECT b.itemFk,- SUM(b.quantity) quantityOut
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel tr ON tr.id = e.travelFk
- WHERE tr.warehouseOutFk = vWh
- AND tr.shipped BETWEEN vDateLastInventory
- AND vDateYesterday
+ WHERE tr.warehouseOutFk = vWarehouseFk
+ AND tr.shipped BETWEEN vDateLastInventory AND vDateYesterday
AND NOT isRaid
GROUP BY b.itemFk
) sub
ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut;
- -- Ventas
- INSERT INTO tmp.inventory(itemFk,quantity)
+ -- Sales
+ INSERT INTO tInventory(itemFk, quantity)
SELECT itemFk, saleOut
- FROM (
+ FROM (
SELECT s.itemFk, - SUM(s.quantity) saleOut
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
- WHERE t.warehouseFk = vWh
+ WHERE t.warehouseFk = vWarehouseFk
AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday
GROUP BY s.itemFk
) sub
ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut;
- -- Actualiza valores de la ultima compra
- UPDATE tmp.inventory inv
- JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh
+ -- Update values of the last purchase
+ UPDATE tInventory inv
+ JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWarehouseFk
JOIN buy b ON b.id = lb.buy_id
JOIN item i ON i.id = b.itemFk
LEFT JOIN producer p ON p.id = i.producerFk
@@ -57247,14 +55781,14 @@ proc: BEGIN
inv.groupingMode = b.groupingMode,
inv.comissionValue = b.comissionValue,
inv.packageValue = b.packageValue,
- inv.packageFk = b.packageFk,
+ inv.packageFk = b.packagingFk,
inv.price1 = b.price1,
inv.price2 = b.price2,
inv.price3 = b.price3,
inv.minPrice = b.minPrice,
inv.producer = p.name;
- INSERT INTO buy( itemFk,
+ INSERT INTO buy(itemFk,
quantity,
buyingValue,
freightValue,
@@ -57263,64 +55797,75 @@ proc: BEGIN
groupingMode,
comissionValue,
packageValue,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
minPrice,
entryFk)
SELECT itemFk,
- GREATEST(quantity, 0),
- buyingValue,
- freightValue,
- packing,
- `grouping`,
- groupingMode,
- comissionValue,
- packageValue,
- packageFk,
- price1,
- price2,
- price3,
- minPrice,
- vEntryFk
- FROM tmp.inventory;
+ GREATEST(quantity, 0),
+ buyingValue,
+ freightValue,
+ packing,
+ `grouping`,
+ groupingMode,
+ comissionValue,
+ packageValue,
+ packageFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ vEntryFk
+ FROM tInventory;
- SELECT vWh, COUNT(*), util.VN_NOW() FROM tmp.inventory;
-
- -- Actualizamos el campo lastUsed de item
- UPDATE item i
- JOIN tmp.inventory i2 ON i2.itemFk = i.id
- SET i.lastUsed = NOW()
- WHERE i2.quantity;
-
- -- DROP TEMPORARY TABLE tmp.inventory;
+ -- Update the 'lastUsed' field of the item
+ UPDATE item i
+ JOIN tInventory i2 ON i2.itemFk = i.id
+ SET i.lastUsed = NOW()
+ WHERE i2.quantity;
+
+ DROP TEMPORARY TABLE tInventory;
END LOOP;
-
+
CLOSE cWarehouses;
- UPDATE config SET inventoried = vDate;
- SET @isModeInventory := FALSE;
+ UPDATE config SET inventoried = vInventoryDate;
- DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete;
- CREATE TEMPORARY TABLE tmp.entryToDelete
- (INDEX(entryId) USING BTREE) ENGINE = MEMORY
- SELECT e.id as entryId,
- t.id as travelId
+ SET @isModeInventory := FALSE;
+
+ CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete
+ (INDEX(entryId)) ENGINE = MEMORY
+ SELECT e.id entryId,
+ t.id travelId
FROM travel t
JOIN `entry` e ON e.travelFk = t.id
+ JOIN (
+ SELECT t.shipped
+ FROM travel t
+ JOIN `entry` e ON e.travelFk = t.id
+ WHERE e.supplierFk = vInventorySupplierFk
+ AND t.shipped <= vInventoryDate
+ GROUP BY t.shipped
+ ORDER BY t.shipped DESC
+ OFFSET vMaxRecentInventories ROWS
+ ) sub
WHERE e.supplierFk = vInventorySupplierFk
- AND t.shipped <= util.VN_CURDATE() - INTERVAL 12 DAY
- AND (DAY(t.shipped) <> 1 OR shipped < util.VN_CURDATE() - INTERVAL 12 DAY);
+ AND t.shipped IN (sub.shipped);
- DELETE e
+ DELETE e
FROM `entry` e
- JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id;
+ JOIN tEntryToDelete tmp ON tmp.entryId = e.id;
DELETE IGNORE t
FROM travel t
- JOIN tmp.entryToDelete tmp ON tmp.travelId = t.id;
+ JOIN tEntryToDelete tmp ON tmp.travelId = t.id;
+
+ DROP TEMPORARY TABLE IF EXISTS tEntryToDelete;
+
+ COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -57340,11 +55885,12 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `inventoryMakeLauncher`()
BEGIN
/**
- * Recalcula los inventarios de todos los almacenes.
+ * Recalculate the inventories of all warehouses
*/
-
- call vn.inventoryMake(TIMESTAMPADD(DAY, -10, util.VN_CURDATE()), 0);
-
+ CALL inventoryMake(
+ util.VN_CURDATE() -
+ INTERVAL (SELECT daysInPastForInventory FROM inventoryConfig LIMIT 1) DAY
+ );
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -57352,14 +55898,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `inventory_repair` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `inventory_repair`()
BEGIN
@@ -57375,7 +55921,7 @@ BEGIN
b.id AS buyFk,
b.entryFk,
b.isIgnored,
- b.price2,
+ b.price2,
b.price3,
b.stickers,
b.packing,
@@ -57385,24 +55931,24 @@ BEGIN
i.stems,
b.quantity,
b.buyingValue,
- b.packageFk ,
+ b.packagingFk ,
s.id AS supplierFk,
s.name AS supplier
FROM itemType it
- RIGHT JOIN (entry e
+ RIGHT JOIN (entry e
LEFT JOIN supplier s ON s.id = e.supplierFk
RIGHT JOIN buy b ON b.entryFk = e.id
LEFT JOIN item i ON i.id = b.itemFk
- LEFT JOIN ink ON ink.id = i.inkFk
+ LEFT JOIN ink ON ink.id = i.inkFk
LEFT JOIN travel tr ON tr.id = e.travelFk
LEFT JOIN warehouse w ON w.id = tr.warehouseInFk
LEFT JOIN origin o ON o.id = i.originFk
) ON it.id = i.typeFk
LEFT JOIN edi.ekt ek ON b.ektFk = ek.id
- WHERE (b.packageFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO';
-
+ WHERE (b.packagingFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO';
+
DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk;
- CREATE TEMPORARY TABLE tmp.lastEntryOk
+ CREATE TEMPORARY TABLE tmp.lastEntryOk
(PRIMARY KEY (buyFk))
SELECT
i.id AS itemFk,
@@ -57412,7 +55958,7 @@ BEGIN
b.id AS buyFk,
b.entryFk,
b.isIgnored,
- b.price2,
+ b.price2,
b.price3,
b.stickers,
b.packing,
@@ -57422,50 +55968,50 @@ BEGIN
i.stems,
b.quantity,
b.buyingValue,
- b.packageFk ,
+ b.packagingFk,
s.id AS supplierFk,
s.name AS supplier
FROM itemType it
- RIGHT JOIN (entry e
+ RIGHT JOIN (entry e
LEFT JOIN supplier s ON s.id = e.supplierFk
RIGHT JOIN buy b ON b.entryFk = e.id
LEFT JOIN item i ON i.id = b.itemFk
- LEFT JOIN ink ON ink.id = i.inkFk
+ LEFT JOIN ink ON ink.id = i.inkFk
LEFT JOIN travel tr ON tr.id = e.travelFk
LEFT JOIN warehouse w ON w.id = tr.warehouseInFk
LEFT JOIN origin o ON o.id = i.originFk
) ON it.id = i.typeFk
LEFT JOIN edi.ekt ek ON b.ektFk = ek.id
- WHERE b.packageFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE()))
+ WHERE b.packagingFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE()))
ORDER BY tr.landed DESC;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup;
- CREATE TEMPORARY TABLE tmp.lastEntryOkGroup
+ CREATE TEMPORARY TABLE tmp.lastEntryOkGroup
(INDEX (warehouseFk,itemFk))
SELECT *
FROM tmp.lastEntryOk tmp
GROUP BY tmp.itemFk,tmp.warehouseFk;
-
+
UPDATE buy b
JOIN tmp.lastEntry lt ON lt.buyFk = b.id
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
- SET b.packageFk = eo.packageFk WHERE b.packageFk = "--";
-
+ SET b.packagingFk = eo.packagingFk WHERE b.packagingFk = "--";
+
UPDATE buy b
JOIN tmp.lastEntry lt ON lt.buyFk = b.id
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
SET b.price2 = eo.price2 WHERE b.price2 = 0 ;
-
+
UPDATE buy b
JOIN tmp.lastEntry lt ON lt.buyFk = b.id
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
SET b.packing = eo.packing WHERE b.packing = 0;
-
+
UPDATE buy b
JOIN tmp.lastEntry lt ON lt.buyFk = b.id
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0;
-
+
DROP TEMPORARY TABLE tmp.lastEntry;
DROP TEMPORARY TABLE tmp.lastEntryOk;
DROP TEMPORARY TABLE tmp.lastEntryOkGroup;
@@ -57477,7 +56023,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake` */;
+/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenseMake` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@@ -57485,28 +56031,28 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceExpenceMake`(IN vInvoice INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceExpenseMake`(IN vInvoice INT)
BEGIN
/* Inserta las partidas de gasto correspondientes a la factura
* REQUIERE tabla tmp.ticketToInvoice
* @param vInvoice Numero de factura
*/
- DELETE FROM invoiceOutExpence
+ DELETE FROM invoiceOutExpense
WHERE invoiceOutFk = vInvoice;
- INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount)
+ INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount)
SELECT vInvoice,
- expenceFk,
+ expenseFk,
SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount
FROM tmp.ticketToInvoice t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
- GROUP BY i.expenceFk
+ GROUP BY i.expenseFk
HAVING amount != 0;
- INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount)
+ INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount)
SELECT vInvoice,
- tst.expenceFk,
+ tst.expenseFk,
SUM(ROUND(ts.quantity * ts.price ,2)) amount
FROM tmp.ticketToInvoice t
JOIN ticketService ts ON ts.ticketFk = t.id
@@ -57533,7 +56079,7 @@ BEGIN
DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(MONTH, -3, util.VN_CURDATE());
- SET vMaxTicketDate = vn2008.DAYEND(vMaxTicketDate);
+ SET vMaxTicketDate = util.dayEnd(vMaxTicketDate);
DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
@@ -57625,7 +56171,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_calculate`(vInvoiceInFk INT)
BEGIN
/**
- * Calcula los vctos. de una factura recibida
+ * Calcula los vctos. de una factura recibida
* En caso de haberlos informado previamente o que el proveedor sea español, no los recalculará
*
* @param vInvoiceInFk Factura recibida
@@ -57646,46 +56192,46 @@ BEGIN
WHERE ii.id = vInvoiceInFk;
SELECT COUNT(*) INTO vHasDueDay
- FROM invoiceInDueDay iid
+ FROM invoiceInDueDay iid
WHERE iid.invoiceInFk = vInvoiceInFk;
IF NOT vHasDueDay AND vCompanyCountryCode = 'ES' THEN
SET @cont := 0;
INSERT INTO invoiceInDueDay (
- invoiceInFk,
- dueDated,
- amount,
+ invoiceInFk,
+ dueDated,
+ amount,
foreignValue
)
SELECT vInvoiceInFk,
- IF(payDay,
+ IF(payDay,
IF(getNextDueDate(issued, pdd.detail, payDay) < created,
created,
- getNextDueDate(issued, pdd.detail, payDay)),
+ getNextDueDate(issued, pdd.detail, payDay)),
GREATEST(created, issued + INTERVAL pdd.detail DAY)),
- IF((@cont := @cont + 1) < cont,
- TRUNCATE(venc / cont, 2),
- venc - (TRUNCATE(venc / cont, 2) * (cont - 1))),
- IF(@cont < cont,
- TRUNCATE(foreignValue / cont, 2),
- foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1)))
- FROM (
- SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax)
- * iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc,
+ IF((@cont := @cont + 1) < cont,
+ TRUNCATE(venc / cont, 2),
+ venc - (TRUNCATE(venc / cont, 2) * (cont - 1))),
+ IF(@cont < cont,
+ TRUNCATE(foreignValue / cont, 2),
+ foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1)))
+ FROM (
+ SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax)
+ * iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc,
SUM(iit.foreignValue) / COUNT(DISTINCT(pdd.detail)) foreignValue,
- s.payDemFk,
+ s.payDemFk,
ii.companyFk,
COUNT(DISTINCT(pdd.detail)) cont,
s.payDay,
ii.issued,
DATE(ii.created) + INTERVAL 2 DAY created
- FROM invoiceIn ii
- JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
- LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk
- JOIN supplier s ON s.id = ii.supplierFk
- JOIN payDemDetail pdd ON pdd.id = s.payDemFk
- WHERE ii.id = vInvoiceInFk
+ FROM invoiceIn ii
+ JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
+ LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk
+ JOIN supplier s ON s.id = ii.supplierFk
+ JOIN payDemDetail pdd ON pdd.id = s.payDemFk
+ WHERE ii.id = vInvoiceInFk
GROUP BY ii.id
)sub
JOIN payDemDetail pdd ON pdd.id = sub.payDemFk
@@ -57713,9 +56259,9 @@ BEGIN
DELETE FROM invoiceInDueDay
WHERE invoiceInFk = vInvoiceInFk;
-
+
CALL invoiceInDueDay_calculate(vInvoiceInFk);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -57732,35 +56278,90 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTaxMakeByDua`(vDuaFk INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTaxMakeByDua`(
+ vDuaFk INT
+)
BEGIN
-
- DECLARE done BOOL DEFAULT FALSE;
+/**
+ * Borra los valores de duaTax y sus vctos. y los vuelve a
+ * crear en base a la tabla duaEntry.
+ *
+ * @param vDuaFk Id del dua a recalcular
+ */
+ DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceInFk INT;
- DECLARE rs CURSOR FOR
- SELECT invoiceInFk
- FROM entry e
- JOIN duaEntry de ON de.entryFk = e.id
- WHERE de.duaFk = vDuaFk;
+ DECLARE vInvoices CURSOR FOR
+ SELECT DISTINCT invoiceInFk
+ FROM entry e
+ JOIN duaEntry de ON de.entryFk = e.id
+ WHERE de.duaFk = vDuaFk;
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- OPEN rs;
+ OPEN vInvoices;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vInvoices INTO vInvoiceInFk;
- FETCH rs INTO vInvoiceInFk;
+ IF vDone THEN
+ LEAVE l;
+ END IF;
- WHILE NOT done DO
-
- CALL vn2008.recibidaIvaInsert(vInvoiceInFk);
+ CALL invoiceInTax_recalc(vInvoiceInFk);
CALL invoiceInDueDay_recalc(vInvoiceInFk);
- FETCH rs INTO vInvoiceInFk;
+ END LOOP;
+ CLOSE vInvoices;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `invoiceInTax_afterUpsert` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_afterUpsert`(vInvoiceInFk INT)
+BEGIN
+/**
+ * Triggered actions when a invoiceInTax is updated or inserted.
+ *
+ * @param vInvoiceInFk The invoiceIn id
+ */
+ DECLARE vTaxRowLimit INT;
+ DECLARE vLines INT;
+ DECLARE vHasDistinctTransactions INT;
- END WHILE;
+ SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig;
+
+ SELECT COUNT(*) INTO vLines
+ FROM invoiceInTax
+ WHERE invoiceInFk = vInvoiceInFk
+ AND (taxTypeSageFk OR transactionTypeSageFk);
+
+ IF vLines >= vTaxRowLimit THEN
+ CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit));
+ END IF;
- CLOSE rs;
+ SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions
+ FROM invoiceIn ii
+ JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
+ JOIN invoiceInSerial iis ON iis.code = ii.serial
+ WHERE ii.id = vInvoiceInFk
+ AND iis.taxAreaFk = 'CEE'
+ AND transactionTypeSageFk;
+ IF vHasDistinctTransactions > 1 THEN
+ CALL util.throw ('This invoice does not allow different types of transactions');
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -57779,33 +56380,36 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromDua`(vDuaFk INT)
BEGIN
-
- DECLARE done BOOL DEFAULT FALSE;
+/**
+ * Borra los valores de duaTax y sus vctos. y los vuelve a crear en base a la tabla duaEntry
+ *
+ * @param vDuaFk Id del dua a recalcular
+ */
+ DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceInFk INT;
- DECLARE rs CURSOR FOR
- SELECT invoiceInFk
+ DECLARE vInvoices CURSOR FOR
+ SELECT DISTINCT invoiceInFk
FROM entry e
JOIN duaEntry de ON de.entryFk = e.id
WHERE de.duaFk = vDuaFk;
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- OPEN rs;
+ OPEN vInvoices;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vInvoices INTO vInvoiceInFk;
- FETCH rs INTO vInvoiceInFk;
-
- WHILE NOT done DO
+ IF vDone THEN
+ LEAVE l;
+ END IF;
CALL invoiceInTax_getFromEntries(vInvoiceInFk);
CALL invoiceInDueDay_calculate(vInvoiceInFk);
- FETCH rs INTO vInvoiceInFk;
-
- END WHILE;
-
- CLOSE rs;
-
+ END LOOP;
+ CLOSE vInvoices;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -57822,16 +56426,25 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromEntries`(IN vId INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromEntries`(IN vInvoiceInFk INT)
BEGIN
DECLARE vRate DOUBLE DEFAULT 1;
DECLARE vDated DATE;
- DECLARE vExpenceFk VARCHAR(10);
+ DECLARE vExpenseFk VARCHAR(10);
+ DECLARE vIsBooked BOOLEAN DEFAULT FALSE;
+ SELECT isBooked INTO vIsBooked
+ FROM invoiceIn ii
+ WHERE id = vInvoiceInFk;
+
+ IF vIsBooked THEN
+ CALL util.throw('A booked invoice cannot be modified');
+ END IF;
+
SELECT MAX(rr.dated) INTO vDated
FROM referenceRate rr
- JOIN invoiceIn ii ON ii.id = vId
- WHERE rr.dated <= ii.issued
+ JOIN invoiceIn ii ON ii.id = vInvoiceInFk
+ WHERE rr.dated <= ii.issued
AND rr.currencyFk = ii.currencyFk ;
IF vDated THEN
@@ -57840,19 +56453,19 @@ BEGIN
WHERE dated = vDated;
END IF;
- SELECT id INTO vExpenceFk
- FROM vn.expence
- WHERE `name` = 'Adquisición mercancia Extracomunitaria'
- GROUP BY id
+ SELECT id INTO vExpenseFk
+ FROM vn.expense
+ WHERE `name` = 'Adquisición mercancia Extracomunitaria'
+ GROUP BY id
LIMIT 1;
+
+ DELETE FROM invoiceInTax
+ WHERE invoiceInFk = vInvoiceInFk;
- DELETE FROM invoiceInTax
- WHERE invoiceInFk = vId;
-
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, foreignValue, taxTypeSageFk, transactionTypeSageFk)
+ INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, foreignValue, taxTypeSageFk, transactionTypeSageFk)
SELECT ii.id,
SUM(b.buyingValue * b.quantity) / IFNULL(vRate,1) taxableBase,
- vExpenceFk,
+ vExpenseFk,
IF(ii.currencyFk = 1,NULL,SUM(b.buyingValue * b.quantity )) divisa,
taxTypeSageFk,
transactionTypeSageFk
@@ -57860,10 +56473,85 @@ BEGIN
JOIN entry e ON e.invoiceInFk = ii.id
JOIN supplier s ON s.id = e.supplierFk
JOIN buy b ON b.entryFk = e.id
+ LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk
+ AND rr.dated = ii.issued
+ WHERE ii.id = vInvoiceInFk
+ HAVING taxableBase IS NOT NULL;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `invoiceInTax_recalc` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_recalc`(
+ vInvoiceInFk INT
+)
+BEGIN
+/**
+ * Recalcula y actualiza los impuestos de la factura
+ * usando la última tasa de cambio y detalles de compra.
+ *
+ * @param vInvoiceInFk Id de factura recibida
+ */
+ DECLARE vRate DOUBLE DEFAULT 1;
+ DECLARE vDated DATE;
+ DECLARE vExpenseFk VARCHAR(10);
+
+ SELECT MAX(rr.dated) INTO vDated
+ FROM referenceRate rr
+ JOIN invoiceIn ii ON ii.id = vInvoiceInFk
+ WHERE rr.dated <= ii.issued
+ AND rr.currencyFk = ii.currencyFk;
+
+ IF vDated THEN
+ SELECT `value` INTO vRate
+ FROM referenceRate
+ WHERE dated = vDated;
+ END IF;
+
+ DELETE FROM invoiceInTax WHERE invoiceInFk = vInvoiceInFk;
+
+ SELECT id INTO vExpenseFk
+ FROM expense
+ WHERE code = 'extraCommGoodsAcquisition';
+
+ IF vExpenseFk IS NULL THEN
+ CALL util.throw('Expense extraCommGoodsAcquisition not exists');
+ END IF;
+
+ INSERT INTO invoiceInTax(
+ invoiceInFk,
+ taxableBase,
+ expenseFk,
+ foreignValue,
+ taxTypeSageFk,
+ transactionTypeSageFk
+ )
+ SELECT ii.id,
+ SUM(b.buyingValue * b.quantity) / vRate bi,
+ vExpenseFk,
+ IF(c.code = 'EUR', NULL, SUM(b.buyingValue * b.quantity)),
+ s.taxTypeSageFk,
+ s.transactionTypeSageFk
+ FROM invoiceIn ii
+ JOIN currency c ON c.id = ii.currencyFk
+ JOIN `entry` e ON e.invoiceInFk = ii.id
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN buy b ON b.entryFk = e.id
LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk
AND rr.dated = ii.issued
- WHERE ii.id = vId
- HAVING taxableBase IS NOT NULL;
+ WHERE ii.id = vInvoiceInFk
+ HAVING bi IS NOT NULL;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -57889,17 +56577,17 @@ BEGIN
SELECT ii.bookEntried,
iit.foreignValue,
ii.companyFk,
- ii.expenceFkDeductible,
+ ii.expenseFkDeductible,
iit.taxableBase,
iit.transactionTypeSageFk,
ii.serial,
ii.issued,
ii.operated,
ii.supplierRef,
- ii.cplusTrascendency472Fk,
+ ii.siiTrascendencyInvoiceInFk,
ii.cplusTaxBreakFk,
ii.cplusSubjectOpFk,
- ii.cplusInvoiceType472Fk,
+ ii.siiTypeInvoiceInFk,
ii.cplusRectificationTypeFk,
ii.booked,
IFNULL(a.isUeeMember, c.isUeeMember) isUeeMember,
@@ -57919,8 +56607,8 @@ BEGIN
cit.id invoicesCount,
e.code,
e.isWithheld,
- e.id expenceFk,
- e.name expenceName
+ e.id expenseFk,
+ e.name expenseName
FROM invoiceIn ii
JOIN supplier s ON s.id = ii.supplierFk
LEFT JOIN province p ON p.id = s.provinceFk
@@ -57928,11 +56616,11 @@ BEGIN
JOIN country c ON c.id = s.countryFk
JOIN supplier sc ON sc.id = ii.companyFk
JOIN country cc ON cc.id = sc.countryFk
- JOIN invoiceInSerial iis ON iis.code = ii.serial
- JOIN cplusInvoiceType472 cit ON cit.id = ii.cplusInvoiceType472Fk
+ JOIN invoiceInSerial iis ON iis.code = ii.serial
+ JOIN siiTypeInvoiceIn cit ON cit.id = ii.siiTypeInvoiceInFk
LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk
- LEFT JOIN expence e ON e.id = iit.expenceFk
+ LEFT JOIN expense e ON e.id = iit.expenseFk
LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
LEFT JOIN sage.taxType tt ON tt.id = ti.CodigoIva
WHERE ii.id = vSelf;
@@ -57951,18 +56639,18 @@ BEGIN
NFACTICK,
CLAVE,
empresa_id)
- SELECT
+ SELECT
vBookNumber ASIEN,
tii.bookEntried FECHA,
tii.supplierAccount SUBCTA,
- SUM(tii.taxableBase *
- IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21')
- AND tii.taxTypeSageFk IS NOT NULL),
- 1 + (tii.PorcentajeIva / 100),
- 1)) EUROHABER,
- CONCAT('s/fra',
- RIGHT(tii.supplierRef, 8),
- ':',
+ SUM(tii.taxableBase *
+ IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21')
+ AND tii.taxTypeSageFk IS NOT NULL),
+ 1 + (tii.PorcentajeIva / 100),
+ 1)) EUROHABER,
+ CONCAT('s/fra',
+ RIGHT(tii.supplierRef, 8),
+ ':',
LEFT(tii.supplierName, 10)) CONCEPTO,
CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10,4)) CAMBIO,
SUM(tii.foreignValue * IF(tii.serial = 'R', 1 + (tii.PorcentajeIva / 100), 1)) HABERME,
@@ -57979,7 +56667,7 @@ BEGIN
CONTRA,
EURODEBE,
EUROHABER,
- CONCEPTO,
+ CONCEPTO,
CAMBIO,
DEBEME,
HABERME,
@@ -57987,13 +56675,13 @@ BEGIN
empresa_id)
SELECT vBookNumber ASIEN,
tii.bookEntried FECHA,
- IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenceFk),tii.expenceFk) SUBCTA,
+ IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenseFk),tii.expenseFk) SUBCTA,
tii.supplierAccount CONTRA,
IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE,
IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER,
- CONCAT('s/fra',
- RIGHT(tii.supplierRef, 8),
- ':',
+ CONCAT('s/fra',
+ RIGHT(tii.supplierRef, 8),
+ ':',
LEFT(tii.supplierName, 10)) CONCEPTO,
CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10, 4)) CAMBIO,
IF(tii.isWithheld, NULL,ABS(ROUND(SUM(tii.foreignValue), 2))) DEBEME,
@@ -58002,20 +56690,20 @@ BEGIN
tii.companyFk empresa_id
FROM tInvoiceIn tii
WHERE tii.code IS NULL OR tii.code <> 'suplido'
- GROUP BY tii.expenceFk;
+ GROUP BY tii.expenseFk;
-- Líneas de IVA
- INSERT INTO XDiario(
+ INSERT INTO XDiario(
ASIEN,
FECHA,
SUBCTA,
- CONTRA,
+ CONTRA,
EURODEBE,
BASEEURO,
CONCEPTO,
- FACTURA,
+ FACTURA,
IVA,
- AUXILIAR,
+ AUXILIAR,
SERIE,
TIPOOPE,
FECHA_EX,
@@ -58036,11 +56724,11 @@ BEGIN
empresa_id)
SELECT vBookNumber ASIEN,
tii.bookEntried FECHA,
- IF(tii.expenceFkDeductible>0, tii.expenceFkDeductible, tii.CuentaIvaSoportado) SUBCTA,
+ IF(tii.expenseFkDeductible>0, tii.expenseFkDeductible, tii.CuentaIvaSoportado) SUBCTA,
tii.supplierAccount CONTRA,
SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100, 2)) EURODEBE,
SUM(tii.taxableBase) BASEEURO,
- GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO,
+ GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO,
vSelf FACTURA,
tii.PorcentajeIva IVA,
IF(tii.isUeeMember AND eWithheld.id IS NULL, '', '*') AUXILIAR,
@@ -58052,10 +56740,10 @@ BEGIN
tii.supplierRef FACTURAEX,
TRUE L340,
(tii.isSameCountry OR NOT tii.isUeeMember) LRECT349,
- tii.cplusTrascendency472Fk TIPOCLAVE,
+ tii.siiTrascendencyInvoiceInFk TIPOCLAVE,
tii.cplusTaxBreakFk TIPOEXENCI,
tii.cplusSubjectOpFk TIPONOSUJE,
- tii.cplusInvoiceType472Fk TIPOFACT,
+ tii.siiTypeInvoiceInFk TIPOFACT,
tii.cplusRectificationTypeFk TIPORECTIF,
tii.cplusTerIdNifFk TERIDNIF,
tii.nif TERNIF,
@@ -58064,28 +56752,28 @@ BEGIN
tii.companyFk
FROM tInvoiceIn tii
LEFT JOIN (
- SELECT e.id
+ SELECT e.id
FROM tInvoiceIn tii
- JOIN expence e ON e.id = tii.expenceFk
+ JOIN expense e ON e.id = tii.expenseFk
WHERE e.isWithheld
LIMIT 1
- ) eWithheld ON TRUE
- WHERE tii.taxTypeSageFk IS NOT NULL
- AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21'))
- GROUP BY tii.PorcentajeIva, tii.expenceFk;
+ ) eWithheld ON TRUE
+ WHERE tii.taxTypeSageFk IS NOT NULL
+ AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21'))
+ GROUP BY tii.PorcentajeIva, tii.expenseFk;
-- Línea iva inversor sujeto pasivo
- INSERT INTO XDiario(
+ INSERT INTO XDiario(
ASIEN,
FECHA,
SUBCTA,
- CONTRA,
+ CONTRA,
EUROHABER,
BASEEURO,
CONCEPTO,
- FACTURA,
+ FACTURA,
IVA,
- AUXILIAR,
+ AUXILIAR,
SERIE,
TIPOOPE,
FECHA_EX,
@@ -58109,7 +56797,7 @@ BEGIN
tii.supplierAccount CONTRA,
SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100,2)) EUROHABER,
ROUND(SUM(tii.taxableBase),2) BASEEURO,
- GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO,
+ GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO,
vSelf FACTURA,
tii.PorcentajeIva IVA,
'*' AUXILIAR,
@@ -58124,7 +56812,7 @@ BEGIN
1 TIPOCLAVE,
tii.cplusTaxBreakFk TIPOEXENCI,
tii.cplusSubjectOpFk TIPONOSUJE,
- tii.cplusInvoiceType472Fk TIPOFACT,
+ tii.siiTypeInvoiceInFk TIPOFACT,
tii.cplusRectificationTypeFk TIPORECTIF,
tii.cplusTerIdNifFk TERIDNIF,
tii.nif TERNIF,
@@ -58134,31 +56822,31 @@ BEGIN
JOIN sage.config c
WHERE tii.taxCode = 'ISP21' OR MID(tii.supplierAccount, 4, 1) = '1'
AND tii.taxTypeSageFk IS NOT NULL
- AND NOT(tii.isVies
- AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk
+ AND NOT(tii.isVies
+ AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk
AND tii.taxCode = 'nonTaxable')
- GROUP BY tii.PorcentajeIva, tii.expenceFk;
-
- -- Actualización del registro original
+ GROUP BY tii.PorcentajeIva, tii.expenseFk;
+
+ -- Actualización del registro original
UPDATE invoiceIn ii
SET ii.isBooked = TRUE
WHERE ii.id = vSelf;
-
+
-- Problemas derivados de la precisión en los decimales al calcular los impuestos
- UPDATE XDiario
- SET EURODEBE = EURODEBE -
+ UPDATE XDiario
+ SET EURODEBE = EURODEBE -
(SELECT IF(ABS(sub.difference) = 0.01, sub.difference, 0)
FROM(
- SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference
+ SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference
FROM XDiario
WHERE ASIEN = vBookNumber
)sub
)
- WHERE ASIEN = vBookNumber
+ WHERE ASIEN = vBookNumber
AND EURODEBE <> 0
ORDER BY id DESC
LIMIT 1;
-
+
DROP TEMPORARY TABLE tInvoiceIn;
END ;;
DELIMITER ;
@@ -58210,14 +56898,14 @@ BEGIN
FROM ticket
WHERE refFk = vInvoiceRef;
- CALL invoiceExpenceMake(vInvoiceFk);
+ CALL invoiceExpenseMake(vInvoiceFk);
CALL invoiceTaxMake(vInvoiceFk,vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) AS total
- FROM invoiceOutExpence
+ FROM invoiceOutExpense
WHERE invoiceOutFk = vInvoiceFk
) base
JOIN (
@@ -58253,7 +56941,7 @@ BEGIN
* param vInvoice factura_id
*/
DECLARE vBookNumber INT;
- DECLARE vExpenceConcept VARCHAR(50);
+ DECLARE vExpenseConcept VARCHAR(50);
DECLARE vSpainCountryFk INT;
DECLARE vOldBookNumber INT;
@@ -58273,7 +56961,7 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS rs;
CREATE TEMPORARY TABLE rs
- SELECT
+ SELECT
c.accountingAccount AS clientBookingAccount,
io.amount as totalAmount,
CONCAT('n/fra ', io.ref) as simpleConcept,
@@ -58284,10 +56972,10 @@ BEGIN
io.issued AS FECHA,
1 AS NFACTICK,
IF(ic.correctingFk,'D','') AS TIPOOPE,
- io.cplusTrascendency477Fk AS TIPOCLAVE,
+ io.siiTrascendencyInvoiceOutFk AS TIPOCLAVE,
io.cplusTaxBreakFk AS TIPOEXENCI,
io.cplusSubjectOpFk AS TIPONOSUJE,
- io.cplusInvoiceType477Fk AS TIPOFACT,
+ io.siiTypeInvoiceOutFk AS TIPOFACT,
ic.cplusRectificationTypeFk AS TIPORECTIF,
io.companyFk,
RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum,
@@ -58307,19 +56995,19 @@ BEGIN
WHERE io.id = vInvoice;
CALL vn.ledger_next(vBookNumber);
-
+
-- Linea del cliente
INSERT INTO XDiario(
ASIEN,
FECHA,
- SUBCTA,
+ SUBCTA,
EURODEBE,
- CONCEPTO,
+ CONCEPTO,
FECHA_EX,
FECHA_OP,
empresa_id
)
- SELECT
+ SELECT
vBookNumber AS ASIEN,
rs.FECHA,
rs.clientBookingAccount AS SUBCTA,
@@ -58335,17 +57023,17 @@ BEGIN
ASIEN,
FECHA,
SUBCTA,
- CONTRA,
+ CONTRA,
EUROHABER,
- CONCEPTO,
+ CONCEPTO,
FECHA_EX,
FECHA_OP,
empresa_id
)
- SELECT
+ SELECT
vBookNumber AS ASIEN,
rs.FECHA,
- ioe.expenceFk AS SUBCTA,
+ ioe.expenseFk AS SUBCTA,
rs.clientBookingAccount AS CONTRA,
ioe.amount AS EUROHABER,
rs.Concept AS CONCEPTO,
@@ -58353,13 +57041,13 @@ BEGIN
rs.FECHA_OP,
rs.companyFk AS empresa_id
FROM rs
- JOIN invoiceOutExpence ioe
+ JOIN invoiceOutExpense ioe
WHERE ioe.invoiceOutFk = vInvoice;
- SELECT GROUP_CONCAT(`name` SEPARATOR ',')
- INTO vExpenceConcept
- FROM expence e
- JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id
+ SELECT GROUP_CONCAT(`name` SEPARATOR ',')
+ INTO vExpenseConcept
+ FROM expense e
+ JOIN invoiceOutExpense ioe ON ioe.expenseFk = e.id
WHERE ioe.invoiceOutFk = vInvoice;
-- Lineas de IVA
@@ -58367,7 +57055,7 @@ BEGIN
ASIEN,
FECHA,
SUBCTA,
- CONTRA,
+ CONTRA,
EUROHABER,
BASEEURO,
CONCEPTO,
@@ -58395,14 +57083,14 @@ BEGIN
TIPORECTIF,
empresa_id
)
- SELECT
+ 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,
+ CONCAT(vExpenseConcept,' : ',rs.Concept) AS CONCEPTO,
rs.invoiceNum AS FACTURA,
IF(pe2.equFk,0,pgc.rate) AS IVA,
IF(pe2.equFk,0,pgce.rate) AS RECEQUIV,
@@ -58415,25 +57103,25 @@ BEGIN
rs.FECHA_OP,
rs.FECHA_EX,
rs.TIPOOPE,
- rs.NFACTICK,
+ rs.NFACTICK,
rs.TERIDNIF,
rs.TERNIF,
rs.TERNOM,
- pgc.mod340 AS L340,
- pgc.cplusTrascendency477Fk AS TIPOCLAVE,
+ pgc.mod340 AS L340,
+ pgc.siiTrascendencyInvoiceOutFk AS TIPOCLAVE,
pgc.cplusTaxBreakFk as TIPOEXENCI,
rs.TIPONOSUJE,
rs.TIPOFACT,
rs.TIPORECTIF,
rs.companyFk AS empresa_id
FROM rs
- JOIN invoiceOutTax iot
+ JOIN 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 pgc pgce ON pgce.code = pe.equFk
LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk -- --------------- Comprueba si la linea es de rec.equiv.
WHERE iot.invoiceOutFk = vInvoice;
-
+
UPDATE invoiceOut
SET booked = util.VN_CURDATE()
WHERE id = vInvoice;
@@ -58465,7 +57153,7 @@ BEGIN
DECLARE done BOOL DEFAULT FALSE;
- DECLARE rs CURSOR FOR
+ DECLARE rs CURSOR FOR
SELECT io.id
FROM invoiceOut io
WHERE RIGHT(ref,7) BETWEEN 1724215 AND 1724224
@@ -58480,15 +57168,15 @@ BEGIN
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;
@@ -58497,85 +57185,6 @@ BEGIN
SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `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 = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutDelete`(vRef VARCHAR(15))
-BEGIN
- DECLARE vAsien INTEGER;
- DECLARE vSendMail BOOL;
- DECLARE vBody TEXT;
-
- SELECT ASIEN INTO vAsien
- FROM XDiario
- WHERE SERIE = SUBSTRING(vRef, 1, 1)
- AND FACTURA = SUBSTRING(vRef, 2, LENGTH(vRef)-1)
- LIMIT 1;
-
- SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE),
- CONCAT(
- '
-
FECHA
-
SUBCTA
-
CONTRA
-
CONCEPTO
-
EURODEBE
-
EUROHABER
-
',
- GROUP_CONCAT(
- CONCAT('
-
', IFNULL(FECHA,''), '
-
', IFNULL(SUBCTA,''), '
-
', IFNULL(CONTRA,''), '
-
', IFNULL(CONCEPTO,''), '
-
', IFNULL(EURODEBE,''), '
-
', IFNULL(EUROHABER,''), '
-
'
- ) SEPARATOR ' '
- ),
- '
'
- )
- INTO vSendMail, vBody
- FROM XDiario
- WHERE ASIEN = vAsien;
-
- DELETE FROM XDiario
- WHERE ASIEN = vAsien;
-
- IF vSendMail THEN
- CALL mail_insert(
- 'administracion@verdnatura.es',
- 'noreply@verdnatura.es',
- CONCAT('Eliminada factura ' ,vRef),
- CONCAT(
- '
-
Se ha eliminado el asiento ', vAsien, ' que estaba enlazado en SAGE/CONTAPLUS, vinculado a la factura ', vRef ,'
- ', vBody, '
'
- )
- );
- END IF;
-
- UPDATE ticket
- SET refFk = NULL
- WHERE refFk = vRef;
-
- DELETE
- FROM invoiceOut
- WHERE ref = vRef;
-
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -58595,7 +57204,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutListByCompany`(vCompany INT, vStarted DATE, vEnded DATE)
BEGIN
-SELECT
+SELECT
c.socialName as RazonSocial,
c.fi as NIF,
io.ref as Factura,
@@ -58607,7 +57216,7 @@ SELECT
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
@@ -58624,7 +57233,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpence` */;
+/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpense` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@@ -58632,7 +57241,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutTaxAndExpence`()
+CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutTaxAndExpense`()
BEGIN
/* Para tickets ya facturados, vuelve a repetir el proceso de facturación.
@@ -58686,7 +57295,7 @@ BEGIN
FROM ticket
WHERE refFk = vInvoiceRef;
- CALL invoiceExpenceMake(vInvoice);
+ CALL invoiceExpenseMake(vInvoice);
CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea);
FETCH rs INTO vInvoice ,vInvoiceRef;
@@ -58867,7 +57476,7 @@ BEGIN
clientFk,
dued,
companyFk,
- cplusInvoiceType477Fk
+ siiTypeInvoiceOutFk
)
SELECT
1,
@@ -58911,22 +57520,22 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.updateInter;
CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY
- SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador
+ SELECT s.id, ti.id ticket_id, vWorker Id_Trabajador
FROM tmp.ticketToInvoice ti
- LEFT JOIN ticketState ts ON ti.id = ts.ticket
+ LEFT JOIN ticketState ts ON ti.id = ts.ticketFk
JOIN state s
- WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = getAlert3State(ti.id);
+ WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id);
- INSERT INTO ticketTracking(stateFk,ticketFk,workerFk)
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT * FROM tmp.updateInter;
- CALL invoiceExpenceMake(vNewInvoiceId);
- CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
+ CALL invoiceExpenseMake(vNewInvoiceId);
+ CALL invoiceTaxMake(vNewInvoiceId, vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) total
- FROM invoiceOutExpence
+ FROM invoiceOutExpense
WHERE invoiceOutFk = vNewInvoiceId
) base
JOIN (
@@ -58963,15 +57572,15 @@ BEGIN
SET @vTaxableBaseServices := 0.00;
SET @vTaxCodeGeneral := NULL;
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
+ INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
@vTaxableBaseServices,
- sub.expenceFk,
+ sub.expenseFk,
sub.taxTypeSageFk,
sub.transactionTypeSageFk
FROM (
SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase,
- i.expenceFk,
+ i.expenseFk,
i.taxTypeSageFk,
i.transactionTypeSageFk,
@vTaxCodeGeneral := i.taxClassCodeFk
@@ -58981,11 +57590,11 @@ BEGIN
HAVING taxableBase
) sub;
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
+ INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral,
@vTaxableBaseServices, 0) taxableBase,
- i.expenceFk,
+ i.expenseFk,
i.taxTypeSageFk ,
i.transactionTypeSageFk
FROM tmp.ticketTax tt
@@ -59052,17 +57661,17 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_newFromClient`(
- IN vClientFk INT,
- IN vSerial CHAR(2),
+ IN vClientFk INT,
+ IN vSerial CHAR(2),
IN vMaxShipped DATE,
- IN vCompanyFk INT,
+ IN vCompanyFk INT,
IN vTaxArea VARCHAR(25),
- IN vRef VARCHAR(25),
+ IN vRef VARCHAR(25),
OUT vInvoiceId INT)
BEGIN
/**
* Factura los tickets de un cliente hasta una fecha dada
- * @param vClientFk Id del cliente a facturar
+ * @param vClientFk Id del cliente a facturar
* @param vSerial Serie de factura
* @param vMaxShipped Fecha hasta la cual cogera tickets para facturar
* @param vCompanyFk Id de la empresa desde la que se factura
@@ -59081,11 +57690,11 @@ BEGIN
IF NOT vIsRefEditable THEN
CALL util.throw('serial non editable');
END IF;
- END IF;
+ END IF;
SELECT COUNT(*) INTO vIsExportation
FROM vn.invoiceOutSerial
- WHERE taxAreaFk = 'WORLD'
+ WHERE taxAreaFk = 'WORLD'
AND `code` = vSerial;
IF vIsExportation THEN
@@ -59098,7 +57707,7 @@ BEGIN
UPDATE invoiceOut
SET `ref` = vRef
- WHERE id = vInvoiceId
+ WHERE id = vInvoiceId
AND vRef IS NOT NULL;
IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
@@ -59127,7 +57736,7 @@ BEGIN
* Factura un ticket
* @param vTicketFk Id del ticket
* @param vSerial Serie de factura
- * @param vTaxArea Area de la factura en caso de querer forzarlo,
+ * @param vTaxArea Area de la factura en caso de querer forzarlo,
* en la mayoria de los casos poner NULL
* @return vInvoiceId
*/
@@ -59142,11 +57751,11 @@ BEGIN
IF NOT vIsRefEditable THEN
CALL util.throw('serial non editable');
END IF;
-
- UPDATE invoiceOut
+
+ UPDATE invoiceOut
SET `ref` = vRef
WHERE id = vInvoiceId;
- END IF;
+ END IF;
IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
CALL invoiceOutBooking(vInvoiceId);
@@ -59228,50 +57837,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemBarcode_update`(vItemFk INT,vCo
BEGIN
IF vDelete THEN
DELETE FROM vn.itemBarcode WHERE itemFk = vItemFk AND code = vCode;
-ELSE
+ELSE
INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode);
END IF;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `itemFreight_Show` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFreight_Show`(vItemFk INT, vWarehouseFk INT)
-BEGIN
-
- SELECT cm3 Volumen_Entrada,
- cm3delivery Volumen_Salida,
- p.volume Volumen_del_embalaje,
- p.width Ancho_del_embalaje,
- p.`depth` Largo_del_embalaje,
- b.packageFk ,
- IFNULL(p.height, i.`size`) + 10 Altura,
- b.packing Packing_Entrada,
- i.packingOut Packing_Salida,
- i.id itemFk,
- b.id buyFk,
- b.entryFk,
- w.name warehouseFk
- FROM vn.itemCost ic
- JOIN vn.item i ON i.id = ic.itemFk
- LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk
- LEFT JOIN vn.buy b ON b.id = lb.buy_id
- LEFT JOIN vn.packaging p ON p.id = b.packageFk
- LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk
- WHERE ic.itemFk = vItemFk
- AND ic.warehouseFk = vWarehouseFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -59292,33 +57861,33 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFuentesBalance`(vDaysInFuture I
BEGIN
/* Se utiliza para calcular la necesidad de mover mercancia entre el almacén de fuentes y el nuestro
- *
+ *
* @param vDaysInFuture Rango de dias para calcular entradas y salidas
- *
+ *
*/
-
+
DECLARE vWarehouseFk INT;
SELECT s.warehouseFk INTO vWarehouseFk
- FROM vn.sector s
+ FROM vn.sector s
WHERE s.code = 'FUENTES_PICASSE';
-
+
CALL cache.stock_refresh(FALSE);
- SELECT i.id itemFk,
+ SELECT i.id itemFk,
i.longName,
i.size,
i.subName,
- v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible,
- fue.Fuentes,
+ v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible,
+ fue.Fuentes,
alb.Albenfruit,
- sale.venta,
- IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra,
- IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0)
+ sale.venta,
+ IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra,
+ IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0)
- IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as saldo
- FROM vn.item i
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ FROM vn.item i
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN (
SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Fuentes
FROM vn.itemShelving ish
@@ -59326,7 +57895,7 @@ BEGIN
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
WHERE s.code = 'FUENTES_PICASSE'
- GROUP BY ish.itemFk
+ GROUP BY ish.itemFk
) fue ON fue.itemFk = i.id
LEFT JOIN (
SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Albenfruit
@@ -59335,35 +57904,34 @@ BEGIN
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
WHERE s.code = 'ALBENFRUIT'
- GROUP BY ish.itemFk
+ GROUP BY ish.itemFk
) alb ON alb.itemFk = i.id
LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk
LEFT JOIN (
- SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta
- FROM vn2008.item_out
- WHERE dat BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
- AND warehouse_id = vWarehouseFk
- GROUP BY item_id
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta
+ FROM itemTicketOut
+ WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
+ AND warehouseFk = vWarehouseFk
+ GROUP BY itemFk
) sale ON sale.item_id = i.id
LEFT JOIN (
- SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra
- FROM vn2008.item_entry_in
- WHERE dat BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
- AND warehouse_id = vWarehouseFk
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra
+ FROM itemEntryIn
+ WHERE landed BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
+ AND warehouseInFk = vWarehouseFk
AND isVirtualStock = FALSE
- GROUP BY item_id
+ GROUP BY itemFk
) buy ON buy.item_id = i.id
LEFT JOIN (
- SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado
- FROM vn2008.item_entry_out
- WHERE dat BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
- AND warehouse_id = vWarehouseFk
- GROUP BY item_id
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado
+ FROM itemEntryOut
+ WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
+ AND warehouseOutFk = vWarehouseFk
+ GROUP BY itemFk
) mov ON mov.item_id = i.id
- WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit)
+ WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit)
AND i.itemPackingTypeFk = 'H'
- AND ic.shortLife
- ;
+ AND ic.shortLife;
END ;;
DELIMITER ;
@@ -59384,7 +57952,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementFromTicket`(vTicket INT)
BEGIN
/**
- * Llama a itemPlacementUpdateVisible
+ * Llama a itemPlacementUpdateVisible
* de los articulos de la tabla temporal tmp.itemPlacement(itemFk)
* @treturn tmp.itemPlacement
* @param vTicket Id del Ticket
@@ -59398,9 +57966,9 @@ BEGIN
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
WHERE t.id = vTicket;
-
+
CALL itemPlacementUpdateVisible();
-
+
DROP TEMPORARY TABLE tmp.itemPlacement;
END ;;
DELIMITER ;
@@ -59433,7 +58001,7 @@ BEGIN
CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)),
' x ',
ish.packing,
- IF (
+ IF (
LEAST(ish.stock,quantity) MOD ish.packing,
CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))),
''
@@ -59464,7 +58032,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementSupplyCloseOrder`(vId INT, vQuantity INT)
BEGIN
- UPDATE vn.itemPlacementSupply
+ UPDATE vn.itemPlacementSupply
SET priority = 10
WHERE id = vId;
@@ -59490,7 +58058,7 @@ BEGIN
DECLARE vId INT;
DECLARE vLastParkingFk INT;
DECLARE vNextParkingFk INT;
-
+
SELECT sh.parkingFk INTO vLastParkingFk
FROM vn.itemShelvingPlacementSupply isps
JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk
@@ -59498,9 +58066,9 @@ BEGIN
WHERE isps.userFk = getUser()
ORDER BY isps.created DESC
LIMIT 1;
-
+
SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk);
-
+
SELECT ipsl.id INTO vId
FROM vn.itemPlacementSupplyList ipsl
JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk
@@ -59509,13 +58077,13 @@ BEGIN
AND ipsl.sectorFk = vSector
ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created
LIMIT 1;
-
+
UPDATE vn.itemPlacementSupply
SET repoUserFk = getUser()
WHERE id = vId;
-
- SELECT * FROM vn.itemPlacementSupplyList
- WHERE id = vId
+
+ SELECT * FROM vn.itemPlacementSupplyList
+ WHERE id = vId
AND sectorFk = vSector;
END ;;
@@ -59543,289 +58111,23 @@ BEGIN
* @param vItemFk Identificador de vn.item
* @param vSectorFk Identificador de vn.sector
*/
- DECLARE vWarehouseAliasFk INT;
-
- SELECT w.aliasFk INTO vWarehouseAliasFk
- FROM vn.sector s
- JOIN vn.warehouse w ON w.id = s.warehouseFk
- WHERE s.id = vSectorFk;
-
SELECT ish.shelvingFk shelving,
- p.code parking,
- sum(ish.visible) as stockTotal,
- ish.created,
- p.pickingOrder
+ p.code parking,
+ SUM(ish.visible) stockTotal,
+ ish.created,
+ p.pickingOrder
FROM vn.itemShelving ish
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector sc ON sc.id = p.sectorFk
JOIN vn.warehouse w ON w.id = sc.warehouseFk
- WHERE w.aliasFk = vWarehouseAliasFk
- AND ish.visible > 0
- AND ish.itemFk = vItemFk
+ WHERE sc.id = vSectorFk
+ AND ish.visible > 0
+ AND ish.itemFk = vItemFk
GROUP BY ish.id
- ORDER BY (sc.id = vSectorFk) DESC, sh.priority DESC;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `itemProposal` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `itemProposal`(vItemFk INT, vTicketFk INT,vShowType BOOL)
-BEGIN
-
-/**
- * Propone articulos disponible ordenado, con la cantidad de veces usado y segun sus caracteristicas
- *
- * @param vItemFk item id
- * @param vTicketFk ticket id
- * @param vShowType mostrar tipos
- */
-
- DECLARE vWarehouseFk INT;
- DECLARE vShipped DATE;
- DECLARE vCalcFk INT;
- DECLARE vTypeFk INT;
-
-
- DECLARE vTag1 VARCHAR(25);
- DECLARE vTag5 VARCHAR(25);
- DECLARE vTag6 VARCHAR(25);
- DECLARE vTag7 VARCHAR(25);
- DECLARE vTag8 VARCHAR(25);
-
- DECLARE vValue1 VARCHAR(50);
- DECLARE vValue5 VARCHAR(50);
- DECLARE vValue6 VARCHAR(50);
- DECLARE vValue7 VARCHAR(50);
- DECLARE vValue8 VARCHAR(50);
-
- SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped
- FROM vn.ticket
- WHERE id = vTicketFk;
-
- SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value
- INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1
- FROM vn.item i
- LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1
- LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk
- WHERE i.id = vItemFk;
-
- CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped);
-
- SELECT i.id itemFk,
- i.longName,
- i.subName,
- i.tag5,
- i.value5,
- (i.value5 <=> vValue5 COLLATE utf8_general_ci) match5,
- i.tag6,
- i.value6,
- (i.value6 <=> vValue6 COLLATE utf8_general_ci) match6,
- i.tag7,
- i.value7,
- (i.value7 <=> vValue7 COLLATE utf8_general_ci) match7,
- i.tag8,
- i.value8,
- (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8,
- a.available,
- IFNULL(ip.counter,0) counter,
- IF(b.groupingMode = 1, b.grouping, b.packing) as minQuantity
- FROM vn.item i
- JOIN cache.available a ON a.item_id = i.id
- LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk
- LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1
- LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk
- LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk
- LEFT JOIN vn.buy b ON b.id = lb.buy_id
- WHERE a.calc_id = vCalcFk
- AND available > 0
- AND IF(vShowType,i.typeFk = vTypeFk,true)
- AND i.id != vItemFk
- ORDER BY counter DESC,
- (t1.name = vTag1 COLLATE utf8_general_ci) DESC,
- (it1.value = vValue1 COLLATE utf8_general_ci) DESC,
- (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC,
- (i.value6 = vValue6 COLLATE utf8_general_ci) DESC,
- (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC,
- (i.value5 = vValue5 COLLATE utf8_general_ci) DESC,
- (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC,
- (i.value7 = vValue7 COLLATE utf8_general_ci) DESC,
- (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC,
- (i.value8 = vValue8 COLLATE utf8_general_ci) DESC;
-
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `itemProposal_Add` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `itemProposal_Add`(vSaleFk INT, vMateFk INT, vQuantity INT)
-BEGIN
-/**
- * Añade un nuevo articulo para sustituir a otro, y actualiza la memoria de sustituciones.
- *
- * @param vSaleFk id de la tabla sale
- * @param vMateFk articulo sustituto
- * @ param vQuantity cantidad que se va a sustituir
- */
- DECLARE vTicketFk INT;
- DECLARE vItemFk INT;
- DECLARE vWarehouseFk SMALLINT;
- DECLARE vDate DATE;
- DECLARE vGrouping INT;
- DECLARE vBox INT;
- DECLARE vPacking INT;
- DECLARE vRoundQuantity INT DEFAULT 1;
-
- SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk
- INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk
- FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- WHERE s.id = vSaleFk;
-
- UPDATE vn.sale
- SET quantity = quantity - vQuantity
- WHERE id = vSaleFk;
-
- CALL vn.buyUltimate(vWarehouseFk, vDate);
-
- SELECT `grouping`, groupingMode, packing
- INTO vGrouping,vBox,vPacking
- FROM buy b
- JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk
- WHERE tmp.itemFk = vMateFk AND tmp.WarehouseFk = vWarehouseFk;
-
- IF vBox = 2 AND vPacking > 0 THEN
- SET vRoundQuantity = vPacking;
- END IF;
- IF vBox = 1 AND vGrouping > 0 THEN
- SET vRoundQuantity = vGrouping;
- END IF;
-
- INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept)
- SELECT vTicketFk, vMateFk, CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ',i.longName)
- FROM vn.item i
- WHERE id = vMateFk;
-
- SELECT LAST_INSERT_ID() INTO vSaleFk;
-
- CALL vn.sale_calculateComponent(vSaleFk, NULL);
-
- INSERT INTO vn.itemProposal(itemFk, mateFk, counter)
- VALUES(vItemFk, vMateFk, 1)
- ON DUPLICATE KEY UPDATE counter = counter + 1;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `itemProposal_beta` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `itemProposal_beta`(vItemFk INT, vTicketFk INT)
-BEGIN
-
- DECLARE vWarehouseFk INT;
- DECLARE vShipped DATE;
- DECLARE vCalcFk INT;
- DECLARE vTypeFk INT;
- DECLARE vResultsMax INT DEFAULT 10;
-
- DECLARE vTag1 VARCHAR(25);
- DECLARE vTag5 VARCHAR(25);
- DECLARE vTag6 VARCHAR(25);
- DECLARE vTag7 VARCHAR(25);
- DECLARE vTag8 VARCHAR(25);
-
- DECLARE vValue1 VARCHAR(50);
- DECLARE vValue5 VARCHAR(50);
- DECLARE vValue6 VARCHAR(50);
- DECLARE vValue7 VARCHAR(50);
- DECLARE vValue8 VARCHAR(50);
-
- SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped
- FROM vn.ticket
- WHERE id = vTicketFk;
-
- SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value
- INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1
- FROM vn.item i
- LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1
- LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk
- WHERE i.id = vItemFk;
-
- CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped);
-
- SELECT i.id itemFk,
- i.longName,
- i.subName,
- i.tag5,
- i.value5,
- (i.value5 <=> vValue5 COLLATE utf8_general_ci) match5,
- i.tag6,
- i.value6,
- (i.value6 <=> vValue6 COLLATE utf8_general_ci) match6,
- i.tag7,
- i.value7,
- (i.value7 <=> vValue7 COLLATE utf8_general_ci) match7,
- i.tag8,
- i.value8,
- (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8,
- a.available,
- IFNULL(ip.counter,0) counter
- FROM vn.item i
- JOIN cache.available a ON a.item_id = i.id
- LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk
- LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1
- LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk
- WHERE a.calc_id = vCalcFk
- AND available > 0
- AND i.typeFk = vTypeFk
- AND i.id != vItemFk
- ORDER BY counter DESC,
- (t1.name = vTag1 COLLATE utf8_general_ci) DESC,
- (it1.value = vValue1 COLLATE utf8_general_ci) DESC,
- (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC,
- (i.value5 = vValue5 COLLATE utf8_general_ci) DESC,
- (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC,
- (i.value6 = vValue6 COLLATE utf8_general_ci) DESC,
- (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC,
- (i.value7 = vValue7 COLLATE utf8_general_ci) DESC,
- (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC,
- (i.value8 = vValue8 COLLATE utf8_general_ci) DESC
- LIMIT vResultsMax;
-
+ ORDER BY sh.priority DESC,
+ ish.created,
+ p.pickingOrder;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -59854,7 +58156,7 @@ BEGIN
CREATE TEMPORARY TABLE tmp.item
SELECT vItem id;
-
+
CALL item_refreshTags();
DROP TEMPORARY TABLE tmp.item;
@@ -59877,23 +58179,23 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSale_byWeek`(vWeek INT, IN vYear INT, vItemFk INT, vWarehouseFk INT)
BEGIN
-
+
DECLARE vStarted DATE;
DECLARE vEnded DATETIME;
SELECT MIN(dated), util.dayEnd(MAX(dated)) INTO vStarted, vEnded
- FROM `time` t
+ FROM `time` t
WHERE CONCAT(vYear, LPAD(vWeek, 2, 0)) = t.period;
SELECT t.shipped,
w.name warehouse,
- s.ticketFk,
+ s.ticketFk,
t.nickname client,
- am.name agencyName,
+ am.name agencyName,
wk.code salesPerson,
s.itemFk,
- IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept,
- s.quantity,
+ IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept,
+ s.quantity,
s.price,
s.priceFixed,
s.discount,
@@ -59903,15 +58205,15 @@ BEGIN
wk.id salesPersonFk
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
- JOIN warehouse w ON w.id = t.warehouseFk
+ JOIN warehouse w ON w.id = t.warehouseFk
JOIN address a ON a.id = t.addressFk
LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN `client` c ON c.id = a.clientFk
- LEFT JOIN worker wk ON wk.id = c.salesPersonFk
+ LEFT JOIN worker wk ON wk.id = c.salesPersonFk
LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id
- LEFT JOIN saleBuy sb ON sb.saleFk = s.id
- LEFT JOIN buy b ON b.id = sb.buyFk
- LEFT JOIN item ig ON ig.id = b.itemOriginalFk
+ LEFT JOIN saleBuy sb ON sb.saleFk = s.id
+ LEFT JOIN buy b ON b.id = sb.buyFk
+ LEFT JOIN item ig ON ig.id = b.itemOriginalFk
WHERE s.itemFk = vItemFk
AND t.shipped BETWEEN vStarted AND vEnded
AND IF(vWarehouseFk = 0, w.hasComission , t.warehouseFk = vWarehouseFk)
@@ -59938,9 +58240,9 @@ BEGIN
DECLARE vItemFk INT;
SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
-
+
UPDATE vn.item SET minimum = min WHERE id = vItemFk;
-
+
END ;;
@@ -59962,8 +58264,8 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSearchShelving`(`vShelvingFk` VARCHAR(3))
BEGIN
SELECT p.`column` AS col , p.`row`
- FROM vn.shelving s
- JOIN parking p ON s.parkingFk = p.id
+ FROM vn.shelving s
+ JOIN parking p ON s.parkingFk = p.id
WHERE s.`code` = vShelvingFk COLLATE utf8_general_ci;
END ;;
DELIMITER ;
@@ -60004,36 +58306,36 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingLog_get`(vShelvingFk VARCHAR(10) )
BEGIN
-
+
/**
* Devuelve el log de los item en cada carro
*
- * @param vShelvingFk Matrícula del carro
- *
+ * @param vShelvingFk Matrícula del carro
+ *
*/
-
- SELECT isl.itemShelvingFk,
- isl.created,
- isl.accion,
- isl.itemFk,
- isl.shelvingFk,
- isl.quantity,
+
+ SELECT isl.itemShelvingFk,
+ isl.created,
+ isl.accion,
+ isl.itemFk,
+ isl.shelvingFk,
+ isl.quantity,
isl.visible,
- isl.available,
- isl.grouping,
- isl.packing,
- isl.stars,
- item.longName,
- item.size,
- item.subName,
- worker.code,
+ isl.available,
+ isl.grouping,
+ isl.packing,
+ isl.stars,
+ item.longName,
+ item.size,
+ item.subName,
+ worker.code,
isl.accion
- FROM item
- JOIN itemShelvingLog isl ON item.id = isl.itemFk
+ FROM item
+ JOIN itemShelvingLog isl ON item.id = isl.itemFk
JOIN worker ON isl.workerFk = worker.id
WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk
ORDER BY isl.created DESC;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60041,18 +58343,18 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingMakeFromDate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22))
BEGIN
-
+
DECLARE vItemFk INT;
SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
@@ -60071,9 +58373,9 @@ BEGIN
END IF;
- IF (SELECT COUNT(*) FROM vn.itemShelving
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
- AND itemFk = vItemFk
+ IF (SELECT COUNT(*) FROM vn.itemShelving
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ AND itemFk = vItemFk
AND packing = vPacking) = 1 THEN
UPDATE vn.itemShelving
@@ -60098,13 +58400,13 @@ BEGIN
vCreated,
IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`,
IF(vPacking = 0, b.packing, vPacking) packing,
- IF(vPackagingFk = '', b.packageFk, vPackagingFk) packaging
+ IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging
FROM vn.item i
LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
LEFT JOIN vn.buy b ON b.id = lb.buy_id
WHERE i.id = vItemFk;
- END IF;
-
+ END IF;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60125,9 +58427,9 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMatch`(vEntryFk INT, vA
BEGIN
DECLARE vTravelFk INT;
-
- SELECT travelFk INTO vTravelFk
- FROM entry
+
+ SELECT travelFk INTO vTravelFk
+ FROM entry
WHERE id = vEntryFk;
SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas, b.printed
@@ -60140,7 +58442,7 @@ BEGIN
GROUP BY itemFk
) b ON b.itemFk = i.id
LEFT JOIN (
- SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas
+ SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas
FROM itemShelving ish
JOIN shelving sh ON sh.code = ish.shelvingFk
LEFT JOIN parking pk ON pk.id = sh.parkingFk
@@ -60180,7 +58482,7 @@ BEGIN
UPDATE vn.itemShelving
SET visible = visible - vQuantity
WHERE id = vItemShelvingFk;
-
+
END ;;
DELIMITER ;
@@ -60203,47 +58505,47 @@ BEGIN
DECLARE vVisibleCache INT;
DECLARE vWarehouseFk INT;
-
+
SELECT warehouseFk INTO vWarehouseFk
FROM vn.sector
WHERE id = vSectorFk;
CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouseFk);
-
- SELECT t.id as ticketFk,
- CAST(s.quantity AS DECIMAL(10,0)) as Cantidad,
- s.itemFk,
- s.concept,
- v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho,
+
+ SELECT t.id as ticketFk,
+ CAST(s.quantity AS DECIMAL(10,0)) as Cantidad,
+ s.itemFk,
+ s.concept,
+ v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho,
i.subName,
- GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo,
+ GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo,
s.id as saleFk,
IFNULL(sub3.transit,0) transit,
v.visible, s.isPicked, s.reserved, t.shipped, tst.productionOrder, mm.Id_Movimiento
- FROM vn.ticket t
+ FROM vn.ticket t
JOIN vn.ticketState tst ON tst.ticketFk = t.id
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.item i ON i.id = s.itemFk
JOIN cache.visible v ON s.itemFk = v.item_id AND v.calc_id = vVisibleCache
LEFT JOIN vn2008.Movimientos_mark mm ON mm.Id_Movimiento = s.id AND mm.stateFk = 26
- JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id
+ JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id
LEFT JOIN
- (SELECT itemFk, sum(saldo) as transit
- FROM vn.itemPlacementSupplyList
- WHERE saldo > 0
+ (SELECT itemFk, sum(saldo) as transit
+ FROM vn.itemPlacementSupplyList
+ WHERE saldo > 0
AND sectorFk = vSectorFk
GROUP BY itemFk) sub3 ON sub3.itemFk = i.id
- WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity
+ WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity
AND IFNULL(sub3.transit,0) < s.quantity
- AND s.isPicked = FALSE
+ AND s.isPicked = FALSE
AND s.reserved = FALSE
- AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE())
+ AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE())
AND tst.isPreviousPreparable = TRUE
AND t.warehouseFk = vWarehouseFk
AND iss.sectorFk = vSectorFk
AND mm.Id_Movimiento IS NULL
ORDER BY itemFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60260,9 +58562,15 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar`(vSectorFk INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar`(
+ vSectorFk INT
+)
proc:BEGIN
-
+/**
+ * Calcula la información detallada respecto un sector.
+ *
+ * @param vSectorFk Id de sector
+ */
DECLARE vCalcVisibleFk INT;
DECLARE vCalcAvailableFk INT;
DECLARE hasFatherSector BOOLEAN;
@@ -60270,106 +58578,98 @@ proc:BEGIN
DECLARE vWarehouseFk INT DEFAULT 0;
DECLARE vSonSectorFk INT;
DECLARE vWorkerFk INT;
-
- SELECT s.workerFk
- INTO vWorkerFk
+
+ SELECT s.workerFk
+ INTO vWorkerFk
FROM vn.sector s
WHERE s.id = vSectorFk;
SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk
- FROM vn.worker w
+ FROM vn.worker w
JOIN vn.sector s ON s.code = w.code
WHERE s.id = vSectorFk;
-
+
SELECT s.id INTO vSectorFk
FROM vn.sector s
WHERE s.warehouseFk = vWarehouseFk
AND s.isMain;
-
SELECT COUNT(*) INTO hasFatherSector
FROM vn.sector
WHERE sonFk = vSectorFk;
-
+
SELECT warehouseFk, sonFk INTO vWarehouseFk, vSonSectorFk
FROM vn.sector
WHERE id = vSectorFk;
-
+
CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk);
CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar;
-
+
IF hasFatherSector THEN
-
CREATE TEMPORARY TABLE tmp.itemShelvingRadar
(PRIMARY KEY (itemFk))
- ENGINE = MEMORY
- SELECT * FROM (
- SELECT iss.itemFk,
- i.longName,
- i.size,
- i.subName producer,
- IFNULL(a.available,0) available,
- SUM(IF(s.sonFk = vSectorFk, IFNULL(iss.visible,0), 0)) upstairs,
- SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs,
- IF(it.isPackaging, null, IFNULL(v.visible,0)) as visible,
- vSectorFk as sectorFk
-
- FROM vn.itemShelvingStock iss
- JOIN vn.sector s ON s.id = iss.sectorFk
- JOIN vn.item i on i.id = iss.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk)
- LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk
- LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
- WHERE vSectorFk IN (iss.sectorFk, s.sonFk)
- AND it.workerFk != 3366
-
- GROUP BY iss.itemFk
-
- UNION ALL
-
- SELECT v.item_id,
- i.longName,
- i.size,
- i.subName producer,
- IFNULL(a.available,0) as available,
- 0 upstairs,
- 0 downstairs,
- IF(it.isPackaging, NULL, v.visible) visible,
- vSectorFk as sectorFk
- FROM cache.visible v
- JOIN vn.item i on i.id = v.item_id
- JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk)
- LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk
- LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk
- WHERE v.calc_id = vCalcVisibleFk
- AND iss.itemFk IS NULL
- AND it.isInventory
- ) sub GROUP BY itemFk;
-
- SELECT ishr.*,
+ ENGINE = MEMORY
+ SELECT *
+ FROM (
+ SELECT iss.itemFk,
+ i.longName,
+ i.size,
+ i.subName producer,
+ IFNULL(a.available,0) available,
+ SUM(IF(s.sonFk = vSectorFk, IFNULL(iss.visible,0), 0)) upstairs,
+ SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs,
+ IF(it.isPackaging, NULL, IFNULL(v.visible,0)) as visible,
+ vSectorFk sectorFk
+ FROM vn.itemShelvingStock iss
+ JOIN vn.sector s ON s.id = iss.sectorFk
+ JOIN vn.item i on i.id = iss.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk)
+ LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk
+ LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
+ WHERE vSectorFk IN (iss.sectorFk, s.sonFk)
+ GROUP BY iss.itemFk
+
+ UNION ALL
+
+ SELECT v.item_id,
+ i.longName,
+ i.size,
+ i.subName producer,
+ IFNULL(a.available,0) as available,
+ 0 upstairs,
+ 0 downstairs,
+ IF(it.isPackaging, NULL, v.visible) visible,
+ vSectorFk as sectorFk
+ FROM cache.visible v
+ JOIN vn.item i on i.id = v.item_id
+ JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk)
+ LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk
+ LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk
+ WHERE v.calc_id = vCalcVisibleFk
+ AND iss.itemFk IS NULL
+ AND it.isInventory
+ ) sub GROUP BY itemFk;
+
+ SELECT ishr.*,
CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho,
CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente
FROM tmp.itemShelvingRadar ishr
JOIN vn.item i ON i.id = ishr.itemFk
LEFT JOIN (SELECT s.itemFk, sum(s.quantity) as notPickedYed
FROM vn.ticket t
- JOIN vn.ticketStateToday tst ON tst.ticket = t.id
+ JOIN vn.ticketStateToday tst ON tst.ticketFk = t.id
JOIN vn.sale s ON s.ticketFk = t.id
WHERE t.warehouseFk = vWarehouseFk
AND tst.alertLevel = 0
GROUP BY s.itemFk
) sub ON sub.itemFk = ishr.itemFk
- ORDER BY i.typeFk, i.longName
- ;
-
-
+ ORDER BY i.typeFk, i.longName;
ELSE
-
CREATE TEMPORARY TABLE tmp.itemShelvingRadar
(PRIMARY KEY (itemFk))
- ENGINE = MEMORY
+ ENGINE = MEMORY
SELECT iss.itemFk,
0 `hour`,
0 `minute`,
@@ -60381,81 +58681,78 @@ proc:BEGIN
IFNULL(a.available,0) available,
IFNULL(v.visible - iss.visible,0) dayEndVisible,
IFNULL(v.visible - iss.visible,0) firstNegative,
- IFNULL(v.visible - iss.visible,0) itemPlacementVisible,
+ IFNULL(v.visible - iss.visible,0) itemPlacementVisible,
IFNULL(i.minimum * b.packing,0) itemPlacementSize,
ips.onTheWay,
iss.visible itemShelvingStock,
IFNULL(v.visible,0) visible,
b.isPickedOff,
iss.sectorFk
- FROM vn.itemShelvingStock iss
- JOIN vn.item i on i.id = iss.itemFk
- LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk
- LEFT JOIN vn.buy b ON b.id = lb.buy_id
- LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk
- LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
- LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay
- FROM vn.itemPlacementSupplyList
- WHERE saldo > 0
- GROUP BY itemFk
- ) ips ON ips.itemFk = i.id
- WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk)
- OR iss.sectorFk = vSectorFk;
- /*
- UPDATE tmp.itemShelvingRadar isr
- JOIN vn.itemShelvingStock iss ON iss.itemFk = isr.itemFk
- SET isr.dayEndVisible = isr.dayEndVisible + iss.visible,
- isr.firstNegative = isr.firstNegative + iss.visible,
- isr.itemPlacementVisible = isr.itemPlacementVisible + iss.visible
- WHERE iss.sectorFk = vSonSectorFk;
- */
+ FROM vn.itemShelvingStock iss
+ JOIN vn.item i on i.id = iss.itemFk
+ LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN vn.buy b ON b.id = lb.buy_id
+ LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk
+ LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
+ LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay
+ FROM vn.itemPlacementSupplyList
+ WHERE saldo > 0
+ GROUP BY itemFk
+ ) ips ON ips.itemFk = i.id
+ WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk)
+ OR iss.sectorFk = vSectorFk;
+
DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime;
CREATE TEMPORARY TABLE tmp.itemOutTime
SELECT *,SUM(amount) quantity
- FROM
- (SELECT item_id itemFk,
- amount,
- IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours,
+ FROM
+ (SELECT io.itemFk,
+ io.quantity amount,
+ IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours,
IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes
- FROM vn2008.item_out io
- JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id
+ FROM itemTicketOut io
+ JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.itemFk
JOIN vn.ticket t on t.id= io.ticketFk
JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk
JOIN vn.state s ON s.id = ts.stateFk
LEFT JOIN vn.zone z ON z.id = t.zoneFk
- LEFT JOIN (SELECT DISTINCT saleFk
- FROM vn.saleTracking st
- WHERE st.created > util.VN_CURDATE()
+ LEFT JOIN (SELECT DISTINCT saleFk
+ FROM vn.saleTracking st
+ WHERE st.created > util.VN_CURDATE()
AND st.isChecked
) stPrevious ON `stPrevious`.`saleFk` = io.saleFk
WHERE t.warehouseFk = vWarehouseFk
- AND s.isPicked = 0
- AND NOT io.Reservado
+ AND s.isPicked = 0
+ AND NOT io.reserved
AND stPrevious.saleFk IS NULL
- AND io.dat >= util.VN_CURDATE()
- AND io.dat < util.VN_CURDATE() + INTERVAL 1 DAY
+ AND io.shipped >= util.VN_CURDATE()
+ AND io.shipped < util.VN_CURDATE() + INTERVAL 1 DAY
) sub
GROUP BY itemFk, hours, minutes;
-
+
INSERT INTO tmp.itemShelvingRadar (itemFk)
SELECT itemFk FROM tmp.itemOutTime
- ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity,
+ ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity,
firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity),
`hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0),
`minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0);
-/*
- UPDATE tmp.itemShelvingRadar
- SET itemPlacementVisible = 0,
- dayEndVisible = 0,
- firstNegative = 0
- WHERE itemPlacementVisible = - itemShelvingStock;
-*/
- SELECT * FROM tmp.itemShelvingRadar;
+ UPDATE tmp.itemShelvingRadar isr
+ JOIN (SELECT s.itemFk, sum(s.quantity) amount
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN ticketLastState tls ON tls.ticketFk = t.id
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND tls.name = 'Prep Camara'
+ GROUP BY s.itemFk) sub ON sub.itemFk = isr.itemFk
+ SET isr.dayEndVisible = dayEndVisible + sub.amount,
+ firstNegative = firstNegative + sub.amount;
+
+ SELECT * FROM tmp.itemShelvingRadar;
END IF;
DROP TEMPORARY TABLE tmp.itemShelvingRadar;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60479,24 +58776,24 @@ BEGIN
DECLARE vCalcVisibleFk INT;
DECLARE vCalcAvailableFk INT;
DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE());
-
+
CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1);
CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
ENGINE = MEMORY
SELECT DISTINCT itemFk
- FROM vn.buy
+ FROM vn.buy
WHERE entryFk = vEntryFk;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.item2;
CREATE TEMPORARY TABLE tmp.item2
ENGINE = MEMORY
SELECT *
FROM tmp.item;
-
- SELECT i.id as itemFk,
+
+ SELECT i.id as itemFk,
i.minimum,
CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) AS DECIMAL(10,0)) as enNicho,
CAST(IFNULL(a.available,0) AS DECIMAL(10,0)) as disponible,
@@ -60516,11 +58813,11 @@ BEGIN
AND IFNULL(tst.productionOrder,0) < 5
GROUP BY s.itemFK
) ts ON ts.itemFk = i.id;
-
-
+
+
DROP TEMPORARY TABLE tmp.item;
DROP TEMPORARY TABLE tmp.item2;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60544,34 +58841,34 @@ BEGIN
DECLARE vCalcVisibleFk INT;
DECLARE vCalcAvailableFk INT;
DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE());
-
+
CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1);
CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
ENGINE = MEMORY
SELECT DISTINCT itemFk
- FROM vn.buy
+ FROM vn.buy
WHERE entryFk = vEntryFk;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.item2;
CREATE TEMPORARY TABLE tmp.item2
ENGINE = MEMORY
SELECT *
FROM tmp.item;
-
- SELECT i.id as itemFk,
+
+ SELECT i.id as itemFk,
CAST(IFNULL(iss.visible,0) - IFNULL(v.visible,0) AS DECIMAL(10,0)) as outShelving
FROM vn.item i
JOIN tmp.item ti ON ti.itemFk = i.id
LEFT JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = i.id
LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id;
-
-
+
+
DROP TEMPORARY TABLE tmp.item;
DROP TEMPORARY TABLE tmp.item2;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60592,10 +58889,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_Add`(vItemShelving
BEGIN
/**
* Añade línea a itemShelvingSale y regulariza el carro
- *
+ *
* @param vItemShelvingFk Id itemShelving
* @param vSaleFk Id de sale
- * @param vQuantity cantidad a regularizar
+ * @param vQuantity cantidad a regularizar
*/
INSERT INTO itemShelvingSale(itemShelvingFk,
saleFk,
@@ -60622,6 +58919,318 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserve` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserve`()
+BEGIN
+/**
+ * Reserva cantidades con ubicaciones para un conjunto de sales del mismo
+ * almacen.
+ *
+ * @table tmp.sale(saleFk, userFk)
+ */
+ DECLARE vCalcFk INT;
+ DECLARE vWarehouseFk INT;
+ DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW());
+ DECLARE vLastPickingOrder INT;
+
+ SELECT t.warehouseFk, MAX(p.pickingOrder)
+ INTO vWarehouseFk, vLastPickingOrder
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN tmp.sale ts ON ts.saleFk = s.id
+ LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk
+ LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ LEFT JOIN shelving sh ON sh.code = ish.shelvingFk
+ LEFT JOIN parking p ON p.id = sh.parkingFk
+ WHERE t.warehouseFk IS NOT NULL;
+
+ IF vWarehouseFk IS NULL THEN
+ CALL util.throw('Warehouse not set');
+ END IF;
+
+ CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
+
+ SET @outstanding = 0;
+ SET @oldsaleFk = 0;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity
+ (INDEX(saleFk))
+ ENGINE = MEMORY
+ SELECT saleFk, userFk, quantityToReserve, itemShelvingFk
+ FROM( SELECT saleFk,
+ sub.userFk,
+ itemShelvingFk ,
+ IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding),
+ @qtr := LEAST(@outstanding, available) quantityToReserve,
+ @outStanding := @outStanding - @qtr,
+ @oldsaleFk := saleFk
+ FROM(
+ SELECT ts.saleFk,
+ ts.userFk,
+ s.quantity,
+ ish.id itemShelvingFk,
+ ish.visible - IFNULL(ishr.reservedQuantity, 0) available
+ FROM tmp.sale ts
+ JOIN sale s ON s.id = ts.saleFk
+ JOIN itemShelving ish ON ish.itemFk = s.itemFk
+ LEFT JOIN (
+ SELECT itemShelvingFk, SUM(quantity) reservedQuantity
+ FROM itemShelvingSale
+ WHERE NOT isPicked
+ GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector sc ON sc.id = p.sectorFk
+ JOIN warehouse w ON w.id = sc.warehouseFk
+ JOIN productionConfig pc
+ WHERE w.id = vWarehouseFk
+ AND NOT sc.isHideForPickers
+ ORDER BY
+ s.id,
+ p.pickingOrder >= vLastPickingOrder,
+ sh.priority DESC,
+ ish.visible >= s.quantity DESC,
+ s.quantity MOD ish.grouping = 0 DESC,
+ ish.grouping DESC,
+ IF(pc.orderMode = 'Location', p.pickingOrder, ish.created)
+ )sub
+ )sub2
+ WHERE quantityToReserve > 0;
+
+ INSERT INTO itemShelvingSale(
+ itemShelvingFk,
+ saleFk,
+ quantity,
+ userFk)
+ SELECT itemShelvingFk,
+ saleFk,
+ quantityToReserve,
+ IFNULL(userFk, getUser())
+ FROM tSalePlacementQuantity spl;
+
+ DROP TEMPORARY TABLE tmp.sale;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveByCollection` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveByCollection`(
+ vCollectionFk INT(11)
+)
+BEGIN
+/**
+ * Reserva cantidades con ubicaciones para el contenido de una colección
+ *
+ * @param vCollectionFk Identificador de collection
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale
+ (INDEX(saleFk))
+ ENGINE = MEMORY
+ SELECT s.id saleFk, NULL userFk
+ FROM ticketCollection tc
+ JOIN sale s ON s.ticketFk = tc.ticketFk
+ LEFT JOIN (
+ SELECT DISTINCT saleFk
+ FROM saleTracking st
+ JOIN state s ON s.id = st.stateFk
+ WHERE st.isChecked
+ AND s.semaphore = 1)st ON st.saleFk = s.id
+ WHERE tc.collectionFk = vCollectionFk
+ AND st.saleFk IS NULL
+ AND NOT s.isPicked;
+
+ CALL itemShelvingSale_reserve();
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveBySale` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveBySale`(
+ vSelf INT ,
+ vQuantity INT,
+ vUserFk INT
+)
+BEGIN
+/**
+ * Reserva cantida y ubicación para una saleFk
+ *
+ * @param vSelf Identificador de la venta
+ * @param vQuantity Cantidad a reservar
+ * @param vUserFk Id de usuario que realiza la reserva
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale
+ ENGINE = MEMORY
+ SELECT vSelf saleFk, vUserFk userFk;
+
+ CALL itemShelvingSale_reserve();
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setQuantity` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`(
+ vItemShelvingSaleFk INT(10),
+ vQuantity DECIMAL(10,0),
+ vIsItemShelvingSaleEmpty BOOLEAN
+)
+BEGIN
+/**
+ * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity
+ * en vn.itemShelvingSale y vn.sale.isPicked en caso necesario.
+ * Si la reserva de la ubicación es fallida, se regulariza la situación
+ *
+ * @param vItemShelvingSaleFk Id itemShelvingSaleFK
+ * @param vQuantity Cantidad real que se ha cogido de la ubicación
+ * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha
+ * quedado vacio tras el movimiento
+ */
+ DECLARE vSaleFk INT;
+ DECLARE vCursorSaleFk INT;
+ DECLARE vItemShelvingFk INT;
+ DECLARE vReservedQuantity INT;
+ DECLARE vRemainingQuantity INT;
+ DECLARE vItemFk INT;
+ DECLARE vUserFk INT;
+ DECLARE vDone BOOLEAN DEFAULT FALSE;
+ DECLARE vSales CURSOR FOR
+ SELECT iss.saleFk, iss.userFk
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.id = vItemShelvingSaleFk
+ AND s.itemFk = vItemFk
+ AND NOT iss.isPicked;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN
+ CALL util.throw('Booking completed');
+ END IF;
+
+ SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk
+ INTO vItemFk, vSaleFk, vItemShelvingFk
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.id = vItemShelvingSaleFk
+ AND NOT iss.isPicked;
+
+ UPDATE itemShelvingSale
+ SET isPicked = TRUE,
+ quantity = vQuantity
+ WHERE id = vItemShelvingSaleFk;
+
+ UPDATE itemShelving
+ SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity))
+ WHERE id = vItemShelvingFk;
+
+ IF vIsItemShelvingSaleEmpty THEN
+ OPEN vSales;
+l: LOOP
+ SET vDone = FALSE;
+ FETCH vSales INTO vCursorSaleFk, vUserFk;
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale
+ (INDEX(saleFk, userFk))
+ ENGINE = MEMORY
+ SELECT vCursorSaleFk, vUserFk;
+
+ CALL itemShelvingSale_reserveWhitUser();
+ DROP TEMPORARY TABLE tmp.sale;
+
+ END LOOP;
+ CLOSE vSales;
+
+ DELETE iss
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.id = vItemShelvingSaleFk
+ AND s.itemFk = vItemFk
+ AND NOT iss.isPicked;
+ END IF;
+
+ SELECT SUM(quantity) INTO vRemainingQuantity
+ FROM itemShelvingSale
+ WHERE saleFk = vSaleFk
+ AND NOT isPicked;
+
+ IF vRemainingQuantity THEN
+ CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL);
+
+ SELECT SUM(quantity) INTO vRemainingQuantity
+ FROM itemShelvingSale
+ WHERE saleFk = vSaleFk
+ AND NOT isPicked;
+
+ IF NOT vRemainingQuantity <=> 0 THEN
+ SELECT SUM(iss.quantity)
+ INTO vReservedQuantity
+ FROM itemShelvingSale iss
+ WHERE iss.saleFk = vSaleFk;
+
+ CALL saleTracking_new(
+ vSaleFk,
+ TRUE,
+ vReservedQuantity,
+ `account`.`myUser_getId`(),
+ NULL,
+ 'PREPARED',
+ TRUE);
+
+ UPDATE sale s
+ SET s.quantity = vReservedQuantity
+ WHERE s.id = vSaleFk ;
+ END IF;
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingTransfer` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -60679,75 +59288,75 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET collation_connection = utf8mb4_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT)
-BEGIN
-
-
-/**
- * Añade registro o lo actualiza si ya existe.
- *
- * @param vShelvingFk matrícula del carro
- * @param vBarcode el id del registro
- * @param vQuantity indica la cantidad del producto
- * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra
- * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra
- * @param vPacking el packing del producto, NULL para coger el de la ultima compra
- * @param vWarehouseFk indica el sector
- *
- **/
-
- DECLARE vItemFk INT;
-
- SELECT barcodeToItem(vBarcode) INTO vItemFk;
-
- IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN
-
- INSERT IGNORE INTO parking(code) VALUES(vShelvingFk);
- INSERT INTO shelving(code, parkingFk)
- SELECT vShelvingFk, id
- FROM parking
- WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci;
-
- END IF;
-
- IF (SELECT COUNT(*) FROM itemShelving
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
- AND itemFk = vItemFk
- AND packing = vPacking) = 1 THEN
-
- UPDATE itemShelving
- SET visible = visible+vQuantity
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking;
-
- ELSE
- CALL cache.last_buy_refresh(FALSE);
- INSERT INTO itemShelving( itemFk,
- shelvingFk,
- visible,
- grouping,
- packing,
- packagingFk)
-
- SELECT vItemFk,
- vShelvingFk,
- vQuantity,
- IFNULL(vGrouping, b.grouping),
- IFNULL(vPacking, b.packing),
- IFNULL(vPackagingFk, b.packageFk)
- FROM item i
- LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
- LEFT JOIN buy b ON b.id = lb.buy_id
- WHERE i.id = vItemFk;
- END IF;
+BEGIN
+
+
+/**
+ * Añade registro o lo actualiza si ya existe.
+ *
+ * @param vShelvingFk matrícula del carro
+ * @param vBarcode el id del registro
+ * @param vQuantity indica la cantidad del producto
+ * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra
+ * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra
+ * @param vPacking el packing del producto, NULL para coger el de la ultima compra
+ * @param vWarehouseFk indica el sector
+ *
+ **/
+
+ DECLARE vItemFk INT;
+
+ SELECT barcodeToItem(vBarcode) INTO vItemFk;
+
+ IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN
+
+ INSERT IGNORE INTO parking(code) VALUES(vShelvingFk);
+ INSERT INTO shelving(code, parkingFk)
+ SELECT vShelvingFk, id
+ FROM parking
+ WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci;
+
+ END IF;
+
+ IF (SELECT COUNT(*) FROM itemShelving
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ AND itemFk = vItemFk
+ AND packing = vPacking) = 1 THEN
+
+ UPDATE itemShelving
+ SET visible = visible+vQuantity
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking;
+
+ ELSE
+ CALL cache.last_buy_refresh(FALSE);
+ INSERT INTO itemShelving( itemFk,
+ shelvingFk,
+ visible,
+ grouping,
+ packing,
+ packagingFk)
+
+ SELECT vItemFk,
+ vShelvingFk,
+ vQuantity,
+ IFNULL(vGrouping, b.grouping),
+ IFNULL(vPacking, b.packing),
+ IFNULL(vPackagingFk, b.packagingFk)
+ FROM item i
+ LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN buy b ON b.id = lb.buy_id
+ WHERE i.id = vItemFk;
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60859,27 +59468,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_BuyerGet` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_BuyerGet`( )
-BEGIN
-
- SELECT * FROM vn.buyer;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_filterBuyer` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -60901,7 +59489,7 @@ proc:BEGIN
CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk);
- SELECT * FROM
+ SELECT * FROM
(SELECT sub.itemFk,
sub.longName,
CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`,
@@ -60912,17 +59500,17 @@ proc:BEGIN
CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho,
sub.name itemColour
FROM (SELECT iss.itemFk,
- CONCAT(i.longName, ' ', i.size,' ', IFNULL(i.subName,'') ) longName,
+ CONCAT(i.longName, ' ', IFNULL(i.size, ''),' ', IFNULL(i.subName, '') ) longName,
'' size,
CONCAT(iss.parkingCode, ' ', iss.shelvingFk) producer,
0 upstairs,
SUM(IFNULL(iss.visible,0)) downstairs,
IF(it.isPackaging, null, IFNULL(v.visible, 0)) visible,
- ik.name
+ ik.name
FROM itemShelvingStock iss
JOIN sector s ON s.id = iss.sectorFk
JOIN item i on i.id = iss.itemFk
- LEFT JOIN ink ik ON ik.id = i.inkFk
+ LEFT JOIN ink ik ON ik.id = i.inkFk
JOIN itemType it ON it.id = i.typeFk
LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
WHERE s.warehouseFk = vWarehouseFk
@@ -60931,16 +59519,15 @@ proc:BEGIN
) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente
FROM sale s
LEFT JOIN saleTracking st ON st.saleFk = s.id
- JOIN ticket t ON t.id = s.ticketFk
+ JOIN ticket t ON t.id = s.ticketFk
JOIN client c on c.id = t.clientFk
- JOIN clientType ct ON ct.id = c.clientTypeFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
AND st.saleFk IS NULL
- AND ct.code IN ('normal', 'trust')
+ AND c.typeFk IN ('normal', 'trust')
GROUP BY s.itemFk
) sub2 ON sub2.itemFk = sub.itemFk
UNION ALL
- SELECT v.item_id ,
+ SELECT v.item_id,
i.longName,
CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`,
CONCAT(IF(sub5.pendiente,'(0) ','(3) ')) producer,
@@ -60957,12 +59544,11 @@ proc:BEGIN
LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente
FROM sale s
LEFT JOIN saleTracking st ON st.saleFk = s.id
- JOIN ticket t ON t.id = s.ticketFk
+ JOIN ticket t ON t.id = s.ticketFk
JOIN client c on c.id = t.clientFk
- JOIN clientType ct ON ct.id = c.clientTypeFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
AND st.saleFk IS NULL
- AND ct.code IN ('normal', 'trust')
+ AND c.typeFk IN ('normal', 'trust')
GROUP BY s.itemFk
) sub5 ON sub5.itemFk = v.item_id
WHERE v.calc_id = vCalcVisibleFk
@@ -60990,12 +59576,12 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_get`(IN vSelf VARCHAR(8))
BEGIN
/**
-* Lista artículos de itemshelving
+* Lista artículos de itemshelving
*
* @param vSelf matrícula del carro
**/
- SELECT ish.itemFk item,
- IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description,
+ SELECT ish.itemFk item,
+ IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description,
ish.visible,
CEIL(ish.visible/ish.packing) stickers,
ish.packing,
@@ -61003,11 +59589,13 @@ BEGIN
p.code,
ish.id,
s.priority,
- ish.isChecked
+ ish.isChecked,
+ ic.url
FROM itemShelving ish
JOIN item i ON i.id = ish.itemFk
JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci
LEFT JOIN parking p ON s.parkingFk = p.id
+ JOIN hedera.imageConfig ic
WHERE ish.shelvingFk COLLATE utf8_unicode_ci = vSelf;
END ;;
DELIMITER ;
@@ -61033,7 +59621,7 @@ BEGIN
*
* @param vShelvingFk matricula del carro
*/
- SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder
+ SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder
FROM itemShelving is2
JOIN shelving sh ON sh.code = is2.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
@@ -61098,92 +59686,167 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3))
-BEGIN
-
- /* Devuelve la minima fecha en que se necesita cada producto en esa matricula.
- *
- * @param vShelvingFk Matrícula del carro o pallet
- */
-
- DECLARE vWarehouseFk INT;
-
- SELECT warehouseFk INTO vWarehouseFk
- FROM shelving s
- JOIN parking p ON s.parkingFk = p.id
- JOIN sector st ON st.id = p.sectorFk
- WHERE s.code = vShelvingFk COLLATE utf8_unicode_ci;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingDistinct;
- CREATE TEMPORARY TABLE tmp.itemShelvingDistinct
- (PRIMARY KEY (itemFk))
- ENGINE = MEMORY
- SELECT itemFk, SUM(visible) visible
- FROM vn.itemShelving
- WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
- GROUP BY itemFk;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.item;
- CREATE TEMPORARY TABLE tmp.item
- (PRIMARY KEY (itemFk))
- ENGINE = MEMORY
- SELECT * FROM tmp.itemShelvingDistinct;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.stockByDay;
- CREATE TEMPORARY TABLE tmp.stockByDay
- (index (itemFk, dated))
- ENGINE = MEMORY
- SELECT t3.amount, dated,
- @stock := IF(@itemFk = t3.itemFk, @stock + t3.amount, t3.amount) stock,
- @itemFk := t3.itemFk itemFk
- FROM (
- SELECT * FROM (
- SELECT t2.* FROM (
- SELECT item_id itemFk, amount, util.VN_CURDATE() dated
- FROM cache.stock
- WHERE warehouse_id = vWarehouseFk
- UNION ALL
- SELECT ish.itemFk, - sum(visible), util.VN_CURDATE()
- FROM vn.itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
- JOIN parking p ON sh.parkingFk = p.id
- JOIN sector s ON s.id = p.sectorFk
- WHERE s.isReserve
- GROUP BY ish.itemFk
- UNION ALL
- SELECT item_id, sum(iei.amount), dat
- FROM vn2008.item_entry_in iei
- WHERE dat >= util.VN_CURDATE()
- AND warehouse_id = vWarehouseFk
- AND isVirtualStock = FALSE
- GROUP BY item_id, dat
- UNION ALL
- SELECT item_id, sum(ieo.amount), dat
- FROM vn2008.item_entry_out ieo
- WHERE dat >= util.VN_CURDATE()
- AND warehouse_id = vWarehouseFk
- GROUP BY item_id, dat
- UNION ALL
- SELECT i.itemFk, sum(io.amount), dat
- FROM vn2008.item_out io
- JOIN tmp.item i ON i.itemFk = io.item_id
- WHERE io.dat >= util.VN_CURDATE()
- AND io.warehouse_id = vWarehouseFk
- GROUP BY io.item_id, io.dat
- ) t2
- JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = t2.itemFk) t
- order by t.itemFk, DATE(t.dated), t.amount DESC) t3;
-
- SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock
- FROM tmp.stockByDay sbd
- JOIN vn.item i ON i.id = sbd.itemFk
- JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = sbd.itemFk
- WHERE ish.visible >= sbd.stock
- GROUP BY itemFk
- ORDER BY dated;
-
- DROP TEMPORARY TABLE tmp.stockByDay,
- tmp.itemShelvingDistinct,
- tmp.item;
+BEGIN
+
+ /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula.
+ *
+ * @param vShelvingFk Matrícula del carro o pallet
+ */
+
+ DECLARE vWarehouseFk INT;
+ DECLARE vStockScopeDays INT;
+
+ SELECT s.warehouseFk, stockScopeDays
+ INTO vWarehouseFk, vStockScopeDays
+ FROM sector s
+ JOIN operator o ON s.id = o.sectorFk
+ JOIN productionConfig pc
+ WHERE o.workerFk = account.myUser_getId();
+
+ IF vWarehouseFk IS NULL
+ THEN CALL util.throw('WarehouseFk not setted');
+ END IF;
+
+ IF vStockScopeDays IS NULL
+ THEN CALL util.throw('StockScopeDays not setted');
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.tItems
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk, SUM(visible) visible
+ FROM itemShelving
+ WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
+ GROUP BY itemFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay
+ (INDEX (itemFk, dated))
+ ENGINE = MEMORY
+ SELECT dated,
+ SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock,
+ t3.itemFk
+ FROM (
+ SELECT t.itemFk, dated, SUM(amount) amount
+ FROM (
+ SELECT t2.itemFk, t2.amount, t2.dated
+ FROM (
+ SELECT item_id itemFk, amount, util.VN_CURDATE() dated
+ FROM cache.stock s
+ JOIN tmp.tItems i ON i.itemFk = s.item_id
+ WHERE s.warehouse_id = vWarehouseFk
+ UNION ALL
+ SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE()
+ FROM itemShelving ish
+ JOIN tmp.tItems i ON i.itemFk = ish.itemFk
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON sh.parkingFk = p.id
+ JOIN sector s ON s.id = p.sectorFk
+ WHERE s.isReserve
+ GROUP BY ish.itemFk
+ UNION ALL
+ SELECT iei.itemFk, SUM(quantity), landed
+ FROM itemEntryIn iei
+ JOIN tmp.tItems i ON i.itemFk = iei.itemFk
+ WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
+ AND iei.warehouseInFk = vWarehouseFk
+ AND NOT isVirtualStock
+ GROUP BY iei.itemFk, iei.landed
+ UNION ALL
+ SELECT ieo.itemFk, SUM(quantity), shipped
+ FROM itemEntryOut ieo
+ JOIN tmp.tItems i ON i.itemFk = ieo.itemFk
+ WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
+ AND ieo.warehouseOutFk = vWarehouseFk
+ GROUP BY ieo.itemFk, ieo.shipped
+ UNION ALL
+ SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped)
+ FROM itemTicketOut ito
+ JOIN tmp.tItems i ON i.itemFk = ito.itemFk
+ WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
+ AND ito.warehouseFk = vWarehouseFk
+ GROUP BY ito.itemFk, ito.shipped
+ ) t2
+ JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t
+ GROUP BY t.itemFk, dated
+ ) t3;
+
+ -- Se restan las entradas de hoy
+ UPDATE tmp.tStockByDay sbd
+ JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry
+ FROM itemEntryIn iei
+ JOIN tmp.tItems i ON i.itemFk = iei.itemFk
+ WHERE iei.landed = util.VN_CURDATE()
+ AND iei.warehouseInFk = vWarehouseFk
+ AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk
+ SET sbd.stock = sbd.stock - sub.todayEntry
+ WHERE sbd.dated = util.VN_CURDATE();
+
+ -- Se añaden las lineas de venta servidas
+ UPDATE tmp.tStockByDay sbd
+ JOIN (SELECT s.itemFK, SUM(quantity) amount
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE t.warehouseFk = vWarehouseFk
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight()
+ AND s.isPicked
+ GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk
+ SET sbd.stock = sbd.stock + sub.amount;
+
+ -- Se añaden los items ubicados hoy
+ UPDATE tmp.tStockByDay sbd
+ JOIN (SELECT ish.itemFK, SUM(ish.visible) amount
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector s ON s.id = p.sectorFk
+ WHERE s.warehouseFk = vWarehouseFk
+ AND NOT s.isReserve
+ AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight()
+ GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk
+ SET sbd.stock = sbd.stock + sub.amount;
+
+ SELECT ts.itemFk,
+ i.longName,
+ IF(ts.stock<=0, ts.dated, NULL) dated,
+ ts.stock,
+ sub4.visible,
+ sub4.shelvingFk
+ FROM(
+ SELECT IFNULL(sub2.minDated, sub.minDated) dated,
+ IFNULL(sub2.itemFk, sub.itemFk) itemFk
+ FROM(SELECT sbd.itemFk,
+ MIN(dated) minDated,
+ sbd.stock
+ FROM tmp.tItems ti
+ LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk
+ GROUP BY itemFk)sub
+ LEFT JOIN (
+ SELECT sbd.itemFk,
+ MIN(dated) minDated,
+ sbd.stock
+ FROM tmp.tItems ti
+ LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk
+ WHERE sbd.stock <= 0
+ GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk
+ WHERE sub2.itemFk IS NOT NULL
+ OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3
+ LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated
+ JOIN (SELECT ish.itemFk,
+ ish.visible,
+ p.sectorFk,
+ ish.shelvingFk
+ FROM itemShelving ish
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ LEFT JOIN parking p ON p.id = parkingFk
+ LEFT JOIN vn.sector s ON s.id = p.sectorFk
+ WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
+ ) sub4 ON sub4.itemFk = ts.itemFk
+ LEFT JOIN sector s ON s.id = sub4.sectorFk
+ LEFT JOIN item i ON i.id = ts.itemFk
+ WHERE NOT s.isReserve;
+
+ DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -61231,10 +59894,11 @@ BEGIN
ish.visible,
p.sectorFk,
it.workerFk buyer,
- CONCAT('http:',ic.url, '/catalog/1600x900/',i.image) urlImage,
+ ic.url,
+ i.image,
ish.isChecked,
CASE
- WHEN s.notPrepared > sm.parked THEN 0
+ WHEN IFNULL (s.notPrepared, 0) > sm.parked THEN 0
WHEN sm.visible > sm.parked THEN 1
ELSE 2
END priority
@@ -61244,7 +59908,7 @@ BEGIN
JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
- JOIN (
+ LEFT JOIN (
SELECT s.itemFk, sum(s.quantity) notPrepared
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
@@ -61276,15 +59940,15 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_selfConsumption`(
- vShelvingFk VARCHAR(10) COLLATE utf8_general_ci,
- vItemFk INT,
+ vShelvingFk VARCHAR(10) COLLATE utf8_general_ci,
+ vItemFk INT,
vQuantity INT
)
-BEGIN
+BEGIN
/**
- * Leave the indicated amount on the shelf
+ * Leave the indicated amount on the shelf
* and create a ticket with the difference.
- *
+ *
* @param vShelvingFk id of the shelf where the item is located.
* @param vItemFk article of which the self-consumption ticket is to be created.
* @param vQuantity amount that will stay on the shelf
@@ -61296,19 +59960,23 @@ BEGIN
DECLARE vCompanyFk INT;
DECLARE vAgencyModeFk INT;
DECLARE vItemShelvingFk INT;
+ DECLARE vAddressFk INT;
SELECT c.id,
- c.clientFk,
- s.warehouseFk
+ pc.clientSelfConsumptionFk,
+ s.warehouseFk,
+ pc.addressSelfConsumptionFk
INTO vCompanyFk,
vClientFk,
- vWarehouseFk
+ vWarehouseFk,
+ vAddressFk
FROM company c
JOIN address a ON a.clientFk = c.clientFk
JOIN warehouse w ON w.addressFk = a.id
JOIN sector s ON s.warehouseFk = w.id
JOIN parking p ON p.sectorFk = s.id
JOIN shelving s2 ON s2.parkingFk = p.id
+ JOIN productionConfig pc
WHERE s2.code = vShelvingFk;
IF vClientFk IS NULL THEN
@@ -61328,10 +59996,10 @@ BEGIN
END IF;
SELECT SUM(visible), id INTO vVisible, vItemShelvingFk
- FROM itemShelving
+ FROM itemShelving
WHERE shelvingFk = vShelvingFk
AND itemFk = vItemFk;
-
+
IF vVisible IS NULL THEN
CALL util.throw('The item is not on the shelf.');
END IF;
@@ -61340,7 +60008,7 @@ BEGIN
vClientFk,
vWarehouseFk,
CURDATE(),
- NULL,
+ vAddressFk,
vCompanyFk,
NULL,
vTicketFk
@@ -61384,9 +60052,9 @@ BEGIN
* @param vGrouping el grouping del producto en itemShelving
*/
UPDATE itemShelving
- SET visible = vVisible,
- packing = vPacking,
- grouping = vGrouping
+ SET visible = vVisible,
+ packing = vPacking,
+ grouping = vGrouping
WHERE id = vShelf;
END ;;
@@ -61408,7 +60076,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagMake`(vItemFk INT)
BEGIN
-/* * Crea los tags usando la tabla plantilla itemTag
+/* * Crea los tags usando la tabla plantilla itemTag
* y si no existe a partir de la ficha del artículo.
* @param vItemFk El item al que se le añaden los tags
*/
@@ -61418,33 +60086,33 @@ BEGIN
DECLARE vProducer VARCHAR(50);
DECLARE vOrigin VARCHAR(20);
DECLARE vTypeFk INTEGER;
-
- DELETE FROM itemTag
+
+ DELETE FROM itemTag
WHERE itemFk = vItemFk;
-
- SELECT typeFk INTO vTypeFk
+
+ SELECT typeFk INTO vTypeFk
FROM item
WHERE id = vItemFk;
-
+
INSERT INTO itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, itt.tagFk, NULL, itt.priority
FROM itemTag it
LEFT JOIN itemTypeTag itt ON itt.itemTypeFk = vTypeFk
WHERE it.itemFk = vItemFk;
-
+
IF (SELECT COUNT(*) FROM itemTag WHERE itemFk = vItemFk LIMIT 1) = 0 THEN
- SELECT ik.name, i.size, i.category, p.name, o.name
+ SELECT ik.name, i.size, i.category, p.name, o.name
INTO vInk, vSize, vCategory, vProducer, vOrigin
FROM item i
LEFT JOIN ink ik ON ik.id = i.inkFk
LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
LEFT JOIN origin o ON o.id = i.originFk
WHERE i.id = vItemFk;
-
+
INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
VALUES(vItemFk, 1, vInk, 1);
-
+
INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
VALUES (vItemFk, 8, vSize, 2);
@@ -61453,11 +60121,11 @@ BEGIN
INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
VALUES(vItemFk, 37, vProducer, 4);
-
+
INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
VALUES(vItemFk, 35, vOrigin, 5);
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -61478,12 +60146,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorder`(itemTypeFk INT)
BEGIN
SET @isTriggerDisabled = TRUE;
-
+
-- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i
DROP TABLE IF EXISTS tmp.item;
CREATE TABLE tmp.item
SELECT DISTINCT i.id
- FROM vn.item i
+ FROM vn.item i
WHERE i.typeFk = itemTypeFk;
UPDATE itemTag it
@@ -61492,8 +60160,8 @@ BEGIN
JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk
SET it.priority = itt.priority
WHERE itt.itemTypeFk = itemTypeFk;
-
- CALL item_refreshTags();
+
+ CALL item_refreshTags();
SET @isTriggerDisabled = FALSE;
@@ -61518,12 +60186,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorderByName`(vName VARCHAR
BEGIN
SET @isTriggerDisabled = TRUE;
-
+
-- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i
DROP TABLE IF EXISTS tmp.item;
CREATE TABLE tmp.item
SELECT DISTINCT i.id
- FROM vn.item i
+ FROM vn.item i
WHERE i.`name` LIKE CONCAT(vName,'%');
UPDATE itemTag it
@@ -61532,8 +60200,8 @@ BEGIN
JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk
SET it.priority = itt.priority
WHERE itt.itemTypeFk = itemTypeFk;
-
- CALL item_refreshTags();
+
+ CALL item_refreshTags();
SET @isTriggerDisabled = FALSE;
@@ -61556,36 +60224,36 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTag_replace`(vItemFromFk INT, vItemToFk INT, vPicture VARCHAR(100))
BEGIN
-
+
/* Reemplaza los tags de un artículo por los de otro, así como su imagen
- *
+ *
* @param vItemFromFk id de vn.item con el artículo del que se toman los tags
* @param vItemToFk id de vn.item con el artículo del que se toman los tags
* @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk
*/
- DELETE FROM vn.itemTag
+ DELETE FROM vn.itemTag
WHERE itemFk = vItemToFk;
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemToFk, tagFk, value, priority
- FROM vn.itemTag
+ FROM vn.itemTag
WHERE itemFk = vItemFromFk;
-
+
IF ISNULL(vPicture) THEN
-
- SELECT image INTO vPicture
- FROM vn.item
+
+ SELECT image INTO vPicture
+ FROM vn.item
WHERE id = vItemFromFk;
-
+
END IF;
- UPDATE vn.item i
+ UPDATE vn.item i
SET i.image = vPicture
WHERE i.id = vItemToFk;
-
+
CALL vn.itemRefreshTags(vItemToFk);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -61610,9 +60278,9 @@ BEGIN
SELECT DISTINCT id
FROM vn.itemCategory
WHERE merchandise <> FALSE;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
RESIGNAL;
END;
@@ -61623,45 +60291,45 @@ BEGIN
INNER JOIN bs.ventas v ON v.Id_Movimiento = s.id
WHERE v.fecha BETWEEN TIMESTAMPADD(DAY, - 7, util.VN_CURDATE()) AND util.VN_CURDATE()
GROUP BY s.itemFk;
-
+
DROP TABLE IF EXISTS tmp.topSeller;
- CREATE TEMPORARY TABLE tmp.topSeller
- (
+ CREATE TEMPORARY TABLE tmp.topSeller
+ (
`id` int(11) NOT NULL DEFAULT '0',
`typeFk` smallint(5) unsigned NOT NULL,
`itemCategoryFk` int(10) unsigned NOT NULL,
`total` bigint(21) NOT NULL DEFAULT '0'
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-
+
OPEN rs;
read_loop: LOOP
FETCH rs INTO vCategoryFk;
-
+
IF vDone THEN
LEAVE read_loop;
END IF;
-
+
INSERT INTO tmp.topSeller
SELECT tsm.itemFk, tsm.typeFk, it.categoryFk, tsm.total
FROM tmp.topSellerMin tsm
INNER JOIN vn.itemType it ON it.id = tsm.typeFk
WHERE it.categoryFk = vCategoryFk
ORDER BY tsm.itemFk ,tsm.total DESC
- LIMIT 5;
+ LIMIT 5;
END LOOP;
CLOSE rs;
-
+
SELECT i.name ,i.id, i.image, i.typeFk, it.categoryFk AS itemCategoryFk,
ic.name AS itemCategoryName, it.name AS itemTypeName, ts.total
FROM tmp.topSeller ts
INNER JOIN vn.item i ON i.id = ts.id
INNER JOIN vn.itemType it ON it.id = ts.typeFk
INNER JOIN vn.itemCategory ic ON ic.id = it.categoryFk;
-
+
DROP TABLE IF EXISTS topSellerMin;
DROP TABLE IF EXISTS tmp.topSeller;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -61771,7 +60439,7 @@ SET tag6 = t.name, value6 = it.value
WHERE it.priority = 2
AND (vItem IS NULL OR vItem = it.itemFk);
-UPDATE item i
+UPDATE item i
JOIN itemTag it ON it.itemFk = i.id
JOIN tag t ON t.id = it.tagFk
SET tag7 = t.name, value7 = it.value
@@ -61804,7 +60472,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_cleanFloramondo`()
BEGIN
/**
-* Elimina todos los items repetidos de floramondo
+* Elimina todos los items repetidos de floramondo
* y los sustituye por el que tiene menor id
*/
DECLARE vItemFrom INT;
@@ -61870,7 +60538,7 @@ BEGIN
AND i2.EmbalageCode <=> i.EmbalageCode
AND i2.quality <=> i.quality
JOIN (
- SELECT DISTINCT b.itemFk
+ SELECT DISTINCT b.itemFk
FROM buy b
JOIN item i ON i.id = b.itemFk
WHERE i.isFloramondo
@@ -61878,7 +60546,7 @@ BEGIN
)sub2 ON sub2.itemFk = GREATEST(i.id, i2.id)
WHERE i.isFloramondo
AND i.id <> i2.id;
-
+
DECLARE EXIT HANDLER FOR SQLEXCEPTION SET vDone = TRUE;
BEGIN
SET vDone = TRUE;
@@ -62009,6 +60677,316 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `item_comparative` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `item_comparative`(
+ vDate DATETIME,
+ vDayRange TINYINT,
+ vWarehouseFk TINYINT,
+ vAvailableSince DATE,
+ vBuyerFk INT,
+ vIsFloramondo BOOL,
+ vCountryFk INT
+)
+proc: BEGIN
+/**
+ * Genera una tabla de comparativa de artículos por itemType/comprador/fecha.
+ * Los datos se calculan en función de los parámetros proporcionados.
+ *
+ * @param vDate La fecha para la cual se generará la comparativa.
+ * @param vDayRange El rango de días a considerar para la comparativa.
+ * @param vWarehouseFk El identificador del almacén para filtrar los artículos.
+ * @param vAvailableSince La fecha de disponibilidad desde la cual se consideran los artículos disponibles.
+ * @param vBuyerFk El identificador del comprador para filtrar los artículos.
+ * @param vIsFloramondo Indica si se deben incluir solo los artículos de Floramondo (opcional).
+ * @param vCountryFk El identificador del país.
+ * @param tmp.comparativeFilterType(filterFk INT ,itemTypeFk INT)
+ * @return tmp.comparative
+ */
+
+ DECLARE vDayRangeStart DATE;
+ DECLARE vDayRangeEnd DATE;
+ DECLARE w1, w2, w3, w4, w5, w6, w7 INT;
+ DECLARE y1, y2, y3, y4, y5, y6, y7 INT;
+ DECLARE z1, z2, z3, z4, z5, z6, z7 INT;
+ DECLARE vPeriod INT;
+ DECLARE i INT DEFAULT 0;
+ DECLARE vHasTypeFilter BOOL;
+ DECLARE vWeekRange INT;
+ DECLARE vWeekCount TINYINT;
+ DECLARE vMaxDayRange INT;
+ DECLARE vMinDayRange INT;
+ DECLARE vDefaultDayRange INT;
+
+ IF NOT(SELECT COUNT(*) FROM comparativeConfig)THEN
+ LEAVE proc;
+ END IF;
+
+ SELECT weekRange,
+ weekRange * 2 + 1,
+ maxDayRange,
+ minDayRange,
+ defaultDayRange
+ INTO vWeekRange,
+ vWeekCount,
+ vMaxDayRange,
+ vMinDayRange,
+ vDefaultDayRange
+ FROM comparativeConfig;
+
+ IF vDayRange < vMinDayRange OR vDayRange > vMaxDayRange THEN
+ SET vDayRange = vDefaultDayRange;
+ END IF;
+
+ SELECT MIN(dated) INTO vDayRangeStart
+ FROM vn.time
+ WHERE dated <= vDate
+ GROUP BY period
+ ORDER BY dated desc
+ LIMIT 1 OFFSET vWeekRange;
+
+ SELECT MAX(dated) INTO vDayRangeEnd
+ FROM vn.time
+ WHERE dated >= vDate
+ GROUP BY period
+ ORDER BY dated ASC
+ LIMIT 1 OFFSET vWeekRange;
+
+ SELECT COUNT(itemTypeFk) > 0 INTO vHasTypeFilter
+ FROM tmp.comparativeFilterType;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemInventory
+ (PRIMARY KEY (id))
+ ENGINE = MEMORY
+ SELECT i.id
+ FROM item i
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN itemCategory c ON c.id = t.categoryFk
+ LEFT JOIN worker w ON w.id = t.workerFk
+ WHERE (NOT vHasTypeFilter
+ OR t.id IN (SELECT itemTypeFk FROM tmp.comparativeFilterType))
+ AND (vBuyerFk IS NULL
+ OR t.workerFk = vBuyerFk)
+ AND (vIsFloramondo IS NULL
+ OR i.isFloramondo = vIsFloramondo);
+
+ IF vDate < util.VN_CURDATE() THEN
+ ALTER TABLE tmp.itemInventory
+ ADD `buy_id` INT NOT NULL DEFAULT 0,
+ ADD `buy_date` DATE DEFAULT '2000-01-01',
+ ADD `life` INT DEFAULT 0,
+ ADD `sd` INT DEFAULT 0,
+ ADD `avalaible` INT DEFAULT 0,
+ ADD `visible` INT DEFAULT 0;
+ ELSE
+ CALL multipleInventory(vAvailableSince, vWarehouseFk, vDayRange);
+ CALL item_multipleBuy(vDate, vWarehouseFk);
+ CALL item_multipleBuyByDate(vDate, vWarehouseFk);
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTable (
+ cy INT(6) PRIMARY KEY,
+ ly INT(6),
+ zy INT(6),
+ INDEX (ly)
+ );
+
+ REPEAT
+ SET i = i + 1;
+
+ SELECT t.period INTO vPeriod
+ FROM vn.`time` t
+ WHERE t.dated = vDayRangeStart + INTERVAL (vWeekCount * (i - 1)) DAY;
+
+ INSERT IGNORE INTO tTable(cy, ly, zy) VALUES(vPeriod, vPeriod - 100, vPeriod - 200);
+ UNTIL i = vWeekCount END REPEAT;
+
+ SELECT cy, ly, zy INTO w1, y1, z1 FROM tTable LIMIT 1;
+ SELECT cy, ly, zy INTO w2, y2, z2 FROM tTable WHERE cy > w1 LIMIT 1;
+ SELECT cy, ly, zy INTO w3, y3, z3 FROM tTable WHERE cy > w2 LIMIT 1;
+ SELECT cy, ly, zy INTO w4, y4, z4 FROM tTable WHERE cy > w3 LIMIT 1;
+ SELECT cy, ly, zy INTO w5, y5, z5 FROM tTable WHERE cy > w4 LIMIT 1;
+ SELECT cy, ly, zy INTO w6, y6, z6 FROM tTable WHERE cy > w5 LIMIT 1;
+ SELECT cy, ly, zy INTO w7, y7, z7 FROM tTable WHERE cy > w6 LIMIT 1;
+
+ -- Genera una tabla con los datos del año pasado.
+
+ CREATE OR REPLACE TEMPORARY TABLE tLastYear
+ (KEY (lItemFk))
+ ENGINE = MEMORY
+ SELECT c.itemFk lItemFk,
+ SUM(IF(c.timePeriod = y1, c.quantity, 0)) lweek1,
+ SUM(IF(c.timePeriod = y2, c.quantity, 0)) lweek2,
+ SUM(IF(c.timePeriod = y3, c.quantity, 0)) lweek3,
+ SUM(IF(c.timePeriod = y4, c.quantity, 0)) lweek4,
+ SUM(IF(c.timePeriod = y5, c.quantity, 0)) lweek5,
+ SUM(IF(c.timePeriod = y6, c.quantity, 0)) lweek6,
+ SUM(IF(c.timePeriod = y7, c.quantity, 0)) lweek7,
+ SUM(IF(c.timePeriod = y1, c.price, 0)) lprice1,
+ SUM(IF(c.timePeriod = y2, c.price, 0)) lprice2,
+ SUM(IF(c.timePeriod = y3, c.price, 0)) lprice3,
+ SUM(IF(c.timePeriod = y4, c.price, 0)) lprice4,
+ SUM(IF(c.timePeriod = y5, c.price, 0)) lprice5,
+ SUM(IF(c.timePeriod = y6, c.price, 0)) lprice6,
+ SUM(IF(c.timePeriod = y7, c.price, 0)) lprice7
+ FROM tmp.itemInventory ai
+ JOIN comparative c ON c.itemFk = ai.id
+ JOIN warehouse w on w.id = c.warehouseFk
+ JOIN tTable wt ON c.timePeriod = wt.ly
+ WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk
+ AND w.isComparative
+ AND (vCountryFk IS NULL OR c.countryFk = vCountryFk)
+ GROUP BY ai.id;
+
+ -- Genera una tabla con los datos de hace DOS años.
+
+ CREATE OR REPLACE TEMPORARY TABLE tTwoYearsAgo
+ (KEY (tItemFk))
+ ENGINE = MEMORY
+ SELECT c.itemFk tItemFk,
+ SUM(IF(c.timePeriod = z1, c.quantity, 0)) vlweek1,
+ SUM(IF(c.timePeriod = z2, c.quantity, 0)) vlweek2,
+ SUM(IF(c.timePeriod = z3, c.quantity, 0)) vlweek3,
+ SUM(IF(c.timePeriod = z4, c.quantity, 0)) vlweek4,
+ SUM(IF(c.timePeriod = z5, c.quantity, 0)) vlweek5,
+ SUM(IF(c.timePeriod = z6, c.quantity, 0)) vlweek6,
+ SUM(IF(c.timePeriod = z7, c.quantity, 0)) vlweek7,
+ SUM(IF(c.timePeriod = z1, c.price, 0)) vlprice1,
+ SUM(IF(c.timePeriod = z2, c.price, 0)) vlprice2,
+ SUM(IF(c.timePeriod = z3, c.price, 0)) vlprice3,
+ SUM(IF(c.timePeriod = z4, c.price, 0)) vlprice4,
+ SUM(IF(c.timePeriod = z5, c.price, 0)) vlprice5,
+ SUM(IF(c.timePeriod = z6, c.price, 0)) vlprice6,
+ SUM(IF(c.timePeriod = z7, c.price, 0)) vlprice7
+ FROM tmp.itemInventory ai
+ JOIN comparative c ON c.itemFk = ai.id
+ JOIN warehouse w on w.id = c.warehouseFk
+ JOIN tTable wt ON c.timePeriod = wt.zy
+ WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk
+ AND w.isComparative
+ AND (vCountryFk IS NULL OR c.countryFk = vCountryFk)
+ GROUP BY ai.id;
+
+ -- Genera una tabla con los datos de este año.ss
+
+ CREATE OR REPLACE TEMPORARY TABLE tCurrentYear
+ (KEY (cItemFk))
+ ENGINE = MEMORY
+ SELECT t.itemFk cItemFk,
+ SUM(IF(week = w1, total, 0)) cweek1,
+ SUM(IF(week = w2, total, 0)) cweek2,
+ SUM(IF(week = w3, total, 0)) cweek3,
+ SUM(IF(week = w4, total, 0)) cweek4,
+ SUM(IF(week = w5, total, 0)) cweek5,
+ SUM(IF(week = w6, total, 0)) cweek6,
+ SUM(IF(week = w7, total, 0)) cweek7,
+ SUM(IF(week = w1, price, 0)) cprice1,
+ SUM(IF(week = w2, price, 0)) cprice2,
+ SUM(IF(week = w3, price, 0)) cprice3,
+ SUM(IF(week = w4, price, 0)) cprice4,
+ SUM(IF(week = w5, price, 0)) cprice5,
+ SUM(IF(week = w6, price, 0)) cprice6,
+ SUM(IF(week = w7, price, 0)) cprice7
+ FROM (
+ SELECT s.itemFk,
+ ti.period `week`,
+ SUM(s.quantity) total,
+ TRUNCATE(SUM(s.quantity * s.priceFixed),0) price
+ FROM ticket t
+ JOIN sale s ON t.id = s.ticketFk
+ JOIN tmp.itemInventory it ON it.id = s.itemFk
+ JOIN time ti ON ti.dated = DATE(t.shipped)
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType tp ON tp.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ STRAIGHT_JOIN address ad ON ad.id = t.addressFk
+ JOIN province p ON p.id = ad.provinceFk
+ JOIN `client` c ON c.id = ad.clientFk
+ WHERE t.shipped BETWEEN vDayRangeStart AND util.dayEnd(vDayRangeEnd)
+ AND c.typeFk IN ('Normal','handMaking')
+ AND w.id = COALESCE(vWarehouseFk, w.id)
+ AND w.isComparative
+ AND (vCountryFk IS NULL OR p.countryFk = vCountryFk)
+ GROUP BY i.id, week
+ ) t
+ GROUP BY t.itemFk;
+
+ -- Genera la tabla con la comparativa.
+ CREATE OR REPLACE TEMPORARY TABLE tmp.comparative
+ ENGINE = MEMORY
+ SELECT it.subName productor,
+ b.packing,
+ b.buyingValue costefijo,
+ b.groupingMode caja,
+ it.image ArticleImage,
+ IFNULL(it.inkFk,"?") color,
+ tp.code tipo,
+ it.typeFk tipo_id,
+ o.code origen,
+ it.category categoria,
+ it.stems tallos,
+ it.size medida,
+ it.name article,
+ w.code codigoTrabajador,
+ tp.categoryFk reino_id,
+ ly.*,
+ cy.*,
+ zy.*,
+ it.*,
+ it.id Id_Article,
+ i.buy_id,
+ tp.life,
+ IFNULL(i.sd,0) sd,
+ i.avalaible,
+ i.visible,
+ i.buy_date,
+ e.id provider_id,
+ it.comment comments,
+ it.description itemDescription,
+ IF(cy.cItemFk IS NULL AND i.visible = 0 AND i.avalaible = 0
+ AND IFNULL(i.sd, 0) = 0, FALSE, TRUE) filtret,
+ IF(it.hasMinPrice, FORMAT(it.minPrice, 2), "") pvp,
+ s.company_name
+ FROM tmp.itemInventory i
+ JOIN item it ON it.id = i.id
+ LEFT JOIN itemType tp ON tp.id = it.typeFk
+ LEFT JOIN worker w ON w.id = tp.workerFk
+ LEFT JOIN buy b ON b.id = i.buy_id
+ LEFT JOIN entry e ON e.id = b.entryFk
+ LEFT JOIN origin o ON o.id = it.originFk
+ LEFT JOIN tLastYear ly ON ly.lItemFk = it.id
+ LEFT JOIN tCurrentYear cy ON cy.cItemFk = it.id
+ LEFT JOIN tTwoYearsAgo zy ON zy.tItemFk = it.id
+ LEFT JOIN edi.ekt e2 ON e2.id = b.ektFk
+ LEFT JOIN edi.supplier s ON s.supplier_id = e2.pro
+ WHERE i.avalaible
+ OR i.visible
+ OR i.sd
+ OR cy.cweek1 OR cy.cweek2 OR cy.cweek3 OR cy.cweek4 OR cy.cweek5 OR cy.cweek6 OR cy.cweek7
+ OR ly.lweek1 OR ly.lweek2 OR ly.lweek3 OR ly.lweek4 OR ly.lweek5 OR ly.lweek6 OR ly.lweek7
+ OR zy.vlweek1 OR zy.vlweek2 OR zy.vlweek3 OR zy.vlweek4 OR zy.vlweek5 OR zy.vlweek6 OR zy.vlweek7;
+
+ -- Elimina las tablas temporales creadas...
+ DROP TEMPORARY TABLE IF EXISTS tmp.itemInventory,
+ tTwoYearsAgo,
+ tLastYear,
+ tCurrentYear,
+ tTable;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_deactivateUnused` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -62062,51 +61040,50 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getAtp`(vDated DATE)
-BEGIN
-/**
- * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y
- * almacén.
- *
- * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0
- * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity)
- * @return tmp.itemAtp(itemFk, warehouseFk, quantity)
- */
- DROP TEMPORARY TABLE IF EXISTS tItemOrdered;
- CREATE TEMPORARY TABLE tItemOrdered
- (UNIQUE(itemFk, warehouseFk, dated))
- ENGINE = MEMORY
- SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity
- FROM (
- SELECT itemFk, warehouseFk, dated, quantity
- FROM tmp.itemCalc
- UNION ALL
- SELECT itemFk, warehouseFk, vDated, 0
- FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2
- ) t1
- GROUP BY itemFk, warehouseFk, dated
- ORDER BY itemFk, warehouseFk, dated;
-
- SET @lastItemFk := 0;
- SET @lastWareHouseFk := 0;
- SET @lastQuantity := 0;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.itemAtp;
- CREATE TEMPORARY TABLE tmp.itemAtp
- SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity
- FROM (
- SELECT
- itemFk,
- IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk,
- @lastQuantity := quantity,
- @lastQuantity := @lastQuantity + quantity) quantityAccumulated,
- wareHouseFk,
- @lastItemFk := itemFk,
- @lastWareHouseFk := wareHouseFk
- FROM tItemOrdered
- )sub
- GROUP BY itemFk, wareHouseFk;
-
- DROP TEMPORARY TABLE tItemOrdered;
+BEGIN
+/**
+ * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y
+ * almacén.
+ *
+ * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0
+ * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity)
+ * @return tmp.itemAtp(itemFk, warehouseFk, quantity)
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tItemOrdered
+ (UNIQUE(itemFk, warehouseFk, dated))
+ ENGINE = MEMORY
+ SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity
+ FROM (
+ SELECT itemFk, warehouseFk, dated, quantity
+ FROM tmp.itemCalc
+ UNION ALL
+ SELECT itemFk, warehouseFk, vDated, 0
+ FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2
+ ) t1
+ GROUP BY itemFk, warehouseFk, dated
+ ORDER BY itemFk, warehouseFk, dated;
+
+ SET @lastItemFk := 0;
+ SET @lastWareHouseFk := 0;
+ SET @lastQuantity := 0;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp
+ (INDEX (itemFk, wareHouseFk))
+ SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity
+ FROM (
+ SELECT
+ itemFk,
+ IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk,
+ @lastQuantity := quantity,
+ @lastQuantity := @lastQuantity + quantity) quantityAccumulated,
+ wareHouseFk,
+ @lastItemFk := itemFk,
+ @lastWareHouseFk := wareHouseFk
+ FROM tItemOrdered
+ )sub
+ GROUP BY itemFk, wareHouseFk;
+
+ DROP TEMPORARY TABLE tItemOrdered;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -62132,13 +61109,13 @@ BEGIN
/**
* @vItemFk item a buscar
* @vWarehouseFk almacen donde buscar
- * @vDate Si la fecha es null, muestra el histórico desde el inventario.
+ * @vDate Si la fecha es null, muestra el histórico desde el inventario.
* Si la fecha no es null, muestra histórico desde la fecha pasada.
*/
DECLARE vDateInventory DATETIME;
IF vDate IS NULL THEN
- SELECT inventoried INTO vDateInventory
+ SELECT inventoried INTO vDateInventory
FROM config;
ELSE
SELECT mockUtcTime INTO vDateInventory
@@ -62164,7 +61141,7 @@ BEGIN
inventorySupplierFk INT(10)
);
- INSERT INTO tItemDiary
+ INSERT INTO tItemDiary
SELECT tr.landed shipped,
b.quantity `in`,
NULL `out`,
@@ -62185,14 +61162,14 @@ BEGIN
JOIN entry e ON e.id = b.entryFk
JOIN travel tr ON tr.id = e.travelFk
JOIN supplier s ON s.id = e.supplierFk
- JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE()
+ JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE()
OR (util.VN_CURDATE() AND tr.isReceived),
- 'DELIVERED',
+ 'DELIVERED',
'FREE')
JOIN entryConfig ec
WHERE tr.landed >= vDateInventory
AND vWarehouseFk = tr.warehouseInFk
- AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL)
+ AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL)
AND b.itemFk = vItemFk
AND e.isExcludedFromAvailable = FALSE
AND e.isRaid = FALSE
@@ -62218,14 +61195,14 @@ BEGIN
JOIN travel tr ON tr.id = e.travelFk
JOIN warehouse w ON w.id = tr.warehouseOutFk
JOIN supplier s ON s.id = e.supplierFk
- JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE()
+ JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE()
OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived),
- 'DELIVERED',
+ 'DELIVERED',
'FREE')
JOIN entryConfig ec
WHERE tr.shipped >= vDateInventory
AND vWarehouseFk = tr.warehouseOutFk
- AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL)
+ AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL)
AND b.itemFk = vItemFk
AND e.isExcludedFromAvailable = FALSE
AND w.isFeedStock = FALSE
@@ -62244,22 +61221,21 @@ BEGIN
TRUE,
s.id,
st.`order`,
- ct.`code`,
+ c.typeFk,
cb.claimFk,
NULL
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
- LEFT JOIN ticketState ts ON ts.ticket = t.id
+ LEFT JOIN ticketState ts ON ts.ticketFk = t.id
LEFT JOIN state st ON st.`code` = ts.`code`
JOIN client c ON c.id = t.clientFk
- JOIN clientType ct ON ct.id = c.clientTypeFk
JOIN state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(),
- 'DELIVERED',
+ 'DELIVERED',
IF (t.shipped > util.dayEnd(util.VN_CURDATE()),
'FREE',
IFNULL(ts.code, 'FREE')))
LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED'
- LEFT JOIN saleTracking stk ON stk.saleFk = s.id
+ LEFT JOIN saleTracking stk ON stk.saleFk = s.id
AND stk.stateFk = stPrep.id
LEFT JOIN claimBeginning cb ON s.id = cb.saleFk
WHERE t.shipped >= vDateInventory
@@ -62275,7 +61251,7 @@ BEGIN
`out` DESC;
IF vDate IS NULL THEN
-
+
SET @a := 0;
SET @currentLineFk := 0;
SET @shipped := '';
@@ -62290,9 +61266,9 @@ BEGIN
`in` invalue,
`out`,
@a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0) balance,
- @currentLineFk := IF (@shipped < util.VN_CURDATE()
+ @currentLineFk := IF (@shipped < util.VN_CURDATE()
OR (@shipped = util.VN_CURDATE() AND (isPicked OR a.`code` >= 'ON_PREPARATION')),
- lineFk,
+ lineFk,
@currentLineFk) lastPreparedLineFk,
isTicket,
lineFk,
@@ -62324,25 +61300,25 @@ BEGIN
0 clientType,
0 claimFk
UNION ALL
- SELECT shipped,
- alertlevel,
- stateName,
- origin,
- reference,
- clientFk,
- name, `in`,
- `out`,
- @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0),
- 0,
- isTicket,
- lineFk,
- isPicked,
- clientType,
+ SELECT shipped,
+ alertlevel,
+ stateName,
+ origin,
+ reference,
+ clientFk,
+ name, `in`,
+ `out`,
+ @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0),
+ 0,
+ isTicket,
+ lineFk,
+ isPicked,
+ clientType,
claimFk
FROM tItemDiary
WHERE shipped >= vDate;
END IF;
-
+
DROP TEMPORARY TABLE tItemDiary;
END ;;
DELIMITER ;
@@ -62449,7 +61425,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getLack`(IN vForce BOOLEAN, IN
BEGIN
/**
* Calcula una tabla con el máximo negativo visible para cada producto y almacen
- *
+ *
* @param vForce Fuerza el recalculo del stock
* @param vDays Numero de dias a considerar
**/
@@ -62457,42 +61433,48 @@ BEGIN
CALL `cache`.stock_refresh(vForce);
CALL item_getMinacum(NULL, util.VN_CURDATE(), vDays, NULL);
CALL item_getMinETD();
+ CALL item_zoneClosure();
- SELECT i.id itemFk,
+ SELECT i.id itemFk,
i.longName,
w.id warehouseFk,
- p.`name` producer,
+ p.`name` producer,
i.`size`,
i.category,
- w.name warehouse,
+ w.name warehouse,
SUM(IFNULL(sub.amount,0)) lack,
i.inkFk,
- IFNULL(im.timed, util.midnight()) timed
- FROM (SELECT item_id,
- warehouse_id,
+ IFNULL(im.timed, util.midnight()) timed,
+ IFNULL(izc.timed, util.midnight()) minTimed,
+ o.name originFk
+ FROM (SELECT item_id,
+ warehouse_id,
amount
FROM cache.stock
WHERE amount > 0
UNION ALL
- SELECT itemFk,
- warehouseFk,
+ SELECT itemFk,
+ warehouseFk,
amount
FROM tmp.itemMinacum
) sub
JOIN warehouse w ON w.id = sub.warehouse_id
JOIN item i ON i.id = sub.item_id
- LEFT JOIN producer p ON p.id = i.producerFk
- JOIN itemType it ON it.id = i.typeFk
+ LEFT JOIN producer p ON p.id = i.producerFk
+ JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id
+ LEFT JOIN tmp.itemZoneClosure izc ON izc.itemFk = i.id
+ JOIN origin o ON o.id = i.originFk
WHERE w.isForTicket
- AND ic.display <> 0
+ AND ic.display
AND it.code != 'GEN'
GROUP BY i.id, w.id
HAVING lack < 0;
DROP TEMPORARY TABLE tmp.itemMinacum;
DROP TEMPORARY TABLE tmp.itemMinETD;
+ DROP TEMPORARY TABLE tmp.itemZoneClosure;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -62603,12 +61585,12 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getMinETD`()
BEGIN
-
+
/* Devuelve una tabla temporal con la primera ETD, para todos los artículos con salida hoy.
- *
+ *
* @return tmp.itemMinETD(itemFk, timed)
*/
-
+
DECLARE vMidnight DATETIME DEFAULT util.midnight();
DROP TEMPORARY TABLE IF EXISTS tmp.itemMinETD;
@@ -62619,7 +61601,7 @@ BEGIN
SELECT s.itemFk, MIN(TIME(IFNULL(z.`hour`,vMidnight))) timed
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
- LEFT JOIN `zone` z ON z.id = t.zoneFk
+ LEFT JOIN `zone` z ON z.id = t.zoneFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND vMidnight
GROUP BY s.itemFk;
END ;;
@@ -62638,87 +61620,98 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getSimilar`(vItemFk INT, vWarehouseFk INT, vDate DATE, vIsShowedByType BOOL)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getSimilar`(
+ vSelf INT,
+ vWarehouseFk INT,
+ vDated DATE,
+ vShowType BOOL
+)
BEGIN
-
/**
- * Propone articulos similares para posible cambio,
- * ordenado con la cantidad de veces usado y segun sus caracteristicas
- *
- * @param vItemFk item id
- * @param vWarehouseFk warehouse id
- * @param vDate fecha para revisar disponible
- * @param vIsShowedByType para mostrar solo artículos de ese tipo
- */
+* Propone articulos disponibles ordenados, con la cantidad
+* de veces usado y segun sus caracteristicas.
+*
+* @param vSelf Id de artículo
+* @param vWarehouseFk Id de almacen
+* @param vDated Fecha
+* @param vShowType Mostrar tipos
+*/
+ DECLARE vCalcFk INT;
+ DECLARE vTypeFk INT;
+ DECLARE vPriority INT DEFAULT 1;
- DECLARE vCalcFk INT;
- DECLARE vTypeFk INT;
+ CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated);
- DECLARE vTag1 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
- DECLARE vTag5 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
- DECLARE vTag6 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
- DECLARE vTag7 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
- DECLARE vTag8 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
+ -- Añadido temporalmente para ver si ya no sucede el cuelgue de db
+ SET vShowType = TRUE;
- DECLARE vValue1 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
- DECLARE vValue5 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
- DECLARE vValue6 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
- DECLARE vValue7 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
- DECLARE vValue8 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci';
-
-
- SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value
- INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1
- FROM vn.item i
- LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1
- LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk
- WHERE i.id = vItemFk;
-
- CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDate);
-
- SELECT i.id itemFk,
- i.longName,
- i.subName,
- i.tag5,
- i.value5,
- (i.value5 <=> vValue5) match5,
- i.tag6,
- i.value6,
- (i.value6 <=> vValue6) match6,
- i.tag7,
- i.value7,
- (i.value7 <=> vValue7) match7,
- i.tag8,
- i.value8,
- (i.value8 <=> vValue8) match8,
- a.available,
- IFNULL(ip.counter,0) counter,
- IF(b.groupingMode = 1, b.grouping, b.packing) as minQuantity
- FROM vn.item i
- JOIN cache.available a ON a.item_id = i.id
- LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk
- LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1
- LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk
- LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk
+ WITH itemTags AS (
+ SELECT i.id,
+ typeFk,
+ tag5,
+ value5,
+ tag6,
+ value6,
+ tag7,
+ value7,
+ tag8,
+ value8,
+ t.name,
+ it.value
+ FROM vn.item i
+ LEFT JOIN vn.itemTag it ON it.itemFk = i.id
+ AND it.priority = vPriority
+ LEFT JOIN vn.tag t ON t.id = it.tagFk
+ WHERE i.id = vSelf
+ )
+ SELECT i.id itemFk,
+ i.longName,
+ i.subName,
+ i.tag5,
+ i.value5,
+ (i.value5 <=> its.value5) match5,
+ i.tag6,
+ i.value6,
+ (i.value6 <=> its.value6) match6,
+ i.tag7,
+ i.value7,
+ (i.value7 <=> its.value7) match7,
+ i.tag8,
+ i.value8,
+ (i.value8 <=> its.value8) match8,
+ a.available,
+ IFNULL(ip.counter, 0) `counter`,
+ IF(b.groupingMode = 1, b.grouping, b.packing) minQuantity,
+ iss.visible located
+ FROM vn.item i
+ JOIN cache.available a ON a.item_id = i.id
+ AND a.calc_id = vCalcFk
+ LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id
+ AND ip.itemFk = vSelf
+ LEFT JOIN vn.itemTag it ON it.itemFk = i.id
+ AND it.priority = vPriority
+ LEFT JOIN vn.tag t ON t.id = it.tagFk
+ LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
+ AND lb.warehouse_id = vWarehouseFk
LEFT JOIN vn.buy b ON b.id = lb.buy_id
- WHERE a.calc_id = vCalcFk
- AND available > 0
- AND IF(vIsShowedByType, i.typeFk = vTypeFk, TRUE)
- AND i.id != vItemFk
- ORDER BY counter DESC,
- (t1.name = vTag1) DESC,
- (it1.value = vValue1) DESC,
- (i.tag6 = vTag6) DESC,
- (i.value6 = vValue6) DESC,
- (i.tag5 = vTag5) DESC,
- (i.value5 = vValue5) DESC,
- (i.tag7 = vTag7) DESC,
- (i.value7 = vValue7) DESC,
- (i.tag8 = vTag8) DESC,
- (i.value8 = vValue8) DESC
- LIMIT 30;
-
-
+ LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id
+ AND iss.warehouseFk = vWarehouseFk
+ JOIN itemTags its
+ WHERE a.available > 0
+ AND IF(vShowType, i.typeFk = its.typeFk, TRUE)
+ AND i.id <> vSelf
+ ORDER BY `counter` DESC,
+ (t.name = its.name) DESC,
+ (it.value = its.value) DESC,
+ (i.tag5 = its.tag5) DESC,
+ match5 DESC,
+ (i.tag6 = its.tag6) DESC,
+ match6 DESC,
+ (i.tag7 = its.tag7) DESC,
+ match7 DESC,
+ (i.tag8 = its.tag8) DESC,
+ match8 DESC
+ LIMIT 100;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -62868,6 +61861,108 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `item_multipleBuy` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `item_multipleBuy`(
+ vDate DATETIME,
+ vWarehouseFk INT
+)
+BEGIN
+/**
+ * Updates the tmp.itemInventory table, adding the buy id.
+ *
+ * @param tmp.itemInventory(buy_id)
+ * @param vDate -> Date of the purchase operation.
+ * @param vWarehouseFk -> Identifier of the warehouse (warehouseId).
+ */
+ ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT;
+
+ CALL buyUltimate(vWarehouseFk, vDate);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp
+ (KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT *
+ FROM (
+ SELECT itemFk, buyFk
+ FROM tmp.buyUltimate
+ ORDER BY (vWarehouseFk = warehouseFk) DESC, landing DESC
+ LIMIT 10000000000000000000
+ ) t
+ GROUP BY itemFk;
+
+ UPDATE tmp.itemInventory ai
+ JOIN tmp t ON ai.id = t.itemFk
+ SET ai.buy_id = t.buyFk;
+
+ DROP TEMPORARY TABLE tmp, tmp.buyUltimate;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `item_multipleBuyByDate` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `item_multipleBuyByDate`(
+ vDated DATETIME,
+ vWarehouseFk TINYINT(3)
+)
+BEGIN
+/**
+ * Updates the tmp.itemInventory table, adding the purchase date.
+ *
+ * @param tmp.itemInventory(buy_date)
+ * @param vDated -> end date
+ * @param vWarehouseFk -> warehouse id
+ */
+ DECLARE vLastBuyScope INT;
+ SELECT comparativeLastBuyScope INTO vLastBuyScope
+ FROM config;
+
+ ALTER TABLE tmp.itemInventory
+ ADD `buy_date` datetime NOT NULL;
+
+ CREATE OR REPLACE TEMPORARY TABLE lastBuyScope
+ SELECT i.id, MAX(t.landed) lastLanded
+ FROM item i
+ JOIN buy b ON b.itemFk = i.id
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN (vDated + INTERVAL - vLastBuyScope DAY) AND vDated
+ AND NOT s.name = 'INVENTARIO'
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND w.isComparative
+ AND NOT e.isRaid
+ GROUP BY i.id;
+
+ UPDATE tmp.itemInventory y
+ JOIN lastBuyScope lbs ON lbs.id = y.id
+ SET y.buy_date = lbs.lastLanded;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_refreshFromTags` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -62915,7 +62010,7 @@ BEGIN
),
i.subname = JSON_VALUE(vValues, '$.4'),
i.size = JSON_VALUE(vOverwrites, '$.size'),
- i.stems = JSON_VALUE(vOverwrites, '$.stems'),
+ i.stems = IFNULL(JSON_VALUE(vOverwrites, '$.stems'),i.stems),
i.category = JSON_VALUE(vOverwrites, '$.category'),
i.tag5 = JSON_VALUE(vTags, '$.5'),
i.tag6 = JSON_VALUE(vTags, '$.6'),
@@ -63002,11 +62097,11 @@ BEGIN
* @param vBarcode del item
* @param vReference referencia a actualizar
*/
-
+
DECLARE vItemFk INT;
SELECT barcodeToItem(vBarcode) INTO vItemFk;
-
+
UPDATE item SET comment = vReference WHERE id = vItemFk;
END ;;
@@ -63029,7 +62124,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_setGeneric`(vSelf INT)
BEGIN
/**
* Asigna el código genérico a un item, salvo que sea un código de item genérico.
- *
+ *
* @param vSelf identificador de vn.item
*/
DECLARE vGenericFk INT;
@@ -63039,7 +62134,7 @@ BEGIN
SELECT itemFk, SUM(matches) = maxMatches `match`
FROM (
SELECT ga.id gaid, ga.itemFk,
- CASE
+ CASE
WHEN t.code = 'nflowers' THEN
it.value <=> ga.numFlores
WHEN t.code = 'origin' THEN
@@ -63070,13 +62165,13 @@ BEGIN
AND (i.`size` = ga.`size` OR ga.`size` IS NULL)
AND i.id != ga.itemFk
WHERE i.id = vSelf
- AND NOT i.isFloramondo) sub
+ AND NOT i.isFloramondo) sub
GROUP BY gaid
HAVING `match`) sub2
LIMIT 1;
- UPDATE vn.item
- SET genericFk = vGenericFk
+ UPDATE vn.item
+ SET genericFk = vGenericFk
WHERE id = vSelf;
END ;;
DELIMITER ;
@@ -63085,29 +62180,90 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `item_updatePackingShelve` */;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `item_setVisibleDiscard` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingShelve`(vSelf INT, vPacking INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `item_setVisibleDiscard`(
+ vItemFk INT,
+ vWarehouseFk INT,
+ vQuantity INT,
+ vAddressFk INT)
BEGIN
+/**
+ * Procedimiento para dar dar de baja/alta un item, si vAddressFk es NULL se entiende que se da de alta y se toma el addressFk de la configuración
+ *
+ * @param vItemFk Identificador del ítem
+ * @param vWarehouseFk id del warehouse
+ * @param vQuantity a dar de alta/baja
+ * @param vAddressFk id address
+ */
+ DECLARE vTicketFk INT;
+ DECLARE vClientFk INT;
+ DECLARE vDefaultCompanyFk INT;
+ DECLARE vCalc INT;
+ DECLARE vAddressShortage INT;
- /**
- * Actualiza el valor de item.packingShelve
- *
- * @param vSelf Identificador de vn.item
- * @param vPacking Cantidad de unidades de venta que caben en una bandeja
- */
+ SELECT barcodeToItem(vItemFk) INTO vItemFk;
- UPDATE vn.item i
- SET i.packingShelve = vPacking
- WHERE i.id = vSelf;
+ SELECT DEFAULT(companyFk) INTO vDefaultCompanyFk
+ FROM vn.ticket LIMIT 1;
+
+ IF vAddressFk IS NULL THEN
+ SELECT pc.shortageAddressFk INTO vAddressShortage
+ FROM productionConfig pc ;
+ ELSE
+ SET vAddressShortage = vAddressFk;
+ END IF;
+ SELECT a.clientFk INTO vClientFk
+ FROM address a
+ WHERE a.id = vAddressFk;
+
+ SELECT t.id INTO vTicketFk
+ FROM ticket t
+ JOIN address a ON a.id = t.addressFk
+ JOIN ticketState ts ON ts.ticketFk = t.id
+ WHERE t.warehouseFk = vWarehouseFk
+ AND a.id = vAddressShortage
+ AND DATE(t.shipped) = util.VN_CURDATE()
+ AND ts.code = 'DELIVERED'
+ LIMIT 1;
+
+ CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk);
+
+ IF vTicketFk IS NULL THEN
+ CALL ticket_add(
+ vClientFk,
+ util.VN_CURDATE(),
+ vWarehouseFk,
+ vDefaultCompanyFk,
+ vAddressFk,
+ NULL,
+ NULL,
+ util.VN_CURDATE(),
+ account.myUser_getId(),
+ FALSE,
+ vTicketFk);
+ END IF;
+
+ INSERT INTO sale(ticketFk, itemFk, concept, quantity)
+ SELECT vTicketFk,
+ vItemFk,
+ CONCAT(longName,' ', worker_getCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)),
+ vQuantity
+ FROM item
+ WHERE id = vItemFk;
+
+ UPDATE cache.visible
+ SET visible = visible - vQuantity
+ WHERE calc_id = vCalc
+ AND item_id = vItemFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63150,195 +62306,278 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `item_ValuateInventory`(IN vDated DATE, IN vIsDetailed BOOLEAN)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `item_ValuateInventory`(vDated DATE, vIsDetailed BOOLEAN)
BEGIN
+ DECLARE vInventoried DATE;
+ DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE;
+ DECLARE vInventoryClone DATE;
+ DECLARE vDateDayEnd DATETIME;
+ DECLARE vInventorySupplierFk INT;
- DECLARE vInventoried DATE;
- DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE;
- DECLARE vInventoried2 DATE;
- DECLARE vDateDayEnd DATETIME;
+ SELECT inventorySupplierFk INTO vInventorySupplierFk
+ FROM entryConfig;
- SET vDateDayEnd = util.dayEnd(vDated);
+ SET vDateDayEnd = util.dayEnd(vDated);
- SELECT landed INTO vInventoried
- FROM travel tr
- JOIN entry E ON E.travelFk = tr.id
- WHERE landed <= vDateDayEnd
- AND E.supplierFk = 4
- ORDER BY landed DESC
- LIMIT 1;
+ SELECT tr.landed INTO vInventoried
+ FROM travel tr
+ JOIN `entry` e ON e.travelFk = tr.id
+ JOIN entryConfig ec
+ WHERE landed <= vDateDayEnd
+ AND e.supplierFk = vInventorySupplierFk
+ ORDER BY tr.landed DESC
+ LIMIT 1;
- SET vHasNotInventory = IF (vInventoried is null, TRUE, FALSE);
+ SET vHasNotInventory = (vInventoried IS NULL);
+
+ IF vHasNotInventory THEN
+ SELECT landed INTO vInventoryClone
+ FROM travel tr
+ JOIN `entry` e ON e.travelFk = tr.id
+ JOIN entryConfig ec
+ WHERE landed >= vDated
+ AND e.supplierFk = vInventorySupplierFk
+ ORDER BY landed ASC
+ LIMIT 1;
- IF vHasNotInventory THEN
+ SET vInventoried = vDated + INTERVAL 1 DAY;
+ SET vDateDayEnd = vInventoryClone;
+ END IF;
- SELECT landed INTO vInventoried2
- FROM travel tr
- JOIN entry E ON E.travelFk = tr.id
- WHERE landed >= vDated
- AND E.supplierFk = 4
- ORDER BY landed ASC
- LIMIT 1;
+ CREATE OR REPLACE TEMPORARY TABLE tInventory(
+ warehouseFk SMALLINT,
+ itemFk BIGINT,
+ quantity INT,
+ cost DOUBLE DEFAULT 0,
+ total DOUBLE DEFAULT 0,
+ warehouseInventory VARCHAR(20),
+ PRIMARY KEY (warehouseInventory, itemFk) USING HASH
+ )
+ ENGINE = MEMORY;
+
+ -- Inventario inicial
+ IF vHasNotInventory THEN
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ SUM(b.quantity),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse w ON w.id = warehouseInFk
+ JOIN entryConfig ec
+ WHERE landed = vDateDayEnd
+ AND e.supplierFk = vInventorySupplierFk
+ AND w.valuatedInventory
+ AND t.isInventory
+ GROUP BY tr.warehouseInFk, b.itemFk;
+ ELSE
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ SUM(b.quantity),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse w ON w.id = warehouseInFk
+ JOIN entryConfig ec
+ WHERE landed = vInventoried
+ AND e.supplierFk = vInventorySupplierFk
+ AND w.valuatedInventory
+ AND t.isInventory
+ GROUP BY tr.warehouseInFk, b.itemFk;
+ END IF;
- SET vInventoried = TIMESTAMPADD(DAY,1,vDated);
- SET vDateDayEnd = vInventoried2;
+ -- Añadimos las entradas
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ b.quantity * IF(vHasNotInventory, -1, 1),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse w ON w.id = tr.warehouseInFk
+ JOIN entryConfig ec
+ WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
+ AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE)
+ AND NOT e.isRaid
+ AND w.valuatedInventory
+ AND t.isInventory
+ AND e.supplierFk <> vInventorySupplierFk
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory, -1, 1));
- END IF;
+ -- Descontamos las salidas
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseOutFk,
+ b.itemFk,
+ b.quantity * IF(vHasNotInventory, 1, -1),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse w ON w.id = tr.warehouseOutFk
+ WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd
+ AND NOT e.isRaid
+ AND w.valuatedInventory
+ AND t.isInventory
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory,1,-1));
- DROP TEMPORARY TABLE IF EXISTS inv;
+ -- Descontamos las lineas de venta
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT w.id,
+ s.itemFk,
+ s.quantity * IF(vHasNotInventory, 1, -1),
+ w.name
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN `client` c ON c.id = t.clientFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vInventoried AND vDateDayEnd
+ AND w.valuatedInventory
+ AND it.isInventory
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1);
- CREATE TEMPORARY TABLE inv
- (warehouseFk SMALLINT,
- Id_Article BIGINT,
- cantidad INT,
- coste DOUBLE DEFAULT 0,
- total DOUBLE DEFAULT 0,
- Almacen VARCHAR(20),
- PRIMARY KEY (Almacen, Id_Article) USING HASH)
- ENGINE = MEMORY;
+ -- Volver a poner lo que esta aun en las estanterias
+ IF vDated = util.VN_CURDATE() THEN
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT w.id,
+ s.itemFk,
+ s.quantity * IF(vHasNotInventory, 0, 1),
+ w.name
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN `client` c ON c.id = t.clientFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDated AND vDateDayEnd
+ AND NOT (s.isPicked OR t.isLabeled)
+ AND w.valuatedInventory
+ AND it.isInventory
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 0, 1);
+ END IF;
- IF vHasNotInventory = TRUE THEN
+ -- Mercancia en transito
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ b.quantity,
+ CONCAT(wOut.`name`, ' - ', wIn.`name`)
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
+ JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
+ WHERE vDated >= tr.shipped AND vDated < tr.landed
+ AND NOT isRaid
+ AND wIn.valuatedInventory
+ AND t.isInventory
+ AND e.isConfirmed
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity);
+
+ CALL vn.buyUltimate(NULL, vDateDayEnd);
- INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
- SELECT tr.warehouseInFk, b.itemFk, SUM(b.quantity), w.`name`
- FROM buy b
- JOIN item i ON i.id = b.itemFk
- JOIN entry e ON e.id = b.entryFk
- JOIN travel tr ON tr.id = e.travelFk
- JOIN itemType t ON t.id = i.typeFk
- JOIN warehouse w ON w.id = warehouseInFk
- WHERE landed = vDateDayEnd
- AND e.supplierFk = 4
- AND w.valuatedInventory
- AND t.isInventory
- GROUP BY tr.warehouseInFk, b.itemFk;
+ UPDATE tInventory i
+ JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.itemFk = bu.itemFk
+ JOIN buy b ON b.id = bu.buyFk
+ SET total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)),
+ cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)
+ WHERE i.quantity;
- END IF;
+ DELETE FROM tInventory
+ WHERE quantity IS NULL OR NOT quantity;
- INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
- SELECT tr.warehouseInFk, b.itemFk, b.quantity * IF(vHasNotInventory,-1,1), w.`name`
- FROM buy b
- JOIN item i ON i.id = b.itemFk
- JOIN entry e ON e.id = b.entryFk
- JOIN travel tr ON tr.id = e.travelFk
- JOIN itemType t ON t.id = i.typeFk
- JOIN warehouse w ON w.id = tr.warehouseInFk
- WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
- AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, trUE)
- AND NOT e.isRaid
- AND w.valuatedInventory
- AND t.isInventory
- ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity * IF(vHasNotInventory,-1,1));
-
- INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
- SELECT tr.warehouseOutFk, b.itemFk, b.quantity * IF(vHasNotInventory,1,-1), w.`name`
- FROM buy b
- JOIN item i ON i.id = b.itemFk
- JOIN entry e ON e.id = b.entryFk
- JOIN travel tr ON tr.id = e.travelFk
- JOIN itemType t ON t.id = i.typeFk
- JOIN warehouse w ON w.id = tr.warehouseOutFk
- WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd
- AND NOT e.isRaid
- AND w.valuatedInventory
- AND t.isInventory
- ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity * IF(vHasNotInventory,1,-1));
-
- INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
- SELECT w.id, s.itemFk, s.quantity * IF(vHasNotInventory,1,-1), w.`name`
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- JOIN `client` c ON c.id = t.clientFk
- JOIN item i ON i.id = s.itemFk
- JOIN itemType it ON it.id = i.typeFk
- JOIN warehouse w ON w.id = t.warehouseFk
- WHERE t.shipped BETWEEN vInventoried AND vDateDayEnd
- AND w.valuatedInventory
- AND it.isInventory
- ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + s.quantity * IF(vHasNotInventory,1,-1);
-
- IF vDated = util.VN_CURDATE() THEN -- volver a poner lo que esta aun en las estanterias
-
- INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
- SELECT w.id, s.itemFk, s.quantity * IF(vHasNotInventory,0,1), w.`name`
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- JOIN `client` c ON c.id = t.clientFk
- JOIN item i ON i.id = s.itemFk
- JOIN itemType it ON it.id = i.typeFk
- JOIN warehouse w ON w.id = t.warehouseFk
- WHERE t.shipped BETWEEN vDated AND vDateDayEnd
- AND (s.isPicked <> 0 or t.isLabeled <> 0 )
- AND w.valuatedInventory
- AND it.isInventory
- ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + s.quantity * IF(vHasNotInventory,0,1);
-
- END IF;
-
- -- Mercancia en transito
- INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
- SELECT tr.warehouseInFk, b.itemFk, b.quantity, CONCAT(wOut.`name`,' - ', wIn.`name`)
- FROM buy b
- JOIN item i ON i.id = b.itemFk
- JOIN entry e ON e.id = b.entryFk
- JOIN travel tr ON tr.id = e.travelFk
- JOIN itemType t ON t.id = i.typeFk
- JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
- JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
- WHERE vDated >= tr.shipped AND vDated < tr.landed
- AND NOT isRaid
- AND wIn.valuatedInventory
- AND t.isInventory
- AND e.isConfirmed
- ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity);
-
- CALL vn.buyUltimate(NULL,vDateDayEnd);
-
- UPDATE inv i
- JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.Id_Article = bu.itemFk
- JOIN buy b ON b.id = bu.buyFk
- SET total = i.cantidad * (ifnull(b.buyingValue,0) + IFNULL(b.packageValue,0) + IFNULL(b.freightValue,0) + IFNULL(b.comissionValue,0)),
- coste = ifnull(b.buyingValue,0) + IFNULL(b.packageValue,0) + IFNULL(b.freightValue,0) + IFNULL(b.comissionValue,0)
- WHERE i.cantidad <> 0;
-
- DELETE FROM inv WHERE Cantidad IS NULL or Cantidad = 0;
-
- IF vIsDetailed THEN
-
- SELECT inv.warehouseFk,
- i.id itemFk,
- i.longName ,
- i.size,
- inv.Cantidad,
- tp.name Tipo,
- ic.name Reino,
- inv.coste,
- cast(inv.total as decimal(10,2)) total,
- almacen
- FROM inv
- JOIN warehouse w on w.id = warehouseFk
- JOIN item i ON i.id = inv.Id_Article
- JOIN itemType tp ON tp.id = i.typeFk
- JOIN itemCategory ic ON ic.id = tp.categoryFk
- WHERE w.valuatedInventory
- and inv.total > 0
- order by inv.total desc;
-
- ELSE
-
- SELECT i.Almacen, ic.name as Reino, cast(i.total as decimal(10,2)) as Euros, w.code as Comprador,it.id
- FROM inv i
- JOIN warehouse wh on wh.id = warehouseFk
- JOIN item it ON it.id = i.Id_Article
- JOIN itemType itp ON itp.id = it.typeFk
- LEFT JOIN worker w ON w.id = itp.workerFk
- JOIN itemCategory ic ON ic.id = itp.categoryFk
+ IF vIsDetailed THEN
+ SELECT ti.warehouseFk,
+ i.id itemFk,
+ i.longName,
+ i.size,
+ ti.quantity,
+ tp.name Tipo,
+ ic.name Reino,
+ ti.cost,
+ CAST(ti.total AS DECIMAL(10, 2)) total,
+ ti.warehouseInventory almacen
+ FROM tInventory ti
+ JOIN warehouse w ON w.id = warehouseFk
+ JOIN item i ON i.id = ti.itemFk
+ JOIN itemType tp ON tp.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
+ WHERE w.valuatedInventory
+ AND ti.total > 0
+ ORDER BY ti.total DESC;
+ ELSE
+ SELECT i.warehouseInventory Almacen,
+ ic.name Reino,
+ CAST(i.total AS DECIMAL(10, 2)) Euros,
+ w.code Comprador,
+ it.id
+ FROM tInventory i
+ JOIN warehouse wh ON wh.id = warehouseFk
+ JOIN item it ON it.id = i.itemFk
+ JOIN itemType itp ON itp.id = it.typeFk
+ LEFT JOIN worker w ON w.id = itp.workerFk
+ JOIN itemCategory ic ON ic.id = itp.categoryFk
WHERE wh.valuatedInventory
- AND i.total > 0;
+ AND i.total > 0;
+ END IF;
- END IF;
- DROP TEMPORARY TABLE tmp.buyUltimate;
- DROP TEMPORARY TABLE inv;
+ DROP TEMPORARY TABLE
+ tmp.buyUltimate,
+ tInventory;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `item_zoneClosure` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `item_zoneClosure`()
+BEGIN
+
+/* Devuelve una tabla temporal con la hora minima de un ticket sino tiene el de la zoneClosure y
+ * si tampoco hay el de la zona , para todos los artículos con salida hoy.
+ *
+ * @return tmp.itemZoneClosure(itemFk, timed)
+ */
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemZoneClosure
+ (INDEX (itemFk))
+ ENGINE = MEMORY
+ SELECT s.itemFk,
+ MIN(DATE_FORMAT(IF(HOUR(t.shipped),t.shipped,
+ IFNULL(zc.hour, z.HOUR)), '%H:%i')
+ )timed
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ LEFT JOIN `zone` z ON z.id = t.zoneFk
+ LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND CONCAT(util.VN_CURDATE(), ' 23:59:59')
+ GROUP BY s.itemFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63366,37 +62605,37 @@ BEGIN
* @param vConcept descripcion
* @param vAmount cantidad que se compensa
* @param vCompany empresa
- * @param vOriginalAccount cuenta contable desde la cual se compensa
- *
- */
+ * @param vOriginalAccount cuenta contable desde la cual se compensa
+ *
+ */
DECLARE vNewBookEntry INT;
DECLARE vIsClientCompensation INT;
DECLARE vClientFk INT;
DECLARE vSupplierFk INT;
DECLARE vIsOriginalAClient BOOL;
DECLARE vPayMethodCompensation INT;
-
+
CALL ledger_next(vNewBookEntry);
SELECT COUNT(id) INTO vIsOriginalAClient FROM client WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci;
- SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation
- FROM client
+ SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation
+ FROM client
WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci;
-
+
SET @vAmount1:= 0.0;
SET @vAmount2:= 0.0;
- INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id)
- VALUES ( vNewBookEntry,
- vDated,
- vOriginalAccount,
- vCompensationAccount,
- vConcept,
+ INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id)
+ VALUES ( vNewBookEntry,
+ vDated,
+ vOriginalAccount,
+ vCompensationAccount,
+ vConcept,
@vAmount1:= IF(
- (vIsOriginalAClient AND vAmount > 0) OR
- (NOT vIsOriginalAClient AND vAmount < 0),
- 0,
+ (vIsOriginalAClient AND vAmount > 0) OR
+ (NOT vIsOriginalAClient AND vAmount < 0),
+ 0,
ABS(vAmount)
),
@vAmount2:= IF(@vAmount1,
@@ -63405,20 +62644,20 @@ BEGIN
),
vCompanyFk
),
- ( vNewBookEntry,
- vDated,
- vCompensationAccount,
- vOriginalAccount,
- vConcept,
+ ( vNewBookEntry,
+ vDated,
+ vCompensationAccount,
+ vOriginalAccount,
+ vConcept,
@vAmount2,
@vAmount1,
vCompanyFk);
-
+
IF vIsClientCompensation THEN
IF vIsOriginalAClient THEN
SET vAmount = -vAmount;
END IF;
- INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate)
+ INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate)
VALUES (vConcept, vAmount, vDated, vBankFk, vCompanyFk, vClientFk, TRUE);
ELSE
IF NOT vIsOriginalAClient THEN
@@ -63426,7 +62665,7 @@ BEGIN
END IF;
SELECT id INTO vSupplierFk FROM supplier WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci;
SELECT id INTO vPayMethodCompensation FROM payMethod WHERE `code` = 'compensation';
-
+
INSERT INTO payment (received, dueDated, supplierFk, amount, bankFk, payMethodFk, concept, companyFk, isConciliated)
VALUES(vDated, vDated, vSupplierFk, vAmount, vBankFk, vPayMethodCompensation, vConcept, vCompanyFk, TRUE);
END IF;
@@ -63448,10 +62687,10 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_next`(OUT vNewBookEntry INT)
BEGIN
-
+
UPDATE vn.ledgerConfig SET lastBookEntry = LAST_INSERT_ID(lastBookEntry + 1);
SET vNewBookEntry = LAST_INSERT_ID();
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63477,15 +62716,15 @@ BEGIN
* @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 ;;
@@ -63510,9 +62749,9 @@ BEGIN
SET @buildingOrder := 0;
SET @route := 0;
set @cajas := 0;
-
+
UPDATE tmp.sorter
- SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1
+ SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1
where date(created) = vDate
order by routeFk, created, weight DESC;
@@ -63530,23 +62769,23 @@ set @cajas := 0;
UPDATE tmp.sorter
SET lungGrow = IF(palletOrder = 0, -13, lungGrow);
-
+
DELETE FROM tmp.lungSize WHERE dia = vDate;
-
+
INSERT INTO tmp.lungSize(dia, hora,size)
select vDate,hora, @cajas := @cajas + cajas as size
from
(
select IF(lungGrow BETWEEN -12 AND -1, ETD,time_format(created,"%H:%i")) as hora, sum(if(lungGrow <= 0, lungGrow, 1)) as cajas, @cajas := 0
- from tmp.sorter
+ from tmp.sorter
where date(created) = vDate
group by hora
) sub;
-
+
SELECT * FROM tmp.lungSize
WHERE dia = vDate;
-
-
+
+
END ;;
@@ -63567,23 +62806,23 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_add`(vPlate VARCHAR(10), vWorkerFk INT)
BEGIN
-
+
/**
* Inserta registro si el vWorkerFk no ha registrado nada en las últimas 12 horas
* @param vPlate número de matrícula
- * @param vWorkerFk id del worker
- *
-*/
- UPDATE vn.machineWorker mw
- JOIN vn.machine m ON m.id = mw.machineFk
+ * @param vWorkerFk id del worker
+ *
+*/
+ UPDATE vn.machineWorker mw
+ JOIN vn.machine m ON m.id = mw.machineFk
SET mw.outTimed = util.VN_NOW()
WHERE (mw.workerFk = vWorkerFk OR m.plate = vPlate)
AND ISNULL(mw.outTimed);
-
+
INSERT INTO machineWorker (machineFk, workerFk)
SELECT m.id, vWorkerFk
FROM machine m
- WHERE m.plate= vPlate;
+ WHERE m.plate= vPlate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63603,21 +62842,21 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_getHistorical`(vPlate VARCHAR(20), vWorkerFk INT)
BEGIN
/**
- * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea,
+ * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea,
* si es jefe de producción muestra el historial completo.
- *
+ *
* @param vPlate número de matrícula
- * @param vWorkerFk id del trabajador
- *
+ * @param vWorkerFk id del trabajador
+ *
*/
DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vWorkerFk);
- SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed
+ SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed
FROM machineWorker mw
JOIN machine m ON m.plate = vPlate
WHERE mw.machineFk = m.id
AND mw.workerFk = IF(account.user_hasRole(vWorkerName, 'coolerAssist'), mw.workerFk, vWorkerFk)
- ORDER BY mw.inTimed DESC;
+ ORDER BY mw.inTimed DESC;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63636,13 +62875,13 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT)
BEGIN
-
+
/**
- * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate,
- *
+ * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate,
+ *
* @param vPlate número de matrícula
- * @param vWorkerFk id del trabajador
- *
+ * @param vWorkerFk id del trabajador
+ *
*/
DECLARE vMachineFk INT(10);
@@ -63651,24 +62890,24 @@ BEGIN
SELECT m.id INTO vMachineFk
FROM machine m
WHERE m.plate = vPlate;
-
+
SELECT maxHours INTO vMaxHours
FROM machineWorkerConfig;
- IF (SELECT COUNT(*)
+ IF (SELECT COUNT(*)
FROM machineWorker m
WHERE m.workerFk = vWorkerFk
- AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN
-
+ AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN
+
UPDATE machineWorker m
SET m.outTimed = CURRENT_TIMESTAMP()
- WHERE m.workerFk = vWorkerFk
- AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW())
+ WHERE m.workerFk = vWorkerFk
+ AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW())
AND ISNULL(m.outTimed)
AND m.machineFk = vMachineFk;
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63723,12 +62962,12 @@ BEGIN
/**
* Inserta en la tabla vn.mail
*
- * @param vReceiver Receptor del correo
+ * @param vReceiver Receptor del correo
* @param vReplyTo A quién contestar el correo
* @param vSubject Título del correo
* @param vBody Cuerpo del correo
*/
-
+
DECLARE vIsRepeated BOOLEAN;
SELECT COUNT(*) INTO vIsRepeated
@@ -63769,12 +63008,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `makeNewItem`()
BEGIN
DECLARE newItemFk INT;
-
+
SELECT getNewItemId() INTO newItemFk;
-
+
INSERT INTO item(id,name,typeFk,originFk)
SELECT newItemFk, 'Nuevo artículo', 78,39;
-
+
SELECT newItemFk;
@@ -63802,34 +63041,34 @@ BEGIN
DECLARE vMinute INT DEFAULT 0;
DECLARE vBoxes INT;
-
+
DROP TEMPORARY TABLE IF EXISTS vn.pcsDay;
CREATE TEMPORARY TABLE vn.pcsDay
SELECT 0 as hh, 0 as mm, 0 as boxes;
-
+
-- Creamos una tabla soporte para acumular las cajas a lo largo del dia
WHILE vHour < 24 DO
-
+
WHILE vMinute < 59 DO
-
+
SET vMinute = vMinute + 1;
-
+
INSERT INTO vn.pcsDay(hh,mm) VALUES(vHour, vMinute);
-
+
END WHILE;
-
+
SET vMinute = -1;
SET vHour = vHour + 1;
-
+
END WHILE;
-
+
-- Acumulamos
UPDATE vn.pcsDay pd
LEFT JOIN (SELECT * FROM vn.pcs_graf WHERE dia = vDated) pg USING(hh,mm)
SET pd.boxes = pd.boxes + pg.box;
-
+
SELECT * FROM vn.pcsDay;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63847,74 +63086,245 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellersRequery`(vWorkerFk INTEGER)
+`whole_proc`:
BEGIN
/**
- * Recalcula el mana consumido por un trabajador
+ * Guarda en workerMana el mana consumido por un trabajador
*
* @param vWorkerFk Id Trabajador
*/
DECLARE vWorkerIsExcluded BOOLEAN;
- DECLARE vFromDated DATE;
- DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,util.VN_CURDATE());
- DECLARE vMana INT;
- DECLARE vAutoMana INT;
- DECLARE vClaimMana INT;
- DECLARE vManaBank INT;
- DECLARE vManaGreugeType INT;
SELECT COUNT(*) INTO vWorkerIsExcluded
FROM workerManaExcluded
WHERE workerFk = vWorkerFk;
- IF NOT vWorkerIsExcluded THEN
- SELECT id INTO vMana
- FROM `component` WHERE code = 'mana';
-
- SELECT id INTO vAutoMana
- FROM `component` WHERE code = 'autoMana';
-
- SELECT id INTO vClaimMana
- FROM `component` WHERE code = 'manaClaim';
-
- SELECT id INTO vManaBank
- FROM `bank` WHERE code = 'mana';
-
- SELECT id INTO vManaGreugeType
- FROM `greugeType` WHERE code = 'mana';
-
- SELECT max(dated) INTO vFromDated
- FROM clientManaCache;
-
- REPLACE workerMana (workerFk, amount)
- SELECT vWorkerFk, sum(mana) FROM
- (
- SELECT s.quantity * sc.value as mana
- FROM ticket t
- JOIN address a ON a.id = t.addressFk
- JOIN client c ON c.id = a.clientFk
- JOIN sale s ON s.ticketFk = t.id
- JOIN saleComponent sc ON sc.saleFk = s.id
- WHERE c.salesPersonFk = vWorkerFk AND sc.componentFk IN (vMana, vAutoMana, vClaimMana)
- AND t.shipped > vFromDated AND t.shipped < vToDated
- UNION ALL
- SELECT - r.amountPaid
- FROM receipt r
- JOIN client c ON c.id = r.clientFk
- WHERE c.salesPersonFk = vWorkerFk AND bankFk = vManaBank
- AND payed > vFromDated
- UNION ALL
- SELECT g.amount
- FROM greuge g
- JOIN client c ON c.id = g.clientFk
- WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType
- AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE()
- UNION ALL
- SELECT cc.mana
- FROM clientManaCache cc
- JOIN client c ON c.id = cc.clientFk
- WHERE c.salesPersonFk = vWorkerFk AND cc.dated = vFromDated
- ) sub;
+ IF vWorkerIsExcluded THEN
+ LEAVE whole_proc;
END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.client
+ SELECT id
+ FROM client
+ WHERE salesPersonFk = vWorkerFk;
+
+ CALL client_getMana();
+
+ INSERT INTO workerMana (workerFk, amount)
+ SELECT vWorkerFk, sum(mana)
+ FROM tmp.clientMana
+ ON DUPLICATE KEY UPDATE amount = VALUES(amount);
+
+ DROP TEMPORARY TABLE
+ tmp.client,
+ tmp.clientMana;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `multipleInventory` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`(
+ vDate DATE,
+ vWarehouseFk TINYINT,
+ vMaxDays TINYINT
+)
+proc: BEGIN
+ DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY;
+ DECLARE vDateFrom DATE DEFAULT vDate;
+ DECLARE vDateTo DATETIME;
+ DECLARE vDateToTomorrow DATETIME;
+ DECLARE vDefaultDayRange INT;
+
+ IF vDate < util.VN_CURDATE() THEN
+ LEAVE proc;
+ END IF;
+
+ IF vDate = util.VN_CURDATE() THEN
+ SELECT inventoried INTO vDateFrom
+ FROM config;
+ END IF;
+
+ SELECT defaultDayRange INTO vDefaultDayRange
+ FROM comparativeConfig;
+
+ SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY;
+ SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY;
+
+ ALTER TABLE tmp.itemInventory
+ ADD `avalaible` INT NOT NULL,
+ ADD `sd` INT NOT NULL,
+ ADD `rest` INT NOT NULL,
+ ADD `expected` INT NOT NULL,
+ ADD `inventory` INT NOT NULL,
+ ADD `visible` INT NOT NULL,
+ ADD `life` TINYINT NOT NULL DEFAULT '0';
+
+ -- Calculo del inventario
+ UPDATE tmp.itemInventory ai
+ JOIN (
+ SELECT itemFk Id_Article, SUM(quantity) Subtotal
+ FROM (
+ SELECT s.itemFk, - s.quantity quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ UNION ALL
+ SELECT b.itemFk, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ ) sub2
+ GROUP BY itemFk
+ ) sub ON ai.id = sub.Id_Article
+ SET ai.inventory = sub.Subtotal,
+ ai.visible = sub.Subtotal,
+ ai.avalaible = sub.Subtotal,
+ ai.sd = sub.Subtotal;
+
+ -- Cálculo del visible
+ UPDATE tmp.itemInventory ai
+ JOIN (
+ SELECT itemFk Id_Article, SUM(quantity) Subtotal
+ FROM (
+ SELECT s.itemFk, s.quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped >= vDate
+ AND t.shipped < vDateTomorrow
+ AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL)
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed = vDate
+ AND NOT t.isReceived
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped = vDate
+ AND NOT t.isReceived
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ ) sub2
+ GROUP BY itemFk
+ ) sub ON ai.id = sub.Id_Article
+ SET ai.visible = ai.visible + sub.Subtotal;
+
+ -- Calculo del disponible
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
+ (INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT sub.itemFk,
+ vWarehouseFk warehouseFk,
+ sub.dated,
+ SUM(sub.quantity) quantity
+ FROM (
+ SELECT s.itemFk,
+ DATE(t.shipped) dated,
+ - s.quantity quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, t.landed, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ UNION ALL
+ SELECT b.itemFk, t.shipped, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ ) sub
+ GROUP BY sub.itemFk, sub.dated;
+
+ CALL item_getAtp(vDate);
+ CALL travel_upcomingArrivals(vWarehouseFk, vDate);
+
+ UPDATE tmp.itemInventory ai
+ JOIN (
+ SELECT it.itemFk,
+ SUM(it.quantity) quantity,
+ im.quantity minQuantity
+ FROM tmp.itemCalc it
+ JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
+ JOIN item i ON i.id = it.itemFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
+ WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
+ t.landing,
+ vDateToTomorrow)
+ GROUP BY it.itemFk
+ ) sub ON sub.itemFk = ai.id
+ SET ai.avalaible = IF(sub.minQuantity > 0,
+ ai.avalaible,
+ ai.avalaible + sub.minQuantity),
+ ai.sd = ai.inventory + sub.quantity;
+
+ DROP TEMPORARY TABLE
+ tmp.itemTravel,
+ tmp.itemCalc,
+ tmp.itemAtp;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63935,20 +63345,20 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlConnectionsSorter_kill`()
BEGIN
/**
- * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre
- */
-
+ * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre
+ */
+
DECLARE vDone INT DEFAULT 0;
DECLARE vProcesId INT;
DECLARE vCursor CURSOR FOR
- SELECT p.id
+ SELECT p.id
FROM information_schema.processlist p
- WHERE USER = 'sorter'
+ WHERE USER = 'sorter'
AND TIME >= 30;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
OPEN vCursor;
l: LOOP
@@ -63985,7 +63395,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlPreparedCount_check`()
BEGIN
DECLARE vPreparedCount INTEGER;
- SELECT VARIABLE_VALUE INTO vPreparedCount
+ SELECT VARIABLE_VALUE INTO vPreparedCount
FROM INFORMATION_SCHEMA.GLOBAL_STATUS
WHERE VARIABLE_NAME LIKE '%prepared_stmt_count%';
@@ -63993,7 +63403,7 @@ BEGIN
CALL `vn`.`mail_insert`('cau@verdnatura.es',
NULL,
'Problemas BBDD prepared_stmt_count',
- CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ',
+ CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ',
vPreparedCount,
', está próximo a exceder su límite. \r\n Hay que reiniciar el servicio LF.VMP.Service del servidor a3.')
);
@@ -64020,37 +63430,37 @@ BEGIN
DECLARE newShelving VARCHAR(3);
DECLARE vCode VARCHAR(3);
-
+
SELECT MAX(code) INTO vCode
FROM vn.shelving
WHERE isPrinted = FALSE;
-
+
SET @a1 := ASCII(MID(vCode,1,1));
SET @a2 := ASCII(MID(vCode,2,1));
SET @a3 := ASCII(MID(vCode,3,1)) + 1;
-
+
IF @a3 > 90 THEN
-
+
SET @a3 = 65;
SET @a2 = @a2 + 1;
-
+
IF @a2 > 90 THEN
-
+
SET @a2 = 65;
SET @a1 = @a1 + 1;
-
+
IF @a1 > 90 THEN
-
+
SET @a1 = 65;
-
+
END IF;
-
+
END IF;
-
+
END IF;
SET newShelving = CHAR(@a1,@a2,@a3 USING utf8);
-
+
INSERT INTO vn.shelving(code) VALUES(newShelving);
END ;;
@@ -64079,18 +63489,18 @@ BEGIN
* @param descripcion Texto de la observacion
*/
DECLARE vTableName VARCHAR(45);
-
+
SET vTableName = CONCAT(vTableCode,'Observation');
-
+
IF ISNULL(vTableName) THEN
CALL util.throw('CODE_NOT_FOUND');
END IF;
-
+
SET @qryLog := CONCAT(
'INSERT INTO ', vTableName, ' (originFk, userFk, description)',
' VALUES (', vOriginFk, ', ', account.myUser_getId(), ', "', vDescription, '")'
);
-
+
PREPARE stmt FROM @qryLog;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -64120,15 +63530,15 @@ BEGIN
DECLARE vDeliveryMethod INT;
DECLARE vClient INT;
-
+
SELECT deliveryMethodFk INTO vDeliveryMethod
- FROM vn.agencyMode
+ FROM vn.agencyMode
WHERE id = vAgencyMode;
-
+
SELECT clientFk INTO vClient
FROM vn.address
WHERE id = vAddress;
-
+
INSERT INTO hedera.order(date_send,customer_id,delivery_method_id,agency_id,address_id,source_app)
VALUES( vLanded,vClient ,vDeliveryMethod,vAgencyMode ,vAddress ,vSourceApp);
@@ -64154,7 +63564,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `orderDelete`(IN vId INT)
BEGIN
DELETE FROM hedera.`order` where id = vId;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64181,7 +63591,7 @@ BEGIN
DECLARE vOrderId INT;
CALL vn.orderCreate(vLanded,vAgencyMode,vAddress,vSourceApp,vOrderId);
SELECT vOrderId;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64201,7 +63611,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `orderListVolume`(IN vOrderId INT)
BEGIN
- SELECT
+ SELECT
o.id,
o.itemFk,
i.description,
@@ -64227,7 +63637,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`(
+CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`(
IN vClient INT,
IN vDate DATE,
IN vCompany INT,
@@ -64246,20 +63656,20 @@ BEGIN
SET vGraceDays = IF(vIsAllInvoiceable ,0, 30);
SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate);
-
- /* Clientes especiales:
+
+ /* Clientes especiales:
3240 MADEFLOR
992 JAVIER FELIU
4 TONI VENDRELL
*/
-
+
IF vClient IN (992, 3240, 4) THEN
-
+
SET vGraceDays = 365;
-
+
END IF;
/* Fin clientes especiales */
-
+
SET vDateEnd = DATE_ADD(vDate, INTERVAL 1 DAY);
DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice;
@@ -64283,22 +63693,22 @@ BEGIN
FROM tmp.packageToInvoice
GROUP BY itemFk
HAVING totalQuantity > 0;
-
+
SELECT COUNT(*)
INTO vIsInvoiceable
FROM tmp.packageToInvoicePositives;
IF vIsInvoiceable THEN
- CALL ticket_add(vClient,
+ CALL ticket_add(vClient,
vDateEnd,
- vWarehouse,
- vCompany,
- NULL,
- NULL,
- NULL,
- vDateEnd,
- account.myUser_getId(),
+ vWarehouse,
+ vCompany,
+ NULL,
+ NULL,
+ NULL,
+ vDateEnd,
+ account.myUser_getId(),
TRUE,
vNewTicket);
@@ -64307,44 +63717,44 @@ BEGIN
packagingFk,
quantity,
pvp)
- SELECT vNewTicket,
- pti.packagingFk,
- - SUM(pti.quantity) AS totalQuantity,
+ SELECT vNewTicket,
+ pti.packagingFk,
+ - SUM(pti.quantity) AS totalQuantity,
pti.price
FROM tmp.packageToInvoice pti
- LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk
- WHERE ptip.itemFK IS NOT NULL
+ LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk
+ WHERE ptip.itemFK IS NOT NULL
OR vIsAllInvoiceable
GROUP BY packagingFk
HAVING totalQuantity;
INSERT INTO sale(
ticketFk,
- itemFk,
- concept,
- quantity,
+ itemFk,
+ concept,
+ quantity,
price
)
- SELECT vNewTicket,
- pti.itemFk,
- i.name as concept,
- sum(pti.quantity) as totalQuantity,
+ SELECT vNewTicket,
+ pti.itemFk,
+ i.name as concept,
+ sum(pti.quantity) as totalQuantity,
pti.price
FROM tmp.packageToInvoice pti
JOIN item i ON i.id = pti.itemFk
LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk
- WHERE ptip.itemFK IS NOT NULL
+ WHERE ptip.itemFK IS NOT NULL
OR vIsAllInvoiceable
GROUP BY pti.itemFk
HAVING totalQuantity;
-
+
INSERT INTO saleComponent(saleFk, componentFk, value)
SELECT id, vComponentCost, price
FROM sale
WHERE ticketFk = vNewTicket;
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64370,7 +63780,7 @@ BEGIN
WHERE mm.valor = 1 -- Listo para imprimir
AND mm.stateFk = 9 -- Encajando
AND m.Id_Ticket = ticketFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64392,15 +63802,15 @@ BEGIN
DECLARE valueFk INT;
DECLARE encajando INT DEFAULT 9;
-
- SELECT valor INTO valueFk
- FROM vn2008.Movimientos_mark
- WHERE Id_Movimiento = saleFk
+
+ SELECT valor INTO valueFk
+ FROM vn2008.Movimientos_mark
+ WHERE Id_Movimiento = saleFk
AND stateFk = encajando;
-
+
SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3;
-
- REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk)
+
+ REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk)
VALUES(saleFk,valueFk,account.myUser_getId(),encajando);
@@ -64492,34 +63902,34 @@ BEGIN
DECLARE vLetters VARCHAR(26) DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
DECLARE vMaxId INT;
DECLARE vCode VARCHAR(8);
-
+
SET vColumn = vFromColumn;
SET vRow = vFromRow;
SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0')));
-
+
SELECT MAX(id) INTO vMaxId
FROM vn.parking;
WHILE vColumn <= vToColumn DO
-
+
WHILE vRow <= vToRow DO
-
+
INSERT IGNORE INTO vn.parking(`column`, `row`, sectorFk, `code`, pickingOrder)
VALUES (vColumn, vRow, vSectorFk, vCode, vColumn * 100 + vRow )
ON DUPLICATE KEY UPDATE `code` = vCode;
-
+
SET vRow = vRow + 1;
SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0')));
-
+
END WHILE;
-
+
SET vRow = vFromRow;
SET vColumn = vColumn + 1;
-
+
SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0')));
-
+
END WHILE;
-
+
SELECT * FROM vn.parking WHERE `column` BETWEEN vFromColumn AND vToColumn;
END ;;
@@ -64544,59 +63954,59 @@ BEGIN
DECLARE vRow INT;
DECLARE vCode VARCHAR(8);
DECLARE i INT;
-
+
IF vToRow < vFromRow THEN
-
+
SET vRow = vFromRow;
-
+
WHILE vRow >= vToRow DO
-
+
SET i = 1;
-
+
WHILE i <= vTrolleysByLine DO
-
+
SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i);
-
+
INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder)
VALUES (vSectorFk, vCode, vPickingOrder + (i * 10))
ON DUPLICATE KEY UPDATE `code` = vCode;
-
+
SET i = i + 1;
-
+
END WHILE;
-
+
SET vRow = vRow - 1;
-
+
END WHILE;
ELSE
-
+
SET vRow = vFromRow;
-
+
WHILE vRow <= vToRow DO
-
+
SET i = 1;
-
+
WHILE i <= vTrolleysByLine DO
-
+
SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i);
-
+
INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder)
VALUES (vSectorFk, vCode, vPickingOrder + (i * 10) )
ON DUPLICATE KEY UPDATE `code` = vCode;
-
+
SET i = i + 1;
-
+
END WHILE;
-
+
SET vRow = vRow + 1;
-
+
END WHILE;
-
-
+
+
END IF;
-
-
+
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64620,28 +64030,28 @@ BEGIN
DECLARE vColumn INT;
DECLARE vLetters VARCHAR(200);
DECLARE vLettersLength INT;
-
+
SET vColumn = vStart;
SET vRow = 1;
SET vLetters = 'ABCDEF';
SET vLettersLength = LENGTH(vLetters);
-
+
WHILE vColumn <= vEnd DO
-
+
REPLACE vn.parking(`column`, `row`, `code`, sectorFk)
VALUES(vColumn, vRow, CONCAT(vColumn,MID(vLetters,vRow,1)), vSectorFk);
-
+
SET vRow = vRow + 1;
-
+
IF vRow > vLettersLength THEN
-
+
SET vRow = 1;
SET vColumn = vColumn + 1;
-
+
END IF;
-
+
END WHILE;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64660,11 +64070,11 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `parking_setOrder`(vWarehouseFk INT)
BEGIN
-
+
/*
* Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor
*/
-
+
UPDATE vn.parking p
JOIN (
SELECT code,
@@ -64673,15 +64083,112 @@ BEGIN
SELECT c.prepOrder,
p.code,
@orden := 0,
- IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor ,
- CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication
+ IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor ,
+ CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication
FROM vn.parking p
- JOIN vn.sector s ON s.id = p.sectorFk
+ JOIN vn.sector s ON s.id = p.sectorFk
JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci
- WHERE s.warehouseFk = vWarehouseFk) sub
- ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code
+ WHERE s.warehouseFk = vWarehouseFk) sub
+ ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code
SET p.pickingOrder = sub2.po;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `payment_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `payment_add`(
+ vDated DATE,
+ vSupplierFk INT,
+ vAmount DOUBLE,
+ vCurrencyFk INT,
+ vForeignValue DOUBLE,
+ vBankFk INT,
+ vPayMethodFk INT,
+ vExpenseFk DOUBLE,
+ vConcept VARCHAR(40),
+ vCompanyFk INT)
+BEGIN
+/**
+ * Registra un pago realizado a un proveedor y
+ * su correspondiente registro en caja.
+ *
+ * @param vDated Fecha del pago
+ * @param vSupplierFk Id del proveedor
+ * @param vAmount Cantidad a pagar
+ * @param vCurrencyFk Id de la moneda
+ * @param vForeignValue Tipo de cambio utilizado
+ * @param vBankFk Id del banco
+ * @param vPayMethodFk Id del método de pago
+ * @param vExpenseFk Id de gasto
+ * @param vConcept Concepto del pago
+ * @param vCompanyFk Id de la empresa
+ * @return paymentFk Id de pago insertado
+ */
+ INSERT INTO till(
+ concept,
+ serie,
+ `number`,
+ `out`,
+ dated,
+ isAccountable,
+ bankFk,
+ workerFk,
+ companyFk,
+ isConciliate
+ )
+ SELECT CONCAT('n/pago a ', `name`),
+ 'R',
+ vSupplierFk,
+ vAmount,
+ vDated,
+ 1,
+ vBankFk,
+ account.myUser_getId(),
+ vCompanyFk,
+ 1
+ FROM supplier
+ WHERE id = vSupplierFk;
+ INSERT INTO payment(
+ received,
+ dueDated,
+ supplierFk,
+ amount,
+ currencyFk,
+ divisa,
+ bankFk,
+ payMethodFk,
+ bankingFees,
+ concept,
+ companyFk
+ )
+ VALUES(
+ vDated,
+ vDated,
+ vSupplierFk,
+ vAmount,
+ vCurrencyFk,
+ IF(NOT vForeignValue, NULL, vForeignValue),
+ vBankFk,
+ vPayMethodFk,
+ vExpenseFk,
+ vConcept,
+ vCompanyFk
+ );
+
+ SELECT LAST_INSERT_ID() paymentFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64700,17 +64207,17 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareClientList`()
BEGIN
-
+
/*
* Require la tabla tmp.ticket(id,clientFk)
*/
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.client;
CREATE TEMPORARY TABLE tmp.client
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT DISTINCT clientFk id
- FROM tmp.ticket;
+ FROM tmp.ticket;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64735,7 +64242,7 @@ BEGIN
ENGINE = MEMORY
SELECT t.id ticketFk, t.clientFk
FROM vn.ticket t
- LEFT JOIN vn.ticketState ts ON ts.ticket = t.id
+ LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id
JOIN vn.client c ON c.id = t.clientFk
WHERE c.typeFk IN ('normal','handMaking','internalUse')
AND (
@@ -64838,14 +64345,14 @@ BEGIN
/**
* Comprueba si la impresora pertenece al sector
*
- * @param vLabelerFk id de la impresora
+ * @param vLabelerFk id de la impresora
* @param vSector sector a comprobar
*/
DECLARE isPrinterInNewSector BOOL;
IF vLabelerFk IS NOT NULL THEN
SELECT COUNT(sectorFK) INTO isPrinterInNewSector
- FROM vn.printer p
+ FROM vn.printer p
WHERE id = vLabelerFk AND sectorFk = vSector;
IF !isPrinterInNewSector THEN
@@ -64869,7 +64376,7 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `productionControl`(
- vWarehouseFk INT,
+ vWarehouseFk INT,
vScopeDays INT
)
proc: BEGIN
@@ -64884,15 +64391,15 @@ proc: BEGIN
DECLARE vEndingDate DATETIME;
DECLARE vIsTodayRelative BOOLEAN;
- SELECT TIMESTAMPADD(DAY, LEAST(vScopeDays, pc.maxProductionScopeDays), util.dayEnd(util.VN_CURDATE()))
+ SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY
INTO vEndingDate
- FROM productionConfig pc;
+ FROM productionConfig;
SELECT isTodayRelative INTO vIsTodayRelative
FROM worker
- WHERE id = getUser();
+ WHERE id = getUser(); -- Cambiar por account.myUser_getId(), falta dar permisos
- CALL prepareTicketList( util.VN_CURDATE() - INTERVAL 1 DAY, vEndingDate);
+ CALL prepareTicketList(util.yesterday(), vEndingDate);
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
SELECT * FROM tmp.productionTicket;
@@ -64950,8 +64457,8 @@ proc: BEGIN
rm.bufferFk
FROM tmp.productionTicket tt
JOIN ticket t ON tt.ticketFk = t.id
- LEFT JOIN ticketStateToday tst ON tst.ticket = t.id
- LEFT JOIN state st ON st.id = tst.state
+ LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id
+ LEFT JOIN `state` st ON st.id = tst.state
LEFT JOIN client c ON c.id = t.clientFk
LEFT JOIN worker wk ON wk.id = c.salesPersonFk
JOIN address a ON a.id = t.addressFk
@@ -64959,9 +64466,9 @@ proc: BEGIN
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
JOIN agency ag ON ag.id = am.agencyFk
- LEFT JOIN ticketState tls ON tls.ticket = tt.ticketFk
+ LEFT JOIN ticketState tls ON tls.ticketFk = tt.ticketFk
LEFT JOIN ticketLastUpdated tlu ON tlu.ticketFk = tt.ticketFk
- LEFT JOIN worker w on w.id = tls.worker
+ LEFT JOIN worker w ON w.id = tls.userFk
LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk
LEFT JOIN `zone` z ON z.id = t.zoneFk
LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
@@ -64970,7 +64477,7 @@ proc: BEGIN
LEFT JOIN parking pk ON pk.id = tp.parkingFk
WHERE t.warehouseFk = vWarehouseFk
AND dm.code IN ('AGENCY', 'DELIVERY', 'PICKUP');
-
+
UPDATE tmp.productionBuffer pb
JOIN (
SELECT pb.ticketFk, GROUP_CONCAT(p.code) previaParking
@@ -64978,12 +64485,12 @@ proc: BEGIN
JOIN sale s ON s.ticketFk = pb.ticketFk
JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
- JOIN parking p ON p.id = sg.parkingFk
+ JOIN parking p ON p.id = sg.parkingFk
GROUP BY pb.ticketFk
) t ON t.ticketFk = pb.ticketFk
SET pb.previaParking = t.previaParking;
- -- Problemas por ticket
+ -- Problemas por ticket
ALTER TABLE tmp.productionBuffer
CHANGE COLUMN `problem` `problem` VARCHAR(255),
ADD COLUMN `collectionH` INT,
@@ -65021,31 +64528,33 @@ proc: BEGIN
FROM tmp.productionTicket tt
JOIN saleVolume sv ON sv.ticketFk = tt.ticketFk
GROUP BY tt.ticketFk
- ) m on m.ticketFk = pb.ticketFk
+ ) m ON m.ticketFk = pb.ticketFk
SET pb.`lines` = m.`lines`,
pb.m3 = m.m3,
pb.preparationRate = m.rate;
DELETE FROM tmp.productionBuffer
- WHERE `lines`= 0;
+ WHERE NOT `lines`;
-- Lineas por linea de encajado
UPDATE tmp.productionBuffer pb
- JOIN ( SELECT ticketFk,
+ JOIN (
+ SELECT ticketFk,
SUM(sub.H) H,
SUM(sub.V) V,
SUM(sub.N) N
FROM (
- SELECT t.ticketFk,
+ SELECT t.ticketFk,
SUM(i.itemPackingTypeFk = 'H') H,
SUM(i.itemPackingTypeFk = 'V') V,
SUM(i.itemPackingTypeFk IS NULL) N
FROM tmp.productionTicket t
JOIN sale s ON s.ticketFk = t.ticketFk
JOIN item i ON i.id = s.itemFk
- GROUP BY t.ticketFk, i.itemPackingTypeFk) sub
+ GROUP BY t.ticketFk, i.itemPackingTypeFk
+ ) sub
GROUP BY ticketFk
- ) sub2 ON sub2.ticketFk = pb.ticketFk
+ ) sub2 ON sub2.ticketFk = pb.ticketFk
SET pb.H = sub2.H,
pb.V = sub2.V,
pb.N = sub2.N;
@@ -65069,15 +64578,31 @@ proc: BEGIN
-- Insertamos todos los tickets que tienen productos parkineados
-- en sectores de previa, segun el sector
+ CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock
+ (PRIMARY KEY(itemFk, sectorFk))
+ ENGINE = MEMORY
+ SELECT ish.itemFk,
+ p.sectorFk,
+ st.code = 'previousPrepared' isPreviousPrepared,
+ sc.itemPackingTypeFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector sc ON sc.id = p.sectorFk
+ JOIN sectorType st ON st.id = sc.typeFk
+ WHERE p.sectorFk
+ AND ish.visible
+ GROUP BY ish.itemFk, p.sectorFk;
+
INSERT INTO tmp.ticketWithPrevia(ticketFk, salesCount)
SELECT pb.ticketFk, COUNT(DISTINCT s.id)
FROM tmp.productionBuffer pb
JOIN sale s ON s.ticketFk = pb.ticketFk
- JOIN itemShelvingStock iss ON iss.itemFk = s.itemFk
+ JOIN tItemShelvingStock iss ON iss.itemFk = s.itemFk
JOIN sector sc ON sc.id = iss.sectorFk
JOIN item i ON i.id = iss.itemFk
WHERE iss.isPreviousPrepared
- AND (sc.itemPackingTypeFk IS NULL
+ AND (sc.itemPackingTypeFk IS NULL
OR (i.itemPackingTypeFk IS NULL AND NOT pb.V)
OR sc.itemPackingTypeFk = i.itemPackingTypeFk)
AND s.quantity > 0
@@ -65085,14 +64610,16 @@ proc: BEGIN
-- Se calcula la cantidad de productos que estan ya preparados porque su saleGroup está aparcado
UPDATE tmp.ticketWithPrevia twp
- JOIN ( SELECT pb.ticketFk, COUNT(DISTINCT s.id) salesInParkingCount
- FROM tmp.productionBuffer pb
- JOIN sale s ON s.ticketFk = pb.ticketFk
- JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
- JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
- WHERE sg.parkingFk IS NOT NULL
- AND s.quantity > 0
- GROUP BY pb.ticketFk) sub ON twp.ticketFk = sub.ticketFk
+ JOIN (
+ SELECT pb.ticketFk, COUNT(DISTINCT s.id) salesInParkingCount
+ FROM tmp.productionBuffer pb
+ JOIN sale s ON s.ticketFk = pb.ticketFk
+ JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
+ WHERE sg.parkingFk IS NOT NULL
+ AND s.quantity > 0
+ GROUP BY pb.ticketFk
+ ) sub ON twp.ticketFk = sub.ticketFk
SET twp.salesInParkingCount = sub.salesInParkingCount;
-- Marcamos como pendientes aquellos que no coinciden las cantidades
@@ -65101,11 +64628,244 @@ proc: BEGIN
SET pb.previousWithoutParking = TRUE
WHERE twp.salesCount > twp.salesInParkingCount;
- DROP TEMPORARY TABLE tmp.productionTicket;
- DROP TEMPORARY TABLE tmp.ticket;
- DROP TEMPORARY TABLE tmp.risk;
- DROP TEMPORARY TABLE tmp.ticket_problems;
- DROP TEMPORARY TABLE tmp.ticketWithPrevia;
+ DROP TEMPORARY TABLE
+ tmp.productionTicket,
+ tmp.ticket,
+ tmp.risk,
+ tmp.ticket_problems,
+ tmp.ticketWithPrevia,
+ tItemShelvingStock;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `productionError_add` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `productionError_add`()
+BEGIN
+ DECLARE vDatedFrom DATETIME;
+ DECLARE vDatedTo DATETIME;
+/**
+ * Rellena la tabla vn.productionError con estadisticas de encajadores, revisores y sacadores. Se ejecuta en el nightTask
+ */
+ SELECT util.VN_CURDATE() - INTERVAL 1 DAY, util.dayend(util.VN_CURDATE() - INTERVAL 1 DAY) INTO vDatedFrom, vDatedTo;
+ CALL timeControl_calculateAll(vDatedFrom, vDatedTo);
+
+ -- Rellena la tabla tmp.errorsByClaim con encajadores, revisores y sacadores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByClaim
+ ENGINE = MEMORY
+ SELECT COUNT(c.ticketFk) errors,
+ cd.workerFk
+ FROM claimDevelopment cd
+ JOIN claim c ON cd.claimFk = c.id
+ JOIN ticket t ON c.ticketFk = t.id
+ JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ AND cr.code IN ('pic', 'chk', 'pck')
+ GROUP BY cd.workerFk;
+
+ -- Genera la tabla tmp.volume con encajadores, sacadores y revisores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.volume
+ ENGINE = MEMORY
+ SELECT SUM(w.volume) volume,
+ w.workerFk
+ FROM bs.workerProductivity w
+ WHERE w.dated BETWEEN vDatedFrom AND vDatedTo
+ GROUP BY w.workerFk;
+
+ -- Rellena la tabla tmp.errorsByChecker con fallos de revisores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByChecker
+ ENGINE = MEMORY
+ SELECT st.workerFk,
+ COUNT(t.id) errors
+ FROM saleMistake sm
+ JOIN saleTracking st ON sm.saleFk = st.saleFk
+ JOIN `state` s2 ON s2.id = st.stateFk
+ JOIN sale s ON s.id = sm.saleFk
+ JOIN ticket t on t.id = s.ticketFk
+ WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo)
+ AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED')
+ GROUP BY st.workerFk;
+
+ -- Rellena la tabla tmp.expeditionErrors con fallos de expediciones
+ CREATE OR REPLACE TEMPORARY TABLE tmp.expeditionErrors
+ ENGINE = MEMORY
+ SELECT COUNT(t.id) errors,
+ e.workerFk
+ FROM vn.expeditionMistake pm
+ JOIN vn.expedition e ON e.id = pm.expeditionFk
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ GROUP BY e.workerFk;
+
+ -- Genera la tabla tmp.total para sacadores y revisores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.total
+ ENGINE = MEMORY
+ SELECT st.workerFk,
+ COUNT(DISTINCT t.id) ticketCount,
+ COUNT(s.id) lineCount
+ FROM saleTracking st
+ JOIN `state` s2 ON s2.id = st.stateFk
+ JOIN sale s ON s.id = st.saleFk
+ JOIN ticket t ON s.ticketFk = t.id
+ WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo)
+ AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED')
+ GROUP BY st.workerFk;
+
+ -- Rellena la tabla vn.productionError con sacadores
+ INSERT INTO productionError(userFk,
+ firstname,
+ lastname,
+ rol,
+ ticketNumber,
+ lineNumber,
+ error,
+ volume,
+ hourStart,
+ hourEnd,
+ hourWorked,
+ dated)
+ SELECT w.id,
+ w.firstName,
+ w.lastName,
+ "Sacadores",
+ t.ticketCount totalTickets,
+ t.lineCount,
+ IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) errors,
+ v.volume volume,
+ SUBSTRING(tc.tableTimed, 1, 5) hourStart,
+ SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd,
+ IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked,
+ vDatedFrom dated
+ FROM tmp.total t
+ LEFT JOIN worker w ON w.id = t.workerFk
+ LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk
+ LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk
+ LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk
+ LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk
+ JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores
+ FROM vn.collection c
+ JOIN vn.state s ON s.id = c.stateFk
+ JOIN vn.train tn ON tn.id = c.trainFk
+ JOIN vn.worker w ON w.id = c.workerFk
+ WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id
+ GROUP BY w.id;
+
+ CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores
+ ENGINE = MEMORY
+ SELECT COUNT(c.ticketFk) errors,
+ tt.userFk
+ FROM claimDevelopment cd
+ JOIN claim c ON cd.claimFk = c.id
+ JOIN ticket t ON c.ticketFk = t.id
+ JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
+ JOIN ticketTracking tt ON tt.ticketFk = t.id
+ JOIN `state` s ON s.id = tt.stateFk
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ AND cr.code = 'chk'
+ AND s.code = 'ON_PREPARATION'
+ GROUP BY tt.userFk;
+
+ UPDATE productionError ep
+ JOIN itemPickerErrors ipe ON ipe.userFk = ep.userFk
+ SET ep.error = ep.error + ipe.errors
+ WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores';
+
+ DROP TEMPORARY TABLE itemPickerErrors;
+
+ -- Rellena la tabla vn.productionError con revisores
+ CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Revisadores");
+
+ -- Genera la tabla tmp.total para encajadores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.total
+ ENGINE = MEMORY
+ SELECT e.workerFk,
+ COUNT(DISTINCT t.id) ticketCount,
+ COUNT(s.id) lineCount
+ FROM expedition e
+ JOIN ticket t ON e.ticketFk = t.id
+ JOIN sale s ON s.ticketFk = t.id
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ GROUP BY e.workerFk;
+
+ -- Rellena la tabla vn.productionError con encajadores
+ CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Encajadores");
+
+ DROP TEMPORARY TABLE tmp.errorsByClaim,
+ tmp.volume,
+ tmp.errorsByChecker,
+ tmp.expeditionErrors,
+ tmp.total;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `productionError_addCheckerPackager` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `productionError_addCheckerPackager`(
+ vDatedFrom DATETIME,
+ vDatedTo DATETIME,
+ vRol VARCHAR(50))
+BEGIN
+/**
+ * Rellena la tabla vn.productionError con rol
+ *
+ * @param vDatedFrom Fecha desde
+ * @param vDatedTo Fecha hasta
+ * @param vRol rol a insertar
+ */
+ INSERT INTO productionError(userFk,
+ firstname,
+ lastname,
+ rol,
+ ticketNumber,
+ lineNumber,
+ error,
+ volume,
+ hourStart,
+ hourEnd,
+ hourWorked,
+ dated)
+ SELECT w.id,
+ w.firstName,
+ w.lastName,
+ vRol,
+ t.ticketCount totalTickets,
+ t.lineCount,
+ IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) + IFNULL(pe.errors,0) errors,
+ NULL volume,
+ SUBSTRING(tc.tableTimed, 1, 5) hourStart,
+ SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd,
+ IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked,
+ vDatedFrom dated
+ FROM tmp.total t
+ LEFT JOIN worker w ON w.id = t.workerFk
+ LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk
+ LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk
+ LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk
+ LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk
+ LEFT JOIN tmp.expeditionErrors pe ON pe.workerFk = t.workerFk
+ GROUP BY w.id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -65125,23 +64885,23 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `productionSectorList`(vSectorFk INT)
BEGIN
/**
- * Devuelve el listado de vn.sale que se puede preparar en previa para ese sector
+ * Devuelve el listado de sale que se puede preparar en previa para ese sector
*
- * @param vSectorFk Identificador de vn.sector
+ * @param vSectorFk Identificador de sector
*/
DECLARE vWarehouseFk INT;
SELECT warehouseFk INTO vWarehouseFk
- FROM vn.sector
+ FROM sector
WHERE id = vSectorFk;
DROP TEMPORARY TABLE IF EXISTS tmp.whiteTicket;
CREATE TEMPORARY TABLE tmp.whiteTicket
(ticketFk INT PRIMARY KEY)
SELECT s.ticketFk , count(*) AS saleNum, sum(ISNULL(i.itemPackingTypeFk)) iptNull
- FROM vn.sale s
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.ticket t ON t.id = s.ticketFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticket t ON t.id = s.ticketFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(HOUR, 23, util.VN_CURDATE())
GROUP BY s.ticketFk
HAVING saleNum = iptNull;
@@ -65150,15 +64910,15 @@ BEGIN
CREATE TEMPORARY TABLE tmp.sectorTypeTicket
(ticketFk INT PRIMARY KEY)
SELECT s.ticketFk , sum(i.itemPackingTypeFk <=> sc.itemPackingTypeFk) iptSector
- FROM vn.sale s
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.sector sc ON sc.id = vSectorFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN sector sc ON sc.id = vSectorFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(HOUR, 23, util.VN_CURDATE())
GROUP BY s.ticketFk
HAVING iptSector;
- CALL vn.productionControl(vWarehouseFk, 0);
+ CALL productionControl(vWarehouseFk, 0);
SELECT 0,999999,0 INTO @sameTicket, @ticket, @litrosTicket;
@@ -65197,19 +64957,19 @@ BEGIN
IF (MINUTE(isa.shipped),MINUTE(isa.shipped), MINUTE(isa.`hour`)) Minuto,
i.subName,
CAST(isa.physicalVolume * 1000 AS DECIMAL(10,0)) as Litros
- FROM vn.itemShelvingAvailable isa
- JOIN vn.item i ON i.id = isa.itemFk
- JOIN vn.sector s ON s.id = isa.sectorFk AND s.warehouseFk = isa.warehouseFk
- JOIN vn.ticket t ON t.id = isa.ticketFk
+ FROM itemShelvingAvailable isa
+ JOIN item i ON i.id = isa.itemFk
+ JOIN sector s ON s.id = isa.sectorFk AND s.warehouseFk = isa.warehouseFk
+ JOIN sectorType st ON st.id = s.typeFk
+ JOIN ticket t ON t.id = isa.ticketFk
LEFT JOIN tmp.whiteTicket wt ON wt.ticketFk = isa.ticketFk
LEFT JOIN tmp.sectorTypeTicket stt ON stt.ticketFk = isa.ticketFk
- LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = isa.saleFk
- JOIN vn.client c ON c.id = t.clientFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = isa.saleFk
+ JOIN client c ON c.id = t.clientFk
JOIN tmp.productionBuffer pb ON pb.ticketFk = t.id
- JOIN vn.packagingConfig pc
- WHERE IF(s.isPreviousPreparedByPacking,
+ JOIN packagingConfig pc
+ WHERE IF(st.code = 'previousByPacking',
i.`size` > pc.previousPreparationMinimumSize
- AND isa.packing > 1
AND (MOD(TRUNCATE(isa.quantity,0), isa.packing)= 0 ),
TRUE)
AND sgd.saleFk IS NULL
@@ -65264,7 +65024,7 @@ BEGIN
`yearMonth` INT
)
ENGINE = MEMORY;
-
+
WHILE vDated <= vEnded DO
INSERT INTO tmp.rangeDate
SET `dated` = vDated,
@@ -65274,7 +65034,7 @@ BEGIN
`day` = DAY(vDated),
`week` = WEEK(vDated, 1),
`yearMonth` = YEAR(vDated) * 100 + MONTH(vDated);
-
+
SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY);
END WHILE;
END ;;
@@ -65363,7 +65123,7 @@ BEGIN
CALL cache.available_refresh(vCalc, FALSE, vWarehouseFk, vDate);
DROP TEMPORARY TABLE IF EXISTS tmp.recipeCook;
-
+
CREATE TEMPORARY TABLE tmp.recipeCook
SELECT *,
@counter := IF(@element = element COLLATE utf8_general_ci , @counter + 1, 1) as counter,
@@ -65381,22 +65141,22 @@ BEGIN
IFNULL((i.inkFk = r.inkFk ) ,0)
+ IFNULL((i.size = r.size) ,0)
+ IFNULL((i.name LIKE CONCAT('%',r.name,'%')) ,0)
- + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0)
+ + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0)
+ IFNULL((i.typeFk = r.typeFk),0) as matches,
i.typeFk,
rl.previousSelected
- FROM vn.recipe r
+ FROM vn.recipe r
JOIN vn.item i ON (IFNULL(i.name LIKE CONCAT('%',r.name,'%'), 0)
OR IFNULL(i.longName LIKE CONCAT('%',r.longName,'%'),0))
OR i.typeFk <=> r.typeFk
JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vCalc
LEFT JOIN (SELECT recipe_ItemFk, element as log_element, selected_ItemFk, count(*) as previousSelected
FROM vn.recipe_log
- GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk
+ GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk
AND rl.log_element = r.element
AND rl.selected_ItemFk = i.id
WHERE r.itemFk = vItemFk
- AND a.available > vBunchesQuantity * r.quantity
+ AND a.available > vBunchesQuantity * r.quantity
UNION ALL
SELECT 100 itemFk,
CONCAT('? ',r.element,' ',IFNULL(r.size,''),' ',IFNULL(r.inkFk,'')) as longName,
@@ -65413,15 +65173,15 @@ BEGIN
WHERE r.itemFk = vItemFk
GROUP BY r.element
) sub
-
+
ORDER BY element, matches DESC, previousSelected DESC;
-
- SELECT *
+
+ SELECT *
FROM tmp.recipeCook
WHERE counter < 6
- OR itemFk = 100
+ OR itemFk = 100
;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -65442,83 +65202,117 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `recipe_Plaster`(vItemFk INT, vTicke
BEGIN
DECLARE vLastCost DECIMAL(10,2);
- DECLARE vWarehouseFk INT;
- DECLARE vShipped DATE;
- DECLARE vEntryFk INT;
- DECLARE vTravelFk INT;
+ DECLARE vWarehouseFk INT;
+ DECLARE vShipped DATE;
+ DECLARE vEntryFk INT;
+ DECLARE vTravelFk INT;
- CALL cache.last_buy_refresh(FALSE);
-
- SELECT warehouseFk, shipped
+ CALL cache.last_buy_refresh(FALSE);
+
+ SELECT warehouseFk, shipped
INTO vWarehouseFk, vShipped
- FROM vn.ticket
- WHERE id = vTicketFk;
+ FROM vn.ticket
+ WHERE id = vTicketFk;
UPDATE vn.ticket t
JOIN vn.item i ON i.id = vItemFk
- SET t.nickname = CONCAT(vQuantity,' ',i.longName)
+ SET t.nickname = CONCAT(vQuantity,' ',i.longName)
WHERE t.id = vTicketFk;
SELECT b.buyingValue INTO vLastCost
FROM vn.buy b
JOIN cache.last_buy lb ON lb.buy_id = b.id
WHERE lb.item_id = vItemFk
- ORDER BY (lb.warehouse_id = vWarehouseFk) DESC
- LIMIT 1;
+ ORDER BY (lb.warehouse_id = vWarehouseFk) DESC
+ LIMIT 1;
INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price)
SELECT vTicketFk, 98, - vQuantity, i.longName, vLastCost
FROM vn.item i
- WHERE i.id = vItemFk;
- /*
- SELECT tr.id INTO vTravelFk
- FROM vn.travel tr
- JOIN vn.warehouse w ON w.id = tr.warehouseOutFk
- WHERE tr.warehouseInFk = vWarehouseFk
- AND tr.landed = vShipped
- AND w.name = 'Confeccion';
-
- IF IFNULL(vTravelFk,0) = 0 THEN
-
- INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyFk)
- SELECT vShipped, vShipped, vWarehouseFk, w.id, am.id
- FROM vn.warehouse w
- JOIN vn.agencyMode am
- WHERE w.name = 'Confeccion'
- AND am.name = 'DIRECTO PROVEEDOR';
-
- SET vTravelFk = LAST_INSERT_ID();
-
- END IF;
-
- SELECT e.id INTO vEntryFk
- FROM vn.entry e
- JOIN vn.supplier s ON s.id = supplierFk
- WHERE e.travelFk = vTravelFk
- AND s.name = 'Confeccion Natural'
- AND e.isRaid = FALSE;
-
- IF IFNULL(vEntryFk,0) = 0 THEN
-
- INSERT INTO vn.entry(supplierFk, evaNotes, travelFk, companyFk)
- SELECT s.id, t.nickname, vTravelFk, c.id
- FROM vn.supplier s
- JOIN vn.ticket t ON t.id = vTicketFk
- JOIN vn.company c ON c.code = 'VNL'
- WHERE s.name = 'Confeccion Natural';
-
- SET vEntryFk = LAST_INSERT_ID();
-
- END IF;
-
- INSERT INTO vn.buy(entryFk, itemFk, quantity, buyingValue, packageFk, packing, grouping)
- SELECT vEntryFk, b.itemFk, vQuantity, b.buyingValue, b.packageFk, b.packing, b.grouping
- FROM cache.last_buy lb
- JOIN vn.buy b ON b.id = lb.buy_id
- WHERE lb.item_id = vItemFk
- ORDER BY (lb.warehouse_id = vWarehouseFk) DESC
- LIMIT 1;
+ WHERE i.id = vItemFk;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `remittance_calc` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `remittance_calc`(
+ vDated DATE
+)
+BEGIN
+/**
+* Calcula los datos de remesa, incluyendo el importe,
+* el vencimiento, y otros datos relevantes.
+*
+* @param vDated Fecha a calcular
+* @return tmp.remittance
*/
+ CREATE OR REPLACE TEMPORARY TABLE tmp.remittance
+ SELECT CONCAT(s.nif, REPEAT('0', 12 - LENGTH(s.nif))) cif,
+ c.id clientFk,
+ c.name client,
+ c.fi,
+ sub.paymentDate,
+ 0 invoiceAmount,
+ CAST(sub.receipt AS DECIMAL(10,2)) receiptAmount,
+ 0 currentAmount,
+ sub.companyFk,
+ c.socialName,
+ CAST(sub.receipt AS DECIMAL(10,2)) totalAmount,
+ CAST(sub.receipt AS DECIMAL(10,2)) balance,
+ s.name company,
+ co.code companyCode,
+ c.accountingAccount,
+ c.iban,
+ c.hasSepaVnl,
+ c.hasCoreVnl,
+ c.hasLcr,
+ be.bic,
+ be.`name` entityName
+ FROM client c
+ JOIN (
+ SELECT risk.companyFk,
+ c.id,
+ SUM(risk.amount) receipt,
+ IF((c.dueDay + graceDays) MOD 30.001 <= DAY(vDated),
+ LAST_DAY(vDated - INTERVAL 1 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY,
+ LAST_DAY(vDated - INTERVAL 2 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY
+ ) paymentDate
+ FROM client c
+ JOIN payMethod pm ON pm.id = c.payMethodFk
+ JOIN (
+ SELECT cr.companyFk, cr.clientFk, cr.amount
+ FROM client c
+ JOIN clientRisk cr ON cr.clientFk = c.id
+ JOIN payMethod pm ON pm.id = c.payMethodFk
+ WHERE pm.code = 'bankDraft'
+ UNION ALL
+ SELECT io.companyFk, io.clientFk, - io.amount
+ FROM invoiceOut io
+ JOIN client c ON c.id = io.clientFk
+ JOIN payMethod pm ON pm.id = c.payMethodFk
+ WHERE io.dued > vDated
+ AND pm.code = 'bankDraft'
+ AND pm.outstandingDebt
+ AND io.amount > 0
+
+ ) risk ON risk.clientFk = c.id
+ GROUP BY risk.companyFk, c.id
+ HAVING receipt > 10
+ ) sub ON sub.id = c.id
+ JOIN supplier s ON s.id = sub.companyFk
+ JOIN company co ON co.id = sub.companyFk
+ LEFT JOIN bankEntity be ON be.id = c.bankEntityFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -65612,7 +65406,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `report_print`(
)
BEGIN
/**
- * Inserts in the print queue the report to be printed and the necessary parameters for this
+ * Inserts in the print queue the report to be printed and the necessary parameters for this
* one taking into account the paper size of both the printer and the report.
*
* @param vReportName the report to be printed.
@@ -65655,11 +65449,11 @@ BEGIN
END IF;
IF vReportFk IS NULL THEN
- CALL util.throw('reportNotExists');
+ CALL util.throw('reportNotExists');
END IF;
IF vReportSize <> vPrinteSize THEN
- CALL util.throw('incorrectSize');
+ CALL util.throw('incorrectSize');
END IF;
START TRANSACTION;
@@ -65668,7 +65462,7 @@ BEGIN
priorityFk = vPriorityFk,
reportFk = vReportFk,
workerFk = vUserFk;
-
+
SET vPrintQueueFk = LAST_INSERT_ID();
WHILE vI < vLength DO
@@ -65701,16 +65495,16 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `riskAllClients`(maxRiskDate DATE)
BEGIN
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
CREATE TEMPORARY TABLE tmp.client_list
(PRIMARY KEY (Id_Cliente))
ENGINE = MEMORY
SELECT id Id_Cliente, null grade FROM vn.client;
-
+
CALL vn2008.risk_vs_client_list(maxRiskDate);
-
- SELECT
+
+ SELECT
c.RazonSocial,
c.Id_Cliente,
c.Credito,
@@ -65722,7 +65516,7 @@ BEGIN
JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente
JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente
GROUP BY c.Id_cliente;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.risk;
DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
END ;;
@@ -65781,25 +65575,25 @@ BEGIN
DECLARE vM3 INT;
DECLARE vKg INT;
DECLARE vMatricula varchar(50);
-
+
SELECT sum(packages) as bultos
INTO vPackages
- FROM vn.ticket t
+ FROM vn.ticket t
WHERE routeFk = vRouteFk;
-
+
SELECT SUM(sv.physicalVolume), SUM(sv.physicalWeight)
INTO vM3, vKg
FROM vn.saleVolume sv
WHERE sv.routeFk = vRouteFk;
-
+
SELECT v.numberPlate as matricula
INTO vMatricula
- FROM vn.route r
+ FROM vn.route r
JOIN vn.vehicle v ON r.vehicleFk = v.id
WHERE r.id = vRouteFk;
-
+
SELECT vRouteFk as Ruta,
- vPackages as Bultos,
+ vPackages as Bultos,
vM3 as m3,
vKg as Kg,
vMatricula as Matricula;
@@ -65864,7 +65658,7 @@ BEGIN
) sub ON sub.routeFk = rm.routeFk
SET rm.ticketFree = sub.ticketFree;
- UPDATE routesMonitor rm
+ UPDATE routesMonitor rm
JOIN(
SELECT t.routeFk, COUNT(*) AS ticketPacked
FROM vn.ticket t
@@ -65950,11 +65744,11 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `routeSetOk`(
vRouteFk INT)
BEGIN
-
+
UPDATE vn.route r
SET r.isOk = 1
WHERE r.id = vRouteFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -65993,15 +65787,18 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `route_calcCommission`(vSelf INT)
-proc: BEGIN
+CREATE DEFINER=`root`@`localhost` PROCEDURE `route_calcCommission`(
+ vSelf INT
+)
+BEGIN
/**
- * Calcula las comisión para una ruta y guarda los valores en la tabla routeCommission
+ * Calcula las comisión para una ruta y guarda los valores
+ * en la tabla vn.routeCommission.
*
- * @param vSelf id de ruta
+ * @param vSelf Id de ruta
*/
- DECLARE vIsUpdatable BOOL;
- DECLARE vIsFreelance BOOL;
+ DECLARE vIsUpdatable, vIsFreelance BOOL DEFAULT 0;
+ DECLARE vAgencyModePricePercentage DOUBLE;
SELECT r.created >= rc.cutoffDated INTO vIsUpdatable
FROM route r
@@ -66017,6 +65814,13 @@ proc: BEGIN
JOIN worker w ON w.id = r.workerFk
WHERE r.id = vSelf;
+ SELECT ampp.percentage INTO vAgencyModePricePercentage
+ FROM route r
+ JOIN agencyMode am ON am.id = r.agencyModeFk
+ JOIN agencyModePricePercentage ampp ON ampp.agencyModeFk = am.id
+ WHERE r.id = vSelf;
+
+ -- Falta calcular el precio, a la espera de saber el/los campo/s exacto/s al que aplicarlo/s
IF vIsFreelance THEN
INSERT INTO routeCommission (
routeFk,
@@ -66026,13 +65830,17 @@ proc: BEGIN
cat5m3
)
SELECT vSelf,
- r.commissionWorkCenterFk,
- rc.freelanceM3 * IF(
- IFNULL(r.m3, 0) >= rc.freelanceMinM3,
+ r.commissionWorkCenterFk,
+ IF(vAgencyModePricePercentage IS NOT NULL,
+ vAgencyModePricePercentage / 100,
+ rc.freelanceM3
+ ) *
+ IF(IFNULL(r.m3, 0) >= rc.freelanceMinM3,
IFNULL(r.m3, 0),
- 0),
- rc.distributionCat4M3 * IFNULL(r.m3, 0),
- rc.distributionCat5M3 * IFNULL(r.m3, 0)
+ 0
+ ),
+ rc.distributionCat4M3 * IFNULL(r.m3, 0),
+ rc.distributionCat5M3 * IFNULL(r.m3, 0)
FROM route r
JOIN vehicle v ON v.id = r.vehicleFk
JOIN routeConfig rc
@@ -66051,15 +65859,15 @@ proc: BEGIN
cat5m3
)
SELECT vSelf,
- r.commissionWorkCenterFk,
- (r.kmEnd - r.kmStart) *
- IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight),
- IFNULL(r.m3, 0) *
- IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4),
- (r.kmEnd - r.kmStart) * rc.kmYearly,
- IFNULL(r.m3, 0) * rc.m3Yearly,
- rc.distributionCat4M3 * IFNULL(r.m3, 0),
- rc.distributionCat5M3 * IFNULL(r.m3, 0)
+ r.commissionWorkCenterFk,
+ (r.kmEnd - r.kmStart) *
+ IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight),
+ IFNULL(r.m3, 0) *
+ IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4),
+ (r.kmEnd - r.kmStart) * rc.kmYearly,
+ IFNULL(r.m3, 0) * rc.m3Yearly,
+ rc.distributionCat4M3 * IFNULL(r.m3, 0),
+ rc.distributionCat5M3 * IFNULL(r.m3, 0)
FROM route r
JOIN vehicle v ON v.id = r.vehicleFk
JOIN routeConfig rc
@@ -66091,7 +65899,7 @@ proc: BEGIN
/**
* Recalculates modified route.
*/
-
+
DECLARE vDone BOOL;
DECLARE vRouteFk INT;
@@ -66100,7 +65908,7 @@ proc: BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
-
+
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK('vn.route_doRecalc');
@@ -66156,63 +65964,66 @@ BEGIN
* @param vRouteFk
* @select Información de los tickets
*/
-SELECT *
- FROM (
- SELECT t.id Id,
- t.clientFk Client,
- a.id Address,
- a.nickname ClientName,
- t.packages Packages,
- a.street AddressName,
- a.postalCode PostalCode,
- a.city City,
- sub2.itemPackingTypeFk PackingType,
- c.phone ClientPhone,
- c.mobile ClientMobile,
- a.phone AddressPhone,
- a.mobile AddressMobile,
- d.longitude Longitude,
- d.latitude Latitude,
- wm.mediaValue SalePersonPhone,
- tob.description Note,
- t.isSigned Signed,
- t.priority,
- t.cmrFk
- FROM ticket t
- JOIN client c ON t.clientFk = c.id
- JOIN address a ON t.addressFk = a.id
- LEFT JOIN delivery d ON d.ticketFk = t.id
- LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk
- LEFT JOIN(
- SELECT tob.description, t.id
- FROM ticketObservation tob
- JOIN ticket t ON tob.ticketFk = t.id
- JOIN observationType ot ON ot.id = tob.observationTypeFk
- WHERE t.routeFk = vRouteFk
- AND ot.code = 'delivery'
- )tob ON tob.id = t.id
- LEFT JOIN(
- SELECT sub.ticketFk,
- CONCAT('(',
- GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk
- ORDER BY sub.items DESC SEPARATOR ','),
- ') ') itemPackingTypeFk
- FROM (
- SELECT s.ticketFk, i.itemPackingTypeFk, COUNT(*) items
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- WHERE t.routeFk = vRouteFk
- GROUP BY t.id, i.itemPackingTypeFk
- )sub
- GROUP BY sub.ticketFk
- )sub2 ON sub2.ticketFk = t.id
- WHERE t.routeFk = vRouteFk
- ORDER BY d.id DESC
- LIMIT 10000000000000000000
- )sub3
- GROUP BY sub3.id
- ORDER BY sub3.priority;
+SELECT t.id Id,
+ t.clientFk Client,
+ a.id Address,
+ a.nickname ClientName,
+ t.packages Packages,
+ a.street AddressName,
+ a.postalCode PostalCode,
+ a.city City,
+ sub3.itemPackingTypeFk PackingType,
+ c.phone ClientPhone,
+ c.mobile ClientMobile,
+ a.phone AddressPhone,
+ a.mobile AddressMobile,
+ d.longitude Longitude,
+ d.latitude Latitude,
+ wm.mediaValue SalePersonPhone,
+ tob.description Note,
+ t.isSigned Signed,
+ t.priority,
+ t.cmrFk
+ FROM ticket t
+ JOIN client c ON t.clientFk = c.id
+ JOIN address a ON t.addressFk = a.id
+ LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk
+ LEFT JOIN (
+ SELECT t.addressFk, MAX(d.ticketFk) lastTicketFk
+ FROM ticket t
+ JOIN delivery d ON t.id = d.ticketFk
+ JOIN ticket ti ON ti.routeFk = vRouteFk
+ AND ti.id = t.id
+ AND ti.clientFk = t.clientFk
+ GROUP BY addressFk
+ )sub ON sub.addressFk = a.id
+ LEFT JOIN delivery d ON d.ticketFk = sub.lastTicketFk
+ LEFT JOIN(
+ SELECT t.id ticketFk, tob.description
+ FROM ticketObservation tob
+ JOIN ticket t ON tob.ticketFk = t.id
+ JOIN observationType ot ON ot.id = tob.observationTypeFk
+ WHERE t.routeFk = vRouteFk
+ AND ot.code = 'delivery'
+ )tob ON tob.ticketFk = t.id
+ LEFT JOIN(
+ SELECT sub2.ticketFk,
+ CONCAT('(',
+ GROUP_CONCAT(DISTINCT sub2.itemPackingTypeFk
+ ORDER BY sub2.items DESC SEPARATOR ','),
+ ') ') itemPackingTypeFk
+ FROM (
+ SELECT s.ticketFk, i.itemPackingTypeFk, COUNT(*) items
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ WHERE t.routeFk = vRouteFk
+ GROUP BY t.id, i.itemPackingTypeFk
+ )sub2
+ GROUP BY sub2.ticketFk
+ )sub3 ON sub3.ticketFk = t.id
+ WHERE t.routeFk = vRouteFk
+ ORDER BY priority, Id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -66258,27 +66069,27 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleBuy_Add`(vSaleFk INT, vBuyFk INT)
BEGIN
-
+
/* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad
- *
+ *
* @param vSaleFk clave primaria de vn.sale
* @param vBuyFk clave primaria de vn.buy
*/
- /*IF (SELECT COUNT(*)
+ /*IF (SELECT COUNT(*)
FROM vn.sale s
JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
WHERE s.id = vSaleFk
AND ic.code = 'fruit') THEN */
-
- IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN
-
+
+ IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN
+
INSERT INTO vn.saleBuy (saleFk, buyFk)
VALUES(vSaleFk, vBuyFk);
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -66295,15 +66106,17 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGroup_add`(vSectorFk INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGroup_add`(vSectorFk INT,vTicketFk INT)
BEGIN
/**
* Añade un nuevo registro a la tabla y devuelve su id.
*
* @param vSectorFk Identificador de vn.sector
*/
- INSERT INTO vn.saleGroup(userFk, sectorFk)
- VALUES (account.myUser_getId(), vSectorFk);
+ INSERT INTO vn.saleGroup
+ SET `userFk` = account.myUser_getId(),
+ `sectorFk` = vSectorFk,
+ `ticketFk` = vTicketFk;
SELECT LAST_INSERT_ID();
END ;;
@@ -66425,6 +66238,62 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `saleSplit` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `saleSplit`(vSaleFk INT, vQuantity INT)
+BEGIN
+
+
+ DECLARE vNewSaleFk INT;
+
+ INSERT INTO vn.sale(itemFk,
+ concept,
+ price,
+ discount,
+ quantity,
+ ticketFk,
+ isPriceFixed)
+ SELECT s.itemFk,
+ i.longName,
+ s.price,
+ s.discount,
+ vQuantity,
+ s.ticketFk,
+ s.isPriceFixed
+ FROM vn.sale s
+ JOIN vn.item i ON i.id = s.itemFk
+ WHERE s.id = vSaleFk;
+
+ UPDATE vn.sale s
+ JOIN vn.item i ON i.id = s.itemFk
+ SET s.quantity = s.quantity - vQuantity, s.concept = i.longName
+ WHERE s.id = vSaleFk;
+
+ SELECT LAST_INSERT_ID() INTO vNewSaleFk;
+
+ INSERT INTO vn.saleComponent( saleFk,
+ componentFk,
+ value)
+ SELECT vNewSaleFk,
+ componentFk,
+ value
+ FROM vn.saleComponent
+ WHERE saleFk = vSaleFk;
+
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sales_merge` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -66434,41 +66303,41 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT)
-BEGIN
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
- CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve
- SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity
- FROM sale s
- JOIN item i ON i.id = s.itemFk
- JOIN itemType it ON it.id = i.typeFk
- WHERE s.ticketFk = vTicketFk
- AND it.isMergeable
- GROUP BY s.itemFk, s.price, s.discount;
-
- START TRANSACTION;
-
- UPDATE sale s
- JOIN tSalesToPreserve stp ON stp.id = s.id
- SET quantity = newQuantity
- WHERE s.ticketFk = vTicketFk;
-
- DELETE s.*
- FROM sale s
- LEFT JOIN tSalesToPreserve stp ON stp.id = s.id
- JOIN item i ON i.id = s.itemFk
- JOIN itemType it ON it.id = i.typeFk
- WHERE s.ticketFk = vTicketFk
- AND stp.id IS NULL
- AND it.isMergeable;
-
- COMMIT;
-
- DROP TEMPORARY TABLE tSalesToPreserve;
+BEGIN
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve
+ SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ WHERE s.ticketFk = vTicketFk
+ AND it.isMergeable
+ GROUP BY s.itemFk, s.price, s.discount;
+
+ START TRANSACTION;
+
+ UPDATE sale s
+ JOIN tSalesToPreserve stp ON stp.id = s.id
+ SET quantity = newQuantity
+ WHERE s.ticketFk = vTicketFk;
+
+ DELETE s.*
+ FROM sale s
+ LEFT JOIN tSalesToPreserve stp ON stp.id = s.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ WHERE s.ticketFk = vTicketFk
+ AND stp.id IS NULL
+ AND it.isMergeable;
+
+ COMMIT;
+
+ DROP TEMPORARY TABLE tSalesToPreserve;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -66503,17 +66372,17 @@ BEGIN
OPEN cCur;
myLoop: LOOP
-
+
SET vDone = FALSE;
-
+
FETCH cCur INTO vTicketFk;
IF vDone THEN
LEAVE myLoop;
END IF;
-
+
CALL vn.sales_merge(vTicketFk);
-
+
END LOOP;
CLOSE cCur;
@@ -66644,9 +66513,9 @@ BEGIN
DELETE st.*
FROM vn.saleTracking st
JOIN vn.state s ON s.id = st.stateFk
- WHERE st.saleFk = vSaleFk
+ WHERE st.saleFk = vSaleFk
AND s.code = vState COLLATE utf8_unicode_ci;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -66663,12 +66532,12 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`(
- vSaleFK INT,
- vIsChecked BOOLEAN,
- vOriginalQuantity INT,
- vWorkerFk INT,
- vAction VARCHAR(50),
+CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`(
+ vSaleFK INT,
+ vIsChecked BOOLEAN,
+ vOriginalQuantity INT,
+ vWorkerFk INT,
+ vAction VARCHAR(50),
vState VARCHAR(50),
vIsScanned BOOLEAN)
BEGIN
@@ -66684,12 +66553,12 @@ BEGIN
* @param vIsScanned Identificador si se ha escaneado automáticamente o manual
*/
- REPLACE vn.saleTracking(saleFk,
- isChecked,
- originalQuantity,
- workerFk,
+ REPLACE vn.saleTracking(saleFk,
+ isChecked,
+ originalQuantity,
+ workerFk,
stateFk,
- isScanned)
+ isScanned)
SELECT vSaleFK,
vIsChecked,
vOriginalQuantity,
@@ -66716,27 +66585,27 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_updateIsChecked`(vSaleFK INT, vIsChecked BOOL, vIsScanned BOOL)
BEGIN
-
+
/**
* Actualiza el estado del campo vn.saleTracking.isChecked y elimina las lineas de vn.itemShelving
* si procede, en el caso de las preparaciones previas, por usuario
- *
+ *
* @param vSaleFk Identificador de vn.sale
* @param vIsChecked Estado del registro
*/
-
+
UPDATE vn.saleTracking st
JOIN vn.state s ON s.id = st.stateFk AND s.code = 'PREVIOUS_PREPARATION'
SET st.isChecked = vIsChecked,
st.isScanned = vIsScanned
WHERE st.saleFk = vSaleFK
AND st.workerFk = account.myUser_getId();
-
+
IF vIsChecked = FALSE THEN
-
- DELETE FROM vn.itemShelvingSale
+
+ DELETE FROM vn.itemShelvingSale
WHERE saleFk = vSaleFK;
-
+
END IF;
END ;;
@@ -66746,16 +66615,16 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_calculateComponent` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_calculateComponent`(vSelf INT, vOption INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_calculateComponent`(vSelf INT, vOption VARCHAR(25))
proc: BEGIN
/**
* Crea tabla temporal para vn.sale_recalcComponent() para recalcular los componentes
@@ -66763,14 +66632,14 @@ proc: BEGIN
* @param vSelf Id de la venta
* @param vOption indica en que componente pone el descuadre, NULL en casos habituales
*/
- CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
- SELECT s.id
- FROM sale s
- WHERE s.id = vSelf;
+ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
+ SELECT s.id
+ FROM sale s
+ WHERE s.id = vSelf;
+
+ CALL sale_recalcComponent(vOption);
- CALL sale_recalcComponent(vOption);
-
- DROP TEMPORARY TABLE tmp.recalculateSales;
+ DROP TEMPORARY TABLE tmp.recalculateSales;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -66779,7 +66648,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `sale_checkNoComponents` */;
+/*!50003 DROP PROCEDURE IF EXISTS `sale_getBoxPickingList` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@@ -66787,74 +66656,77 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_checkNoComponents`(vCreatedFrom DATETIME, vCreatedTo DATETIME)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getBoxPickingList`(vSectorFk INT, vDated DATE)
BEGIN
/**
- * Comprueba que las ventas creadas entre un rango de fechas tienen componentes
- *
- * @param vCreatedFrom inicio del rango
- * @param vCreatedTo fin del rango
- */
- DECLARE v_done BOOL DEFAULT FALSE;
- DECLARE vSaleFk INTEGER;
- DECLARE vTicketFk INTEGER;
- DECLARE vConcept VARCHAR(50);
- DECLARE vCur CURSOR FOR
- SELECT s.id
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- JOIN item i ON i.id = s.itemFk
- JOIN itemType tp ON tp.id = i.typeFk
- JOIN itemCategory ic ON ic.id = tp.categoryFk
- LEFT JOIN tmp.coste c ON c.id = s.id
- WHERE s.created >= vCreatedFrom AND s.created <= vCreatedTo
- AND c.id IS NULL
- AND t.agencyModeFk IS NOT NULL
- AND t.isDeleted IS FALSE
- AND t.warehouseFk = 60
- AND ic.merchandise != FALSE
- GROUP BY s.id;
+* Returns a suitable boxPicking sales list
+*
+* @param vSectorFk Identifier for vn.sector table
+* @param vDated Date for vn.tickets.shipping
+*
+* @return tmp.sale
+*/
+ DECLARE vWarehouseFk INT;
- DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET v_done = TRUE;
+ SELECT warehouseFk INTO vWarehouseFk
+ FROM sector
+ WHERE id = vSectorFk;
- DROP TEMPORARY TABLE IF EXISTS tmp.coste;
+ CALL productionControl(vWarehouseFk, 0);
- DROP TEMPORARY TABLE IF EXISTS tmp.coste;
- CREATE TEMPORARY TABLE tmp.coste
- (PRIMARY KEY (id)) ENGINE = MEMORY
- SELECT s.id
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale
+ (saleFk INT PRIMARY KEY)
+ SELECT
+ s.ticketFk,
+ s.id saleFk,
+ s.itemFk,
+ s.concept,
+ s.quantity,
+ MAKETIME(pb.HH,pb.mm,0) etd,
+ pb.routeFk,
+ FLOOR(s.quantity / IF(i.isBoxPickingMode, ish.packing, i.packingOut)) stickers,
+ IF(i.isBoxPickingMode, ish.packing, i.packingOut) packing,
+ b.packagingFk
FROM sale s
JOIN item i ON i.id = s.itemFk
- JOIN itemType tp ON tp.id = i.typeFk
- JOIN itemCategory ic ON ic.id = tp.categoryFk
- JOIN saleComponent sc ON sc.saleFk = s.id
- JOIN component c ON c.id = sc.componentFk
- JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 6
- WHERE s.created >= vCreatedFrom
- AND ic.merchandise != FALSE;
+ JOIN itemShelving ish ON ish.itemFk = s.itemFk
+ LEFT JOIN ( SELECT iss.itemShelvingFk,
+ s.itemFk,
+ SUM(iss.quantity) reserve
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.isPicked = FALSE
+ AND iss.created >= vDated
+ GROUP BY iss.itemShelvingFk, s.itemFk) tISS
+ ON tISS.itemFk = ish.itemFk AND tISS.itemShelvingFk = ish.id
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk
+ JOIN agencyMode am ON am.id = pb.agencyModeFk
+ LEFT JOIN routesMonitor rm ON rm.routeFk = pb.routeFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk
+ LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN buy b ON b.id = lb.buy_id
+ WHERE IF(i.isBoxPickingMode, ish.packing, i.packingOut)
+ <= LEAST(s.quantity, ish.visible - IFNULL(tISS.reserve,0))
+ AND NOT pb.problem
+ AND sgd.saleFk IS NULL
+ AND p.sectorFk = vSectorFk
+ AND ts.isPreviousPreparable
+ AND ((rm.bufferFk AND rm.isPickingAllowed)
+ OR am.code = 'REC_ALG')
+ AND pb.shipped = vDated
+ GROUP BY s.id
+ ORDER BY etd;
- OPEN vCur;
+ SELECT *
+ FROM tmp.sale
+ WHERE stickers;
- l: LOOP
- SET v_done = FALSE;
- FETCH vCur INTO vSaleFk;
-
- IF v_done THEN
- LEAVE l;
- END IF;
-
- SELECT ticketFk, concept
- INTO vTicketFk, vConcept
- FROM sale
- WHERE id = vSaleFk;
-
- CALL sale_calculateComponent(vSaleFk, 1);
- END LOOP;
-
- CLOSE vCur;
- DROP TEMPORARY TABLE tmp.coste;
-END ;;
+ DROP TEMPORARY TABLE tmp.productionBuffer;
+ DROP TEMPORARY TABLE tmp.sale;
+ END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
@@ -66939,7 +66811,7 @@ DECLARE vIsCollection BOOL;
TRIM(CONCAT(LPAD(s.concept,30,' '), ' ',
RPAD(IFNULL(i.size,''),5,' '))) line1,
'' cel1,
- TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2,
+ TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2,
IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1),
CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)),
CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2,
@@ -66948,20 +66820,22 @@ DECLARE vIsCollection BOOL;
s.isAdded,
IF(c.workerFk IS NULL, getUser(), c.workerFk) workerFk,
IF(SUM(iss.quantity) IS NULL, 0, SUM(iss.quantity)) pickedQuantity,
- i.packingShelve,
MIN(iss.created) picked,
IF(sm.id, TRUE, FALSE) hasMistake,
- sg.sectorFk
+ sg.sectorFk,
+ b.packing,
+ b.grouping,
+ o.code
FROM tmp.ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN ticket tt ON tt.id = t.id
LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk
- LEFT JOIN buy b ON b.id = lb.buy_id
+ LEFT JOIN buy b ON b.id = lb.buy_id
JOIN item i ON i.id = s.itemFk
LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id
LEFT JOIN collection c ON c.id = tc.collectionFk
- LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity
- FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity
+ LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity
+ FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity
FROM tmp.ticket2 t
JOIN sale s ON s.ticketFk = t.id
JOIN saleTracking st ON st.saleFk = s.id
@@ -66973,7 +66847,7 @@ DECLARE vIsCollection BOOL;
LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk
LEFT JOIN origin o ON o.id = i.originFk
- LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
LEFT JOIN parking p ON p.id = sg.parkingFk
LEFT JOIN saleMistake sm ON sm.saleFk = s.id
@@ -67015,19 +66889,19 @@ BEGIN
DECLARE vComponentCount INT;
DECLARE vCursor CURSOR FOR
- SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), date(tt.shipped))
+ SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), DATE(tt.shipped))
FROM tmp.sale_getProblems tt
WHERE DATE(tt.shipped) BETWEEN util.VN_CURDATE()
- AND TIMESTAMPADD(DAY, IF(vIsTodayRelative, 9.9, 1.9), util.VN_CURDATE());
+ AND util.VN_CURDATE() + INTERVAL IF(vIsTodayRelative, 9.9, 1.9) DAY;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DELETE tt.*
FROM tmp.sale_getProblems tt
- JOIN vn.ticketObservation tto ON tto.ticketFk = tt.ticketFk
- JOIN vn.observationType ot ON ot.id = tto.observationTypeFk
- WHERE ot.code = 'administrative'
- AND tto.description = 'Miriam';
+ JOIN ticketObservation tto ON tto.ticketFk = tt.ticketFk
+ JOIN observationType ot ON ot.id = tto.observationTypeFk
+ WHERE ot.code = 'administrative'
+ AND tto.description = 'Miriam';
CREATE OR REPLACE TEMPORARY TABLE tmp.sale_problems (
ticketFk INT(11),
@@ -67049,38 +66923,41 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_list
(PRIMARY KEY (ticketFk))
ENGINE = MEMORY
- SELECT tp.ticketFk, tp.clientFk
- FROM tmp.sale_getProblems tp;
+ SELECT ticketFk, clientFk
+ FROM tmp.sale_getProblems;
SELECT COUNT(*) INTO vComponentCount
- FROM vn.component c
- WHERE c.isRequired;
+ FROM component
+ WHERE isRequired;
-- Too Little
INSERT INTO tmp.sale_problems(ticketFk, isTooLittle)
- SELECT tp.ticketFk, TRUE
+ SELECT tp.ticketFk, TRUE
FROM tmp.sale_getProblems tp
- JOIN vn.ticket t ON t.id = tp.ticketFk
- JOIN (SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat
+ JOIN ticket t ON t.id = tp.ticketFk
+ JOIN (
+ SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat
FROM tmp.ticket_list tl
- JOIN vn.saleVolume sv ON sv.ticketFk = tl.ticketFk
- JOIN vn.ticket t ON t.id = tl.ticketFk
- JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = util.VN_CURDATE()
- JOIN vn.agencyMode am ON am.id = t.agencyModeFk
- JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk
- WHERE util.VN_NOW() < TIMESTAMPADD(MINUTE,MINUTE(zc.`hour`) ,TIMESTAMPADD(HOUR,HOUR(zc.`hour`),util.VN_CURDATE()))
- AND dm.code IN('AGENCY','DELIVERY','PICKUP')
+ JOIN saleVolume sv ON sv.ticketFk = tl.ticketFk
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
+ AND zc.dated = util.VN_CURDATE()
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ WHERE util.VN_NOW() < (util.VN_CURDATE() + INTERVAL HOUR(zc.`hour`) HOUR) + INTERVAL MINUTE(zc.`hour`) MINUTE
+ AND dm.code IN ('AGENCY','DELIVERY','PICKUP')
AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight()
- GROUP BY t.addressFk) sub ON sub.addressFk = t.addressFk
- JOIN vn.volumeConfig vc
+ GROUP BY t.addressFk
+ ) sub ON sub.addressFk = t.addressFk
+ JOIN volumeConfig vc
WHERE sub.litros < vc.minTicketVolume
- AND sub.totalWithoutVat < vc.minTicketValue;
+ AND sub.totalWithoutVat < vc.minTicketValue;
-- Faltan componentes
INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk)
- SELECT sub.ticketFk, sub.hasComponentLack, sub.saleFk
- FROM(
- SELECT tl.ticketFk, (COUNT(DISTINCT s.id) * vComponentCount > COUNT(c.id)) hasComponentLack, s.id saleFk
+ SELECT ticketFk, (vComponentCount > nComp) hasComponentLack, saleFk
+ FROM (
+ SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk
FROM tmp.ticket_list tl
JOIN vn.sale s ON s.ticketFk = tl.ticketFk
LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id
@@ -67088,17 +66965,17 @@ BEGIN
JOIN vn.ticket t ON t.id = tl.ticketFk
JOIN vn.agencyMode am ON am.id = t.agencyModeFk
JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk
- WHERE dm.code IN('AGENCY','DELIVERY','PICKUP')
+ WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP')
AND s.quantity > 0
GROUP BY s.id
- LIMIT 10000000000000000) sub
- WHERE sub.hasComponentLack;
+ ) sub
+ HAVING hasComponentLack;
-- Cliente congelado
INSERT INTO tmp.sale_problems(ticketFk, isFreezed)
SELECT DISTINCT tl.ticketFk, TRUE
FROM tmp.ticket_list tl
- JOIN vn.client c ON c.id = tl.clientFk
+ JOIN client c ON c.id = tl.clientFk
WHERE c.isFreezed
ON DUPLICATE KEY UPDATE isFreezed = c.isFreezed;
@@ -67106,21 +66983,21 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt
(PRIMARY KEY (clientFk))
ENGINE = MEMORY
- SELECT DISTINCT clientFk
- FROM tmp.ticket_list;
+ SELECT DISTINCT clientFk
+ FROM tmp.ticket_list;
CALL client_getDebt(util.VN_CURDATE());
INSERT INTO tmp.sale_problems(ticketFk, risk, hasHighRisk)
SELECT DISTINCT tl.ticketFk, r.risk, ((r.risk - cc.riskTolerance) > c.credit + 10)
FROM tmp.ticket_list tl
- JOIN vn.ticket t ON t.id = tl.ticketFk
- JOIN vn.agencyMode a ON t.agencyModeFk = a.id
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN agencyMode a ON t.agencyModeFk = a.id
JOIN tmp.risk r ON r.clientFk = t.clientFk
- JOIN vn.client c ON c.id = t.clientFk
- JOIN vn.clientConfig cc
+ JOIN client c ON c.id = t.clientFk
+ JOIN clientConfig cc
WHERE r.risk > c.credit + 10
- AND a.isRiskFree = FALSE
+ AND NOT a.isRiskFree
ON DUPLICATE KEY UPDATE
risk = r.risk, hasHighRisk = ((r.risk - cc.riskTolerance) > c.credit + 10);
@@ -67128,13 +67005,25 @@ BEGIN
INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest)
SELECT DISTINCT tl.ticketFk, TRUE
FROM tmp.ticket_list tl
- JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk
+ JOIN ticketRequest tr ON tr.ticketFk = tl.ticketFk
WHERE tr.isOK IS NULL
ON DUPLICATE KEY UPDATE hasTicketRequest = TRUE;
+ CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock_byWarehouse
+ (INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT ish.itemFk itemFk,
+ SUM(ish.visible) visible,
+ s.warehouseFk warehouseFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector s ON s.id = p.sectorFk
+ GROUP BY ish.itemFk,
+ s.warehouseFk;
+
-- Disponible, Faltas, Inventario y Retrasos
OPEN vCursor;
-
l: LOOP
SET vDone = FALSE;
FETCH vCursor INTO vWarehouseFk, vDate;
@@ -67145,90 +67034,104 @@ BEGIN
-- Disponible: no va a haber suficiente producto para preparar todos los pedidos
CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouseFk, vDate);
-
- -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida
+
+ -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida
CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk);
INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
- SELECT tl.ticketFk,
- LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem,
+ SELECT tl.ticketFk,
+ LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem,
s.id AS saleFk
FROM tmp.ticket_list tl
- JOIN vn.ticket t ON t.id = tl.ticketFk
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it on it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache
- LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache
- LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = i.id
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN cache.available av ON av.item_id = i.id
+ AND av.calc_id = vAvailableCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible,0) < s.quantity
AND IFNULL(av.available ,0) < s.quantity
AND IFNULL(issw.visible, 0) < s.quantity
- AND s.isPicked = FALSE
- AND s.reserved = FALSE
- AND ic.merchandise = TRUE
- AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate)
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate)
AND NOT i.generic
AND util.VN_CURDATE() = vDate
AND t.warehouseFk = vWarehouseFk
GROUP BY tl.ticketFk) sub
ON DUPLICATE KEY UPDATE itemShortage = sub.problem, saleFk = sub.saleFk;
-
+
-- Inventario: Visible suficiente, pero ubicado menor a la cantidad vendida
INSERT INTO tmp.sale_problems(ticketFk, itemLost, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
- SELECT tl.ticketFk, LEFT(GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' '),250) problem, s.id AS saleFk
+ SELECT tl.ticketFk,
+ LEFT(GROUP_CONCAT('I: ', i.id, ' ', i.longName, ' '), 250) problem,
+ s.id saleFk
FROM tmp.ticket_list tl
- JOIN vn.ticket t ON t.id = tl.ticketFk
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it on it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache
- LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = s.itemFk
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible,0) >= s.quantity
AND IFNULL(issw.visible, 0) < s.quantity
AND s.quantity > 0
- AND s.isPicked = FALSE
- AND s.reserved = FALSE
- AND ic.merchandise = TRUE
- AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate)
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate)
AND NOT i.generic
AND util.VN_CURDATE() = vDate
AND t.warehouseFk = vWarehouseFk
- GROUP BY tl.ticketFk) sub
+ GROUP BY tl.ticketFk
+ ) sub
ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
-
+
-- Retraso: Disponible suficiente, pero no visible ni ubicado
INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
- SELECT tl.ticketFk, LEFT(GROUP_CONCAT('R: ',i.id, ' ', i.longName, ' '),250) problem, s.id AS saleFk
+ SELECT tl.ticketFk,
+ LEFT(GROUP_CONCAT('R: ', i.id, ' ', i.longName, ' '), 250) problem,
+ s.id saleFk
FROM tmp.ticket_list tl
- JOIN vn.ticket t ON t.id = tl.ticketFk
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it on it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache
- LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache
- LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
- WHERE IFNULL(v.visible,0) < s.quantity
- AND IFNULL(av.available ,0) >= s.quantity
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = s.itemFk
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN cache.available av ON av.item_id = i.id
+ AND av.calc_id = vAvailableCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible, 0) < s.quantity
+ AND IFNULL(av.available, 0) >= s.quantity
AND IFNULL(issw.visible, 0) < s.quantity
AND s.quantity > 0
- AND s.isPicked = FALSE
- AND s.reserved = FALSE
- AND ic.merchandise = TRUE
- AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate)
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate)
AND NOT i.generic
AND util.VN_CURDATE() = vDate
AND t.warehouseFk = vWarehouseFk
- GROUP BY tl.ticketFk) sub
+ GROUP BY tl.ticketFk
+ ) sub
ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
-- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra
@@ -67236,13 +67139,12 @@ BEGIN
INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
- SELECT
- tl.ticketFk,
- s.id saleFk ,
- LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem,
- MOD(s.quantity, b.`grouping`) hasRounding
+ SELECT tl.ticketFk,
+ s.id saleFk ,
+ LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem,
+ MOD(s.quantity, b.`grouping`) hasRounding
FROM tmp.ticket_list tl
- JOIN ticket t ON t.id = tl.ticketFk
+ JOIN ticket t ON t.id = tl.ticketFk
AND t.warehouseFk = vWarehouseFk
JOIN sale s ON s.ticketFk = tl.ticketFk
JOIN item i ON i.id = s.itemFk
@@ -67250,22 +67152,22 @@ BEGIN
JOIN buy b ON b.id = bu.buyFk
GROUP BY tl.ticketFk
HAVING hasRounding
- ) sub
+ ) sub
ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk;
END LOOP;
-
CLOSE vCursor;
-
+
INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked)
SELECT DISTINCT tl.ticketFk, FALSE
FROM tmp.ticket_list tl
- JOIN vn.client c ON c.id = tl.clientFk
- WHERE c.isTaxDataChecked = FALSE
+ JOIN client c ON c.id = tl.clientFk
+ WHERE NOT c.isTaxDataChecked
ON DUPLICATE KEY UPDATE isTaxDataChecked = FALSE;
DROP TEMPORARY TABLE
tmp.clientGetDebt,
- tmp.ticket_list;
+ tmp.ticket_list,
+ tItemShelvingStock_byWarehouse;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -67285,16 +67187,16 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getProblemsByTicket`(IN vTicketFk INT, IN vIsTodayRelative TINYINT(1))
BEGIN
/**
- * Calcula los problemas de cada venta
+ * Calcula los problemas de cada venta
* para un conjunto de tickets.
*
* @return Problems result
*/
DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems;
- CREATE TEMPORARY TABLE tmp.sale_getProblems
+ CREATE TEMPORARY TABLE tmp.sale_getProblems
(INDEX (ticketFk))
ENGINE = MEMORY
- SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped
+ SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped
FROM ticket t
WHERE t.id = vTicketFk;
@@ -67323,7 +67225,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_PriceFix`(vTicketFk INT)
BEGIN
-
+
DELETE sc.*
FROM vn.saleComponent sc
JOIN vn.sale s ON s.id = sc.saleFk
@@ -67347,80 +67249,80 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_recalcComponent` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_recalcComponent`(vOption INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_recalcComponent`(vOption VARCHAR(25))
proc: BEGIN
/**
- * Este procedimiento recalcula los componentes de un conjunto de sales,
+ * Este procedimiento recalcula los componentes de un conjunto de sales,
* eliminando los componentes existentes e insertandolos de nuevo
*
* @param vOption si no se quiere forzar llamar con NULL
* @table tmp.recalculateSales (id)
- */
- DECLARE vShipped DATE;
+ */
+ DECLARE vShipped DATE;
DECLARE vWarehouseFk SMALLINT;
- DECLARE vAgencyModeFk INT;
- DECLARE vAddressFk INT;
- DECLARE vTicketFk INT;
- DECLARE vLanded DATE;
- DECLARE vIsEditable BOOLEAN;
- DECLARE vZoneFk INTEGER;
- DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vAgencyModeFk INT;
+ DECLARE vAddressFk INT;
+ DECLARE vTicketFk INT;
+ DECLARE vLanded DATE;
+ DECLARE vIsEditable BOOLEAN;
+ DECLARE vZoneFk INTEGER;
+ DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vCur CURSOR FOR
SELECT DISTINCT s.ticketFk
FROM tmp.recalculateSales rs
JOIN vn.sale s ON s.id = rs.id;
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vCur;
l: LOOP
SET vDone = FALSE;
- FETCH vCur INTO vTicketFk;
-
+ FETCH vCur INTO vTicketFk;
+
IF vDone THEN
LEAVE l;
END IF;
- SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL,
- t.zoneFk,
- t.warehouseFk,
- t.shipped,
- t.addressFk,
- t.agencyModeFk,
+ SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL,
+ t.zoneFk,
+ t.warehouseFk,
+ t.shipped,
+ t.addressFk,
+ t.agencyModeFk,
t.landed
- INTO vIsEditable,
- vZoneFk,
- vWarehouseFk,
- vShipped,
- vAddressFk,
- vAgencyModeFk,
+ INTO vIsEditable,
+ vZoneFk,
+ vWarehouseFk,
+ vShipped,
+ vAddressFk,
+ vAgencyModeFk,
vLanded
FROM ticket t
- LEFT JOIN ticketState ts ON t.id = ts.ticket
+ LEFT JOIN ticketState ts ON t.id = ts.ticketFk
LEFT JOIN alertLevel al ON al.id = ts.alertLevel
WHERE t.id = vTicketFk;
CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE);
-
+
IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN
CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk));
END IF;
IF vLanded IS NULL OR vZoneFk IS NULL THEN
-
+
UPDATE ticket t
- SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1)
+ SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1)
WHERE t.id = vTicketFk AND t.landed IS NULL;
IF vZoneFk IS NULL THEN
@@ -67429,14 +67331,14 @@ proc: BEGIN
SET t.zoneFk = vZoneFk
WHERE t.id = vTicketFk AND t.zoneFk IS NULL;
END IF;
-
+
END IF;
-
+
DROP TEMPORARY TABLE tmp.zoneGetLanded;
- -- rellena la tabla buyUltimate con la ultima compra
- CALL buyUltimate (vWarehouseFk, vShipped);
-
+ -- rellena la tabla buyUltimate con la ultima compra
+ CALL buyUltimate (vWarehouseFk, vShipped);
+
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (saleFk)) ENGINE = MEMORY
SELECT s.id saleFk, vWarehouseFk warehouseFk
@@ -67444,7 +67346,7 @@ proc: BEGIN
JOIN tmp.recalculateSales rs ON s.id = rs.id
WHERE s.ticketFk = vTicketFk;
- CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot
SELECT vWarehouseFk warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk
FROM sale s
JOIN tmp.recalculateSales rs ON s.id = rs.id
@@ -67456,17 +67358,17 @@ proc: BEGIN
CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
IF vOption IS NULL THEN
- SET vOption = IF(vIsEditable, 1, 6);
- END IF;
+ SET vOption = IF(vIsEditable, 'renewPrices', 'imbalance');
+ END IF;
CALL ticketComponentUpdateSale(vOption);
- CALL catalog_componentPurge();
+ CALL catalog_componentPurge();
DROP TEMPORARY TABLE tmp.buyUltimate;
- DROP TEMPORARY TABLE tmp.sale;
+ DROP TEMPORARY TABLE tmp.sale;
END LOOP;
- CLOSE vCur;
+ CLOSE vCur;
END ;;
DELIMITER ;
@@ -67475,6 +67377,149 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `sale_replaceItem` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_general_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_replaceItem`(vSaleFk INT, vNewItemFk INT, vQuantity INT)
+BEGIN
+/**
+ * Añade un nuevo articulo para sustituir a otro, y actualiza la memoria de sustituciones.
+ *
+ * @param vSaleFk id de la tabla sale
+ * @param vNewItemFk articulo sustituto
+ * @param vQuantity cantidad que se va a sustituir
+ */
+ DECLARE vTicketFk INT;
+ DECLARE vItemFk INT;
+ DECLARE vWarehouseFk SMALLINT;
+ DECLARE vDate DATE;
+ DECLARE vGrouping INT;
+ DECLARE vGroupingModeFk INT;
+ DECLARE vPacking INT;
+ DECLARE vRoundQuantity INT DEFAULT 1;
+ DECLARE vLanded DATE;
+ DECLARE vAddressFk INT;
+ DECLARE vAgencyModeFk INT;
+ DECLARE vNewPrice DECIMAL(10,2);
+ DECLARE vOldPrice DECIMAL(10,2);
+ DECLARE vOption VARCHAR(255);
+ DECLARE vNewSaleFk INT;
+ DECLARE vForceToGrouping INT DEFAULT 1;
+ DECLARE vForceToPacking INT DEFAULT 2;
+ DECLARE vFinalPrice DECIMAL(10,2);
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ SELECT s.ticketFk,
+ LEAST(s.quantity, vQuantity),
+ s.itemFk,
+ t.shipped,
+ t.warehouseFk,
+ t.landed,
+ t.addressFk,
+ t.agencyModeFk,
+ s.price
+ INTO vTicketFk,
+ vQuantity,
+ vItemFk,
+ vDate,
+ vWarehouseFk,
+ vLanded,
+ vAddressFk,
+ vAgencyModeFk,
+ vOldPrice
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE s.id = vSaleFk;
+
+ CALL buyUltimate(vWarehouseFk, vDate);
+
+ SELECT `grouping`, groupingMode, packing
+ INTO vGrouping,vGroupingModeFk,vPacking
+ FROM buy b
+ JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk
+ WHERE tmp.itemFk = vNewItemFk AND tmp.WarehouseFk = vWarehouseFk;
+
+ IF vGroupingModeFk = vForceToPacking AND vPacking > 0 THEN
+ SET vRoundQuantity = vPacking;
+ END IF;
+ IF vGroupingModeFk = vForceToGrouping AND vGrouping > 0 THEN
+ SET vRoundQuantity = vGrouping;
+ END IF;
+
+ CALL catalog_calcFromItem(
+ vLanded,
+ vAddressFk,
+ vAgencyModeFk,
+ vNewItemFk);
+
+ SELECT price INTO vNewPrice
+ FROM tmp.ticketCalculateItem;
+
+ IF vNewPrice IS NULL THEN
+ CALL util.throw('price retrieval failed');
+ END IF;
+
+ IF vNewPrice > vOldPrice THEN
+ SET vFinalPrice = vOldPrice;
+ SET vOption = 'substitution';
+ ELSE
+ SET vFinalPrice = vNewPrice;
+ SET vOption = 'renewPrices';
+ END IF;
+
+ START TRANSACTION;
+
+ UPDATE sale
+ SET quantity = quantity - vQuantity
+ WHERE id = vSaleFk;
+
+ INSERT INTO vn.sale(ticketFk,
+ itemFk,
+ quantity,
+ concept,
+ price)
+ SELECT vTicketFk,
+ vNewItemFk,
+ CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ',i.longName),
+ vFinalPrice
+ FROM vn.item i
+ WHERE id = vNewItemFk;
+
+ SELECT LAST_INSERT_ID() INTO vNewSaleFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.sale;
+ CREATE TEMPORARY TABLE tmp.sale
+ (PRIMARY KEY (saleFk))
+ ENGINE = MEMORY
+ SELECT id saleFk, vWarehouseFk warehouseFk
+ FROM sale s WHERE id = vNewSaleFk;
+
+ CALL ticketComponentUpdateSale(vOption);
+ CALL catalog_componentPurge();
+
+ INSERT INTO itemProposal(itemFk, mateFk, counter)
+ VALUES(vItemFk, vNewItemFk, 1)
+ ON DUPLICATE KEY UPDATE counter = counter + 1;
+
+ COMMIT;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sectorCollectionSaleGroup_add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
@@ -67487,22 +67532,41 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollectionSaleGroup_add`(vSaleGroupFk INT, vSectorCollectionFk INT)
BEGIN
/**
- * Inserta un nuevo registro en vn.sectorCollectionSaleGroup
+ * Inserta un nuevo registro en vn.sectorCollectionSaleGroup
* Actualiza el usuario en vn.saleGroup y reemplaza los registros de vn.saleTracking
- *
+ *
* @param vSaleGroupFk Identificador de vn.saleGroup
* @param vSectorCollectionFk Identificador de vn.sectorCollection
*/
- REPLACE sectorCollectionSaleGroup
- SET sectorCollectionFk = vSectorCollectionFk,
- saleGroupFk = vSaleGroupFk;
+ DECLARE vHasSaleGroup INT;
+ DECLARE vHasSectorCollection INT;
+ SELECT COUNT(id) INTO vHasSaleGroup
+ FROM saleGroup
+ WHERE id = vSaleGroupFk;
+
+ IF !vHasSaleGroup THEN
+ CALL util.throw ("invalid saleGroup");
+ END IF;
+
+ SELECT COUNT(id) INTO vHasSectorCollection
+ FROM sectorCollection
+ WHERE id = vSectorCollectionFk;
+
+ IF !vHasSectorCollection THEN
+ CALL util.throw ("invalid sectorCollection");
+ END IF;
+
+ REPLACE sectorCollectionSaleGroup
+ SET sectorCollectionFk = vSectorCollectionFk,
+ saleGroupFk = vSaleGroupFk;
+
UPDATE saleGroup sg
JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
- SET sg.userFk = sc.userFk
+ SET sg.userFk = sc.userFk
WHERE sg.id = vSaleGroupFk;
-
+
INSERT IGNORE saleTracking(
saleFk,
isChecked,
@@ -67514,8 +67578,8 @@ BEGIN
sc.userFk,
s.id
FROM saleGroupDetail sgd
- JOIN sectorCollectionSaleGroup scsg
- ON scsg.saleGroupFk = sgd.saleGroupFk
+ JOIN sectorCollectionSaleGroup scsg
+ ON scsg.saleGroupFk = sgd.saleGroupFk
JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
JOIN state s ON s.code = 'PREVIOUS_PREPARATION'
WHERE sgd.saleGroupFk = vSaleGroupFk;
@@ -67616,30 +67680,30 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT)
-BEGIN
-/**
- * Inserta una nueva colección, si el usuario no tiene ninguna vacia.
- * Esto se hace para evitar que por error se generen colecciones sin sentido.
- *
- * @param vSectorFk Identificador de #vn.sector
- */
- DECLARE hasEmptyCollections BOOL;
- DECLARE vUserFk INT;
-
- SET vUserFk = account.myUser_getId();
-
- SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections
- FROM vn.sectorCollection sc
- LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
- WHERE ISNULL(scsg.id)
- AND sc.userFk = vUserFk
- AND sc.sectorFk = vSectorFk
- AND sc.created >= util.VN_CURDATE();
-
- IF NOT hasEmptyCollections THEN
- INSERT INTO vn.sectorCollection(userFk, sectorFk)
- VALUES(vUserFk, vSectorFk);
- END IF;
+BEGIN
+/**
+ * Inserta una nueva colección, si el usuario no tiene ninguna vacia.
+ * Esto se hace para evitar que por error se generen colecciones sin sentido.
+ *
+ * @param vSectorFk Identificador de #vn.sector
+ */
+ DECLARE hasEmptyCollections BOOL;
+ DECLARE vUserFk INT;
+
+ SET vUserFk = account.myUser_getId();
+
+ SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections
+ FROM vn.sectorCollection sc
+ LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
+ WHERE ISNULL(scsg.id)
+ AND sc.userFk = vUserFk
+ AND sc.sectorFk = vSectorFk
+ AND sc.created >= util.VN_CURDATE();
+
+ IF NOT hasEmptyCollections THEN
+ INSERT INTO vn.sectorCollection(userFk, sectorFk)
+ VALUES(vUserFk, vSectorFk);
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -67683,7 +67747,7 @@ BEGIN
CREATE TEMPORARY TABLE tmp.previousErrors -- Errores de previa, derivadores de los revisadores (por reclamación)
ENGINE = MEMORY
- SELECT tt.workerFk, COUNT(c.ticketFk) errorsByClaim
+ SELECT tt.userFk, COUNT(c.ticketFk) errorsByClaim
FROM claimDevelopment cd
JOIN claim c ON cd.claimFk = c.id
JOIN ticket t ON c.ticketFk = t.id
@@ -67691,7 +67755,7 @@ BEGIN
JOIN ticketTracking tt ON tt.ticketFk = t.id
JOIN `state` s ON s.id = tt.stateFk
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = 'Revisadores' AND s.code = 'OK PREVIOUS'
- GROUP BY workerFk;
+ GROUP BY tt.userFk;
DELETE FROM sectorProductivity
WHERE dated = vDatedFrom
@@ -67719,7 +67783,7 @@ BEGIN
LEFT JOIN bs.workerProductivity wp ON wp.workerFk = w.id
LEFT JOIN `state` s2 ON s2.id = wp.stateFk AND s2.code = 'OK PREVIOUS'
LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = w.id
- LEFT JOIN tmp.previousErrors pe ON pe.workerFk = w.id
+ LEFT JOIN tmp.previousErrors pe ON pe.userFk = w.id
WHERE DATE(sc.created) = vDatedFrom
AND wp.dated = vDatedFrom
GROUP BY w.id;
@@ -67735,32 +67799,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `sector_get` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `sector_get`()
-BEGIN
-
-/**
- * Obtiene los sectores
-*/
-
- SELECT s.id,s.description,s.warehouseFk
- FROM vn.sector s;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sector_getWarehouse` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -67775,7 +67813,7 @@ BEGIN
SELECT s.warehouseFk
FROM vn.sector s
WHERE s.id = vSectorFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -67870,10 +67908,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingChange`(IN `vShelvingO` VAR
BEGIN
UPDATE vn.itemShelving
- SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci
- WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci;
-
-
+ SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci
+ WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci;
+
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -67892,16 +67930,16 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingLog_get`(shelvingFk VARCHAR(10))
BEGIN
-
+
/* Lista el log de un carro
- *
+ *
* @param shelvingFk matrícula del carro
- *
+ *
*/
-
+
SELECT originFk, name, creationDate, description
FROM shelvingLog sl
- JOIN account.user u ON u.id = sl.userFk
+ JOIN account.user u ON u.id = sl.userFk
WHERE sl.originFk = shelvingFk COLLATE utf8_general_ci
ORDER BY creationDate DESC;
@@ -67924,22 +67962,22 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT)
BEGIN
-
-SELECT s.itemFk,
+
+SELECT s.itemFk,
s.concept,
- CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir,
- CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado
+ CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir,
+ CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado
FROM vn.sale s
LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id
JOIN vn.ticket t ON t.id = s.ticketFk
LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci
- WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE()))
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE()))
AND iss.saleFk IS NULL
AND t.warehouseFk = vWarehouseFk
GROUP BY s.itemFk
HAVING sinServir > aparcado;
-
+
END ;;
DELIMITER ;
@@ -67981,30 +68019,36 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelving_clean`()
BEGIN
- DELETE FROM vn.shelving
+ DELETE FROM shelving
WHERE length(code) > 3
AND parked < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
-
- DELETE FROM vn.itemShelving
+
+ DELETE FROM itemShelving
WHERE visible <= 0
AND created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE());
- DELETE ish.*
- FROM vn.itemShelving ish
+ DELETE ish.*
+ FROM itemShelving ish
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
WHERE sh.parkingFk IS NULL
AND ish.created < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
- UPDATE vn.shelving sh
- LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code`
+UPDATE shelving sh
+ LEFT JOIN itemShelving its ON its.shelvingFk = sh.`code`
SET isPrinted = 0,
- parkingFk = NULL
- WHERE its.id IS NULL
- AND sh.isRecyclable
- AND ( sh.parked IS NULL
- OR
- sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())
- );
+ parkingFk = NULL
+ WHERE its.id IS NULL
+ AND sh.isRecyclable
+ AND (
+ sh.parked IS NULL
+ OR
+ sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())
+ )
+ AND IF(code REGEXP '^[A-Za-z]{2}[0-9]', LEFT (code, 2) NOT IN (
+ SELECT DISTINCT LEFT(its.shelvingFk, 2)
+ FROM itemShelving its
+ WHERE its.shelvingFk REGEXP '^[A-Za-z]{2}[0-9]'
+ ), TRUE);
END ;;
DELIMITER ;
@@ -68057,26 +68101,26 @@ BEGIN
) fue ON fue.itemFk = i.id
LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk
LEFT JOIN (
- SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta
- FROM vn2008.item_out
- WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
- AND warehouse_id = vWarehouseFk
- GROUP BY item_id
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta
+ FROM itemTicketOut
+ WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
+ AND warehouseFk = vWarehouseFk
+ GROUP BY itemFk
) sale ON sale.item_id = i.id
LEFT JOIN (
- SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra
- FROM vn2008.item_entry_in
- WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
- AND warehouse_id = vWarehouseFk
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra
+ FROM itemEntryIn
+ WHERE landed BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
+ AND warehouseInFk = vWarehouseFk
AND isVirtualStock = FALSE
- GROUP BY item_id
+ GROUP BY itemFk
) buy ON buy.item_id = i.id
LEFT JOIN (
- SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado
- FROM vn2008.item_entry_out
- WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
- AND warehouse_id = vWarehouseFk
- GROUP BY item_id
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado
+ FROM itemEntryOut
+ WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
+ AND warehouseOutFk = vWarehouseFk
+ GROUP BY itemFk
) mov ON mov.item_id = i.id
WHERE v.amount;
@@ -68179,20 +68223,20 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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
+ 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
LIMIT 10000000000000000000) t1 GROUP BY Id_Cliente;
-
+
CALL vn2008.risk_vs_client_list(util.VN_CURDATE());
-
- SELECT
+
+ 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
@@ -68202,7 +68246,7 @@ BEGIN
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 ;;
@@ -68212,58 +68256,86 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorker` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `stockBuyedByWorker`(
- vDate DATE,
- vWorker INT)
+ vDated DATE,
+ vWorker INT
+)
BEGIN
/**
- * Calculates the space reserved by buyers of the same container
+ * Inserta el volumen de compra de un comprador
+ * en stockBuyed de acuerdo con la fecha.
*
- * @param vdate date of container delivery
- * @param vWorker buyer reserving space in the container
+ * @param vDated Fecha de compra
+ * @param vWorker Id de trabajador
*/
- DECLARE vVolume DECIMAL(10, 2);
- DECLARE vWarehouseFk INT;
- DECLARE vCompressionRatio DECIMAL(1, 1);
+ CREATE OR REPLACE TEMPORARY TABLE tStockBuyed
+ (INDEX (userFk))
+ ENGINE = MEMORY
+ SELECT requested, reserved, userFk
+ FROM stockBuyed
+ WHERE dated = vDated
+ AND userFk = vWorker;
- CALL stockTraslation(vDate);
+ DELETE FROM stockBuyed
+ WHERE dated = vDated
+ AND userFk = vWorker;
- SELECT warehouseFk, conversionCoefficient INTO vWarehouseFk, vCompressionRatio
- FROM auctionConfig;
+ CALL stockTraslation(vDated);
- SELECT volume INTO vVolume
- FROM vn.packaging WHERE id = 'cc';
+ INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description)
+ SELECT it.workerFk,
+ SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000,
+ vDated,
+ sb.reserved,
+ sb.requested,
+ u.name
+ FROM itemType it
+ JOIN item i ON i.typeFk = it.id
+ LEFT JOIN tmp.item ti ON ti.itemFk = i.id
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ JOIN warehouse wh ON wh.code = 'VNH'
+ JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
+ AND bu.warehouseFk = wh.id
+ JOIN buy b ON b.id = bu.buyFk
+ JOIN volumeConfig vc
+ JOIN account.`user` u ON u.id = it.workerFk
+ LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk
+ WHERE ic.display
+ AND it.workerFk = vWorker;
SELECT b.entryFk Id_Entrada,
i.id Id_Article,
i.name Article,
- ti.amount Cantidad,
- (vCompressionRatio * (ti.amount / b.packing) * vn.buy_getVolume(b.id))
- / vVolume buyed,
- b.packageFk id_cubo,
+ ti.quantity Cantidad,
+ (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id))
+ / (vc.trolleyM3 * 1000000) buyed,
+ b.packagingFk id_cubo,
b.packing
FROM tmp.item ti
- JOIN item i ON i.id = ti.item_id
+ JOIN item i ON i.id = ti.itemFk
JOIN itemType it ON i.typeFk = it.id
JOIN itemCategory ic ON ic.id = it.categoryFk
JOIN worker w ON w.id = it.workerFk
+ JOIN auctionConfig ac
JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
- AND bu.warehouseFk = vWarehouseFk
+ AND bu.warehouseFk = ac.warehouseFk
JOIN buy b ON b.id = bu.buyFk
- WHERE ic.display AND w.id = vWorker;
+ JOIN volumeConfig vc
+ WHERE ic.display
+ AND w.id = vWorker;
- DROP TEMPORARY TABLE
- tmp.buyUltimate,
- tmp.item;
+ DROP TEMPORARY TABLE tmp.buyUltimate,
+ tmp.item,
+ tStockBuyed;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68280,51 +68352,59 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `stockBuyed_add`(vDated DATE)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `stockBuyed_add`(
+ vDated DATE
+)
BEGIN
/**
- * Inserta el volumen de compra por comprador en stockBuyed de acuerdo con la fecha
+ * Inserta el volumen de compra por comprador
+ * en stockBuyed de acuerdo con la fecha.
*
* @param vDated Fecha de compra
*/
-
- CREATE OR REPLACE TEMPORARY TABLE tStockBuyed
+ CREATE OR REPLACE TEMPORARY TABLE tStockBuyed
(INDEX (userFk))
ENGINE = MEMORY
SELECT requested, reserved, userFk
FROM stockBuyed
WHERE dated = vDated;
+ DELETE FROM stockBuyed WHERE dated = vDated;
+
CALL stockTraslation(vDated);
INSERT INTO stockBuyed(userFk, buyed, `dated`, description)
- SELECT it.workerFk,
- SUM(( ti.amount / b.packing ) * buy_getVolume(b.id)) / vc.palletM3 / 1000000 buyed,
+ SELECT it.workerFk,
+ SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000,
vDated,
u.name
- FROM tmp.item ti
- JOIN item i ON i.id = ti.item_id
- JOIN itemType it ON it.id = i.typeFk
+ FROM itemType it
+ JOIN item i ON i.typeFk = it.id
+ LEFT JOIN tmp.item ti ON ti.itemFk = i.id
JOIN itemCategory ic ON ic.id = it.categoryFk
JOIN warehouse wh ON wh.code = 'VNH'
JOIN tmp.buyUltimate bu ON bu.itemFk = i.id AND bu.warehouseFk = wh.id
JOIN buy b ON b.id = bu.buyFk
JOIN volumeConfig vc
JOIN account.`user` u ON u.id = it.workerFk
- WHERE ic.display <> 0
+ JOIN workerDepartment wd ON wd.workerFk = u.id
+ JOIN department d ON d.id = wd.departmentFk
+ WHERE ic.display
+ AND d.code IN ('shopping', 'logistic', 'franceTeam')
GROUP BY it.workerFk;
INSERT INTO stockBuyed(buyed, dated, description)
- SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000),
+ SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000),
vDated,
- IF(c.country = 'España',p.name,c.country) destiny
+ IF(c.code = 'ES', p.name, c.country) destiny
FROM itemTicketOut ito
JOIN ticket t ON t.id = ito.ticketFk
JOIN `address` a ON a.id = t.addressFk
JOIN province p ON p.id = a.provinceFk
JOIN country c ON c.id = p.countryFk
JOIN warehouse wh ON wh.id = t.warehouseFk
- JOIN itemCost ic ON ic.itemFk = ito.itemFk AND ic.warehouseFk = t.warehouseFk
+ JOIN itemCost ic ON ic.itemFk = ito.itemFk
+ AND ic.warehouseFk = t.warehouseFk
JOIN volumeConfig vc
WHERE ito.shipped BETWEEN vDated AND util.dayend(vDated)
AND wh.code = 'VNH'
@@ -68336,8 +68416,7 @@ BEGIN
s.reserved = ts.reserved
WHERE s.dated = vDated;
- DROP TEMPORARY TABLE
- tmp.buyUltimate,
+ DROP TEMPORARY TABLE tmp.buyUltimate,
tmp.item,
tStockBuyed;
END ;;
@@ -68356,44 +68435,44 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `stockTraslation`(vDate DATE)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `stockTraslation`(
+ vDated DATE
+)
BEGIN
/**
- * Calcula el stock del almacén de subasta desde FechaInventario hasta vDate
- * sin tener en cuenta las salidas del mismo dia vDate
+ * Calcula el stock del almacén de subasta desde FechaInventario hasta vDated
+ * sin tener en cuenta las salidas del mismo dia vDated
* para ver el transporte a reservar
- * @param vDate Fecha hasta la cual calcula el stock
+ *
+ * @param vDated Fecha hasta la cual calcula el stock
+ * @return tmp.item
*/
DECLARE vAuctionWarehouseFk INT;
- DELETE FROM stockBuyed WHERE dated = vDate;
-
SELECT warehouseFk INTO vAuctionWarehouseFk
FROM auctionConfig;
- DROP TEMPORARY TABLE IF EXISTS tmp.item;
- CREATE TEMPORARY TABLE tmp.item
- (UNIQUE INDEX i USING HASH (item_id))
+ CREATE OR REPLACE TEMPORARY TABLE tmp.item
+ (UNIQUE INDEX i USING HASH (itemFk))
ENGINE = MEMORY
- SELECT item_id, SUM(amount) amount
- FROM vn2008.item_entry_in
- WHERE dat = vDate
- AND vDate >= util.VN_CURDATE()
- AND warehouse_id = vAuctionWarehouseFk
- AND isVirtualStock is FALSE
- GROUP BY item_id
- HAVING amount != 0;
+ SELECT itemFk, SUM(quantity) quantity
+ FROM itemEntryIn
+ WHERE landed = vDated
+ AND vDated >= util.VN_CURDATE()
+ AND warehouseInFk = vAuctionWarehouseFk
+ AND NOT isVirtualStock
+ GROUP BY itemFk
+ HAVING quantity;
- CALL `cache`.stock_refresh (FALSE);
+ CALL `cache`.stock_refresh(FALSE);
- INSERT INTO tmp.item (item_id,amount)
- SELECT item_id,s.amount
- FROM `cache`.stock s
+ INSERT INTO tmp.item (itemFk, quantity)
+ SELECT item_id, amount
+ FROM `cache`.stock
WHERE warehouse_id = vAuctionWarehouseFk
- ON DUPLICATE KEY UPDATE amount = tmp.item.amount + VALUES(amount);
-
- CALL buyUltimate(vAuctionWarehouseFk, vDate);
+ ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity);
+ CALL buyUltimate(vAuctionWarehouseFk, vDated);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68417,10 +68496,10 @@ BEGIN
DECLARE vBossId INT;
DECLARE vDone BOOL;
DECLARE workerCur CURSOR FOR
- SELECT workerFk
- FROM tmp.subordinate
+ SELECT workerFk
+ FROM tmp.subordinate
WHERE NOT isChecked;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR 1062 BEGIN
@@ -68428,29 +68507,29 @@ BEGIN
END;
DROP TEMPORARY TABLE IF EXISTS tmp.subordinate;
-
+
CREATE TEMPORARY TABLE tmp.subordinate
(PRIMARY KEY (workerFk))
ENGINE = MEMORY
SELECT vBossFk AS workerFk, 0 AS isChecked;
-
+
WHILE (SELECT COUNT(*) FROM tmp.subordinate WHERE NOT isChecked) > 0 DO
OPEN workerCur;
workerLoop: LOOP
SET vDone = FALSE;
FETCH workerCur INTO vBossId;
-
+
IF vDone THEN
LEAVE workerLoop;
END IF;
-
- INSERT INTO tmp.subordinate
- SELECT id, 0
- FROM worker
+
+ INSERT INTO tmp.subordinate
+ SELECT id, 0
+ FROM worker
WHERE bossFk = vBossId;
-
- UPDATE tmp.subordinate
+
+ UPDATE tmp.subordinate
SET isChecked = 1
WHERE workerFk = vBossId;
END LOOP;
@@ -68490,13 +68569,13 @@ BEGIN
-- Calcula el balance inicial y final de cada proveedor
INSERT INTO openingBalance
SELECT MAX(dueDated),
- supplierFk,
- companyFk,
+ supplierFk,
+ companyFk,
sum(amount) eurAmount,
sum(divisa) foreignAmount
FROM (
SELECT p.dueDated,
- p.supplierFk,
+ p.supplierFk,
p.companyFk,
p.amount,
p.divisa
@@ -68512,7 +68591,7 @@ BEGIN
SELECT iidd.dueDated,
ii.supplierFk,
ii.companyFk,
- - iidd.amount,
+ - iidd.amount,
- iidd.foreignValue
FROM invoiceIn ii
JOIN invoiceInDueDay iidd ON ii.id = iidd.invoiceInFk
@@ -68520,14 +68599,14 @@ BEGIN
JOIN company co ON co.id = ii.companyFk
WHERE iidd.dueDated > '2014-12-31'
AND iidd.dueDated <= vEnded
- AND ii.isBooked AND co.`code` = 'VNL'
+ AND ii.isBooked AND co.`code` = 'VNL'
AND c.`code` <> 'EUR'
UNION ALL
SELECT se.dueDated,
se.supplierFk,
se.companyFk,
- - se.amount,
+ - se.amount,
0
FROM supplierExpense se
JOIN currency c ON c.id = se.currencyFk
@@ -68537,7 +68616,7 @@ BEGIN
AND co.`code` = 'VNL' AND c.`code` <> 'EUR'
) sub
GROUP BY companyFk, supplierFk;
-
+
SELECT ob.dueDated
, ob.supplierFk
, ob.companyFk
@@ -68565,7 +68644,10 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `supplierPackaging_ReportSource`(vFromDated DATE, vSupplierFk INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `supplierPackaging_ReportSource`(
+ vFromDated DATE,
+ vSupplierFk INT
+)
BEGIN
/**
* Selecciona los embalajes de un proveedor a partir de una fecha
@@ -68573,15 +68655,26 @@ BEGIN
* @param vFromDated Fecha de la que partir
* @param vSupplierFk Id del proveedor
*/
- DECLARE vCounter INT DEFAULT 0;
- DECLARE vMaxRow INT DEFAULT 0;
- DECLARE vItemFk INT DEFAULT 0;
SET @vBalance = 0;
+ SET @vItemFk = NULL;
- CREATE OR REPLACE TEMPORARY TABLE tSupplierPackagingList
- SELECT ROW_NUMBER() OVER(ORDER BY landed) `row`,
+ CREATE OR REPLACE TEMPORARY TABLE tSupplierPackaging
+ SELECT supplierFk,
itemFk,
- entryFk
+ longName,
+ supplier,
+ entryFk,
+ landed,
+ `in`,
+ `out`,
+ warehouse,
+ buyingValue,
+ IF (
+ NOT (@vItemFk <=> sub.itemFk),
+ @vBalance := (`in` - `out`),
+ @vBalance := (`in` - `out` + @vBalance)
+ ) balance,
+ @vItemFk := sub.itemFk previousItemFk
FROM (
SELECT supplierFk,
itemFk,
@@ -68589,8 +68682,8 @@ BEGIN
supplier,
entryFk,
landed,
- `out`,
`in`,
+ `out`,
warehouse,
buyingValue
FROM supplierPackaging
@@ -68603,103 +68696,33 @@ BEGIN
supplier,
'previous',
vFromDated,
- SUM(`out`),
SUM(`in`),
+ SUM(`out`),
NULL,
buyingValue
FROM supplierPackaging
WHERE supplierFk = vSupplierFk
AND landed < vFromDated
GROUP BY itemFk
- ) sub
- GROUP BY itemFk
- HAVING entryFk <> 'previous'
- ORDER BY landed;
+ ORDER BY itemFk, landed, entryFk
+ ) sub
+ WHERE `out` OR `in`;
- SELECT MAX(`row`) INTO vMaxRow
- FROM tSupplierPackagingList;
-
- CREATE OR REPLACE TEMPORARY TABLE tSupplierPackaging(
- supplierFk INT,
- itemFk INT,
- longName VARCHAR(50),
- supplier VARCHAR(50),
- entryFk VARCHAR(50),
- landed DATE,
- `in` VARCHAR(50),
- `out` VARCHAR(50),
- warehouse INT,
- buyingValue INT,
- balance INT
- );
-
- l1: LOOP
- SET @vBalance = 0;
- IF vCounter = vMaxRow THEN
- LEAVE l1;
- ELSE
- SET vCounter = vCounter + 1;
- END IF;
-
- SELECT itemFk INTO vItemFk
- FROM tSupplierPackagingList
- WHERE `row` = vCounter;
-
- INSERT INTO tSupplierPackaging
- SELECT supplierFk,
- itemFk,
- longName,
- supplier,
- entryFk,
- landed,
- `in`,
- `out`,
- warehouse,
- buyingValue,
- @vBalance:= (`in` - `out` + @vBalance)
- FROM (
- SELECT supplierFk,
- itemFk,
- longName,
- supplier,
- entryFk,
- landed,
- `out`,
- `in`,
- warehouse,
- buyingValue
- FROM supplierPackaging
- WHERE supplierFk = vSupplierFk
- AND landed >= vFromDated
- AND itemFk = vItemFk
- UNION ALL
- SELECT vSupplierFk,
- itemFk,
- longName,
- supplier,
- 'previous',
- vFromDated,
- SUM(`out`),
- SUM(`in`),
- NULL,
- buyingValue
- FROM supplierPackaging
- WHERE supplierFk = vSupplierFk
- AND landed < vFromDated
- AND itemFk = vItemFk
- GROUP BY itemFk
- ORDER BY landed
- ) sub
- WHERE `out` OR `in`;
- END LOOP l1;
-
- SELECT *
+ SELECT supplierFk,
+ itemFk,
+ longName,
+ supplier,
+ entryFk,
+ landed,
+ `in`,
+ `out`,
+ warehouse,
+ buyingValue,
+ balance
FROM tSupplierPackaging
- ORDER BY itemFk, landed;
+ WHERE NOT (NOT balance AND landed < CURDATE() - INTERVAL 1 YEAR);
- DROP TEMPORARY TABLE IF EXISTS
- tSupplierPackaging,
- tSupplierPackagingList;
+ DROP TEMPORARY TABLE tSupplierPackaging;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68751,7 +68774,7 @@ BEGIN
- SUM(iid.amount) mysql,
0 sage
FROM invoiceInDueDay iid
- JOIN invoiceIn ii ON ii.id = iid.invoiceInFk
+ JOIN invoiceIn ii ON ii.id = iid.invoiceInFk
WHERE IFNULL(ii.bookEntried, ii.issued) BETWEEN vDateFrom AND vDateTo
AND ii.isBooked
GROUP BY ii.id
@@ -68777,7 +68800,7 @@ BEGIN
SELECT lc.companyFk,
s.id,
0,
- - (NZ(lc.debit) - NZ(lc.credit))
+ - (IFNULL(lc.debit, 0) - IFNULL(lc.credit, 0))
FROM tmp.ledgerComparative lc
JOIN supplier s ON s.account = lc.account
WHERE lc.`date` BETWEEN vDateFrom AND vDateTo
@@ -68844,9 +68867,11 @@ BEGIN
UPDATE vn.supplier s
JOIN ( SELECT p.supplierFk
- FROM vn.payment p
- LEFT JOIN vn.supplier s ON s.id = p.supplierFk
- LEFT JOIN vn.payMethod pm ON pm.id = s.payMethodFk
+ FROM supplier s
+ JOIN payMethod pm ON pm.id = s.payMethodFk
+ JOIN (SELECT supplierFk,MAX(created) created
+ FROM payment
+ GROUP BY supplierFk) p ON p.supplierFk = s.id
WHERE p.created < (util.VN_CURDATE() - INTERVAL pm.graceMonthsDisableChecked MONTH)
AND pm.graceMonthsDisableChecked
AND s.isPayMethodChecked
@@ -68861,7 +68886,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `test` */;
+/*!50003 DROP PROCEDURE IF EXISTS `supplier_statement` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@@ -68869,9 +68894,142 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `test`()
+CREATE DEFINER=`root`@`localhost` PROCEDURE `supplier_statement`(
+ vSupplierFk INT,
+ vCurrencyFk INT,
+ vCompanyFk INT,
+ vOrderBy VARCHAR(15),
+ vIsConciliated BOOL
+)
BEGIN
-select 'procedimiento ejecutado con éxito';
+/**
+ * Crea un estado de cuenta de proveedores calculando
+ * los saldos en euros y en la moneda especificada.
+ *
+ * @param vSupplierFk Id del proveedor
+ * @param vCurrencyFk Id de la moneda
+ * @param vCompanyFk Id de la empresa
+ * @param vOrderBy Criterio de ordenación
+ * @param vIsConciliated Indica si está conciliado o no
+ * @return tmp.supplierStatement
+ */
+ SET @euroBalance:= 0;
+ SET @currencyBalance:= 0;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement
+ ENGINE = MEMORY
+ SELECT *,
+ @euroBalance:= ROUND(
+ @euroBalance + IFNULL(paymentEuros, 0) -
+ IFNULL(invoiceEuros, 0), 2
+ ) euroBalance,
+ @currencyBalance:= ROUND(
+ @currencyBalance + IFNULL(paymentCurrency, 0) -
+ IFNULL(invoiceCurrency, 0), 2
+ ) currencyBalance
+ FROM (
+ SELECT * FROM
+ (
+ SELECT NULL bankFk,
+ ii.companyFk,
+ ii.serial,
+ ii.id,
+ CASE
+ WHEN vOrderBy = 'issued' THEN ii.issued
+ WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried
+ WHEN vOrderBy = 'booked' THEN ii.booked
+ WHEN vOrderBy = 'dueDate' THEN iid.dueDated
+ END dated,
+ CONCAT('S/Fra ', ii.supplierRef) sref,
+ IF(ii.currencyFk > 1,
+ ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3),
+ NULL
+ ) changeValue,
+ CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros,
+ CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency,
+ NULL paymentEuros,
+ NULL paymentCurrency,
+ ii.currencyFk,
+ ii.isBooked,
+ c.code,
+ 'invoiceIn' statementType
+ FROM invoiceIn ii
+ JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
+ JOIN currency c ON c.id = ii.currencyFk
+ WHERE ii.issued > '2014-12-31'
+ AND ii.supplierFk = vSupplierFk
+ AND vCurrencyFk IN (ii.currencyFk, 0)
+ AND vCompanyFk IN (ii.companyFk, 0)
+ AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated)
+ GROUP BY iid.id
+ UNION ALL
+ SELECT p.bankFk,
+ p.companyFk,
+ NULL,
+ p.id,
+ CASE
+ WHEN vOrderBy = 'issued' THEN p.received
+ WHEN vOrderBy = 'bookEntried' THEN p.received
+ WHEN vOrderBy = 'booked' THEN p.received
+ WHEN vOrderBy = 'dueDate' THEN p.dueDated
+ END,
+ CONCAT(IFNULL(pm.name, ''),
+ IF(pn.concept <> '',
+ CONCAT(' : ', pn.concept),
+ '')
+ ),
+ IF(p.currencyFk > 1, p.divisa / p.amount, NULL),
+ NULL,
+ NULL,
+ p.amount,
+ p.divisa,
+ p.currencyFk,
+ p.isConciliated,
+ c.code,
+ 'payment'
+ FROM payment p
+ LEFT JOIN currency c ON c.id = p.currencyFk
+ LEFT JOIN accounting a ON a.id = p.bankFk
+ LEFT JOIN payMethod pm ON pm.id = p.payMethodFk
+ LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id
+ WHERE p.received > '2014-12-31'
+ AND p.supplierFk = vSupplierFk
+ AND vCurrencyFk IN (p.currencyFk, 0)
+ AND vCompanyFk IN (p.companyFk, 0)
+ AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated)
+ UNION ALL
+ SELECT NULL,
+ companyFk,
+ NULL,
+ se.id,
+ CASE
+ WHEN vOrderBy = 'issued' THEN se.dated
+ WHEN vOrderBy = 'bookEntried' THEN se.dated
+ WHEN vOrderBy = 'booked' THEN se.dated
+ WHEN vOrderBy = 'dueDate' THEN se.dueDated
+ END,
+ se.description,
+ 1,
+ amount,
+ NULL,
+ NULL,
+ NULL,
+ currencyFk,
+ isConciliated,
+ c.`code`,
+ 'expense'
+ FROM supplierExpense se
+ JOIN currency c ON c.id = se.currencyFk
+ WHERE se.supplierFk = vSupplierFk
+ AND vCurrencyFk IN (se.currencyFk,0)
+ AND vCompanyFk IN (se.companyFk,0)
+ AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated)
+ ) sub
+ ORDER BY (dated IS NULL AND NOT isBooked),
+ dated,
+ IF(vOrderBy = 'dueDate', id, NULL)
+ LIMIT 10000000000000000000
+ ) t;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68879,37 +69037,37 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketBoxesView` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketBoxesView`(IN vTicketFk INT)
BEGIN
-
- SELECT s.id,
- s.itemFk,
- s.concept,
- floor(s.quantity / b.packing) as Cajas,
- b.packing,
- s.isPicked,
+
+ SELECT s.id,
+ s.itemFk,
+ s.concept,
+ floor(s.quantity / b.packing) as Cajas,
+ b.packing,
+ s.isPicked,
i.size
- FROM ticket t
+ FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk
JOIN buy b on b.id = lb.buy_id
- JOIN packaging p on p.id = b.packageFk
+ JOIN packaging p on p.id = b.packagingFk
WHERE s.quantity >= b.packing
AND t.id = vTicketFk
AND p.isBox
GROUP BY s.itemFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68931,7 +69089,7 @@ BEGIN
DECLARE vDateStart DATETIME DEFAULT DATE(vDate);
DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate);
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketBuiltTime;
CREATE TEMPORARY TABLE tmp.ticketBuiltTime
@@ -68944,7 +69102,7 @@ BEGIN
SELECT ticketFk, builtTime
FROM
(
- SELECT
+ SELECT
ticketFk,
created as builtTime
FROM
@@ -68952,13 +69110,13 @@ BEGIN
WHERE created BETWEEN vDateStart AND vDateEnd
ORDER BY ticketFk, created DESC
LIMIT 10000000000000000000
- ) sub
+ ) sub
GROUP BY ticketFk
) sub2 ON sub2.ticketFk = t.id
WHERE t.shipped BETWEEN vDate AND util.dayEnd(vDate)
AND t.clientFk NOT IN (50,400,200)
AND t.companyFk = 442
-
+
;
END ;;
@@ -68968,14 +69126,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculateClon` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT)
BEGIN
@@ -68987,9 +69145,9 @@ BEGIN
*/
REPLACE INTO orderTicket(orderFk,ticketFk)
- SELECT orderFk, vTicketNew
- FROM orderTicket
- WHERE ticketFk = vTicketOld;
+ SELECT orderFk, vTicketNew
+ FROM orderTicket
+ WHERE ticketFk = vTicketOld;
-- Bionizamos lineas con Preu = 0
CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
@@ -68998,16 +69156,16 @@ BEGIN
FROM sale
WHERE ticketFk = vTicketNew AND price = 0;
- CALL sale_recalcComponent(1);
+ CALL sale_recalcComponent('renewPrices');
-- Bionizamos lineas con Preu > 0
CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
(PRIMARY KEY (id)) ENGINE = MEMORY
- SELECT id
+ SELECT id
FROM sale
WHERE ticketFk = vTicketNew AND price > 0;
- CALL sale_recalcComponent(6);
+ CALL sale_recalcComponent('imbalance');
DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales;
@@ -69033,12 +69191,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculateFromType`( vLanded D
vTypeFk INT)
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.item;
- CREATE TEMPORARY TABLE tmp.item
- (INDEX (itemFk))
- ENGINE = MEMORY
+ CREATE TEMPORARY TABLE tmp.item
+ (INDEX (itemFk))
+ ENGINE = MEMORY
SELECT id itemFk FROM vn.item
WHERE typeFk = vTypeFk;
-
+
CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);
DROP TEMPORARY TABLE tmp.item;
DROP TEMPORARY TABLE tmp.ticketLot;
@@ -69060,7 +69218,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculatePurge`()
BEGIN
- DROP TEMPORARY TABLE
+ DROP TEMPORARY TABLE
tmp.ticketCalculateItem,
tmp.ticketComponentPrice,
tmp.ticketComponent,
@@ -69084,56 +69242,56 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketClon`(vTicketFk INT, vNewShipped DATE)
BEGIN
-
+
DECLARE done INT DEFAULT FALSE;
- DECLARE vNewTicketFk INT;
+ DECLARE vNewTicketFk INT;
DECLARE vOldSaleFk INT;
DECLARE vNewSaleFk INT;
-
+
DECLARE cur1 CURSOR FOR
SELECT id
FROM vn.sale
WHERE ticketFk = vTicketFk;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-
+
SET vNewShipped = IFNULL(vNewShipped, util.VN_CURDATE());
-
+
CALL vn.ticket_Clone(vTicketFk, vNewTicketFk);
-
- UPDATE vn.ticket
+
+ UPDATE vn.ticket
SET landed = TIMESTAMPADD(DAY, DATEDIFF(vNewShipped, shipped), landed),
shipped = vNewShipped
WHERE id = vNewTicketFk;
-
+
OPEN cur1;
-
+
read_loop: LOOP
-
+
FETCH cur1 INTO vOldSaleFk;
-
+
IF done THEN
LEAVE read_loop;
END IF;
-
+
INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed)
SELECT vNewTicketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed
FROM vn.sale
WHERE id = vOldSaleFk;
-
+
SELECT max(id) INTO vNewSaleFk
FROM vn.sale
WHERE ticketFk = vNewTicketFk;
-
+
INSERT INTO vn.saleComponent(saleFk, componentFk, value, isGreuge)
SELECT vNewSaleFk, componentFk, value, isGreuge
FROM vn.saleComponent
WHERE saleFk = vOldSaleFk;
-
+
END LOOP;
CLOSE cur1;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -69155,18 +69313,18 @@ BEGIN
DECLARE vShipped DATE;
DECLARE vMaxDated DATE;
-
- SELECT shipped, TIMESTAMPADD(YEAR,1,shipped)
+
+ SELECT shipped, TIMESTAMPADD(YEAR,1,shipped)
INTO vShipped, vMaxDated
FROM vn.ticket
WHERE id = vTicketFk;
-
+
WHILE vShipped <= vMaxDated DO
-
+
SET vShipped = TIMESTAMPADD(WEEK, 1, vShipped);
-
+
CALL vn.ticketClon(vTicketFk, vShipped);
-
+
END WHILE;
END ;;
@@ -69188,10 +69346,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_get`(vTicketFk INT)
BEGIN
- SELECT tc.collectionFk
+ SELECT tc.collectionFk
FROM vn.ticketCollection tc
WHERE ticketFk = vTicketFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -69210,18 +69368,18 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_setUsedShelves`(vTicketFk INT, vUsedShelves INT)
BEGIN
-
+
/*
* Inserta número de baldas que ocupa un ticket
- *
+ *
* @param vTicketFk Identificador de ticket
* @param vUsedShelves Número de baldas
*/
-
+
UPDATE ticketCollection tc
SET tc.usedShelves = vUsedShelves
WHERE tc.ticketFk = vTicketFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -69229,76 +69387,73 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentUpdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketComponentUpdate`(
vTicketFk INT,
- vClientFk INT,
- vAgencyModeFk INT,
- vAddressFk INT,
- vWarehouseFk TINYINT,
- vCompanyFk SMALLINT,
- vShipped DATETIME,
- vLanded DATE,
- vIsDeleted BOOLEAN,
- vHasToBeUnrouted BOOLEAN,
- vOption INT)
+ vClientFk INT,
+ vAgencyModeFk INT,
+ vAddressFk INT,
+ vWarehouseFk TINYINT,
+ vCompanyFk SMALLINT,
+ vShipped DATETIME,
+ vLanded DATE,
+ vIsDeleted BOOLEAN,
+ vHasToBeUnrouted BOOLEAN,
+ vOption VARCHAR(25))
BEGIN
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
ROLLBACK;
- RESIGNAL;
+ RESIGNAL;
END;
START TRANSACTION;
- IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN
-
- UPDATE ticket t
+ IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN
+
+ UPDATE ticket t
JOIN address a ON a.id = vAddressFk
SET t.nickname = a.nickname
WHERE t.id = vTicketFk;
-
- END IF;
+ END IF;
UPDATE ticket t
- SET
+ SET
t.clientFk = vClientFk,
t.agencyModeFk = vAgencyModeFk,
t.addressFk = vAddressFk,
t.warehouseFk = vWarehouseFk,
- t.companyFk = vCompanyFk,
+ t.companyFk = vCompanyFk,
t.landed = vLanded,
t.shipped = vShipped,
- t.isDeleted = vIsDeleted
+ t.isDeleted = vIsDeleted
WHERE
t.id = vTicketFk;
IF vHasToBeUnrouted THEN
UPDATE ticket t SET t.routeFk = NULL
WHERE t.id = vTicketFk;
- END IF;
-
- IF vOption <> 8 THEN
- DROP TEMPORARY TABLE IF EXISTS tmp.sale;
- CREATE TEMPORARY TABLE tmp.sale
- (PRIMARY KEY (saleFk))
- ENGINE = MEMORY
- SELECT id AS saleFk, vWarehouseFk warehouseFk
- FROM sale s WHERE s.ticketFk = vTicketFk;
-
- CALL ticketComponentUpdateSale (vOption);
-
- DROP TEMPORARY TABLE tmp.sale;
END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.sale;
+ CREATE TEMPORARY TABLE tmp.sale
+ (PRIMARY KEY (saleFk))
+ ENGINE = MEMORY
+ SELECT id AS saleFk, vWarehouseFk warehouseFk
+ FROM sale s WHERE s.ticketFk = vTicketFk;
+
+ CALL ticketComponentUpdateSale (vOption);
+
+ DROP TEMPORARY TABLE tmp.sale;
COMMIT;
END ;;
DELIMITER ;
@@ -69307,16 +69462,16 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentUpdateSale` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketComponentUpdateSale`(vOption INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketComponentUpdateSale`(vCode VARCHAR(25))
BEGIN
/**
* A partir de la tabla tmp.sale, crea los Movimientos_componentes
@@ -69326,132 +69481,59 @@ BEGIN
* @param table tmp.sale tabla memory con el campo saleFk, warehouseFk
**/
DECLARE vComponentFk INT;
- DECLARE vRenewComponents BOOLEAN;
- DECLARE vKeepPrices BOOLEAN;
- CASE vOption
- WHEN 1 THEN
- SET vRenewComponents = TRUE;
- SET vKeepPrices = FALSE;
- WHEN 2 THEN
- SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection';
- SET vRenewComponents = TRUE;
- SET vKeepPrices = TRUE;
- WHEN 3 THEN
- SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana';
- SET vRenewComponents = TRUE;
- SET vKeepPrices = TRUE;
- WHEN 4 THEN
- SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount';
- SET vRenewComponents = TRUE;
- SET vKeepPrices = TRUE;
- /* WHEN 5 THEN
- SET vComponentFk = 35;
- SET vRenewComponents = TRUE;
- SET vKeepPrices = TRUE;*/
- WHEN 6 THEN
- SELECT id INTO vComponentFk FROM component WHERE `code` = 'imbalance';
- SET vRenewComponents = TRUE;
- SET vKeepPrices = TRUE;
- WHEN 7 THEN
- REPLACE INTO saleComponent(saleFk, componentFk, value)
- SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3)
- FROM sale s
- JOIN tmp.sale tmps ON tmps.saleFk = s.id
- LEFT JOIN saleComponent sc ON sc.saleFk = s.id
- AND sc.componentFk NOT IN (28, 29)
- GROUP BY s.id;
+ IF vCode <> 'renewPrices' THEN
+ SELECT id INTO vComponentFk FROM component WHERE `code` = vCode;
+ END IF;
- REPLACE INTO saleComponent(saleFk, componentFk, value)
- SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3)
- FROM sale s
- JOIN tmp.sale tmps ON tmps.saleFk = s.id
- LEFT JOIN saleComponent sc ON sc.saleFk = s.id
- AND sc.componentFk NOT IN (28, 29)
- GROUP BY s.id;
+ DELETE sc.*
+ FROM tmp.sale tmps
+ JOIN saleComponent sc ON sc.saleFk = tmps.saleFk
+ JOIN `component` c ON c.id = sc.componentFk
+ WHERE c.isRenewable;
- SET vRenewComponents = FALSE;
- SET vKeepPrices = FALSE;
- WHEN 8 THEN
- DELETE sc.*
- FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk;
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, tc.componentFk, tc.cost
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ AND sc.componentFk = tc.componentFk
+ LEFT JOIN `component` c ON c.id = tc.componentFk
+ WHERE IF(sc.componentFk IS NULL AND NOT c.isRenewable, FALSE, TRUE);
- REPLACE INTO saleComponent(saleFk, componentFk, value)
- SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3)
- FROM sale s
- JOIN tmp.sale tmps ON tmps.saleFk = s.id;
-
- SET vRenewComponents = FALSE;
- SET vKeepPrices = FALSE;
- WHEN 9 THEN
- SET vRenewComponents = TRUE;
- SET vKeepPrices = TRUE;
- END CASE;
-
- IF vRenewComponents THEN
- DELETE sc.*
- FROM tmp.sale tmps
- JOIN saleComponent sc ON sc.saleFk = tmps.saleFk
- JOIN `component` c ON c.id = sc.componentFk
- WHERE c.isRenewable;
-
- REPLACE INTO saleComponent(saleFk, componentFk, value)
- SELECT s.id, tc.componentFk, tc.cost
- FROM sale s
- JOIN tmp.sale tmps ON tmps.saleFk = s.id
- JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
- LEFT JOIN saleComponent sc ON sc.saleFk = s.id
- AND sc.componentFk = tc.componentFk
- LEFT JOIN `component` c ON c.id = tc.componentFk
- WHERE IF(sc.componentFk IS NULL AND NOT c.isRenewable, FALSE, TRUE);
-
- -- Añadir componente venta por paquete
- DROP TEMPORARY TABLE IF EXISTS tmp.sale2;
- CREATE TEMPORARY TABLE tmp.sale2
- (PRIMARY KEY (saleFk))
- ENGINE = MEMORY
- SELECT * FROM tmp.sale;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent2;
- CREATE TEMPORARY TABLE tmp.ticketComponent2
- SELECT * FROM tmp.ticketComponent;
+ -- Añadir componente venta por paquete
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT t.id, t.componentFk, t.cost
+ FROM (
+ SELECT s.id, tc.componentFk, tc.cost, MOD(s.quantity, b.packing) as resto
+ FROM vn.sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id
+ JOIN vn.buy b ON b.id = buy_id
+ JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
+ JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage'
+ LEFT JOIN (
+ SELECT s.id
+ FROM vn.sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
+ JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk
+ JOIN `component` c ON c.id = sc.componentFk AND c.code = 'lastUnitsDiscount'
+ ) tp ON tp.id = s.id
+ WHERE tp.id IS NULL
+ HAVING resto <> 0) t;
+ IF vCode <> 'renewPrices' THEN
REPLACE INTO saleComponent(saleFk, componentFk, value)
- SELECT t.id, t.componentFk, t.cost
- FROM (
- SELECT s.id, tc.componentFk, tc.cost, MOD(s.quantity, b.packing) as resto
- FROM vn.sale s
- JOIN tmp.sale tmps ON tmps.saleFk = s.id
- JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id
- JOIN vn.buy b ON b.id = buy_id
- JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
- JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage'
- LEFT JOIN (
- SELECT s.id
- FROM vn.sale s
- JOIN tmp.sale2 tmps ON tmps.saleFk = s.id
- JOIN tmp.ticketComponent2 tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
- JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk
- JOIN `component` c ON c.id = sc.componentFk AND c.code = 'lastUnitsDiscount'
- ) tp ON tp.id = s.id
- WHERE tp.id IS NULL
- HAVING resto <> 0) t;
-
- DROP TEMPORARY TABLE IF EXISTS
- tmp.sale2,
- tmp.ticketComponent2;
- END IF;
-
- IF vKeepPrices THEN
- REPLACE INTO saleComponent(saleFk, componentFk, value)
- SELECT s.id, vComponentFk, ROUND((s.price * (100 - s.discount) / 100) - SUM(sc.value), 3) dif
- FROM sale s
- JOIN tmp.sale tmps ON tmps.saleFk = s.id
- LEFT JOIN saleComponent sc ON sc.saleFk = s.id
- WHERE sc.saleFk <> vComponentFk
- GROUP BY s.id
- HAVING dif <> 0;
- ELSE
+ SELECT s.id, vComponentFk, ROUND((s.price * (100 - s.discount) / 100) - SUM(sc.value), 3) dif
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ WHERE sc.saleFk <> vComponentFk
+ GROUP BY s.id
+ HAVING dif <> 0;
+ ELSE
UPDATE sale s
JOIN item i on i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk
@@ -69470,11 +69552,11 @@ BEGIN
WHERE sc.componentFk != 21
GROUP BY s.id
HAVING ROUND(saleValue, 4) <> 0;
- END IF;
+ END IF;
- UPDATE sale s
+ UPDATE sale s
JOIN (
- SELECT SUM(sc.value) sumValue, sc.saleFk
+ SELECT SUM(sc.value) sumValue, sc.saleFk
FROM saleComponent sc
JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
JOIN `component` c ON c.id = sc.componentFk
@@ -69482,14 +69564,14 @@ BEGIN
GROUP BY sc.saleFk) sc ON sc.saleFk = s.id
SET s.priceFixed = sumValue, s.isPriceFixed = 1;
- DELETE sc.*
+ DELETE sc.*
FROM saleComponent sc
JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
JOIN sale s on s.id = sc.saleFk
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
WHERE it.code = 'PRT';
-
+
INSERT INTO saleComponent(saleFk, componentFk, value)
SELECT s.id, 15, s.price
FROM sale s
@@ -69558,24 +69640,24 @@ BEGIN
CREATE TEMPORARY TABLE tmp.ticket
ENGINE = MEMORY
SELECT vTicketFk ticketFk;
-
+
CALL vn.ticket_getTax(NULL);
- SELECT
+ SELECT
tt.ticketFk,
CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase,
CAST(tt.rate * tt.taxableBase / 100 AS DECIMAL(10, 2)) AS tax,
- pgc.*,
+ pgc.*,
CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base,
pgc.rate / 100 as vatPercent
FROM tmp.ticketTax tt
JOIN vn.pgc ON pgc.code = tt.pgcFk
LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code;
-
+
DROP TEMPORARY TABLE tmp.ticket;
DROP TEMPORARY TABLE tmp.ticketTax;
DROP TEMPORARY TABLE tmp.ticketAmount;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -69613,29 +69695,29 @@ BEGIN
JOIN ticket t ON t.id = tmpTicket.ticketFk;
CALL addressTaxArea ();
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
CREATE TEMPORARY TABLE tmp.ticketTax
(INDEX (ticketFk))
ENGINE = MEMORY
SELECT tmpTicket.ticketFk,
bp.pgcFk,
- SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)
+ SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)
) AS taxableBase,
SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)
) * pgc.rate / 100 AS tax,
tc.code
-
+
FROM tmp.ticket tmpTicket
JOIN sale s ON s.ticketFk = tmpTicket.ticketFk
JOIN item i ON i.id = s.itemFk
JOIN ticket t ON t.id = tmpTicket.ticketFk
JOIN supplier su ON su.id = t.companyFk
- JOIN tmp.addressTaxArea ata
+ JOIN tmp.addressTaxArea ata
ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk
- JOIN itemTaxCountry itc
+ JOIN itemTaxCountry itc
ON itc.itemFk = i.id AND itc.countryFk = su.countryFk
- JOIN bookingPlanner bp
+ JOIN bookingPlanner bp
ON bp.countryFk = su.countryFk
AND bp.taxAreaFk = ata.areaFk
AND bp.taxClassFk = itc.taxClassFk
@@ -69643,7 +69725,7 @@ BEGIN
JOIN taxClass tc ON tc.id = bp.taxClassFk
GROUP BY tmpTicket.ticketFk, pgc.code
HAVING taxableBase != 0;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount;
CREATE TEMPORARY TABLE tmp.ticketAmount
(INDEX (ticketFk))
@@ -69654,7 +69736,7 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -69675,7 +69757,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketGetTotal`(vTaxArea VARCHAR(25
BEGIN
/**
* Calcula el total con IVA para un conjunto de tickets.
- *
+ *
* @param vTaxArea
* @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
* @return tmp.ticketTotal Total para cada ticket
@@ -69692,7 +69774,7 @@ BEGIN
FROM tmp.ticket t
LEFT JOIN tmp.ticketAmount ta ON t.ticketFk = ta.ticketFk
GROUP BY ticketFk;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
END ;;
@@ -69764,24 +69846,24 @@ BEGIN
DECLARE vParked DATETIME;
DECLARE vLevel INT;
DECLARE vCollectionFk INT;
-
- SELECT IFNULL(`level`,0), IFNULL(collectionFk,0)
+
+ SELECT IFNULL(`level`,0), IFNULL(collectionFk,0)
INTO vLevel, vCollectionFk
FROM vn.ticketCollection
WHERE ticketFk = vTicketFk
LIMIT 1;
-
- SELECT created, parkingFk
+
+ SELECT created, parkingFk
INTO vParked, vParkingFk
FROM vn.ticketParking
WHERE ticketFk = vTicketFk;
-
+
SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia
FROM vn.ticketParking tp
JOIN vn.parking p ON p.id = tp.parkingFk
JOIN vn.sector sc ON sc.id = p.sectorFk
LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk
- JOIN vn.ticketStateToday tst ON tst.ticket = tp.ticketFk
+ JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk
JOIN vn.ticket t ON t.id = tp.ticketFk
JOIN vn.zone z ON z.id = t.zoneFk
JOIN vn.agencyMode am ON am.id = z.agencyModeFk
@@ -69802,7 +69884,7 @@ BEGIN
AND sc.isPackagingArea
AND tp.created < vParked
AND t.packages <=> 0);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -69823,7 +69905,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketNotInvoicedByClient`(vClientF
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
-
+
CREATE TEMPORARY TABLE tmp.ticket
SELECT id ticketFk
FROM ticket
@@ -69833,7 +69915,7 @@ BEGIN
CALL vn.ticketGetTotal(NULL);
- SELECT c.id,
+ SELECT c.id,
c.name as Cliente,
t.shipped as Fecha,
t.id as Id_Ticket,
@@ -69844,7 +69926,7 @@ BEGIN
DROP TEMPORARY TABLE
tmp.ticket,
- tmp.ticketTotal;
+ tmp.ticketTotal;
END ;;
DELIMITER ;
@@ -69864,21 +69946,21 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketObservation_addNewBorn`(vTicketFk INT)
BEGIN
-
+
/**
* Inserta observaciones para los tickets con clientes nuevos o recuperados
- *
+ *
* @param vTicketFk Identificador de vn.ticket
*/
-
+
DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! ';
INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description)
SELECT vTicketFk, ot.id, vDescription
FROM vn.observationType ot
WHERE ot.hasNewBornMessage
- ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description);
-
+ ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description);
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -69918,7 +70000,7 @@ BEGIN
DECLARE vComponentCost INT;
DECLARE vDone INT DEFAULT FALSE;
DECLARE vClientId INT;
-
+
DECLARE vCursor CURSOR FOR
SELECT DISTINCT clientFk
FROM (
@@ -69935,31 +70017,31 @@ BEGIN
RESIGNAL;
END;
- SELECT id INTO vWarehouseInventory
- FROM warehouse
+ SELECT id INTO vWarehouseInventory
+ FROM warehouse
WHERE `code`= 'inv';
-
- SELECT id INTO vComponentCost
- FROM component
+
+ SELECT id INTO vComponentCost
+ FROM component
WHERE `code`= 'purchaseValue';
-
- SELECT packagingInvoicingDated INTO vDateStart
- FROM ticketConfig;
-
+
+ SELECT packagingInvoicingDated INTO vDateStart
+ FROM ticketConfig;
+
IF vWarehouseInventory IS NULL THEN
CALL util.throw('Warehouse inventory not set');
END IF;
IF vComponentCost IS NULL THEN
CALL util.throw('Component cost not set');
- END IF;
+ END IF;
SET vDateEnd = vDated + INTERVAL 1 DAY;
-
+
IF NOT vWithoutPeriodGrace THEN
SET vGraceDate = vGraceDate -INTERVAL 1 MONTH;
END IF;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.packagingToInvoice;
CREATE TEMPORARY TABLE tmp.packagingToInvoice
(INDEX (clientFk))
@@ -69972,7 +70054,7 @@ BEGIN
t.clientFk
FROM ticketPackaging tp
JOIN packaging p ON p.id = tp.packagingFk
- JOIN ticket t ON t.id = tp.ticketFk
+ JOIN ticket t ON t.id = tp.ticketFk
JOIN client c ON c.id = t.clientFk
WHERE c.isActive
AND (vClientFk IS NULL OR t.clientFk = vClientFk)
@@ -69980,7 +70062,7 @@ BEGIN
AND (tp.quantity < 0 OR (tp.quantity > 0 AND t.shipped < vGraceDate))
AND tp.quantity
AND p.itemFk;
-
+
OPEN vCursor;
l: LOOP
@@ -69993,25 +70075,25 @@ BEGIN
START TRANSACTION;
CALL ticket_add(
- vClientId,
+ vClientId,
vDateEnd,
- vWarehouseInventory,
- vCompanyFk,
- NULL,
- NULL,
- NULL,
- vDateEnd,
- account.myUser_getId(),
+ vWarehouseInventory,
+ vCompanyFk,
+ NULL,
+ NULL,
+ NULL,
+ vDateEnd,
+ account.myUser_getId(),
TRUE,
vNewTicket);
-
+
INSERT INTO ticketPackaging(ticketFk, packagingFk, quantity, pvp)
SELECT vNewTicket, packagingFk, - SUM(quantity) totalQuantity, price
- FROM tmp.packagingToInvoice
+ FROM tmp.packagingToInvoice
WHERE clientFk = vClientId
GROUP BY packagingFk
HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity < 0);
-
+
INSERT INTO sale(ticketFk, itemFk, concept, quantity, price)
SELECT vNewTicket, pti.itemFk, i.name, SUM(pti.quantity) totalQuantity, pti.price
FROM tmp.packagingToInvoice pti
@@ -70019,12 +70101,12 @@ BEGIN
WHERE pti.clientFk = vClientId
GROUP BY pti.itemFk
HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity > 0);
-
+
INSERT INTO saleComponent(saleFk, componentFk, value)
SELECT id, vComponentCost, price
FROM sale
WHERE ticketFk = vNewTicket;
-
+
COMMIT;
END LOOP;
CLOSE vCursor;
@@ -70048,43 +70130,43 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1))
BEGIN
-
+
/**
* Averigua los tickets que se han saltado por un error en el proceso encajado
* @param vTicketFk Ticket
* @param vItemPackingTypeFk Modo de encajado
* @return un select con los tickets afectados
- */
+ */
DECLARE vParkingFk INT;
DECLARE vParked DATETIME;
DECLARE vLevel INT;
DECLARE vWagon INT;
DECLARE vCollectionFk INT;
-
- SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0)
+
+ SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0)
INTO vLevel, vWagon, vCollectionFk
FROM vn.ticketCollection tc
JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk
WHERE ticketFk = vTicketFk
ORDER BY c.id DESC
LIMIT 1;
-
- SELECT created, parkingFk
+
+ SELECT created, parkingFk
INTO vParked, vParkingFk
FROM vn.ticketParking tp
- JOIN vn.parking p ON p.id = tp.parkingFk
- JOIN vn.sector s ON s.id = p.sectorFk
+ JOIN vn.parking p ON p.id = tp.parkingFk
+ JOIN vn.sector s ON s.id = p.sectorFk
WHERE ticketFk = vTicketFk
AND s.itemPackingTypeFk = vItemPackingTypeFk
AND s.isPackagingArea ;
-
+
SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia
FROM vn.ticketParking tp
JOIN vn.parking p ON p.id = tp.parkingFk
JOIN vn.sector sc ON sc.id = p.sectorFk
LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk
- JOIN vn.ticketStateToday tst ON tst.ticket = tp.ticketFk
+ JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk
JOIN vn.ticket t ON t.id = tp.ticketFk
JOIN vn.zone z ON z.id = t.zoneFk
JOIN vn.agencyMode am ON am.id = z.agencyModeFk
@@ -70095,9 +70177,9 @@ BEGIN
AND (
( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked )
OR
- ( tc.collectionFk = vCollectionFk
+ ( tc.collectionFk = vCollectionFk
AND (LEFT(tc.wagon,1) < LEFT(vWagon,1)
- OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1)))
+ OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1)))
)
)
) -- Etiquetas que no se han escaneado y ya estamos con una posterior
@@ -70105,7 +70187,7 @@ BEGIN
(s.alertLevel > 1
AND tp.parkingFk = vParkingFk
AND sc.isPackagingArea
- AND tp.created < vParked
+ AND tp.created < vParked
AND t.packages <=> 0);
END ;;
DELIMITER ;
@@ -70157,11 +70239,11 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketRequest_Add`(vDescription VARCHAR(255), vQuantity INT, vPrice DOUBLE, vTicketFk INT, vBuyerCode VARCHAR(3))
BEGIN
- INSERT INTO vn.ticketRequest(description,
- quantity,
- price,
- ticketFk,
- buyerCode,
+ INSERT INTO vn.ticketRequest(description,
+ quantity,
+ price,
+ ticketFk,
+ buyerCode,
requesterFk)
VALUES(vDescription,
vQuantity,
@@ -70169,7 +70251,7 @@ BEGIN
vTicketFk,
vBuyerCode,
vn.getUser());
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -70188,26 +70270,26 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45))
BEGIN
-
+
/* Modifica el estado de un ticket de hoy
- *
+ *
* @param vTicketFk el id del ticket
* @param vStateCode estado a modificar del ticket
- *
+ *
*/
-
+
DECLARE vAlertLevel INT;
-
- SELECT s.alertLevel INTO vAlertLevel
- FROM state s
- JOIN ticketStateToday tst ON tst.state = s.id
- WHERE tst.ticket = vTicketFk
+
+ SELECT s.alertLevel INTO vAlertLevel
+ FROM state s
+ JOIN ticketStateToday tst ON tst.state = s.id
+ WHERE tst.ticketFk = vTicketFk
LIMIT 1;
-
+
IF vAlertLevel < 2 THEN
-
+
CALL vn.ticket_setState(vTicketFk, vStateCode);
-
+
END IF;
END ;;
@@ -70217,34 +70299,34 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketStateUpdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45))
BEGIN
-
+
/*
* @deprecated:utilizar ticket_setState
*/
-
+
DECLARE vAlertLevel INT;
- SELECT s.alertLevel INTO vAlertLevel
+ SELECT s.alertLevel INTO vAlertLevel
FROM vn.state s
JOIN vn.ticketState ts ON ts.stateFk = s.id
WHERE ts.ticketFk = vTicketFk;
-
- IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN
-
- INSERT INTO ticketTracking(stateFk, ticketFk, workerFk)
+
+ IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN
+
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT id, vTicketFk, account.myUser_getId()
- FROM vn.state
+ FROM vn.state
WHERE `code` = vStateCode collate utf8_unicode_ci;
END IF;
@@ -70388,14 +70470,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_add`(
vClientId INT
@@ -70410,11 +70492,26 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_add`(
,vIsRequiredZone INT
,OUT vNewTicket INT)
BEGIN
+/**
+* Crea un ticket,
+* ¡¡NO se debe llamar directamente, llamar a salix que hace comprobaciones previas!!
+*
+* @param vClientId id del cliente
+* @param vShipped dia preparacion
+* @param vWarehouseFk id del warehouse
+* @param vCompanyFk id la empresa
+* @param vAddressFk id del consignatario
+* @param vAgencyModeFk id de la agencia
+* @param vRouteFk id de la ruta | NULL
+* @param vlanded dia llegada
+* @param vUserId que crea el ticket
+* @param vIsRequiredZone Indica si tiene que tener zona valida para ser creado
+* @return vNewTicket id del ticket creado
+*/
DECLARE vZoneFk INT;
DECLARE vPrice DECIMAL(10,2);
DECLARE vBonus DECIMAL(10,2);
DECLARE vIsActive BOOL;
- DECLARE vNickname VARCHAR(100);
IF vClientId IS NULL THEN
CALL util.throw ('CLIENT_NOT_ESPECIFIED');
@@ -70480,10 +70577,6 @@ BEGIN
JOIN agencyMode am ON am.id = a.agencyModeFk
WHERE a.id = vAddressFk;
- SELECT a.nickname INTO vNickname
- FROM address a
- WHERE a.id = vAddressFk;
-
SET vNewTicket = LAST_INSERT_ID();
INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
@@ -70501,7 +70594,7 @@ BEGIN
END IF;
IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN
- INSERT INTO ticketTracking(stateFk, ticketFk, workerFk)
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT id, vNewTicket, account.myUser_getId()
FROM state
WHERE `code` = 'DELIVERED';
@@ -70524,20 +70617,20 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_administrativeCopy`(vOriginalTicket INT, OUT vNewTicket INT)
BEGIN
-
+
INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed)
- SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed
+ SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed
FROM vn.ticket t
JOIN vn.warehouse w ON w.name = 'INVENTARIO'
WHERE t.id = vOriginalTicket;
-
+
SELECT LAST_INSERT_ID() INTO vNewTicket;
INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount)
- SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount
+ SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount
FROM vn.sale s
WHERE s.ticketFk = vOriginalTicket;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -70545,14 +70638,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_canAdvance` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT)
BEGIN
@@ -70567,8 +70660,7 @@ BEGIN
SELECT inventoried INTO vDateInventory FROM config;
- DROP TEMPORARY TABLE IF EXISTS tmp.stock;
- CREATE TEMPORARY TABLE tmp.stock
+ CREATE OR REPLACE TEMPORARY TABLE tmp.stock
(itemFk INT PRIMARY KEY,
amount INT)
ENGINE = MEMORY;
@@ -70585,7 +70677,7 @@ BEGIN
SELECT itemFk, quantity
FROM itemEntryIn
WHERE landed >= vDateInventory
- AND landed < vDateFuture
+ AND landed <= vDateToAdvance
AND isVirtualStock = FALSE
AND warehouseInFk = vWarehouseFk
UNION ALL
@@ -70614,44 +70706,63 @@ BEGIN
dest.totalWithVat,
origin.totalWithVat futureTotalWithVat,
dest.agency,
+ dest.agencyModeFk,
origin.futureAgency,
+ origin.agencyModeFk futureAgencyModeFk,
dest.lines,
dest.liters,
origin.futureLines - origin.hasStock AS notMovableLines,
(origin.futureLines = origin.hasStock) AS isFullMovable,
+ dest.zoneFk,
+ origin.futureZoneFk,
+ origin.futureZoneName,
origin.classColor futureClassColor,
- dest.classColor
+ dest.classColor,
+ origin.clientFk futureClientFk,
+ origin.addressFk futureAddressFk,
+ origin.warehouseFk futureWarehouseFk,
+ origin.companyFk futureCompanyFk,
+ IFNULL(dest.nickname, origin.nickname) nickname,
+ dest.landed
FROM (
SELECT
s.ticketFk,
- t.workerFk,
+ c.salesPersonFk workerFk,
t.shipped,
t.totalWithVat,
st.name futureState,
- t.addressFk,
am.name futureAgency,
count(s.id) futureLines,
GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
SUM((s.quantity <= IFNULL(st.amount,0))) hasStock,
- st.classColor
+ z.id futureZoneFk,
+ z.name futureZoneName,
+ st.classColor,
+ t.clientFk,
+ t.nickname,
+ t.addressFk,
+ t.warehouseFk,
+ t.companyFk,
+ t.agencyModeFk
FROM ticket t
+ JOIN client c ON c.id = t.clientFk
JOIN sale s ON s.ticketFk = t.id
JOIN saleVolume sv ON sv.saleFk = s.id
JOIN item i ON i.id = s.itemFk
JOIN ticketState ts ON ts.ticketFk = t.id
JOIN state st ON st.id = ts.stateFk
JOIN agencyMode am ON t.agencyModeFk = am.id
+ JOIN zone z ON t.zoneFk = z.id
LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
LEFT JOIN tmp.stock st ON st.itemFk = i.id
WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
AND t.warehouseFk = vWarehouseFk
GROUP BY t.id
) origin
- JOIN (
+ LEFT JOIN (
SELECT
t.id ticketFk,
- t.addressFk,
st.name state,
GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
t.shipped,
@@ -70659,7 +70770,15 @@ BEGIN
am.name agency,
CAST(SUM(litros) AS DECIMAL(10,0)) liters,
CAST(COUNT(*) AS DECIMAL(10,0)) `lines`,
- st.classColor
+ st.classColor,
+ t.clientFk,
+ t.nickname,
+ t.addressFk,
+ t.zoneFk,
+ t.warehouseFk,
+ t.companyFk,
+ t.landed,
+ t.agencyModeFk
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN saleVolume sv ON sv.saleFk = s.id
@@ -70673,7 +70792,7 @@ BEGIN
AND st.order <= 5
GROUP BY t.id
) dest ON dest.addressFk = origin.addressFk
- WHERE origin.hasStock != 0;
+ WHERE origin.hasStock;
DROP TEMPORARY TABLE tmp.stock;
END ;;
@@ -70715,6 +70834,7 @@ BEGIN
t.warehouseFk,
ts.alertLevel,
t.shipped,
+ t.totalWithVat,
sub2.shipped futureShipped,
t.workerFk,
st.code stateCode,
@@ -70781,7 +70901,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canMerge`(vDated DATE, vScop
BEGIN
/**
* Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro
- *
+ *
* @param vDated Fecha en cuestión
* @param vScopeDays Dias en el futuro a sondear
* @param vLitersMax Volumen máximo de los tickets a catapultar
@@ -70846,14 +70966,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_checkNoComponents` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_checkNoComponents`(vShippedFrom DATETIME, vShippedTo DATETIME)
BEGIN
@@ -70862,10 +70982,10 @@ BEGIN
* Comprueba que los tickets entre un rango de fechas tienen componentes
* y recalcula sus componentes
*
- * @param vShippedFrom rango inicial de fecha
+ * @param vShippedFrom rango inicial de fecha
* @param vShippedTo rango final de fecha
*/
-
+
CREATE OR REPLACE TEMPORARY TABLE tmp.coste
(primary key (id)) ENGINE = MEMORY
SELECT s.id
@@ -70880,9 +71000,9 @@ BEGIN
WHERE t.shipped BETWEEN vShippedFrom AND vShippedTo
AND ic.merchandise;
- CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
+ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
(primary key (id)) ENGINE = MEMORY
- SELECT DISTINCT s.id
+ SELECT DISTINCT s.id
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
@@ -70893,10 +71013,10 @@ BEGIN
AND c.id IS NULL
AND ic.merchandise;
- CALL vn.sale_recalcComponent(1);
+ CALL sale_recalcComponent('renewPrices');
- DROP TEMPORARY TABLE tmp.recalculateSales;
- DROP TEMPORARY TABLE tmp.coste;
+ DROP TEMPORARY TABLE tmp.recalculateSales;
+ DROP TEMPORARY TABLE tmp.coste;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -70904,14 +71024,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_Clone` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT)
BEGIN
@@ -70924,22 +71044,22 @@ BEGIN
DECLARE vStateFk INT;
INSERT INTO ticket (
- clientFk,
- shipped,
- addressFk,
- agencyModeFk,
- nickname,
- warehouseFk,
- companyFk,
- landed,
- zoneFk,
- zonePrice,
- zoneBonus,
- routeFk,
- priority,
- hasPriority,
- clonedFrom
- )
+ clientFk,
+ shipped,
+ addressFk,
+ agencyModeFk,
+ nickname,
+ warehouseFk,
+ companyFk,
+ landed,
+ zoneFk,
+ zonePrice,
+ zoneBonus,
+ routeFk,
+ priority,
+ hasPriority,
+ clonedFrom
+ )
SELECT
clientFk,
shipped,
@@ -70956,18 +71076,18 @@ BEGIN
priority,
hasPriority,
vOriginalTicket
- FROM ticket
- WHERE id = vOriginalTicket;
+ FROM ticket
+ WHERE id = vOriginalTicket;
SET vNewTicket = LAST_INSERT_ID();
INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
- SELECT vNewTicket, o.observationTypeFk, o.description
- FROM ticketObservation o
- WHERE o.ticketFk = vOriginalTicket;
+ SELECT vNewTicket, observationTypeFk, description
+ FROM ticketObservation
+ WHERE ticketFk = vOriginalTicket;
- INSERT INTO ticketTracking(ticketFk, stateFk, workerFk, created)
- SELECT vNewTicket, stateFk, workerFk , created
+ INSERT INTO ticketTracking(ticketFk, stateFk, userFk, created)
+ SELECT vNewTicket, stateFk, userFk, created
FROM ticketTracking
WHERE ticketFk = vOriginalTicket
ORDER BY created;
@@ -70987,14 +71107,13 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`(vWeek INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`(vDateFrom DATE, vDateTo DATE)
BEGIN
DECLARE vIsDone BOOL;
DECLARE vLanding DATE;
DECLARE vShipment DATE;
DECLARE vWarehouseFk INT;
DECLARE vTicketFk INT;
- DECLARE vWeekDay INT;
DECLARE vClientFk INT;
DECLARE vCompanyFk INT;
DECLARE vAddressFk INT;
@@ -71006,19 +71125,21 @@ BEGIN
DECLARE rsTicket CURSOR FOR
SELECT tt.ticketFk,
- tt.weekDay,
- t.clientFk,
- t.warehouseFk,
- t.companyFk,
- t.addressFk,
- tt.agencyModeFk
- FROM ticketWeekly tt
- JOIN ticket t ON tt.ticketFk = t.id;
+ t.clientFk,
+ t.warehouseFk,
+ t.companyFk,
+ t.addressFk,
+ tt.agencyModeFk,
+ ti.dated
+ FROM ticketWeekly tt
+ JOIN ticket t ON tt.ticketFk = t.id
+ JOIN tmp.time ti
+ WHERE WEEKDAY(ti.dated) = tt.weekDay;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
-
- SET vYear = YEAR(util.VN_CURDATE()) + IF(vWeek < WEEK(util.VN_CURDATE()),1, 0);
-
+
+ CALL `util`.`time_generate`(vDateFrom,vDateTo);
+
OPEN rsTicket;
myLoop: LOOP
BEGIN
@@ -71026,36 +71147,31 @@ BEGIN
DECLARE vIsDuplicateMail BOOL;
DECLARE vSubject VARCHAR(150);
DECLARE vMessage TEXT;
-
+
SET vIsDone = FALSE;
- FETCH rsTicket INTO vTicketFk, vWeekDay, vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk;
+ FETCH rsTicket INTO vTicketFk,vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk,vShipment;
IF vIsDone THEN
LEAVE myLoop;
END IF;
- SELECT dated INTO vShipment
- FROM `time`
- WHERE `year` = vYear AND `week` = vWeek
- AND WEEKDAY(dated) = vWeekDay;
-
-- busca si el ticket ya ha sido clonado
IF EXISTS (SELECT TRUE FROM ticket tOrig
JOIN sale saleOrig ON tOrig.id = saleOrig.ticketFk
JOIN saleCloned sc ON sc.saleOriginalFk = saleOrig.id
JOIN sale saleClon ON saleClon.id = sc.saleClonedFk
JOIN ticket tClon ON tClon.id = saleClon.ticketFk
- WHERE tOrig.id = vTicketFk
- AND tClon.isDeleted = FALSE
+ WHERE tOrig.id = vTicketFk
+ AND tClon.isDeleted = FALSE
AND DATE(tClon.shipped) = vShipment)
THEN
ITERATE myLoop;
END IF;
IF vAgencyModeFk IS NULL THEN
- SELECT agencyModeFk INTO vAgencyModeFk
+ SELECT agencyModeFk INTO vAgencyModeFk
FROM address
- WHERE clientFk = vClientFk
+ WHERE clientFk = vClientFk
AND isDefaultAddress;
END IF;
@@ -71076,8 +71192,8 @@ BEGIN
FALSE,
vNewTicket);
- UPDATE ticket
- SET clonedFrom = vTicketFk
+ UPDATE ticket
+ SET clonedFrom = vTicketFk
WHERE id = vNewTicket;
INSERT INTO sale (ticketFk, itemFk, concept, quantity, price,
@@ -71096,7 +71212,7 @@ BEGIN
INSERT IGNORE INTO saleCloned(saleOriginalFk, saleClonedFk)
SELECT saleOriginal.id, saleClon.id
FROM sale saleOriginal
- JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk
+ JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk
AND saleOriginal.quantity = saleClon.quantity
WHERE saleOriginal.ticketFk = vTicketFk
AND saleClon.ticketFk = vNewTicket;
@@ -71126,7 +71242,7 @@ BEGIN
buyed,
requesterFk,
attenderFk,
- vNewTicket
+ vNewTicket
FROM ticketRequest
WHERE ticketFk =vTicketFk;
@@ -71141,26 +71257,26 @@ BEGIN
INSERT INTO ticketObservation(
ticketFk,
observationTypeFk,
- description)
+ description)
VALUES(
vNewTicket,
vSalesPersonFK,
CONCAT('turno desde ticket: ',vTicketFk))
- ON DUPLICATE KEY UPDATE description =
+ ON DUPLICATE KEY UPDATE description =
CONCAT(ticketObservation.description,VALUES(description),' ');
INSERT INTO ticketObservation(ticketFk,
observationTypeFk,
- description)
+ description)
VALUES(
vNewTicket,
vItemPicker,
'ATENCION: Contiene lineas de TURNO')
- ON DUPLICATE KEY UPDATE description =
+ ON DUPLICATE KEY UPDATE description =
CONCAT(ticketObservation.description,VALUES(description),' ');
IF (vLanding IS NULL) THEN
-
+
SELECT e.email INTO vSalesPersonEmail
FROM client c
JOIN account.emailUser e ON e.userFk = c.salesPersonFk
@@ -71168,8 +71284,8 @@ BEGIN
SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ',
vTicketFk,' para el dia: ', vShipment);
- SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk,
- ' para el dia: ', vShipment,
+ SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk,
+ ' para el dia: ', vShipment,
' porque no hay una zona de envío disponible. Se ha creado el ticket: ',
vNewTicket, ' pero ha que revisar las fechas y la agencia');
@@ -71189,6 +71305,7 @@ BEGIN
END;
END LOOP;
CLOSE rsTicket;
+ DROP TEMPORARY TABLE IF EXISTS tmp.time;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -71208,7 +71325,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_close`()
BEGIN
/**
- * Realiza el cierre de todos los
+ * Realiza el cierre de todos los
* tickets de la tabla tmp.ticket_close.
*
* @table tmp.ticket_close(ticketFk) Identificadores de los tickets a cerrar
@@ -71226,7 +71343,7 @@ BEGIN
DECLARE cur CURSOR FOR
SELECT ticketFk FROM tmp.ticket_close;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
RESIGNAL;
@@ -71236,7 +71353,7 @@ BEGIN
proc: LOOP
SET vDone = FALSE;
-
+
FETCH cur INTO vCurTicketFk;
IF vDone THEN
@@ -71253,12 +71370,12 @@ BEGIN
c.hasToInvoice
INTO vClientFk,
vIsTaxDataChecked,
- vCompanyFk,
+ vCompanyFk,
vShipped,
vHasDailyInvoice,
vWithPackage,
vHasToInvoice
- FROM ticket t
+ FROM ticket t
JOIN `client` c ON c.id = t.clientFk
JOIN province p ON p.id = c.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
@@ -71268,22 +71385,22 @@ BEGIN
INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity)
(SELECT vCurTicketFk, p.id, COUNT(*)
- FROM expedition e
+ FROM expedition e
JOIN packaging p ON p.itemFk = e.freightItemFk
WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable
AND vWithPackage
GROUP BY p.itemFk);
-- No retornables o no catalogados
- INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed)
+ INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed)
(SELECT e.freightItemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.freightItemFk, vClientFk), 1
- FROM expedition e
+ FROM expedition e
JOIN item i ON i.id = e.freightItemFk
LEFT JOIN packaging p ON p.itemFk = i.id
WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0
AND getSpecialPrice(e.freightItemFk, vClientFk) > 0
GROUP BY e.freightItemFk);
-
+
IF(vHasDailyInvoice) AND vHasToInvoice THEN
-- Facturacion rapida
@@ -71291,10 +71408,10 @@ BEGIN
-- Facturar si está contabilizado
IF vIsTaxDataChecked THEN
CALL invoiceOut_newFromClient(
- vClientFk,
- (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')),
- vShipped,
- vCompanyFk,
+ vClientFk,
+ (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')),
+ vShipped,
+ vCompanyFk,
NULL,
NULL,
vNewInvoiceId);
@@ -71337,10 +71454,11 @@ BEGIN
JOIN agencyMode am ON am.id = t.agencyModeFk
LEFT JOIN ticketState ts ON ts.ticketFk = t.id
JOIN alertLevel al ON al.id = ts.alertLevel
- WHERE al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered')
+ WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered'))
AND t.id = vTicketFk
AND t.refFk IS NULL
- GROUP BY t.id);
+ GROUP BY t.id
+ );
CALL ticket_close();
@@ -71352,35 +71470,35 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_componentMakeUpdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentMakeUpdate`(
vTicketFk INT,
vClientFk INT,
vNickname VARCHAR(50),
vAgencyModeFk INT,
- vAddressFk INT,
+ vAddressFk INT,
vZoneFk INT,
vWarehouseFk INT,
- vCompanyFk INT,
+ vCompanyFk INT,
vShipped DATETIME,
- vLanded DATE,
+ vLanded DATE,
vIsDeleted BOOLEAN,
- vHasToBeUnrouted BOOLEAN,
- vOption INT)
+ vHasToBeUnrouted BOOLEAN,
+ vOption VARCHAR(25))
BEGIN
-
+
/**
* Modifica en el ticket los campos que se le pasan por parámetro
* y cambia sus componentes
- *
+ *
* @param vTicketFk Id del ticket a modificar
* @param vClientFk nuevo cliente
* @param vNickname nuevo alias
@@ -71395,29 +71513,29 @@ BEGIN
* @param vHasToBeUnrouted si se le elimina la ruta al ticket
* @param vOption opcion para el case del proc ticketComponentUpdateSale
*/
-
+
DECLARE vPrice DECIMAL(10,2);
DECLARE vBonus DECIMAL(10,2);
CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk);
IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN
-
- UPDATE ticket t
+
+ UPDATE ticket t
JOIN address a ON a.id = vAddressFk
SET t.nickname = a.nickname
WHERE t.id = vTicketFk;
-
+
END IF;
CALL zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, TRUE);
- SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus
+ SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus
FROM tmp.zoneGetShipped
WHERE shipped BETWEEN DATE(vShipped) AND util.dayEnd(vShipped) AND warehouseFk = vWarehouseFk LIMIT 1;
UPDATE ticket t
- SET
+ SET
t.clientFk = vClientFk,
t.nickname = vNickname,
t.agencyModeFk = vAgencyModeFk,
@@ -71438,23 +71556,21 @@ BEGIN
WHERE t.id = vTicketFk;
END IF;
- IF vOption <> 8 THEN
- DROP TEMPORARY TABLE IF EXISTS tmp.sale;
- CREATE TEMPORARY TABLE tmp.sale
- (PRIMARY KEY (saleFk))
- ENGINE = MEMORY
- SELECT id AS saleFk, vWarehouseFk warehouseFk
- FROM sale s WHERE s.ticketFk = vTicketFk;
+ DROP TEMPORARY TABLE IF EXISTS tmp.sale;
+ CREATE TEMPORARY TABLE tmp.sale
+ (PRIMARY KEY (saleFk))
+ ENGINE = MEMORY
+ SELECT id AS saleFk, vWarehouseFk warehouseFk
+ FROM sale s WHERE s.ticketFk = vTicketFk;
- DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
- CREATE TEMPORARY TABLE tmp.ticketComponent
- SELECT * FROM tmp.ticketComponentPreview;
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
+ CREATE TEMPORARY TABLE tmp.ticketComponent
+ SELECT * FROM tmp.ticketComponentPreview;
- CALL ticketComponentUpdateSale (vOption);
+ CALL ticketComponentUpdateSale (vOption);
- DROP TEMPORARY TABLE tmp.sale;
- DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
- END IF;
+ DROP TEMPORARY TABLE tmp.sale;
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
DROP TEMPORARY TABLE tmp.zoneGetShipped, tmp.ticketComponentPreview;
END ;;
@@ -71475,7 +71591,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentPreview`(
vTicketFk INT,
- vLanded DATE,
+ vLanded DATE,
vAddressFk INT,
vZoneFk INT,
vWarehouseFk SMALLINT)
@@ -71491,7 +71607,7 @@ BEGIN
*
* @return tmp.ticketComponentPreview (warehouseFk, itemFk, componentFk, cost)
*/
- DECLARE vHasDataChanged BOOL DEFAULT FALSE;
+ DECLARE vHasDataChanged BOOL DEFAULT FALSE;
DECLARE vHasAddressChanged BOOL;
DECLARE vHasZoneChanged BOOL DEFAULT FALSE;
DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE;
@@ -71502,8 +71618,8 @@ BEGIN
DECLARE vHasChangeAll BOOL DEFAULT FALSE;
- SELECT DATE(landed) <> vLanded,
- addressFk <> vAddressFk,
+ SELECT DATE(landed) <> vLanded,
+ addressFk <> vAddressFk,
zoneFk <> vZoneFk,
warehouseFk <> vWarehouseFk
INTO
@@ -71526,15 +71642,15 @@ BEGIN
SET vAgencyModeTypeRateFk = 6;
END IF;
- SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped
+ SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped
FROM zone
WHERE id = vZoneFk;
-
+
CALL buyUltimate(vWarehouseFk, vShipped);
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
- CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY (
- SELECT
+ CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY (
+ SELECT
vWarehouseFk AS warehouseFk,
NULL AS available,
s.itemFk,
@@ -71554,9 +71670,9 @@ BEGIN
JOIN sale s ON s.id = sc.saleFk
JOIN ticket t ON t.id = s.ticketFk
JOIN `component` c ON c.id = sc.componentFk
- WHERE s.ticketFk = vTicketFk
- AND (c.isRenewable = FALSE
- OR
+ WHERE s.ticketFk = vTicketFk
+ AND (c.isRenewable = FALSE
+ OR
(NOT vHasChangeAll
AND (NOT (c.typeFk <=> vAddressTypeRateFk
OR c.typeFk <=> vAgencyModeTypeRateFk))));
@@ -71635,55 +71751,59 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT)
-BEGIN
-
- /*
- * Splita las lineas de ticket que no estan ubicadas
- *
- */
-
- DECLARE vNewTicketFk INT;
- DECLARE vTotalLines INT;
- DECLARE vLinesToSplit INT;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit;
-
- SELECT COUNT(*) INTO vTotalLines
- FROM vn.sale
- WHERE ticketFk = vTicketFk;
-
- CREATE TEMPORARY TABLE tmp.SalesToSplit
- SELECT s.id saleFk
- FROM vn.ticket t
- JOIN vn.sale s ON t.id = s.ticketFk
- LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = s.itemFk AND issw.warehouseFk = t.warehouseFk
- WHERE s.quantity > IFNULL(issw.visible, 0)
- AND s.quantity > 0
- AND s.isPicked = FALSE
- AND s.reserved = FALSE
- AND t.id = vTicketFk;
-
- SELECT COUNT(*) INTO vLinesToSplit
- FROM tmp.SalesToSplit;
-
- IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN
-
- SET vNewTicketFk = vTicketFk;
-
- ELSE
-
- CALL vn.ticket_Clone(vTicketFk, vNewTicketFk);
-
- UPDATE vn.sale s
- JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id
- SET s.ticketFk = vNewTicketFk;
-
- END IF;
-
- CALL vn.ticketStateUpdate(vNewTicketFk, 'FIXING');
-
- DROP TEMPORARY TABLE tmp.SalesToSplit;
-
+BEGIN
+/**
+ * Splita las lineas de ticket que no estan ubicadas
+ *
+ * @param vTicketFk Id ticket
+ */
+ DECLARE vNewTicketFk INT;
+ DECLARE vTotalLines INT;
+ DECLARE vLinesToSplit INT;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit;
+
+ SELECT COUNT(*) INTO vTotalLines
+ FROM sale
+ WHERE ticketFk = vTicketFk;
+
+ CREATE TEMPORARY TABLE tmp.SalesToSplit
+ SELECT s.id saleFk
+ FROM ticket t
+ JOIN sale s ON t.id = s.ticketFk
+ LEFT JOIN (
+ SELECT ish.itemFk itemFk,
+ SUM(ish.visible) visible,
+ s.warehouseFk warehouseFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector s ON s.id = p.sectorFk
+ GROUP BY ish.itemFk,
+ s.warehouseFk
+ ) issw ON issw.itemFk = s.itemFk
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE s.quantity > IFNULL(issw.visible, 0)
+ AND s.quantity > 0
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND t.id = vTicketFk;
+
+ SELECT COUNT(*) INTO vLinesToSplit
+ FROM tmp.SalesToSplit;
+
+ IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN
+ SET vNewTicketFk = vTicketFk;
+ ELSE
+ CALL ticket_Clone(vTicketFk, vNewTicketFk);
+ UPDATE sale s
+ JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id
+ SET s.ticketFk = vNewTicketFk;
+ END IF;
+
+ CALL ticketStateUpdate(vNewTicketFk, 'FIXING');
+
+ DROP TEMPORARY TABLE tmp.SalesToSplit;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -71701,91 +71821,91 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT)
-BEGIN
-/**
-* Crea u actualiza la información del CMR asociado con
-* un ticket específico en caso de que sea necesario.
-*
-* @param vSelf El id del ticket
-*/
- DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT;
- SELECT cmrFk INTO vCmrFk
- FROM ticket
- WHERE id = vSelf;
-
- CREATE OR REPLACE TEMPORARY TABLE tTicket
- SELECT wo.firstName,
- v.numberPlate,
- com.id companyFk,
- a.id addressFk,
- c2.defaultAddressFk,
- su.id supplierFk,
- t.landed
- FROM ticket t
- JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN `state` s ON s.id = ts.stateFk
- JOIN alertLevel al ON al.id = s.alertLevel
- JOIN client c ON c.id = t.clientFk
- JOIN `address` a ON a.id = t.addressFk
- JOIN province p ON p.id = a.provinceFk
- JOIN country co ON co.id = p.countryFk
- JOIN agencyMode am ON am.id = t.agencyModeFk
- JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
- JOIN warehouse w ON w.id = t.warehouseFk
- JOIN company com ON com.id = t.companyFk
- JOIN client c2 ON c2.id = com.clientFk
- JOIN supplierAccount sa ON sa.id = com.supplierAccountFk
- JOIN supplier su ON su.id = sa.supplierFk
- LEFT JOIN route r ON r.id = t.routeFk
- LEFT JOIN worker wo ON wo.id = r.workerFk
- LEFT JOIN vehicle v ON v.id = r.vehicleFk
- WHERE t.shipped BETWEEN util.yesterday() AND util.dayEnd(util.VN_CURDATE())
- AND al.code IN ('PACKED', 'DELIVERED')
- AND co.code <> 'ES'
- AND am.name <> 'ABONO'
- AND w.code = 'ALG'
- AND dm.code = 'DELIVERY'
- AND t.id = vSelf
- GROUP BY t.id;
-
- START TRANSACTION;
-
- IF vCmrFk THEN
- UPDATE cmr c
- JOIN tTicket t
- SET c.senderInstruccions = t.firstName,
- c.truckPlate = t.numberPlate,
- c.companyFk = t.companyFk,
- c.addressToFk = t.addressFk,
- c.addressFromFk = t.defaultAddressFk,
- c.supplierFk = t.supplierFk,
- c.ead = t.landed
- WHERE id = vCmrFk;
- ELSE
- SELECT MAX(id) INTO vPreviousCmrFk FROM cmr;
-
- INSERT INTO cmr (
- senderInstruccions,
- truckPlate,
- companyFk,
- addressToFk,
- addressFromFk,
- supplierFk,
- ead
- )
- SELECT * FROM tTicket;
-
- SELECT MAX(id) INTO vCurrentCmrFk FROM cmr;
-
- IF vPreviousCmrFk <> vCurrentCmrFk THEN
- UPDATE ticket
- SET cmrFk = vCurrentCmrFk
- WHERE id = vSelf;
- END IF;
- END IF;
-
- COMMIT;
- DROP TEMPORARY TABLE tTicket;
+BEGIN
+/**
+* Crea u actualiza la información del CMR asociado con
+* un ticket específico en caso de que sea necesario.
+*
+* @param vSelf El id del ticket
+*/
+ DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT;
+ SELECT cmrFk INTO vCmrFk
+ FROM ticket
+ WHERE id = vSelf;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTicket
+ SELECT wo.firstName,
+ v.numberPlate,
+ com.id companyFk,
+ a.id addressFk,
+ c2.defaultAddressFk,
+ su.id supplierFk,
+ t.landed
+ FROM ticket t
+ JOIN ticketState ts ON ts.ticketFk = t.id
+ JOIN `state` s ON s.id = ts.stateFk
+ JOIN alertLevel al ON al.id = s.alertLevel
+ JOIN client c ON c.id = t.clientFk
+ JOIN `address` a ON a.id = t.addressFk
+ JOIN province p ON p.id = a.provinceFk
+ JOIN country co ON co.id = p.countryFk
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ JOIN company com ON com.id = t.companyFk
+ JOIN client c2 ON c2.id = com.clientFk
+ JOIN supplierAccount sa ON sa.id = com.supplierAccountFk
+ JOIN supplier su ON su.id = sa.supplierFk
+ LEFT JOIN route r ON r.id = t.routeFk
+ LEFT JOIN worker wo ON wo.id = r.workerFk
+ LEFT JOIN vehicle v ON v.id = r.vehicleFk
+ WHERE t.shipped BETWEEN util.yesterday() AND util.dayEnd(util.VN_CURDATE())
+ AND al.code IN ('PACKED', 'DELIVERED')
+ AND co.code <> 'ES'
+ AND am.name <> 'ABONO'
+ AND w.code = 'ALG'
+ AND dm.code = 'DELIVERY'
+ AND t.id = vSelf
+ GROUP BY t.id;
+
+ START TRANSACTION;
+
+ IF vCmrFk THEN
+ UPDATE cmr c
+ JOIN tTicket t
+ SET c.senderInstruccions = t.firstName,
+ c.truckPlate = t.numberPlate,
+ c.companyFk = t.companyFk,
+ c.addressToFk = t.addressFk,
+ c.addressFromFk = t.defaultAddressFk,
+ c.supplierFk = t.supplierFk,
+ c.ead = t.landed
+ WHERE id = vCmrFk;
+ ELSE
+ SELECT MAX(id) INTO vPreviousCmrFk FROM cmr;
+
+ INSERT INTO cmr (
+ senderInstruccions,
+ truckPlate,
+ companyFk,
+ addressToFk,
+ addressFromFk,
+ supplierFk,
+ ead
+ )
+ SELECT * FROM tTicket;
+
+ SELECT MAX(id) INTO vCurrentCmrFk FROM cmr;
+
+ IF vPreviousCmrFk <> vCurrentCmrFk THEN
+ UPDATE ticket
+ SET cmrFk = vCurrentCmrFk
+ WHERE id = vSelf;
+ END IF;
+ END IF;
+
+ COMMIT;
+ DROP TEMPORARY TABLE tTicket;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -72008,26 +72128,35 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getMovable`(vTicketFk INT, vDatedNew DATETIME, vWarehouseFk INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getMovable`(
+ vTicketFk INT,
+ vNewShipped DATETIME,
+ vWarehouseFk INT
+)
BEGIN
/**
* Cálcula el stock movible para los artículos de un ticket
- * vDatedNew debe ser menor que vDatedOld, en los otros casos se
+ * vNewShipped debe ser menor que vOldShipped, en los otros casos se
* asume que siempre es posible
*
* @param vTicketFk -> Ticket
- * @param vDatedNew -> Nueva fecha
+ * @param vNewShipped -> Nueva fecha
* @return Sales con Movible
*/
- DECLARE vDatedOld DATETIME;
- SET vDatedNew = DATE_ADD(vDatedNew, INTERVAL 1 DAY);
+ DECLARE vOldShipped DATETIME;
- SELECT t.shipped INTO vDatedOld
+ SELECT t.shipped INTO vOldShipped
FROM ticket t
WHERE t.id = vTicketFk;
- CALL item_getStock(vWarehouseFk, vDatedNew, NULL);
- CALL item_getMinacum(vWarehouseFk, vDatedNew, DATEDIFF(DATE_SUB(vDatedOld, INTERVAL 1 DAY), vDatedNew), NULL);
+ -- Añadimos un dia más para calcular el stock hasta vNewShipped inclusive
+ CALL item_getStock(vWarehouseFk, DATE_ADD(vNewShipped, INTERVAL 1 DAY), NULL);
+ CALL item_getMinacum(
+ vWarehouseFk,
+ vNewShipped,
+ DATEDIFF(DATE_SUB(vOldShipped, INTERVAL 1 DAY), vNewShipped),
+ NULL
+ );
SELECT s.id,
s.itemFk,
@@ -72042,12 +72171,14 @@ BEGIN
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
- LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk AND im.warehouseFk = vWarehouseFk
+ LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk
+ AND im.warehouseFk = vWarehouseFk
LEFT JOIN tmp.itemList il ON il.itemFk = s.itemFk
WHERE t.id = vTicketFk;
- DROP TEMPORARY TABLE IF EXISTS tmp.itemList;
- DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum;
+ DROP TEMPORARY TABLE IF EXISTS
+ tmp.itemList,
+ tmp.itemMinacum;
END ;;
DELIMITER ;
@@ -72076,32 +72207,29 @@ BEGIN
*/
CALL sale_getProblems(vIsTodayRelative);
- DROP TEMPORARY TABLE IF EXISTS tmp.ticket_problems;
- CREATE TEMPORARY TABLE tmp.ticket_problems
- (PRIMARY KEY (ticketFk))
- ENGINE = MEMORY
- SELECT
- ticketFk,
- MAX(p.isFreezed) isFreezed,
- MAX(p.risk) risk,
- MAX(p.hasHighRisk) hasHighRisk,
- MAX(p.hasTicketRequest) hasTicketRequest,
- MAX(p.itemShortage) itemShortage,
- MIN(p.isTaxDataChecked) isTaxDataChecked,
- MAX(p.hasComponentLack) hasComponentLack,
- MAX(p.isTooLittle) isTooLittle,
- MAX(p.itemDelay) itemDelay,
- MAX(p.hasRounding) hasRounding,
- MAX(p.itemLost) itemLost,
- 0 totalProblems
- FROM tmp.sale_problems p
- GROUP BY ticketFk;
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_problems
+ (PRIMARY KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT ticketFk,
+ MAX(isFreezed) isFreezed,
+ MAX(risk) risk,
+ MAX(hasHighRisk) hasHighRisk,
+ MAX(hasTicketRequest) hasTicketRequest,
+ MAX(itemShortage) itemShortage,
+ MIN(isTaxDataChecked) isTaxDataChecked,
+ MAX(hasComponentLack) hasComponentLack,
+ MAX(isTooLittle) isTooLittle,
+ MAX(itemDelay) itemDelay,
+ MAX(hasRounding) hasRounding,
+ MAX(itemLost) itemLost,
+ 0 totalProblems
+ FROM tmp.sale_problems
+ GROUP BY ticketFk;
UPDATE tmp.ticket_problems tp
- SET tp.totalProblems =
- (
+ SET tp.totalProblems = (
(tp.isFreezed) +
- IF(tp.risk, TRUE, FALSE) +
+ IF(tp.risk,TRUE, FALSE) +
(tp.hasTicketRequest) +
(tp.isTaxDataChecked = 0) +
(tp.hasComponentLack) +
@@ -72112,8 +72240,7 @@ BEGIN
(tp.itemShortage)
);
- DROP TEMPORARY TABLE
- tmp.sale_problems;
+ DROP TEMPORARY TABLE tmp.sale_problems;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -72146,124 +72273,147 @@ BEGIN
CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk);
CALL `vn`.`zoneClosure_recalc`();
- DROP TEMPORARY TABLE IF EXISTS tmp.salesToSplit;
-
- CREATE TEMPORARY TABLE tmp.salesToSplit
+ CREATE OR REPLACE TEMPORARY TABLE tmp.salesToSplit
(saleFk INT PRIMARY KEY,
ticketFk INT,
- problem VARCHAR(1)) ENGINE = MEMORY;
+ problem VARCHAR(1),
+ INDEX(ticketFk)) ENGINE = MEMORY;
+
+ CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock_byWarehouse
+ (INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT ish.itemFk itemFk,
+ SUM(ish.visible) visible,
+ s.warehouseFk warehouseFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector s ON s.id = p.sectorFk
+ GROUP BY ish.itemFk,
+ s.warehouseFk;
INSERT INTO tmp.salesToSplit(saleFk, ticketFk, problem)
- SELECT s.id, s.ticketFk, 'F'
- FROM vn.ticket t
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it on it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache
- LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache
- LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
- WHERE IFNULL(v.visible,0) < s.quantity
- AND IFNULL(av.available ,0) < s.quantity
- AND IFNULL(issw.visible, 0) < s.quantity
- AND s.isPicked = FALSE
- AND s.reserved = FALSE
- AND ic.merchandise = TRUE
- AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
- AND NOT i.generic
- AND t.warehouseFk = vWarehouseFk;
-
+ SELECT s.id, s.ticketFk, 'F'
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = i.id
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN cache.available av ON av.item_id = i.id
+ AND av.calc_id = vAvailableCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible,0) < s.quantity
+ AND IFNULL(av.available ,0) < s.quantity
+ AND IFNULL(issw.visible, 0) < s.quantity
+ AND s.isPicked = FALSE
+ AND s.reserved = FALSE
+ AND ic.merchandise = TRUE
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND NOT i.generic
+ AND t.warehouseFk = vWarehouseFk;
+
INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem)
- SELECT s.id, s.ticketFk, 'I'
- FROM vn.ticket t
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it on it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache
- LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
- WHERE IFNULL(v.visible,0) >= s.quantity
- AND IFNULL(issw.visible, 0) < s.quantity
- AND s.quantity > 0
- AND s.isPicked = FALSE
- AND s.reserved = FALSE
- AND ic.merchandise = TRUE
- AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
- AND NOT i.generic
- AND t.warehouseFk = vWarehouseFk;
-
+ SELECT s.id, s.ticketFk, 'I'
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = s.itemFk
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible,0) >= s.quantity
+ AND IFNULL(issw.visible, 0) < s.quantity
+ AND s.quantity > 0
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND NOT i.generic
+ AND t.warehouseFk = vWarehouseFk;
+
INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem)
- SELECT s.id, s.ticketFk, 'R'
- FROM vn.ticket t
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it on it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache
- LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache
- LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
- WHERE IFNULL(v.visible,0) < s.quantity
- AND IFNULL(av.available ,0) >= s.quantity
- AND IFNULL(issw.visible, 0) < s.quantity
- AND s.quantity > 0
- AND s.isPicked = FALSE
- AND s.reserved = FALSE
- AND ic.merchandise = TRUE
- AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
- AND NOT i.generic
- AND t.warehouseFk = vWarehouseFk;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.ticketsToSplit;
-
- CREATE TEMPORARY TABLE tmp.ticketsToSplit
- (ticketFk INT PRIMARY KEY,
+ SELECT s.id, s.ticketFk, 'R'
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = s.itemFk
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN cache.available av ON av.item_id = i.id
+ AND av.calc_id = vAvailableCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible,0) < s.quantity
+ AND IFNULL(av.available ,0) >= s.quantity
+ AND IFNULL(issw.visible, 0) < s.quantity
+ AND s.quantity > 0
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND NOT i.generic
+ AND t.warehouseFk = vWarehouseFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTicketsToSplit(
+ ticketFk INT PRIMARY KEY,
problems VARCHAR(100),
addressFk INT,
ipt VARCHAR(10),
- etd TIME) ENGINE = MEMORY;
+ etd TIME,
+ INDEX(addressFk)
+ ) ENGINE = MEMORY;
- INSERT INTO tmp.ticketsToSplit
- SELECT
- ss.ticketFk,
- GROUP_CONCAT(DISTINCT ss.problem ORDER BY ss.problem) problems,
- t.addressFk,
- GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
- zc.`hour` etd
- FROM tmp.salesToSplit ss
- JOIN vn.ticket t ON t.id = ss.ticketFk
- JOIN vn.sale s ON s.id = ss.saleFk
- JOIN vn.item i ON i.id = s.itemFk
- LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk
- GROUP BY ss.ticketFk;
+ INSERT INTO tTicketsToSplit
+ SELECT ss.ticketFk,
+ GROUP_CONCAT(DISTINCT ss.problem ORDER BY ss.problem) problems,
+ t.addressFk,
+ GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
+ DATE_FORMAT(IF(HOUR(t.shipped),
+ t.shipped,
+ IFNULL(zc.hour, z.HOUR)),'%H:%i') etd
+ FROM tmp.salesToSplit ss
+ JOIN ticket t ON t.id = ss.ticketFk
+ JOIN sale s ON s.id = ss.saleFk
+ JOIN item i ON i.id = s.itemFk
+ LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
+ LEFT JOIN zone z ON z.id = t.zoneFk
+ GROUP BY ss.ticketFk;
- SELECT
- ts.*,
- t.id ticketFuture,
- st.name state,
- zc.`hour` tfEtd,
- GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) tfIpt,
- st2.name tfState
- FROM tmp.ticketsToSplit ts
- LEFT JOIN vn.ticketState ts2 ON ts2.ticketFk = ts.ticketFk
- LEFT JOIN vn.state st ON st.id = ts2.stateFk
- LEFT JOIN vn.ticket t
- ON t.id != ts.ticketFk
- AND t.addressFk = ts.addressFk
- AND t.shipped BETWEEN vDated AND util.dayend(vDated)
- LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated
- LEFT JOIN vn.sale s ON s.ticketFk = t.id
- LEFT JOIN vn.item i ON i.id = s.itemFk
- LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id
- LEFT JOIN vn.state st2 ON st2.id = tst.stateFk
- WHERE (t.id IS NULL
- OR (vDated > util.VN_CURDATE())
- OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`))
+ SELECT ts.*,
+ t.id ticketFuture,
+ st.name state,
+ zc.`hour` tfEtd,
+ GROUP_CONCAT(
+ DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk
+ ) tfIpt,
+ st2.name tfState
+ FROM tTicketsToSplit ts
+ LEFT JOIN ticketState ts2 ON ts2.ticketFk = ts.ticketFk
+ LEFT JOIN `state` st ON st.id = ts2.stateFk
+ LEFT JOIN ticket t ON t.id != ts.ticketFk
+ AND t.addressFk = ts.addressFk
+ AND t.shipped BETWEEN vDated AND util.dayend(vDated)
+ LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated
+ LEFT JOIN sale s ON s.ticketFk = t.id
+ LEFT JOIN item i ON i.id = s.itemFk
+ LEFT JOIN ticketState tst ON tst.ticketFk = t.id
+ LEFT JOIN state st2 ON st2.id = tst.stateFk
+ WHERE (t.id IS NULL
+ OR (vDated > util.VN_CURDATE())
+ OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`))
AND ts.etd <= vHour
GROUP BY ts.ticketFk, t.id
ORDER BY ts.etd, ts.ticketFk;
-
+
DROP TEMPORARY TABLE
- tmp.ticketsToSplit;
+ tTicketsToSplit,
+ tItemShelvingStock_byWarehouse;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -72290,6 +72440,8 @@ BEGIN
* @return tmp.ticketAmount (ticketFk, taxableBase, tax, code)
* @return tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code) Impuesto desglosado para cada ticket.
*/
+ -- Mantengo el drop porque si no da error en los tests de back de salix
+ -- Table 'addressCompany' was locked with a READ lock and can't be updated'
DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
CREATE TEMPORARY TABLE tmp.addressCompany
(INDEX (addressFk, companyFk))
@@ -72298,24 +72450,24 @@ BEGIN
FROM tmp.ticket tmpTicket
JOIN ticket t ON t.id = tmpTicket.ticketFk;
- CALL addressTaxArea ();
-
+ CALL addressTaxArea();
+
IF vTaxArea IS NOT NULL THEN
UPDATE tmp.addressTaxArea
SET areaFk = vTaxArea;
END IF;
- /* Solo se calcula la base imponible (taxableBase) y el impuesto se calculará posteriormente
- * No se debería cambiar el sistema por problemas con los decimales
- */
- DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
- CREATE TEMPORARY TABLE tmp.ticketTax
+ -- Solo se calcula la base imponible (taxableBase) y
+ -- el impuesto se calculará posteriormente
+ -- No se debería cambiar el sistema por problemas con los decimales
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketTax
(PRIMARY KEY (ticketFk, code, rate))
ENGINE = MEMORY
SELECT * FROM (
SELECT tmpTicket.ticketFk,
bp.pgcFk,
- SUM(s.quantity * s.price * (100 - s.discount)/100 ) taxableBase,
+ SUM(s.quantity * s.price * (100 - s.discount) / 100 ) taxableBase,
pgc.rate,
tc.code,
bp.priority
@@ -72324,22 +72476,21 @@ BEGIN
JOIN item i ON i.id = s.itemFk
JOIN ticket t ON t.id = tmpTicket.ticketFk
JOIN supplier su ON su.id = t.companyFk
- JOIN tmp.addressTaxArea ata
- ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk
- JOIN itemTaxCountry itc
- ON itc.itemFk = i.id AND itc.countryFk = su.countryFk
- JOIN bookingPlanner bp
- ON bp.countryFk = su.countryFk
- AND bp.taxAreaFk = ata.areaFk
- AND bp.taxClassFk = itc.taxClassFk
+ JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk
+ AND ata.companyFk = t.companyFk
+ JOIN itemTaxCountry itc ON itc.itemFk = i.id
+ AND itc.countryFk = su.countryFk
+ JOIN bookingPlanner bp ON bp.countryFk = su.countryFk
+ AND bp.taxAreaFk = ata.areaFk
+ AND bp.taxClassFk = itc.taxClassFk
JOIN pgc ON pgc.code = bp.pgcFk
JOIN taxClass tc ON tc.id = bp.taxClassFk
GROUP BY tmpTicket.ticketFk, pgc.code, pgc.rate
- HAVING taxableBase <> 0) t3
+ HAVING taxableBase
+ ) t3
ORDER BY priority;
- DROP TEMPORARY TABLE IF EXISTS tmp.ticketServiceTax;
- CREATE TEMPORARY TABLE tmp.ticketServiceTax
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketServiceTax
(PRIMARY KEY (ticketFk, code, rate))
ENGINE = MEMORY
SELECT tt.ticketFk,
@@ -72351,35 +72502,34 @@ BEGIN
JOIN ticketService ts ON ts.ticketFk = tt.ticketFk
JOIN ticket t ON t.id = tt.ticketFk
JOIN supplier su ON su.id = t.companyFk
- JOIN tmp.addressTaxArea ata
- ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk
- JOIN bookingPlanner bp
- ON bp.countryFk = su.countryFk
- AND bp.taxAreaFk = ata.areaFk
- AND bp.taxClassFk = ts.taxClassFk
+ JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk
+ AND ata.companyFk = t.companyFk
+ JOIN bookingPlanner bp ON bp.countryFk = su.countryFk
+ AND bp.taxAreaFk = ata.areaFk
+ AND bp.taxClassFk = ts.taxClassFk
JOIN pgc ON pgc.code = bp.pgcFk
JOIN taxClass tc ON tc.id = bp.taxClassFk
GROUP BY tt.ticketFk, pgc.code
- HAVING taxableBase <> 0;
+ HAVING taxableBase;
INSERT INTO tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code)
SELECT ts.ticketFk, ts.pgcFk, ts.taxableBase, ts.rate, ts.code
FROM tmp.ticketServiceTax ts
ON DUPLICATE KEY UPDATE ticketTax.taxableBase = VALUES (taxableBase) + ticketTax.taxableBase ;
- DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount;
- CREATE TEMPORARY TABLE tmp.ticketAmount
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketAmount
(INDEX (ticketFk))
ENGINE = MEMORY
- SELECT ticketFk,
- taxableBase,
+ SELECT ticketFk,
+ taxableBase,
SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax,
code
FROM tmp.ticketTax
GROUP BY ticketFk, code;
- DROP TEMPORARY TABLE tmp.addressCompany;
- DROP TEMPORARY TABLE tmp.addressTaxArea;
+ DROP TEMPORARY TABLE
+ tmp.addressCompany,
+ tmp.addressTaxArea;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -72452,11 +72602,11 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getWithParameters`(
- vClientFk INT,
+ vClientFk INT,
vWarehouseFk INT,
- vShipped DATE,
- vAddressFk INT,
- vCompanyFk INT,
+ vShipped DATE,
+ vAddressFk INT,
+ vCompanyFk INT,
vAgencyModeFk INT,
OUT vTicketFk INT
)
@@ -72470,8 +72620,8 @@ BEGIN
* @param vAddressFk Consignatario
* @param vCompanyFk Empresa
* @param vAgencyModeFk agencia
- */
-
+ */
+
SELECT t.id INTO vTicketFk
FROM vn.ticket t
WHERE t.clientFk <=> vClientFk
@@ -72481,7 +72631,7 @@ BEGIN
AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL)
AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL)
LIMIT 1;
-
+
IF vTicketFk IS NULL THEN
CALL vn.ticket_add(
vClientFk,
@@ -72521,24 +72671,24 @@ BEGIN
DECLARE vAddressFk INT;
DECLARE vAgencyModeFk INT;
DECLARE vWarehouseFk INT;
- DECLARE vCursor CURSOR FOR
+ DECLARE vCursor CURSOR FOR
SELECT id, landed, addressFk, agencyModeFk, warehouseFk
FROM vn.ticket WHERE shipped > '2020-01-01' AND zoneFk is null;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1;
-
+
OPEN vCursor;
REPEAT
FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk;
CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE);
-
+
UPDATE vn.ticket t
JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk
SET t.zoneFk = zgs.zoneFk
WHERE t.id = vFechedTicket;
-
+
UNTIL vDone END REPEAT;
DROP TEMPORARY TABLE tmp.zoneGetShipped;
-
+
CLOSE vCursor;
END ;;
DELIMITER ;
@@ -72558,14 +72708,14 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_priceDifference`(
vTicketFk INT,
- vLanded DATE,
+ vLanded DATE,
vAddressFk INT,
vZoneFk INT,
vWarehouseFk INT)
BEGIN
/**
* Devuelve las diferencias de precio de los movimientos de un ticket.
- *
+ *
* @param vTicketFk Id del ticket
* @param vLanded Fecha de recepcion
* @param vAddressFk Id del consignatario
@@ -72574,26 +72724,26 @@ BEGIN
*/
CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk);
- SELECT s.itemFk,
- i.name,
- i.size,
- i.category,
- IFNULL(s.quantity, 0) AS quantity,
- IFNULL(s.price, 0) AS price,
+ SELECT s.itemFk,
+ i.name,
+ i.size,
+ i.category,
+ IFNULL(s.quantity, 0) AS quantity,
+ IFNULL(s.price, 0) AS price,
ROUND(SUM(tc.cost), 2) AS newPrice,
s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference,
s.id AS saleFk
FROM sale s
- JOIN item i ON i.id = s.itemFk
- JOIN ticket t ON t.id = s.ticketFk
- LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticket t ON t.id = s.ticketFk
+ LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk
AND tc.warehouseFk = vWarehouseFk
- LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
AND sc.componentFk = tc.componentFk
- LEFT JOIN `component` c ON c.id = tc.componentFk
- WHERE t.id = vTicketFk
- AND IF(sc.componentFk IS NULL
- AND c.classRate IS NOT NULL, FALSE, TRUE)
+ LEFT JOIN `component` c ON c.id = tc.componentFk
+ WHERE t.id = vTicketFk
+ AND IF(sc.componentFk IS NULL
+ AND c.classRate IS NOT NULL, FALSE, TRUE)
GROUP BY s.id ORDER BY s.id;
DROP TEMPORARY TABLE tmp.ticketComponentPreview;
@@ -72616,7 +72766,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_printLabelPrevious`(vTicketFk INT)
BEGIN
/**
- * Calls the report_print procedure and passes it
+ * Calls the report_print procedure and passes it
* the necessary parameters for printing.
*
* @param vTicketFk id ticket to print.
@@ -72624,18 +72774,18 @@ BEGIN
DECLARE vPrinterFk INT;
DECLARE vSaleGroup INT;
DECLARE vUserFk INT DEFAULT account.myUser_getId();
-
+
SELECT sg.id, o.labelerFk INTO vSaleGroup, vPrinterFk
FROM saleGroup sg
JOIN sector sc ON sc.id = sg.sectorFk
- JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk
+ JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk
JOIN sale s ON sgd.saleFk = s.id
JOIN ticket t ON s.ticketFk = t.id
JOIN operator o ON o.workerFk = vUserFk
- WHERE sc.id = o.sectorFk
+ WHERE sc.id = o.sectorFk
AND t.id = vTicketFk
LIMIT 1;
-
+
CALL report_print(
'LabelPrevia',
vPrinterFk,
@@ -72669,12 +72819,12 @@ proc:BEGIN
*/
DECLARE hasInvoice BOOL;
- SELECT COUNT(*) INTO hasInvoice
- FROM ticket
+ SELECT COUNT(*) INTO hasInvoice
+ FROM ticket
WHERE id = vSelf
AND refFk IS NOT NULL;
-
- IF hasInvoice THEN
+
+ IF hasInvoice THEN
LEAVE proc;
END IF;
@@ -72700,16 +72850,16 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_recalcComponents` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalcComponents`(vSelf INT, vOption INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalcComponents`(vSelf INT, vOption VARCHAR(25))
proc: BEGIN
/**
@@ -72762,14 +72912,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_setNextState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setNextState`(vSelf INT)
BEGIN
@@ -72789,7 +72939,7 @@ BEGIN
FROM state
WHERE id = vStateFk;
- INSERT INTO ticketTracking(stateFk, ticketFk, workerFk)
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
VALUES (vNewStateFk, vSelf, account.myUser_getId());
END ;;
DELIMITER ;
@@ -72853,14 +73003,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_setPreviousState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setPreviousState`(vTicketFk INT)
BEGIN
@@ -72885,7 +73035,7 @@ BEGIN
ORDER BY id DESC
LIMIT 1;
- INSERT INTO ticketTracking(stateFk, ticketFk, workerFk)
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT s.nextStateFk, tt.ticketFk, account.myUser_getId()
FROM ticketTracking tt
JOIN vn.state s ON tt.stateFk = s.id
@@ -72907,7 +73057,10 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setState`(vSelf INT, vStateCode VARCHAR(255) COLLATE utf8_general_ci)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setState`(
+ vSelf INT,
+ vStateCode VARCHAR(255) COLLATE utf8_general_ci
+)
BEGIN
/**
* Modifica el estado de un ticket si se cumplen las condiciones necesarias.
@@ -72919,51 +73072,44 @@ BEGIN
DECLARE vTicketStateCode VARCHAR(255);
DECLARE vCanChangeState BOOL;
DECLARE vPackedAlertLevel INT;
- DECLARE vOnPreparationAlertLevel INT;
- DECLARE vNextAlertLevel INT;
DECLARE vZoneFk INT;
- SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk
- INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk
+ SELECT s.alertLevel, s.`code`, t.zoneFk
+ INTO vticketAlertLevel, vTicketStateCode, vZoneFk
FROM state s
JOIN ticketTracking tt ON tt.stateFk = s.id
- JOIN state s2 ON s2.code = vStateCode
JOIN ticket t ON t.id = tt.ticketFk
WHERE tt.ticketFk = vSelf
ORDER BY tt.created DESC
LIMIT 1;
- SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED';
- SELECT id INTO vOnPreparationAlertLevel FROM alertLevel WHERE code = 'ON_PREPARATION';
+ SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED';
IF vStateCode = 'OK' AND vZoneFk IS NULL THEN
CALL util.throw('ASSIGN_ZONE_FIRST');
END IF;
- IF vNextAlertLevel > vticketAlertLevel && vticketAlertLevel < vOnPreparationAlertLevel THEN
- UPDATE sale
- SET originalQuantity = quantity
- WHERE ticketFk = vSelf;
- END IF;
-
- SET vCanChangeState = (vStateCode <> 'ON_CHECKING' OR vticketAlertLevel < vPackedAlertLevel)
- AND NOT (
+ SET vCanChangeState = ((
+ vStateCode <> 'ON_CHECKING' AND vStateCode <> 'CHECKED') OR
+ vticketAlertLevel < vPackedAlertLevel
+ )AND NOT (
vTicketStateCode IN ('CHECKED', 'CHECKING')
AND vStateCode IN ('PREPARED', 'ON_PREPARATION')
);
IF vCanChangeState THEN
- INSERT INTO ticketTracking (stateFk, ticketFk, workerFk)
+ INSERT INTO ticketTracking (stateFk, ticketFk, userFk)
SELECT id, vSelf, account.myUser_getId()
FROM state
WHERE `code` = vStateCode COLLATE utf8_unicode_ci;
-
+
IF vStateCode = 'PACKED' THEN
CALL ticket_doCmr(vSelf);
END IF;
ELSE
CALL util.throw('INCORRECT_TICKET_STATE');
END IF;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -72997,40 +73143,39 @@ proc:BEGIN
SELECT COUNT(*) INTO vProblemLines
FROM tmp.salesToSplit
WHERE ticketFk = vTicketFk;
-
+
SELECT count(*) INTO vTotalLines
- FROM vn.sale s
+ FROM vn.sale s
WHERE s.ticketFk = vTicketFk;
-
+
SET vHasFullProblem = (vTotalLines = vProblemLines);
-- Ticket completo
IF vHasFullProblem THEN
-
+
UPDATE vn.ticket
SET landed = vDated + INTERVAL 1 DAY,
shipped = vDated,
nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname )
WHERE id = vTicketFk;
-
- SELECT CONCAT("Se ha cambiado el ticket ", vTicketFk, " al dia ", vDated);
+
+ SELECT "moved" message, NULL ticketFuture;
LEAVE proc;
-
+
END IF;
-- Ticket a futuro existe
IF vTicketFutureFk THEN
-
- UPDATE vn.sale s
+
+ UPDATE vn.sale s
JOIN tmp.salesToSplit ss ON s.id = ss.saleFk
SET s.ticketFk = vTicketFutureFk,
s.concept = CONCAT('(s) ', s.concept)
WHERE ss.ticketFk = vTicketFk;
-
- SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk,
- " al ticket existente ", vTicketFutureFk,"(", vDated,")");
+
+ SELECT "future" message, NULL ticketFuture;
LEAVE proc;
-
+
END IF;
-- Ticket nuevo
@@ -73042,19 +73187,18 @@ proc:BEGIN
t.landed = vDated + INTERVAL 1 DAY,
t.shipped = vDated,
t.agencyModeFk = pc.defautlAgencyMode,
- t.zoneFk = pc.defaultZone
+ t.zoneFk = pc.defaultZone
WHERE t.id = vTicketFutureFk;
-
- UPDATE vn.sale s
- JOIN tmp.salesToSplit sts ON sts.saleFk = s.id
+
+ UPDATE vn.sale s
+ JOIN tmp.salesToSplit sts ON sts.saleFk = s.id
SET s.ticketFk = vTicketFutureFk,
s.concept = CONCAT('(s) ', s.concept)
WHERE sts.ticketFk = vTicketFk;
CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING');
- SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk,
- " al nuevo ticket ", vTicketFutureFk,"(", vDated,")");
+ SELECT "new" message,vTicketFutureFk ticketFuture;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -73162,7 +73306,7 @@ proc:BEGIN
SELECT itemPackingTypeFk INTO vItemPackingTypeFk
FROM tmp.saleGroup sg
WHERE NOT ISNULL(sg.itemPackingTypeFk)
- ORDER BY sg.totalLitros
+ ORDER BY sg.itemPackingTypeFk
LIMIT 1;
UPDATE vn.sale s
@@ -73192,43 +73336,43 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitPackingComplete`(vTicketFk INT, vSectorFk INT)
BEGIN
-
+
DECLARE vNeedToSplit BOOLEAN;
DECLARE vNewTicketFk INT;
-
+
DROP TEMPORARY TABLE IF EXISTS tmpSale;
-
+
CREATE TEMPORARY TABLE tmpSale
SELECT DISTINCT s.id
- FROM vn.ticket t
+ FROM vn.ticket t
JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.item i ON i.id = s.itemFk
LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = vSectorFk
- JOIN vn.packagingConfig pc
+ JOIN vn.packagingConfig pc
WHERE t.id = vTicketFk
AND ( s.quantity MOD IFNULL(iss.packing,1) != 0
- OR
+ OR
IFNULL(iss.packing,1) = 1
- OR
+ OR
i.`size` <= pc.previousPreparationMinimumSize
);
-
- SELECT COUNT(*)
+
+ SELECT COUNT(*)
INTO vNeedToSplit
- FROM tmpSale;
-
+ FROM tmpSale;
+
IF vNeedToSplit THEN
-
+
CALL vn.ticket_Clone(vTicketFk, vNewTicketFk);
-
+
UPDATE vn.sale s
- JOIN vn.tmpSale ts ON ts.id = s.id
+ JOIN vn.tmpSale ts ON ts.id = s.id
SET s.ticketFk = vNewTicketFk;
-
+
END IF;
-
+
DROP TEMPORARY TABLE tmpSale;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -73259,7 +73403,7 @@ BEGIN
WHERE ot.description = 'Peso Aduana'
AND t.clientFk = vClientFk
AND t.shipped BETWEEN vDated AND util.dayend(vDated);
-
+
SELECT sum(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight)) INTO vTheorycalWeight
FROM vn.ticket t
JOIN vn.sale s ON s.ticketFk = t.id
@@ -73268,9 +73412,9 @@ BEGIN
JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk
WHERE t.clientFk = vClientFk
AND t.shipped BETWEEN vDated AND util.dayend(vDated);
-
+
SET vRatio = vRealWeight / vTheorycalWeight;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketWeight;
CREATE TEMPORARY TABLE tmp.ticketWeight
@@ -73291,7 +73435,7 @@ BEGIN
AND t.shipped BETWEEN vDated AND util.dayend(vDated)
GROUP BY ib.ediBotanic, o.code;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -73322,7 +73466,7 @@ BEGIN
(INDEX (departmentFk))
SELECT dated,
businessFk,
- userFk,
+ sub.id userFk,
departmentFk,
hourStart,
hourEnd,
@@ -73350,8 +73494,7 @@ BEGIN
at2.permissionRate,
at2.discountRate,
ct.hoursWeek hoursWeek,
- at2.isAllowedToWork,
- u.userFk
+ at2.isAllowedToWork
FROM time t
LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo)
LEFT JOIN worker w ON w.id = b.workerFk
@@ -73411,18 +73554,18 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateAll`(vDatedFr
BEGIN
/**
- * @param vDatedFrom Fecha desde
+ * @param vDatedFrom Fecha desde
* @param vDatedTo Fecha hasta
*/
- CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
+ CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
SELECT w.id userFk
FROM vn.worker w;
-
+
CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo);
DROP TEMPORARY TABLE tmp.`user`;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -73442,21 +73585,21 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
/**
- * @param vDepartmentFk
+ * @param vDepartmentFk
* @param vDatedFrom workerTimeControl
* @param vDatedTo workerTimeControl
*/
DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
-
+
CREATE TEMPORARY TABLE tmp.`user`
SELECT DISTINCT b.workerFk userFk
- FROM business AS b
- WHERE (b.started BETWEEN vDatedFrom AND vDatedTo
+ FROM business AS b
+ WHERE (b.started BETWEEN vDatedFrom AND vDatedTo
OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo
OR (b.started <= vDatedFrom AND b.ended >= vDatedTo)
) AND b.departmentFk = vDepartmentFk
ORDER BY b.ended DESC;
-
+
CALL timeBusiness_calculate(vDatedFrom, vDatedTo);
DROP TEMPORARY TABLE tmp.`user`;
@@ -73481,19 +73624,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByUser`(vUser
BEGIN
/**
- * @param vUserFk
+ * @param vUserFk
* @param vDatedFrom workerTimeControl
* @param vDatedTo workerTimeControl
*/
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
-
+
CREATE TEMPORARY TABLE tmp.`user`
SELECT id userFk
- FROM account.user
- WHERE id = vUserFk;
+ FROM account.user
+ WHERE id = vUserFk;
CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo);
-
+
DROP TEMPORARY TABLE tmp.`user`;
END ;;
@@ -73520,14 +73663,14 @@ BEGIN
* @param vDatedFrom Fecha desde
* @param vDatedTo Fecha hasta
*/
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
SELECT w.id userFk
FROM worker w
WHERE w.id = vWorkerFk;
-
+
CALL timeBusiness_calculate(vDatedFrom, vDatedTo);
-
+
DROP TEMPORARY TABLE tmp.`user`;
END ;;
@@ -73547,202 +73690,195 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculate`(
- vDatedFrom DATETIME,
+ vDatedFrom DATETIME,
vDatedTo DATETIME)
BEGIN
/*
+ * Agrupa por trabajador y día, el tiempo de trabajo y descanso retribuido(si tiene).
+ * Los registros horarios incorrectos (tmp.timeControlError) no se considerarán.
+ * Si un trabajador ha trabajado más de un cierto umbral de tiempo (vTimeToBreakTime)
+ * y no ha tenido descansos que superen un parámetro determinado(vMaxTimeToBreak),
+ * se le añadirá un tiempo de descanso (vBreakTime) a sus horas trabajadas.
+ * El tiempo de descanso solo se añade si el trabajador realmente disfrutó del descanso.
+ * Si disfrutó de menos tiempo de descanso, solo se añade el tiempo que disfrutó.
+ *
* @param vDatedFrom
- * @param vDatedTo
- * Cálculo de horas trabajadas por empleado y día,
- * sin tener en cuenta los días con fichadas incorrectas (tabla tmp.timeControlError)
- * En el caso de haber hecho descanso y trabajado un mínimo de tiempo (vTimeToBreakTime),
- * se añade al tiempo de trabajo efectivo el descanso (vBreakTime)
- * @return tmp.timeControlCalculate
+ * @param vDatedTo
+ *
+ * @return tmp.timeControlCalculate
* (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed)
*/
- DECLARE vHourToSeconds INTEGER;
+ DECLARE vHourSeconds INTEGER;
DECLARE vDatedFromYesterday DATETIME;
DECLARE vDatedToTomorrow DATETIME;
DECLARE vTimeToBreakTime INT;
DECLARE vBreakTime INT;
+ DECLARE vMaxTimeToBreak INT;
SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY)
INTO vDatedFromYesterday, vDatedToTomorrow;
- SELECT timeToBreakTime, breakTime INTO vTimeToBreakTime, vBreakTime
+ SELECT timeToBreakTime, breakTime, maxTimeToBreak, TIME_TO_SEC('01:00:00')
+ INTO vTimeToBreakTime, vBreakTime, vMaxTimeToBreak, vHourSeconds
FROM workerTimeControlConfig
LIMIT 1;
- CALL timeControl_getError(vDatedFrom, vDatedTo);
+ CALL timeControl_getError(vDatedFromYesterday, vDatedToTomorrow);
- DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControl;
- CREATE TEMPORARY TABLE tmp.workerTimeControl
- (INDEX (userFk), INDEX (timed))
- ENGINE = MEMORY
- SELECT DISTINCT(wtc.id),
- wtc.userFk,
+ CREATE OR REPLACE TEMPORARY TABLE tmp.workerTimeControl
+ (INDEX(userFk, timed), INDEX(timed), INDEX(direction))
+ ENGINE = MEMORY
+ SELECT wtc.userFk,
wtc.timed,
+ DATE(wtc.timed) dated,
wtc.direction,
TRUE isReal
FROM workerTimeControl wtc
- JOIN tmp.`user` w ON w.userFk = wtc.userFk
+ JOIN tmp.`user` u ON u.userFk = wtc.userFk
+ LEFT JOIN (
+ SELECT wtc.userFk, MIN(wtc.timed) firstIn
+ FROM workerTimeControl wtc
+ JOIN tmp.`user` u ON u.userFk = wtc.userFk
+ LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
+ WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ AND wtc.direction = 'in'
+ AND tce.id IS NULL
+ GROUP BY userFk
+ ) fi ON wtc.userFk = fi.userFk
+ LEFT JOIN (
+ SELECT wtc.userFk, MAX(wtc.timed) lastOut
+ FROM workerTimeControl wtc
+ JOIN tmp.`user` u ON u.userFk = wtc.userFk
+ LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
+ WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ AND wtc.direction = 'out'
+ AND tce.id IS NULL
+ GROUP BY userFk
+ ) lo ON wtc.userFk = lo.userFk
LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
- WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ WHERE wtc.timed BETWEEN fi.firstIn AND lo.lastOut
AND tce.id IS NULL
- ORDER BY wtc.userFk, wtc.timed ASC;
+ ORDER BY wtc.userFk, wtc.timed;
- SELECT MAX(id) INTO @vCont
- FROM tmp.workerTimeControl;
+ CREATE OR REPLACE TEMPORARY TABLE tmp.wtcToinsert
+ (INDEX(timed))
+ ENGINE = MEMORY
+ WITH wtc AS(
+ SELECT timed,
+ userFk,
+ dated,
+ direction,
+ LEAD(dated) OVER
+ (PARTITION BY userFk, dated ORDER BY timed) nextDay,
+ LEAD(userFk) OVER
+ (PARTITION BY userFk ORDER BY timed) nextUserFk,
+ ROW_NUMBER() OVER (ORDER BY userFk, timed) MOD 2 isOdd
+ FROM tmp.workerTimeControl
+ WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ ORDER BY userFk, timed
+ ), wtcToinsert AS(
+ SELECT userFk,
+ dated,
+ IF(userFk = nextUserFk
+ AND nextDay IS NULL
+ AND isOdd
+ AND direction <> 'out', TRUE, FALSE) outNextDay,
+ IF(userFk = nextUserFk
+ AND nextDay IS NULL
+ AND NOT isOdd
+ AND direction <> 'out', TRUE, FALSE) outNextDayWhitBreak
+ FROM wtc
+ HAVING outNextDay OR outNextDayWhitBreak
+ )SELECT userFk, util.dayEnd(dated) timed, 'out' direction
+ FROM wtcToinsert
+ WHERE outNextDay
+ UNION ALL
+ SELECT userFk, dated + INTERVAL 1 DAY, 'in'
+ FROM wtcToinsert
+ WHERE outNextDay
+ UNION ALL
+ SELECT userFk, util.dayEnd(dated) - INTERVAL 1 SECOND, 'middle'
+ FROM wtcToinsert
+ WHERE outNextDayWhitBreak
+ UNION ALL
+ SELECT userFk, util.dayEnd(dated), 'out'
+ FROM wtcToinsert
+ WHERE outNextDayWhitBreak
+ UNION ALL
+ SELECT userFk, dated + INTERVAL 1 DAY, 'in'
+ FROM wtcToinsert
+ WHERE outNextDayWhitBreak
+ UNION ALL
+ SELECT userFk, dated + INTERVAL 1 DAY + INTERVAL 1 SECOND, 'middle'
+ FROM wtcToinsert
+ WHERE outNextDayWhitBreak;
- DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux;
- CREATE TEMPORARY TABLE tmp.workerTimeControlAux (
- `id` int(11) ,
- `userFk` int(10) unsigned ,
- `timed` datetime,
- `direction` enum('in', 'out','middle')
- ) ENGINE=MEMORY;
+ INSERT INTO tmp.workerTimeControl (userFk, timed, dated, direction, isReal)
+ SELECT userFk, timed, DATE(timed), direction, FALSE
+ FROM tmp.wtcToinsert;
- SET @counter := 0;
- SET @vIsOdd := FALSE;
-
- -- Cambio de dia en medio de un descanso
- INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
- SELECT @vCont:= @vCont + 1 id,
- userFk,
- util.dayEnd(dated) timed,
- 'middle' direction
- FROM(SELECT wtc.userFk,
- DATE(@lastTimed) dated,
- (@vIsOdd := NOT @vIsOdd) isOdd,
- IF(@vIsOdd AND wtc.direction = 'middle'
- AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak,
- @lastTimed := wtc.timed
- FROM tmp.workerTimeControl wtc
- ORDER BY wtc.userFk, wtc.timed
- LIMIT 10000000000000000000
- )sub
- WHERE hasBreak;
-
- SET @counter := 0;
- SET @vIsOdd := FALSE;
-
- INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
- SELECT @vCont:= @vCont + 1,
- userFk,
- DATE_ADD(sub.dated, INTERVAL 1 DAY),
- 'middle'
- FROM(SELECT wtc.userFk,
- DATE(@lastTimed) dated,
- (@vIsOdd := NOT @vIsOdd) isOdd,
- IF(@vIsOdd AND wtc.direction = 'middle'
- AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak,
- @lastTimed := wtc.timed
- FROM tmp.workerTimeControl wtc
- ORDER BY wtc.userFk, wtc.timed
- LIMIT 10000000000000000000
- )sub
- WHERE hasBreak;
-
- -- Cambio de dia
- INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
- SELECT @vCont:= @vCont + 1 id,
- sub.userFk,
- util.dayEnd(sub.dated) timed,
- 'out' direction
- FROM (SELECT MAX(wtc.timed) timed, wtc.userFk, date(wtc.timed) dated
- FROM workerTimeControl wtc
- JOIN tmp.`user` w ON w.userFk = wtc.userFk
- LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
- WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
- AND tce.id IS NULL
- GROUP BY wtc.userFk, DATE(wtc.timed)
- ) sub
- JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed
- AND wtc.userFk = sub.userFk
- WHERE wtc.direction <> 'out';
-
- INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
- SELECT @vCont:= @vCont + 1, sub.userFk, DATE_ADD(sub.dated, INTERVAL 1 DAY), 'in'
- FROM (SELECT MAX(wtc.timed) timed, wtc.userFk, date(wtc.timed) dated
- FROM workerTimeControl wtc
- JOIN tmp.`user` w ON w.userFk = wtc.userFk
- LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
- WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
- AND tce.id IS NULL
- GROUP BY wtc.userFk, DATE(wtc.timed)
- ) sub
- JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed
- AND wtc.userFk = sub.userFk
- WHERE wtc.direction <> 'out';
-
- INSERT INTO tmp.workerTimeControl (id, userFk, timed, direction, isReal)
- SELECT id, userFk, timed, direction, FALSE FROM tmp.workerTimeControlAux;
-
- SET vHourToSeconds = 3600;
- SET @vIsOdd := TRUE;
- SET @vDated := 0;
- SET @vLastTimed := 0;
- SET @vPreviousTimed := 0;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.workerBreakDays;
- CREATE TEMPORARY TABLE tmp.workerBreakDays
- (INDEX (userFk), INDEX (dated))
- ENGINE = MEMORY
- SELECT sub.userFk,
- sub.dated
- FROM (SELECT (@vIsOdd := NOT @vIsOdd),
- IF(wtc.direction = 'in', @vIsOdd := TRUE, NULL),
- IF(@vIsOdd, @vLastTimed := UNIX_TIMESTAMP(wtc.timed), NULL),
- IF(@vIsOdd, 0, UNIX_TIMESTAMP(wtc.timed) - @vLastTimed) timeWork,
- IF(direction='in', @vDated := DATE(wtc.timed), @vDated) dated,
- wtc.userFk
- FROM tmp.workerTimeControl wtc
- ORDER BY wtc.userFk, wtc.timed, wtc.id
- LIMIT 10000000000000000000
- )sub
- GROUP BY sub.userFk, sub.dated
- HAVING SUM(sub.timeWork) >= vTimeToBreakTime;
-
- SET @vIsOdd := TRUE;
- SET @vDated := 0;
- SET @vLastTimed := 0;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux2;
- CREATE TEMPORARY TABLE tmp.workerTimeControlAux2
- SELECT *
- FROM tmp.workerTimeControl
- WHERE timed BETWEEN vDatedFromYesterday AND vDatedTo
- ORDER BY userFk, timed, id;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate;
+ SET @accumulatedForBreakTime = 0;
+ SET @oldrealDay = NULL;
CREATE OR REPLACE TEMPORARY TABLE tmp.timeControlCalculate
- (INDEX (userFk, dated))
- ENGINE = MEMORY
- SELECT sub.userFk,
- sub.dated,
- IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork) timeWorkSeconds,
- SEC_TO_TIME(IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) timeWorkSexagesimal,
- (IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) / vHourToSeconds timeWorkDecimal,
- CAST(GROUP_CONCAT(DATE_FORMAT(sub.realTimed, "%H:%i")
- ORDER BY sub.timed ASC SEPARATOR ' - ') AS CHAR(256)) timed
- FROM (SELECT (@vIsOdd := NOT @vIsOdd),
- IF(direction='in', @vIsOdd := TRUE, 0),
- IF(@vIsOdd, @vLastTimed := UNIX_TIMESTAMP(timed), 0),
- IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed) - @vLastTimed) timeWork,
- timed,
- userFk,
- DATE(timed) dated,
- IF(isReal, timed, NULL) realTimed
- FROM tmp.workerTimeControlAux2
- )sub
- LEFT JOIN tmp.workerBreakDays wb ON wb.userFk = sub.userFk AND wb.dated = sub.dated
- WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo
- GROUP BY sub.userFk, sub.dated;
+ WITH workerTimed AS (
+ SELECT
+ userFk,
+ dated,
+ timed,
+ (direction ='in' AND isReal) breakPoint,
+ SUM(CASE WHEN (direction ='in' AND isReal) THEN TRUE ELSE FALSE END)
+ OVER (ORDER BY userFk, timed) AS realDay,
+ TIMESTAMPDIFF(SECOND, LAG(timed)
+ OVER (PARTITION BY userFk, dated ORDER BY timed), timed) gapTime,
+ ROW_NUMBER()
+ OVER (PARTITION BY userFk, dated ORDER BY timed) MOD 2 isOdd
+ FROM tmp.workerTimeControl
+ WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ ), accumulated AS (
+ SELECT SUM(IF(isOdd, 0, gapTime))
+ OVER (PARTITION BY userFk,dated ORDER BY userFk,timed) accumulatedWorkTime,
+ SUM(IF(NOT isOdd OR breakPoint OR gapTime >= vMaxTimeToBreak OR gapTime IS NULL, 0, gapTime))
+ OVER (PARTITION BY realDay ORDER BY realDay,timed) accumulatedBreakTime,
+ IF(realDay <> @oldrealDay OR (isOdd AND gapTime >= vMaxTimeToBreak),
+ @accumulatedForBreakTime := 0,
+ @accumulatedForBreakTime := @accumulatedForBreakTime +
+ IF(isOdd, 0, gapTime )) accumulatedForBreakTime,
+ @oldrealDay := realDay,
+ userFk,
+ dated,
+ realDay
+ FROM workerTimed
+ ), totalWorked AS (
+ SELECT userFk,
+ dated,
+ MAX(accumulatedWorkTime) +
+ IF(MAX(accumulatedForBreakTime) + LEAST(vBreakTime, MAX(accumulatedBreakTime)) >= vTimeToBreakTime,
+ LEAST(vBreakTime, MAX(accumulatedBreakTime)),
+ 0) timeWorkSeconds
+ FROM accumulated
+ GROUP BY userFk, dated
+ )SELECT tw.userFk,
+ tw.dated,
+ timeWorkSeconds,
+ SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal,
+ timeWorkSeconds / vHourSeconds timeWorkDecimal,
+ sub.tableTimed
+ FROM totalWorked tw
+ JOIN (
+ SELECT userFk,
+ dated,
+ GROUP_CONCAT(DATE_FORMAT(timed, "%H:%i") ORDER BY timed ASC
+ SEPARATOR ' - ')tableTimed
+ FROM tmp.workerTimeControl
+ WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ AND isReal
+ GROUP BY userFk, dated
+ )sub ON sub.dated = tw.dated
+ AND sub.userFk = tw.userFk
+ WHERE tw.dated BETWEEN vDatedFrom AND vDatedTo;
- DROP TEMPORARY TABLE tmp.workerBreakDays;
DROP TEMPORARY TABLE tmp.timeControlError;
- DROP TEMPORARY TABLE tmp.workerTimeControlAux;
- DROP TEMPORARY TABLE tmp.workerTimeControlAux2;
+ DROP TEMPORARY TABLE tmp.wtcToinsert;
DROP TEMPORARY TABLE tmp.workerTimeControl;
END ;;
DELIMITER ;
@@ -73768,14 +73904,14 @@ BEGIN
* @param vDatedTo Fecha hasta
*/
- CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
+ CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
SELECT w.id userFk
FROM vn.worker w;
-
+
CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
DROP TEMPORARY TABLE tmp.`user`;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -73795,21 +73931,21 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
/**
- * @param vDepartmentFk
+ * @param vDepartmentFk
* @param vDatedFrom workerTimeControl
* @param vDatedTo workerTimeControl
*/
DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
-
+
CREATE TEMPORARY TABLE tmp.`user`
SELECT DISTINCT b.workerFk userFk
- FROM business AS b
- WHERE (b.started BETWEEN vDatedFrom AND vDatedTo
+ FROM business AS b
+ WHERE (b.started BETWEEN vDatedFrom AND vDatedTo
OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo
OR (b.started <= vDatedFrom AND b.ended >= vDatedTo)
) AND b.departmentFk = vDepartmentFk
ORDER BY b.ended DESC;
-
+
CALL timeControl_calculate(vDatedFrom, vDatedTo);
DROP TEMPORARY TABLE tmp.`user`;
@@ -73834,19 +73970,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByUser`(vUserF
BEGIN
/**
- * @param vUserFk
+ * @param vUserFk
* @param vDatedFrom workerTimeControl
* @param vDatedTo workerTimeControl
*/
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
-
+
CREATE TEMPORARY TABLE tmp.`user`
SELECT id userFk
- FROM account.user
- WHERE id = vUserFk;
+ FROM account.user
+ WHERE id = vUserFk;
CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
-
+
DROP TEMPORARY TABLE tmp.`user`;
END ;;
@@ -73873,19 +74009,17 @@ BEGIN
* @param vDatedFrom workerTimeControl
* @param vDatedTo workerTimeControl
*/
+ DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
- DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
-
- CREATE TEMPORARY TABLE tmp.`user`
+ CREATE TEMPORARY TABLE tmp.`user`
SELECT u.id userFk
FROM account.user u
- JOIN vn.worker w ON w.userFk = u.id
- WHERE w.id = vWorkerFk;
+ JOIN vn.worker w ON w.id = u.id
+ WHERE w.id = vWorkerFk;
- CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
-
- DROP TEMPORARY TABLE tmp.`user`;
+ CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
+ DROP TEMPORARY TABLE tmp.`user`;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -73906,12 +74040,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_getError`(vDatedFrom DA
BEGIN
/*
* @param vDatedFrom
- * @param vDatedTo
+ * @param vDatedTo
* @table tmp.`user`(userFk)
* Fichadas incorrectas de las cuales no se puede calcular horas trabajadas
* @return tmp.timeControlError (id)
*/
- DECLARE vDayMaxTime INTEGER;
+ DECLARE vDayMaxTime INTEGER;
SET @journeyCounter := 0;
SET @lastUserFk := NULL;
@@ -73919,16 +74053,16 @@ BEGIN
SELECT dayMaxTime INTO vDayMaxTime
FROM workerTimeControlConfig LIMIT 1;
- DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
- CREATE TEMPORARY TABLE tmp.timeControl
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
+ CREATE TEMPORARY TABLE tmp.timeControl
(INDEX(id), INDEX(journeyCounter))
ENGINE = MEMORY
SELECT sub.id,
- sub.direction,
+ sub.direction,
sub.timed,
IF(sub.direction = 'in' OR @hasOut OR sub.userFk <> @lastUserFk, @journeyCounter := @journeyCounter + 1, @journeyCounter) journeyCounter,
- @lastUserFk := sub.userFk workerFk,
- IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE)
+ @lastUserFk := sub.userFk workerFk,
+ IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE)
FROM (
SELECT DISTINCT wtc.id,
wtc.direction,
@@ -73939,59 +74073,36 @@ BEGIN
WHERE wtc.timed BETWEEN DATE_SUB(vDatedFrom, INTERVAL 1 DAY) AND DATE_ADD(vDatedTo, INTERVAL 1 DAY)
ORDER BY wtc.userFk, wtc.timed
) sub;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
CREATE TEMPORARY TABLE tmp.timeControlAux
(INDEX(id), INDEX(journeyCounter))
ENGINE = MEMORY
SELECT * FROM tmp.timeControl;
- DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError;
- CREATE TEMPORARY TABLE tmp.timeControlError
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError;
+ CREATE TEMPORARY TABLE tmp.timeControlError
(INDEX(id))
ENGINE = MEMORY
- SELECT id
+ SELECT id
FROM tmp.timeControlAux tca
JOIN (
- SELECT journeyCounter,
+ SELECT journeyCounter,
UNIX_TIMESTAMP(MAX(timed)) - UNIX_TIMESTAMP(MIN(timed)) timeWork,
- SUM(direction = 'in') totalIn,
+ SUM(direction = 'in') totalIn,
SUM(direction = 'out') totalOut,
timed
FROM tmp.timeControl
GROUP BY journeyCounter
- HAVING COUNT(*) MOD 2 = 1
- OR totalIn <> 1
- OR totalOut <> 1
+ HAVING COUNT(*) MOD 2 = 1
+ OR totalIn <> 1
+ OR totalOut <> 1
OR timeWork >= vDayMaxTime
)sub ON sub.journeyCounter = tca.journeyCounter
WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo;
- DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
- DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `timeWorkerControl_check` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `timeWorkerControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100))
-proc: BEGIN
-/**
- * deprecated call workerTimeControl_check
- */
-CALL vn.workerTimeControl_check(vUserFk,vDated,vTabletFk);
-
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -74036,42 +74147,42 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travelVolume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume`(vTravelFk INT)
BEGIN
-
- SELECT w1.name AS ORI,
- w2.name AS DES,
+
+ SELECT w1.name AS ORI,
+ w2.name AS DES,
tr.shipped shipment,
tr.landed landing,
- a.name Agencia,
+ a.name Agencia,
s.name Proveedor,
e.id Id_Entrada,
e.invoiceNumber Referencia,
CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
- vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC,
+ vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC,
CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
- vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais
- FROM vn.buy b
- JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.supplier s ON s.id = e.supplierFk
- JOIN vn.travel tr ON tr.id = e.travelFk
+ vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais
+ FROM vn.buy b
+ JOIN vn.entry e ON e.id = b.entryFk
+ JOIN vn.supplier s ON s.id = e.supplierFk
+ JOIN vn.travel tr ON tr.id = e.travelFk
JOIN vn.agencyMode a ON a.id = tr.agencyModeFk
- JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk
- JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk
- JOIN vn.volumeConfig vc
- JOIN vn.item i ON i.id = b.itemFk
+ JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk
+ JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk
+ JOIN vn.volumeConfig vc
+ JOIN vn.item i ON i.id = b.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
WHERE tr.id = vTravelFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -74079,21 +74190,21 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travelVolume_get` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume_get`(vFromDated DATE, vToDated DATE, vWarehouseFk INT)
BEGIN
SELECT tr.landed Fecha,
a.name Agencia,
count(DISTINCT e.id) numEntradas,
- FLOOR(sum(item_getVolume(b.itemFk, b.packageFk) * b.stickers / 1000000 )) AS m3
+ FLOOR(sum(item_getVolume(b.itemFk, b.packagingFk) * b.stickers / 1000000 )) AS m3
FROM vn.travel tr
JOIN vn.agencyMode a ON a.id = tr.agencyModeFk
JOIN vn.entry e ON e.travelFk = tr.id
@@ -74127,11 +74238,11 @@ BEGIN
* @param vShipped The shipment date
* @param vLanded The landing date
*/
-
+
IF vLanded < vShipped THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Landing cannot be lesser than shipment';
- END IF;
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -74195,7 +74306,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_checkWarehouseIsFeedStock`(v
proc: BEGIN
/*
* Check that the warehouse is not Feed Stock
- *
+ *
* @vWarehouseFk param warehouse id
*/
IF vWarehouseFk IS NULL THEN
@@ -74294,11 +74405,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`(
BEGIN
/**
* Clona un travel junto con sus entradas y compras
- *
* @param vTravelFk travel plantilla a clonar
* @param vDateStart fecha del shipment del nuevo travel
* @param vDateEnd fecha del landing del nuevo travel
- * @param vWarehouseOutFk fecha del salida del nuevo travel
+ * @param vWarehouseOutFk warehouse del salida del nuevo travel
* @param vWarehouseInFk warehouse de landing del nuevo travel
* @param vRef referencia del nuevo travel
* @param vAgencyModeFk del nuevo travel
@@ -74308,6 +74418,7 @@ BEGIN
DECLARE vEvaNotes VARCHAR(255);
DECLARE vDone BOOL;
DECLARE vAuxEntryFk INT;
+ DECLARE vTx BOOLEAN DEFAULT @@in_transaction;
DECLARE vRsEntry CURSOR FOR
SELECT e.id
FROM entry e
@@ -74318,11 +74429,11 @@ BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
- ROLLBACK;
+ CALL util.tx_rollback(vTx);
RESIGNAL;
END;
- START TRANSACTION;
+ CALL util.tx_start(vTx);
INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, cargoSupplierFk, kg,clonedFrom)
SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3,cargoSupplierFk, kg,vTravelFk
@@ -74345,7 +74456,7 @@ BEGIN
END IF;
CALL entry_cloneHeader(vAuxEntryFk, vNewEntryFk, vNewTravelFk);
- CALL entry_copyBuys(vAuxEntryFk, vNewEntryFk);
+ CALL entry_copyBuys(vAuxEntryFk, vNewEntryFk);
SELECT evaNotes INTO vEvaNotes
FROM entry
@@ -74359,60 +74470,7 @@ BEGIN
SET @isModeInventory = FALSE;
CLOSE vRsEntry;
- COMMIT;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `travel_doRecalc` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_doRecalc`()
-BEGIN
-/**
- * Recounts the number of entries of changed travels.
- */
- DECLARE vDone BOOL;
- DECLARE vTravelFk INT;
- DECLARE vTotalEntries INT;
-
- DECLARE cCur CURSOR FOR
- SELECT travelFk FROM travelRecalc;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET vDone = TRUE;
-
- OPEN cCur;
-
- myLoop: LOOP
- SET vDone = FALSE;
- FETCH cCur INTO vTravelFk;
-
- IF vDone THEN
- LEAVE myLoop;
- END IF;
-
- SELECT COUNT(*) INTO vTotalEntries
- FROM entry
- WHERE travelFk = vTravelFk;
-
- UPDATE travel
- SET totalEntries = vTotalEntries
- WHERE id = vTravelFk;
-
- DELETE FROM travelRecalc WHERE travelFk = vTravelFk;
- END LOOP;
-
- CLOSE cCur;
+ CALL util.tx_commit(vTx);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -74421,7 +74479,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `travel_getEntriesMissingPackage` */;
+/*!50003 DROP PROCEDURE IF EXISTS `travel_doRecalc` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@@ -74429,6 +74487,175 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_doRecalc`()
+proc: BEGIN
+/**
+* Recounts the number of entries of changed travels.
+*/
+ DECLARE vTravelFk INT;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ DO RELEASE_LOCK('vn.ticket_doRecalc');
+ END;
+
+ IF !GET_LOCK('vn.travel_doRecalc', 0) THEN
+ LEAVE proc;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTravel
+ ENGINE = MEMORY
+ SELECT travelFk FROM travelRecalc;
+
+ UPDATE travel t
+ JOIN tTravel tt ON tt.travelFk = t.id
+ SET t.totalEntries = (
+ SELECT COUNT(e.id)
+ FROM entry e
+ WHERE e.travelFk = t.id
+ );
+
+ DELETE tr FROM travelRecalc tr JOIN tTravel t ON tr.travelFk = t.travelFk;
+ DROP TEMPORARY TABLE tTravel;
+ DO RELEASE_LOCK('vn.travel_doRecalc');
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `travel_getDetailFromContinent` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_getDetailFromContinent`(
+ vContinentFk INT
+)
+BEGIN
+/**
+ * Devuelve los detalles de los vuelos que tienen
+ * un almacén de salida de un continente.
+ *
+ * @param vContinentFk Id de continente
+ */
+ DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK;
+ SELECT IFNULL(CONCAT(" ", entryFk), travelFk) travelAndEntry,
+ sub.*
+ FROM (
+ SELECT tr.id travelFk,
+ NULL entryFk,
+ TRUE isTravel,
+ am.name agency,
+ tr.ref,
+ tr.shipped,
+ wOut.name originBoxes,
+ tr.landed,
+ wIn.name destination,
+ SUM(b.stickers) stickers,
+ NULL evaNotes,
+ tr.kg,
+ CAST(SUM(b.weight * b.stickers) AS INT) loadedkg,
+ CAST(
+ SUM(vc.aerealVolumetricDensity *
+ b.stickers *
+ IF(p.volume,
+ p.volume,
+ p.width * p.depth * p.height
+ ) / 1000000
+ ) AS INT
+ ) volumeKg,
+ NULL loadPriority,
+ NULL invoiceAmount,
+ s.nickname freighter,
+ NULL reference
+ FROM travel tr
+ LEFT JOIN supplier s ON s.id = tr.cargoSupplierFk
+ LEFT JOIN entry e ON e.travelFk = tr.id
+ LEFT JOIN buy b ON b.entryFk = e.id
+ LEFT JOIN packaging p ON p.id = b.packagingFk
+ LEFT JOIN item i ON i.id = b.itemFk
+ LEFT JOIN itemType it ON it.id = i.typeFk
+ JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
+ JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
+ JOIN country co ON co.id = wOut.countryFk
+ JOIN agencyMode am ON am.id = tr.agencyModeFk
+ JOIN volumeConfig vc
+ WHERE tr.landed >= vDateFrom
+ AND co.continentFk = vContinentFk
+ GROUP BY tr.id
+ UNION ALL
+ SELECT e.travelFk,
+ e.id,
+ FALSE,
+ s.name,
+ e.invoiceNumber,
+ tr.shipped,
+ wOut.name,
+ tr.landed,
+ wIn.name,
+ SUM(b.stickers),
+ e.evaNotes,
+ NULL,
+ CAST(SUM(b.weight * b.stickers) AS INT),
+ CAST(
+ SUM(vc.aerealVolumetricDensity *
+ b.stickers *
+ IF(p.volume,
+ p.volume,
+ p.width * p.depth * p.height
+ ) / 1000000
+ ) AS INT
+ ),
+ loadPriority,
+ e.invoiceAmount,
+ s2.nickname,
+ e.reference
+ FROM entry e
+ JOIN buy b ON b.entryFk = e.id
+ JOIN packaging p ON p.id = b.packagingFk
+ JOIN item i ON i.id = b.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN travel tr ON tr.id = e.travelFk
+ LEFT JOIN supplier s2 ON s2.id = tr.cargoSupplierFk
+ JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
+ JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
+ JOIN country co ON co.id = wOut.countryFk
+ JOIN volumeConfig vc
+ WHERE tr.landed >= vDateFrom
+ AND co.continentFk = vContinentFk
+ GROUP BY e.id
+ ) sub
+ ORDER BY landed ASC,
+ shipped ASC,
+ travelFk,
+ isTravel DESC,
+ (loadPriority > 0) DESC,
+ loadPriority,
+ agency,
+ evaNotes;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `travel_getEntriesMissingPackage` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb3 */ ;
+/*!50003 SET character_set_results = utf8mb3 */ ;
+/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
+DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_getEntriesMissingPackage`(vSelf INT)
BEGIN
DECLARE vpackageOrPackingNull INT;
@@ -74439,11 +74666,11 @@ BEGIN
WHERE id = vSelf;
SELECT e.id entryFk
- FROM travel t
- JOIN entry e ON e.travelFk = t.id
- JOIN buy b ON b.entryFk = e.id
- WHERE t.id = vTravelFk
- AND (b.packing IS NULL OR b.packageFk IS NULL);
+ FROM travel t
+ JOIN entry e ON e.travelFk = t.id
+ JOIN buy b ON b.entryFk = e.id
+ WHERE t.id = vTravelFk
+ AND (b.packing IS NULL OR b.packagingFk IS NULL);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -74465,7 +74692,7 @@ BEGIN
/*
* Desplaza al dia siguiente los travels que contengan redadas y avisa a los compradores
- *
+ *
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vWorkerName VARCHAR(50);
@@ -74477,7 +74704,7 @@ BEGIN
SELECT GROUP_CONCAT( DISTINCT CONCAT('https://salix.verdnatura.es/#!/travel/', ttr.id, '/summary ') ORDER BY ttr.id SEPARATOR '\n\r'),
u.name
FROM tmp.travel ttr
- JOIN entry e ON e.travelFk = ttr.id
+ JOIN entry e ON e.travelFk = ttr.id
JOIN buy b ON b.entryFk = e.id
JOIN item i ON i.id = b.itemFk
JOIN itemType it ON it.id = i.typeFk
@@ -74485,19 +74712,19 @@ BEGIN
GROUP BY u.name;
DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET vDone = TRUE;
+ SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.travel;
CREATE TEMPORARY TABLE tmp.travel
SELECT tr.id,tr.landed
FROM travel tr
- JOIN entry e ON e.travelFk = tr.id
+ JOIN entry e ON e.travelFk = tr.id
WHERE tr.landed = util.tomorrow()
AND e.isRaid
GROUP BY tr.id;
@@ -74555,7 +74782,7 @@ proc: BEGIN
IF vSelf IS NULL THEN
LEAVE proc;
END IF;
-
+
INSERT IGNORE INTO travelRecalc SET travelFk = vSelf;
END ;;
DELIMITER ;
@@ -74565,6 +74792,100 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `travel_upcomingArrivals` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_upcomingArrivals`(
+ vWarehouseFk INT,
+ vDate DATETIME
+)
+BEGIN
+/**
+ * Procedure to track and organize the movement of items between warehouses,
+ * where 'warehouseINFk' is @vWarehouseFk.
+ * Uses temporary tables to process and store the travel data of the items.
+ *
+ * @params vWarehouseFk warehouse id
+ * @params vDate selected landed date
+ * @return tmp.itemTravel
+ */
+ DECLARE vTravelFk INT;
+ DECLARE vWarehouseOutFk INT;
+ DECLARE vShipment DATETIME;
+ DECLARE vDateStart DATETIME;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTravelTop
+ (PRIMARY KEY (wh_in,wh_out,landing,shipment))
+ ENGINE = MEMORY
+ SELECT 0 id,
+ vWarehouseFk wh_in,
+ vWarehouseFk wh_out,
+ FALSE ok,
+ vDate landing,
+ vDate shipment;
+
+ REPEAT
+ SET vTravelFk = NULL;
+
+ SELECT id,
+ wh_out,
+ shipment,
+ landing
+ INTO vTravelFk,
+ vWarehouseOutFk,
+ vShipment,
+ vDateStart
+ FROM tTravelTop
+ WHERE ok = FALSE LIMIT 1;
+
+ UPDATE tTravelTop
+ SET ok = TRUE
+ WHERE id = vTravelFk;
+
+ INSERT IGNORE INTO tTravelTop
+ SELECT id,
+ vWarehouseFk,
+ warehouseOutFk,
+ FALSE,
+ IF(vTravelFk, vDateStart, landed),
+ shipped shipment
+ FROM travel
+ WHERE warehouseOutFk = vWarehouseOutFk
+ AND IF(vTravelFk, landed <= vShipment, landed >= vShipment)
+ AND shipped >= util.VN_CURDATE()
+ AND NOT isDelivered;
+ UNTIL vTravelFk IS NULL END REPEAT;
+
+ DELETE FROM tTravelTop WHERE id = 0;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemTravel
+ (KEY (wh))
+ ENGINE = MEMORY
+ SELECT *
+ FROM (
+ SELECT wh_out wh,
+ landing
+ FROM tTravelTop
+ WHERE wh_out <> vWarehouseFk
+ ORDER BY landing
+ LIMIT 10000000000000000000
+ ) t
+ GROUP BY wh;
+
+ DROP TEMPORARY TABLE tTravelTop;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_updatePacking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -74581,10 +74902,10 @@ BEGIN
* @param vItemFk id del item
* @param vPacking nuevo packing
*/
-
+
DECLARE vAuctionWarehouseFk INT;
DECLARE vMainWarehouseFk INT;
-
+
SELECT warehouseFk INTO vAuctionWarehouseFk
FROM auctionConfig;
@@ -74644,7 +74965,7 @@ BEGIN
FROM travelClonedWeekly
WHERE travelFk;
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vCounter = vSinceWeek;
@@ -74706,12 +75027,12 @@ BEGIN
/*
* Plantilla para modificar reemplazar todos los tags
* por los valores que tienen los articulos
- *
+ *
* @param vTypeFk tipo a modificar
- *
+ *
*/
- DELETE it.*
- FROM itemTag it
+ DELETE it.*
+ FROM itemTag it
JOIN item i ON i.id = it.itemFk
WHERE i.typeFk = vTypeFk;
@@ -74720,40 +75041,40 @@ BEGIN
FROM item i
JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci
WHERE i.typeFk = vTypeFk;
-
+
INSERT INTO itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id, i.category, 5
FROM item i
JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci
WHERE i.typeFk = vTypeFk;
-
+
INSERT INTO itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id, ink.name, 2
FROM item i
JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci
JOIN ink ON ink.id = i.inkFk
WHERE i.typeFk = vTypeFk;
-
+
INSERT INTO itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id, p.name, 3
FROM item i
JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci
JOIN producer p ON p.id = i.producerFk
- WHERE i.typeFk = vTypeFk;
-
+ WHERE i.typeFk = vTypeFk;
+
INSERT INTO itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id, o.name, 4
FROM item i
JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci
JOIN origin o ON o.id = i.originFk
WHERE i.typeFk = vTypeFk;
- /*
+ /*
INSERT INTO itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id, i.stems, 6
FROM item i
JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci
- WHERE i.typeFk = vTypeFk;
- */
+ WHERE i.typeFk = vTypeFk;
+ */
-- CALL itemTagArrangedUpdate(NULL);
END ;;
@@ -74776,7 +75097,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `updatePedidosInternos`(vItemFk INT)
BEGIN
UPDATE vn.item SET upToDown = 0 WHERE item.id = vItemFk;
-
+
END ;;
DELIMITER ;
@@ -74804,7 +75125,7 @@ BEGIN
SELECT vp.regex INTO vRegex
FROM vehiclePlateRegex vp
WHERE vp.countryCodeFk = vCountryCodeFk;
-
+
IF NOT vNumberPlate REGEXP BINARY (vRegex)THEN
CALL util.throw(CONCAT('Error: la matricula ', vNumberPlate, ' no es valida para ',vCountryCodeFk));
END IF;
@@ -74837,7 +75158,7 @@ proc:BEGIN
ROLLBACK;
RESIGNAL;
END;
-
+
SELECT eventEarlyDays INTO vEventEarlyDays
FROM vehicleConfig;
@@ -74855,7 +75176,7 @@ proc:BEGIN
IF NOT vHasEvents THEN
LEAVE proc;
END IF;
-
+
START TRANSACTION;
SELECT util.notification_send('vehicle-event-expired',
@@ -74890,21 +75211,21 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `visible_getMisfit`(vSectorFk INT)
BEGIN
-
+
/* Devuelve una tabla temporal con los descuadres entre el visible teórico y lo ubicado en la práctica
- *
+ *
* @param vSectorFk Identificador de vn.sector
- *
+ *
* @return tmp.stockMisfit(itemFk, visible, parked)
*/
-
+
DECLARE vCalcVisibleFk INT;
DECLARE vWarehouseFk INT;
SELECT warehouseFk INTO vWarehouseFk
- FROM vn.sector s
+ FROM vn.sector s
WHERE s.id = vSectorFk;
-
+
CALL cache.visible_refresh(vCalcVisibleFk, FALSE, vWarehouseFk);
DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit;
@@ -74917,17 +75238,17 @@ BEGIN
INSERT INTO tmp.stockMisfit(itemFk, parked)
SELECT iss.itemFk , sum(iss.visible )
- FROM vn.itemShelvingStock iss
- JOIN vn.sector s ON s.id = iss.sectorFk
+ FROM vn.itemShelvingStock iss
+ JOIN vn.sector s ON s.id = iss.sectorFk
WHERE vSectorFk IN (s.id, s.sonFk)
GROUP BY iss.itemFk;
-
+
INSERT INTO tmp.stockMisfit(itemFk, visible)
- SELECT v.item_id , v.visible
- FROM cache.visible v
- WHERE v.calc_id = vCalcVisibleFk
+ SELECT v.item_id , v.visible
+ FROM cache.visible v
+ WHERE v.calc_id = vCalcVisibleFk
ON DUPLICATE KEY UPDATE visible = v.visible;
-
+
DELETE FROM tmp.stockMisfit
WHERE visible = parked;
@@ -74951,17 +75272,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `warehouseFitting`(IN vWhOrigin INT
BEGIN
DECLARE vCacheVisibleOriginFk INT;
DECLARE vCacheVisibleDestinyFk INT;
-
+
CALL cache.visible_refresh(vCacheVisibleOriginFk, FALSE, vWhOrigin);
CALL cache.visible_refresh(vCacheVisibleDestinyFk, FALSE, vWhDestiny);
-
+
SELECT i.id itemFk,
i.longName,
i.size,
i.subName,
vOrigin.visible AS Origen,
vDestiny.visible Destino
-
+
FROM vn.item i
JOIN vn.itemType it ON it.id = i.typeFk
LEFT JOIN cache.visible vOrigin ON vOrigin.calc_id = vCacheVisibleOriginFk AND vOrigin.item_id = i.id
@@ -74990,13 +75311,13 @@ BEGIN
DECLARE vWhOrigin INT;
DECLARE vWhDestiny INT;
-
+
SELECT warehouseInFk, warehouseOutFk INTO vWhDestiny, vWhOrigin
FROM vn.travel
WHERE id = vTravelFk;
-
+
CALL vn.warehouseFitting(vWhOrigin, vWhDestiny);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -75060,7 +75381,7 @@ BEGIN
* Calcula los días y horas de vacaciones en función de un contrato y año
*
* @param vYear
- * @param vBusinessFk
+ * @param vBusinessFk
* @return tmp.workerCalendarCalculateBusiness (days, hours, daysEnjoyed, hoursEnjoyed)
*/
DECLARE vStarted DATE;
@@ -75072,17 +75393,17 @@ BEGIN
DECLARE vPayedHolidays DECIMAL(5,2);
DECLARE vDifDays INT;
- SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started),
- IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended),
+ SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started),
+ IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended),
IF(wbt.hasHolidayEntitlement, w.days, 0),
c.hoursWeek,
IF(YEAR(b.ended) = vYear, b.payedHolidays, 0) payedHolidays
- INTO vStarted,
- vEnded,
- vDaysHoliday,
+ INTO vStarted,
+ vEnded,
+ vDaysHoliday,
vHoursWeek,
vPayedHolidays
- FROM business b
+ FROM business b
JOIN workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
JOIN workCenterHoliday w ON w.workcenterFk = b.workcenterFk
LEFT JOIN calendarType c ON c.id = b.calendarTypeFk
@@ -75090,23 +75411,23 @@ BEGIN
AND w.year = vYear;
DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateBusiness;
-
+
IF vStarted < vEnded THEN
SET vDifDays = DAYOFYEAR(vEnded) - DAYOFYEAR(vStarted) + 1;
- SELECT IFNULL(SUM(a.holidayEntitlementRate), 0),
+ SELECT IFNULL(SUM(a.holidayEntitlementRate), 0),
SUM(-(a.discountRate - 1)) + vPayedHolidays
- INTO vDaysToSubtract,
- vDaysHolidayEnjoyed
+ INTO vDaysToSubtract,
+ vDaysHolidayEnjoyed
FROM calendar c
JOIN absenceType a ON a.id = c.dayOffTypeFk
JOIN business b ON b.id = c.businessFk
- WHERE b.id = vBusinessFk
+ WHERE b.id = vBusinessFk
AND YEAR(c.dated) = vYear;
END IF;
- CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness
+ CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness
ENGINE = MEMORY
SELECT @days := IFNULL(ROUND((vDaysHoliday * (vDifDays - vDaysToSubtract) / IF(util.isLeapYear(vYear) , 366, 365)), 1), 0) days,
@days * (vHoursWeek / 5) hours,
@@ -75134,32 +75455,32 @@ BEGIN
/**
* Calcula los días y horas de vacaciones en función de un trabajador y año
*
- * @param vYear
- * @param vWorkerFk
+ * @param vYear
+ * @param vWorkerFk
* @return tmp.workerCalendarCalculateYear (days, hours, daysEnjoyed, hoursEnjoyed)
- */
+ */
DECLARE vDone BOOL;
DECLARE vBusinessFk INT;
DECLARE cur CURSOR FOR
- SELECT b.id
+ SELECT b.id
FROM business b
- WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear)
+ WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear)
AND b.workerFk = vWorkerFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET vDone = TRUE;
-
+ SET vDone = TRUE;
+
DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateYear;
CREATE TEMPORARY TABLE tmp.workerCalendarCalculateYear
- (days DEC(5,2),
+ (days DEC(5,2),
hours DEC(5,2),
- daysEnjoyed DEC(5,2),
- hoursEnjoyed DEC(5,2))
+ daysEnjoyed DEC(5,2),
+ hoursEnjoyed DEC(5,2))
ENGINE = MEMORY;
INSERT INTO tmp.workerCalendarCalculateYear VALUES(0, 0, 0, 0);
-
+
OPEN cur;
l: LOOP
@@ -75172,12 +75493,12 @@ BEGIN
CALL workerCalendar_calculateBusiness(vYear, vBusinessFk);
UPDATE tmp.workerCalendarCalculateYear w
- JOIN tmp.workerCalendarCalculateBusiness wc
+ JOIN tmp.workerCalendarCalculateBusiness wc
SET w.days = w.days + wc.days,
w.hours = w.hours + wc.hours,
w.daysEnjoyed = w.daysEnjoyed + wc.daysEnjoyed,
w.hoursEnjoyed = w.hoursEnjoyed + wc.hoursEnjoyed;
-
+
DROP TEMPORARY TABLE tmp.workerCalendarCalculateBusiness;
END LOOP;
@@ -75192,38 +75513,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `workerCreate` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCreate`(
- vFirstname VARCHAR(50),
- vLastName VARCHAR(50),
- vCode CHAR(3),
- vBossFk INT,
- vUserFk INT,
- vFi VARCHAR(15) ,
- vBirth DATE
-)
-BEGIN
-/**
- * Create new worker
- *
- */
- INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth,userFk)
- VALUES (vUserFk, vCode, vFirstname, vLastName, vBossFk, vFi, vBirth,vUserFk);
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerCreateExternal` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -75280,20 +75569,20 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate;
CREATE TEMPORARY TABLE tmp.workerDepartmentByDate
ENGINE = MEMORY
- SELECT w.id userFk,
- w.lastName name,
- w.firstName firstname,
- d.name department,
+ SELECT w.id userFk,
+ w.lastName name,
+ w.firstName firstname,
+ d.name department,
d.id departmentFk,
- b.started,
- d.isProduction,
+ b.started,
+ d.isProduction,
CAST(12 * b.amount / ct.hoursWeek / 52 AS DECIMAL(10,2)) costeHora,
w.fi nif
FROM business b
JOIN calendarType ct ON ct.id = b.calendarTypeFk
JOIN department d ON d.id = b.departmentFk
JOIN worker w ON w.id = b.workerFk
- WHERE b.started <= vDate
+ WHERE b.started <= vDate
AND (b.ended > vDate OR b.ended IS NULL);
END ;;
DELIMITER ;
@@ -75317,21 +75606,26 @@ mainLabel:BEGIN
IF (SELECT COUNT(*) FROM workerDisableExcluded WHERE workerFk = vUserId AND (dated > util.VN_CURDATE() OR dated IS NULL)) > 0 THEN
LEAVE mainLabel;
END IF;
+
+ DELETE cp FROM clientProtected cp
+ JOIN client c ON c.id = cp.clientFk
+ WHERE c.salesPersonFk = vUserId;
+
DELETE FROM account.account
WHERE id = vUserId;
- UPDATE account.user
+ UPDATE account.user
SET role = 2
- WHERE id = vUserId;
+ WHERE id = vUserId;
- DELETE FROM pbx.sip
- WHERE user_id = vUserId;
+ DELETE FROM pbx.sip
+ WHERE user_id = vUserId;
UPDATE `client` c
JOIN payMethod p ON p.name = 'CONTADO'
SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE
WHERE c.id = vUserId;
-
+
UPDATE `client` c
SET c.salesPersonFk = null
WHERE c.salesPersonFk = vUserId;
@@ -75360,12 +75654,12 @@ BEGIN
SELECT b.workerFk
FROM business b
JOIN vn.worker w ON w.id = b.workerFk
- JOIN account.account a ON a.id = b.workerFk
- LEFT JOIN (SELECT b.workerFk
+ JOIN account.account a ON a.id = b.workerFk
+ LEFT JOIN (SELECT b.workerFk
FROM business b
WHERE (ended IS NULL OR ended >=util.VN_CURDATE())
)sub ON sub.workerFk = a.id
- LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk
+ LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk
WHERE sub.workerFk IS NULL
AND wd.workerFk IS NULL
GROUP BY w.id;
@@ -75383,7 +75677,7 @@ BEGIN
END WHILE;
CLOSE rs;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -75447,19 +75741,19 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerJourney_replace`(
- vDatedFrom DATE,
- vDatedTo DATE,
+ vDatedFrom DATE,
+ vDatedTo DATE,
vWorkerFk INT)
BEGIN
/**
- * Actualiza la tabla workerJourney para que actue como caché permanente revisable
+ * Actualiza la tabla workerJourney para que actue como caché permanente revisable
* de las jornadas laborales.
* @param vDatedFrom workerTimeControl
* @param vDatedTo workerTimeControl
* @param vWorkerFk, en caso de pasar 0 ó NULL se aplica a todos
- */
+ */
DECLARE vDatedTimeTo DATETIME;
- DECLARE vMaxTimePerDay INT;
+ DECLARE vMaxTimePerDay INT;
DECLARE vMinHoursToBreak DECIMAL(10,2);
DECLARE vBreakHours DECIMAL(10,2);
DECLARE vMonthByYear INT;
@@ -75467,57 +75761,57 @@ BEGIN
DECLARE vMonthsByYear INT DEFAULT 12;
DECLARE vDaysByWeek INT DEFAULT 5;
DECLARE vDatedFromYesterday DATETIME;
- DECLARE vDatedToTomorrow DATETIME;
-
- SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY)
+ DECLARE vDatedToTomorrow DATETIME;
+
+ SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY)
INTO vDatedFromYesterday, vDatedToTomorrow;
SET vDatedTimeTo = util.dayEnd(vDatedTo);
-
- SELECT minHoursToBreak, breakHours, maxTimePerDay
+
+ SELECT minHoursToBreak, breakHours, maxTimePerDay
INTO vMinHoursToBreak, vBreakHours, vMaxTimePerDay
FROM workerTimeControlConfig;
DELETE FROM workerJourney
- WHERE dated BETWEEN vDatedFrom AND vDatedTo
+ WHERE dated BETWEEN vDatedFrom AND vDatedTo
AND NOT isPaid
AND NOT isUpdated
- AND (vWorkerFk IS NULL OR userFK = vWorkerFk);
+ AND (vWorkerFk IS NULL OR userFK = vWorkerFk);
- -- Se inserta todos los días del periodo por worker y business en el rango de fechas.
+ -- Se inserta todos los días del periodo por worker y business en el rango de fechas.
INSERT IGNORE INTO workerJourney(userFk, dated, businessFk)
SELECT b.workerFk, t.dated, b.id
- FROM business b
+ FROM business b
JOIN time t ON t.dated BETWEEN b.started AND IFNULL(b.ended,util.VN_CURDATE())
WHERE t.dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR b.workerFk = vWorkerFk)
ORDER BY b.workerFk, t.dated, b.id;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
IF vWorkerFk THEN
CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo);
- CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user`
- SELECT vWorkerFk userFk;
+ CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user`
+ SELECT vWorkerFk userFk;
ELSE
CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo);
- CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user`
+ CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user`
SELECT id userFk
FROM worker w;
- END IF;
+ END IF;
UPDATE workerJourney wj
JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk
- SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak,
- t.timeWorkDecimal - vBreakHours,
+ SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak,
+ t.timeWorkDecimal - vBreakHours,
t.timeWorkDecimal) AS DECIMAL (10,2)),
wj.lunch = IF(t.timeWorkDecimal >= vMinHoursToBreak , vBreakHours , 0)
WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
AND NOT wj.isPaid
AND NOT wj.isUpdated
AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk);
-
- -- NOCTURNIDAD
+
+ -- NOCTURNIDAD
CALL timeControl_getError(vDatedFrom, vDatedTimeTo);
SET @vIsOdd := TRUE;
@@ -75527,9 +75821,9 @@ BEGIN
CREATE TEMPORARY TABLE tmp.workerTimeControl
(INDEX (userFk), INDEX (timed))
ENGINE = MEMORY
- SELECT DISTINCT(wtc.id),
- wtc.userFk,
- wtc.timed,
+ SELECT DISTINCT(wtc.id),
+ wtc.userFk,
+ wtc.timed,
wtc.direction
FROM workerTimeControl wtc
JOIN tmp.`user` w ON w.userFk = wtc.userFk
@@ -75539,10 +75833,10 @@ BEGIN
AND (vWorkerFk IS NULL OR wtc.userFk = vWorkerFk)
ORDER BY wtc.userFk, wtc.timed ASC;
- SELECT MAX(id) INTO @vCont
+ SELECT MAX(id) INTO @vCont
FROM tmp.workerTimeControl;
- DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux;
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux;
CREATE TEMPORARY TABLE tmp.workerTimeControlAux (
`id` int(11) ,
`userFk` int(10) unsigned ,
@@ -75564,9 +75858,9 @@ BEGIN
DATE(@lastTimed) dated,
@lastUserFk lastUserFk,
IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd,
- IF(@vIsOdd
- AND @lastDirection = 'middle'
- AND (DATE(@lastTimed) <> date(timed)
+ IF(@vIsOdd
+ AND @lastDirection = 'middle'
+ AND (DATE(@lastTimed) <> date(timed)
OR @lastUserFk <> userFk), TRUE, FALSE) hasBreak,
@lastTimed := wtc.timed,
@lastUserFk := userFk,
@@ -75580,16 +75874,16 @@ BEGIN
SET @lastDirection := NULL;
INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
- SELECT @vCont:= @vCont + 1,
- lastUserFk,
- DATE_ADD(sub.dated, INTERVAL 1 DAY),
+ SELECT @vCont:= @vCont + 1,
+ lastUserFk,
+ DATE_ADD(sub.dated, INTERVAL 1 DAY),
'middle'
FROM (SELECT IF(@lastUserFk <> userFk, @vIsOdd := TRUE, NULL),
DATE(@lastTimed) dated,
@lastUserFk lastUserFk,
IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd,
- IF(@vIsOdd
- AND @lastDirection = 'middle'
+ IF(@vIsOdd
+ AND @lastDirection = 'middle'
AND (DATE(@lastTimed)<>date(timed)
OR @lastUserFk<>userFk), TRUE, FALSE) hasBreak,
@lastTimed := wtc.timed,
@@ -75602,7 +75896,7 @@ BEGIN
-- Cambio de dia
INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
SELECT @vCont:= @vCont + 1,
- wtc.userFk,
+ wtc.userFk,
util.dayEnd(date(wtc.timed)),
'out'
FROM workerTimeControl wtc
@@ -75613,8 +75907,8 @@ BEGIN
GROUP BY wtc.userFk, DATE(wtc.timed);
INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
- SELECT @vCont:= @vCont + 1,
- wtc.userFk,
+ SELECT @vCont:= @vCont + 1,
+ wtc.userFk,
DATE_ADD(date(wtc.timed), INTERVAL 1 DAY),
'in'
FROM workerTimeControl wtc
@@ -75640,8 +75934,8 @@ BEGIN
IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed),
IF(direction='in', @vDated := DATE(wtc.timed), @vDated ) dated,
wtc.userFk,
- IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay,
- workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed),
+ IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay,
+ workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed),
0) NigthlyHours,
@lastUserFk := userFk
FROM (SELECT DISTINCT(wtc.id), wtc.userFk, wtc.timed, wtc.direction
@@ -75654,7 +75948,7 @@ BEGIN
) wtc
ORDER BY wtc.userFk, wtc.timed
)sub
- WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo
+ WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo
GROUP BY userFk, sub.dated
)night ON night.userFk = wj.userFk AND night.dated = wj.dated
SET wj.nocturn = night.NigthlyHours
@@ -75666,8 +75960,8 @@ BEGIN
UPDATE workerJourney wj
JOIN business b ON b.id = wj.businessFk
JOIN calendarType ct ON ct.id = b.calendarTypeFk
- SET wj.priceOrdinaryHour =
- (vMonthsByYear * b.amount) /
+ SET wj.priceOrdinaryHour =
+ (vMonthsByYear * b.amount) /
(vWeeksByYear * ct.hoursWeek),
wj.contractJourney = ct.hoursWeek / vDaysByWeek
WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
@@ -75675,7 +75969,7 @@ BEGIN
AND NOT wj.isPaid
AND NOT isUpdated;
- -- Precio Extras, Vacaciones y Nocturnas
+ -- Precio Extras, Vacaciones y Nocturnas
UPDATE workerJourney wj
JOIN(SELECT MAX(w.dated), t.dated, w.holidayInc, w.nightInc, w.extraInc
FROM time t
@@ -75699,12 +75993,12 @@ BEGIN
WHERE ct.isPartial
AND wj.dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
- AND NOT wj.isPaid
+ AND NOT wj.isPaid
AND NOT wj.isUpdated;
-- Ausencias
UPDATE workerJourney wj
- JOIN businessCalendar bc ON bc.businessFk = wj.businessFk
+ JOIN businessCalendar bc ON bc.businessFk = wj.businessFk
AND bc.dated = wj.dated
JOIN absenceType ab ON ab.id = bc.absenceTypeFk
SET wj.permission = ab.permissionRate * wj.contractJourney,
@@ -75719,7 +76013,7 @@ BEGIN
UPDATE workerJourney
SET holiday = IF(DAYNAME(dated)='sábado', 0, total),
contractJourney = 0
- WHERE DAYNAME(dated) IN ('sábado', 'domingo')
+ WHERE DAYNAME(dated) IN ('sábado', 'domingo')
AND dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR userFk = vWorkerFk)
AND NOT isPaid
@@ -75728,8 +76022,8 @@ BEGIN
-- Festivos por centro de trabajo
UPDATE workerJourney wj
JOIN calendarHolidays ch ON ch.dated = wj.dated
- JOIN business b ON b.id = wj.businessFk
- AND b.workcenterFk = ch.workcenterFk
+ JOIN business b ON b.id = wj.businessFk
+ AND b.workcenterFk = ch.workcenterFk
SET wj.holiday = wj.total,
wj.permission = wj.contractJourney,
wj.contractJourney = 0
@@ -75739,7 +76033,7 @@ BEGIN
AND NOT wj.isUpdated;
-- Horas extras
- UPDATE workerJourney
+ UPDATE workerJourney
SET extra = lunch + total - contractJourney
WHERE dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR userFk = vWorkerFk)
@@ -75769,15 +76063,15 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistakeType_get`()
BEGIN
-
+
/**
* Obtiene los tipos de error para los trabajadores
*/
-
- SELECT code, description
- FROM workerMistakeType
+
+ SELECT code, description
+ FROM workerMistakeType
ORDER BY description;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -75804,89 +76098,7 @@ BEGIN
*
*/
INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk)
- VALUES(vWorkerFk, vWorkerMistakeTypeFk);
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlAdd` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControlAdd`(IN vUserFk INT, IN vWarehouseFk INT, IN vDated DATETIME)
-BEGIN
-
- /*INSERT INTO workerTimeControl(userFk, timed, manual, warehouseFk)
- VALUES(vUserFk, vDated, FALSE, vWarehouseFk);
-
- CALL vn.workerTimeControlSOWP(vUserFk , vDated);*/
-
- CALL vn.workerTimeControl_add(vUserFk,vWarehouseFk,util.VN_NOW(),FALSE);
-
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlPinGenerate` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControlPinGenerate`(
- vWorkerFk INT)
-BEGIN
-/**
- * Create new pin for workerFk or new pin for all workers if vWorkerFk is null
- *
- */
-
-
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlSetOrder` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControlSetOrder`()
-BEGIN
-
- SET @order := 1;
- SET @userFk := 0;
- SET @day := 0;
-
- UPDATE tmp.workerTimeControl
- SET `order` = IF(userFk = @userFk AND day(timed) = @day, @order := @order + 1, @order := 1),
- userFk = @userFk := userFk,
- manual = manual + (0 * @day := day(timed))
- ORDER BY userFk, timed;
+ VALUES(vWorkerFk, vWorkerMistakeTypeFk);
END ;;
DELIMITER ;
@@ -75907,34 +76119,13 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControlSOWP`(IN vUserFk INT, IN vDated DATE)
BEGIN
SET @order := 0;
-
- UPDATE workerTimeControl
- SET `order` = @order := @order + 1
- WHERE vUserFk =userFk
+
+ UPDATE workerTimeControl
+ SET `order` = @order := @order + 1
+ WHERE vUserFk =userFk
AND vDated = DATE(timed)
ORDER BY timed;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_add` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL)
-BEGIN
-
-
- SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual);
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -76021,73 +76212,73 @@ proc: BEGIN
DECLARE vTo VARCHAR(50) DEFAULT NULL;
DECLARE vUserName VARCHAR(50) DEFAULT NULL;
DECLARE vBody VARCHAR(255) DEFAULT NULL;
-
- SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax
+
+ SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax
INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax
FROM workerTimeControlParams;
SELECT MAX(timed) INTO vLastIn
- FROM workerTimeControl
- WHERE userFk = vUserFk
+ FROM workerTimeControl
+ WHERE userFk = vUserFk
AND direction = 'in';
-
+
SELECT MAX(timed) INTO vLastOut
- FROM workerTimeControl
- WHERE userFk = vUserFk
- AND direction = 'out';
+ FROM workerTimeControl
+ WHERE userFk = vUserFk
+ AND direction = 'out';
SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo
FROM account.user u
- WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk);
-
+ WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk);
+
SELECT CONCAT(firstName,' ',lastName) INTO vUserName
FROM worker w
WHERE w.id = vUserFk;
IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA
-
- -- VERIFICAR DESCANSO DIARIO
- IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN
+
+ -- VERIFICAR DESCANSO DIARIO
+ IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN
SELECT "Descansos 12 h" AS problem;
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
LEAVE proc;
- END IF;
-
+ END IF;
+
-- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ
- IF (SELECT MOD(COUNT(*),2) -- <>0
- FROM workerTimeControl
+ IF (SELECT MOD(COUNT(*),2) -- <>0
+ FROM workerTimeControl
WHERE userFk = vUserFk
AND timed >= vLastIn
- ) THEN
+ ) THEN
SELECT "Dias con fichadas impares" AS problem;
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
+ LEAVE proc;
END IF;
-
+
-- VERIFICAR VACACIONES
SELECT at2.name INTO vCalendarStateType
- FROM calendar c
+ FROM calendar c
JOIN business b ON b.id = c.businessFk
JOIN absenceType at2 ON at2.id = c.dayOffTypeFk
WHERE c.dated = util.VN_CURDATE()
AND at2.isAllowedToWork = FALSE
AND b.workerFk = vUserFk
LIMIT 1;
-
+
IF(LENGTH(vCalendarStateType)) THEN
SELECT vCalendarStateType AS problem;
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
-
+ LEAVE proc;
+
END IF;
-
+
-- VERIFICAR CONTRATO EN VIGOR
IF (SELECT COUNT(*)
FROM business b
@@ -76099,44 +76290,44 @@ proc: BEGIN
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
-
+ LEAVE proc;
+
END IF;
-- VERIFICAR DESCANSO SEMANAL
SET @vHasBreakWeek:= FALSE;
- SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND));
-
+ SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND));
+
DROP TEMPORARY TABLE IF EXISTS tmp.trash;
CREATE TEMPORARY TABLE tmp.trash
SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias,
@vLastTimed:= UNIX_TIMESTAMP(timed)
- FROM workerTimeControl
+ FROM workerTimeControl
WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND)
AND userFk= vUserFk
AND direction IN ('in','out')
- ORDER BY timed ASC;
-
- IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA
+ ORDER BY timed ASC;
+
+ IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA
SELECT "Descansos 36 h" AS problem;
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
LEAVE proc;
END IF;
+
+ DROP TEMPORARY TABLE tmp.trash;
- DROP TEMPORARY TABLE tmp.trash;
-
- ELSE -- DIA ACTUAL
-
+ ELSE -- DIA ACTUAL
+
-- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO
- SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked
+ SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked
FROM workerTimeControl wtc
- WHERE userFk = vUserFk
+ WHERE userFk = vUserFk
AND timed >= vLastIn
ORDER BY timed;
- IF vTimedWorked > vDayWorkMax THEN
+ IF vTimedWorked > vDayWorkMax THEN
SELECT "Jornadas" AS problem;
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody;
@@ -76159,10 +76350,10 @@ proc: BEGIN
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
+ LEAVE proc;
END IF;
END IF;*/
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -76182,7 +76373,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_checkBreak`(vStarted DATE)
BEGIN
/**
- * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas
+ * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas
* El sistema verificará el descanso corto en la siguiente semana
* o el largo en las 2 siguientes semanas a partir de la fecha dada
* @param vStarted día inicio de la semana en el que se quiere verificar
@@ -76193,27 +76384,27 @@ BEGIN
DECLARE vShortWeekBreak INT;
DECLARE vLongWeekBreak INT;
- SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)),
+ SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)),
util.dayEnd(DATE_ADD(vStarted, INTERVAL longWeekDays DAY)),
- shortWeekBreak,
+ shortWeekBreak,
longWeekBreak
INTO vShortEnded, vLongEnded, vShortWeekBreak, vLongWeekBreak
FROM workerTimeControlConfig;
-
+
SET @previousTimed:= UNIX_TIMESTAMP(vStarted);
SET @lastUserFk := NULL;
-
+
-- Descanso corto en la semana
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.worker;
CREATE TEMPORARY TABLE tmp.worker
(PRIMARY KEY(workerFk))
ENGINE = MEMORY
SELECT DISTINCT userFk workerFk
- FROM workerTimeControl
+ FROM workerTimeControl
WHERE timed BETWEEN vStarted AND vShortEnded
AND direction IN ('in', 'out');
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.worker2;
CREATE TEMPORARY TABLE tmp.worker2
(PRIMARY KEY(workerFk))
@@ -76226,28 +76417,28 @@ BEGIN
SELECT sub2.userFk workerFk
FROM(SELECT sub.userFk,
IF(sub.userFk <> @lastUserFk,
- @previousTimed:= sub.timed,
+ @previousTimed:= sub.timed,
FALSE),
- IF(sub.timed - @previousTimed >= vShortWeekBreak,
- TRUE,
+ IF(sub.timed - @previousTimed >= vShortWeekBreak,
+ TRUE,
FALSE) hasShortWeekBreak,
@previousTimed:= sub.timed,
@lastUserFk:= sub.userFk
FROM (
SELECT userFk, UNIX_TIMESTAMP(timed) timed
- FROM workerTimeControl
+ FROM workerTimeControl
WHERE timed BETWEEN vStarted AND vShortEnded
AND direction IN ('in', 'out')
- UNION
+ UNION
SELECT w.workerFk,
UNIX_TIMESTAMP(IFNULL(
- MIN(wtc.timed),
+ MIN(wtc.timed),
DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND)))
FROM tmp.worker w
- LEFT JOIN workerTimeControl wtc
- ON wtc.userFk = w.workerFk
- AND wtc.timed BETWEEN vShortEnded
- AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND)
+ LEFT JOIN workerTimeControl wtc
+ ON wtc.userFk = w.workerFk
+ AND wtc.timed BETWEEN vShortEnded
+ AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND)
GROUP BY w.workerFk
UNION
SELECT w.workerFk,
@@ -76255,10 +76446,10 @@ BEGIN
MAX(wtc.timed),
DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND)))
FROM tmp.worker2 w
- LEFT JOIN workerTimeControl wtc
- ON wtc.userFk = w.workerFk
- AND wtc.timed BETWEEN
- DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND)
+ LEFT JOIN workerTimeControl wtc
+ ON wtc.userFk = w.workerFk
+ AND wtc.timed BETWEEN
+ DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND)
AND vStarted
GROUP BY w.workerFk
ORDER BY userFk, timed
@@ -76268,7 +76459,7 @@ BEGIN
GROUP BY sub2.userFk
HAVING NOT SUM(hasShortWeekBreak);
- -- Descanso largo en las 2 siguientes semanas
+ -- Descanso largo en las 2 siguientes semanas
DROP TEMPORARY TABLE tmp.worker;
CREATE TEMPORARY TABLE tmp.worker
(PRIMARY KEY(workerFk))
@@ -76288,12 +76479,12 @@ BEGIN
(PRIMARY KEY(workerFk))
ENGINE = MEMORY
SELECT sub2.userFk workerFk
- FROM(SELECT userFk,
+ FROM(SELECT userFk,
IF(userFk <> @lastUserFk,
- @previousTimed:= timed,
+ @previousTimed:= timed,
TRUE),
- IF(timed - @previousTimed >= vLongWeekBreak,
- TRUE,
+ IF(timed - @previousTimed >= vLongWeekBreak,
+ TRUE,
FALSE) hasLongWeekBreak,
@previousTimed:= timed,
@lastUserFk:= userFk
@@ -76302,24 +76493,24 @@ BEGIN
JOIN tmp.workerWithoutShortWeekBreak wws ON wws.workerFk = wtc.userFk
WHERE timed BETWEEN vStarted AND vLongEnded
AND direction IN ('in', 'out')
- UNION
+ UNION
SELECT w.workerFk,
- UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed),
+ UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed),
DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND)))
FROM tmp.worker w
- LEFT JOIN workerTimeControl wtc
- ON wtc.userFk = w.workerFk
- AND timed BETWEEN vLongEnded
- AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND)
+ LEFT JOIN workerTimeControl wtc
+ ON wtc.userFk = w.workerFk
+ AND timed BETWEEN vLongEnded
+ AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND)
GROUP BY w.workerFk
UNION
- SELECT w.workerFk,
- UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed),
+ SELECT w.workerFk,
+ UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed),
DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND)))
FROM tmp.worker2 w
- LEFT JOIN workerTimeControl wtc
- ON wtc.userFk = w.workerFk
- AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND)
+ LEFT JOIN workerTimeControl wtc
+ ON wtc.userFk = w.workerFk
+ AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND)
AND vStarted
GROUP BY w.workerFk
ORDER BY userFk, timed
@@ -76347,31 +76538,36 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_clockIn`(
- vWorker INT,
+ vWorkerFk INT,
vTimed DATETIME,
- vDirection VARCHAR(10))
+ vDirection VARCHAR(10),
+ vDevice VARCHAR(255)
+)
BEGIN
/**
- * Verifica si el empleado puede fichar
- * @param vWorker Identificador del trabajador
- * @param vTimed valor de la fichada, IF vTimed IS NULL vTimed = NOW
- * @param vDirection solo se pueden pasa los valores del campo
- * workerTimeControl.direction ENUM('in', 'out', 'middle')
- * @return Si todo es correcto, retorna el número de id la tabla workerTimeControl.
- * Si hay algún problema, devuelve el mesaje a que se debe mostrar al usuario
- * Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá
- * fichada a la tabla vn.workerTimeControl
- */
+* Verifica si el empleado puede fichar
+* @param vWorkerFk Identificador del trabajador
+* @param vTimed Balor de la fichada, IF vTimed IS NULL vTimed = NOW
+* @param vDirection Solo se pueden pasa los valores del campo
+* workerTimeControl.direction ENUM('in', 'out', 'middle')
+* @param vDevice Dispositivo en el que se ha fichado
+* @return Si todo es correcto, retorna el número de id la tabla workerTimeControl.
+* Si hay algún problema, devuelve el mesaje que se debe mostrar al usuario
+* Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá
+* fichada a la tabla vn.workerTimeControl
+*/
+
DECLARE vLastIn DATETIME;
DECLARE vLastOut DATETIME;
DECLARE vNextIn DATETIME;
- DECLARE vLastDirection VARCHAR(6);
- DECLARE vNextDirection VARCHAR(6);
+ DECLARE vNextOut DATETIME;
+ DECLARE vNextDirection ENUM('in', 'out');
+ DECLARE vLastDirection ENUM('in', 'out');
+ DECLARE vDayMaxTime INTEGER;
DECLARE vDayBreak INT;
DECLARE vShortWeekBreak INT;
DECLARE vLongWeekBreak INT;
DECLARE vWeekScope INT;
- DECLARE vGap INT;
DECLARE vMailTo VARCHAR(50) DEFAULT NULL;
DECLARE vUserName VARCHAR(50) DEFAULT NULL;
DECLARE vIsError BOOLEAN DEFAULT FALSE;
@@ -76379,152 +76575,81 @@ BEGIN
DECLARE vErrorCode VARCHAR(50);
DECLARE vDated DATE;
DECLARE vIsAllowedToWork VARCHAR(50);
- DECLARE vDepartmentFk INT;
- DECLARE vTimedLoop BIGINT;
- DECLARE vTimedLoopPrevious BIGINT;
- DECLARE vHasBreakWeek BOOLEAN DEFAULT FALSE;
- DECLARE vManual BOOLEAN DEFAULT TRUE;
- DECLARE vDone INT DEFAULT FALSE;
-
- DECLARE vCursor CURSOR FOR
- SELECT UNIX_TIMESTAMP(vTimed) timed
- UNION
- SELECT UNIX_TIMESTAMP(timed)
- FROM workerTimeControl
- WHERE timed BETWEEN (vTimed - INTERVAL vGap SECOND) AND vTimed
- AND userFk = vWorker
- AND direction IN ('in', 'out')
- ORDER BY timed ASC;
-
- DECLARE vCursor2 CURSOR FOR
- SELECT UNIX_TIMESTAMP(vTimed) timed
- UNION
- SELECT UNIX_TIMESTAMP(timed)
- FROM workerTimeControl
- WHERE timed BETWEEN vTimed AND (vTimed + INTERVAL vGap SECOND)
- AND userFk = vWorker
- AND direction IN ('in', 'out')
- ORDER BY timed ASC;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE vIsManual BOOLEAN DEFAULT TRUE;
+ DECLARE vMaxWorkShortCycle INT;
+ DECLARE vMaxWorkLongCycle INT;
DECLARE EXIT HANDLER FOR SQLSTATE '45000'
BEGIN
- SELECT CONCAT(u.name, '@verdnatura.es'),
+ SELECT CONCAT(u.name, '@verdnatura.es'),
CONCAT(w.firstName, ' ', w.lastName)
INTO vMailTo, vUserName
FROM account.user u
JOIN worker w ON w.bossFk = u.id
- WHERE w.id = vWorker;
+ WHERE w.id = vWorkerFk;
- CASE vErrorCode
- WHEN 'IS_NOT_ALLOWED_FUTURE' THEN
- SELECT 'No se permite fichar a futuro' INTO vErrorMessage;
- WHEN 'INACTIVE_BUSINESS' THEN
- SELECT 'No hay un contrato en vigor' INTO vErrorMessage;
- WHEN 'IS_NOT_ALLOWED_WORK' THEN
- SELECT 'No está permitido trabajar' INTO vErrorMessage;
- WHEN 'ODD_WORKERTIMECONTROL' THEN
- SELECT 'Fichadas impares' INTO vErrorMessage;
- WHEN 'BREAK_DAY' THEN
- SELECT CONCAT('Descanso diario ', FORMAT(vDayBreak/3600, 0), 'h.')
- INTO vErrorMessage;
- WHEN 'BREAK_WEEK' THEN
- SELECT CONCAT('Descanso semanal ',
- FORMAT(vShortWeekBreak / 3600,0) ,'h. / ',
- FORMAT(vLongWeekBreak / 3600, 0) ,'h.') INTO vErrorMessage;
- WHEN 'WRONG_DIRECTION' THEN
- SELECT 'Dirección incorrecta' INTO vErrorMessage;
- ELSE
- SELECT 'Error sin definir'INTO vErrorMessage;
- END CASE;
+ SELECT `description` INTO vErrorMessage
+ FROM workerTimeControlError
+ WHERE `code` = vErrorCode;
+
+ IF vErrorMessage IS NULL THEN
+ SET vErrorMessage = 'Error sin definir';
+ END IF;
SELECT vErrorMessage `error`;
SELECT CONCAT(vUserName,
' no ha podido fichar por el siguiente problema: ',
vErrorMessage)
INTO vErrorMessage;
+
CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage);
-
END;
IF (vTimed IS NULL) THEN
SET vTimed = util.VN_NOW();
- SET vManual = FALSE;
+ SET vIsManual = FALSE;
END IF;
SET vDated = DATE(vTimed);
- SELECT IF(pc.name = 'Conductor +3500kg',
+ SELECT IF(pc.code = 'driverCE',
wc.dayBreakDriver,
wc.dayBreak),
wc.shortWeekBreak,
wc.longWeekBreak,
- wc.weekScope
+ wc.weekScope,
+ wc.dayMaxTime,
+ wc.maxWorkShortCycle,
+ wc.maxWorkLongCycle
INTO vDayBreak,
vShortWeekBreak,
vLongWeekBreak,
- vWeekScope
+ vWeekScope,
+ vDayMaxTime,
+ vMaxWorkShortCycle,
+ vMaxWorkLongCycle
FROM business b
JOIN professionalCategory pc
ON pc.id = b.workerBusinessProfessionalCategoryFk
- JOIN workerTimeControlConfig wc ON TRUE
- WHERE b.workerFk = vWorker
+ JOIN workerTimeControlConfig wc
+ WHERE b.workerFk = vWorkerFk
AND vDated BETWEEN b.started AND IFNULL(b.ended, vDated);
-
- SELECT timed INTO vLastIn
- FROM workerTimeControl
- WHERE userFk = vWorker
- AND direction = 'in'
- AND timed < vTimed
- ORDER BY timed DESC
- LIMIT 1;
-
- SELECT timed INTO vLastOut
- FROM workerTimeControl
- WHERE userFk = vWorker
- AND direction = 'out'
- AND timed < vTimed
- ORDER BY timed DESC
- LIMIT 1;
-
- SELECT timed INTO vNextIn
- FROM workerTimeControl
- WHERE userFk = vWorker
- AND direction = 'in'
- AND timed > vTimed
- ORDER BY timed ASC
- LIMIT 1;
-
- SELECT direction INTO vNextDirection
- FROM workerTimeControl
- WHERE userFk = vWorker
- AND timed > vTimed
- ORDER BY timed ASC
- LIMIT 1;
-
- SELECT direction INTO vLastDirection
- FROM workerTimeControl
- WHERE userFk = vWorker
- AND timed < vTimed
- ORDER BY timed DESC
- LIMIT 1;
-
- -- FICHADAS A FUTURO
- IF vTimed > DATE_ADD(util.VN_NOW(), INTERVAL 60 SECOND) THEN
- SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE';
- CALL util.throw(vErrorCode);
- END IF;
-
+
-- CONTRATO EN VIGOR
IF vDayBreak IS NULL THEN
SET vErrorCode = 'INACTIVE_BUSINESS';
CALL util.throw(vErrorCode);
END IF;
-
+
+ -- FICHADAS A FUTURO
+ IF vTimed > util.VN_NOW() + INTERVAL 1 MINUTE THEN
+ SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE';
+ CALL util.throw(vErrorCode);
+ END IF;
+
-- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR
- CALL timeBusiness_calculateByWorker(vWorker, vDated, vDated);
+ CALL timeBusiness_calculateByWorker(vWorkerFk, vDated, vDated);
SELECT isAllowedToWork INTO vIsAllowedToWork
FROM tmp.timeBusinessCalculate;
DROP TEMPORARY TABLE tmp.timeBusinessCalculate;
@@ -76535,7 +76660,7 @@ BEGIN
END IF;
-- DIRECCION CORRECTA
- CALL workerTimeControl_direction(vWorker, vTimed);
+ CALL workerTimeControl_direction(vWorkerFk, vTimed);
IF (SELECT
IF(IF(option1 IN ('inMiddle', 'outMiddle'),
'middle',
@@ -76549,26 +76674,50 @@ BEGIN
) THEN
SET vIsError = TRUE;
END IF;
-
+
DROP TEMPORARY TABLE tmp.workerTimeControlDirection;
- IF vIsError = TRUE THEN
+ IF vIsError THEN
SET vErrorCode = 'WRONG_DIRECTION';
CALL util.throw(vErrorCode);
END IF;
-- FICHADAS IMPARES
+ SELECT timed INTO vLastIn
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'in'
+ AND timed < vTimed
+ ORDER BY timed DESC
+ LIMIT 1;
+
IF (SELECT IF(vDirection = 'in',
MOD(COUNT(*), 2) ,
IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE))
FROM workerTimeControl
- WHERE userFk = vWorker
+ WHERE userFk = vWorkerFk
AND timed BETWEEN vLastIn AND vTimed
) THEN
SET vErrorCode = 'ODD_WORKERTIMECONTROL';
CALL util.throw(vErrorCode);
END IF;
-
+
-- DESCANSO DIARIO
+ SELECT timed INTO vLastOut
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'out'
+ AND timed < vTimed
+ ORDER BY timed DESC
+ LIMIT 1;
+
+ SELECT timed INTO vNextIn
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'in'
+ AND timed > vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+
CASE vDirection
WHEN 'in' THEN
IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN
@@ -76586,94 +76735,93 @@ BEGIN
CALL util.throw(vErrorCode);
END IF;
- -- VERIFICAR DESCANSO SEMANAL
- IF (vDirection IN('in', 'out')) THEN
- -- VERIFICA DESCANSO CORTO EN LA ÚLTIMA SEMANA
- SET vGap = vWeekScope;
- SET vTimedLoopPrevious = UNIX_TIMESTAMP((vTimed - INTERVAL vGap SECOND));
- SET vDone = FALSE;
- OPEN vCursor;
- l:LOOP
- FETCH vCursor INTO vTimedLoop;
- IF vDone THEN
- LEAVE l;
- END IF;
- IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN
- SET vHasBreakWeek = TRUE;
- LEAVE l;
- END IF;
- SET vTimedLoopPrevious = vTimedLoop;
- END LOOP l;
- CLOSE vCursor;
- -- VERIFICA DESCANSO LARGO EN LA ÚLTIMAS 2 SEMANAS
- IF NOT vHasBreakWeek THEN
- SET vGap = vWeekScope * 2;
- SET vTimedLoopPrevious = UNIX_TIMESTAMP(vTimed - INTERVAL vGap SECOND);
- SET vDone = FALSE;
- OPEN vCursor;
- l:LOOP
- FETCH vCursor INTO vTimedLoop;
- IF vDone THEN
- LEAVE l;
- END IF;
- IF vLongWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN
- SET vHasBreakWeek = TRUE;
- LEAVE l;
- END IF;
- SET vTimedLoopPrevious = vTimedLoop;
- END LOOP l;
- CLOSE vCursor;
- END IF;
- IF vManual THEN
- -- VERIFICA DESCANSO CORTO EN LA PRÓXIMA SEMANA
- SET vGap = vWeekScope;
- SET vTimedLoopPrevious = vTimed;
- SET vDone = FALSE;
- OPEN vCursor2;
- l:LOOP
- FETCH vCursor2 INTO vTimedLoop;
- IF vDone THEN
- LEAVE l;
- END IF;
- IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN
- SET vHasBreakWeek = TRUE;
- LEAVE l;
- END IF;
- SET vTimedLoopPrevious = vTimedLoop;
- END LOOP l;
- CLOSE vCursor2;
- -- VERIFICA DESCANSO LARGO EN LAS PRÓXIMAS 2 SEMANAS
- IF NOT vHasBreakWeek THEN
- SET vGap = vWeekScope * 2;
- SET vTimedLoopPrevious = vTimed;
- SET vDone = FALSE;
- OPEN vCursor2;
- l:LOOP
- FETCH vCursor2 INTO vTimedLoop;
- IF vDone THEN
- LEAVE l;
- END IF;
- IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN
- SET vHasBreakWeek = TRUE;
- LEAVE l;
- END IF;
- SET vTimedLoopPrevious = vTimedLoop;
- END LOOP l;
- CLOSE vCursor2;
- END IF;
+
+ IF (vDirection IN('in', 'out')) THEN
+ -- VERIFICA MAXIMO TIEMPO DESDE ENTRADA HASTA LA SALIDA
+
+ SELECT timed INTO vNextOut
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'out'
+ AND timed > vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+
+ SELECT direction INTO vNextDirection
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction IN('in','out')
+ AND timed > vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+
+ SELECT direction INTO vLastDirection
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction IN('in', 'out')
+ AND timed < vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+
+ IF (vDirection ='in'
+ AND vNextDirection = 'out'
+ AND UNIX_TIMESTAMP(vNextOut) - UNIX_TIMESTAMP(vTimed) > vDayMaxTime) OR
+ (vDirection ='out'
+ AND vLastDirection = 'in'
+ AND UNIX_TIMESTAMP(vTimed) -UNIX_TIMESTAMP(vLastIn) > vDayMaxTime) THEN
+ SET vErrorCode = 'DAY_MAX_TIME';
+ CALL util.throw(vErrorCode);
END IF;
- IF NOT vHasBreakWeek THEN
+
+ -- VERIFICA DESCANSO SEMANAL
+
+ WITH wtc AS(
+ (SELECT timed
+ FROM vn.workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction IN ('in', 'out')
+ AND timed BETWEEN vTimed - INTERVAL (vWeekScope * 2) SECOND
+ AND vTimed + INTERVAL (vWeekScope * 2) SECOND )
+ UNION
+ (SELECT vTimed)
+ ), wtcGap AS(
+ SELECT timed,
+ TIMESTAMPDIFF(SECOND, LAG(timed) OVER (ORDER BY timed), timed) gap
+ FROM wtc
+ ORDER BY timed
+ ), wtcBreak AS(
+ SELECT timed,
+ IF(IFNULL(gap, 0) > vShortWeekBreak, TRUE, FALSE) hasShortBreak,
+ IF(IFNULL(gap, 0) > vLongWeekBreak, TRUE, FALSE) hasLongBreak
+ FROM wtcGap
+ ORDER BY timed
+ ), wtcBreakCounter AS(
+ SELECT timed,
+ SUM(hasShortBreak) OVER (ORDER BY timed) breakCounter ,
+ LEAD(hasLongBreak) OVER (ORDER BY timed) nextHasLongBreak
+ FROM wtcBreak
+ )SELECT TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed)) > vMaxWorkLongCycle OR
+ (TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed))> vMaxWorkShortCycle
+ AND NOT SUM(IFNULL(nextHasLongBreak, 1)))
+ hasError INTO vIsError
+ FROM wtcBreakCounter
+ GROUP BY breakCounter
+ HAVING hasError
+ LIMIT 1;
+
+ IF vIsError THEN
SET vErrorCode = 'BREAK_WEEK';
CALL util.throw(vErrorCode);
END IF;
END IF;
- -- SE PERMITE FICHAR
- INSERT INTO workerTimeControl(userFk, timed, direction, manual)
- VALUES(vWorker, vTimed, vDirection, vManual);
+ -- Se permite fichar
+ INSERT INTO workerTimeControl(userFk, timed, direction, device, `manual`)
+ VALUES(vWorkerFk, vTimed, vDirection, vDevice, vIsManual);
SELECT LAST_INSERT_ID() id;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -76696,27 +76844,27 @@ BEGIN
* Devuelve que direcciones de fichadas son lógicas a partir de la anterior fichada
* @param vWorkerFk Identificador del trabajador
* @return (option1, option2)
- * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out')
+ * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out')
*/
DECLARE vLastIn DATETIME ;
DECLARE vIsMiddleOdd BOOLEAN ;
- IF (vTimed IS NULL) THEN
+ IF (vTimed IS NULL) THEN
SET vTimed = util.VN_NOW();
END IF;
-
+
SELECT timed INTO vLastIn
- FROM workerTimeControl
+ FROM workerTimeControl
WHERE userFk = vWorkerFk
- AND direction = 'in'
+ AND direction = 'in'
AND timed < vTimed
ORDER BY timed DESC
LIMIT 1;
-
+
SELECT (COUNT(*)mod 2 = 1) INTO vIsMiddleOdd
- FROM workerTimeControl
+ FROM workerTimeControl
WHERE userFk = vWorkerFk
- AND direction = 'middle'
+ AND direction = 'middle'
AND timed BETWEEN vLastIn AND util.VN_NOW();
DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlDirection;
@@ -76765,7 +76913,7 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_getClockIn`(
- vUserFk INT,
+ vUserFk INT,
vDated DATE)
BEGIN
/**
@@ -76775,9 +76923,9 @@ BEGIN
* @param vDated Fecha proporcionada
*/
CALL timeControl_calculateByWorker(
- vUserFk,
+ vUserFk,
DATE_SUB(vDated, INTERVAL 6 DAY), util.dayEnd(vDated));
-
+
SET @position := 0;
SET @lastDated := NULL;
@@ -76794,7 +76942,7 @@ BEGIN
MAX(2daysAgoDirection) 2daysAgoDirection,
MAX(1daysAgo) 1daysAgo,
MAX(1daysAgoDirection) 1daysAgoDirection,
- MAX(0daysAgo) 0daysAgo,
+ MAX(0daysAgo) 0daysAgo,
MAX(0daysAgoDirection) 0daysAgoDirection
FROM(SELECT IF(daysAgo = 6, timed, '') 6daysAgo,
IF(daysAgo = 5, timed, '') 5daysAgo,
@@ -76814,7 +76962,7 @@ BEGIN
direction,
position
FROM(SELECT DATEDIFF(vDated, timed) daysAgo,
- TIME_FORMAT(timed,'%H:%i') timed,
+ TIME_FORMAT(timed,'%H:%i') timed,
IF(DATE(timed) <> @lastDated, @position := 0, NULL),
@position := @position+1 position,
@lastDated := DATE(timed),
@@ -76826,18 +76974,18 @@ BEGIN
LIMIT 10000000000000000000
)sub
)sub2
- GROUP BY position) sub3
+ GROUP BY position) sub3
JOIN (SELECT MAX(IF(daysAgo = 6, timeWorkSeconds, 0)) 6daysAgoTotal,
MAX(IF(daysAgo = 5, timeWorkSeconds, 0)) 5daysAgoTotal,
MAX(IF(daysAgo = 4, timeWorkSeconds, 0)) 4daysAgoTotal,
MAX(IF(daysAgo = 3, timeWorkSeconds, 0)) 3daysAgoTotal,
MAX(IF(daysAgo = 2, timeWorkSeconds, 0)) 2daysAgoTotal,
MAX(IF(daysAgo = 1, timeWorkSeconds, 0)) 1daysAgoTotal,
- MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal
+ MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal
FROM (SELECT DATEDIFF(vDated, dated) daysAgo,
timeWorkSeconds
FROM tmp.timeControlCalculate) sub4)sub5 ON TRUE;
-
+
DROP TEMPORARY TABLE tmp.timeControlCalculate;
END ;;
DELIMITER ;
@@ -76901,97 +77049,45 @@ BEGIN
DECLARE vDirectionPrevious VARCHAR(6);
DECLARE vTimedPrevious DATETIME;
- SELECT direction INTO vDirectionRemove
- FROM vn.workerTimeControl
- WHERE userFk = vUserFk
+ SELECT direction INTO vDirectionRemove
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
AND timed = vTimed ;
IF vDirectionRemove = 'out' THEN
-
+
SELECT timed, direction INTO vTimedPrevious, vDirectionPrevious
- FROM vn.workerTimeControl
- WHERE userFk = vUserFk
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
AND timed < vTimed
ORDER BY timed DESC
- LIMIT 1;
-
+ LIMIT 1;
+
IF vDirectionPrevious = "middle" THEN
- UPDATE vn.workerTimeControl
+ UPDATE vn.workerTimeControl
SET direction = "out"
WHERE userFk = vUserFk
AND timed = vTimedPrevious;
END IF;
-
+
ELSE IF vDirectionRemove = 'in' THEN
- UPDATE vn.workerTimeControl
+ UPDATE vn.workerTimeControl
SET direction = "in"
WHERE userFk = vUserFk
AND timed > vTimed
ORDER BY timed ASC
- LIMIT 1;
+ LIMIT 1;
END IF;
-
+
END IF;
-
+
DELETE FROM vn.workerTimeControl
- WHERE userFk = vUserFk
+ WHERE userFk = vUserFk
AND timed = vTimed;
-
+
CALL vn.workerTimeControlSOWP(vUserFk, vTimed);
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_repair` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_repair`()
-proc: BEGIN
-/**
- * Corrige las fichadas
- *
- */
-
-/*1- poner todos a middle*/
-UPDATE vn.workerTimeControl SET direction = 'middle';
-
-/*2- poner los out*/
-UPDATE vn.workerTimeControl wtc
- JOIN
- (SELECT userFk,MAX(timed) maxTimed FROM
- (SELECT id, userFk, timed, date(timed) dated
- FROM vn.workerTimeControl
- ) sub
- GROUP BY userFk,dated
- )sub
- SET direction = "out"
- WHERE wtc.userFk = sub.userFk
- AND wtc.timed = sub.maxTimed;
-
- /*3- poner los in*/
-UPDATE vn.workerTimeControl wtc
- JOIN
- (SELECT userFk,MIN(timed) maxTimed FROM
- (SELECT id, userFk, timed, date(timed) dated
- FROM vn.workerTimeControl
- ) sub
- GROUP BY userFk,dated
- )sub
- SET direction = "in"
- WHERE wtc.userFk = sub.userFk
- AND wtc.timed = sub.maxTimed ;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -77064,7 +77160,7 @@ BEGIN
AND w.businessFk
GROUP BY tm.userFk,t.dated
ORDER BY tm.userFk,t.dated;
-
+
INSERT INTO vn.mail (receiver, replyTo, subject, body)
SELECT eu.email, 'laboral@verdnatura.es', CONCAT('Registro de horas semana ', WEEK(vDatedFrom), ' año ', YEAR(vDatedFrom)) ,
CONCAT('
@@ -77156,7 +77252,7 @@ BEGIN
IF (DAYNAME(util.VN_CURDATE()) = 'miércoles') THEN
SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL 9 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(), INTERVAL 3 DAY), ' 23:59:59') INTO vDatedFrom, vDatedTo;
-
+
CALL vn.workerTimeControl_sendMailByDepartment(vDatedFrom, vDatedTo, NULL);
END IF;
END ;;
@@ -77167,34 +77263,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_setOrder` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_setOrder`(vUserFk INT, vStarted DATE, vFinished DATE)
-BEGIN
-
- SET @order := 0;
- SET @day := '2000-01-01';
-
- UPDATE vn.workerTimeControl w
- SET w.`order` = @order := IF(@day = @day := date(timed), @order, 0) + 1
- WHERE w.userFk = vUserFk
- AND w.timed BETWEEN vStarted AND util.dayend(vFinished)
- ORDER BY w.timed;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_weekCheckBreak` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -77206,9 +77274,9 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_weekCheckBreak`(vStarted DATE, vEnded DATE)
BEGIN
/**
- * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas
- * El sistema verificará el descanso corto en la siguiente semana
- * o el largo en las 2 siguientes semanas a partir de las fechas dadas
+ * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas
+ * El sistema verificará el descanso corto en la siguiente semana
+ * o el largo en las 2 siguientes semanas a partir de las fechas dadas
* @param vStarted día inicio para verificar
* @param vEnded día final para verificar
* @return tmp.workerWithoutWeekBreak (workerFk)
@@ -77230,10 +77298,10 @@ BEGIN
CALL workerTimeControl_checkBreak(vStarted);
INSERT IGNORE INTO tmp.workerWithoutWeekBreakInWeek
- SELECT workerFk
+ SELECT workerFk
FROM tmp.workerWithoutWeekBreak;
DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreak;
- SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY);
+ SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY);
END WHILE;
END ;;
@@ -77271,7 +77339,7 @@ BEGIN
DECLARE vDepartmentFk INT;
DECLARE isEnabled BOOLEAN DEFAULT TRUE;
- SELECT COUNT(*) INTO vHasSignedToday
+ SELECT COUNT(*) INTO vHasSignedToday
FROM workerTimeControl WHERE timed >= vDated AND userFk = vUserFk;
SET @day := 0;
@@ -77284,16 +77352,16 @@ BEGIN
SELECT fichada_anterior, fichada_actual, interval_in_minutes, jornadas
FROM
(
- SELECT @lastTimed fichada_anterior,
+ SELECT @lastTimed fichada_anterior,
timed,
CAST(time_to_sec(timediff(timed,@lastTimed )) / 60 AS UNSIGNED) as interval_in_minutes,
IF(day(timed) != @day, 1, 0) as jornadas,
@day := day(timed) dia_del_mes,
- @lastTimed := timed fichada_actual
+ @lastTimed := timed fichada_actual
FROM
(
SELECT day(timed) as dayNumber, dayname(timed) as dayName, timed
- FROM
+ FROM
(SELECT TIMESTAMPADD(DAY, -11, util.VN_NOW()) as timed, vUserFk as userFk -- Fichada virtual para los en los que no se ha trabajado la semana anterior
UNION ALL
SELECT timed, userFk
@@ -77301,18 +77369,18 @@ BEGIN
WHERE userFk = vUserFk
AND timed >= TIMESTAMPADD(DAY, -10,vDated)
UNION ALL
- SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk
+ SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk
) sub4
ORDER BY timed
) sub
-
+
) sub2
WHERE fichada_actual >= TIMESTAMPADD(WEEK, -1, vDated)
) sub3 ;
SELECT IFNULL(SUM(impar),0) into vImpares
FROM (
- SELECT day(timed) as dayNumber,
+ SELECT day(timed) as dayNumber,
count(*) mod 2 as impar
FROM vn.workerTimeControl wtc
WHERE userFk = vUserFk
@@ -77329,29 +77397,29 @@ BEGIN
AND at2.isAllowedToWork = FALSE
AND b.workerFk = vUserFk
LIMIT 1;
-
+
-- Contrato en vigor
SELECT IF(COUNT(*),vCantWork,'Sin contrato') INTO vCantWork
FROM business b
WHERE b.workerFk = vUserFk
AND b.started <= vDated
AND IFNULL(b.ended, vDated) >= vDated;
-
+
-- Departamento si vTabletFk es 0 no hacemos comprobacion (Madrid y Vilassar)
IF vTabletFk <> '0' THEN
-- 1 Obtener el departamento del usuario
SELECT wtcu.departmentFk INTO vDepartmentFk
FROM workerTimeControlUserInfo wtcu
WHERE wtcu.userFk = vUserFk;
- -- 2 Comprobar si la tablet pertenece al departamento
+ -- 2 Comprobar si la tablet pertenece al departamento
SELECT COUNT(td.tabletFk) INTO isEnabled
FROM tabletDepartment td
WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk;
-
+
END IF;
-
+
IF vJornadas IS NOT NULL THEN
-
+
SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis
UNION ALL
SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, IF(vDescansos12h >= vJornadas, 'Correcto','Error: 1 por jornada') as Análisis
@@ -77360,9 +77428,9 @@ BEGIN
UNION ALL
SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, IF(vImpares = 0, 'Correcto','Error') as Análisis
UNION ALL
- SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item,
- '' as Cantidad,
- IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis
+ SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item,
+ '' as Cantidad,
+ IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis
UNION ALL
SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis;
@@ -77376,7 +77444,7 @@ BEGIN
UNION ALL
SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, 'Correcto' as Análisis
UNION ALL
- SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item,
+ SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item,
'' as Cantidad, IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis
UNION ALL
SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis;
@@ -77406,11 +77474,11 @@ BEGIN
* @param vDepartmentFk id del departamento
*
*/
-
- SELECT w.id,w.firstName, w.lastName,d.name
- FROM worker w
- JOIN workerDepartment wd ON wd.workerFk = w.id
- JOIN department d ON d.id = wd.departmentFk
+
+ SELECT w.id,w.firstName, w.lastName,d.name
+ FROM worker w
+ JOIN workerDepartment wd ON wd.workerFk = w.id
+ JOIN department d ON d.id = wd.departmentFk
WHERE d.id = vDepartmentFk
ORDER BY firstName;
@@ -77430,46 +77498,30 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_getHierarchy`(vBoss INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_getHierarchy`(vUserFk INT)
BEGIN
- DECLARE EXIT HANDLER FOR 1062 BEGIN
- CALL util.throw('INFINITE_LOOP');
- END;
-
- DROP TEMPORARY TABLE IF EXISTS workerHierarchy;
- CREATE TEMPORARY TABLE workerHierarchy
+/**
+ * Retorna una tabla temporal con los trabajadores que tiene
+ * el usuario por debajo en la jerarquía de la empresa.
+ *
+ * @param vUserFk Id de usuario.
+ * @return tmp.workerHierarchyList
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tmp.workerHierarchyList
(PRIMARY KEY (workerFk))
ENGINE = MEMORY
- SELECT vBoss AS workerFk;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.workerHierarchyList;
- CREATE TEMPORARY TABLE tmp.workerHierarchyList
- (PRIMARY KEY (workerFk))
- ENGINE = MEMORY
- SELECT vBoss AS workerFk, 0 AS isChecked;
-
-
- WHILE (SELECT COUNT(*) FROM tmp.workerHierarchyList WHERE NOT isChecked) > 0 DO
-
- INSERT INTO tmp.workerHierarchyList
- SELECT w.id, 0
- FROM worker w
- JOIN workerHierarchy wh ON wh.workerFk = w.bossFk;
-
- UPDATE tmp.workerHierarchyList whl
- JOIN workerHierarchy wh ON wh.workerFk = whl.workerFk
- SET whl.isChecked = 1;
-
- TRUNCATE workerHierarchy;
-
- INSERT INTO workerHierarchy
- SELECT workerFk
- FROM tmp.workerHierarchyList
- WHERE NOT isChecked;
-
- END WHILE;
-
- DROP TEMPORARY TABLE IF EXISTS workerHierarchy;
+ WITH RECURSIVE workerHierarchy AS (
+ SELECT id workerFk, bossFk, 0 depth
+ FROM vn.worker
+ WHERE id = vUserFk
+ UNION ALL
+ SELECT w.id, w.bossFk, wh.depth + 1
+ FROM vn.worker w
+ JOIN workerHierarchy wh ON w.bossFk = wh.workerFk
+ )
+ SELECT *
+ FROM workerHierarchy
+ ORDER BY depth, workerFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -77495,7 +77547,7 @@ BEGIN
SELECT s.id,s.description,s.warehouseFk
FROM sector s
- JOIN operator o ON o.sectorFk = s.id
+ JOIN operator o ON o.sectorFk = s.id
WHERE o.workerFk = account.myUser_getId();
END ;;
@@ -77543,15 +77595,34 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_updateBusiness`(vSelf INT)
BEGIN
/**
- * Actualiza en la tabla @worker el contrato actual del trabajador.
+ * Activates an account and configures its email settings.
*
- * @param vSelf Id del trabajador
+ * @param vSelf account id.
*/
- UPDATE worker w
- LEFT JOIN business b ON b.workerFk = w.id
- AND util.VN_CURDATE() BETWEEN b.started AND IFNULL(b.ended, util.VN_CURDATE())
- SET w.businessFk = b.id
- WHERE w.id = vSelf;
+ DECLARE vOldBusinessFk INT;
+ DECLARE vNewBusinessFk INT;
+
+ SELECT businessFk INTO vOldBusinessFk FROM worker WHERE id = vSelf;
+
+ SELECT id INTO vNewBusinessFk
+ FROM business
+ WHERE workerFk = vSelf
+ AND util.VN_CURDATE() BETWEEN started AND IFNULL(ended, util.VN_CURDATE())
+ LIMIT 1;
+
+ UPDATE worker
+ SET businessFk = vNewBusinessFk
+ WHERE id = vSelf;
+
+ IF vOldBusinessFk IS NULL THEN
+ CALL account.account_enable(vSelf);
+
+ UPDATE client c
+ JOIN payMethod pm ON pm.code = 'bankDraft'
+ SET c.payMethodFk = pm.id
+ WHERE c.id = vSelf
+ AND c.iban;
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -77580,8 +77651,8 @@ BEGIN
DECLARE vDone BOOL;
DECLARE vCursor CURSOR FOR
- SELECT DISTINCT b.workerFk
- FROM business b
+ SELECT DISTINCT b.workerFk
+ FROM business b
WHERE b.started > vBusinessUpdated AND b.started <= vCurdate
OR b.ended >= vBusinessUpdated AND b.ended < vCurdate;
@@ -77624,10 +77695,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workingHours`(username varchar(255), logon boolean)
BEGIN
DECLARE userid int(11);
-
+
SELECT vn.getUserId(username) INTO userid;
SELECT username, userid;
- IF userid IS NOT NULL THEN
+ IF userid IS NOT NULL THEN
IF (logon) THEN
CALL vn.workingHoursTimeIn(userid);
ELSE
@@ -77696,17 +77767,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `wrongEqualizatedClient`()
BEGIN
SELECT clientFk, c.name, c.isActive, c.isTaxDataChecked, count(ie) as num
FROM vn.client c
- JOIN
+ JOIN
(
- SELECT DISTINCT
+ SELECT DISTINCT
`a`.`clientFk` ,
a.isEqualizated = 0 as ie
-
+
FROM
`vn`.`address` `a`
) sub ON sub.clientFk = c.id
WHERE c.hasToInvoiceByAddress = FALSE
-
+
GROUP BY clientFk
HAVING num > 1
UNION ALL
@@ -77724,6 +77795,60 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `XDiario_check` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `XDiario_check`()
+BEGIN
+/**
+ * Realiza la revisión diaria de los asientos contables,
+ * identificando y notificando los asientos descuadrados
+ * y ajustando los saldos en caso necesario.
+ */
+ INSERT INTO mail (receiver, subject, body)
+ SELECT 'cau@verdnatura.es',
+ 'Asientos descuadrados',
+ GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n')
+ FROM (
+ SELECT ASIEN,
+ SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon
+ FROM XDiario
+ WHERE NOT enlazado
+ GROUP BY ASIEN
+ HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01
+ ) sub
+ HAVING COUNT(*);
+
+ UPDATE XDiario xd
+ JOIN (
+ SELECT xd.id, SUBCTA, recon
+ FROM XDiario xd
+ JOIN (
+ SELECT ASIEN,
+ SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon
+ FROM XDiario
+ WHERE NOT enlazado
+ GROUP BY ASIEN
+ HAVING recon
+ ) sub ON sub.ASIEN = xd.ASIEN
+ WHERE xd.SUBCTA > '5999999999'
+ GROUP BY xd.ASIEN
+ ) sub ON sub.id = xd.id
+ SET xd.Eurohaber = IF(IFNULL(xd.Eurohaber, 0) = 0, xd.Eurohaber, xd.Eurohaber + sub.recon),
+ xd.Eurodebe = IF(IFNULL(xd.Eurodebe, 0) = 0, xd.Eurodebe, xd.Eurodebe - sub.recon);
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `XDiario_checkDate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -77790,27 +77915,27 @@ proc: BEGIN
SELECT scope INTO vScope
FROM zoneConfig;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.zone;
CREATE TEMPORARY TABLE tmp.zone
(INDEX (id))
ENGINE = MEMORY
SELECT id FROM zone;
-
+
TRUNCATE TABLE zoneClosure;
-
+
WHILE vCounter <= vScope DO
-
+
CALL zone_getOptionsForShipment(vShipped, TRUE);
-
+
REPLACE zoneClosure(zoneFk, dated, `hour`)
- SELECT zoneFk, vShipped, `hour`
+ SELECT zoneFk, vShipped, `hour`
FROM tmp.zoneOption;
-
+
SET vCounter = vCounter + 1;
SET vShipped = TIMESTAMPADD(DAY, 1, vShipped);
END WHILE;
-
+
-- DROP TEMPORARY TABLE tmp.zone;
DO RELEASE_LOCK('vn.zoneClosure_recalc');
END ;;
@@ -77904,7 +78029,7 @@ BEGIN
OR (vSelf IS NOT NULL AND parentFk = vSelf);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
SET vSons = 0;
OPEN vChildren;
@@ -77915,11 +78040,11 @@ BEGIN
IF vDone THEN
LEAVE myLoop;
END IF;
-
+
SET vIndex = vIndex + 1;
SET vLft = vIndex;
SET vSons = vSons + 1;
-
+
CALL zoneGeo_calcTreeRec(
vChildFk,
CONCAT(vPath, vChildFk, '/'),
@@ -78022,7 +78147,7 @@ proc: BEGIN
SELECT isChanged INTO vIsChanged
FROM zoneGeoRecalc;
-
+
IF vIsChanged THEN
UPDATE zoneGeoRecalc SET isChanged = FALSE;
CALL vn.zoneGeo_calcTree;
@@ -78119,6 +78244,74 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `zone_getAddresses` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getAddresses`(
+ vSelf INT,
+ vLanded DATE
+)
+BEGIN
+/**
+ * Devuelve un listado de todos los clientes activos
+ * con consignatarios a los que se les puede
+ * vender producto para esa zona y no tiene un ticket
+ * para ese día.
+ *
+ * @param vSelf Id de zona
+ * @param vDated Fecha de entrega
+ * @return Un select
+ */
+ CALL zone_getPostalCode(vSelf);
+
+ WITH notHasTicket AS (
+ SELECT id
+ FROM vn.client
+ WHERE id NOT IN (
+ SELECT clientFk
+ FROM vn.ticket
+ WHERE landed BETWEEN vLanded AND util.dayEnd(vLanded)
+ )
+ )
+ SELECT c.id clientFk,
+ c.name,
+ c.phone,
+ c.mobile,
+ c.salesPersonFk,
+ u.name username,
+ aai.invoiced,
+ cnb.lastShipped
+ FROM vn.client c
+ JOIN notHasTicket ON notHasTicket.id = c.id
+ LEFT JOIN account.`user` u ON u.id = c.salesPersonFk
+ JOIN vn.`address` a ON a.clientFk = c.id
+ JOIN vn.postCode pc ON pc.code = a.postalCode
+ JOIN vn.town t ON t.id = pc.townFk AND t.provinceFk = a.provinceFk
+ JOIN vn.zoneGeo zg ON zg.name = a.postalCode
+ JOIN tmp.zoneNodes zn ON zn.geoFk = pc.geoFk
+ LEFT JOIN bs.clientNewBorn cnb ON cnb.clientFk = c.id
+ LEFT JOIN vn.annualAverageInvoiced aai ON aai.clientFk = c.id
+ JOIN vn.clientType ct ON ct.code = c.typeFk
+ WHERE a.isActive
+ AND c.isActive
+ AND ct.code = 'normal'
+ AND c.businessTypeFk <> 'worker'
+ GROUP BY c.id;
+
+ DROP TEMPORARY TABLE tmp.zoneNodes;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getAgency` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -78210,7 +78403,7 @@ proc:BEGIN
* @table tmp.closedZones(zoneFk, warehouseFk);
*/
DROP TEMPORARY TABLE IF EXISTS tmp.closedZones;
-
+
CREATE TEMPORARY TABLE tmp.closedZones (
`zoneFk` int(11) NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL,
@@ -78252,7 +78445,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getCollisions`()
BEGIN
/**
- * Calcula si para un mismo codigo postal y dia
+ * Calcula si para un mismo codigo postal y dia
* hay mas de una zona configurada y manda correo
*
*/
@@ -78261,16 +78454,16 @@ BEGIN
DECLARE vIsDone INT DEFAULT FALSE;
DECLARE vTableCollisions TEXT;
DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
DROP TEMPORARY TABLE IF EXISTS tmp.zone;
CREATE TEMPORARY TABLE tmp.zone
- SELECT z.id
+ SELECT z.id
FROM zone z
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
- WHERE dm.code IN ('AGENCY','DELIVERY');
+ WHERE dm.code IN ('AGENCY','DELIVERY');
CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE);
@@ -78285,7 +78478,7 @@ BEGIN
PRIMARY KEY zoneFkk (zoneFk, geoFk),
INDEX(geoFk))
ENGINE = MyISAM;
-
+
OPEN cur1;
cur1Loop: LOOP
SET vIsDone = FALSE;
@@ -78293,40 +78486,40 @@ BEGIN
IF vIsDone THEN
LEAVE cur1Loop;
END IF;
-
+
CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE);
- myLoop: LOOP
+ myLoop: LOOP
SET vGeoFk = NULL;
- SELECT geoFk INTO vGeoFk
+ SELECT geoFk INTO vGeoFk
FROM tmp.zoneNodes zn
WHERE NOT isChecked
LIMIT 1;
-
+
IF vGeoFk IS NULL THEN
LEAVE myLoop;
END IF;
-
+
CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE);
UPDATE tmp.zoneNodes
- SET isChecked = TRUE
+ SET isChecked = TRUE
WHERE geoFk = vGeoFk;
END LOOP;
END LOOP;
CLOSE cur1;
- DELETE FROM tmp.zoneNodes
+ DELETE FROM tmp.zoneNodes
WHERE sons > 0;
-
+
DROP TEMPORARY TABLE IF EXISTS geoCollision;
CREATE TEMPORARY TABLE geoCollision
SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk
FROM tmp.zoneNodes zn
JOIN zone z ON z.id = zn.zoneFk
- JOIN zoneWarehouse zw ON z.id = zw.zoneFk
+ JOIN zoneWarehouse zw ON z.id = zw.zoneFk
GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk
HAVING count(*) > 1;
-
+
SELECT '
C.Postal
@@ -78336,39 +78529,39 @@ BEGIN
Almacén
Salix
' INTO vTableCollisions;
-
- INSERT INTO mail (receiver,replyTo,subject,body)
+
+ INSERT INTO mail (receiver,replyTo,subject,body)
SELECT 'pepe@verdnatura.es' receiver,
'noreply@verdnatura.es' replyTo,
CONCAT('Colisiones en zonas ', util.VN_CURDATE()) subject,
CONCAT(vTableCollisions,
GROUP_CONCAT(sub.td SEPARATOR ''),
'
')
+ FROM printQueue pq
+ LEFT JOIN worker w ON w.id = pq.workerFk
+ LEFT JOIN printer p ON p.id = pq.printerFk
+ LEFT JOIN report r ON r.id = pq.reportFk
+ JOIN printQueueConfig
+ LIMIT vPrintQueueLimit;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ SELECT printQueueLimit INTO vPrintQueueLimit
+ FROM printQueueConfig;
+
+ SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum
+ FROM printQueue WHERE statusCode = 'queued';
+
+ SELECT isAlreadyNotified INTO vIsAlreadyNotified
+ FROM printingQueueCheck;
+
+ IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND
+ (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND
+ vIsAlreadyNotified = FALSE AND vCurrentCount > 0
+ THEN
+
+ SELECT '
\n\t\t\t\t\t
\n\t\t\t\t\t\t
Id Cola
\n\t\t\t\t\t\t
Ruta Impresora
\n\t\t\t\t\t\t
Informe
\n\t\t\t\t\t\t
Estado
\n\t\t\t\t\t\t
Trabajador
\n\t\t\t\t\t\t
Error
\n\t\t\t\t\t
' INTO vTableQueue;
+
+ OPEN vCur;
+
+ l: LOOP
+
+ SET vDone = FALSE;
+
+ FETCH vCur INTO vLineQueue;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue;
+
+ END LOOP;
+
+ CLOSE vCur;
+
+ CALL mail_insert(
+ 'cau@verdnatura.es',
+ NULL,
+ 'Servidor de impresion parado',
+ CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
')
+ );
+
+ UPDATE printingQueueCheck SET isAlreadyNotified = TRUE;
+ END IF;
+
+ IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND
+ vIsAlreadyNotified = TRUE
+ THEN
+ UPDATE printingQueueCheck SET isAlreadyNotified = FALSE;
+ END IF;
+
+ UPDATE printingQueueCheck
+ SET lastCount = vCurrentCount,
+ lastCheckSum = vCheckSum;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/events/route_doRecalc.sql b/db/routines/vn/events/route_doRecalc.sql
new file mode 100644
index 000000000..62f75a3bc
--- /dev/null
+++ b/db/routines/vn/events/route_doRecalc.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`route_doRecalc`
+ ON SCHEDULE EVERY 10 SECOND
+ STARTS '2021-07-08 07:32:23.000'
+ ON COMPLETION PRESERVE
+ ENABLE
+DO CALL route_doRecalc$$
+DELIMITER ;
diff --git a/db/routines/vn/events/ticket_doRecalc.sql b/db/routines/vn/events/ticket_doRecalc.sql
new file mode 100644
index 000000000..9209c5715
--- /dev/null
+++ b/db/routines/vn/events/ticket_doRecalc.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`ticket_doRecalc`
+ ON SCHEDULE EVERY 10 SECOND
+ STARTS '2022-01-28 09:29:18.000'
+ ON COMPLETION PRESERVE
+ ENABLE
+DO CALL ticket_doRecalc$$
+DELIMITER ;
diff --git a/db/routines/vn/events/travel_doRecalc.sql b/db/routines/vn/events/travel_doRecalc.sql
new file mode 100644
index 000000000..a08ecc068
--- /dev/null
+++ b/db/routines/vn/events/travel_doRecalc.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`travel_doRecalc`
+ ON SCHEDULE EVERY 15 SECOND
+ STARTS '2019-05-17 10:52:29.000'
+ ON COMPLETION PRESERVE
+ ENABLE
+DO CALL travel_doRecalc$$
+DELIMITER ;
diff --git a/db/routines/vn/events/vehicle_notify.sql b/db/routines/vn/events/vehicle_notify.sql
new file mode 100644
index 000000000..d974e1817
--- /dev/null
+++ b/db/routines/vn/events/vehicle_notify.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`vehicle_notify`
+ ON SCHEDULE EVERY 1 DAY
+ STARTS '2022-01-01 00:07:00.000'
+ ON COMPLETION NOT PRESERVE
+ ENABLE
+ COMMENT 'Notifies subscribed users of events in vehicles that are about t'
+DO CALL vn.vehicle_notifyEvents$$
+DELIMITER ;
diff --git a/db/routines/vn/events/workerJourney_doRecalc.sql b/db/routines/vn/events/workerJourney_doRecalc.sql
new file mode 100644
index 000000000..61077fc5b
--- /dev/null
+++ b/db/routines/vn/events/workerJourney_doRecalc.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`workerJourney_doRecalc`
+ ON SCHEDULE EVERY 1 DAY
+ STARTS '2023-07-22 04:00:00.000'
+ ON COMPLETION PRESERVE
+ ENABLE
+DO CALL workerJourney_replace(util.VN_CURDATE() - INTERVAL 1 WEEK, util.VN_CURDATE(), NULL)$$
+DELIMITER ;
diff --git a/db/routines/vn/events/worker_updateChangedBusiness.sql b/db/routines/vn/events/worker_updateChangedBusiness.sql
new file mode 100644
index 000000000..02f7af8aa
--- /dev/null
+++ b/db/routines/vn/events/worker_updateChangedBusiness.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`worker_updateChangedBusiness`
+ ON SCHEDULE EVERY 1 DAY
+ STARTS '2000-01-01 00:00:05.000'
+ ON COMPLETION NOT PRESERVE
+ ENABLE
+DO CALL worker_updateChangedBusiness$$
+DELIMITER ;
diff --git a/db/routines/vn/events/zoneGeo_doCalc.sql b/db/routines/vn/events/zoneGeo_doCalc.sql
new file mode 100644
index 000000000..579141e13
--- /dev/null
+++ b/db/routines/vn/events/zoneGeo_doCalc.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`zoneGeo_doCalc`
+ ON SCHEDULE EVERY 15 SECOND
+ STARTS '2019-09-13 15:30:47.000'
+ ON COMPLETION PRESERVE
+ ENABLE
+DO CALL vn.zoneGeo_doCalc$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/MIDNIGHT.sql b/db/routines/vn/functions/MIDNIGHT.sql
new file mode 100644
index 000000000..c2df0c0c6
--- /dev/null
+++ b/db/routines/vn/functions/MIDNIGHT.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`MIDNIGHT`(vDate DATE)
+ RETURNS datetime
+ DETERMINISTIC
+BEGIN
+ RETURN TIMESTAMP(vDate,'23:59:59');
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/addressTaxArea.sql b/db/routines/vn/functions/addressTaxArea.sql
new file mode 100644
index 000000000..1d4e9e2f0
--- /dev/null
+++ b/db/routines/vn/functions/addressTaxArea.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`addressTaxArea`(vAddresId INT, vCompanyId INT)
+ RETURNS varchar(25) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ DETERMINISTIC
+BEGIN
+/**
+ * Devuelve el area de un Consignatario,
+ * intracomunitario, extracomunitario, nacional o recargo de equivalencia.
+ * Asumimos que no tenemos ninguna empresa
+ *
+ * @param vAddresId Id del Consignatario
+ * @param vCompanyId Compañia desde la que se factura
+ * @return Código de area
+ */
+ DECLARE vTaxArea VARCHAR(25);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
+ CREATE TEMPORARY TABLE tmp.addressCompany
+ SELECT vAddresId addressFk, vCompanyId companyFk;
+
+ CALL vn.addressTaxArea();
+ SELECT areaFk INTO vTaxArea FROM tmp.addressTaxArea;
+
+ DROP TEMPORARY TABLE
+ tmp.addressCompany,
+ tmp.addressTaxArea;
+
+ RETURN vTaxArea;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/address_getGeo.sql b/db/routines/vn/functions/address_getGeo.sql
new file mode 100644
index 000000000..1a9f5ddb8
--- /dev/null
+++ b/db/routines/vn/functions/address_getGeo.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`address_getGeo`(vSelf INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Returns the geo for the passed address.
+ *
+ * @param vSelf The address id
+ * @return The geo id
+ */
+ DECLARE vGeoFk INT;
+
+ SELECT p.geoFk INTO vGeoFk
+ FROM address a
+ JOIN town t ON t.provinceFk = a.provinceFk
+ JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode
+ WHERE a.id = vSelf
+ ORDER BY (a.city SOUNDS LIKE t.`name`) DESC
+ LIMIT 1;
+
+ RETURN vGeoFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/barcodeToItem.sql b/db/routines/vn/functions/barcodeToItem.sql
new file mode 100644
index 000000000..ee0315118
--- /dev/null
+++ b/db/routines/vn/functions/barcodeToItem.sql
@@ -0,0 +1,51 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`barcodeToItem`(vBarcode VARCHAR(22))
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+
+/**
+ * Obtiene el id del artículo
+ *
+ * @param vBarcode código de barras
+ *
+ * return id del item
+ */
+
+ DECLARE vItemFk INT;
+
+ SELECT id INTO vItemFk
+ FROM vn.item
+ WHERE id = vBarcode OR comment = vBarcode
+ LIMIT 1;
+
+ IF vItemFk THEN
+ RETURN vItemFk;
+ END IF;
+
+ SELECT itemFk INTO vItemFk
+ FROM buy
+ WHERE id = vBarcode;
+
+ IF vItemFk THEN
+ RETURN vItemFk;
+ END IF;
+
+ SELECT itemFk INTO vItemFk
+ FROM itemBarcode
+ WHERE code = vBarcode;
+
+ IF vItemFk THEN
+ RETURN vItemFk;
+ END IF;
+
+ SELECT i.id INTO vItemFk
+ FROM vn.item i
+ WHERE i.name LIKE CONCAT('%',vBarcode,'%')
+ ORDER BY i.id ASC
+ LIMIT 1;
+
+ RETURN vItemFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/buy_getUnitVolume.sql b/db/routines/vn/functions/buy_getUnitVolume.sql
new file mode 100644
index 000000000..baf300450
--- /dev/null
+++ b/db/routines/vn/functions/buy_getUnitVolume.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`buy_getUnitVolume`(vSelf INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Calculates the unit volume occupied by a buy.
+ *
+ * @param vSelf The buy id
+ * @return The unit volume in cubic centimeters
+ */
+ DECLARE vItem INT;
+ DECLARE vPackaging VARCHAR(10);
+ DECLARE vPacking INT;
+
+ SELECT itemFk, packagingFk, packing
+ INTO vItem, vPackaging, vPacking
+ FROM buy
+ WHERE id = vSelf;
+
+ RETURN IFNULL(ROUND(item_getVolume(vItem, vPackaging) / vPacking), 0);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/buy_getVolume.sql b/db/routines/vn/functions/buy_getVolume.sql
new file mode 100644
index 000000000..c29c0a57c
--- /dev/null
+++ b/db/routines/vn/functions/buy_getVolume.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`buy_getVolume`(vSelf INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Calculates the volume occupied by a buy.
+ *
+ * @param vSelf The buy id
+ * @return The volume in cubic centimeters
+ */
+ DECLARE vItem INT;
+ DECLARE vPackaging VARCHAR(10);
+
+ SELECT itemFk, packagingFk INTO vItem, vPackaging
+ FROM buy
+ WHERE id = vSelf;
+
+ RETURN item_getVolume(vItem, vPackaging);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/catalog_componentReverse.sql b/db/routines/vn/functions/catalog_componentReverse.sql
new file mode 100644
index 000000000..f37b20890
--- /dev/null
+++ b/db/routines/vn/functions/catalog_componentReverse.sql
@@ -0,0 +1,95 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`catalog_componentReverse`(vWarehouse INT,
+ vCost DECIMAL(10,3),
+ vM3 DECIMAL(10,3),
+ vAddressFk INT,
+ vZoneFk INT)
+ RETURNS decimal(10,3)
+ DETERMINISTIC
+BEGIN
+ /* Calcula los componentes para un cliente a partir de un coste y volumen
+ * @param vWarehouse
+ * @param vCost Valor de coste del articulo
+ * @param vM3 m3 del articulo
+ * @param vAddressFk
+ * @param vZoneFk
+ * @return vRetailedPrice precio de venta sin iva
+ * @return tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
+ */
+
+ DECLARE vBoxVolume BIGINT;
+ DECLARE vCustomer INT;
+ DECLARE vComponentRecovery INT DEFAULT 17;
+ DECLARE vComponentMana INT DEFAULT 39;
+ DECLARE vDeliveryComponent INT DEFAULT 15;
+ DECLARE vComponentMargin INT DEFAULT 29;
+ DECLARE vComponentCost INT DEFAULT 28;
+ DECLARE vRetailedPrice DECIMAL(10,2);
+ DECLARE vItem INT DEFAULT 98;
+
+ SELECT volume INTO vBoxVolume
+ FROM vn.packaging
+ WHERE id = '94';
+
+ SELECT clientFk INTO vCustomer FROM address WHERE id = vAddressFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.catalog_component;
+ CREATE TEMPORARY TABLE tmp.catalog_component (
+ `warehouseFk` INT UNSIGNED NOT NULL,
+ `itemFk` INT NOT NULL,
+ `componentFk` INT UNSIGNED NOT NULL,
+ `cost` DECIMAL(10,4) NOT NULL,
+ INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
+ UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC));
+
+ -- Cost
+ INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
+ SELECT vWarehouse, vItem, vComponentCost, vCost
+ FROM vn.rate
+ WHERE dated <= util.VN_CURDATE()
+ AND warehouseFk = vWarehouse
+ ORDER BY dated DESC
+ LIMIT 1;
+
+ -- Margen
+ -- No se aplica margen, cau 12589
+/* INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
+ SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost
+ FROM vn.rate
+ WHERE dated <= util.VN_CURDATE()
+ AND warehouseFk = vWarehouse
+ ORDER BY dated DESC
+ LIMIT 1;
+ */
+ -- Recobro
+ INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
+ SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3)
+ FROM bi.claims_ratio
+ WHERE Id_Cliente = vCustomer AND recobro > 0.009;
+
+ -- Componente de maná automático, en función del maná acumulado por el comercial.
+ INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
+ SELECT vWarehouse, vItem, vComponentMana, ROUND(wm.pricesModifierRate, 3)
+ FROM client c
+ JOIN vn.workerMana wm ON c.salesPersonFk = wm.workerFk
+ WHERE wm.isPricesModifierActivated AND c.id = vCustomer LIMIT 1;
+
+ -- Reparto
+ INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
+ SELECT vWarehouse, vItem, vDeliveryComponent,
+ ROUND(
+ vM3
+ * (z.price - z.bonus)
+ * z.inflation
+ / vBoxVolume, 4
+ )
+ FROM zone z
+ WHERE z.id = vZoneFk;
+
+ -- Precio de venta
+ SELECT SUM(cost) INTO vRetailedPrice
+ FROM tmp.catalog_component;
+
+ RETURN vRetailedPrice;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/clientGetMana.sql b/db/routines/vn/functions/clientGetMana.sql
new file mode 100644
index 000000000..fa983c2b2
--- /dev/null
+++ b/db/routines/vn/functions/clientGetMana.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`clientGetMana`(vClient INT)
+ RETURNS decimal(10,2)
+ DETERMINISTIC
+BEGIN
+/**
+ * Devuelve el mana del cliente.
+ *
+ * @param vClient Id del cliente
+ * @return Mana del cliente
+ */
+ DECLARE vMana DECIMAL(10,2);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.client
+ SELECT vClient id;
+
+ CALL client_getMana();
+
+ SET vMana = (SELECT mana
+ FROM tmp.clientMana);
+
+ DROP TEMPORARY TABLE
+ tmp.client,
+ tmp.clientMana;
+
+ RETURN IFNULL(vMana,0);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/clientGetSalesPerson.sql b/db/routines/vn/functions/clientGetSalesPerson.sql
new file mode 100644
index 000000000..4b8601be3
--- /dev/null
+++ b/db/routines/vn/functions/clientGetSalesPerson.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`clientGetSalesPerson`(vClientFk INT, vDated DATE)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * DEPRECATED: use client_getSalesPerson
+ **/
+ RETURN client_getSalesPerson(vClientFk, vDated);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/clientTaxArea.sql b/db/routines/vn/functions/clientTaxArea.sql
new file mode 100644
index 000000000..f03520b0b
--- /dev/null
+++ b/db/routines/vn/functions/clientTaxArea.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`clientTaxArea`(vClientId INT, vCompanyId INT)
+ RETURNS varchar(25) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+* Devuelve el area de un cliente,
+* intracomunitario, extracomunitario o nacional.
+*
+* @param vClient Id del cliente
+* @param vCompanyFk Compañia desde la que se factura
+* @return Código de area
+*/
+ DECLARE vTaxArea VARCHAR(25);
+
+ SELECT addressTaxArea(defaultAddressFk, vCompanyId)
+ INTO vTaxArea
+ FROM client
+ WHERE id = vClientId;
+
+ RETURN vTaxArea;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/client_getDebt.sql b/db/routines/vn/functions/client_getDebt.sql
new file mode 100644
index 000000000..8c715d2db
--- /dev/null
+++ b/db/routines/vn/functions/client_getDebt.sql
@@ -0,0 +1,38 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getDebt`(`vClient` INT, `vDate` DATE)
+ RETURNS decimal(10,2)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Returns the risk of a customer.
+ *
+ * @param vClient client id
+ * @param vDate date to check the risk
+ * @return Client risk
+ */
+ DECLARE vDebt DECIMAL(10,2);
+ DECLARE vHasDebt BOOLEAN;
+
+ SELECT COUNT(*) INTO vHasDebt
+ FROM `client` c
+ WHERE c.id = vClient AND c.typeFk = 'normal';
+
+ IF NOT vHasDebt THEN
+ RETURN 0;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT);
+ INSERT INTO tmp.clientGetDebt SET clientFk = vClient;
+
+ CALL vn.client_getDebt(vDate);
+
+ SELECT risk INTO vDebt FROM tmp.risk;
+
+ DROP TEMPORARY TABLE
+ tmp.clientGetDebt,
+ tmp.risk;
+
+ RETURN vDebt;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/client_getFromPhone.sql b/db/routines/vn/functions/client_getFromPhone.sql
new file mode 100644
index 000000000..c6ded691b
--- /dev/null
+++ b/db/routines/vn/functions/client_getFromPhone.sql
@@ -0,0 +1,43 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getFromPhone`(vPhone VARCHAR(255))
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Searchs a customer associated to the phone number.
+ *
+ * @param vPhone The phone number
+ * @return The client id or %NULL if not found
+ */
+ DECLARE vClient INT DEFAULT NULL;
+
+ -- SET vPhone = vPhone COLLATE 'utf8_unicode_ci';
+
+ DROP TEMPORARY TABLE IF EXISTS tClient;
+ CREATE TEMPORARY TABLE tClient
+ ENGINE = MEMORY
+ SELECT id clientFk
+ FROM `client`
+ WHERE phone = vPhone
+ OR mobile = vPhone
+ UNION
+ SELECT clientFk
+ FROM address
+ WHERE phone = vPhone
+ OR mobile = vPhone
+ UNION
+ SELECT clientFk
+ FROM vn.clientContact
+ WHERE phone = vPhone;
+
+ SELECT t.clientFk INTO vClient
+ FROM tClient t
+ JOIN `client` c ON c.id = t.clientFk
+ WHERE c.isActive
+ LIMIT 1;
+
+ DROP TEMPORARY TABLE tClient;
+
+ RETURN vClient;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/client_getSalesPerson.sql b/db/routines/vn/functions/client_getSalesPerson.sql
new file mode 100644
index 000000000..c53816f7f
--- /dev/null
+++ b/db/routines/vn/functions/client_getSalesPerson.sql
@@ -0,0 +1,74 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getSalesPerson`(vClientFk INT, vDated DATE)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo
+ * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de
+ * sharingcart y tercero la de clientes.
+ *
+ * @param vClientFk El id del cliente
+ * @param vDated Fecha a comprobar
+ * @return El id del comercial para la fecha dada
+ **/
+ DECLARE vSalesPersonFk INT DEFAULT NULL;
+ DECLARE vWorkerSubstituteFk INT DEFAULT NULL;
+ DECLARE vLoop BOOLEAN;
+
+ -- Obtiene el comercial original y el de sharingclient
+
+ SELECT c.salesPersonFk, s.workerFk
+ INTO vSalesPersonFk, vWorkerSubstituteFk
+ FROM client c
+ LEFT JOIN sharingClient s
+ ON c.id = s.clientFk
+ AND vDated BETWEEN s.started AND s.ended
+ WHERE c.id = vClientFk
+ ORDER BY s.id
+ LIMIT 1;
+
+ -- Si no hay ninguno en sharingclient busca en sharingcart
+
+ IF vWorkerSubstituteFk IS NOT NULL
+ THEN
+ SET vSalesPersonFk = vWorkerSubstituteFk;
+ ELSEIF vSalesPersonFk IS NOT NULL
+ THEN
+ DROP TEMPORARY TABLE IF EXISTS tmp.stack;
+ CREATE TEMPORARY TABLE tmp.stack
+ (INDEX (substitute))
+ ENGINE = MEMORY
+ SELECT vSalesPersonFk substitute;
+
+ l: LOOP
+ SELECT workerSubstitute INTO vWorkerSubstituteFk
+ FROM sharingCart
+ WHERE util.VN_CURDATE() BETWEEN started AND ended
+ AND workerFk = vSalesPersonFk
+ ORDER BY id
+ LIMIT 1;
+
+ IF vWorkerSubstituteFk IS NULL THEN
+ LEAVE l;
+ END IF;
+
+ SELECT COUNT(*) > 0 INTO vLoop
+ FROM tmp.stack WHERE substitute = vWorkerSubstituteFk;
+
+ IF vLoop THEN
+ LEAVE l;
+ END IF;
+
+ INSERT INTO tmp.stack SET
+ substitute = vWorkerSubstituteFk;
+
+ SET vSalesPersonFk = vWorkerSubstituteFk;
+ END LOOP;
+
+ DROP TEMPORARY TABLE tmp.stack;
+ END IF;
+
+ RETURN vSalesPersonFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/client_getSalesPersonByTicket.sql b/db/routines/vn/functions/client_getSalesPersonByTicket.sql
new file mode 100644
index 000000000..640df11ce
--- /dev/null
+++ b/db/routines/vn/functions/client_getSalesPersonByTicket.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getSalesPersonByTicket`(vTicketFk INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Dado un id ticket, devuelve su comercial.
+ * Para más información ir a client_getSalesPerson()
+ *
+ * @param vClientFk El id del cliente
+ * @param vDated Fecha a comprobar
+ * @return El id del comercial para la fecha dada
+ **/
+ DECLARE vClientFk INT;
+ DECLARE vDated DATE;
+
+ SELECT clientFk, shipped
+ INTO vClientFk, vDated
+ FROM ticket WHERE id = vTicketFk;
+
+ RETURN client_getSalesPerson(vClientFk, vDated);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/client_getSalesPersonCode.sql b/db/routines/vn/functions/client_getSalesPersonCode.sql
new file mode 100644
index 000000000..69b8424d8
--- /dev/null
+++ b/db/routines/vn/functions/client_getSalesPersonCode.sql
@@ -0,0 +1,26 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getSalesPersonCode`(vClientFk INT, vDated DATE)
+ RETURNS varchar(3) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ DETERMINISTIC
+BEGIN
+/**
+ * Dado un id cliente y una fecha, devuelve su comercial.
+ * Para más información ir a client_getSalesPerson()
+ *
+ * @param vClientFk El id del cliente
+ * @param vDated Fecha a comprobar
+ * @return El código del comercial para la fecha dada
+ **/
+ DECLARE vWorkerCode CHAR(3);
+ DECLARE vSalesPersonFk INT;
+
+ SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated);
+
+ SELECT code
+ INTO vWorkerCode
+ FROM worker
+ WHERE id = vSalesPersonFk;
+
+ RETURN vWorkerCode;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/client_getSalesPersonCodeByTicket.sql b/db/routines/vn/functions/client_getSalesPersonCodeByTicket.sql
new file mode 100644
index 000000000..3ec5a8e9d
--- /dev/null
+++ b/db/routines/vn/functions/client_getSalesPersonCodeByTicket.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getSalesPersonCodeByTicket`(vTicketFk INT)
+ RETURNS varchar(3) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ DETERMINISTIC
+BEGIN
+/**
+ * Dado un id ticket, devuelve su comercial.
+ * Para más información ir a client_getSalesPerson()
+ *
+ * @param vClientFk El id del cliente
+ * @param vDated Fecha a comprobar
+ * @return El código del comercial para la fecha dada
+ **/
+ DECLARE vClientFk INT;
+ DECLARE vDated DATE;
+
+ SELECT clientFk, shipped
+ INTO vClientFk, vDated
+ FROM ticket WHERE id = vTicketFk;
+
+ RETURN client_getSalesPersonCode(vClientFk, vDated);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/client_hasDifferentCountries.sql b/db/routines/vn/functions/client_hasDifferentCountries.sql
new file mode 100644
index 000000000..a90b774c7
--- /dev/null
+++ b/db/routines/vn/functions/client_hasDifferentCountries.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_hasDifferentCountries`(vClientFk INT)
+ RETURNS tinyint(1)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Return if client have address in different countries.
+ *
+ * @param vClientFk The id client
+ * @return BOOL
+ **/
+ RETURN (SELECT COUNT(DISTINCT c.id) > 1
+ FROM `address` a
+ JOIN province p ON p.id = a.provinceFk
+ JOIN country c ON c.id = p.countryFk
+ WHERE a.clientFk = vClientFk
+ AND a.isActive);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/collection_isPacked.sql b/db/routines/vn/functions/collection_isPacked.sql
new file mode 100644
index 000000000..9f148273f
--- /dev/null
+++ b/db/routines/vn/functions/collection_isPacked.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`collection_isPacked`(vSelf INT)
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+/**
+ * Check if collection is packed.
+ *
+ * @param vSelf the collection to check
+ * @return true if the collection is packed
+ */
+ DECLARE vTicketsWithoutExpeditions INT;
+
+ SELECT (COUNT(*) > 0) INTO vTicketsWithoutExpeditions
+ FROM vn.ticketCollection tc
+ LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk
+ WHERE tc.collectionFk = vSelf
+ AND ISNULL(e.id);
+
+ RETURN NOT vTicketsWithoutExpeditions;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/currency_getCommission.sql b/db/routines/vn/functions/currency_getCommission.sql
new file mode 100644
index 000000000..b0a591c23
--- /dev/null
+++ b/db/routines/vn/functions/currency_getCommission.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`currency_getCommission`(vSelf INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Devuelve el tipo de cambio en el dia de hoy dada el tipo de moneda
+ *
+ * @param vSelf id del tipo de moneda
+ * @return devuelve la comision
+ */
+ DECLARE vCommission INT;
+
+ SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission
+ FROM referenceCurrent r
+ WHERE r.currencyFk = vSelf
+ AND r.`dated` <= util.VN_CURDATE()
+ ORDER BY r.`dated` DESC
+ LIMIT 1;
+
+ RETURN vCommission;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/currentRate.sql b/db/routines/vn/functions/currentRate.sql
new file mode 100644
index 000000000..57870fca4
--- /dev/null
+++ b/db/routines/vn/functions/currentRate.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`currentRate`(vCurrencyFk INT, vDated DATE)
+ RETURNS decimal(10,4)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ DECLARE curRate DECIMAL(10,4);
+
+ SELECT value INTO curRate
+ FROM referenceRate
+ WHERE dated <= vDated
+ AND currencyFk = vCurrencyFk
+ ORDER BY dated DESC
+ LIMIT 1;
+
+RETURN curRate;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/deviceProductionUser_accessGranted.sql b/db/routines/vn/functions/deviceProductionUser_accessGranted.sql
new file mode 100644
index 000000000..a2d39a0ab
--- /dev/null
+++ b/db/routines/vn/functions/deviceProductionUser_accessGranted.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`deviceProductionUser_accessGranted`(vUserFK INT(10) , android_id VARCHAR(50))
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+ /*
+ * Comprueba si el usuario puede entrar en la aplicacion de almacen con ese movil
+ *
+ * */
+
+ /*DECLARE vIsGranted BOOLEAN;
+ DECLARE vDeviceProductionFk INT(11) DEFAULT NULL;
+
+ SELECT dp.id INTO vDeviceProductionFk
+ FROM vn.deviceProduction dp
+ WHERE dp.android_id = android_id;
+
+ IF vDeviceProductionFk THEN
+
+ SELECT COUNT(*) INTO vIsGranted
+ FROM vn.deviceProductionUser dpu
+ WHERE dpu.userFk = vUserFK
+ AND dpu.deviceProductionFk = vDeviceProductionFk;
+
+ RETURN vIsGranted;
+ END IF;*/
+ RETURN TRUE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/duaTax_getRate.sql b/db/routines/vn/functions/duaTax_getRate.sql
new file mode 100644
index 000000000..a11015066
--- /dev/null
+++ b/db/routines/vn/functions/duaTax_getRate.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`duaTax_getRate`(vDuaFk INT, vTaxClassFk INT)
+ RETURNS decimal(5,2)
+ DETERMINISTIC
+BEGIN
+/**
+ * Devuelve el rate para un Dua teniendo en cuenta la fecha de opreción del DUA
+ *
+ * @param vDuaFk Identificador de la tabla dua
+ * @param vTaxClassFk Identificador del IVA de la tabla invoiceInTaxBookingAccount
+ */
+ RETURN (
+ SELECT rate
+ FROM dua d
+ JOIN supplier s ON s.id = d.companyFk
+ JOIN invoiceInTaxBookingAccount iit ON iit.countryFk = s.countryFk
+ AND iit.taxClassFk = vTaxClassFk
+ AND iit.effectived <= IFNULL( d.operated, util.VN_CURDATE())
+ WHERE d.id = vDuaFk
+ ORDER BY effectived DESC
+ LIMIT 1);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ekt_getEntry.sql b/db/routines/vn/functions/ekt_getEntry.sql
new file mode 100644
index 000000000..c629098a6
--- /dev/null
+++ b/db/routines/vn/functions/ekt_getEntry.sql
@@ -0,0 +1,71 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ekt_getEntry`(vEktFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Devuelve el numero de entrada para el ekt
+ *
+ * @param vEktFk Identificador de edi.ekt
+ */
+ DECLARE vTravelFk INT;
+ DECLARE vEntryFk INT DEFAULT 0;
+ DECLARE vEntryAssignFk INT;
+
+ SELECT ea.id
+ INTO vEntryAssignFk
+ FROM edi.ekt e
+ JOIN vn.ektEntryAssign ea ON
+ IFNULL(ea.sub, e.sub) <=> e.sub AND
+ IFNULL(ea.kop, e.kop) <=> e.kop AND
+ IFNULL(ea.pro, e.pro) <=> e.pro AND
+ IFNULL(ea.auction, e.auction) <=> e.auction
+ WHERE e.id = vEktFk
+ ORDER BY
+ IF(ea.sub,1,0) * 1000 +
+ IF(ea.kop,1,0) * 100 +
+ IF(ea.pro,1,0) * 10 +
+ IF(ea.auction,1,0) DESC
+ LIMIT 1;
+
+ SET vTravelFk = vn.ekt_getTravel(vEntryAssignFk, vEktFk);
+
+ IF vTravelFk THEN
+
+ SELECT MAX(e.id)
+ INTO vEntryFk
+ FROM vn.entry e
+ JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk
+ WHERE e.travelFk = vTravelFk
+ AND e.sub <=> ea.sub
+ AND e.kop <=> ea.kop
+ AND e.pro <=> ea.pro
+ AND e.auction <=> ea.auction
+ AND e.companyFk <=> ea.companyFk;
+
+ IF vEntryFk IS NULL THEN
+ INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, reference, pro, auction)
+ SELECT vTravelFk, ea.supplierFk, ea.companyFk, cu.id, ea.kop, ea.sub, ea.ref, ea.pro, ea.auction
+ FROM vn.ektEntryAssign ea
+ JOIN vn.currency cu ON cu.code = 'EUR'
+ WHERE ea.id = vEntryAssignFk;
+
+ SET vEntryFk = LAST_INSERT_ID();
+ END IF;
+
+ UPDATE vn.ektEntryAssign
+ SET entryFk = vEntryFk
+ WHERE id = vEntryAssignFk;
+
+ ELSE
+
+ SELECT ec.defaultEntry INTO vEntryFk
+ FROM vn.entryConfig ec;
+
+ INSERT IGNORE INTO vn.entry(id) VALUES(vEntryFk);
+ END IF;
+
+ RETURN vEntryFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ekt_getTravel.sql b/db/routines/vn/functions/ekt_getTravel.sql
new file mode 100644
index 000000000..4cf7f5631
--- /dev/null
+++ b/db/routines/vn/functions/ekt_getTravel.sql
@@ -0,0 +1,45 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ekt_getTravel`(vEntryAssignFk INT, vEktFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Devuelve un vn.travel.id
+ *
+ * @param vEntryAssignFk Identificador de vn.entryAssign
+ */
+ DECLARE vTravelFk INT;
+
+ IF vEntryAssignFk IS NOT NULL THEN
+ SELECT MAX(tr.id) INTO vTravelFk
+ FROM vn.travel tr
+ JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk
+ JOIN edi.ekt e ON e.id = vEktFk
+ WHERE ea.warehouseOutFk = tr.warehouseOutFk
+ AND ea.warehouseInFk = tr.warehouseInFk
+ AND ea.agencyModeFk = tr.agencyModeFk
+ AND tr.landed = e.fec;
+
+ IF vTravelFk IS NULL THEN
+
+ INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
+ SELECT e.fec, e.fec, ea.warehouseInFk, ea.warehouseOutFk, ea.agencyModeFk
+ FROM edi.ekt e
+ JOIN vn.ektEntryAssign ea ON ea.kop = e.kop
+ WHERE e.id = vEktFk
+ ORDER BY
+ IF(ea.sub,1,0) * 1000 +
+ IF(ea.kop,1,0) * 100 +
+ IF(ea.pro,1,0) * 10 +
+ IF(ea.auction,1,0) DESC
+ LIMIT 1;
+
+ SET vTravelFk = LAST_INSERT_ID();
+
+ END IF;
+ END IF;
+
+ RETURN vTravelFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/entry_getCommission.sql b/db/routines/vn/functions/entry_getCommission.sql
new file mode 100644
index 000000000..62946407a
--- /dev/null
+++ b/db/routines/vn/functions/entry_getCommission.sql
@@ -0,0 +1,58 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`entry_getCommission`(vTravelFk INT,
+ vCurrencyFk INT,
+ vSupplierFk INT
+)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vCommission INT;
+ DECLARE vCurrentCommission INT;
+ DECLARE vIsCurrencyUsd INT;
+ DECLARE vLastEntryFk INT;
+
+ SELECT count(*) INTO vIsCurrencyUsd
+ FROM currency c
+ WHERE c.code = 'USD' AND id = vCurrencyFk;
+
+ IF NOT vIsCurrencyUsd THEN
+
+ SELECT e.id INTO vLastEntryFk
+ FROM vn.entry e
+ JOIN vn.travel tr ON tr.id = e.travelFk
+ WHERE e.supplierFk = vSupplierFk
+ ORDER BY tr.landed DESC
+ LIMIT 1;
+
+ IF vLastEntryFk THEN
+
+ SELECT commission INTO vCurrentCommission
+ FROM vn.entry
+ WHERE id = vLastEntryFk;
+
+ ELSE
+
+ SELECT commission INTO vCurrentCommission
+ FROM supplier s
+ WHERE s.id = vSupplierFk;
+
+ END IF;
+
+ RETURN vCurrentCommission;
+
+ ELSE
+
+ SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission
+ FROM travel t
+ LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped
+ WHERE t.id = vTravelFk
+ ORDER BY r.`dated` DESC
+ LIMIT 1;
+
+ RETURN IFNULL(vCommission, 0);
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/entry_getCurrency.sql b/db/routines/vn/functions/entry_getCurrency.sql
new file mode 100644
index 000000000..4cfce19db
--- /dev/null
+++ b/db/routines/vn/functions/entry_getCurrency.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`entry_getCurrency`(vCurrency INT,
+ vSupplierFk INT
+)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vIsDollarAccount BOOL;
+
+ SELECT account LIKE '___4______' INTO vIsDollarAccount
+ FROM vn.supplier WHERE id = vSupplierFk;
+
+ IF vIsDollarAccount THEN
+ RETURN 2;
+ ELSE
+ RETURN vCurrency;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/entry_getForLogiflora.sql b/db/routines/vn/functions/entry_getForLogiflora.sql
new file mode 100644
index 000000000..71f0b585c
--- /dev/null
+++ b/db/routines/vn/functions/entry_getForLogiflora.sql
@@ -0,0 +1,64 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ /**
+ * Devuelve una entrada para Logiflora. Si no existe la crea.
+ *
+ * @param vLanded Fecha de llegada al almacén
+ * @param vWarehouseFk Identificador de vn.warehouse
+ */
+
+ DECLARE vTravelFk INT;
+ DECLARE vEntryFk INT;
+ DECLARE previousEntryFk INT;
+
+ SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk);
+
+ IF vLanded THEN
+
+ SELECT IFNULL(MAX(id),0) INTO vEntryFk
+ FROM vn.entry
+ WHERE travelFk = vTravelFk
+ AND isRaid;
+
+ IF NOT vEntryFk THEN
+
+ INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid)
+ SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE
+ FROM vn.supplier s
+ JOIN vn.company c ON c.code = 'VNL'
+ JOIN vn.currency cu ON cu.code = 'EUR'
+ WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN';
+
+ SELECT MAX(id) INTO vEntryFk
+ FROM vn.entry
+ WHERE travelFk = vTravelFk;
+
+ END IF;
+
+ END IF;
+
+ SELECT entryFk INTO previousEntryFk
+ FROM edi.warehouseFloramondo wf
+ WHERE wf.warehouseFk = vWarehouseFk;
+
+ IF IFNULL(previousEntryFk,0) != vEntryFk THEN
+
+ UPDATE buy b
+ SET b.printedStickers = 0
+ WHERE entryFk = previousEntryFk;
+
+ DELETE FROM buy WHERE entryFk = previousEntryFk;
+
+ DELETE FROM entry WHERE id = previousEntryFk;
+
+ END IF;
+
+ RETURN vEntryFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/entry_isIntrastat.sql b/db/routines/vn/functions/entry_isIntrastat.sql
new file mode 100644
index 000000000..8d46b4a02
--- /dev/null
+++ b/db/routines/vn/functions/entry_isIntrastat.sql
@@ -0,0 +1,39 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`entry_isIntrastat`(vSelf INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+* Devuelve si el proveedor de la entrada es de la CEE
+*
+* @param vSelf Id de la entrada
+* @return true si es de la CEE
+*/
+ DECLARE vIsUeeSupplier BOOLEAN;
+ DECLARE vIsUeeCompany BOOLEAN;
+ DECLARE vSupplierCountry INT;
+ DECLARE vCompanyCountry INT;
+
+ SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id
+ INTO vIsUeeSupplier, vSupplierCountry
+ FROM entry e
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN country c ON c.id = s.countryFk
+ LEFT JOIN province p ON p.id = s.provinceFk
+ LEFT JOIN autonomy a ON a.id = p.autonomyFk
+ WHERE e.id = vSelf;
+
+ SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id
+ INTO vIsUeeCompany, vCompanyCountry
+ FROM entry e
+ JOIN supplier s ON s.id = e.companyFk
+ JOIN country c ON c.id = s.countryFk
+ LEFT JOIN province p ON p.id = s.provinceFk
+ LEFT JOIN autonomy a ON a.id = p.autonomyFk
+ WHERE e.id = vSelf;
+
+
+ RETURN vIsUeeCompany AND vIsUeeSupplier AND (vSupplierCountry <> vCompanyCountry);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/entry_isInventoryOrPrevious.sql b/db/routines/vn/functions/entry_isInventoryOrPrevious.sql
new file mode 100644
index 000000000..4acbf060d
--- /dev/null
+++ b/db/routines/vn/functions/entry_isInventoryOrPrevious.sql
@@ -0,0 +1,18 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`entry_isInventoryOrPrevious`(vSelf INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+ DECLARE vIsInventoryOrPrevious BOOL;
+
+ SELECT ec.inventorySupplierFk = e.supplierFk OR t.landed < c.inventoried
+ INTO vIsInventoryOrPrevious
+ FROM entry e
+ JOIN travel t ON e.travelFk = t.id
+ JOIN entryConfig ec
+ JOIN config c
+ WHERE e.id = vSelf;
+
+ RETURN vIsInventoryOrPrevious;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/expedition_checkRoute.sql b/db/routines/vn/functions/expedition_checkRoute.sql
new file mode 100644
index 000000000..9b2929797
--- /dev/null
+++ b/db/routines/vn/functions/expedition_checkRoute.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`expedition_checkRoute`(vPalletFk INT,vExpeditionFk INT)
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+/**
+* Comprueba si las expediciones del pallet son todas
+* de la misma ruta.
+*
+* @param vExpeditionFk numero de expedition a comprobar
+* @param vPalletFk numero de pallet
+* @return vHasDistinctRoutes
+*/
+ DECLARE vRouteFk INT;
+ DECLARE vHasDistinctRoutes BOOL;
+
+ SELECT t.routeFk INTO vRouteFk
+ FROM vn.expedition e
+ JOIN vn.ticket t ON e.ticketFk = t.id
+ WHERE e.id = vExpeditionFk;
+
+ SELECT COUNT(*) > 0 INTO vHasDistinctRoutes
+ FROM vn.expeditionScan es
+ JOIN vn.expedition e ON es.expeditionFk = e.id
+ JOIN vn.ticket t ON e.ticketFk = t.id
+ WHERE es.palletFk = vPalletFk
+ AND t.routeFk <> vRouteFk;
+
+ RETURN vHasDistinctRoutes;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/firstDayOfWeek.sql b/db/routines/vn/functions/firstDayOfWeek.sql
new file mode 100644
index 000000000..25ab4480c
--- /dev/null
+++ b/db/routines/vn/functions/firstDayOfWeek.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`firstDayOfWeek`(vYear INT, vWeek INT)
+ RETURNS date
+ DETERMINISTIC
+BEGIN
+/**
+ * Returns the date of the first day of the week
+ *
+ * @param vYear The year
+ * @param vWeek The week number
+ * @return Date of the first day of the week
+ */
+ DECLARE vDate DATE;
+
+ SELECT dated INTO vDate
+ FROM `time`
+ WHERE `year` = vYear
+ AND `week` = vWeek
+ ORDER BY dated
+ LIMIT 1;
+
+ RETURN vDate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getAlert3State.sql b/db/routines/vn/functions/getAlert3State.sql
new file mode 100644
index 000000000..f3a7aae53
--- /dev/null
+++ b/db/routines/vn/functions/getAlert3State.sql
@@ -0,0 +1,39 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getAlert3State`(vTicket INT)
+ RETURNS varchar(45) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vDeliveryType INTEGER DEFAULT 0;
+ DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
+ DECLARE vCode VARCHAR(45);
+
+ SELECT am.deliveryMethodFk
+ INTO vDeliveryType
+ FROM ticket t
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ WHERE t.id = vTicket;
+
+ CASE vDeliveryType
+ WHEN 1 THEN -- AGENCIAS
+ SET vCode = 'DELIVERED';
+
+ WHEN 2 THEN -- REPARTO
+ SET vCode = 'ON_DELIVERY';
+
+ ELSE -- MERCADO, OTROS
+ SELECT MIN(t.warehouseFk <> w.id) INTO isWaitingForPickUp
+ FROM ticket t
+ LEFT JOIN warehouse w
+ ON w.pickUpagencyModeFk = t.agencyModeFk
+ WHERE t.id = vTicket;
+
+ IF isWaitingForPickUp THEN
+ SET vCode = 'WAITING_FOR_PICKUP';
+ ELSE
+ SET vCode = 'DELIVERED';
+ END IF;
+ END CASE;
+ RETURN vCode;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getAlert3StateTest.sql b/db/routines/vn/functions/getAlert3StateTest.sql
new file mode 100644
index 000000000..6a14d80d4
--- /dev/null
+++ b/db/routines/vn/functions/getAlert3StateTest.sql
@@ -0,0 +1,40 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getAlert3StateTest`(vTicket INT)
+ RETURNS varchar(45) CHARSET latin1 COLLATE latin1_swedish_ci
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vDeliveryType INTEGER DEFAULT 0;
+ DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
+ DECLARE vCode VARCHAR(45);
+
+ SELECT
+ a.Vista
+ INTO vDeliveryType
+ FROM vn2008.Tickets t
+ JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
+ WHERE Id_Ticket = vTicket;
+
+ CASE vDeliveryType
+ WHEN 1 THEN -- AGENCIAS
+ SET vCode = 'DELIVERED';
+
+ WHEN 2 THEN -- REPARTO
+ SET vCode = 'ON_DELIVERY';
+
+ ELSE -- MERCADO, OTROS
+ SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp
+ FROM vn2008.Tickets t
+ LEFT JOIN vn2008.warehouse_pickup w
+ ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id
+ WHERE t.Id_Ticket = vTicket;
+
+ IF isWaitingForPickUp THEN
+ SET vCode = 'WAITING_FOR_PICKUP';
+ ELSE
+ SET vCode = 'DELIVERED';
+ END IF;
+ END CASE;
+ RETURN vCode;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getDueDate.sql b/db/routines/vn/functions/getDueDate.sql
new file mode 100644
index 000000000..694117a52
--- /dev/null
+++ b/db/routines/vn/functions/getDueDate.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getDueDate`(vDated DATE, vDayToPay INT)
+ RETURNS date
+ NOT DETERMINISTIC
+ NO SQL
+BEGIN
+ DECLARE vDued DATE;
+
+ IF vDayToPay = 0 THEN
+ RETURN vDated;
+ END IF;
+
+ SET vDued = TIMESTAMPADD(DAY,vDayToPay MOD 30, LAST_DAY(TIMESTAMPADD(MONTH, vDayToPay DIV 30, vDated)));
+
+ RETURN vDued;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getInventoryDate.sql b/db/routines/vn/functions/getInventoryDate.sql
new file mode 100644
index 000000000..b67f1c384
--- /dev/null
+++ b/db/routines/vn/functions/getInventoryDate.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getInventoryDate`()
+ RETURNS date
+ DETERMINISTIC
+BEGIN
+ RETURN (SELECT inventoried FROM config LIMIT 1);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getNewItemId.sql b/db/routines/vn/functions/getNewItemId.sql
new file mode 100644
index 000000000..2cb9b275b
--- /dev/null
+++ b/db/routines/vn/functions/getNewItemId.sql
@@ -0,0 +1,18 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getNewItemId`()
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE newItemId INT;
+
+ SELECT i1.id + 1 INTO newItemId
+ FROM item i1
+ LEFT JOIN item i2 ON i1.id + 1 = i2.id
+ WHERE i2.id IS NULL
+ ORDER BY i1.id
+ LIMIT 1;
+
+ RETURN newItemId;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getNextDueDate.sql b/db/routines/vn/functions/getNextDueDate.sql
new file mode 100644
index 000000000..8e8691ec5
--- /dev/null
+++ b/db/routines/vn/functions/getNextDueDate.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getNextDueDate`(vDated DATE, vGapDays INT, vPayDay INT)
+ RETURNS date
+ NOT DETERMINISTIC
+ NO SQL
+BEGIN
+
+ DECLARE vReturn DATE;
+ DECLARE vDuaDate DATE;
+ DECLARE vDuaDateDay INT;
+
+ SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate;
+
+ IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN
+ SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate);
+ ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN
+ SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate);
+ END IF;
+
+ IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN
+ IF util.isLeapYear(YEAR(vDuaDate)) THEN
+ SET vPayDay = 29;
+ ELSE
+ SET vPayDay = 28;
+ END IF;
+ END IF;
+
+ SELECT DAY(vDuaDate) INTO vDuaDateDay;
+ RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay)));
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getShipmentHour.sql b/db/routines/vn/functions/getShipmentHour.sql
new file mode 100644
index 000000000..9eca04ac4
--- /dev/null
+++ b/db/routines/vn/functions/getShipmentHour.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getShipmentHour`(vTicket INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vShipmentHour INT;
+
+ SELECT HOUR(shipped) INTO vShipmentHour
+ FROM ticket
+ WHERE id = vTicket;
+
+ IF vShipmentHour = 0
+ THEN
+ DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
+ CREATE TEMPORARY TABLE tmp.production_buffer
+ ENGINE = MEMORY
+ SELECT am.agencyFk as agency_id
+ , t.warehouseFk as warehouse_id
+ , a.provinceFk as province_id
+ , 0 as Hora
+ , 0 as Departure
+ FROM ticket t
+ JOIN agencyMode am on am.id = t.agencyModeFk
+ JOIN address a on a.id = t.addressFk
+ WHERE t.id = vTicket;
+
+ SELECT Hora INTO vShipmentHour
+ FROM tmp.production_buffer;
+ END IF;
+
+ RETURN vShipmentHour;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getSpecialPrice.sql b/db/routines/vn/functions/getSpecialPrice.sql
new file mode 100644
index 000000000..2cc5f2b99
--- /dev/null
+++ b/db/routines/vn/functions/getSpecialPrice.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getSpecialPrice`(vItemFk int(11),vClientFk int(11))
+ RETURNS decimal(10,2)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE price DECIMAL(10,2);
+
+ SELECT rate3 INTO price
+ FROM vn.priceFixed
+ WHERE itemFk = vItemFk
+ AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1;
+
+ SELECT `value` INTO price
+ FROM vn.specialPrice
+ WHERE itemFk = vItemFk
+ AND (clientFk = vClientFk OR clientFk IS NULL)
+ AND started <= util.VN_CURDATE()
+ AND (ended >= util.VN_CURDATE() OR ended IS NULL)
+ ORDER BY id DESC LIMIT 1;
+RETURN price;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getTicketTrolleyLabelCount.sql b/db/routines/vn/functions/getTicketTrolleyLabelCount.sql
new file mode 100644
index 000000000..b978db73a
--- /dev/null
+++ b/db/routines/vn/functions/getTicketTrolleyLabelCount.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getTicketTrolleyLabelCount`(vTicket INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vLabelCount INT DEFAULT 0;
+
+ SELECT labelCount INTO vLabelCount
+ FROM ticketTrolley
+ WHERE ticket = vTicket;
+
+ SET vLabelCount = vLabelCount +1 ;
+
+ REPLACE ticketTrolley(ticket,labelCount)
+ SELECT vTicket, vLabelCount;
+
+ RETURN vlabelCount;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getUser.sql b/db/routines/vn/functions/getUser.sql
new file mode 100644
index 000000000..eb85b8346
--- /dev/null
+++ b/db/routines/vn/functions/getUser.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getUser`()
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * @deprecated Use account.userGetId()
+ */
+ RETURN account.myUser_getId();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/getUserId.sql b/db/routines/vn/functions/getUserId.sql
new file mode 100644
index 000000000..9afcb8912
--- /dev/null
+++ b/db/routines/vn/functions/getUserId.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getUserId`(userName varchar(30))
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vUser INT;
+
+ SELECT id INTO vUser
+ FROM account.user
+ WHERE `name` = userName;
+
+ RETURN vUser;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/hasAnyNegativeBase.sql b/db/routines/vn/functions/hasAnyNegativeBase.sql
new file mode 100644
index 000000000..97d1e7328
--- /dev/null
+++ b/db/routines/vn/functions/hasAnyNegativeBase.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`hasAnyNegativeBase`()
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+
+/**
+* Calcula si existe alguna base imponible negativa
+* Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases()
+*
+* returns BOOLEAN
+*/
+
+ DECLARE hasAnyNegativeBase BOOLEAN;
+
+ CALL getTaxBases();
+
+ SELECT negative INTO hasAnyNegativeBase
+ FROM tmp.taxBases
+ LIMIT 1;
+
+ DROP TEMPORARY TABLE
+ tmp.ticketTax,
+ tmp.ticket,
+ tmp.taxBases;
+
+ RETURN hasAnyNegativeBase;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/hasAnyPositiveBase.sql b/db/routines/vn/functions/hasAnyPositiveBase.sql
new file mode 100644
index 000000000..7222c3b2a
--- /dev/null
+++ b/db/routines/vn/functions/hasAnyPositiveBase.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`hasAnyPositiveBase`()
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+
+/**
+* Calcula si existe alguna base imponible positiva
+* Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases()
+*
+* returns BOOLEAN
+*/
+
+ DECLARE hasAnyPositiveBase BOOLEAN;
+
+ CALL getTaxBases();
+
+ SELECT positive INTO hasAnyPositiveBase
+ FROM tmp.taxBases
+ LIMIT 1;
+
+ DROP TEMPORARY TABLE
+ tmp.ticketTax,
+ tmp.ticket,
+ tmp.taxBases;
+
+ RETURN hasAnyPositiveBase;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/hasItemsInSector.sql b/db/routines/vn/functions/hasItemsInSector.sql
new file mode 100644
index 000000000..4aa4edb9c
--- /dev/null
+++ b/db/routines/vn/functions/hasItemsInSector.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`hasItemsInSector`(vTicketFk INT, vSectorFk INT)
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vItemCount INT;
+
+ SELECT count(*) INTO vItemCount
+ FROM vn.sale s
+ JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.parking p ON p.id = sh.parkingFk
+ WHERE s.ticketFk = vTicketFk
+ AND p.sectorFk = vSectorFk;
+
+ RETURN vItemCount;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/hasSomeNegativeBase.sql b/db/routines/vn/functions/hasSomeNegativeBase.sql
new file mode 100644
index 000000000..ea7efe777
--- /dev/null
+++ b/db/routines/vn/functions/hasSomeNegativeBase.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`hasSomeNegativeBase`(vTicket INT)
+ RETURNS tinyint(1)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vCountry INT;
+ DECLARE hasSomeNegativeBase BOOLEAN;
+
+ SELECT s.countryFk
+ INTO vCountry
+ FROM supplier s
+ JOIN ticket t ON t.companyFk = s.id
+ WHERE t.id = vTicket;
+
+ SELECT COUNT(*) INTO hasSomeNegativeBase
+ FROM (
+ SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemTaxCountry itc
+ ON itc.itemFk = i.id AND itc.countryFk = vCountry
+ WHERE s.ticketFk = vTicket
+ GROUP BY itc.taxClassFk
+ HAVING taxableBase < 0
+ ) t1 ;
+
+ RETURN hasSomeNegativeBase;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/intrastat_estimateNet.sql b/db/routines/vn/functions/intrastat_estimateNet.sql
new file mode 100644
index 000000000..350cb788a
--- /dev/null
+++ b/db/routines/vn/functions/intrastat_estimateNet.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`intrastat_estimateNet`(
+ vSelf INT,
+ vStems INT
+)
+ RETURNS double
+ DETERMINISTIC
+BEGIN
+/**
+* Calcula un valor neto estimado en función de
+* datos históricos de facturas intrastat.
+*
+* @param vSelf Id de intrastat
+* @param vStems Número de unidades
+* @return vNet
+*/
+ DECLARE vNet DOUBLE;
+
+ SELECT ROUND(vStems / (SUM(average) / COUNT(average)), 2) INTO vNet
+ FROM (
+ SELECT *, stems / net average
+ FROM invoiceInIntrastat
+ WHERE intrastatFk = vSelf
+ AND net
+ AND stems > 0
+ ORDER BY dated DESC
+ LIMIT 20
+ ) sub;
+
+ RETURN vNet/2;
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/functions/invoiceOutAmount.sql b/db/routines/vn/functions/invoiceOutAmount.sql
new file mode 100644
index 000000000..6c66a46f3
--- /dev/null
+++ b/db/routines/vn/functions/invoiceOutAmount.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceOutAmount`(vInvoiceRef VARCHAR(15))
+ RETURNS decimal(10,2)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE totalAmount DECIMAL(10,2);
+
+ SELECT SUM(vat) INTO totalAmount
+ FROM (
+ SELECT iot.vat
+ FROM invoiceOutTax iot
+ JOIN invoiceOut io ON io.id = iot.invoiceOutFk
+ WHERE io.ref = vInvoiceRef
+ UNION ALL
+ SELECT ioe.amount
+ FROM invoiceOutExpense ioe
+ JOIN invoiceOut io ON io.id = ioe.invoiceOutFk
+ WHERE io.ref = vInvoiceRef
+ ) t1;
+
+ RETURN totalAmount;
+END$$
+DELIMITER ;
diff --git a/db/.archive/231001/01-invoiceOut_getMaxIssued.sql b/db/routines/vn/functions/invoiceOut_getMaxIssued.sql
similarity index 83%
rename from db/.archive/231001/01-invoiceOut_getMaxIssued.sql
rename to db/routines/vn/functions/invoiceOut_getMaxIssued.sql
index e120b949d..dc1a59eaa 100644
--- a/db/.archive/231001/01-invoiceOut_getMaxIssued.sql
+++ b/db/routines/vn/functions/invoiceOut_getMaxIssued.sql
@@ -1,13 +1,11 @@
-DROP FUNCTION IF EXISTS `vn`.`invoiceOut_getMaxIssued`;
-
DELIMITER $$
-$$
-CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceOut_getMaxIssued`(
- vSerial VARCHAR(2),
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceOut_getMaxIssued`(vSerial VARCHAR(2),
vCompanyFk INT,
vYear INT
-) RETURNS DATE
- READS SQL DATA
+)
+ RETURNS date
+ NOT DETERMINISTIC
+ READS SQL DATA
BEGIN
/**
* Retorna la fecha a partir de la cual es válido emitir una factura
@@ -31,4 +29,4 @@ BEGIN
RETURN vInvoiceOutIssued;
END$$
-DELIMITER ;
\ No newline at end of file
+DELIMITER ;
diff --git a/db/routines/vn/functions/invoiceOut_getPath.sql b/db/routines/vn/functions/invoiceOut_getPath.sql
new file mode 100644
index 000000000..1e174a4cf
--- /dev/null
+++ b/db/routines/vn/functions/invoiceOut_getPath.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceOut_getPath`(vSelf INT)
+ RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ DETERMINISTIC
+BEGIN
+ DECLARE vIssued DATE;
+ DECLARE vSerial VARCHAR(15);
+
+ SELECT issued, ref
+ INTO vIssued, vSerial
+ FROM invoiceOut WHERE id = vSelf;
+
+ RETURN CONCAT_WS('/'
+ ,'invoice'
+ ,YEAR(vIssued)
+ ,MONTH(vIssued)
+ ,DAY(vIssued)
+ ,CONCAT(YEAR(vIssued), vSerial, '.pdf')
+ );
+END$$
+DELIMITER ;
diff --git a/db/.archive/231001/00-invoiceOut_getWeight.sql b/db/routines/vn/functions/invoiceOut_getWeight.sql
similarity index 75%
rename from db/.archive/231001/00-invoiceOut_getWeight.sql
rename to db/routines/vn/functions/invoiceOut_getWeight.sql
index 3f34b6fb7..1302c0341 100644
--- a/db/.archive/231001/00-invoiceOut_getWeight.sql
+++ b/db/routines/vn/functions/invoiceOut_getWeight.sql
@@ -1,11 +1,9 @@
-DROP FUNCTION IF EXISTS `vn`.`invoiceOut_getWeight`;
-
DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceOut_getWeight`(
- vInvoiceRef VARCHAR(15)
-)RETURNS decimal(10,2)
- READS SQL DATA
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceOut_getWeight`(vInvoiceRef VARCHAR(15)
+)
+ RETURNS decimal(10,2)
+ NOT DETERMINISTIC
+ READS SQL DATA
BEGIN
/**
* Calcula el peso de una factura emitida
diff --git a/db/routines/vn/functions/invoiceSerial.sql b/db/routines/vn/functions/invoiceSerial.sql
new file mode 100644
index 000000000..66448ac9c
--- /dev/null
+++ b/db/routines/vn/functions/invoiceSerial.sql
@@ -0,0 +1,26 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceSerial`(vClientFk INT, vCompanyFk INT, vType CHAR(1))
+ RETURNS char(1) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ DETERMINISTIC
+BEGIN
+ /**
+ * Obtiene la serie de de una factura
+ * dependiendo del area del cliente.
+ *
+ * @param vClientFk Id del cliente
+ * @param vCompanyFk Id de la empresa
+ * @param vType Tipo de factura ["R", "M", "G"]
+ * @return Serie de la factura
+ */
+ DECLARE vTaxArea VARCHAR(25);
+ DECLARE vSerie CHAR(1);
+
+ IF (SELECT hasInvoiceSimplified FROM client WHERE id = vClientFk) THEN
+ RETURN 'S';
+ END IF;
+
+ SELECT clientTaxArea(vClientFk, vCompanyFk) INTO vTaxArea;
+ SELECT invoiceSerialArea(vType,vTaxArea) INTO vSerie;
+ RETURN vSerie;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/invoiceSerialArea.sql b/db/routines/vn/functions/invoiceSerialArea.sql
new file mode 100644
index 000000000..02edd83f2
--- /dev/null
+++ b/db/routines/vn/functions/invoiceSerialArea.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceSerialArea`(vType CHAR(1), vTaxArea VARCHAR(25))
+ RETURNS char(1) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
+ DETERMINISTIC
+BEGIN
+ DECLARE vSerie CHAR(1);
+
+ IF vType = 'R' THEN
+ SELECT
+ CASE vTaxArea
+ WHEN 'CEE' THEN 'H'
+ WHEN 'WORLD' THEN 'E'
+ ELSE 'T'
+ END INTO vSerie;
+ -- Factura multiple
+ ELSEIF vType = 'M' THEN
+ SELECT
+ CASE vTaxArea
+ WHEN 'CEE' THEN 'H'
+ WHEN 'WORLD' THEN 'E'
+ ELSE 'M'
+ END INTO vSerie;
+ -- Factura global
+ ELSEIF vType = 'G' THEN
+ SELECT
+ CASE vTaxArea
+ WHEN 'CEE' THEN 'V'
+ WHEN 'WORLD' THEN 'X'
+ ELSE 'A'
+ END INTO vSerie;
+ END IF;
+ RETURN vSerie;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/isLogifloraDay.sql b/db/routines/vn/functions/isLogifloraDay.sql
new file mode 100644
index 000000000..8e9c9b264
--- /dev/null
+++ b/db/routines/vn/functions/isLogifloraDay.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`isLogifloraDay`(vShipped DATE, vWarehouse INT)
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vIsLogifloraDay BOOLEAN;
+
+ SELECT COUNT(*) INTO vIsLogifloraDay
+ FROM edi.warehouseFloramondo wf
+ JOIN vn.floramondoConfig fc
+ WHERE wf.warehouseFk = vWarehouse
+ AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded))
+ AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded));
+
+ RETURN vIsLogifloraDay;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/itemPacking.sql b/db/routines/vn/functions/itemPacking.sql
new file mode 100644
index 000000000..6856c12cd
--- /dev/null
+++ b/db/routines/vn/functions/itemPacking.sql
@@ -0,0 +1,41 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`itemPacking`(vBarcode VARCHAR(22), vWarehouseFk INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vPacking INTEGER DEFAULT 0;
+ DECLARE vItemFk INTEGER;
+
+ SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
+
+ SELECT IFNULL(packing,0) INTO vPacking
+ FROM vn.buy
+ WHERE id = CAST(vBarcode AS DECIMAL(18,0));
+
+
+
+
+ IF NOT vPacking THEN
+ CALL cache.last_buy_refresh(FALSE);
+ SELECT IFNULL(packing,1) INTO vPacking
+ FROM
+ (SELECT packing , created
+ FROM vn.itemShelving
+ WHERE itemFk = vItemFk
+ UNION ALL
+ SELECT b.packing, landing
+ FROM vn.buy b
+ JOIN cache.last_buy lb ON lb.buy_id = b.id
+ WHERE lb.warehouse_id = vWarehouseFk
+ AND b.itemFk = vItemFk
+ ) packings
+ ORDER BY created desc
+ LIMIT 1;
+
+ END IF;
+
+ RETURN vPacking;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/itemShelvingPlacementSupply_ClosestGet.sql b/db/routines/vn/functions/itemShelvingPlacementSupply_ClosestGet.sql
new file mode 100644
index 000000000..6b5fc3ae3
--- /dev/null
+++ b/db/routines/vn/functions/itemShelvingPlacementSupply_ClosestGet.sql
@@ -0,0 +1,33 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`itemShelvingPlacementSupply_ClosestGet`(vParkingFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ /* Devuelve el parking más cercano.*/
+ DECLARE vColumn INT;
+ DECLARE vClosestParkingFk INT;
+ DECLARE vSectorFk INT;
+
+ SELECT p.column, sectorFk INTO vColumn, vSectorFk
+ FROM vn.parking p
+ WHERE p.id = vParkingFk;
+
+ SELECT itemShelvingFk INTO vClosestParkingFk
+ FROM
+ (
+ SELECT ABS(p.column - vColumn) as distance, itemShelvingFk
+ FROM vn.itemShelvingPlacementSupplyStock ispss
+ JOIN vn.parking p ON p.id = ispss.parkingFk
+ JOIN vn.itemPlacementSupplyList ipsl ON ipsl.sectorFk = ispss.sectorFk AND ipsl.itemFk = ispss.itemFk
+ WHERE p.sectorFk = vSectorFk
+ AND ipsl.saldo > 0
+ ) sub
+ ORDER BY distance
+ LIMIT 1;
+
+ RETURN vClosestParkingFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/itemTag_getIntValue.sql b/db/routines/vn/functions/itemTag_getIntValue.sql
new file mode 100644
index 000000000..fa5a03552
--- /dev/null
+++ b/db/routines/vn/functions/itemTag_getIntValue.sql
@@ -0,0 +1,12 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`itemTag_getIntValue`(vValue VARCHAR(255))
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+ IF vValue NOT REGEXP '^-?[0-9]+' THEN
+ RETURN NULL;
+ END IF;
+
+ RETURN CAST(vValue AS SIGNED);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/item_getFhImage.sql b/db/routines/vn/functions/item_getFhImage.sql
new file mode 100644
index 000000000..13e02e8fe
--- /dev/null
+++ b/db/routines/vn/functions/item_getFhImage.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`item_getFhImage`(itemFk INT)
+ RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
+ DETERMINISTIC
+BEGIN
+ DECLARE vImageUrl VARCHAR(255);
+ SELECT sr.PictureReference INTO vImageUrl
+ FROM vn.buy b
+ JOIN edi.ekt e ON b.ektFk = e.id
+ JOIN edi.supplyResponse sr ON sr.Item_ArticleCode =e.`ref`
+ JOIN vn.item i ON i.id = b.itemFk
+ WHERE b.itemFk = itemFk
+ ORDER BY (sr.EmbalageCode = e.package) DESC
+ LIMIT 1;
+ RETURN vImageUrl;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/item_getPackage.sql b/db/routines/vn/functions/item_getPackage.sql
new file mode 100644
index 000000000..894abe4cf
--- /dev/null
+++ b/db/routines/vn/functions/item_getPackage.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`item_getPackage`(vItemFk INT)
+ RETURNS varchar(50) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vDiameter INT;
+ DECLARE vPackageFk VARCHAR(50);
+ DECLARE vCoeficient DOUBLE DEFAULT 1.08;
+
+ SELECT MAX(LEFT(value,3)) INTO vDiameter
+ FROM vn.itemTag it
+ JOIN vn.tag t ON t.id = it.tagFk
+ WHERE it.itemFk = vItemFk
+ AND t.overwrite = 'diameter';
+
+ SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2)))
+ INTO vPackageFk
+ FROM vn.volumeConfig vc;
+
+ INSERT IGNORE INTO vn.packaging(id, width, `depth`)
+ SELECT vPackageFk,
+ FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)),
+ FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter))
+ FROM vn.volumeConfig vc;
+
+ RETURN vPackageFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/item_getVolume.sql b/db/routines/vn/functions/item_getVolume.sql
new file mode 100644
index 000000000..afcb32c93
--- /dev/null
+++ b/db/routines/vn/functions/item_getVolume.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`item_getVolume`(vSelf INT, vPackaging VARCHAR(10))
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Calculates the volume occupied by an item together
+ * with its packaging.
+ *
+ * @param vSelf The item id
+ * @param vPackaging The packaging id
+ * @return The volume in cubic centimeters
+ */
+ DECLARE vVolume INT;
+
+ SELECT SUM(IF(p.volume > 0,
+ p.volume,
+ p.width * p.depth * IF(IFNULL(p.height,0), p.height, IFNULL(i.size,60) + 10)
+ )) INTO vVolume
+ FROM packaging p
+ JOIN item i ON i.id = vSelf
+ WHERE p.id = vPackaging;
+
+ RETURN vVolume;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/itemsInSector_get.sql b/db/routines/vn/functions/itemsInSector_get.sql
new file mode 100644
index 000000000..9054087b3
--- /dev/null
+++ b/db/routines/vn/functions/itemsInSector_get.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`itemsInSector_get`(vTicketFk INT, vSectorFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ DECLARE vItemCount INT;
+
+ SELECT count(*) INTO vItemCount
+ FROM vn.sale s
+ JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.parking p ON p.id = sh.parkingFk
+ WHERE s.ticketFk = vTicketFk
+ AND p.sectorFk = vSectorFk;
+
+ RETURN vItemCount;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/lastDayOfWeek.sql b/db/routines/vn/functions/lastDayOfWeek.sql
new file mode 100644
index 000000000..464bf5afe
--- /dev/null
+++ b/db/routines/vn/functions/lastDayOfWeek.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`lastDayOfWeek`(vYear INT, vWeek INT)
+ RETURNS date
+ DETERMINISTIC
+BEGIN
+/**
+ * Returns the date of the last day of the week
+ *
+ * @param vYear The year
+ * @param vWeek The week number
+ * @return Date of the first day of the week
+ */
+ DECLARE vDate DATE;
+
+ SELECT dated INTO vDate
+ FROM `time`
+ WHERE `year` = vYear
+ AND `week` = vWeek
+ ORDER BY dated DESC
+ LIMIT 1;
+
+ RETURN vDate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/machine_checkPlate.sql b/db/routines/vn/functions/machine_checkPlate.sql
new file mode 100644
index 000000000..d08ed97c5
--- /dev/null
+++ b/db/routines/vn/functions/machine_checkPlate.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`machine_checkPlate`(vPlate VARCHAR(10))
+ RETURNS tinyint(1)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Comprueba si existe matrícula
+ *
+ * @param vPlate matrícula del vehículo
+ * @return Devuelve TRUE en caso de que exista
+ *
+ */
+
+ IF (SELECT COUNT(*)
+ FROM machine m
+ WHERE m.plate = vPlate
+ ) THEN
+ RETURN TRUE;
+ ELSE
+ RETURN FALSE;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/messageSend.sql b/db/routines/vn/functions/messageSend.sql
new file mode 100644
index 000000000..8a95118e7
--- /dev/null
+++ b/db/routines/vn/functions/messageSend.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`messageSend`(vRecipient VARCHAR(255) CHARSET utf8, vMessage TEXT CHARSET utf8)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE result INT;
+ DECLARE vSenderFk INT;
+
+ SELECT id INTO vSenderFk
+ FROM account.user WHERE `name` = account.myUser_getName();
+
+ RETURN (SELECT messageSendWithUser(vSenderFk, vRecipient, vMessage));
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/messageSendWithUser.sql b/db/routines/vn/functions/messageSendWithUser.sql
new file mode 100644
index 000000000..1d5b730a8
--- /dev/null
+++ b/db/routines/vn/functions/messageSendWithUser.sql
@@ -0,0 +1,53 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`messageSendWithUser`(vSenderFK INT, vRecipient VARCHAR(255) CHARSET utf8, vMessage TEXT CHARSET utf8)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vCount INT;
+ DECLARE vUuid VARCHAR(255);
+ DECLARE vSendDate DATETIME DEFAULT util.VN_NOW();
+ DECLARE vSender VARCHAR(255) CHARSET utf8;
+
+ SELECT `name` INTO vSender
+ FROM account.user WHERE id = vSenderFK;
+
+ SET vRecipient = LOWER(vRecipient);
+
+ DROP TEMPORARY TABLE IF EXISTS tRecipients;
+ CREATE TEMPORARY TABLE tRecipients
+ SELECT u.name finalRecipient
+ FROM account.mailAlias a
+ JOIN account.mailAliasAccount aa ON aa.mailAlias = a.id
+ JOIN account.user u ON u.id = aa.account
+ WHERE a.alias = vRecipient COLLATE utf8_unicode_ci
+ AND u.name != vSender
+ AND u.active
+ UNION
+ SELECT u.name FROM account.user u
+ WHERE u.name = vRecipient
+ AND u.active;
+
+ SELECT COUNT(*) INTO vCount FROM tRecipients;
+
+ IF vCount = 0 THEN
+ RETURN vCount;
+ END IF;
+
+ SET vUuid = UUID();
+
+ INSERT INTO message
+ SET uuid = vUuid,
+ sender = vSender,
+ recipient = vRecipient,
+ message = vMessage,
+ sendDate = vSendDate;
+
+ INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate)
+ SELECT vUuid, vSender, vRecipient, finalRecipient, vMessage, vSendDate
+ FROM tRecipients;
+
+ DROP TEMPORARY TABLE tRecipients;
+ RETURN vCount;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/orderTotalVolume.sql b/db/routines/vn/functions/orderTotalVolume.sql
new file mode 100644
index 000000000..962baa8ec
--- /dev/null
+++ b/db/routines/vn/functions/orderTotalVolume.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`orderTotalVolume`(vOrderId INT)
+ RETURNS decimal(10,3)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ -- Devuelte el volumen total de la orden sumada
+ DECLARE vWarehouseId INTEGER;
+ DECLARE vVolume DECIMAL(10,3);
+
+ SELECT IFNULL(SUM(o.amount * ic.cm3delivery)/1000000,0) INTO vVolume
+ FROM hedera.orderRow o
+ JOIN item i ON i.id = o.itemFk
+ JOIN itemCost ic on ic.itemFk = o.itemFk AND ic.warehouseFk = o.warehouseFk
+ WHERE o.orderFk = vOrderId;
+
+ RETURN vVolume;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/orderTotalVolumeBoxes.sql b/db/routines/vn/functions/orderTotalVolumeBoxes.sql
new file mode 100644
index 000000000..cbc0e94ac
--- /dev/null
+++ b/db/routines/vn/functions/orderTotalVolumeBoxes.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`orderTotalVolumeBoxes`(vOrderId INT)
+ RETURNS decimal(10,3)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Devuelve el volumen estimado del ticket sumado, en cajas
+ *
+ * @param vOrder Id del pedido
+ */
+ DECLARE vVolumeBoxM3 DOUBLE;
+ DECLARE vOrderTotalVolumeBoxes DECIMAL(10,1);
+ DECLARE vVnBoxId VARCHAR(10) DEFAULT '94';
+
+ SELECT volume / 1000000
+ INTO vVolumeBoxM3
+ FROM packaging
+ WHERE id = vVnBoxId;
+
+ SET vOrderTotalVolumeBoxes = orderTotalVolume(vOrderId) / vVolumeBoxM3;
+
+ RETURN vOrderTotalVolumeBoxes;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/packaging_calculate.sql b/db/routines/vn/functions/packaging_calculate.sql
new file mode 100644
index 000000000..c9aaf07b9
--- /dev/null
+++ b/db/routines/vn/functions/packaging_calculate.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`packaging_calculate`(isPackageReturnable TINYINT(1),
+ packagingReturnFk INT(11),
+ base DECIMAL(10,2),
+ price DECIMAL(10,2),
+ upload VARCHAR(255))
+ RETURNS decimal(10,2)
+ DETERMINISTIC
+BEGIN
+ DECLARE vAmount INT DEFAULT NULL;
+ DECLARE vValue DECIMAL(10,2);
+
+ IF isPackageReturnable THEN
+ SELECT cb.freightPackagingFull INTO vAmount
+ FROM returnBuckets cb
+ WHERE cb.id = packagingReturnFk;
+
+ SET vValue = IF (vAmount IS NULL,
+ IFNULL(base,0),
+ vAmount / IFNULL(upload, 0) + IFNULL(base, 0));
+ ELSE
+ SET vValue = IFNULL(price, 0) + IFNULL(base, 0);
+ END IF;
+
+ RETURN vValue;
+END$$
+DELIMITER ;
diff --git a/db/.archive/230201/00-priceFixed_getRate2.sql b/db/routines/vn/functions/priceFixed_getRate2.sql
similarity index 69%
rename from db/.archive/230201/00-priceFixed_getRate2.sql
rename to db/routines/vn/functions/priceFixed_getRate2.sql
index cf36efb57..d97a20e59 100644
--- a/db/.archive/230201/00-priceFixed_getRate2.sql
+++ b/db/routines/vn/functions/priceFixed_getRate2.sql
@@ -1,9 +1,7 @@
-DROP FUNCTION IF EXISTS `vn`.`priceFixed_getRate2`;
-
DELIMITER $$
-$$
-CREATE FUNCTION `vn`.`priceFixed_getRate2`(vFixedPriceFk INT, vRate3 DOUBLE)
-RETURNS DOUBLE
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`priceFixed_getRate2`(vFixedPriceFk INT, vRate3 DOUBLE)
+ RETURNS double
+ NOT DETERMINISTIC
BEGIN
DECLARE vWarehouse INT;
diff --git a/db/routines/vn/functions/routeProposal.sql b/db/routines/vn/functions/routeProposal.sql
new file mode 100644
index 000000000..81b5d9048
--- /dev/null
+++ b/db/routines/vn/functions/routeProposal.sql
@@ -0,0 +1,55 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`routeProposal`(vTicketFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ DECLARE vRouteFk INT;
+ DECLARE vAddressFk INT;
+
+ DECLARE vLanded DATE;
+ DECLARE vZoneFk INT;
+ DECLARE vSignificativeFriendship INT DEFAULT 6;
+ DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10;
+
+ SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded
+ FROM vn.ticket
+ WHERE id = vTicketFk;
+
+ -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona
+ DROP TEMPORARY TABLE IF EXISTS tmp.route;
+ CREATE TEMPORARY TABLE tmp.route
+ SELECT r.id routeFk,
+ zf.friendship zoneFriendship
+ FROM vn.route r
+ JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
+ WHERE friendship >= vSignificativeFriendship
+ AND zf.zoneFk = vZoneFk
+ AND r.created = vLanded
+ ORDER BY friendship;
+
+ -- Se eliminan aquellas que superan el volumen máximo
+ DELETE r.*
+ FROM tmp.route r
+ JOIN (SELECT routeFk, sum(volume) volume
+ FROM vn.saleVolume
+ WHERE landed = vLanded
+ GROUP BY routeFk) sub ON sub.routeFk = r.routeFk
+ WHERE sub.volume > vVolumeMax;
+
+ -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta
+ SELECT routeFk INTO vRouteFk
+ FROM
+ (SELECT r.routeFk, r.zoneFriendship, sum(af.friendship) friendshipSum
+ FROM tmp.route r
+ LEFT JOIN vn.ticket t ON t.routeFk = r.routeFk
+ LEFT JOIN cache.addressFriendship af ON af.addressFk2 = t.addressFk AND af.addressFk1 = vAddressFk
+ GROUP BY routeFk
+ ORDER BY zoneFriendship DESC, friendshipSum DESC
+ ) sub
+ LIMIT 1;
+
+ RETURN vRouteFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/routeProposal_.sql b/db/routines/vn/functions/routeProposal_.sql
new file mode 100644
index 000000000..b4559c10c
--- /dev/null
+++ b/db/routines/vn/functions/routeProposal_.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`routeProposal_`(vTicketFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ DECLARE vRouteFk INT;
+ DECLARE vAddressFk INT;
+ DECLARE vShipped DATETIME;
+
+ SELECT addressFk, date(shipped) INTO vAddressFk, vShipped
+ FROM vn.ticket
+ WHERE id = vTicketFk;
+
+ SELECT routeFk INTO vRouteFk
+ FROM
+ (SELECT t.routeFk, sum(af.friendship) friendshipSum
+ FROM vn.ticket t
+ JOIN cache.addressFriendship af ON af.addressFk2 = t.addressFk AND af.addressFk1 = vAddressFk
+ WHERE t.shipped BETWEEN vShipped and MIDNIGHT(vShipped)
+ AND t.routeFk
+ GROUP BY routeFk
+ ORDER BY friendshipSum DESC
+ ) sub
+ LIMIT 1;
+
+ RETURN vRouteFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/routeProposal_beta.sql b/db/routines/vn/functions/routeProposal_beta.sql
new file mode 100644
index 000000000..4ec17d3ed
--- /dev/null
+++ b/db/routines/vn/functions/routeProposal_beta.sql
@@ -0,0 +1,55 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`routeProposal_beta`(vTicketFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ DECLARE vRouteFk INT;
+ DECLARE vAddressFk INT;
+
+ DECLARE vLanded DATE;
+ DECLARE vZoneFk INT;
+ DECLARE vSignificativeFriendship INT DEFAULT 6;
+ DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10;
+
+ SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded
+ FROM vn.ticket
+ WHERE id = vTicketFk;
+
+ -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona
+ DROP TEMPORARY TABLE IF EXISTS tmp.route;
+ CREATE TEMPORARY TABLE tmp.route
+ SELECT r.id routeFk,
+ zf.friendship zoneFriendship
+ FROM vn.route r
+ JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
+ WHERE friendship >= vSignificativeFriendship
+ AND zf.zoneFk = vZoneFk
+ AND r.created = vLanded
+ ORDER BY friendship;
+
+ -- Se eliminan aquellas que superan el volumen máximo
+ DELETE r.*
+ FROM tmp.route r
+ JOIN (SELECT routeFk, sum(volume) volume
+ FROM vn.saleVolume
+ WHERE landed = vLanded
+ GROUP BY routeFk) sub ON sub.routeFk = r.routeFk
+ WHERE sub.volume > vVolumeMax;
+
+ -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta
+ SELECT routeFk INTO vRouteFk
+ FROM
+ (SELECT r.routeFk, r.zoneFriendship, sum(af.friendship) friendshipSum
+ FROM tmp.route r
+ LEFT JOIN vn.ticket t ON t.routeFk = r.routeFk
+ LEFT JOIN cache.addressFriendship af ON af.addressFk2 = t.addressFk AND af.addressFk1 = vAddressFk
+ GROUP BY routeFk
+ ORDER BY zoneFriendship DESC, friendshipSum DESC
+ ) sub
+ LIMIT 1;
+
+ RETURN vRouteFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/specie_IsForbidden.sql b/db/routines/vn/functions/specie_IsForbidden.sql
new file mode 100644
index 000000000..5e7275ae7
--- /dev/null
+++ b/db/routines/vn/functions/specie_IsForbidden.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`specie_IsForbidden`(vItemFk INT, vAddressFk INT)
+ RETURNS tinyint(1)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ DECLARE vIsForbbiden BOOL;
+ DECLARE vLeft INT;
+
+ SELECT zg.lft INTO vLeft
+ FROM vn.address a
+ JOIN vn.zoneGeo zg ON zg.name = a.postalCode
+ WHERE a.id = vAddressFk;
+
+ SELECT sgi.isForbidden INTO vIsForbbiden
+ FROM vn.specieGeoInvasive sgi
+ JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk
+ JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk)
+ WHERE vLeft BETWEEN zg.lft AND zg.rgt
+ AND ib.itemFk = vItemFk
+ ORDER BY zg.`depth` DESC
+ LIMIT 1;
+
+ RETURN IFNULL(vIsForbbiden, FALSE);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/testCIF.sql b/db/routines/vn/functions/testCIF.sql
new file mode 100644
index 000000000..ba2cc8345
--- /dev/null
+++ b/db/routines/vn/functions/testCIF.sql
@@ -0,0 +1,73 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`testCIF`(vCIF VARCHAR(9))
+ RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vLetraInicial VARCHAR(1);
+ DECLARE vLetraFinal VARCHAR(1);
+ DECLARE vParteNumerica VARCHAR(7);
+ DECLARE vSuma INT DEFAULT 0;
+ DECLARE vNumero INT DEFAULT 0;
+ DECLARE i INT DEFAULT 0;
+ DECLARE vResult BOOL DEFAULT FALSE;
+
+ SET vLetraInicial = SUBSTR(vCIF, 1, 1);
+ SET vLetraFinal = SUBSTR(vCIF, 9, 1);
+ SET vParteNumerica = SUBSTR(vCIF, 2, 7);
+
+ WHILE i < 7 DO
+
+ SET i = i + 1;
+
+ SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0));
+
+ IF i MOD 2 THEN
+
+ SET vNumero = vNumero * 2;
+ SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10);
+
+ END IF;
+
+ SET vSuma = vSuma + vNumero;
+
+ END WHILE;
+
+ SET vSuma = vSuma MOD 10;
+
+ IF vSuma > 0 THEN
+
+ SET vSuma = 10 - vSuma;
+
+ END IF;
+
+ -- Comprobación de dígito de control
+ IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN
+
+ SET vResult = TRUE;
+
+ END IF;
+
+ IF vSuma = 0 THEN
+
+ SET vSuma = 10;
+
+ END IF;
+
+ IF CHAR(64 + vSuma) = vLetraFinal THEN
+
+ SET vResult = TRUE;
+
+ END IF;
+
+ -- Sólo se aceptan letras como caracter inicial
+ IF ASCII(vLetraInicial) < 65 OR ASCII(vLetraInicial) > 87 THEN -- Ha de ser entre la A y la W
+
+ SET vResult = FALSE;
+
+ END IF;
+
+ RETURN vResult;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/testNIE.sql b/db/routines/vn/functions/testNIE.sql
new file mode 100644
index 000000000..6843becad
--- /dev/null
+++ b/db/routines/vn/functions/testNIE.sql
@@ -0,0 +1,55 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`testNIE`(vNIE VARCHAR(9))
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vIndice INT;
+ DECLARE vNumero VARCHAR(7);
+ DECLARE vOperador VARCHAR(9);
+ DECLARE vParteNumerica DECIMAL(8,0);
+ DECLARE vLetraInicial VARCHAR(1);
+ DECLARE vLetraFinal VARCHAR(1);
+ DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE";
+ DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE;
+
+ SET vLetraInicial = SUBSTR(vNIE, 1, 1);
+ SET vLetraFinal = SUBSTR(vNIE, 9, 1);
+ SET vNumero = SUBSTR(vNIE, 2, 7);
+
+ CASE vLetraInicial
+
+ WHEN 'X' THEN
+
+ SET vOperador = "0";
+
+ WHEN 'Y' THEN
+
+ SET vOperador = "1";
+
+ WHEN 'Z' THEN
+
+ SET vOperador = "2";
+
+ ELSE
+
+ SET vLetraInicialEsIncorrecta = TRUE;
+
+ END CASE;
+
+ SET vOperador = CONCAT(vOperador, vNumero);
+ SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0));
+ SET vIndice = Round(vParteNumerica Mod 23, 0) + 1;
+
+ IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN
+
+ RETURN TRUE;
+
+ ELSE
+
+ RETURN FALSE;
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/testNIF.sql b/db/routines/vn/functions/testNIF.sql
new file mode 100644
index 000000000..5b6654312
--- /dev/null
+++ b/db/routines/vn/functions/testNIF.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`testNIF`(vNIF VARCHAR(9))
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vIndice INT;
+ DECLARE vParteNumerica DECIMAL(8,0);
+ DECLARE vLetra VARCHAR(1);
+ DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE";
+
+ SET vLetra = SUBSTRING(vNIF, 9, 1);
+
+ SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0));
+
+ SET vIndice = Round(vParteNumerica MOD 23, 0) + 1;
+
+ If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then
+
+ RETURN TRUE;
+
+ ELSE
+
+ RETURN FALSE;
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticketCollection_getNoPacked.sql b/db/routines/vn/functions/ticketCollection_getNoPacked.sql
new file mode 100644
index 000000000..a9f04cc88
--- /dev/null
+++ b/db/routines/vn/functions/ticketCollection_getNoPacked.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticketCollection_getNoPacked`(vCollectionFk INT)
+ RETURNS varchar(100) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
+ DETERMINISTIC
+BEGIN
+
+ /*
+ * return message with tickets and collection if there is tickets of a collection without expeditions
+ *
+ * @param vCollectionFk the collection to check
+ * @return an array with collection and tickets without expeditions
+ *
+ */
+
+ DECLARE vAnswer VARCHAR(100) DEFAULT '';
+
+ IF collection_isPacked(vCollectionFk) = FALSE THEN
+ SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer
+ FROM vn.ticketCollection tc
+ LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk
+ WHERE tc.collectionFk = vCollectionFk
+ AND ISNULL(e.id);
+ END IF;
+
+ RETURN vAnswer;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticketGetTotal.sql b/db/routines/vn/functions/ticketGetTotal.sql
new file mode 100644
index 000000000..ced02e3c5
--- /dev/null
+++ b/db/routines/vn/functions/ticketGetTotal.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticketGetTotal`(vTicketId INT)
+ RETURNS decimal(10,2)
+ DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Calcula el total con IVA de un ticket.
+ *
+ * @param vTicketId Identificador del ticket
+ * @return Total del ticket
+ */
+ DECLARE vTotal DECIMAL(10,2);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
+ CREATE TEMPORARY TABLE tmp.ticket
+ ENGINE = MEMORY
+ SELECT vTicketId ticketFk;
+
+ CALL ticketGetTotal(NULL);
+
+ SELECT total INTO vTotal FROM tmp.ticketTotal;
+
+ DROP TEMPORARY TABLE
+ tmp.ticket,
+ tmp.ticketTotal;
+
+ RETURN vTotal;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticketPositionInPath.sql b/db/routines/vn/functions/ticketPositionInPath.sql
new file mode 100644
index 000000000..9bd2c110e
--- /dev/null
+++ b/db/routines/vn/functions/ticketPositionInPath.sql
@@ -0,0 +1,79 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticketPositionInPath`(vTicketId INT)
+ RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vRestTicketsMaxOrder INT;
+ DECLARE vRestTicketsMinOrder INT;
+ DECLARE vRestTicketsPacking INT;
+ DECLARE vMyProductionOrder INT;
+ DECLARE vPosition VARCHAR(10) DEFAULT 'MID';
+ DECLARE vMyPath INT;
+ DECLARE vMyWarehouse INT;
+ DECLARE PACKING_ORDER INT;
+ DECLARE vExpeditionsCount INT;
+ DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE;
+
+SELECT `order`
+ INTO PACKING_ORDER
+ FROM state
+ WHERE code = 'PACKING';
+
+SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0)
+ INTO vMyPath, vMyWarehouse, vMyProductionOrder
+ FROM ticket t
+ LEFT JOIN ticketState ts on ts.ticketFk = t.id
+ WHERE t.id = vTicketId;
+
+SELECT (ag.`name` = 'VN_VALENCIA')
+ INTO vIsValenciaPath
+ FROM vn2008.Rutas r
+ JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia
+ JOIN vn2008.agency ag on ag.agency_id = a.agency_id
+ WHERE r.Id_Ruta = vMyPath;
+
+IF vIsValenciaPath THEN -- Rutas Valencia
+
+ SELECT COUNT(*)
+ INTO vExpeditionsCount
+ FROM expedition e
+ JOIN ticket t ON t.id = e.ticketFk
+ WHERE t.routeFk = vMyPath;
+
+ SELECT MAX(ts.productionOrder), MIN(ts.productionOrder)
+ INTO vRestTicketsMaxOrder, vRestTicketsMinOrder
+ FROM ticket t
+ LEFT JOIN ticketState ts on t.id = ts.ticketFk
+ WHERE t.routeFk = vMyPath
+ AND t.warehouseFk = vMyWarehouse
+ AND t.id != vTicketid;
+
+ SELECT COUNT(*)
+ INTO vRestTicketsPacking
+ FROM ticket t
+ LEFT JOIN ticketState ts on t.id = ts.ticketFk
+ WHERE ts.productionOrder = PACKING_ORDER
+ AND t.routeFk = vMyPath
+ AND t.warehouseFk = vMyWarehouse
+ AND t.id != vTicketid;
+
+ IF vExpeditionsCount = 1 THEN
+ SET vPosition = 'FIRST';
+ ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN
+ SET vPosition = 'LAST';
+ ELSEIF vRestTicketsPacking THEN
+ SET vPosition = 'SHARED';
+ ELSE
+ SET vPosition = 'MID';
+ END IF;
+
+ELSE
+ SET vPosition = 'MID';
+
+END IF;
+
+RETURN vPosition;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticketSplitCounter.sql b/db/routines/vn/functions/ticketSplitCounter.sql
new file mode 100644
index 000000000..a04c4f8a9
--- /dev/null
+++ b/db/routines/vn/functions/ticketSplitCounter.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticketSplitCounter`(vTicketFk INT)
+ RETURNS varchar(15) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vSplitCounter VARCHAR(15);
+
+ SELECT CONCAT(printedStickers,'/',Total, IF(printedStickers = Total ,' LS','')) INTO vSplitCounter
+ FROM
+ (
+ SELECT count(l.Id_Movimiento) as printedStickers, COUNT(*) as Total
+ FROM vn.sale s
+ LEFT JOIN vn2008.movement_label l ON l.Id_Movimiento = s.id
+ WHERE ticketFk = vTicketFk
+ ) sub;
+
+ RETURN IFNULL(vSplitCounter,'--');
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticketTotalVolume.sql b/db/routines/vn/functions/ticketTotalVolume.sql
new file mode 100644
index 000000000..dc861ab6c
--- /dev/null
+++ b/db/routines/vn/functions/ticketTotalVolume.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticketTotalVolume`(vTicketId INT)
+ RETURNS decimal(10,3)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ -- Devuelte el volumen total del ticket sumado
+
+ DECLARE vVolume DECIMAL(10,3);
+
+ SELECT SUM(volume) INTO vVolume
+ FROM saleVolume
+ WHERE ticketFk = vTicketId;
+ RETURN vVolume;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticketTotalVolumeBoxes.sql b/db/routines/vn/functions/ticketTotalVolumeBoxes.sql
new file mode 100644
index 000000000..eb529bab9
--- /dev/null
+++ b/db/routines/vn/functions/ticketTotalVolumeBoxes.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticketTotalVolumeBoxes`(vTicketId INT)
+ RETURNS decimal(10,1)
+ DETERMINISTIC
+BEGIN
+
+/*
+ * Devuelve el volumen estimado del ticket sumado, en cajas
+ *
+ * vTicketId Numero de ticket
+ *
+ */
+
+ DECLARE vVolumeBoxM3 DOUBLE;
+ DECLARE vTicketTotalVolumeBoxes DECIMAL(10,1);
+ DECLARE vVnBoxId VARCHAR(10) DEFAULT '94';
+
+ SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId;
+
+ SET vTicketTotalVolumeBoxes = ticketTotalVolume(vTicketId) / vVolumeBoxM3;
+
+ RETURN vTicketTotalVolumeBoxes;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticketWarehouseGet.sql b/db/routines/vn/functions/ticketWarehouseGet.sql
new file mode 100644
index 000000000..705949f24
--- /dev/null
+++ b/db/routines/vn/functions/ticketWarehouseGet.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticketWarehouseGet`(vTicketFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vWarehouseFk INT;
+
+ SELECT warehouseFk INTO vWarehouseFk
+ FROM ticket
+ WHERE id = vTicketFk;
+
+ RETURN vWarehouseFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticket_CC_volume.sql b/db/routines/vn/functions/ticket_CC_volume.sql
new file mode 100644
index 000000000..2572ae12d
--- /dev/null
+++ b/db/routines/vn/functions/ticket_CC_volume.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_CC_volume`(vTicketFk INT)
+ RETURNS decimal(10,1)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ DECLARE vCC DECIMAL(10,1);
+
+ SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000)
+ INTO vCC
+ FROM vn.saleVolume sv
+ JOIN vn.sale s ON s.id = sv.saleFk
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.packaging p ON p.id = 'CC'
+ JOIN vn.volumeConfig vc
+ WHERE sv.ticketFk = vTicketFk;
+
+ RETURN vCC;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticket_HasUbication.sql b/db/routines/vn/functions/ticket_HasUbication.sql
new file mode 100644
index 000000000..344a34aa9
--- /dev/null
+++ b/db/routines/vn/functions/ticket_HasUbication.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_HasUbication`(vTicketFk INT)
+ RETURNS tinyint(1)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ DECLARE hasUbication BOOL;
+
+ SELECT COUNT(*) INTO hasUbication
+ FROM vn.ticket t
+ JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
+ WHERE rm.beachFk
+ AND t.id = vTicketFk;
+
+ RETURN hasUbication;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticket_get.sql b/db/routines/vn/functions/ticket_get.sql
new file mode 100644
index 000000000..1f0e9a25a
--- /dev/null
+++ b/db/routines/vn/functions/ticket_get.sql
@@ -0,0 +1,64 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_get`(vParamFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+proc:BEGIN
+
+ /* Devuelve el número de ticket o collection consultando en varias tablas posibles
+ *
+ * @param vParamFk Número a validar
+ * @return vValidFk Identificador validado
+ */
+
+ DECLARE vValidFk INT;
+
+ -- Tabla vn.saleGroup
+ SELECT s.ticketFk INTO vValidFk
+ FROM vn.sale s
+ JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
+ JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
+ WHERE sg.id = vParamFk
+ AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE())
+ LIMIT 1;
+
+ IF vValidFk THEN
+
+ RETURN vValidFk;
+
+ LEAVE proc;
+
+ END IF;
+
+ -- Tabla vn.collection
+ SELECT c.id INTO vValidFk
+ FROM vn.collection c
+ WHERE c.id = vParamFk
+ AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
+
+ IF vValidFk THEN
+
+ RETURN vValidFk;
+
+ LEAVE proc;
+
+ END IF;
+
+ -- Tabla vn.ticket
+ SELECT t.id INTO vValidFk
+ FROM vn.ticket t
+ WHERE t.id = vParamFk
+ AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
+
+ IF vValidFk THEN
+
+ RETURN vValidFk;
+
+ LEAVE proc;
+
+ END IF;
+
+ RETURN NULL;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticket_getFreightCost.sql b/db/routines/vn/functions/ticket_getFreightCost.sql
new file mode 100644
index 000000000..61905aff2
--- /dev/null
+++ b/db/routines/vn/functions/ticket_getFreightCost.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_getFreightCost`(vTicketFk INT)
+ RETURNS decimal(10,2)
+ DETERMINISTIC
+BEGIN
+/**
+ * Devuelve el coste de transportar un ticket.
+ *
+ * @vTicketFk Id del ticket a calcular
+ */
+ DECLARE deliveryPrice DECIMAL (10,2);
+
+ IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id
+ WHERE t.id = vTicketFk) THEN
+ SELECT SUM(sv.freight) INTO deliveryPrice
+ FROM vn.saleVolume sv
+ WHERE sv.ticketFk = vTicketFk;
+ ELSE
+ SELECT SUM((t.zonePrice - t.zoneBonus) * ebv.ratio) INTO deliveryPrice
+ FROM vn.ticket t
+ LEFT JOIN expedition e ON e.ticketFk = t.id
+ JOIN expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
+ WHERE t.id = vTicketFk;
+
+ END IF;
+ RETURN deliveryPrice;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticket_getWeight.sql b/db/routines/vn/functions/ticket_getWeight.sql
new file mode 100644
index 000000000..32f84cac7
--- /dev/null
+++ b/db/routines/vn/functions/ticket_getWeight.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_getWeight`(vTicketFk INT)
+ RETURNS decimal(10,3)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Devuelve el peso total del ticket
+ *
+ * @return Total peso
+ */
+
+ DECLARE vWeight DECIMAL(10,3);
+
+ SELECT sum(weight) INTO vWeight
+ FROM saleVolume
+ WHERE ticketFk = vTicketFk;
+
+ RETURN vWeight;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/ticket_isOutClosureZone.sql b/db/routines/vn/functions/ticket_isOutClosureZone.sql
new file mode 100644
index 000000000..ebddcf505
--- /dev/null
+++ b/db/routines/vn/functions/ticket_isOutClosureZone.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_isOutClosureZone`(vSelf INT)
+ RETURNS tinyint(1)
+ DETERMINISTIC
+BEGIN
+/**
+ * Devuelve true/false si la hora actual supera la hora del cierre del ticket más el tiempo configurado en packingDelay
+ *
+ * @param vSelf Ticket id
+ * @return true o false
+ */
+ DECLARE vIsTicketInTime BOOL;
+
+ SELECT TIMEDIFF(CURRENT_TIME(), zc.hour + INTERVAL tc.packingDelay HOUR) > 0 INTO vIsTicketInTime
+ FROM vn.ticket t
+ JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk
+ LEFT JOIN vn.ticketConfig tc ON TRUE
+ WHERE t.id = vSelf
+ AND zc.dated = util.VN_CURDATE();
+
+ RETURN vIsTicketInTime;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/till_new.sql b/db/routines/vn/functions/till_new.sql
new file mode 100644
index 000000000..24f4f2b79
--- /dev/null
+++ b/db/routines/vn/functions/till_new.sql
@@ -0,0 +1,79 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`till_new`(vClient INT
+ ,vBank INT
+ ,vAmount DOUBLE
+ ,vConcept VARCHAR(25)
+ ,vDated DATE
+ ,vSerie CHAR(1)
+ ,vBatch TINYINT
+ ,vNumber INT
+ ,vCompany SMALLINT
+ ,vWorker INT
+)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+ DECLARE vAccount VARCHAR(12);
+ DECLARE vSubaccount VARCHAR(12);
+ DECLARE vAsiento INT DEFAULT NULL;
+
+ -- Inserta el registro en cajas
+
+ INSERT INTO till
+ SET
+ workerFk = vWorker
+ ,bankFk = vBank
+ ,`in` = vAmount
+ ,concept = vConcept
+ ,dated = vDated
+ ,serie = vSerie
+ ,isAccountable = vBatch
+ ,`number` = vNumber
+ ,companyFk = vCompany;
+
+ -- Inserta los asientos contables
+
+ SELECT account INTO vAccount
+ FROM accounting WHERE id = vBank;
+
+ SELECT accountingAccount INTO vSubaccount
+ FROM `client` WHERE id = vClient;
+
+ SET vAsiento = xdiario_new
+ (
+ vAsiento
+ ,vDated
+ ,vAccount
+ ,vSubaccount
+ ,vConcept
+ ,vAmount
+ ,0
+ ,0
+ ,NULL -- Serie
+ ,NULL -- Factura
+ ,NULL -- IVA
+ ,NULL -- Recargo
+ ,FALSE -- Auxiliar
+ ,vCompany
+ );
+ DO xdiario_new
+ (
+ vAsiento
+ ,vDated
+ ,vSubaccount
+ ,vAccount
+ ,vConcept
+ ,0
+ ,vAmount
+ ,0
+ ,NULL -- Serie
+ ,NULL -- Factura
+ ,NULL -- IVA
+ ,NULL -- Recargo
+ ,FALSE -- Auxiliar
+ ,vCompany
+ );
+
+ RETURN NULL;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/timeWorkerControl_getDirection.sql b/db/routines/vn/functions/timeWorkerControl_getDirection.sql
new file mode 100644
index 000000000..518e4aeb5
--- /dev/null
+++ b/db/routines/vn/functions/timeWorkerControl_getDirection.sql
@@ -0,0 +1,65 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`timeWorkerControl_getDirection`(vUserFk INT, vTimed DATETIME)
+ RETURNS varchar(6) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Verifica la dirección de la fichada
+ * @param vUserFk Identificador del trabajador
+ * @param vTimed Hora de la fichada
+ * @return Retorna sentido de la fichada 'in, out, middle'
+ */
+
+ DECLARE vPrevious DATETIME ;
+ DECLARE vNext DATETIME ;
+ DECLARE vPreviousDirection VARCHAR(3) ;
+ DECLARE vNextDirection VARCHAR(3) ;
+ DECLARE vDayStayMax INT;
+ DECLARE vTimedSeconds INT;
+ DECLARE vLastTimeIn INT;
+
+ SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds;
+
+ SELECT dayStayMax INTO vDayStayMax
+ FROM vn.workerTimeControlParams;
+
+ SELECT timed, direction INTO vNext,vNextDirection
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
+ AND direction IN ('in','out')
+ AND timed > vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+
+ SELECT timed, direction INTO vPrevious, vPreviousDirection
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
+ AND direction IN ('in','out')
+ AND timed < vTimed
+ ORDER BY timed DESC
+ LIMIT 1;
+
+ IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN
+ RETURN 'middle';
+ END IF;
+
+
+ IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN
+ IF vPreviousDirection = 'in' THEN
+ RETURN 'out';
+ ELSE
+ SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
+ AND direction ='in'
+ AND timed < vPrevious;
+ IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN
+ RETURN 'out';
+ END IF;
+ END IF;
+ END IF;
+
+ RETURN 'in';
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/time_getSalesYear.sql b/db/routines/vn/functions/time_getSalesYear.sql
new file mode 100644
index 000000000..658a1112a
--- /dev/null
+++ b/db/routines/vn/functions/time_getSalesYear.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`time_getSalesYear`(vMonth INT, vYear INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+DECLARE vSalesYear INT;
+SELECT salesYear INTO vSalesYear
+FROM `time`
+WHERE `month` = vMonth AND `year` = vYear
+LIMIT 1;
+RETURN vSalesYear;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/travel_getForLogiflora.sql b/db/routines/vn/functions/travel_getForLogiflora.sql
new file mode 100644
index 000000000..cb3f0dac0
--- /dev/null
+++ b/db/routines/vn/functions/travel_getForLogiflora.sql
@@ -0,0 +1,52 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+
+ /**
+ * Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén.
+ * Si no existe lo genera.
+ *
+ * @param vLanded Fecha de llegada al almacén
+ * @param vWarehouseFk Identificador de vn.warehouse
+ */
+
+ DECLARE vTravelFk INT;
+
+ IF vLanded THEN
+
+ SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
+ FROM vn.travel tr
+ JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
+ JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
+ JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
+ WHERE wIn.id = vWarehouseFk
+ AND wOut.name = 'Holanda'
+ AND am.name = 'LOGIFLORA'
+ AND landed = vLanded;
+
+ IF NOT vTravelFk THEN
+
+ INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
+ SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id
+ FROM vn.warehouse wOut
+ JOIN vn.agencyMode am ON am.name = 'LOGIFLORA'
+ WHERE wOut.name = 'Holanda';
+
+ SELECT MAX(tr.id) INTO vTravelFk
+ FROM vn.travel tr
+ JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
+ JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
+ WHERE wIn.id = vWarehouseFk
+ AND wOut.name = 'Holanda'
+ AND landed = vLanded;
+ END IF;
+
+ END IF;
+
+ RETURN vTravelFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/travel_hasUniqueAwb.sql b/db/routines/vn/functions/travel_hasUniqueAwb.sql
new file mode 100644
index 000000000..e918f1a26
--- /dev/null
+++ b/db/routines/vn/functions/travel_hasUniqueAwb.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`travel_hasUniqueAwb`(
+ vSelf INT
+)
+ RETURNS BOOL
+ READS SQL DATA
+BEGIN
+/**
+ * Comprueba que el travel pasado tiene un AWB lógico,
+ * no se pueden tener varios AWB asociados al mismo DUA
+ *
+ * @param vSelf Id del travel
+ */
+ DECLARE vHasUniqueAwb BOOL DEFAULT TRUE;
+
+ SELECT NOT COUNT(t2.awbFk) INTO vHasUniqueAwb
+ FROM entry e
+ JOIN travel t ON t.id = e.travelFk
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN duaEntry de2 ON de2.duaFk = de.duaFk
+ JOIN entry e2 ON e2.id = de2.entryFk
+ JOIN travel t2 ON t2.id = e2.travelFk
+ WHERE t.id = vSelf
+ AND t2.awbFk <> t.awbFk;
+
+ RETURN vHasUniqueAwb;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/validationCode.sql b/db/routines/vn/functions/validationCode.sql
new file mode 100644
index 000000000..75d603d24
--- /dev/null
+++ b/db/routines/vn/functions/validationCode.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`validationCode`(vString VARCHAR(255))
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vSeed DOUBLE DEFAULT 0;
+ DECLARE vCode INT;
+ DECLARE vLength INT;
+ DECLARE vChar INT;
+
+ SET vLength = length(vString);
+
+ WHILE vLength > 0 DO
+
+ SET vChar = MID(vString,vLength,1);
+
+ SET vSeed = vSeed + ASCII(vChar);
+
+ SET vLength = vLength - 1;
+
+ END WHILE;
+
+ SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000;
+
+ RETURN vCode;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/validationCode_beta.sql b/db/routines/vn/functions/validationCode_beta.sql
new file mode 100644
index 000000000..0e27a4722
--- /dev/null
+++ b/db/routines/vn/functions/validationCode_beta.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`validationCode_beta`(vString VARCHAR(255))
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vSeed DOUBLE DEFAULT 0;
+ DECLARE vCode INT;
+ DECLARE vLength INT;
+ DECLARE vChar INT;
+
+ SET vLength = length(vString);
+
+ WHILE vLength > 0 DO
+
+ SET vChar = MID(vString,vLength,1);
+
+ SET vSeed = vSeed + ASCII(vChar);
+
+ SET vLength = vLength - 1;
+
+ END WHILE;
+
+ SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000;
+
+ RETURN vCode;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/workerMachinery_isRegistered.sql b/db/routines/vn/functions/workerMachinery_isRegistered.sql
new file mode 100644
index 000000000..89a1c44ac
--- /dev/null
+++ b/db/routines/vn/functions/workerMachinery_isRegistered.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`workerMachinery_isRegistered`(vWorkerFk VARCHAR(10))
+ RETURNS tinyint(1)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Comprueba si existen registros en las últimas horas (maxHours de machineWorkerConfig) del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo)
+ *
+ * @param vWorkerFk id del trabajador
+ * @return Devuelve TRUE/FALSE en caso de que haya o no registros
+ */
+ IF (SELECT COUNT(*)
+ FROM machineWorker m
+ WHERE m.workerFk = vWorkerFk
+ AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), util.VN_NOW()) AND ISNULL(m.outTimed))
+ THEN
+ RETURN TRUE;
+ ELSE
+ RETURN FALSE;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/workerNigthlyHours_calculate.sql b/db/routines/vn/functions/workerNigthlyHours_calculate.sql
new file mode 100644
index 000000000..0828b30f9
--- /dev/null
+++ b/db/routines/vn/functions/workerNigthlyHours_calculate.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`workerNigthlyHours_calculate`(vTimeIn DATETIME, vTimeOut DATETIME)
+ RETURNS decimal(5,2)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Calcula el número decimal de horas nocturnas comprendidas entre 2 horas dadas
+ *
+ * @param vTimeIn
+ * @param vTimeOut
+ * @return vNigthlyHours
+ */
+ DECLARE vNigthlyHours DECIMAL(5,2);
+ DECLARE vSecondsPerHour INT(4) DEFAULT 3600;
+
+ SELECT GREATEST(0, TIMESTAMPDIFF(SECOND,
+ IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours,
+ CONCAT(DATE(vTimeIn), ' ', startNightlyHours),
+ vTimeIn),
+ IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours,
+ CONCAT(DATE(vTimeOut), ' ', endNightlyHours),
+ vTimeOut))) / vSecondsPerHour INTO vNigthlyHours
+ FROM vn.workerTimeControlConfig;
+
+ RETURN vNigthlyHours;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/worker_getCode.sql b/db/routines/vn/functions/worker_getCode.sql
new file mode 100644
index 000000000..d3d63dccc
--- /dev/null
+++ b/db/routines/vn/functions/worker_getCode.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`worker_getCode`()
+ RETURNS varchar(3) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+ DECLARE vUserCode VARCHAR(3) CHARSET utf8 COLLATE utf8_unicode_ci;
+
+ SELECT code INTO vUserCode
+ FROM worker
+ WHERE id = account.myUser_getId();
+
+ RETURN vUserCode;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/worker_isBoss.sql b/db/routines/vn/functions/worker_isBoss.sql
new file mode 100644
index 000000000..7efada705
--- /dev/null
+++ b/db/routines/vn/functions/worker_isBoss.sql
@@ -0,0 +1,47 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`worker_isBoss`(vUserId INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Comprueba por jerarquía si el trabajador actual es jefe
+ * de un trabajador en concreto.
+ *
+ * @param vSelf Id del trabajador que se desea comprobar.
+ * @return Revuelve verdadero si es jefe del empleado por escala jerárquica.
+ */
+ DECLARE vWorkerId INT;
+ DECLARE vBossId INT;
+
+ SELECT id INTO vWorkerId
+ FROM worker
+ WHERE id = vSelf;
+ IF vWorkerId IS NULL THEN
+ CALL util.throw('USER_NOT_FOUND');
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tCheckedWorker;
+ CREATE TEMPORARY TABLE tCheckedWorker
+ (PRIMARY KEY (workerFk))
+ ENGINE = MEMORY
+ SELECT id workerFk FROM worker LIMIT 0;
+ LOOP
+ SELECT bossFk INTO vBossId
+ FROM worker
+ WHERE id = vWorkerId;
+ IF (SELECT COUNT(*) FROM tCheckedWorker WHERE workerFk = vBossId) THEN
+ CALL util.throw('INFINITE_LOOP');
+ END IF;
+ IF vBossId = vWorkerId THEN
+ RETURN FALSE;
+ ELSEIF vBossId = account.myUser_getId() THEN
+ RETURN TRUE;
+ ELSE
+ INSERT INTO tCheckedWorker VALUES (vWorkerId);
+ SET vWorkerId = vBossId;
+ END IF;
+ END LOOP;
+ DROP TEMPORARY TABLE tCheckedWorker;
+ RETURN FALSE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/worker_isInDepartment.sql b/db/routines/vn/functions/worker_isInDepartment.sql
new file mode 100644
index 000000000..8eee3656e
--- /dev/null
+++ b/db/routines/vn/functions/worker_isInDepartment.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`worker_isInDepartment`(vDepartmentCode VARCHAR(255))
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Devuelve booleano si el trabajador conectado pertenece
+ * al departamento vDepartmentCode o a sus departamentos subordinados
+ *
+ * @param vDepartmentCode code del departamento que se desea comprobar.
+ * @return Devuelve verdadero si es jefe del empleado por escala jerárquica.
+ */
+ DECLARE vIsInDepartment BOOLEAN;
+ WITH RECURSIVE department AS (
+ SELECT d.id FROM vn.department d WHERE code = vDepartmentCode
+ UNION
+ SELECT d.id
+ FROM department ds
+ JOIN vn.department d ON ds.id = d.parentFk
+ )
+ SELECT COUNT(*) INTO vIsInDepartment FROM department ds
+ JOIN vn.workerDepartment wd ON wd.departmentFk = ds.id
+ WHERE wd.workerFk = account.myUser_getId();
+
+ RETURN vIsInDepartment;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/worker_isWorking.sql b/db/routines/vn/functions/worker_isWorking.sql
new file mode 100644
index 000000000..3db333bd0
--- /dev/null
+++ b/db/routines/vn/functions/worker_isWorking.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`worker_isWorking`(vWorkerFk INT)
+ RETURNS tinyint(1)
+ NOT DETERMINISTIC
+ READS SQL DATA
+BEGIN
+/**
+ * Comprueba si el trabajador está trabajando en el momento de la consulta
+ * @return Devuelve TRUE en caso de que este trabajando. Si se encuentra en un descanso devolverá FALSE
+ */
+ DECLARE vLastIn DATETIME ;
+
+ SELECT MAX(timed) INTO vLastIn
+ FROM vn.workerTimeControl
+ WHERE userFk = vWorkerFk AND
+ direction = 'in';
+
+ IF (SELECT MOD(COUNT(*),2)
+ FROM vn.workerTimeControl
+ WHERE userFk = vWorkerFk AND
+ timed >= vLastIn
+ ) THEN
+ RETURN TRUE;
+ ELSE
+ RETURN FALSE;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/xdiario_new.sql b/db/routines/vn/functions/xdiario_new.sql
new file mode 100644
index 000000000..06e6e57b2
--- /dev/null
+++ b/db/routines/vn/functions/xdiario_new.sql
@@ -0,0 +1,44 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`xdiario_new`(vAsiento INT,
+ vDated DATE,
+ vSubaccount VARCHAR(12),
+ vAccount VARCHAR(12),
+ vConcept VARCHAR(25),
+ vDebit DOUBLE,
+ vCredit DOUBLE,
+ vEuro DOUBLE,
+ vSerie CHAR(1),
+ vInvoice VARCHAR(8),
+ vVat DOUBLE,
+ vRe DOUBLE,
+ vAux TINYINT,
+ vCompany INT
+)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ NO SQL
+BEGIN
+ IF vAsiento IS NULL THEN
+ CALL vn.ledger_next(vAsiento);
+ END IF;
+
+ INSERT INTO XDiario
+ SET ASIEN = vAsiento,
+ FECHA = vDated,
+ SUBCTA = vSubaccount,
+ CONTRA = vAccount,
+ CONCEPTO = vConcept,
+ EURODEBE = vDebit,
+ EUROHABER = vCredit,
+ BASEEURO = vEuro,
+ SERIE = vSerie,
+ FACTURA = vInvoice,
+ IVA = vVat,
+ RECEQUIV = vRe,
+ AUXILIAR = IF(vAux = FALSE, NULL, '*'),
+ MONEDAUSO = 2,
+ empresa_id = vCompany;
+
+ RETURN vAsiento;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/zoneGeo_new.sql b/db/routines/vn/functions/zoneGeo_new.sql
new file mode 100644
index 000000000..65b045962
--- /dev/null
+++ b/db/routines/vn/functions/zoneGeo_new.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`zoneGeo_new`(vType VARCHAR(255), vName VARCHAR(255), vParentFk INT)
+ RETURNS int(11)
+ NOT DETERMINISTIC
+ NO SQL
+BEGIN
+/**
+ * Creates a new node a node from the #zoneGeo table.
+ * Also sets a mark to force the tree recalculation.
+ *
+ * @param vType The node type
+ * @param vName The node name
+ * @param vParentFk The parent node identifier
+ * @return The new node identifier
+ */
+ DECLARE vSelf INT;
+
+ INSERT INTO zoneGeo
+ SET `type` = vType,
+ `name` = vName,
+ parentFk = vParentFk;
+
+ SET vSelf = LAST_INSERT_ID();
+
+ UPDATE zoneGeoRecalc SET isChanged = TRUE;
+
+ RETURN vSelf;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/XDiario_check.sql b/db/routines/vn/procedures/XDiario_check.sql
new file mode 100644
index 000000000..0fb1c410d
--- /dev/null
+++ b/db/routines/vn/procedures/XDiario_check.sql
@@ -0,0 +1,41 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_check`()
+BEGIN
+/**
+ * Realiza la revisión diaria de los asientos contables,
+ * identificando y notificando los asientos descuadrados
+ * y ajustando los saldos en caso necesario.
+ */
+ INSERT INTO mail (receiver, subject, body)
+ SELECT 'cau@verdnatura.es',
+ 'Asientos descuadrados',
+ GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n')
+ FROM (
+ SELECT ASIEN,
+ SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon
+ FROM XDiario
+ WHERE NOT enlazado
+ GROUP BY ASIEN
+ HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01
+ ) sub
+ HAVING COUNT(*);
+
+ UPDATE XDiario xd
+ JOIN (
+ SELECT xd.id, SUBCTA, recon
+ FROM XDiario xd
+ JOIN (
+ SELECT ASIEN,
+ SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon
+ FROM XDiario
+ WHERE NOT enlazado
+ GROUP BY ASIEN
+ HAVING recon
+ ) sub ON sub.ASIEN = xd.ASIEN
+ WHERE xd.SUBCTA > '5999999999'
+ GROUP BY xd.ASIEN
+ ) sub ON sub.id = xd.id
+ SET xd.Eurohaber = IF(IFNULL(xd.Eurohaber, 0) = 0, xd.Eurohaber, xd.Eurohaber + sub.recon),
+ xd.Eurodebe = IF(IFNULL(xd.Eurodebe, 0) = 0, xd.Eurodebe, xd.Eurodebe - sub.recon);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/XDiario_checkDate.sql b/db/routines/vn/procedures/XDiario_checkDate.sql
new file mode 100644
index 000000000..b481d1f36
--- /dev/null
+++ b/db/routines/vn/procedures/XDiario_checkDate.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_checkDate`(vDate DATE)
+proc: BEGIN
+/**
+ * Comprueba si la fecha pasada esta en el rango
+ * de fecha de contabilidad
+ *
+ * @param vDate Fecha para comparar
+ */
+ DECLARE vIsInvalid BOOL;
+
+ IF vDate IS NULL THEN
+ LEAVE proc;
+ END IF;
+
+ SELECT COUNT(*) = 0 INTO vIsInvalid
+ FROM accountingConfig
+ WHERE vDate BETWEEN minDate AND maxDate;
+
+ IF vIsInvalid THEN
+ CALL util.throw ('Fecha fuera de rango');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/absoluteInventoryHistory.sql b/db/routines/vn/procedures/absoluteInventoryHistory.sql
new file mode 100644
index 000000000..627b7c8be
--- /dev/null
+++ b/db/routines/vn/procedures/absoluteInventoryHistory.sql
@@ -0,0 +1,102 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`absoluteInventoryHistory`(
+ vItemFk INT,
+ vWarehouseFk INT,
+ vDate DATETIME
+)
+BEGIN
+/**
+* Calcula y proporciona un historial de inventario absoluto
+* para un artículo específico en un almacén dado
+* hasta una fecha determinada.
+*
+* @param vItemFk Id de artículo
+* @param vWarehouseFk Id de almacén
+* @param vDate Fecha
+*/
+ DECLARE vCalculatedInventory INT;
+ DECLARE vToday DATETIME DEFAULT util.VN_CURDATE();
+ DECLARE vStartDate DATE DEFAULT '2001-01-01';
+
+ CREATE OR REPLACE TEMPORARY TABLE tHistoricalPast
+ ENGINE = MEMORY
+ SELECT *
+ FROM (
+ SELECT tr.landed `date`,
+ b.quantity input,
+ NULL `output`,
+ tr.isReceived ok,
+ s.name alias,
+ e.invoiceNumber reference,
+ e.id id,
+ tr.isDelivered f5
+ FROM buy b
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN supplier s ON s.id = e.supplierFk
+ WHERE tr.landed >= vStartDate
+ AND s.id <> (SELECT supplierFk FROM inventoryConfig)
+ AND vWarehouseFk IN (tr.warehouseInFk, 0)
+ AND b.itemFk = vItemFk
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ UNION ALL
+ SELECT tr.shipped,
+ NULL,
+ b.quantity,
+ tr.isDelivered,
+ s.name,
+ e.invoiceNumber,
+ e.id,
+ tr.isDelivered
+ FROM buy b
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN supplier s ON s.id = e.supplierFk
+ WHERE tr.shipped >= vStartDate
+ AND vWarehouseFk = tr.warehouseOutFk
+ AND s.id <> (SELECT supplierFk FROM inventoryConfig)
+ AND b.itemFk = vItemFk
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ UNION ALL
+ SELECT t.shipped,
+ NULL,
+ m.quantity,
+ (m.isPicked OR t.isLabeled OR t.refFk IS NOT NULL),
+ t.nickname,
+ t.refFk,
+ t.id,
+ t.isPrinted
+ FROM sale m
+ JOIN ticket t ON t.id = m.ticketFk
+ JOIN client c ON c.id = t.clientFk
+ WHERE t.shipped >= vStartDate
+ AND m.itemFk = vItemFk
+ AND vWarehouseFk IN (t.warehouseFk, 0)
+ ) t1
+ ORDER BY `date`, input DESC, ok DESC;
+
+ SELECT SUM(input) - SUM(`output`) INTO vCalculatedInventory
+ FROM tHistoricalPast
+ WHERE `date` < vDate;
+
+ SELECT p1.*, NULL v_virtual
+ FROM (
+ SELECT vDate `date`,
+ vCalculatedInventory input,
+ NULL `output`,
+ 1 ok,
+ 'Inventario calculado' alias,
+ '' reference,
+ 0 id,
+ 1 f5
+ UNION ALL
+ SELECT *
+ FROM tHistoricalPast
+ WHERE `date` >= vDate
+ ) p1;
+
+ DROP TEMPORARY TABLE tHistoricalPast;
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/addNoteFromDelivery.sql b/db/routines/vn/procedures/addNoteFromDelivery.sql
new file mode 100644
index 000000000..61295b7db
--- /dev/null
+++ b/db/routines/vn/procedures/addNoteFromDelivery.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`addNoteFromDelivery`(idTicket INT,nota TEXT)
+BEGIN
+
+ DECLARE observationTypeFk INT DEFAULT 3; /*3 = REPARTIDOR*/
+
+ INSERT INTO ticketObservation(ticketFk,observationTypeFk,description)
+ VALUES (idTicket,observationTypeFk,nota)
+ ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' ');
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/addressTaxArea.sql b/db/routines/vn/procedures/addressTaxArea.sql
new file mode 100644
index 000000000..5deb01fa4
--- /dev/null
+++ b/db/routines/vn/procedures/addressTaxArea.sql
@@ -0,0 +1,38 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`addressTaxArea`()
+ READS SQL DATA
+BEGIN
+/**
+ * Devuelve el taxArea para un conjunto de Consignatarios y empresas,
+ *
+ * @table tmp.addressCompany(addressFk, companyFk) valores a calcular
+ * @return tmp.addressTaxArea(addressFk,companyFk)
+ */
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea;
+ CREATE TEMPORARY TABLE tmp.addressTaxArea
+ (PRIMARY KEY (addressFk, companyFk))
+ ENGINE = MEMORY
+ SELECT CASE
+ WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember)
+ AND NOT (auSupplier.id <=> auClient.id) THEN
+ 'WORLD'
+ WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN
+ 'CEE'
+ WHEN a.isEqualizated AND cClient.code = 'ES' THEN
+ 'EQU'
+ ELSE
+ 'NATIONAL'
+ END AS areaFk, ac.addressFk, ac.companyFk
+ FROM tmp.addressCompany ac
+ JOIN address a ON a.id = ac.addressFk
+ JOIN `client` c ON c.id = a.clientFk
+ JOIN country cClient ON cClient.id = c.countryFk
+ LEFT JOIN province pClient ON pClient.id = c.provinceFk
+ LEFT JOIN autonomy auClient ON auClient.id = pClient.autonomyFk
+ JOIN supplier s ON s.id = ac.companyFk
+ JOIN country cSupplier ON cSupplier.id = s.countryFk
+ LEFT JOIN province pSupplier ON pSupplier.id = s.provinceFk
+ LEFT JOIN autonomy auSupplier ON auSupplier.id = pSupplier.autonomyFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/agencyHourGetFirstShipped.sql b/db/routines/vn/procedures/agencyHourGetFirstShipped.sql
new file mode 100644
index 000000000..4bd1c4222
--- /dev/null
+++ b/db/routines/vn/procedures/agencyHourGetFirstShipped.sql
@@ -0,0 +1,35 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`agencyHourGetFirstShipped`(vAgencyMode INT, vAddress INT, vWarehouse INT)
+BEGIN
+/**
+ * DEPRECATED usar zoneGetFirstShipped
+* Devuelve la primera fecha de envio disponible para una agencia en una direccion y un warehouse
+*
+* @param vAgencyMode id de la agencia en vn.agencyMode
+* @param vAddress id de la direccion
+* @param vWarehouse id del warehouse
+* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida
+*/
+DECLARE vAgency INT;
+DECLARE vShipped DATE;
+DECLARE vLanded DATE DEFAULT util.VN_CURDATE();
+ SELECT agencyFk INTO vAgency FROM agencyMode WHERE id= vAgencyMode;
+
+ l: LOOP
+
+ CALL agencyHourGetShipped(vLanded,vAddress,vAgency);
+ SELECT shipped INTO vShipped
+ FROM tmp.agencyHourGetShipped
+ WHERE warehouseFk = vWarehouse LIMIT 1;
+
+ IF vShipped THEN
+ LEAVE l;
+ END IF;
+
+ SET vLanded = DATE_ADD(vLanded, INTERVAL +1 DAY);
+
+ END LOOP;
+
+ SELECT vShipped,vLanded;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/agencyHourGetLanded.sql b/db/routines/vn/procedures/agencyHourGetLanded.sql
new file mode 100644
index 000000000..ee48388a0
--- /dev/null
+++ b/db/routines/vn/procedures/agencyHourGetLanded.sql
@@ -0,0 +1,37 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`agencyHourGetLanded`(vDated DATE, vAddress INT, vAgency INT, vWarehouse INT)
+BEGIN
+/**
+ * DEPRECATED usar zoneGetLanded
+ * Devuelve una tabla temporal con el dia de recepcion para vDated.
+ *
+ * @param vDated Fecha de preparacion de mercancia
+ * @param vAddress Id de consignatario, %NULL para recogida
+ * @param vAgency Id agencia
+ * @table tmp.agencyHourGetLanded Datos de recepción
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetLanded;
+ CREATE TEMPORARY TABLE tmp.agencyHourGetLanded
+ ENGINE = MEMORY
+ SELECT vWarehouse warehouseFk, landed FROM (
+ SELECT * FROM (
+ SELECT vWarehouse, TIMESTAMPADD(DAY, ah.substractDay, vDated) landed, ah.substractDay, ah.maxHour
+ FROM agencyHour ah
+ LEFT JOIN address a ON a.id = vAddress
+ WHERE (ah.weekDay = WEEKDAY(TIMESTAMPADD(DAY, ah.substractDay, vDated)) OR ah.weekDay IS NULL)
+ AND (ah.agencyFk = vAgency OR ah.agencyFk IS NULL)
+ AND ah.warehouseFk = vWarehouse
+ AND (ah.provinceFk = a.provinceFk OR ah.provinceFk IS NULL OR vAddress IS NULL)
+ ORDER BY (
+ (ah.weekDay IS NOT NULL) +
+ (ah.agencyFk IS NOT NULL) +
+ (- ah.substractDay) +
+ ((ah.provinceFk IS NOT NULL)*3)
+ ) DESC
+ ) t
+ LIMIT 1
+ ) t
+ WHERE IF(vDated = util.VN_CURDATE(), t.maxHour > HOUR(util.VN_NOW()), TRUE) AND t.substractDay < 225;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/agencyHourGetWarehouse.sql b/db/routines/vn/procedures/agencyHourGetWarehouse.sql
new file mode 100644
index 000000000..7fc524fce
--- /dev/null
+++ b/db/routines/vn/procedures/agencyHourGetWarehouse.sql
@@ -0,0 +1,78 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`agencyHourGetWarehouse`(vAddress INT, vDate DATE, vWarehouse INT)
+BEGIN
+/**
+ * DEPRECATED usar zoneGetWarehouse
+ * Devuelve el listado de agencias disponibles para la fecha,
+ * dirección y warehouuse pasadas
+ *
+ * @param vAddress no puede ser NULL
+ * @param vWarehouse warehouse donde comprobaremos las agencias y fecha
+ * @param vDate Fecha de recogida
+ * @table agencyModeWarehouseList Listado de agencias disponibles
+ */
+ DECLARE vAgency INT;
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vCur CURSOR FOR
+ SELECT DISTINCT a.id
+ FROM agency a
+ JOIN agencyHour ah ON ah.agencyFk = a.id;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ IF vAddress IS NULL
+ THEN
+ CALL util.throw ('Address cannot be null');
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.agencyModeWarehouseList;
+ CREATE TEMPORARY TABLE tmp.agencyModeWarehouseList (
+ id INT NOT NULL,
+ agency VARCHAR(20),
+ description VARCHAR(45),
+ deliveryMethodFk VARCHAR(45),
+ shipped DATE,
+ warehouse VARCHAR(45),
+ PRIMARY KEY(id)
+ )
+ ENGINE = MEMORY;
+
+ OPEN vCur;
+ FETCH vCur INTO vAgency;
+
+ WHILE NOT vDone
+ DO
+
+ INSERT INTO tmp.agencyModeWarehouseList
+ SELECT am.id, am.name, am.description,am.deliveryMethodFk, TIMESTAMPADD(DAY, -ah.substractDay, vDate), w.name
+ FROM agencyHour ah
+ LEFT JOIN address a ON a.id = vAddress
+ JOIN agencyMode am ON am.agencyFk = vAgency
+ JOIN warehouse w on w.id = ah.warehouseFk
+ WHERE ah.warehouseFk = vWarehouse
+ AND (weekDay = WEEKDAY(vDate)
+ OR weekDay IS NULL)
+ AND (ah.agencyFk = vAgency
+ OR ah.agencyFk IS NULL)
+ AND (ah.provinceFk = a.provinceFk
+ OR ah.provinceFk IS NULL
+ OR vAddress IS NULL)
+ AND TIMESTAMPADD(DAY, -ah.substractDay, vDate) >= util.VN_CURDATE()
+ AND IF(TIMESTAMPADD(DAY, -ah.substractDay, vDate) = util.VN_CURDATE(), ah.maxHour > HOUR(util.VN_NOW()), TRUE)
+ ORDER BY (
+ (ah.weekDay IS NOT NULL) +
+ (ah.agencyFk IS NOT NULL) +
+ ((ah.provinceFk IS NOT NULL) * 3)
+ ) DESC
+ LIMIT 1;
+
+
+ FETCH vCur INTO vAgency;
+ END WHILE;
+
+ CLOSE vCur;
+
+ SELECT * FROM tmp.agencyModeWarehouseList;
+ DROP TEMPORARY TABLE tmp.agencyModeWarehouseList;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/agencyHourListGetShipped.sql b/db/routines/vn/procedures/agencyHourListGetShipped.sql
new file mode 100644
index 000000000..b4cf35f77
--- /dev/null
+++ b/db/routines/vn/procedures/agencyHourListGetShipped.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`agencyHourListGetShipped`(vDate DATE, vAddress INT, vAgency INT)
+BEGIN
+ /* * DEPRECATED usar zoneGetShipped
+*/
+ CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency);
+
+ SELECT * FROM tmp.agencyHourGetShipped;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/available_calc.sql b/db/routines/vn/procedures/available_calc.sql
new file mode 100644
index 000000000..8c806d41d
--- /dev/null
+++ b/db/routines/vn/procedures/available_calc.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`available_calc`(
+ vDate DATE,
+ vAddress INT,
+ vAgencyMode INT)
+BEGIN
+/**
+ * Calculates the available for all available stores
+ * according to the given parameters.
+ *
+ * @param vDate The delivery date
+ * @param vAddress The delivery address id
+ * @param vAgencyMode The shipping agency
+ * @return tmp.availableCalc(calcFk) The available cache ids
+ */
+ DECLARE vCalcFk INT;
+ DECLARE vShipment DATE;
+ DECLARE vWarehouse INT;
+ DECLARE vDone BOOL;
+
+ DECLARE cWarehouses CURSOR FOR
+ SELECT warehouseFk, shipped FROM tmp.zoneGetShipped;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ -- Establecemos los almacenes y las fechas que van a entrar al disponible
+
+ CALL vn.zone_getShipped (vDate, vAddress, vAgencyMode, FALSE);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc;
+ CREATE TEMPORARY TABLE tmp.availableCalc(
+ calcFk INT UNSIGNED,
+ PRIMARY KEY (calcFk)
+ )
+ ENGINE = MEMORY;
+
+ OPEN cWarehouses;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH cWarehouses INTO vWarehouse, vShipment;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment);
+
+ INSERT IGNORE INTO tmp.availableCalc
+ SET calcFk = vCalcFk;
+ END LOOP;
+
+ CLOSE cWarehouses;
+ DROP TEMPORARY TABLE tmp.zoneGetShipped;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/balanceNestTree_addChild.sql b/db/routines/vn/procedures/balanceNestTree_addChild.sql
new file mode 100644
index 000000000..5cd1ab470
--- /dev/null
+++ b/db/routines/vn/procedures/balanceNestTree_addChild.sql
@@ -0,0 +1,52 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_addChild`(
+ vSelf INT,
+ vName VARCHAR(45)
+)
+BEGIN
+/**
+ * Agrega un nuevo nodo hijo a un nodo existente dentro de la estructura
+ * de árbol de vn.balanceNestTree.
+ *
+ * @param vSelf Identificador del nodo
+ * @param vName Nombre del nuevo nodo hijo
+ */
+ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree');
+ DECLARE vLeft INT;
+
+ CREATE OR REPLACE TEMPORARY TABLE tAux
+ SELECT 0 lft;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux
+ SET lft = (SELECT lft
+ FROM ', vTable,
+ ' WHERE id = ?)')
+ USING vSelf;
+
+ SELECT lft INTO vLeft FROM tAux;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable, '
+ SET rgt = rgt + 2
+ WHERE rgt > ?
+ ORDER BY rgt DESC')
+ USING vLeft;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable, '
+ SET lft = lft + 2
+ WHERE lft > ?
+ ORDER BY lft DESC')
+ USING vLeft;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'INSERT INTO ', vTable, ' (name, lft, rgt)
+ VALUES(?, ? + 1, ? + 2)')
+ USING vName,
+ vLeft,
+ vLeft;
+
+ DROP TEMPORARY TABLE tAux;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/balanceNestTree_delete.sql b/db/routines/vn/procedures/balanceNestTree_delete.sql
new file mode 100644
index 000000000..1d6a9efff
--- /dev/null
+++ b/db/routines/vn/procedures/balanceNestTree_delete.sql
@@ -0,0 +1,53 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_delete`(
+ vSelf INT
+)
+BEGIN
+/**
+ * Elimina un nodo dentro de la estructura de árbol de vn.balanceNestTree.
+ *
+ * @param vSelf Identificador del nodo
+ */
+ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree');
+ DECLARE vRight INT;
+ DECLARE vLeft INT;
+ DECLARE vWidth INT;
+
+ CREATE OR REPLACE TEMPORARY TABLE tAux
+ SELECT 0 rgt, 0 lft, 0 wdt;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux a
+ JOIN ', vTable, ' t
+ SET a.rgt = t.rgt,
+ a.lft = t.lft,
+ a.wdt = t.rgt - t.lft + 1
+ WHERE t.id = ?')
+ USING vSelf;
+
+ SELECT rgt, lft, wdt
+ INTO vRight, vLeft, vWidth
+ FROM tAux;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'DELETE FROM ', vTable,
+ ' WHERE lft BETWEEN ? AND ?')
+ USING vLeft, vRight;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ ' SET rgt = rgt - ?
+ WHERE rgt > ?
+ ORDER BY rgt')
+ USING vWidth,vRight;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ ' SET lft = lft - ?
+ WHERE lft > ?
+ ORDER BY lft')
+ USING vWidth, vRight;
+
+ DROP TEMPORARY TABLE tAux;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/balanceNestTree_move.sql b/db/routines/vn/procedures/balanceNestTree_move.sql
new file mode 100644
index 000000000..ce29de1d9
--- /dev/null
+++ b/db/routines/vn/procedures/balanceNestTree_move.sql
@@ -0,0 +1,117 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_move`(
+ vSelf INT,
+ vFather INT
+)
+BEGIN
+/**
+ * Mueve un nodo dentro de la estructura de árbol de vn.balanceNestTree.
+ *
+ * @param vSelf Identificador del nodo
+ * @param vFather Identificador del nuevo padre del nodo
+ */
+ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree');
+ DECLARE vRight INT;
+ DECLARE vLeft INT;
+ DECLARE vWidth INT;
+ DECLARE vFatherRight INT;
+ DECLARE vFatherLeft INT;
+ DECLARE vGap INT;
+
+ CREATE OR REPLACE TEMPORARY TABLE tAux
+ SELECT 0 rgt, 0 lft, 0 wdt, 0 frg, 0 flf;
+
+ -- Averiguamos el ancho de la rama
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux a
+ JOIN ', vTable, ' t
+ SET a.wdt = t.rgt - t.lft + 1
+ WHERE t.id = ?')
+ USING vSelf;
+
+ -- Averiguamos la posicion del nuevo padre
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux a
+ JOIN ', vTable, ' t
+ SET a.frg = t.rgt,
+ a.flf = t.lft
+ WHERE t.id = ?')
+ USING vFather;
+
+ SELECT wdt, frg, flf
+ INTO vWidth, vFatherRight, vFatherLeft
+ FROM tAux;
+
+ -- 1º Incrementamos los valores de todos los nodos a la derecha
+ -- del punto de inserción (vFatherRight) , para hacer sitio
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET rgt = rgt + ?
+ WHERE rgt >= ?
+ ORDER BY rgt DESC')
+ USING vWidth,
+ vFatherRight;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET lft = lft + ?
+ WHERE lft >= ?
+ ORDER BY lft DESC')
+ USING vWidth,
+ vFatherRight;
+
+ -- Es preciso recalcular los valores del nodo en el
+ -- caso de que estuviera a la derecha del nuevo padre
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE tAux a
+ JOIN ', vTable, ' t
+ SET a.rgt = t.rgt,
+ a.lft = t.lft
+ WHERE t.id = ?')
+ USING vSelf;
+
+ SELECT lft, rgt, frg - lft
+ INTO vLeft, vRight, vGap
+ FROM tAux;
+
+ -- 2º Incrementamos el valor de todos los nodos a
+ -- trasladar hasta alcanzar su nueva posicion
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET lft = lft + ?
+ WHERE lft BETWEEN ? AND ?
+ ORDER BY lft DESC')
+ USING vGap,
+ vLeft,
+ vRight;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET rgt = rgt + ?
+ WHERE rgt BETWEEN ? AND ?
+ ORDER BY rgt DESC')
+ USING vGap,
+ vLeft,
+ vRight;
+
+ -- 3º Restaremos a todos los nodos resultantes, a la derecha
+ -- de la posicion arrancada el ancho de la rama escindida
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET lft = lft - ?
+ WHERE lft > ?
+ ORDER BY lft')
+ USING vWidth,
+ vLeft;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'UPDATE ', vTable,
+ 'SET rgt = rgt - ?
+ WHERE rgt > ?
+ ORDER BY rgt')
+ USING vWidth,
+ vRight;
+
+ DROP TEMPORARY TABLE tAux;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/bankEntity_checkBic.sql b/db/routines/vn/procedures/bankEntity_checkBic.sql
new file mode 100644
index 000000000..2f05ae654
--- /dev/null
+++ b/db/routines/vn/procedures/bankEntity_checkBic.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`bankEntity_checkBic`(vBic VARCHAR(255))
+BEGIN
+ /**
+ * If the bic length is Incorrect throw exception
+ *
+ * @param vBic bic code
+ */
+
+ DECLARE vConfigBicLenght INT;
+
+ SELECT bicLength INTO vConfigBicLenght
+ FROM vn.bankEntityConfig bec;
+
+ IF LENGTH(vBic) <> vConfigBicLenght THEN
+ CALL util.throw(CONCAT('bic must be of length ', vConfigBicLenght ));
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/bankPolicy_notifyExpired.sql b/db/routines/vn/procedures/bankPolicy_notifyExpired.sql
new file mode 100644
index 000000000..61216938d
--- /dev/null
+++ b/db/routines/vn/procedures/bankPolicy_notifyExpired.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`bankPolicy_notifyExpired`()
+BEGIN
+/**
+*
+* Manda correo cuando caduca un seguro
+* de los leasing
+*
+*/
+ INSERT INTO mail (receiver,replyTo,subject,body)
+ SELECT 'administracion@verdnatura.es' receiver,
+ 'noreply@verdnatura.es' replyTo,
+ CONCAT('El seguro de la poliza ',a.id,' ',a.bank,' ha finalizado.') subject,
+ CONCAT('El seguro de la poliza ',a.id,' ',a.bank,' ha finalizado.') body
+ FROM bankPolicy bp
+ LEFT JOIN supplier s ON s.id = bp.supplierFk
+ LEFT JOIN accounting a ON a.id = bp.accountingFk
+ WHERE bp.insuranceExpired = util.VN_CURDATE();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buyUltimate.sql b/db/routines/vn/procedures/buyUltimate.sql
new file mode 100644
index 000000000..4346ef640
--- /dev/null
+++ b/db/routines/vn/procedures/buyUltimate.sql
@@ -0,0 +1,39 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`(vWarehouseFk SMALLINT, vDated DATE)
+BEGIN
+/**
+ * Calcula las últimas compras realizadas hasta una fecha
+ *
+ * @param vWarehouseFk Id del almacén
+ * @param vDated Compras hasta fecha
+ * @return tmp.buyUltimate
+ */
+ CALL cache.last_buy_refresh (FALSE);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
+ CREATE TEMPORARY TABLE tmp.buyUltimate
+ (PRIMARY KEY (itemFk, warehouseFk),
+ INDEX(itemFk))
+ ENGINE = MEMORY
+ SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing
+ FROM cache.last_buy
+ WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL;
+
+ CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated);
+
+ REPLACE INTO tmp.buyUltimate
+ SELECT itemFk, buyFk, warehouseFk, landed landing
+ FROM tmp.buyUltimateFromInterval
+ WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
+ AND landed <= vDated
+ AND NOT isIgnored;
+
+ INSERT IGNORE INTO tmp.buyUltimate
+ SELECT itemFk, buyFk, warehouseFk, landed landing
+ FROM tmp.buyUltimateFromInterval
+ WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
+ AND landed > vDated
+ ORDER BY isIgnored = FALSE DESC;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buyUltimateFromInterval.sql b/db/routines/vn/procedures/buyUltimateFromInterval.sql
new file mode 100644
index 000000000..e264b500d
--- /dev/null
+++ b/db/routines/vn/procedures/buyUltimateFromInterval.sql
@@ -0,0 +1,137 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInterval`(vWarehouseFk SMALLINT, vStarted DATE, vEnded DATE)
+BEGIN
+/**
+ * Calcula las últimas compras realizadas
+ * desde un rango de fechas.
+ *
+ * @param vWarehouseFk Id del almacén si es NULL se actualizan todos
+ * @param vStarted Fecha inicial
+ * @param vEnded Fecha fin
+ * @return tmp.buyUltimateFromInterval
+ */
+ IF vEnded IS NULL THEN
+ SET vEnded = vStarted;
+ END IF;
+
+ IF vEnded < vStarted THEN
+ SET vStarted = TIMESTAMPADD(MONTH, -1, vEnded);
+ END IF;
+
+ -- Item
+ DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval;
+ CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval
+ (PRIMARY KEY (itemFk, warehouseFk), INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ MAX(landed) landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND b.price2 > 0
+ ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT
+ b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed > vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND b.price2 > 0
+ AND NOT b.isIgnored
+ GROUP BY itemFk, warehouseInFk;
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT
+ b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND b.quantity = 0
+ GROUP BY itemFk, warehouseInFk;
+
+ -- ItemOriginal
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ MAX(landed) landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ itemOriginalFk,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND b.price2 > 0
+ AND NOT b.isIgnored
+ AND b.quantity > 0
+ AND itemOriginalFk
+ ORDER BY t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemOriginalFk, warehouseFk;
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT
+ b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed > vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND b.price2 > 0
+ AND NOT b.isIgnored
+ AND itemOriginalFk
+ GROUP BY itemOriginalFk, warehouseInFk;
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT
+ b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND b.quantity = 0
+ AND itemOriginalFk
+ GROUP BY itemOriginalFk, warehouseInFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_afterUpsert.sql b/db/routines/vn/procedures/buy_afterUpsert.sql
new file mode 100644
index 000000000..17e84177c
--- /dev/null
+++ b/db/routines/vn/procedures/buy_afterUpsert.sql
@@ -0,0 +1,81 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_afterUpsert`(vSelf INT)
+BEGIN
+/**
+ * Triggered actions when a buy is updated or inserted.
+ *
+ * @param vSelf The buy reference
+ */
+ DECLARE vEntryFk INT;
+ DECLARE vItemFk INT;
+ DECLARE vPackingOut DECIMAL(10,2);
+ DECLARE vWarehouse INT;
+ DECLARE vStandardFlowerBox INT;
+ DECLARE vWarehouseOut INT;
+ DECLARE vIsMerchandise BOOL;
+ DECLARE vIsFeedStock BOOL;
+ DECLARE vWeight DECIMAL(10,2);
+ DECLARE vPacking INT;
+
+ SELECT b.entryFk,
+ b.itemFk,
+ i.packingOut,
+ ic.merchandise,
+ vc.standardFlowerBox,
+ b.weight,
+ b.packing
+ INTO
+ vEntryFk,
+ vItemFk,
+ vPackingOut,
+ vIsMerchandise,
+ vStandardFlowerBox,
+ vWeight,
+ vPacking
+ FROM buy b
+ LEFT JOIN item i ON i.id = b.itemFk
+ LEFT JOIN itemType it ON it.id = i.typeFk
+ LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN packaging p ON p.id = b.packagingFk AND NOT p.isBox
+ JOIN volumeConfig vc ON TRUE
+ WHERE b.id = vSelf;
+
+ SELECT t.warehouseInFk, t.warehouseOutFk
+ INTO vWarehouse, vWarehouseOut
+ FROM entry e
+ JOIN travel t ON t.id = e.travelFk
+ WHERE e.id = vEntryFk;
+
+ IF vIsMerchandise THEN
+
+ REPLACE itemCost SET
+ itemFk = vItemFk,
+ warehouseFk = vWarehouse,
+ cm3 = buy_getUnitVolume(vSelf),
+ cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf));
+
+ IF vWeight AND vPacking THEN
+ UPDATE itemCost SET
+ grams = vWeight * 1000 / vPacking
+ WHERE itemFk = vItemFk
+ AND warehouseFk = vWarehouse;
+ END IF;
+ END IF;
+
+ SELECT isFeedStock INTO vIsFeedStock
+ FROM warehouse WHERE id = vWarehouseOut;
+
+ IF vIsFeedStock THEN
+ INSERT IGNORE INTO producer(`name`)
+ SELECT es.company_name
+ FROM buy b
+ JOIN edi.ekt be ON be.id = b.ektFk
+ JOIN edi.supplier es ON es.supplier_id = be.pro
+ WHERE b.id = vSelf;
+
+ END IF;
+ CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck
+ SELECT vSelf id;
+ CALL buy_checkItem();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_checkGrouping.sql b/db/routines/vn/procedures/buy_checkGrouping.sql
new file mode 100644
index 000000000..11c727fb1
--- /dev/null
+++ b/db/routines/vn/procedures/buy_checkGrouping.sql
@@ -0,0 +1,14 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_checkGrouping`(vGrouping INT)
+BEGIN
+/**
+ * Checks the buy grouping, throws an error if it's invalid.
+ *
+ * @param vGrouping The grouping
+ */
+ IF vGrouping = 0 THEN
+ SIGNAL SQLSTATE '45000'
+ SET MESSAGE_TEXT = 'Grouping cannot be zero';
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_chekItem.sql b/db/routines/vn/procedures/buy_chekItem.sql
new file mode 100644
index 000000000..0a0f00345
--- /dev/null
+++ b/db/routines/vn/procedures/buy_chekItem.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_checkItem`()
+BEGIN
+/**
+ * Checks if the item has weightByPiece or size null on any buy.
+ *
+ * @param tmp.buysToCheck(id as INT).
+ */
+ DECLARE hasVolumetricAgency INT;
+
+ SELECT a.hasWeightVolumetric INTO hasVolumetricAgency
+ FROM entry e
+ JOIN travel t ON t.id = e.travelFk
+ JOIN agencyMode a ON a.id = t.agencyModeFk
+ JOIN buy b ON b.entryFk = e.id
+ JOIN item i ON i.id = b.itemFk
+ JOIN tmp.buysToCheck bt ON bt.id = b.id
+ WHERE (i.weightByPiece IS NULL OR i.`size` IS NULL)
+ AND a.hasWeightVolumetric
+ LIMIT 1;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.buysToCheck;
+
+ IF hasVolumetricAgency THEN
+ CALL util.throw('Some purchase line has an item without size or weight per stem in the volumetric agency.');
+ END IF;
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/buy_getSplit.sql b/db/routines/vn/procedures/buy_getSplit.sql
new file mode 100644
index 000000000..73cc1dda7
--- /dev/null
+++ b/db/routines/vn/procedures/buy_getSplit.sql
@@ -0,0 +1,128 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getSplit`(vSelf INT, vDated DATE)
+BEGIN
+/**
+ * Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de
+ * las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen
+ * habilitada la venta de productos con stock virtual, aunque los productos pueden ser de cualquier tipo.
+ *
+ * @param vSelf Identificador de vn.buy
+ * @param vDated Fecha de preparación de las ventas que queremos etiquetar
+ */
+ DECLARE vItemFk INT;
+ DECLARE vPacking INT;
+ DECLARE vRemaining INT;
+ DECLARE vLabels INT;
+ DECLARE vSaleFk INT;
+ DECLARE vAmount INT;
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vCounter INT DEFAULT 1;
+
+ DECLARE cur CURSOR FOR
+ SELECT s.id, s.quantity - IFNULL(l.stem, 0)
+ FROM vn.sale s
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.warehouse w ON w.id = t.warehouseFk
+ LEFT JOIN vn.saleLabel l ON l.saleFk = s.id
+ WHERE s.itemFk = vItemFk
+ AND t.shipped >= vDated
+ AND w.isLogiflora
+ AND IFNULL(l.stem, 0) < s.quantity
+ ORDER BY s.quantity = vRemaining DESC
+ LOCK IN SHARE MODE;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ -- Obtiene los datos de la compra
+
+ SELECT itemFk, packing, quantity
+ INTO vItemFk, vPacking, vRemaining
+ FROM vn.buy WHERE id = vSelf;
+
+ -- Crea splits de los tickets
+ CREATE OR REPLACE TEMPORARY TABLE tmp.split
+ (
+ id INT,
+ labels INT DEFAULT 0,
+ counter INT DEFAULT 0
+ )
+ ENGINE = MEMORY;
+
+ OPEN cur;
+
+ l: LOOP
+ SET vDone = FALSE;
+
+ FETCH cur INTO vSaleFk, vAmount;
+
+ IF vDone OR vRemaining = 0 THEN
+ LEAVE l;
+ END IF;
+
+ SET vAmount = LEAST(vAmount, vRemaining);
+
+ SET vRemaining = vRemaining - vAmount;
+
+ SET vLabels = vAmount DIV vPacking;
+
+ -- Se inserta una linea por cada etiqueta
+ SET vCounter = 1;
+
+ WHILE vLabels >= vCounter DO
+ INSERT INTO tmp.split
+ SET
+ id = vSaleFk,
+ labels = vLabels,
+ counter = vCounter;
+
+ SET vCounter = vCounter + 1;
+ END WHILE;
+
+ INSERT INTO vn.saleLabel
+ SET
+ saleFk = vSaleFk,
+ stem = vAmount,
+ label = vLabels
+ ON DUPLICATE KEY UPDATE
+ stem = stem + VALUES(stem),
+ label = label + VALUES(label);
+ END LOOP;
+
+ CLOSE cur;
+
+ -- Devuelve los splits creados
+ SELECT CONCAT(sp.counter,'/',sp.labels) labels,
+ COALESCE(sfc.nickname, sfa.nickname, a.nickname) destination,
+ s.itemFk,
+ i.longName,
+ i.`size`,
+ vn.ticketSplitCounter(t.id) counter,
+ IF(sfa.id OR sfc.id,
+ a.nickname,
+ CONCAT(a.id, ' ', p.`name`,' (', c.`code`,')')) destination2
+ FROM tmp.split sp
+ JOIN vn.sale s ON sp.id = s.id
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.address a ON a.id = t.addressFk
+ JOIN vn.province p ON p.id = a.provinceFk
+ JOIN vn.country c ON c.id = p.countryFk
+ LEFT JOIN vn.splitFilter sfa ON sfa.autonomyFk = p.autonomyFk
+ LEFT JOIN vn.splitFilter sfc ON sfc.clientFk = t.clientFk;
+
+ -- Limpia y confirma cambios
+ DROP TEMPORARY TABLE
+ tmp.split;
+
+ COMMIT;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_getVolume.sql b/db/routines/vn/procedures/buy_getVolume.sql
new file mode 100644
index 000000000..633be7ec0
--- /dev/null
+++ b/db/routines/vn/procedures/buy_getVolume.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getVolume`()
+BEGIN
+/**
+ * Cálculo de volumen en líneas de compra
+ * @table tmp.buy(buyFk)
+ */
+ SELECT t.name Temp,
+ CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
+ item_getVolume(b.itemFk, b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros ,
+ CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
+ item_getVolume(b.itemFk, b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais
+ FROM buy b
+ JOIN tmp.buy tb ON tb.buyFk = b.id
+ JOIN volumeConfig vc
+ JOIN item i ON i.id = b.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ LEFT JOIN temperature t ON t.code = it.temperatureFk
+ GROUP BY Temp;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_getVolumeByAgency.sql b/db/routines/vn/procedures/buy_getVolumeByAgency.sql
new file mode 100644
index 000000000..2f63c2bdf
--- /dev/null
+++ b/db/routines/vn/procedures/buy_getVolumeByAgency.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT)
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.buy;
+ CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
+
+ INSERT INTO tmp.buy
+ SELECT b.id
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed = vDated
+ AND t.agencyModeFk IN (0, vAgencyFk);
+
+ CALL buy_getVolume();
+ DROP TEMPORARY TABLE tmp.buy;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_getVolumeByEntry.sql b/db/routines/vn/procedures/buy_getVolumeByEntry.sql
new file mode 100644
index 000000000..e9a2bca2e
--- /dev/null
+++ b/db/routines/vn/procedures/buy_getVolumeByEntry.sql
@@ -0,0 +1,18 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getVolumeByEntry`(vEntryFk INT)
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.buy;
+ CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
+
+ INSERT INTO tmp.buy
+ SELECT b.id
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ WHERE e.id = vEntryFk;
+
+ CALL buy_getVolume();
+ DROP TEMPORARY TABLE tmp.buy;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_recalcPrices.sql b/db/routines/vn/procedures/buy_recalcPrices.sql
new file mode 100644
index 000000000..35eb00cf1
--- /dev/null
+++ b/db/routines/vn/procedures/buy_recalcPrices.sql
@@ -0,0 +1,52 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_recalcPrices`()
+BEGIN
+/**
+ * Recalcula los precios para las compras insertadas en tmp.buyRecalc
+ *
+ * @param tmp.buyRecalc (id)
+ */
+ DECLARE vLanded DATE;
+ DECLARE vWarehouseFk INT;
+ DECLARE vHasNotPrice BOOL;
+ DECLARE vBuyingValue DECIMAL(10,4);
+ DECLARE vPackagingFk VARCHAR(10);
+ DECLARE vIsWarehouseFloramondo BOOL;
+
+ SELECT t.landed, t.warehouseInFk, (w.`name` = 'Floramondo')
+ INTO vLanded, vWarehouseFk, vIsWarehouseFloramondo
+ FROM tmp.buyRecalc br
+ JOIN buy b ON b.id = br.id
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ LIMIT 1;
+
+ CALL rate_getPrices(vLanded, vWarehouseFk);
+
+ UPDATE buy b
+ JOIN tmp.buyRecalc br ON br.id = b.id AND (@buyId := b.id)
+ LEFT JOIN packaging p ON p.id = b.packagingFk
+ JOIN item i ON i.id = b.itemFk
+ JOIN entry e ON e.id = b.entryFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN agencyMode am ON am.id = tr.agencyModeFk
+ JOIN tmp.rate r
+ JOIN volumeConfig vc
+ SET b.freightValue = @PF:= IFNULL(((am.m3 * @m3:= item_getVolume(b.itemFk, b.packagingFk) / 1000000)
+ / b.packing) * IF(am.hasWeightVolumetric, GREATEST(b.weight / @m3 / vc.aerealVolumetricDensity, 1), 1), 0),
+ b.comissionValue = @CF:= ROUND(IFNULL(e.commission * b.buyingValue / 100, 0), 3),
+ b.packageValue = @EF:= IF(vIsWarehouseFloramondo, 0, IFNULL(ROUND(IF(p.isPackageReturnable, p.returnCost / b.packing , p.`value` / b.packing), 3),0)),
+ b.price3 = @t3:= IF(r.rate3 = 0, b.buyingValue,ROUND((b.buyingValue + @CF + @EF + @PF) / ((100 - r.rate3 - it.promo ) /100) ,2)), -- He añadido que el coste sea igual a tarifa3 si t3 = 0
+ b.price2 = @t2:= round(@t3 * (1 + ((r.rate2 - r.rate3)/100)),2),
+ b.price2 = @t2:= IF(@t2 <= @t3,@t3 , @t2);
+
+ SELECT (b.buyingValue = b.price2), b.buyingValue, b.packagingFk
+ INTO vHasNotPrice, vBuyingValue, vPackagingFk
+ FROM vn.buy b
+ WHERE b.id = @buyId AND b.buyingValue <> 0.01;
+
+ DROP TEMPORARY TABLE tmp.rate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_recalcPricesByAwb.sql b/db/routines/vn/procedures/buy_recalcPricesByAwb.sql
new file mode 100644
index 000000000..6f6baf305
--- /dev/null
+++ b/db/routines/vn/procedures/buy_recalcPricesByAwb.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_recalcPricesByAwb`(IN awbFk varchar(18))
+BEGIN
+/**
+ * inserta en tmp.buyRecalc las compras de un awb
+ *
+ * @param awbFk
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
+
+ CREATE TEMPORARY TABLE tmp.buyRecalc
+ SELECT b.id
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN awb a ON a.id = t.awbFk
+ WHERE a.code = awbFk;
+
+ CALL buy_recalcPrices();
+
+ DROP TEMPORARY TABLE tmp.buyRecalc;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_recalcPricesByBuy.sql b/db/routines/vn/procedures/buy_recalcPricesByBuy.sql
new file mode 100644
index 000000000..b963bae14
--- /dev/null
+++ b/db/routines/vn/procedures/buy_recalcPricesByBuy.sql
@@ -0,0 +1,18 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_recalcPricesByBuy`(IN vBuyFk INT(11))
+BEGIN
+/**
+ * Recalcula los precios de una compra
+ *
+ * @param vBuyFk
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
+
+ CREATE TEMPORARY TABLE tmp.buyRecalc
+ SELECT vBuyFk id;
+
+ CALL buy_recalcPrices();
+
+ DROP TEMPORARY TABLE tmp.buyRecalc;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_recalcPricesByEntry.sql b/db/routines/vn/procedures/buy_recalcPricesByEntry.sql
new file mode 100644
index 000000000..db0fc0690
--- /dev/null
+++ b/db/routines/vn/procedures/buy_recalcPricesByEntry.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_recalcPricesByEntry`(IN vEntryFk INT(11))
+BEGIN
+/**
+ * Recalcula los precios de una entrada
+ *
+ * @param vEntryFk
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
+
+ CREATE TEMPORARY TABLE tmp.buyRecalc
+ SELECT b.id
+ FROM buy b
+ WHERE b.entryFk = vEntryFk;
+
+ CALL buy_recalcPrices();
+
+ DROP TEMPORARY TABLE tmp.buyRecalc;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_scan.sql b/db/routines/vn/procedures/buy_scan.sql
new file mode 100644
index 000000000..0d4e8fcdb
--- /dev/null
+++ b/db/routines/vn/procedures/buy_scan.sql
@@ -0,0 +1,39 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_scan`(vBarcode VARCHAR(512))
+BEGIN
+/**
+ * Busca compras a partir de un código de barras de subasta, las marca como
+ * escaneadas y como etiquetas impresas y las devuelve.
+ *
+ * @param vBarcode Código de compra de una etiqueta de subasta
+ * @select (buy, do_photo) Identificadores de compra escaneados
+ */
+ CALL edi.ekt_scan(vBarcode);
+
+ DROP TEMPORARY TABLE IF EXISTS tBuy;
+ CREATE TEMPORARY TABLE tBuy
+ SELECT id buyFk
+ FROM vn.buy b
+ LIMIT 0;
+
+ INSERT INTO tBuy(buyFk)
+ SELECT b.id
+ FROM buy b
+ JOIN tmp.ekt t ON t.ektFk = b.ektFk
+ JOIN vn.entry en ON en.id = b.entryFk
+ JOIN vn.travel tr ON tr.id = en.travelFk
+ JOIN vn.warehouse w ON w.id = tr.warehouseInFk
+ JOIN vn.country c ON c.id = w.countryFk AND c.code = 'NL';
+
+ SELECT b.id buy, i.doPhoto do_photo, b.stickers - CAST(b.printedStickers AS INT) stickersToPrint
+ FROM tBuy tb
+ JOIN vn.buy b ON tb.buyFk = b.id
+ JOIN vn.item i ON i.id = b.itemFk;
+
+ UPDATE vn.buy b
+ JOIN tBuy tb ON tb.buyFk = b.id
+ SET b.printedStickers = b.stickers;
+
+ DROP TEMPORARY TABLE tmp.ekt, tBuy;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_updateGrouping.sql b/db/routines/vn/procedures/buy_updateGrouping.sql
new file mode 100644
index 000000000..fb7adc0a3
--- /dev/null
+++ b/db/routines/vn/procedures/buy_updateGrouping.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_updateGrouping`(vWarehouseFk INT, vItemFk INT, vGrouping INT)
+BEGIN
+/**
+ * Actualiza el grouping de las últimas compras de un artículo
+ *
+ * @param vWarehouseFk Id del almacén
+ * @param vItemFk Id del Artículo
+ * @param vGrouping Cantidad de grouping
+ */
+ CALL vn.buyUltimate(vWarehouseFk, util.VN_CURDATE());
+
+ UPDATE vn.buy b
+ JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
+ SET b.`grouping` = vGrouping
+ WHERE bu.warehouseFk = vWarehouseFk
+ AND bu.itemFk = vItemFk;
+
+ DROP TEMPORARY TABLE tmp.buyUltimate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_updatePacking.sql b/db/routines/vn/procedures/buy_updatePacking.sql
new file mode 100644
index 000000000..d86edc98f
--- /dev/null
+++ b/db/routines/vn/procedures/buy_updatePacking.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_updatePacking`(vWarehouseFk INT, vItemFk INT, vPacking INT)
+BEGIN
+/**
+ * Actualiza packing
+ *
+ * @param vWarehouseFk warehouse del item
+ * @param vItemFk id del item
+ * @param vPacking packing a actualizar
+ */
+ CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
+
+ UPDATE buy b
+ JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
+ SET b.packing = vPacking
+ WHERE bu.warehouseFk = vWarehouseFk
+ AND bu.itemFk = vItemFk;
+
+ DROP TEMPORARY TABLE tmp.buyUltimate;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/catalog_calcFromItem.sql b/db/routines/vn/procedures/catalog_calcFromItem.sql
new file mode 100644
index 000000000..497fd107c
--- /dev/null
+++ b/db/routines/vn/procedures/catalog_calcFromItem.sql
@@ -0,0 +1,26 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`catalog_calcFromItem`(
+ vLanded DATE,
+ vAddressFk INT,
+ vAgencyModeFk INT,
+ vItemFk INT)
+BEGIN
+/**
+ * Calculates available and price for a single item.
+ *
+ * @param vItemFk The item id
+ * @return tmp.ticketCalculateItem
+ * @return tmp.ticketComponentPrice
+ * @return tmp.ticketComponent
+ * @return tmp.ticketLot
+ * @return tmp.zoneGetShipped
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.item;
+ CREATE TEMPORARY TABLE tmp.item
+ ENGINE = MEMORY
+ SELECT vItemFk itemFk;
+
+ CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk, TRUE);
+ DROP TEMPORARY TABLE tmp.item;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/catalog_calculate.sql b/db/routines/vn/procedures/catalog_calculate.sql
new file mode 100644
index 000000000..bb52020df
--- /dev/null
+++ b/db/routines/vn/procedures/catalog_calculate.sql
@@ -0,0 +1,190 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`catalog_calculate`(
+ vLanded DATE,
+ vAddressFk INT,
+ vAgencyModeFk INT,
+ vShowExpiredZones BOOLEAN)
+BEGIN
+/**
+ * Calcula los articulos disponibles y sus precios
+ *
+ * @table tmp.item(itemFk) Listado de artículos a calcular
+ * @param vLanded Fecha de recepcion de mercancia
+ * @param vAddressFk Id del consignatario
+ * @param vAgencyModeFk Id de la agencia
+ * @return tmp.ticketCalculateItem(itemFk, available, producer,
+ * item, size, stems, category, inkFk, image, origin, price)
+ * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk)
+ * @return tmp.ticketComponent
+ * @return tmp.ticketComponentPrice
+ */
+ DECLARE vAvailableCalc INT;
+ DECLARE vAvailableNoRaidsCalc INT;
+ DECLARE vShipped DATE;
+ DECLARE vWarehouseFk SMALLINT;
+ DECLARE vZoneFk INT;
+ DECLARE vDone BOOL;
+ DECLARE cTravelTree CURSOR FOR
+ SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, vShowExpiredZones);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
+ CREATE TEMPORARY TABLE tmp.ticketLot(
+ `warehouseFk` smallint(5) unsigned NOT NULL,
+ `itemFk` int(11) NOT NULL,
+ `available` double DEFAULT NULL,
+ `buyFk` int(11) DEFAULT NULL,
+ `fix` tinyint(3) unsigned DEFAULT '0', -- este campo parece obsoleto
+ `zoneFk` int(11) NOT NULL,
+ KEY `itemFk` (`itemFk`),
+ KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH
+ ) ENGINE=MEMORY DEFAULT CHARSET=utf8;
+
+ CALL catalog_componentPrepare();
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
+ CREATE TEMPORARY TABLE tmp.ticketCalculateItem(
+ itemFk INT(11) NOT NULL,
+ available INT(11),
+ producer VARCHAR(50),
+ item VARCHAR(50),
+ size INT(10) UNSIGNED,
+ stems INT(11),
+ category VARCHAR(3),
+ inkFk VARCHAR(3),
+ image VARCHAR(50),
+ origin VARCHAR(3),
+ price DECIMAL(10,2),
+ priceKg DECIMAL(10,2),
+ `grouping` INT(10) UNSIGNED,
+ PRIMARY KEY `itemFk` (`itemFk`)
+ ) ENGINE = MEMORY DEFAULT CHARSET=utf8;
+
+ OPEN cTravelTree;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped);
+ CALL `cache`.availableNoRaids_refresh (vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped);
+ CALL vn.buyUltimate(vWarehouseFk, vShipped);
+
+ INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk)
+ SELECT vWarehouseFk,
+ a.item_id,
+ IFNULL(a.available, 0),
+ bu.buyFk,
+ vZoneFk
+ FROM `cache`.available a
+ LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id
+ AND anr.calc_id = vAvailableNoRaidsCalc
+ JOIN tmp.item i ON i.itemFk = a.item_id
+ JOIN vn.item it ON it.id = i.itemFk
+ JOIN vn.`zone` z ON z.id = vZoneFk
+ LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id
+ LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk
+ LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
+ LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
+ LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed
+ FROM vn.addressFilter af
+ JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed
+ FROM vn.address ad
+ JOIN vn.province p ON p.id = ad.provinceFk
+ WHERE ad.id = vAddressFk
+ ) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk)
+ AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk)
+ AND sub2.isLogifloraAllowed <=> IFNULL(af.isLogifloraAllowed, sub2.isLogifloraAllowed)
+ WHERE vWarehouseFk = af.warehouseFk
+ AND (vShipped < af.beforeDated
+ OR ISNULL(af.beforeDated)
+ OR vShipped > af.afterDated
+ OR ISNULL(af.afterDated))
+ ) sub ON sub.isVNHSupplier = v.isVNHSupplier
+ AND (sub.isEarlyBird = mp.isEarlyBird OR ISNULL(sub.isEarlyBird))
+ JOIN vn.agencyMode am ON am.id = vAgencyModeFk
+ JOIN vn.agency ag ON ag.id = am.agencyFk
+ JOIN vn.itemType itt ON itt.id = it.typeFk
+ JOIN vn.itemCategory itc on itc.id = itt.categoryFk
+ JOIN vn.address ad ON ad.id = vAddressFk
+ LEFT JOIN vn.clientItemType cit
+ ON cit.clientFk = ad.clientFk
+ AND cit.itemTypeFk = itt.id
+ LEFT JOIN vn.zoneItemType zit
+ ON zit.zoneFk = vZoneFk
+ AND zit.itemTypeFk = itt.id
+ LEFT JOIN vn.agencyModeItemType ait
+ ON ait.agencyModeFk = vAgencyModeFk
+ AND ait.itemTypeFk = itt.id
+ WHERE a.calc_id = vAvailableCalc
+ AND a.available > 0
+ AND (sub.itemAllowed OR NOT it.isFloramondo OR anr.available > 0)
+ AND (ag.isAnyVolumeAllowed OR NOT itt.isUnconventionalSize)
+ AND (itc.isReclining OR it.`size` IS NULL OR it.`size` < z.itemMaxSize OR z.itemMaxSize IS NULL)
+ AND cit.id IS NULL
+ AND zit.id IS NULL
+ AND ait.id IS NULL;
+
+ DROP TEMPORARY TABLE tmp.buyUltimate;
+
+ CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
+
+ INSERT INTO tmp.ticketCalculateItem (
+ itemFk,
+ available,
+ producer,
+ item,
+ size,
+ stems,
+ category,
+ inkFk,
+ image,
+ origin,
+ price,
+ priceKg,
+ `grouping`)
+ SELECT
+ tl.itemFk,
+ SUM(tl.available) available,
+ p.name producer,
+ i.name item,
+ i.size size,
+ i.stems,
+ i.category,
+ i.inkFk,
+ i.image,
+ o.code origin,
+ bl.price,
+ bl.priceKg,
+ bl.`grouping`
+ FROM tmp.ticketLot tl
+ JOIN item i ON tl.itemFk = i.id
+ LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
+ JOIN origin o ON o.id = i.originFk
+ JOIN (
+ SELECT price, itemFk, priceKg, MIN(`grouping`) `grouping`
+ FROM (
+ SELECT price, itemFk, priceKg, `grouping`
+ FROM tmp.ticketComponentPrice
+ WHERE warehouseFk = vWarehouseFk
+ ORDER BY (rate = 2) DESC, price
+ LIMIT 10000000000000000000
+ ) sub
+ GROUP BY itemFk
+ ) bl ON bl.itemFk = tl.itemFk
+ WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk
+ GROUP BY tl.itemFk
+ ON DUPLICATE KEY UPDATE available = available + VALUES(available);
+
+ END LOOP;
+
+ CLOSE cTravelTree;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/catalog_componentCalculate.sql b/db/routines/vn/procedures/catalog_componentCalculate.sql
new file mode 100644
index 000000000..1af0ff9eb
--- /dev/null
+++ b/db/routines/vn/procedures/catalog_componentCalculate.sql
@@ -0,0 +1,307 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`catalog_componentCalculate`(
+ vZoneFk INT,
+ vAddressFk INT,
+ vShipped DATE,
+ vWarehouseFk INT
+)
+BEGIN
+/**
+ * Calcula los componentes de los articulos de tmp.ticketLot
+ *
+ * @param vZoneFk para calcular el transporte
+ * @param vAddressFk Consignatario
+ * @param vShipped dia de salida del pedido
+ * @param vWarehouseFk warehouse de salida del pedido
+ * @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk)
+ * @table tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
+ *
+ * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
+ */
+ DECLARE vClientFk INT;
+ DECLARE vVNHWarehouseFk INT DEFAULT 7;
+
+ SELECT clientFk INTO vClientFK
+ FROM address
+ WHERE id = vAddressFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSpecialPrice
+ (INDEX (itemFk))
+ ENGINE = MEMORY
+ SELECT * FROM (
+ SELECT *
+ FROM specialPrice
+ WHERE (clientFk = vClientFk OR clientFk IS NULL)
+ AND started <= vShipped
+ AND (ended >= vShipped OR ended IS NULL)
+ ORDER BY (clientFk = vClientFk) DESC, id DESC
+ LIMIT 10000000000000000000) t
+ GROUP BY itemFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate
+ (PRIMARY KEY (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT tl.itemFk,
+ tl.warehouseFk,
+ tl.available,
+ IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate2, b.price2)),IFNULL(pf.rate2, b.price2)) rate2,
+ IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate3, b.price3)),IFNULL(pf.rate3, b.price3)) rate3,
+ IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing,
+ IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
+ ABS(IFNULL(pf.box, b.groupingMode)) groupingMode,
+ tl.buyFk,
+ i.typeFk,
+ IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping
+ FROM tmp.ticketLot tl
+ JOIN buy b ON b.id = tl.buyFk
+ JOIN item i ON i.id = tl.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN tSpecialPrice sp ON sp.itemFk = i.id
+ LEFT JOIN (
+ SELECT * FROM (
+ SELECT pf.itemFk,
+ pf.`grouping`,
+ pf.packing,
+ pf.box,
+ pf.rate2,
+ pf.rate3,
+ zw.warehouseFk
+ FROM priceFixed pf
+ JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk
+ AND zw.warehouseFk IN (pf.warehouseFk,0)
+ WHERE vShipped BETWEEN pf.started AND pf.ended
+ ORDER BY pf.itemFk, pf.warehouseFk DESC
+ LIMIT 10000000000000000000
+ ) tpf
+ GROUP BY tpf.itemFk, tpf.warehouseFk
+ ) pf ON pf.itemFk = tl.itemFk
+ AND pf.warehouseFk = tl.warehouseFk
+ WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01
+ AND ic.merchandise
+ AND tl.zoneFk = vZoneFk
+ AND tl.warehouseFk = vWarehouseFk;
+
+ -- Coste
+ INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
+ SELECT tcc.warehouseFk,
+ tcc.itemFk,
+ c2.id,
+ b.buyingValue + b.freightValue + b.packageValue + b.comissionValue
+ FROM tmp.ticketComponentCalculate tcc
+ JOIN vn.component c2 ON c2.code = 'purchaseValue'
+ JOIN buy b ON b.id = tcc.buyFk;
+
+ -- Margen
+ INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
+ SELECT tcc.warehouseFk,
+ tcc.itemFk,
+ c2.id,
+ tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue
+ FROM tmp.ticketComponentCalculate tcc
+ JOIN vn.component c2 ON c2.code = 'margin'
+ JOIN buy b ON b.id = tcc.buyFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY
+ SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk
+ FROM tmp.ticketComponent tc
+ JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk
+ GROUP BY tc.itemFk, warehouseFk;
+
+ -- RECOBRO
+ INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
+ SELECT tcb.warehouseFk, tcb.itemFk, c2.id,
+ ROUND(tcb.base *
+ LEAST(
+ MAX(GREATEST(IFNULL(cr.priceIncreasing,0),
+ IFNULL(cr1.priceIncreasing,0),
+ IFNULL(cr2.priceIncreasing,0))
+ ),
+ cc.maxPriceIncreasingRatio),
+ 3)
+ FROM tmp.ticketComponentBase tcb
+ JOIN vn.component c2 ON c2.code = 'debtCollection'
+ JOIN vn.clientConfig cc
+ JOIN claimRatio cr ON cr.clientFk = vClientFk
+ LEFT JOIN clientYoke cy1 ON cy1.leftOx = cr.clientFk
+ LEFT JOIN claimRatio cr1 ON cr1.clientFk = cy1.rightOx
+ LEFT JOIN clientYoke cy2 ON cy2.rightOx = cr.clientFk
+ LEFT JOIN claimRatio cr2 ON cr2.clientFk = cy2.leftOx
+ WHERE GREATEST(
+ IFNULL(cr.priceIncreasing,0),
+ IFNULL(cr1.priceIncreasing,0),
+ IFNULL(cr2.priceIncreasing,0)) > 0.009
+ GROUP BY tcb.itemFk;
+
+ -- Mana auto
+ INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
+ SELECT tcb.warehouseFk,
+ tcb.itemFk,
+ c2.id,
+ ROUND(base * wm.pricesModifierRate, 3) manaAuto
+ FROM tmp.ticketComponentBase tcb
+ JOIN `client` c on c.id = vClientFk
+ JOIN workerMana wm ON c.salesPersonFk = wm.workerFk
+ JOIN vn.component c2 ON c2.code = 'autoMana'
+ WHERE wm.isPricesModifierActivated
+ HAVING manaAuto <> 0;
+
+ -- Precios especiales
+ INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
+ SELECT tcb.warehouseFk,
+ tcb.itemFk,
+ c2.id,
+ GREATEST(
+ IFNULL(ROUND(tcb.base * c2.tax, 4), 0),
+ IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3
+ ) cost
+ FROM tmp.ticketComponentBase tcb
+ JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount'
+ JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk
+ LEFT JOIN tSpecialPrice sp ON sp.itemFk = tcc.itemFk
+ JOIN vn.item i ON i.id = tcb.itemFk
+ WHERE sp.value IS NULL
+ AND i.supplyResponseFk IS NULL;
+
+ -- Individual
+ INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
+ SELECT tcb.warehouseFk,
+ tcb.itemFk,
+ c2.id,
+ IFNULL(ROUND(tcb.base * c2.tax, 4), 0) cost
+ FROM tmp.ticketComponentBase tcb
+ JOIN vn.component c2 ON c2.code = 'individual'
+ JOIN vn.client c ON c.id = vClientFk
+ JOIN vn.businessType bt ON bt.code = c.businessTypeFk
+ WHERE bt.code = 'individual';
+
+ -- Venta por paquetes
+ INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
+ SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3
+ FROM tmp.ticketComponentCalculate tcc
+ JOIN vn.component c2 ON c2.code = 'salePerPackage'
+ JOIN buy b ON b.id = tcc.buyFk
+ LEFT JOIN tSpecialPrice sp ON sp.itemFk = tcc.itemFk
+ WHERE sp.value IS NULL;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.`zone` (INDEX (id))
+ ENGINE = MEMORY
+ SELECT vZoneFk id;
+
+ CALL zone_getOptionsForShipment(vShipped, TRUE);
+
+ -- Reparto
+ INSERT INTO tmp.ticketComponent
+ SELECT tcc.warehouseFK,
+ tcc.itemFk,
+ c2.id,
+ z.inflation * ROUND(ic.cm3delivery * (IFNULL(zo.price,5000) - IFNULL(zo.bonus,0)) / (1000 * vc.standardFlowerBox) , 4) cost
+ FROM tmp.ticketComponentCalculate tcc
+ JOIN item i ON i.id = tcc.itemFk
+ JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk
+ JOIN zone z ON z.id = vZoneFk
+ JOIN agencyMode am ON am.id = z.agencyModeFk
+ JOIN vn.volumeConfig vc
+ JOIN vn.component c2 ON c2.code = 'delivery'
+ LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk
+ AND ic.itemFk = tcc.itemFk
+ HAVING cost <> 0;
+
+ DROP TEMPORARY TABLE tmp.zoneOption;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY
+ SELECT * FROM tmp.ticketComponent;
+
+ -- Precio especial
+ INSERT INTO tmp.ticketComponent
+ SELECT tcc.warehouseFk,
+ tcc.itemFk,
+ c2.id,
+ sp.value - SUM(tcc.cost) sumCost
+ FROM tmp.ticketComponentCopy tcc
+ JOIN component c ON c.id = tcc.componentFk
+ JOIN tSpecialPrice sp ON sp.itemFk = tcc.itemFk
+ JOIN vn.component c2 ON c2.code = 'specialPrices'
+ WHERE c.classRate IS NULL
+ AND tcc.warehouseFk = vWarehouseFk
+ GROUP BY tcc.itemFk, tcc.warehouseFk
+ HAVING ABS(sumCost) > 0.001;
+
+ -- Rappel
+ INSERT INTO tmp.ticketComponent
+ SELECT tcc.warehouseFk,
+ tcc.itemFk,
+ IFNULL(c.componentFk ,c2.id),
+ SUM(tcc.cost) * ((1/(1-c.rappel/100)) -1) sumCost
+ FROM tmp.ticketComponentCopy tcc
+ JOIN vn.clientChain cc ON cc.clientFk = vClientFk
+ JOIN vn.`chain` c ON c.id = cc.chainFk
+ JOIN vn.component c2 ON c2.code = 'rappel'
+ WHERE tcc.warehouseFk = vWarehouseFk
+ GROUP BY tcc.itemFk, tcc.warehouseFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentSum
+ (INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, c.classRate
+ FROM tmp.ticketComponent tc
+ JOIN component c ON c.id = tc.componentFk
+ GROUP BY tc.itemFk, tc.warehouseFk, c.classRate;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY
+ SELECT tcc.warehouseFk,
+ tcc.itemFk,
+ 1 rate,
+ IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`,
+ CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price,
+ CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg
+ FROM tmp.ticketComponentCalculate tcc
+ JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
+ AND tcs.warehouseFk = tcc.warehouseFk
+ WHERE IFNULL(tcs.classRate, 1) = 1
+ AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0)
+ GROUP BY tcs.warehouseFk, tcs.itemFk;
+
+ INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
+ SELECT tcc.warehouseFk,
+ tcc.itemFk,
+ 2 rate,
+ tcc.packing `grouping`,
+ SUM(tcs.sumCost) price,
+ SUM(tcs.sumCost) / weightGrouping priceKg
+ FROM tmp.ticketComponentCalculate tcc
+ JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
+ AND tcs.warehouseFk = tcc.warehouseFk
+ WHERE tcc.available IS NULL
+ OR (IFNULL(tcs.classRate, 2) = 2
+ AND tcc.packing > 0 AND tcc.available >= tcc.packing)
+ GROUP BY tcs.warehouseFk, tcs.itemFk;
+
+ INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
+ SELECT tcc.warehouseFk,
+ tcc.itemFk,
+ 3 rate,
+ tcc.available `grouping`,
+ SUM(tcs.sumCost) price,
+ SUM(tcs.sumCost) / weightGrouping priceKg
+ FROM tmp.ticketComponentCalculate tcc
+ JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
+ AND tcs.warehouseFk = tcc.warehouseFk
+ WHERE IFNULL(tcs.classRate, 3) = 3
+ GROUP BY tcs.warehouseFk, tcs.itemFk;
+
+ INSERT INTO tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
+ SELECT * FROM (
+ SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000
+ ) t
+ GROUP BY itemFk, warehouseFk, `grouping`;
+
+ DROP TEMPORARY TABLE
+ tmp.ticketComponentCalculate,
+ tmp.ticketComponentSum,
+ tmp.ticketComponentBase,
+ tmp.ticketComponentRate,
+ tmp.ticketComponentCopy,
+ tSpecialPrice;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/catalog_componentPrepare.sql b/db/routines/vn/procedures/catalog_componentPrepare.sql
new file mode 100644
index 000000000..2e58a28e2
--- /dev/null
+++ b/db/routines/vn/procedures/catalog_componentPrepare.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`catalog_componentPrepare`()
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
+ CREATE TEMPORARY TABLE tmp.ticketComponent (
+ `warehouseFk` INT UNSIGNED NOT NULL,
+ `itemFk` INT NOT NULL,
+ `componentFk` INT UNSIGNED NOT NULL,
+ `cost` DECIMAL(10,4) NOT NULL,
+ INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
+ UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)
+ )ENGINE=MEMORY DEFAULT CHARSET=utf8;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice;
+ CREATE TEMPORARY TABLE tmp.ticketComponentPrice (
+ `warehouseFk` INT UNSIGNED NOT NULL,
+ `itemFk` INT NOT NULL,
+ `rate` INT NOT NULL,
+ `grouping` INT UNSIGNED NOT NULL,
+ `price` DECIMAL(10,4) NOT NULL,
+ `priceKg` DECIMAL(10,4),
+ INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
+ UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC)
+ )ENGINE=MEMORY DEFAULT CHARSET=utf8;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/catalog_componentPurge.sql b/db/routines/vn/procedures/catalog_componentPurge.sql
new file mode 100644
index 000000000..c6a19ba62
--- /dev/null
+++ b/db/routines/vn/procedures/catalog_componentPurge.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`catalog_componentPurge`()
+BEGIN
+ DROP TEMPORARY TABLE
+ tmp.ticketComponentPrice,
+ tmp.ticketComponent,
+ tmp.ticketLot;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clean.sql b/db/routines/vn/procedures/clean.sql
new file mode 100644
index 000000000..ed1569935
--- /dev/null
+++ b/db/routines/vn/procedures/clean.sql
@@ -0,0 +1,226 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clean`()
+BEGIN
+/**
+ * Purges outdated data to optimize performance.
+ * Exercise caution when executing.
+ */
+ DECLARE v2Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 MONTH;
+ DECLARE v3Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 3 MONTH;
+ DECLARE v18Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 18 MONTH;
+ DECLARE v26Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 26 MONTH;
+ DECLARE v1Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 1 YEAR;
+ DECLARE v2Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR;
+ DECLARE v4Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 4 YEAR;
+ DECLARE v5Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 5 YEAR;
+ DECLARE vTrashId VARCHAR(15);
+ DECLARE vCompanyBlk INT;
+
+ DELETE FROM workerActivity WHERE created < v2Years;
+ DELETE FROM ticketParking WHERE created < v2Months;
+ DELETE FROM routesMonitor WHERE dated < v2Months;
+ DELETE FROM workerTimeControlLog WHERE created < v2Months;
+ DELETE FROM `message` WHERE sendDate < v2Months;
+ DELETE FROM messageInbox WHERE sendDate < v2Months;
+ DELETE FROM messageInbox WHERE sendDate < v2Months;
+ DELETE FROM workerTimeControl WHERE timed < v4Years;
+ DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0;
+ DELETE FROM ticketDown WHERE created < util.yesterday();
+ DELETE FROM entryLog WHERE creationDate < v2Months;
+ DELETE IGNORE FROM expedition WHERE created < v26Months;
+ DELETE FROM sms WHERE created < v18Months;
+ DELETE FROM saleTracking WHERE created < v1Years;
+ DELETE FROM productionError WHERE dated < v1Years;
+ DELETE FROM ticketTracking WHERE created < v18Months;
+ DELETE tobs FROM ticketObservation tobs
+ JOIN ticket t ON tobs.ticketFk = t.id
+ WHERE t.shipped < v5Years;
+ DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < v1Years;
+ DELETE FROM sharingCart where ended < v2Months;
+ DELETE FROM sharingClient where ended < v2Months;
+ DELETE tw.* FROM ticketWeekly tw
+ LEFT JOIN sale s ON s.ticketFk = tw.ticketFk
+ LEFT JOIN ticketRequest tr ON tr.ticketFk = tw.ticketFk
+ LEFT JOIN ticketService ts ON ts.ticketFk = tw.ticketFk
+ WHERE s.id IS NULL
+ AND tr.id IS NULL
+ AND ts.id IS NULL;
+ DELETE FROM claim WHERE ticketCreated < v4Years;
+ -- Robert ubicacion anterior de travelLog comentario para debug
+ DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Months;
+ DELETE bm
+ FROM buyMark bm
+ JOIN buy b ON b.id = bm.id
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed <= v2Months;
+ DELETE b FROM buy b
+ JOIN entryConfig e ON e.defaultEntry = b.entryFk
+ WHERE b.created < v2Months;
+ DELETE FROM itemShelvingLog WHERE created < v2Months;
+ DELETE FROM stockBuyed WHERE creationDate < v2Months;
+ DELETE FROM itemCleanLog WHERE created < util.VN_NOW() - INTERVAL 1 YEAR;
+ DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months;
+ DELETE FROM ticketLog WHERE creationDate <= v5Years;
+ -- Equipos duplicados
+ DELETE w.*
+ FROM workerTeam w
+ JOIN (
+ SELECT id, team, workerFk, COUNT(*) - 1 duplicated
+ FROM workerTeam
+ GROUP BY team,workerFk
+ HAVING duplicated
+ ) d ON d.team = w.team
+ AND d.workerFk = w.workerFk
+ AND d.id <> w.id;
+
+ DELETE sc
+ FROM saleComponent sc
+ JOIN sale s ON s.id= sc.saleFk
+ JOIN ticket t ON t.id= s.ticketFk
+ WHERE t.shipped < v18Months;
+
+ DELETE c
+ FROM claim c
+ JOIN claimState cs ON cs.id = c.claimStateFk
+ WHERE cs.description = 'Anulado'
+ AND c.created < v2Months;
+
+ DELETE FROM expeditionTruck WHERE eta < v3Months;
+ DELETE FROM XDiario WHERE FECHA < v3Months OR FECHA IS NULL;
+
+ -- Borrar travels sin entradas
+ CREATE OR REPLACE TEMPORARY TABLE tThermographToDelete
+ SELECT th.id,th.dmsFk
+ FROM travel t
+ LEFT JOIN entry e ON e.travelFk = t.id
+ JOIN travelThermograph th ON th.travelFk = t.id
+ WHERE t.shipped < v3Months
+ AND e.travelFk IS NULL;
+
+ SELECT dt.id INTO vTrashId
+ FROM dmsType dt
+ WHERE dt.code = 'trash';
+
+ UPDATE tThermographToDelete th
+ JOIN dms d ON d.id = th.dmsFk
+ SET d.dmsTypeFk = vTrashId;
+
+ DELETE th
+ FROM tThermographToDelete tmp
+ JOIN travelThermograph th ON th.id = tmp.id;
+
+ DELETE t
+ FROM travel t
+ LEFT JOIN entry e ON e.travelFk = t.id
+ WHERE t.shipped < v3Months AND e.travelFk IS NULL;
+
+ UPDATE dms d
+ JOIN dmsType dt ON dt.id = d.dmsTypeFk
+ SET d.dmsTypeFk = vTrashId
+ WHERE created < util.VN_CURDATE() - INTERVAL dt.monthToDelete MONTH;
+
+ -- borrar entradas sin compras
+ CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete
+ SELECT e.*
+ FROM entry e
+ LEFT JOIN buy b ON b.entryFk = e.id
+ JOIN entryConfig ec ON e.id <> ec.defaultEntry
+ WHERE e.dated < v3Months
+ AND b.entryFK IS NULL;
+
+ DELETE e
+ FROM entry e
+ JOIN tEntryToDelete tmp ON tmp.id = e.id;
+
+ -- borrar de route registros menores a 4 años
+ CREATE OR REPLACE TEMPORARY TABLE tRouteToDelete
+ SELECT *
+ FROM route r
+ WHERE created < v4Years;
+
+ UPDATE tRouteToDelete tmp
+ JOIN dms d ON d.id = tmp.gestdocFk
+ SET d.dmsTypeFk = vTrashId;
+
+ DELETE r
+ FROM tRouteToDelete tmp
+ JOIN route r ON r.id = tmp.id;
+
+ -- borrar registros de dua y awb menores a 2 años
+ CREATE OR REPLACE TEMPORARY TABLE tDuaToDelete
+ SELECT *
+ FROM dua
+ WHERE operated < v2Years;
+
+ UPDATE tDuaToDelete tm
+ JOIN dms d ON d.id = tm.gestdocFk
+ SET d.dmsTypeFk = vTrashId;
+
+ DELETE d
+ FROM tDuaToDelete tmp
+ JOIN dua d ON d.id = tmp.id;
+
+ DELETE a
+ FROM awb a
+ LEFT JOIN travel t ON t.awbFk = a.id
+ WHERE a.created < v2Years
+ AND t.id IS NULL;
+
+ -- Borra los registros de collection y ticketcollection
+ DELETE FROM collection WHERE created < v2Months;
+ DELETE FROM travelLog WHERE creationDate < v3Months;
+
+ CALL shelving_clean();
+
+ DELETE FROM chat WHERE dated < v5Years;
+ DELETE tt FROM ticketTracking tt
+ JOIN ticket t ON tt.ticketFk = t.id
+ WHERE t.shipped <= v2Months;
+
+ DELETE FROM mail WHERE creationDate < v2Months;
+ DELETE FROM split WHERE dated < v18Months;
+ DELETE FROM remittance WHERE dated < v18Months;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTicketDelete
+ SELECT DISTINCT tl.originFk ticketFk
+ FROM ticketLog tl
+ JOIN (
+ SELECT MAX(tl.id)ids
+ FROM ticket t
+ JOIN ticketLog tl ON tl.originFk = t.id
+ LEFT JOIN ticketWeekly tw ON tw.ticketFk = t.id
+ WHERE t.shipped BETWEEN '2000-01-01' AND '2000-12-31'
+ AND t.isDeleted
+ AND tw.ticketFk IS NULL
+ GROUP BY t.id
+ ) sub ON sub.ids = tl.id
+ WHERE tl.creationDate <= v2Months;
+ DELETE t
+ FROM ticket t
+ JOIN tTicketDelete tmp ON tmp.ticketFk = t.id;
+
+ DELETE sl
+ FROM saleLabel sl
+ JOIN sale s ON s.id = sl.saleFk
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE t.shipped < v2Months;
+
+ -- Tickets Nulos PAK 11/10/2016
+ SELECT id INTO vCompanyBlk FROM company WHERE code = 'BLK';
+ UPDATE ticket
+ SET companyFk = vCompanyBlk
+ WHERE clientFk = (SELECT id FROM client WHERE name = 'AUTOCONSUMO')
+ AND companyFk <> vCompanyBlk;
+
+ DROP TEMPORARY TABLE tTicketDelete,
+ tThermographToDelete,
+ tEntryToDelete,
+ tDuaToDelete,
+ tRouteToDelete;
+
+ -- Other schemas
+ DELETE FROM hedera.`order` WHERE date_send < v18Months;
+ DELETE FROM pbx.cdr WHERE call_date < v18Months;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clean_logiflora.sql b/db/routines/vn/procedures/clean_logiflora.sql
new file mode 100644
index 000000000..dd08410fd
--- /dev/null
+++ b/db/routines/vn/procedures/clean_logiflora.sql
@@ -0,0 +1,81 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clean_logiflora`()
+BEGIN
+/**
+ * Elimina las compras y los artículos residuales de logiflora.
+ */
+ DECLARE vDone INT DEFAULT FALSE;
+ DECLARE vBuyFk INT;
+ DECLARE vItemFk INT;
+
+ DECLARE cur1 CURSOR FOR SELECT id FROM tBuy;
+ DECLARE cur2 CURSOR FOR SELECT id FROM tItem;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ CREATE OR REPLACE TEMPORARY TABLE tBuy
+ ENGINE = MEMORY
+ SELECT b.id
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN agencyMode am ON am.id = tr.agencyModeFk
+ WHERE NOT b.quantity
+ AND am.code = 'logiflora'
+ AND e.isRaid;
+
+ START TRANSACTION;
+
+ OPEN cur1;
+ read_loop: LOOP
+ SET vDone = FALSE;
+ FETCH cur1 INTO vBuyFk;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ DELETE FROM buy WHERE id = vBuyFk;
+ END LOOP;
+ CLOSE cur1;
+
+ CREATE OR REPLACE TEMPORARY TABLE tItem
+ ENGINE = MEMORY
+ SELECT DISTINCT i.id
+ FROM item i
+ LEFT JOIN hedera.orderRow o ON o.itemFk = i.id
+ LEFT JOIN sale s ON s.itemFk = i.id
+ LEFT JOIN buy b ON b.itemFk = i.id
+ LEFT JOIN bs.waste w ON w.itemFk = i.id
+ WHERE i.supplyResponseFk
+ AND o.id IS NULL
+ AND b.id IS NULL
+ AND s.id IS NULL
+ AND w.itemFk IS NULL
+ AND i.created < (util.VN_CURDATE() - INTERVAL (SELECT daysToKeepItem FROM floramondoConfig) DAY);
+
+ OPEN cur2;
+ read_loop: LOOP
+ SET vDone = FALSE;
+
+ FETCH cur2 INTO vItemFk;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ DELETE FROM item WHERE id = vItemFk;
+ END LOOP;
+ CLOSE cur2;
+
+ COMMIT;
+
+ DROP TEMPORARY TABLE tBuy, tItem;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clearShelvingList.sql b/db/routines/vn/procedures/clearShelvingList.sql
new file mode 100644
index 000000000..dbaca2747
--- /dev/null
+++ b/db/routines/vn/procedures/clearShelvingList.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clearShelvingList`(vShelvingFk VARCHAR(8))
+BEGIN
+ UPDATE vn.itemShelving
+ SET visible = 0
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk COLLATE utf8_unicode_ci;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clientDebtSpray.sql b/db/routines/vn/procedures/clientDebtSpray.sql
new file mode 100644
index 000000000..687c08fe2
--- /dev/null
+++ b/db/routines/vn/procedures/clientDebtSpray.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientDebtSpray`(vClientFk INT)
+BEGIN
+
+ /* Reparte el saldo de un cliente en greuge en la cartera que corresponde, y desasigna el comercial
+ *
+ *
+ */
+
+ DECLARE vClientDebt DOUBLE;
+
+ SELECT vn.client_getDebt(vClientFk, util.VN_CURDATE()) INTO vClientDebt;
+
+ INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
+ VALUES (vClientFk, 'Saldo pendiente', vClientDebt, util.VN_CURDATE(), 5);
+
+ CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE);
+
+ INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
+ SELECT vClientFk, 'Liquidación cliente', sum(amount), util.VN_CURDATE(), 5
+ FROM vn.greuge
+ WHERE clientFk = vClientFk;
+
+ UPDATE vn.client
+ SET salesPersonFk = NULL
+ WHERE id = vClientFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clientFreeze.sql b/db/routines/vn/procedures/clientFreeze.sql
new file mode 100644
index 000000000..c89db2316
--- /dev/null
+++ b/db/routines/vn/procedures/clientFreeze.sql
@@ -0,0 +1,44 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientFreeze`()
+BEGIN
+/**
+ * Congela diariamente aquellos clientes que son morosos sin recobro,
+ * pero que no sean trabajadores,
+ * y que el riesgo no sea menor que cero
+ * hasta que no se gire la remesa no se congelan a los clientes de giro
+ */
+ DECLARE vIsRemittanced BOOLEAN;
+
+ SELECT id into vIsRemittanced
+ FROM receipt
+ WHERE invoiceFk LIKE 'REMESA%'
+ AND payed > util.firstDayOfMonth(util.VN_CURDATE())
+ LIMIT 1;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
+ CREATE TEMPORARY TABLE tmp.clientGetDebt
+ (INDEX (clientFk))
+ SELECT clientFk
+ FROM bs.defaulter
+ WHERE created = util.VN_CURDATE()
+ AND amount;
+
+ CALL client_getDebt(util.VN_CURDATE());
+
+ UPDATE client c
+ JOIN bi.defaulters d ON d.client = c.id AND d.date = util.VN_CURDATE()
+ JOIN config ON TRUE
+ LEFT JOIN recovery r ON r.clientFk = c.id AND r.finished IS NULL
+ LEFT JOIN payMethod pm ON pm.id = c.payMethodFk
+ LEFT JOIN tmp.risk rk ON rk.clientFk = c.id
+ SET c.isFreezed = TRUE,
+ d.frozened = util.VN_CURDATE()
+ WHERE (d.amount > config.defaultersMaxAmount
+ AND rk.risk > 0)
+ AND c.typeFk = 'normal'
+ AND r.id IS NULL
+ AND (vIsRemittanced OR pm.code <> 'bankDraft');
+
+ DROP TEMPORARY TABLE tmp.clientGetDebt;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clientGetDebtDiary.sql b/db/routines/vn/procedures/clientGetDebtDiary.sql
new file mode 100644
index 000000000..bd7a0b292
--- /dev/null
+++ b/db/routines/vn/procedures/clientGetDebtDiary.sql
@@ -0,0 +1,117 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientGetDebtDiary`(vClientFK INT, vCompanyFk INT)
+BEGIN
+/**
+ * Devuelve el registro de deuda
+ *
+ * @param vClientFK Id del cliente
+ * @param vCompanyFk Id de la empresa
+ */
+ DECLARE vDone BOOL;
+ DECLARE vDate DATETIME;
+ DECLARE vTotalBalance DOUBLE DEFAULT 0.00;
+ DECLARE vCreated DATETIME;
+ DECLARE vIssued DATETIME;
+ DECLARE vBalance DOUBLE DEFAULT 0.00;
+ DECLARE cur CURSOR FOR
+ SELECT
+ created,
+ issued,
+ ROUND(amount, 2) AS balance
+ FROM invoiceOut
+ WHERE clientFk = vClientFk AND companyFk = vCompanyFk
+ UNION ALL
+ SELECT
+ created,
+ payed,
+ ROUND(-1 * amountPaid, 2) AS balance
+ FROM receipt
+ WHERE clientFk = vClientFk AND companyFk = vCompanyFk
+ ORDER BY issued, created;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN cur;
+
+ proc: LOOP
+ SET vDone = FALSE;
+
+ FETCH cur INTO vCreated, vIssued, vBalance;
+
+ IF vDate IS NULL THEN
+ SET vDate=vIssued;
+ END IF;
+
+ IF vDone THEN
+ LEAVE proc;
+ END IF;
+
+ SET vTotalBalance = vTotalBalance + vBalance;
+
+ IF CAST(ABS(vTotalBalance) AS UNSIGNED) = 0 THEN
+ SET vDate = vIssued;
+ SET vDone = TRUE;
+ END IF;
+ END LOOP;
+
+ CLOSE cur;
+
+ SELECT
+ issued,
+ CAST(debtOut AS DECIMAL(10,2)) debtOut,
+ CAST(debtIn AS DECIMAL(10,2)) debtIn,
+ ref,
+ companyFk,
+ priority
+ FROM
+ (SELECT
+ NULL AS issued,
+ SUM(amountUnpaid) AS debtOut,
+ NULL AS debtIn,
+ 'Saldo Anterior' AS ref,
+ companyFk,
+ 0 as priority
+ FROM
+ (SELECT SUM(amount) AS amountUnpaid, companyFk, 0
+ FROM invoiceOut
+ WHERE clientFk = vClientFK
+ AND issued < vDate
+ GROUP BY companyFk
+
+ UNION ALL
+
+ SELECT SUM(-1 * amountPaid), companyFk, 0
+ FROM receipt
+ WHERE clientFk = vClientFK
+ AND payed < vDate
+ GROUP BY companyFk) AS transactions
+ GROUP BY companyFk
+
+ UNION ALL
+
+ SELECT
+ issued,
+ amount as debtOut,
+ NULL AS debtIn,
+ ref,
+ companyFk,
+ 1
+ FROM invoiceOut
+ WHERE clientFk = vClientFK
+ AND issued >= vDate
+ UNION ALL
+
+ SELECT
+ r.payed,
+ NULL as debtOut,
+ r.amountPaid,
+ r.invoiceFk,
+ r.companyFk,
+ 0
+ FROM receipt r
+ WHERE r.clientFk = vClientFK
+ AND r.payed >= vDate) t
+ INNER JOIN `client` c ON c.id = vClientFK
+ HAVING debtOut <> 0 OR debtIn <> 0
+ ORDER BY issued, priority DESC, debtIn;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clientGreugeSpray.sql b/db/routines/vn/procedures/clientGreugeSpray.sql
new file mode 100644
index 000000000..c337e2dd3
--- /dev/null
+++ b/db/routines/vn/procedures/clientGreugeSpray.sql
@@ -0,0 +1,73 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientGreugeSpray`(IN vClientFk INT, IN onlyForHisOwner BOOL, IN vWorkerCode VARCHAR(3), IN vWithMana BOOLEAN)
+BEGIN
+
+ DECLARE vGreuge DECIMAL(10,2);
+ DECLARE vOwner INT;
+ DECLARE vTotalSale INT;
+ DECLARE vGreugeTypeFk INT DEFAULT 5; -- HERENCIA
+ DECLARE vGreugeTypeMana INT DEFAULT 3;-- Maná
+ DECLARE vMana DECIMAL(10,2);
+
+ SELECT vn.clientGetMana(vClientFk) INTO vMana;
+
+ IF vWithMana AND vMana THEN
+
+ INSERT INTO vn.greuge( clientFk,
+ description,
+ amount,
+ shipped,
+ greugeTypeFk)
+ VALUES( vClientFk,
+ 'Desasignación',
+ -1 * vMana,
+ util.VN_CURDATE(),
+ vGreugeTypeMana);
+
+ END IF;
+
+ SELECT sum(amount) INTO vGreuge
+ FROM vn.greuge
+ WHERE clientFk = vClientFk;
+
+ IF vGreuge != 0 THEN
+
+ IF LENGTH(vWorkerCode) = 0 THEN
+
+ SELECT salesPersonFk INTO vOwner
+ FROM vn.client
+ WHERE id = vClientFk;
+
+ ELSE
+
+ SELECT id INTO vOwner
+ FROM vn.worker
+ WHERE code = vWorkerCode COLLATE utf8_general_ci;
+
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.clientList;
+ CREATE TEMPORARY TABLE tmp.clientList
+ SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) monthSale
+ FROM vn.ticket t
+ JOIN vn.client c ON c.id = t.clientFk
+ JOIN vn.workerMana wm ON wm.workerFk = c.salesPersonFk
+ JOIN vn.claimRatio cr ON cr.clientFk = c.id
+ WHERE wm.workerFk = IF(onlyForHisOwner, vOwner, wm.workerFk)
+ AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())
+ AND c.id != vClientFk
+ HAVING monthSale > 100;
+
+ SELECT SUM(monthSale) INTO vTotalSale
+ FROM tmp.clientList;
+
+ INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
+ SELECT clientFk, CONCAT('Cliente: ',vClientFk), vGreuge * monthSale / vTotalSale, util.VN_CURDATE(), vGreugeTypeFk
+ FROM tmp.clientList
+ UNION ALL
+ SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk;
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clientPackagingOverstock.sql b/db/routines/vn/procedures/clientPackagingOverstock.sql
new file mode 100644
index 000000000..fcd34c41b
--- /dev/null
+++ b/db/routines/vn/procedures/clientPackagingOverstock.sql
@@ -0,0 +1,92 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientPackagingOverstock`(vClientFk INT, vGraceDays INT)
+BEGIN
+ DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock;
+ CREATE TEMPORARY TABLE tmp.clientPackagingOverstock
+ ENGINE = MEMORY
+ SELECT itemFk,
+ sum(GotfromClient) - sum(SenttoClient) as devueltos,
+ sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados,
+ LEAST(
+ sum(GotfromClient) - sum(SenttoClient),
+ sum(InvoicedtoClient) - sum(InvoicedfromClient)
+ ) as abonables
+ FROM
+ (
+ SELECT t.*,
+ IF(@month = month, 0, 1) monthEnd,
+ @month := month
+ FROM
+ (
+ SELECT x.id as ticketFk,
+ date(x.shipped) as shipped,
+ x.itemFk,
+ IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient,
+ IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient,
+ IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient,
+ IFNULL(cast(sum(x.GotfromClient) as DECIMAL(10,0)),0) GotfromClient,
+ i.name as concept,
+ x.refFk as invoice,
+ month(shipped) month,
+ x.companyFk
+ FROM
+ (
+ SELECT t.id,
+ t.shipped,
+ IFNULL(pe.equivalentFk, s.itemFk) itemFk,
+ IF(s.quantity > 0, s.quantity, NULL) InvoicedtoClient,
+ IF(s.quantity < 0, -s.quantity, NULL) InvoicedfromClient,
+ NULL SenttoClient,
+ NULL GotfromClient,
+ t.refFk,
+ @month := 0 month,
+ t.companyFk
+ FROM sale s
+ JOIN ticket t on t.id = s.ticketFk
+ JOIN packaging p ON p.itemFk = s.itemFk
+ LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk
+ WHERE t.clientFk = vClientFk
+ AND t.shipped > '2017-11-30'
+ AND p.isPackageReturnable
+ UNION ALL
+ SELECT NULL,
+ '2017-11-30',
+ IFNULL(pe.equivalentFk, tps.itemFk) itemFk,
+ tps.sent InvoicedtoClient,
+ tps.returned InvoicedfromClient,
+ NULL SenttoClient,
+ NULL GotfromClient,
+ 'Histórico',
+ NULL,
+ NULL
+ FROM ticketPackagingStartingStock tps
+ LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk
+ WHERE tps.clientFk = vClientFk
+ AND tps.isForgetable = FALSE
+ UNION ALL
+ SELECT t.id,
+ t.shipped,
+ IFNULL(pe.equivalentFk, p.itemFk) itemFk,
+ NULL,
+ NULL,
+ IF(tp.quantity > 0 AND t.shipped <= TIMESTAMPADD(DAY, - vGraceDays, CURDATE()), tp.quantity, NULL) SenttoClient,
+ IF(tp.quantity < 0, -tp.quantity, NULL) GotfromClient,
+ NULL AS refFk,
+ NULL,
+ t.companyFk
+ FROM ticketPackaging tp
+ JOIN ticket t on t.id = tp.ticketFk
+ JOIN packaging p ON p.id = tp.packagingFk
+ LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk
+ WHERE t.clientFk = vClientFk
+ AND t.shipped > '2017-11-21' ) x
+
+ JOIN item i ON x.itemFk = i.id
+ GROUP BY x.id, x.itemFk
+ ) t
+ ORDER BY itemFk, shipped DESC
+ LIMIT 10000000000000000000
+ ) t2
+ GROUP BY itemFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clientPackagingOverstockReturn.sql b/db/routines/vn/procedures/clientPackagingOverstockReturn.sql
new file mode 100644
index 000000000..ac37bbc8d
--- /dev/null
+++ b/db/routines/vn/procedures/clientPackagingOverstockReturn.sql
@@ -0,0 +1,40 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientPackagingOverstockReturn`(vClientFk INT, vGraceDays INT)
+BEGIN
+ DECLARE vNewTicket INT DEFAULT 0;
+ DECLARE vWarehouseFk INT;
+
+ CALL vn.clientPackagingOverstock(vClientFk,vGraceDays);
+
+ SELECT id INTO vWarehouseFk
+ FROM vn.warehouse
+ WHERE hasConfectionTeam;
+
+ CALL vn.ticket_add(
+ vClientFk
+ ,CURDATE()
+ ,vWarehouseFk -- Algemesi
+ ,442 -- Verdnatura
+ ,NULL -- address
+ ,NULL -- agencia
+ ,NULL -- route
+ ,CURDATE()
+ ,account.myUser_getId()
+ ,TRUE
+ ,vNewTicket);
+
+ INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price)
+ SELECT vNewTicket, cpo.itemFk, - cpo.abonables, i.longName, p.price
+ FROM tmp.clientPackagingOverstock cpo
+ JOIN vn.item i ON i.id = cpo.itemFk
+ JOIN vn.packaging p ON p.itemFk = cpo.itemFk
+ WHERE cpo.abonables > 0;
+ INSERT INTO vn.ticketPackaging(ticketFk, packagingFk, quantity)
+ SELECT vNewTicket, p.id, cpo.abonables
+ FROM tmp.clientPackagingOverstock cpo
+ JOIN vn.packaging p ON p.itemFk = cpo.itemFk
+ WHERE cpo.abonables > 0;
+
+ SELECT vNewTicket;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clientRemoveWorker.sql b/db/routines/vn/procedures/clientRemoveWorker.sql
new file mode 100644
index 000000000..15d247c67
--- /dev/null
+++ b/db/routines/vn/procedures/clientRemoveWorker.sql
@@ -0,0 +1,40 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientRemoveWorker`()
+BEGIN
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vClientFk INT;
+ DECLARE rs CURSOR FOR
+ SELECT c.clientFk
+ FROM tmp.clientGetDebt c
+ LEFT JOIN clientRisk r ON r.clientFk = c.clientFk
+ GROUP BY c.clientFk
+ HAVING SUM(IFNULL(r.amount,0)) = 0;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
+ CREATE TEMPORARY TABLE tmp.clientGetDebt
+ SELECT cd.clientFk
+ FROM bs.clientDied cd
+ LEFT JOIN clientProtected cp ON cp.clientFk = cd.clientFk
+ JOIN client c ON c.id = cd.clientFk
+ JOIN province p ON p.id = c.provinceFk
+ LEFT JOIN autonomy a ON a.id = p.autonomyFk
+ JOIN country co ON co.id = p.countryFk
+ WHERE cd.warning = 'third'
+ AND cp.clientFk IS NULL
+ AND co.code NOT IN ('PT')
+ AND a.name <> 'Canarias'
+ AND c.salesPersonFk IS NOT NULL;
+
+ OPEN rs;
+ FETCH rs INTO vClientFk;
+ WHILE NOT vDone DO
+ CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE);
+ UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk;
+ FETCH rs INTO vClientFk;
+ END WHILE;
+ CLOSE rs;
+ DROP TEMPORARY TABLE tmp.clientGetDebt;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/clientRisk_update.sql b/db/routines/vn/procedures/clientRisk_update.sql
new file mode 100644
index 000000000..30ab3265f
--- /dev/null
+++ b/db/routines/vn/procedures/clientRisk_update.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientRisk_update`(vClientId INT, vCompanyId INT, vAmount DECIMAL(10,2))
+BEGIN
+ IF vAmount IS NOT NULL
+ THEN
+ INSERT INTO clientRisk
+ SET
+ clientFk = vClientId,
+ companyFk = vCompanyId,
+ amount = vAmount
+ ON DUPLICATE KEY UPDATE
+ amount = amount + VALUES(amount);
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/client_RandomList.sql b/db/routines/vn/procedures/client_RandomList.sql
new file mode 100644
index 000000000..2bd0d609b
--- /dev/null
+++ b/db/routines/vn/procedures/client_RandomList.sql
@@ -0,0 +1,59 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_RandomList`(vNumber INT)
+BEGIN
+
+ DECLARE i INT DEFAULT 0;
+ DECLARE c INT DEFAULT 0;
+ DECLARE maxClientFk INT;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.client;
+
+ CREATE TEMPORARY TABLE tmp.`client`
+ (id INT AUTO_INCREMENT,
+ clientFk INT,
+ isSelected TINYINT(1) NOT NULL DEFAULT 0,
+ PRIMARY KEY(id),
+ UNIQUE KEY clientFk (clientFk))
+ ENGINE = MEMORY;
+
+ INSERT INTO tmp.client(clientFk)
+ SELECT DISTINCT clientFk
+ FROM vn.invoiceOut
+ WHERE issued > TIMESTAMPADD(MONTH, -2, util.VN_CURDATE());
+
+ SELECT max(id) INTO maxClientFk
+ FROM tmp.client;
+
+
+ WHILE i < vNumber DO
+
+ SET i = i + 1;
+
+ WHILE c = 0 DO
+
+ SELECT id INTO c
+ FROM tmp.client
+ WHERE id = floor(RAND() * maxClientFk) + 1
+ AND isSelected = FALSE
+ LIMIT 1;
+
+ END WHILE;
+
+ -- SELECT i, maxClientFk, c;
+
+ UPDATE tmp.client
+ SET isSelected = TRUE
+ WHERE id = c;
+
+ SET c = 0;
+
+ END WHILE;
+
+ SELECT c.id, c.name FROM tmp.client tc
+ JOIN vn.client c ON c.id = tc.clientFk
+ WHERE isSelected
+ ORDER BY clientFk;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/client_checkBalance.sql b/db/routines/vn/procedures/client_checkBalance.sql
new file mode 100644
index 000000000..210fcc00f
--- /dev/null
+++ b/db/routines/vn/procedures/client_checkBalance.sql
@@ -0,0 +1,68 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_checkBalance`(IN vDateTo DATETIME, IN vIsConciliated BOOL)
+BEGIN
+/**
+ * Compara los datos de nuestros clientes con
+ * los que hay en la base de datos de sage
+ *
+ * @param vDateTo
+ * @param vIsConciliated
+ * @table tmp.ledgerComparative (id, date, account, debit, credit, companyFk)
+ */
+ DECLARE vDateFrom DATE;
+ DECLARE vMaxTolerance DECIMAL(10,2);
+
+ SELECT util.firstDayOfYear(vDateTo), util.dayEnd(vDateTo), maxTolerance
+ INTO vDateFrom, vDateTo, vMaxTolerance
+ FROM vn.ledgerConfig;
+
+ SELECT s.nickname,
+ c.id,
+ c.accountingAccount,
+ sub1.mysql,
+ sub1.sage,
+ sub1.mysql - sub1.sage difference,
+ sub1.companyFk,
+ c.name
+ FROM client c
+ JOIN payMethod pm ON pm.id = c.payMethodFk
+ JOIN (SELECT sub.companyFk,
+ sub.clientFk,
+ CAST(ROUND(SUM(sub.mysql), 2) AS DECIMAL(10,2)) mysql,
+ CAST(ROUND(SUM(sub.sage), 2) AS DECIMAL(10,2)) sage
+ FROM(SELECT io.companyFk,
+ io.clientFk,
+ - io.amount mysql,
+ 0 sage
+ FROM invoiceOut io
+ WHERE issued BETWEEN vDateFrom AND vDateTo
+ UNION ALL
+ SELECT r.companyFk,
+ r.clientFk,
+ r.amountPaid,
+ 0
+ FROM receipt r
+ WHERE payed BETWEEN vDateFrom AND vDateTo
+ AND IF(vIsConciliated,r.isConciliate, TRUE) = TRUE
+ UNION ALL
+ SELECT lc.companyFk,
+ c.id,
+ 0,
+ - (IFNULL(lc.credit, 0) - IFNULL(lc.debit, 0))
+ FROM tmp.ledgerComparative lc
+ JOIN client c ON c.accountingAccount = lc.account
+ WHERE lc.`date` BETWEEN vDateFrom AND vDateTo
+ )sub
+ GROUP BY companyFk, clientFk
+ ) sub1 ON sub1.clientFk = c.id
+ JOIN supplier s ON s.id = sub1.companyFk
+ JOIN company co ON co.id = sub1.companyFk
+ LEFT JOIN clientUnpaid cu ON cu.clientFk = c.id
+ AND cu.dated BETWEEN vDateFrom AND vDateTo
+ WHERE pm.outstandingDebt
+ AND co.code <> 'BLK'
+ AND cu.clientFk IS NULL
+ HAVING ABS(difference) > vMaxTolerance
+ ORDER BY c.name;
+END$$
+DELIMITER ;
diff --git a/db/changes/233202/00-client_create_upper.sql b/db/routines/vn/procedures/client_create.sql
similarity index 100%
rename from db/changes/233202/00-client_create_upper.sql
rename to db/routines/vn/procedures/client_create.sql
diff --git a/db/routines/vn/procedures/client_getDebt.sql b/db/routines/vn/procedures/client_getDebt.sql
new file mode 100644
index 000000000..ad7b5b7d2
--- /dev/null
+++ b/db/routines/vn/procedures/client_getDebt.sql
@@ -0,0 +1,62 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_getDebt`(vDate DATE)
+BEGIN
+/**
+ * Calculates the risk for active clients
+ *
+ * @table tmp.clientGetDebt(clientFk)
+ * @param vDate Maximum date of records
+ * @return tmp.risk
+ */
+
+ DECLARE vStarted DATETIME;
+ DECLARE vEnded DATETIME;
+
+ SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted
+ FROM clientConfig;
+
+ SET vEnded = util.dayEnd(IFNULL(vDate, util.VN_CURDATE()));
+
+ CREATE OR REPLACE TEMPORARY TABLE tClientRisk
+ ENGINE = MEMORY
+ SELECT cr.clientFk, SUM(cr.amount) amount
+ FROM clientRisk cr
+ JOIN tmp.clientGetDebt c ON c.clientFk = cr.clientFk
+ GROUP BY cr.clientFk;
+
+ INSERT INTO tClientRisk
+ SELECT c.clientFk, SUM(r.amountPaid)
+ FROM receipt r
+ JOIN tmp.clientGetDebt c ON c.clientFk = r.clientFk
+ WHERE r.payed > vEnded
+ GROUP BY c.clientFk;
+
+ INSERT INTO tClientRisk
+ SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2))
+ FROM hedera.tpvTransaction t
+ JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk
+ WHERE t.receiptFk IS NULL
+ AND t.status = 'ok'
+ GROUP BY t.clientFk;
+
+ INSERT INTO tClientRisk
+ SELECT t.clientFk, SUM(totalWithVat)
+ FROM ticket t
+ JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk
+ WHERE refFk IS NULL
+ AND shipped BETWEEN vStarted AND vEnded
+ GROUP BY t.clientFk;
+
+ -- refs #6351 BUG: No cambiar a CREATE OR REPLACE
+ DROP TEMPORARY TABLE IF EXISTS tmp.risk;
+ CREATE TEMPORARY TABLE tmp.risk
+ (PRIMARY KEY (clientFk))
+ ENGINE = MEMORY
+ SELECT clientFk, SUM(amount) risk
+ FROM client c
+ JOIN tClientRisk cr ON cr.clientFk = c.id
+ GROUP BY c.id;
+
+ DROP TEMPORARY TABLE tClientRisk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/client_getMana.sql b/db/routines/vn/procedures/client_getMana.sql
new file mode 100644
index 000000000..f5bb5747d
--- /dev/null
+++ b/db/routines/vn/procedures/client_getMana.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_getMana`()
+BEGIN
+/**
+ * Devuelve el mana de los clientes de la tabla tmp.client(id)
+ * @return tmp.clientMana(id, mana)
+ *
+ */
+ DECLARE vFromDated DATE;
+
+ DELETE tc FROM tmp.client tc
+ JOIN client c ON c.id = tc.id
+ WHERE c.typeFk <> 'normal';
+
+ SELECT MAX(dated) INTO vFromDated
+ FROM clientManaCache;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.clientMana
+ SELECT id, SUM(mana) mana
+ FROM
+ (
+ SELECT tc.id, cmc.mana
+ FROM clientManaCache cmc
+ JOIN tmp.client tc ON tc.id = cmc.clientFk
+ WHERE cmc.dated = vFromDated
+ UNION ALL
+ SELECT tc.id, s.quantity * value
+ FROM ticket t
+ JOIN address a ON a.id = t.addressFk
+ JOIN tmp.client tc ON tc.id = a.clientFk
+ JOIN sale s on s.ticketFk = t.id
+ JOIN saleComponent sc on sc.saleFk = s.id
+ JOIN component comp ON sc.componentFk = comp.id
+ JOIN componentType ct ON ct.id = comp.typeFk AND ct.code = 'mana'
+ WHERE t.shipped > vFromDated
+ AND t.shipped < util.tomorrow()
+ UNION ALL
+ SELECT tc.id, -amountPaid
+ FROM receipt r
+ JOIN `client` c ON c.id = r.clientFk
+ JOIN tmp.client tc ON tc.id = c.id
+ JOIN accounting a ON r.bankFk = a.id
+ AND a.code = 'mana'
+ WHERE r.payed > vFromDated
+ AND r.payed <= util.VN_CURDATE()
+ UNION ALL
+ SELECT tc.id, g.amount
+ FROM greuge g
+ JOIN `client` c ON c.id = g.clientFk
+ JOIN tmp.client tc ON tc.id = c.id
+ JOIN greugeType gt ON gt.id = g.greugeTypeFk AND gt.code = 'mana'
+ WHERE g.shipped > vFromDated
+ AND g.shipped <= util.VN_CURDATE()
+ ) sub
+ GROUP BY id;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/client_unassignSalesPerson.sql b/db/routines/vn/procedures/client_unassignSalesPerson.sql
new file mode 100644
index 000000000..f939ae68b
--- /dev/null
+++ b/db/routines/vn/procedures/client_unassignSalesPerson.sql
@@ -0,0 +1,51 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_unassignSalesPerson`()
+BEGIN
+/**
+ * Elimina la asignación de salesPersonFk de la ficha del clientes
+ * que no han realizado una compra en los últimos 3 meses y reparte
+ * su greuge entre el resto de clientes
+ */
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vClientFk INT;
+ DECLARE vCursor CURSOR FOR
+ SELECT c.clientFk
+ FROM tClientList c
+ LEFT JOIN clientRisk r ON r.clientFk = c.clientFk
+ GROUP BY c.clientFk
+ HAVING NOT SUM(IFNULL(r.amount, 0));
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ CREATE OR REPLACE TEMPORARY TABLE tClientList
+ SELECT c.id clientFk
+ FROM bs.clientDied cd
+ JOIN client c ON c.id = cd.clientFk
+ LEFT JOIN clientProtected cp ON cp.clientFk = c.id
+ LEFT JOIN salesPersonProtected sp ON sp.salesPersonFk = c.salesPersonFk
+ JOIN province p ON p.id = c.provinceFk
+ LEFT JOIN autonomy a ON a.id = p.autonomyFk
+ JOIN country co ON co.id = p.countryFk
+ WHERE cd.warning = 'third'
+ AND cp.clientFk IS NULL
+ AND sp.salesPersonFk IS NULL
+ AND a.name <> 'Canarias'
+ AND c.salesPersonFk IS NOT NULL;
+
+ OPEN vCursor;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vCursor INTO vClientFk;
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+ CALL clientGreugeSpray(vClientFk, TRUE, '', TRUE);
+ UPDATE client
+ SET salesPersonFk = NULL
+ WHERE id = vClientFk;
+ END LOOP;
+ CLOSE vCursor;
+
+ DROP TEMPORARY TABLE tClientList;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/cmrPallet_add.sql b/db/routines/vn/procedures/cmrPallet_add.sql
new file mode 100644
index 000000000..2267cd312
--- /dev/null
+++ b/db/routines/vn/procedures/cmrPallet_add.sql
@@ -0,0 +1,37 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`cmrPallet_add`(vExpeditionPalletFk INT, vCmrFk INT)
+BEGIN
+/**
+ * Añade registro a tabla cmrPallet.
+ *
+ * @param vExpeditionPalletFk Id de expeditionPallet
+ * @param vCmrFk Id de cmrPallet
+ */
+ DECLARE vIsACurrentExpeditionPallet BOOL;
+ DECLARE vIsACurrentCMR BOOL;
+ DECLARE vYesterday DATE;
+
+ SET vYesterday = util.yesterday();
+
+ SELECT COUNT(*) INTO vIsACurrentExpeditionPallet
+ FROM vn.expeditionPallet cp
+ WHERE cp.id = vExpeditionPalletFk
+ AND cp.built >= vYesterday;
+
+ IF !vIsACurrentExpeditionPallet THEN
+ CALL util.throw('expeditionPalletNotExist');
+ END IF;
+
+ SELECT COUNT(*) INTO vIsACurrentCMR
+ FROM vn.cmr c
+ WHERE c.id = vCmrFk
+ AND c.created >= vYesterday;
+
+ IF vIsACurrentCMR THEN
+ INSERT INTO cmrPallet (cmrFk, expeditionPalletFk)
+ VALUES(vCmrFk, vExpeditionPalletFk);
+ ELSE
+ Call util.throw('cmrNotExist');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collectionPlacement_get.sql b/db/routines/vn/procedures/collectionPlacement_get.sql
new file mode 100644
index 000000000..3641ba705
--- /dev/null
+++ b/db/routines/vn/procedures/collectionPlacement_get.sql
@@ -0,0 +1,150 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collectionPlacement_get`(
+ vParamFk INT(11),
+ vIsPicker bool)
+BEGIN
+/**
+ * Devuelve el listado de ubicaciones a las que hay que ir
+ * para preparar una colección o ticket de manera ordenada
+ *
+ * @param vParamFk Identificador de collection o Identificador de ticket
+ * @param vIsPicker Booleano para distinguer el sacador del revisador
+ */
+ DECLARE vCalcFk INT;
+ DECLARE vWarehouseFk INT;
+ DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW());
+
+ CREATE OR REPLACE TEMPORARY TABLE tSale
+ (INDEX(ticketFk), INDEX(saleFk), INDEX(itemFk))
+ ENGINE = MEMORY
+ SELECT s.ticketFk, s.id saleFk, s.itemFk, s.quantity
+ FROM ticketCollection tc
+ JOIN sale s ON s.ticketFk = tc.ticketFk
+ WHERE tc.collectionFk = vParamFk
+ UNION ALL
+ SELECT s.ticketFk, s.id, s.itemFk, s.quantity
+ FROM sale s
+ WHERE s.ticketFk = vParamFk;
+
+ SELECT t.warehouseFk
+ INTO vWarehouseFk
+ FROM ticket t
+ JOIN tSale ts ON ts.ticketFk = t.id
+ JOIN warehouse w ON w.id = t.warehouseFk
+ LIMIT 1;
+
+ CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
+
+ CREATE OR REPLACE TEMPORARY TABLE tGrouping
+ (INDEX(itemFk))
+ ENGINE = MEMORY
+ SELECT b.itemFk,
+ CASE b.groupingMode
+ WHEN 0 THEN 1
+ WHEN 2 THEN b.packing
+ ELSE b.`grouping`
+ END `grouping`
+ FROM buy b
+ JOIN cache.last_buy lb ON lb.buy_id = b.id
+ WHERE lb.warehouse_id = vWarehouseFk
+ GROUP BY b.itemFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSalePlacementList
+ (INDEX(saleFk), INDEX(`order`))
+ ENGINE = MEMORY
+ SELECT ts.saleFk,
+ ts.itemFk,
+ CAST(0 AS DECIMAL(10,0)) saleOrder,
+ IF(ish.visible > 0 OR iss.id, 1, 100000) *
+ IFNULL(p2.pickingOrder, p.pickingOrder) `order`,
+ TO_SECONDS(IF(iss.id,
+ iss.created - INTERVAL vCurrentYear YEAR,
+ ish.created - INTERVAL YEAR(ish.created) YEAR)) priority,
+ CONCAT(
+ IF(iss.id,
+ CONCAT('< ', IFNULL(wk.`code`, '---'),' > '),
+ ''),
+ p.`code`) COLLATE utf8_general_ci placement,
+ sh.priority shelvingPriority,
+ sh.code COLLATE utf8_general_ci shelving,
+ ish.created,
+ ish.visible,
+ IFNULL(
+ IF(st.code = 'previousByPacking', ish.packing, g.`grouping`),
+ 1) `grouping`,
+ st.code = 'previousPrepared' isPreviousPrepared,
+ iss.id itemShelvingSaleFk,
+ ts.ticketFk,
+ iss.id,
+ st.saleFk salePreviousPrepared,
+ iss.userFk,
+ ts.quantity
+ FROM tSale ts
+ LEFT JOIN (SELECT DISTINCT saleFk
+ FROM saleTracking st
+ JOIN state s ON s.id = st.stateFk
+ WHERE st.isChecked
+ AND s.semaphore = 1) st ON st.saleFk = ts.saleFk
+ JOIN itemShelving ish ON ish.itemFk = ts.itemFk
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector sc ON sc.id = p.sectorFk
+ JOIN sectorType st ON st.id = sc.typeFk
+ JOIN warehouse w ON w.id = sc.warehouseFk
+ LEFT JOIN tGrouping g ON g.itemFk = ts.itemFk
+ LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk
+ AND iss.itemShelvingFk = ish.id
+ LEFT JOIN worker wk ON wk.id = iss.userFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = ts.saleFk
+ LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
+ LEFT JOIN parking p2 ON p2.id = sg.parkingFk
+ WHERE w.id = vWarehouseFk
+ AND NOT sc.isHideForPickers
+ HAVING (iss.id AND st.saleFk) OR salePreviousPrepared IS NULL;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSalePlacementList2
+ (INDEX(saleFk), INDEX(olderPriority))
+ ENGINE = MEMORY
+ SELECT saleFk, priority olderPriority
+ FROM (SELECT saleFk, priority
+ FROM tSalePlacementList
+ ORDER BY isPreviousPrepared DESC,
+ itemShelvingSaleFk IS NULL DESC,
+ visible >= quantity DESC,
+ visible > 0 DESC,
+ IFNULL(shelvingPriority, 0) DESC,
+ priority
+ LIMIT 10000000000000000000
+ )sub
+ GROUP BY saleFk;
+
+ UPDATE tSalePlacementList tsp
+ JOIN (SELECT s1.saleFk, `order` saleOrder
+ FROM tSalePlacementList s1
+ JOIN tSalePlacementList2 s2 ON s2.saleFk = s1.saleFk
+ AND s2.olderPriority = s1.priority
+ ) sub ON sub.saleFk = tsp.saleFk
+ SET tsp.saleOrder = sub.saleOrder;
+
+ -- Anula el orden de antigüedad y ordena por ubicación
+ UPDATE tSalePlacementList
+ SET saleOrder = `order`;
+
+ SELECT spl.*
+ FROM tSalePlacementList spl
+ JOIN sale s ON s.id = spl.saleFk
+ ORDER BY saleOrder,
+ isPreviousPrepared DESC,
+ itemShelvingSaleFk DESC,
+ IF(vIsPicker, visible = 0, TRUE),
+ s.quantity <= spl.visible DESC,
+ shelvingPriority DESC,
+ priority;
+
+ DROP TEMPORARY TABLE
+ tSale,
+ tGrouping,
+ tSalePlacementList,
+ tSalePlacementList2;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_addItem.sql b/db/routines/vn/procedures/collection_addItem.sql
new file mode 100644
index 000000000..c19d88684
--- /dev/null
+++ b/db/routines/vn/procedures/collection_addItem.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_addItem`(
+ vBarccodeFk INT,
+ vQuantity INT,
+ vTicketFk INT
+)
+BEGIN
+/**
+ * Add a sales line to the ticket with the indicated amount.
+ *
+ * @param vBarcodeFk barcode on the item label
+ * @param vQuantity quantity to be added to the ticket
+ * @param vTicketFk ticket to which the sales line is added
+ */
+ DECLARE vConcept VARCHAR(50);
+ DECLARE vItemFk INT;
+ DECLARE vSaleFk INT;
+ DECLARE vDescription VARCHAR(50);
+ DECLARE vItemName VARCHAR(50);
+
+ SELECT barcodeToItem(vBarccodeFk) INTO vItemFk;
+
+ SELECT CONCAT(getUser(),
+ ' ',
+ DATE_FORMAT(util.VN_NOW(), '%H:%i' ),
+ ' ',
+ i.name
+ ) INTO vConcept
+ FROM item i
+ WHERE i.id = vItemFk;
+
+ SELECT name INTO vItemName FROM item WHERE id = vBarccodeFk;
+
+ SELECT CONCAT('Añadido articulo ',
+ vItemName,
+ ' cantidad:',
+ vQuantity
+ ) INTO vDescription;
+
+ INSERT INTO ticketLog
+ SET originFk = vTicketFk,
+ userFk = getUser(),
+ `action` = 'update',
+ `description` = vDescription;
+
+ INSERT INTO sale
+ SET itemFk = vItemFk,
+ ticketFk = vTicketFk,
+ concept = vConcept,
+ quantity = vQuantity,
+ isAdded = TRUE;
+
+ SELECT LAST_INSERT_ID() INTO vSaleFk;
+
+ CALL sale_calculateComponent(vSaleFk, NULL);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_assign.sql b/db/routines/vn/procedures/collection_assign.sql
new file mode 100644
index 000000000..49b4eb7bb
--- /dev/null
+++ b/db/routines/vn/procedures/collection_assign.sql
@@ -0,0 +1,95 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_assign`(
+ vUserFk INT,
+ OUT vCollectionFk INT
+)
+proc:BEGIN
+/**
+ * Comprueba si existen colecciones libres que se ajustan
+ * al perfil del usuario y le asigna la más antigua.
+ * Añade un registro al semillero de colecciones.
+ *
+ * @param vUserFk Id de usuario
+ * @param vCollectionFk Id de colección
+ */
+ DECLARE vHasTooMuchCollections BOOL;
+ DECLARE vLockTime INT DEFAULT 15;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ DO RELEASE_LOCK('collection_assign');
+
+ RESIGNAL;
+ END;
+
+ -- Si hay colecciones sin terminar, sale del proceso
+ CALL collection_get(vUserFk);
+
+ SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0
+ INTO vHasTooMuchCollections
+ FROM tCollection
+ JOIN productionConfig pc ;
+
+ DROP TEMPORARY TABLE tCollection;
+
+ IF vHasTooMuchCollections THEN
+ CALL util.throw('Hay colecciones pendientes');
+ LEAVE proc;
+ END IF;
+
+ IF NOT GET_LOCK('collection_assign',vLockTime) THEN
+ LEAVE proc;
+ END IF;
+
+ -- Se eliminan las colecciones sin asignar que estan obsoletas
+ INSERT INTO ticketTracking(stateFk, ticketFk)
+ SELECT s.id, tc.ticketFk
+ FROM `collection` c
+ JOIN ticketCollection tc ON tc.collectionFk = c.id
+ JOIN `state` s ON s.code = 'PRINTED_AUTO'
+ JOIN productionConfig pc
+ WHERE c.workerFk IS NULL
+ AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
+
+ DELETE c.*
+ FROM `collection` c
+ JOIN productionConfig pc
+ WHERE c.workerFk IS NULL
+ AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
+
+ -- Se añade registro al semillero
+ INSERT INTO collectionHotbed(userFk)
+ VALUES(vUserFk);
+
+ -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion
+ SELECT MIN(c.id)
+ INTO vCollectionFk
+ FROM `collection` c
+ JOIN operator o
+ ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL)
+ AND o.numberOfWagons = c.wagons
+ AND o.trainFk = c.trainFk
+ AND o.warehouseFk = c.warehouseFk
+ AND c.workerFk IS NULL
+ AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL)
+ JOIN (
+ SELECT tc.collectionFk, SUM(sv.volume) volume
+ FROM ticketCollection tc
+ JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk
+ WHERE sv.shipped >= util.VN_CURDATE()
+ GROUP BY tc.collectionFk
+ ) sub ON sub.collectionFk = c.id
+ AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL)
+ WHERE o.workerFk = vUserFk;
+
+ IF vCollectionFk IS NULL THEN
+ CALL collection_new(vUserFk, vCollectionFk);
+ END IF;
+
+ UPDATE `collection`
+ SET workerFk = vUserFk
+ WHERE id = vCollectionFk;
+
+ DO RELEASE_LOCK('collection_assign');
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_get.sql b/db/routines/vn/procedures/collection_get.sql
new file mode 100644
index 000000000..372d963c0
--- /dev/null
+++ b/db/routines/vn/procedures/collection_get.sql
@@ -0,0 +1,33 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_get`(vWorkerFk INT)
+BEGIN
+/**
+ * Obtiene colección del sacador si tiene líneas pendientes.
+ *
+ * @param vWorkerFk id del worker.
+ * @table Devuelve tabla temporal con las colecciones pendientes
+ */
+ DROP TEMPORARY TABLE IF EXISTS tCollection;
+
+ CREATE TEMPORARY TABLE tCollection
+ SELECT c.id collectionFk,
+ date(c.created) created,
+ COUNT(DISTINCT tc.ticketFk) ticketTotalCount
+ FROM collection c
+ JOIN ticketCollection tc ON tc.collectionFk = c.id
+ JOIN sale s ON s.ticketFk = tc.ticketFk
+ JOIN ticketState ts ON ts.ticketFk = tc.ticketFk
+ JOIN state s2 ON s2.id = ts.stateFk
+ JOIN productionConfig pc
+ JOIN vn.state ss on ss.code = 'PREPARED'
+ LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id
+ WHERE c.workerFk = vWorkerFk
+ AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge
+ AND s.quantity != 0
+ AND s2.order < pc.pendingCollectionsOrder
+ GROUP BY c.id
+ HAVING COUNT(*) > COUNT(DISTINCT st.id);
+
+ SELECT * FROM tCollection;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql
new file mode 100644
index 000000000..0a71ada78
--- /dev/null
+++ b/db/routines/vn/procedures/collection_getTickets.sql
@@ -0,0 +1,62 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_getTickets`(vParamFk INT)
+BEGIN
+/**
+ * Selecciona los tickets de una colección/ticket
+ * @param vParamFk ticketFk/collectionFk
+ * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones
+ */
+ DECLARE vItemPackingTypeFk VARCHAR(1);
+
+ -- Si los sacadores son los de pruebas, pinta los colores
+ SELECT itemPackingTypeFk INTO vItemPackingTypeFk
+ FROM vn.collection
+ WHERE id = vParamFk;
+
+ SELECT t.id ticketFk,
+ IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`,
+ am.name agencyName,
+ t.warehouseFk,
+ w.id salesPersonFk,
+ IFNULL(tob.description,'') observaciones,
+ cc.rgb
+ FROM vn.ticket t
+ LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
+ LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21
+ LEFT JOIN vn.collectionColors cc
+ ON cc.wagon = tc.wagon
+ AND cc.shelve = tc.`level`
+ AND cc.trainFk = c2.trainFk -- PAK 23/12/21
+ LEFT JOIN vn.zone z ON z.id = t.zoneFk
+ LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
+ LEFT JOIN vn.client c ON c.id = t.clientFk
+ LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
+ LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
+ AND tob.observationTypeFk = 1
+ WHERE t.id = vParamFk
+ AND t.shipped >= util.yesterday()
+ UNION ALL
+ SELECT t.id ticketFk,
+ IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`,
+ am.name agencyName,
+ t.warehouseFk,
+ w.id salesPersonFk,
+ IFNULL(tob.description, '') observaciones,
+ IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`
+ FROM vn.ticket t
+ JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
+ LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21
+ LEFT JOIN vn.collectionColors cc
+ ON cc.wagon = tc.wagon
+ AND cc.shelve = tc.`level`
+ AND cc.trainFk = c2.trainFk -- PAK 23/12/21
+ LEFT JOIN vn.zone z ON z.id = t.zoneFk
+ LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
+ LEFT JOIN vn.client c ON c.id = t.clientFk
+ LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
+ LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
+ AND tob.observationTypeFk = 1
+ WHERE tc.collectionFk = vParamFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_kill.sql b/db/routines/vn/procedures/collection_kill.sql
new file mode 100644
index 000000000..f80fea512
--- /dev/null
+++ b/db/routines/vn/procedures/collection_kill.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_kill`(vSelf INT)
+BEGIN
+/**
+ * Elimina una coleccion y coloca sus tickets en OK
+ */
+ INSERT INTO ticketTracking(stateFk, ticketFk)
+ SELECT s.id, ticketFk
+ FROM vn.ticketCollection tc
+ JOIN vn.state s ON s.code = 'OK'
+ WHERE tc.collectionFk = vSelf;
+
+ DELETE FROM vn.collection
+ WHERE id = vSelf;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_make.sql b/db/routines/vn/procedures/collection_make.sql
new file mode 100644
index 000000000..b5b728000
--- /dev/null
+++ b/db/routines/vn/procedures/collection_make.sql
@@ -0,0 +1,68 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_make`()
+proc:BEGIN
+/**
+ * Genera colecciones de tickets sin asignar trabajador a partir de la tabla
+ * vn.collectionHotbed.
+ */
+ DECLARE vUserFk INT;
+ DECLARE vCounter INT;
+ DECLARE vMaxCollectionWithoutUser INT;
+ DECLARE vHasEnoughFreeCollections BOOL;
+ DECLARE vDone INT DEFAULT FALSE;
+
+ DECLARE cur1 CURSOR FOR
+ SELECT DISTINCT userFk
+ FROM vn.collectionHotbed;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SELECT maxCollectionWithoutUser
+ INTO vMaxCollectionWithoutUser
+ FROM vn.productionConfig pc;
+
+ SELECT (vMaxCollectionWithoutUser - COUNT(*)) <= 0
+ INTO vHasEnoughFreeCollections
+ FROM vn.collection c
+ JOIN vn.operator o
+ ON o.numberOfWagons = c.wagons
+ AND o.trainFk = c.trainFk
+ AND o.itemPackingTypeFk = c.itemPackingTypeFk
+ WHERE c.workerFk IS NULL
+ AND o.workerFk = vUserFk;
+
+ IF vHasEnoughFreeCollections THEN
+ LEAVE proc;
+ END IF;
+
+ OPEN cur1;
+
+ read_loop: LOOP
+
+ SET vDone = FALSE;
+
+ FETCH cur1 INTO vUserFk;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ SET vCounter = vMaxCollectionWithoutUser;
+
+ WHILE vCounter > 0 DO
+
+ SET vCounter = vCounter - 1;
+
+ CALL vn.collection_new(vUserFk, @vCollectionFk);
+
+ END WHILE;
+
+ DELETE
+ FROM vn.collectionHotbed
+ WHERE userFk = vUserFk;
+
+ END LOOP;
+
+ CLOSE cur1;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql
new file mode 100644
index 000000000..1292707af
--- /dev/null
+++ b/db/routines/vn/procedures/collection_new.sql
@@ -0,0 +1,344 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_new`(vUserFk INT, OUT vCollectionFk INT)
+proc:BEGIN
+/**
+ * Genera colecciones de tickets sin asignar trabajador.
+ *
+ * @param vUserFk Identificador de account.user
+ */
+ DECLARE vWarehouseFk INT;
+ DECLARE vWagons INT;
+ DECLARE vTrainFk INT;
+ DECLARE vLinesLimit INT DEFAULT NULL;
+ DECLARE vTicketLines INT;
+ DECLARE vVolumeLimit DECIMAL DEFAULT NULL;
+ DECLARE vTicketVolume DECIMAL;
+ DECLARE vMaxTickets INT;
+ DECLARE vStateFk VARCHAR(45);
+ DECLARE vFirstTicketFk INT;
+ DECLARE vHour INT;
+ DECLARE vMinute INT;
+ DECLARE vWorkerCode VARCHAR(3);
+ DECLARE vWagonCounter INT DEFAULT 0;
+ DECLARE vTicketFk INT;
+ DECLARE vItemPackingTypeFk VARCHAR(1);
+ DECLARE vHasAssignedTickets BOOLEAN;
+ DECLARE vHasUniqueCollectionTime BOOL;
+ DECLARE vDone INT DEFAULT FALSE;
+ DECLARE vLockName VARCHAR(215);
+ DECLARE vLockTime INT DEFAULT 15;
+ DECLARE vFreeWagonFk INT;
+
+ DECLARE c1 CURSOR FOR
+ SELECT ticketFk, `lines`, m3
+ FROM tmp.productionBuffer
+ WHERE ticketFk <> vFirstTicketFk
+ ORDER BY HH,
+ mm,
+ productionOrder DESC,
+ m3 DESC,
+ agency,
+ zona,
+ routeFk,
+ ticketFk
+ LIMIT vMaxTickets;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ IF vLockName IS NOT NULL THEN
+ DO RELEASE_LOCK(vLockName);
+ END IF;
+
+ RESIGNAL;
+ END;
+
+ SELECT pc.ticketTrolleyMax * o.numberOfWagons,
+ pc.hasUniqueCollectionTime,
+ w.code,
+ o.warehouseFk,
+ o.itemPackingTypeFk,
+ st.code,
+ o.numberOfWagons,
+ o.trainFk,
+ o.linesLimit,
+ o.volumeLimit
+ INTO vMaxTickets,
+ vHasUniqueCollectionTime,
+ vWorkerCode,
+ vWarehouseFk,
+ vItemPackingTypeFk,
+ vStateFk,
+ vWagons,
+ vTrainFk,
+ vLinesLimit,
+ vVolumeLimit
+ FROM productionConfig pc
+ JOIN worker w ON w.id = vUserFk
+ JOIN state st ON st.`code` = 'ON_PREPARATION'
+ JOIN operator o ON o.workerFk = vUserFk;
+
+ SET vLockName = CONCAT_WS('/',
+ 'collection_new',
+ vWarehouseFk,
+ vItemPackingTypeFk
+ );
+
+ IF NOT GET_LOCK(vLockName, vLockTime) THEN
+ LEAVE proc;
+ END IF;
+
+ -- Se prepara el tren, con tantos vagones como sea necesario.
+ CREATE OR REPLACE TEMPORARY TABLE tTrain
+ (wagon INT,
+ shelve INT,
+ liters INT,
+ `lines`INT,
+ height INT,
+ ticketFk INT,
+ PRIMARY KEY(wagon, shelve))
+ ENGINE = MEMORY;
+
+ WHILE vWagons > vWagonCounter DO
+ SET vWagonCounter = vWagonCounter + 1;
+
+ INSERT INTO tTrain(wagon, shelve, liters, `lines`, height)
+ SELECT vWagonCounter, cv.`level` , cv.liters , cv.`lines` , cv.height
+ FROM collectionVolumetry cv
+ WHERE cv.trainFk = vTrainFk
+ AND cv.itemPackingTypeFk = vItemPackingTypeFk;
+ END WHILE;
+
+ -- Esto desaparecerá cuando tengamos la table cache.ticket
+ CALL productionControl(vWarehouseFk, 0);
+
+ ALTER TABLE tmp.productionBuffer
+ ADD COLUMN liters INT,
+ ADD COLUMN height INT;
+
+ -- Se obtiene nº de colección.
+ INSERT INTO collection
+ SET itemPackingTypeFk = vItemPackingTypeFk,
+ trainFk = vTrainFk,
+ wagons = vWagons,
+ warehouseFk = vWarehouseFk;
+
+ SELECT LAST_INSERT_ID() INTO vCollectionFk;
+
+ -- Los tickets de recogida en Algemesí sólo se sacan si están asignados.
+ -- Los pedidos con riesgo no se sacan aunque se asignen.
+ DELETE pb.*
+ FROM tmp.productionBuffer pb
+ JOIN state s ON s.id = pb.state
+ WHERE (pb.agency = 'REC_ALGEMESI'
+ AND s.code <> 'PICKER_DESIGNED')
+ OR pb.problem LIKE '%RIESGO%';
+
+ -- Comprobamos si hay tickets asignados. En ese caso, nos centramos
+ -- exclusivamente en esos tickets y los sacamos independientemente
+ -- de problemas o tamaños
+ SELECT COUNT(*) INTO vHasAssignedTickets
+ FROM tmp.productionBuffer pb
+ JOIN state s ON s.id = pb.state
+ WHERE s.code = 'PICKER_DESIGNED'
+ AND pb.workerCode = vWorkerCode;
+
+ -- Se dejan en la tabla tmp.productionBuffer sólo aquellos tickets adecuados
+ IF vHasAssignedTickets THEN
+ DELETE pb.*
+ FROM tmp.productionBuffer pb
+ JOIN state s ON s.id = pb.state
+ WHERE s.code <> 'PICKER_DESIGNED'
+ OR pb.workerCode <> vWorkerCode;
+ ELSE
+ DELETE pb.*
+ FROM tmp.productionBuffer pb
+ JOIN state s ON s.id = pb.state
+ JOIN agencyMode am ON am.id = pb.agencyModeFk
+ JOIN agency a ON a.id = am.agencyFk
+ JOIN productionConfig pc
+ WHERE pb.shipped <> util.VN_CURDATE()
+ OR (pb.ubicacion IS NULL AND a.isOwn)
+ OR (NOT s.isPreparable AND NOT s.isPrintable)
+ OR pb.collectionH IS NOT NULL
+ OR pb.collectionV IS NOT NULL
+ OR pb.collectionN IS NOT NULL
+ OR (NOT pb.H AND pb.V > 0 AND vItemPackingTypeFk = 'H')
+ OR (NOT pb.V AND vItemPackingTypeFk = 'V')
+ OR (pc.isPreviousPreparationRequired AND pb.previousWithoutParking)
+ OR LENGTH(pb.problem) > 0
+ OR (pb.lines >= vLinesLimit AND vLinesLimit IS NOT NULL)
+ OR (pb.m3 >= vVolumeLimit AND vVolumeLimit IS NOT NULL);
+ END IF;
+
+ -- Es importante que el primer ticket se coja en todos los casos
+ SELECT ticketFk,
+ HH,
+ mm,
+ `lines`,
+ m3
+ INTO vFirstTicketFk,
+ vHour,
+ vMinute,
+ vTicketLines,
+ vTicketVolume
+ FROM tmp.productionBuffer
+ ORDER BY HH,
+ mm,
+ productionOrder DESC,
+ m3 DESC,
+ agency,
+ zona,
+ routeFk,
+ ticketFk
+ LIMIT 1;
+
+ -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede
+ IF vHasUniqueCollectionTime THEN
+ DELETE FROM tmp.productionBuffer
+ WHERE HH <> vHour
+ OR mm <> vMinute;
+ END IF;
+
+ SET vTicketFk = vFirstTicketFk;
+ SET @lines = 0;
+ SET @volume = 0;
+
+ OPEN c1;
+ read_loop: LOOP
+ SET vDone = FALSE;
+
+ -- Buscamos un ticket que cumpla con los requisitos en el listado
+ IF ((vTicketLines + @lines) <= vLinesLimit OR vLinesLimit IS NULL)
+ AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN
+
+ CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk);
+ DROP TEMPORARY TABLE tmp.ticketIPT;
+
+ UPDATE tmp.productionBuffer pb
+ JOIN (
+ SELECT SUM(litros) liters,
+ @lines:= COUNT(*) + @lines,
+ COUNT(*) `lines`,
+ MAX(i.`size`) height,
+ @volume := SUM(sv.volume) + @volume,
+ SUM(sv.volume) volume
+ FROM saleVolume sv
+ JOIN sale s ON s.id = sv.saleFk
+ JOIN item i ON i.id = s.itemFk
+ WHERE sv.ticketFk = vTicketFk
+ ) sub
+ SET pb.liters = sub.liters,
+ pb.`lines` = sub.`lines`,
+ pb.height = sub.height
+ WHERE pb.ticketFk = vTicketFk;
+
+ UPDATE tTrain tt
+ JOIN tmp.productionBuffer pb ON pb.ticketFk = vTicketFk
+ SET tt.ticketFk = pb.ticketFk
+ WHERE tt.liters >= pb.liters
+ AND tt.`lines` >= pb.`lines`
+ AND (tt.height >= pb.height OR vItemPackingTypeFk <> 'V')
+ AND tt.ticketFk IS NULL
+ ORDER BY wagon,
+ shelve,
+ tt.liters,
+ tt.`lines`,
+ tt.height
+ LIMIT 1;
+
+ -- Si no le encuentra una balda adecuada, intentamos darle un carro entero si queda alguno libre
+ IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
+ SELECT tt.wagon
+ INTO vFreeWagonFk
+ FROM tTrain tt
+ LEFT JOIN (
+ SELECT DISTINCT wagon
+ FROM tTrain
+ WHERE ticketFk IS NOT NULL
+ ) nn ON nn.wagon = tt.wagon
+ WHERE nn.wagon IS NULL
+ ORDER BY wagon
+ LIMIT 1;
+
+ IF vFreeWagonFk THEN
+ UPDATE tTrain
+ SET ticketFk = vFirstTicketFk
+ WHERE wagon = vFreeWagonFk;
+
+ -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo
+ DELETE tt.*
+ FROM tTrain tt
+ LEFT JOIN (
+ SELECT DISTINCT wagon
+ FROM tTrain
+ WHERE ticketFk IS NOT NULL
+ ) nn ON nn.wagon = tt.wagon
+ WHERE nn.wagon IS NULL;
+ END IF;
+ END IF;
+
+ FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume;
+ IF vDone OR NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk IS NULL) THEN
+ LEAVE read_loop;
+ END IF;
+ ELSE
+ FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume;
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+ END IF;
+ END LOOP;
+ CLOSE c1;
+
+ IF (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
+ UPDATE collection c
+ JOIN state st ON st.code = 'ON_PREPARATION'
+ SET c.stateFk = st.id
+ WHERE c.id = vCollectionFk;
+
+ -- Asigna las bandejas
+ INSERT IGNORE INTO ticketCollection(ticketFk, collectionFk, `level`, wagon, liters)
+ SELECT tt.ticketFk, vCollectionFk, tt.shelve, tt.wagon, tt.liters
+ FROM tTrain tt
+ WHERE tt.ticketFk IS NOT NULL
+ ORDER BY tt.wagon, tt.shelve;
+
+ -- Actualiza el estado de los tickets
+ CALL collection_setState(vCollectionFk, vStateFk);
+
+ -- Aviso para la preparacion previa
+ INSERT INTO ticketDown(ticketFk, collectionFk)
+ SELECT tc.ticketFk, tc.collectionFk
+ FROM ticketCollection tc
+ WHERE tc.collectionFk = vCollectionFk;
+
+ CALL sales_mergeByCollection(vCollectionFk);
+
+ UPDATE `collection` c
+ JOIN (
+ SELECT COUNT(*) saleTotalCount,
+ SUM(s.isPicked <> 0) salePickedCount
+ FROM ticketCollection tc
+ JOIN sale s ON s.ticketFk = tc.ticketFk
+ WHERE tc.collectionFk = vCollectionFk
+ AND s.quantity > 0
+ ) sub
+ SET c.saleTotalCount = sub.saleTotalCount,
+ c.salePickedCount = sub.salePickedCount
+ WHERE c.id = vCollectionFk;
+
+ ELSE
+ DELETE FROM `collection`
+ WHERE id = vCollectionFk;
+ SET vCollectionFk = NULL;
+ END IF;
+
+ DO RELEASE_LOCK(vLockName);
+
+ DROP TEMPORARY TABLE
+ tTrain,
+ tmp.productionBuffer;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_printSticker.sql b/db/routines/vn/procedures/collection_printSticker.sql
new file mode 100644
index 000000000..50259152d
--- /dev/null
+++ b/db/routines/vn/procedures/collection_printSticker.sql
@@ -0,0 +1,33 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_printSticker`(
+ vSelf INT,
+ vLabelCount INT
+)
+BEGIN
+/**
+ * Prints a yellow label from a collection or a ticket
+ *
+ * @param vSelf collection or ticket
+ * @param vLabelCount number of times the collection has been printed
+ */
+ DECLARE vPrintArgs JSON DEFAULT JSON_OBJECT('collectionOrTicketFk', vSelf);
+
+ IF vLabelCount IS NULL THEN
+ INSERT INTO ticketTrolley
+ SELECT ticketFk, 1
+ FROM ticketCollection
+ WHERE collectionFk = vSelf
+ ON DUPLICATE KEY UPDATE labelCount = labelCount + 1;
+ ELSE
+ SET vPrintArgs = JSON_MERGE_PATCH(vPrintArgs, JSON_OBJECT('labelCount', vLabelCount));
+ END IF;
+
+ CALL report_print(
+ 'LabelCollection',
+ (SELECT o.labelerFk FROM operator o WHERE o.workerFk = account.myUser_getId()),
+ account.myUser_getId(),
+ vPrintArgs,
+ 'high'
+ );
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_setParking.sql b/db/routines/vn/procedures/collection_setParking.sql
new file mode 100644
index 000000000..73aa87bfb
--- /dev/null
+++ b/db/routines/vn/procedures/collection_setParking.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_setParking`(IN `vCollectionFk` VARCHAR(8), IN `vParkingFk` INT)
+proc: BEGIN
+/**
+ * Aparca una colección en un parking.
+ *
+ * @param vCollectionFk Id de la colección
+ * @param vParkingFk Id del parking
+ */
+ REPLACE vn.ticketParking(ticketFk, parkingFk)
+ SELECT tc.ticketFk, vParkingFk
+ FROM vn.ticketCollection tc
+ WHERE tc.collectionFk = vCollectionFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_setState.sql b/db/routines/vn/procedures/collection_setState.sql
new file mode 100644
index 000000000..2d33c53d6
--- /dev/null
+++ b/db/routines/vn/procedures/collection_setState.sql
@@ -0,0 +1,44 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_setState`(vSelf INT, vStateCode VARCHAR(255) COLLATE utf8_general_ci)
+BEGIN
+/**
+ * Modifica el estado de los tickets de una colección.
+ *
+ * @param vSelf el id del colección
+ * @param vStateCode estado a modificar de los tickets
+ */
+ DECLARE vTicketFk INT;
+ DECLARE vDone INT DEFAULT FALSE;
+ DECLARE vCursor CURSOR FOR
+ SELECT DISTINCT ticketFk
+ FROM ticketCollection tc
+ WHERE tc.collectionFk = vSelf;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ OPEN vCursor;
+
+ read_loop: LOOP
+
+ FETCH vCursor INTO vTicketFk;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ CALL ticket_setState(vTicketFk, vStateCode);
+
+ END LOOP;
+
+ CLOSE vCursor;
+
+ COMMIT;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/company_getFiscaldata.sql b/db/routines/vn/procedures/company_getFiscaldata.sql
new file mode 100644
index 000000000..7c56382e9
--- /dev/null
+++ b/db/routines/vn/procedures/company_getFiscaldata.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`company_getFiscaldata`(workerFk INT)
+BEGIN
+
+DECLARE vCompanyFk INT;
+
+ SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk)
+ INTO vCompanyFk
+ FROM vn.routeConfig rc
+ LEFT JOIN userConfig uc ON uc.userFk = workerFk;
+
+
+ SELECT
+ s.name AS name ,
+ s.NIF AS nif ,
+ s.street AS street ,
+ s.city AS city ,
+ s.postCode AS postCode
+
+ FROM vn.company c
+ JOIN vn.worker w ON w.id = c.workerManagerFk
+ JOIN vn.supplier s ON s.id = c.id
+ WHERE c.id = vCompanyFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/company_getSuppliersDebt.sql b/db/routines/vn/procedures/company_getSuppliersDebt.sql
new file mode 100644
index 000000000..f4814abcc
--- /dev/null
+++ b/db/routines/vn/procedures/company_getSuppliersDebt.sql
@@ -0,0 +1,201 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`company_getSuppliersDebt`(vSelf INT, vMonthsAgo INT)
+BEGIN
+/**
+ * Generates a temporary table containing outstanding payments to suppliers.
+ *
+ * @param vSelf company id
+ * @param vMonthAgo time interval to be consulted
+ */
+ DECLARE vStartingDate DATETIME DEFAULT TIMESTAMPADD (MONTH,- vMonthsAgo,util.VN_CURDATE());
+ DECLARE vCurrencyEuroFk INT;
+ DECLARE vStartDate DATE;
+ DECLARE vInvalidBalances DOUBLE;
+
+ SELECT dated, invalidBalances INTO vStartDate, vInvalidBalances FROM supplierDebtConfig;
+ SELECT id INTO vCurrencyEuroFk FROM currency WHERE code = 'EUR';
+
+ DROP TEMPORARY TABLE IF EXISTS tOpeningBalances;
+ CREATE TEMPORARY TABLE tOpeningBalances (
+ supplierFk INT NOT NULL,
+ companyFk INT NOT NULL,
+ openingBalances DOUBLE NOT NULL,
+ closingBalances DOUBLE NOT NULL,
+ currencyFk INT NOT NULL,
+ PRIMARY KEY (supplierFk, companyFk, currencyFk)
+ ) ENGINE = MEMORY;
+
+ -- Calculates the opening and closing balance for each supplier
+ INSERT INTO tOpeningBalances
+ SELECT supplierFk,
+ companyFk,
+ SUM(amount * isBeforeStarting) AS openingBalances,
+ SUM(amount) closingBalances,
+ currencyFk
+ FROM (
+ SELECT p.supplierFk,
+ p.companyFk,
+ IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount,
+ p.dueDated < vStartingDate isBeforeStarting,
+ p.currencyFk
+ FROM payment p
+ WHERE p.received > vStartDate
+ AND p.companyFk = vSelf
+ UNION ALL
+ SELECT r.supplierFk,
+ r.companyFk,
+ - IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue) AS Total,
+ rv.dueDated < vStartingDate isBeforeStarting,
+ r.currencyFk
+ FROM invoiceIn r
+ INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk
+ WHERE r.issued > vStartDate
+ AND r.isBooked
+ AND r.companyFk = vSelf
+ ) sub GROUP BY companyFk, supplierFk, currencyFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tPendingDuedates;
+ CREATE TEMPORARY TABLE tPendingDuedates (
+ id INT auto_increment,
+ expirationId INT,
+ dated DATE,
+ supplierFk INT NOT NULL,
+ companyFk INT NOT NULL,
+ amount DECIMAL(10, 2) NOT NULL,
+ currencyFk INT NOT NULL,
+ pending DECIMAL(10, 2) DEFAULT 0,
+ balance DECIMAL(10, 2) DEFAULT 0,
+ endingBalance DECIMAL(10, 2) DEFAULT 0,
+ isPayment BOOLEAN,
+ isReconciled BOOLEAN,
+ PRIMARY KEY (id),
+ INDEX (supplierFk, companyFk, currencyFk)
+ ) ENGINE = MEMORY;
+
+ INSERT INTO tPendingDuedates (
+ expirationId,
+ dated,
+ supplierFk,
+ companyFk,
+ amount,
+ currencyFk,
+ isPayment,
+ isReconciled
+ )SELECT p.id,
+ p.dueDated,
+ p.supplierFk,
+ p.companyFk,
+ IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa),
+ p.currencyFk,
+ TRUE isPayment,
+ p.isConciliated
+ FROM payment p
+ WHERE p.dueDated >= vStartingDate
+ AND p.companyFk = vSelf
+ UNION ALL
+ SELECT r.id,
+ rv.dueDated,
+ r.supplierFk,
+ r.companyFk,
+ -IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue),
+ r.currencyFk,
+ FALSE isPayment,
+ TRUE
+ FROM invoiceIn r
+ LEFT JOIN tOpeningBalances si ON r.companyFk = si.companyFk
+ AND r.supplierFk = si.supplierFk
+ AND r.currencyFk = si.currencyFk
+ JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk
+ WHERE rv.dueDated >= vStartingDate
+ AND (si.closingBalances IS NULL OR si.closingBalances <> 0)
+ AND r.isBooked
+ AND r.companyFk = vSelf
+ ORDER BY supplierFk, companyFk, companyFk, dueDated, isPayment DESC, id;
+ -- Now, we calculate the outstanding amount for each receipt in descending order
+ SET @risk := 0.0;
+ SET @supplier := 0.0;
+ SET @company := 0.0;
+ SET @moneda := 0.0;
+ SET @pending := 0.0;
+ SET @day := util.VN_CURDATE();
+
+ UPDATE tPendingDuedates vp
+ LEFT JOIN tOpeningBalances si ON vp.companyFk = si.companyFk
+ AND vp.supplierFk = si.supplierFk
+ AND vp.currencyFk = si.currencyFk
+ SET vp.balance = @risk := (
+ IF (
+ @company <> vp.companyFk
+ OR @supplier <> vp.supplierFk
+ OR @moneda <> vp.currencyFk,
+ IFNULL(si.openingBalances, 0),
+ @risk
+ ) +
+ vp.amount
+ ),
+ -- if there is a change of company or supplier or currency, the balance is reset
+ vp.pending = @pending := IF (
+ @company <> vp.companyFk
+ OR @supplier <> vp.supplierFk
+ OR @moneda <> vp.currencyFk
+ OR @day <> vp.dated,
+ vp.amount * (NOT vp.isPayment),
+ @pending + vp.amount
+ ),
+ vp.companyFk = @company := vp.companyFk,
+ vp.supplierFk = @supplier := vp.supplierFk,
+ vp.currencyFk = @moneda := vp.currencyFk,
+ vp.dated = @day := vp.dated,
+ vp.balance = @risk,
+ vp.pending = @pending;
+
+ CREATE OR REPLACE TEMPORARY TABLE tRowsToDelete ENGINE = MEMORY
+ SELECT expirationId,
+ dated,
+ supplierFk,
+ companyFk,
+ currencyFk,
+ balance
+ FROM tPendingDuedates
+ WHERE balance < vInvalidBalances
+ AND balance > - vInvalidBalances;
+
+ DELETE vp.*
+ FROM tPendingDuedates vp
+ JOIN tRowsToDelete rd ON (
+ vp.dated < rd.dated
+ OR (vp.dated = rd.dated AND vp.expirationId <= rd.expirationId)
+ )
+ AND vp.supplierFk = rd.supplierFk
+ AND vp.companyFk = rd.companyFk
+ AND vp.currencyFk = rd.currencyFk
+ WHERE NOT vp.isPayment;
+
+ SELECT vp.expirationId,
+ vp.dated,
+ vp.supplierFk,
+ vp.companyFk,
+ vp.currencyFk,
+ vp.amount,
+ vp.pending,
+ vp.balance,
+ s.payMethodFk,
+ vp.isPayment,
+ vp.isReconciled,
+ vp.endingBalance,
+ cr.amount clientRiskAmount,
+ co.CEE
+ FROM tPendingDuedates vp
+ LEFT JOIN supplier s ON s.id = vp.supplierFk
+ LEFT JOIN client c ON c.fi = s.nif
+ LEFT JOIN clientRisk cr ON cr.clientFk = c.id
+ LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id
+ LEFT JOIN bankEntity be ON be.id = sa.bankEntityFk
+ LEFT JOIN country co ON co.id = be.countryFk
+ AND cr.companyFk = vp.companyFk;
+
+ DROP TEMPORARY TABLE tOpeningBalances;
+ DROP TEMPORARY TABLE tPendingDuedates;
+ DROP TEMPORARY TABLE tRowsToDelete;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/comparative_add.sql b/db/routines/vn/procedures/comparative_add.sql
new file mode 100644
index 000000000..44f9686aa
--- /dev/null
+++ b/db/routines/vn/procedures/comparative_add.sql
@@ -0,0 +1,59 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`comparative_add`()
+BEGIN
+/**
+ * Inserts sales records less than one month old in comparative.
+ */
+ DECLARE vMaxPeriod INT;
+ DECLARE vPeriod INT;
+ DECLARE vWeek INT;
+ DECLARE vConfigPeriod INT;
+ DECLARE vConfigWeek INT;
+
+ SELECT period, week INTO vConfigPeriod, vConfigWeek
+ FROM comparativeAddConfig;
+
+ SELECT IFNULL(MAX(timePeriod), 0) INTO vMaxPeriod
+ FROM comparative;
+
+ SELECT period - vConfigPeriod,
+ week
+ INTO vPeriod,
+ vWeek
+ FROM `time`
+ WHERE dated = util.VN_CURDATE();
+
+ IF vMaxPeriod < vPeriod AND vWeek > vConfigWeek THEN
+ DELETE FROM comparative WHERE timePeriod BETWEEN vMaxPeriod AND vPeriod;
+
+ INSERT INTO comparative(
+ timePeriod,
+ itemFk,
+ warehouseFk,
+ quantity,
+ price,
+ countryFk
+ )
+ SELECT tm.period,
+ s.itemFk,
+ t.warehouseFk,
+ sum(s.quantity),
+ sum(v.importe),
+ p.countryFk
+ FROM bs.ventas v
+ JOIN time tm ON tm.dated = v.fecha
+ JOIN sale s ON s.id = v.Id_Movimiento
+ JOIN itemType tp ON tp.id = v.tipo_id
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN client c ON c.id = t.clientFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ JOIN address ad ON ad.id = t.addressFk
+ LEFT JOIN province p ON p.id = ad.provinceFk
+ WHERE tm.period BETWEEN vMaxPeriod AND vPeriod
+ AND c.typeFk <> 'loses'
+ AND NOT w.code = 'inv'
+ GROUP BY p.countryFk, s.itemFk, tm.period, t.warehouseFk;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/confection_controlSource.sql b/db/routines/vn/procedures/confection_controlSource.sql
new file mode 100644
index 000000000..f011a52e9
--- /dev/null
+++ b/db/routines/vn/procedures/confection_controlSource.sql
@@ -0,0 +1,103 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`confection_controlSource`(
+ vDated DATE,
+ vScopeDays INT,
+ vMaxAlertLevel INT,
+ vWarehouseFk INT
+)
+BEGIN
+/**
+ * Obtiene la información para el control de confección,
+ * ya sean tickets y/o entradas.
+ *
+ * @param vDated Fecha a calcular
+ * @param vScopeDays Número de días desde hoy en adelante que entran en el cálculo.
+ * @param vMaxAlertLevel Id nivel de alerta
+ * @param vWarehouseFk Id de almacén
+ */
+ DECLARE vEndingDate DATETIME DEFAULT util.dayEnd(vDated) + INTERVAL vScopeDays DAY;
+
+ SELECT t.shipped,
+ t.id ticketFk,
+ s.id saleFk,
+ s.quantity,
+ s.concept,
+ ABS(s.reserved) isReserved,
+ i.category,
+ it.name itemType,
+ t.nickname,
+ wh.name warehouse,
+ t.warehouseFk warehouseFk,
+ a.provinceFk,
+ am.agencyFk,
+ ct.description,
+ stock.visible,
+ stock.available
+ FROM ticket t
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN warehouse wh ON wh.id = t.warehouseFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN confectionType ct ON ct.id = it.making
+ JOIN `address` a on a.id = t.addressFk
+ LEFT JOIN ticketState tls on tls.ticketFk = t.id
+ LEFT JOIN
+ (
+ SELECT item_id,
+ SUM(visible) visible,
+ SUM(available) available
+ FROM (
+ SELECT a.item_id,
+ 0 visible,
+ a.available
+ FROM cache.cache_calc cc
+ LEFT JOIN cache.available a ON a.calc_id = cc.id
+ WHERE cc.cache_id IN ('visible', 'available')
+ AND cc.params = CONCAT(vWarehouseFk, "/", util.VN_CURDATE())
+ UNION ALL
+ SELECT v.item_id,
+ v.visible,
+ 0
+ FROM cache.cache_calc cc
+ LEFT JOIN cache.visible v ON v.calc_id = cc.id
+ WHERE cc.cacheName IN ('visible', 'available')
+ AND cc.params = vWarehouseFk
+ ) sub
+ GROUP BY item_id
+ ) stock ON stock.item_id = s.itemFk
+ WHERE it.making
+ AND tls.alertLevel < vMaxAlertLevel
+ AND wh.hasConfectionTeam
+ AND t.shipped BETWEEN vDated AND vEndingDate
+ AND s.quantity > 0
+ UNION ALL
+ SELECT tr.shipped,
+ e.id,
+ NULL,
+ b.quantity,
+ i.name,
+ NULL,
+ i.category,
+ NULL,
+ whi.name,
+ who.name,
+ NULL,
+ NULL,
+ NULL,
+ ct.description,
+ NULL,
+ NULL
+ FROM buy b
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN warehouse whi ON whi.id = tr.warehouseInFk
+ JOIN warehouse who ON who.id = tr.warehouseOutFk
+ JOIN item i ON i.id = b.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN confectionType ct ON ct.id = it.making
+ WHERE who.hasConfectionTeam
+ AND it.making
+ AND tr.shipped BETWEEN vDated AND vEndingDate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/conveyorExpedition_Add.sql b/db/routines/vn/procedures/conveyorExpedition_Add.sql
new file mode 100644
index 000000000..c57c2ea37
--- /dev/null
+++ b/db/routines/vn/procedures/conveyorExpedition_Add.sql
@@ -0,0 +1,52 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME)
+BEGIN
+
+
+ DECLARE startingMinute INT;
+
+ TRUNCATE vn.conveyorExpedition;
+
+ INSERT INTO vn.conveyorExpedition( expeditionFk,
+ created,
+ length,
+ width,
+ height,
+ routeFk,
+ productionMinute,
+ truck,
+ criterion,
+ conveyorBuildingClassFk)
+ SELECT e.id,
+ e.created,
+ 10 * p.depth as depth,
+ 10 * p.width as width,
+ 10 * p.height as height,
+ IFNULL(t.routeFk,am.agencyFk) routeFk,
+ hour(e.created) * 60 + minute(e.created),
+ IFNULL(et.description , a.name),
+ IFNULL(t.routeFk,am.agencyFk) criterion,
+ IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass)
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.packaging p ON p.id = e.packagingFk
+ LEFT JOIN vn.zone z ON z.id = t.zoneFk
+ LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
+ LEFT JOIN vn.agency a ON a.id = am.agencyFk
+ LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
+ LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ JOIN vn.packagingConfig pc
+ WHERE t.warehouseFk IN (60,1,44)
+ AND e.created BETWEEN vStarted AND vEnded
+ AND p.height < 140
+ AND p.width < 60
+ AND p.depth < 125;
+
+ SELECT MIN(productionMinute) INTO startingMinute
+ FROM vn.conveyorExpedition ce ;
+
+ UPDATE vn.conveyorExpedition
+ SET productionMinute = productionMinute - startingMinute;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/copyComponentsFromSaleList.sql b/db/routines/vn/procedures/copyComponentsFromSaleList.sql
new file mode 100644
index 000000000..17cf487b1
--- /dev/null
+++ b/db/routines/vn/procedures/copyComponentsFromSaleList.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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 ;
diff --git a/db/routines/vn/procedures/createPedidoInterno.sql b/db/routines/vn/procedures/createPedidoInterno.sql
new file mode 100644
index 000000000..ecc5e57a5
--- /dev/null
+++ b/db/routines/vn/procedures/createPedidoInterno.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`createPedidoInterno`(vItemFk INT,vQuantity INT)
+BEGIN
+
+
+ UPDATE vn.item SET upToDown = vQuantity WHERE id = vItemFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/creditInsurance_getRisk.sql b/db/routines/vn/procedures/creditInsurance_getRisk.sql
new file mode 100644
index 000000000..8028dc5fb
--- /dev/null
+++ b/db/routines/vn/procedures/creditInsurance_getRisk.sql
@@ -0,0 +1,42 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`creditInsurance_getRisk`()
+BEGIN
+/**
+ * Devuelve el riesgo de los clientes que estan asegurados
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tmp.client_list
+ (PRIMARY KEY (Id_Cliente))
+ ENGINE = MEMORY
+ SELECT * FROM (
+ SELECT cc.client Id_Cliente, ci.grade
+ FROM creditClassification cc
+ JOIN creditInsurance ci ON cc.id = ci.creditClassification
+ WHERE dateEnd IS NULL
+ ORDER BY ci.creationDate DESC
+ LIMIT 10000000000000000000) t1
+ GROUP BY Id_Cliente;
+
+ CALL vn2008.risk_vs_client_list(util.VN_CURDATE());
+
+ SELECT
+ c.id,
+ c.name,
+ c.credit clientCredit,
+ c.creditInsurance solunion,
+ CAST(r.risk AS DECIMAL(10,0)) risk,
+ CAST(c.creditInsurance - r.risk AS DECIMAL(10,0)) riskAlive,
+ cac.invoiced billedAnnually,
+ c.dueDay,
+ ci.grade,
+ c2.country
+ FROM tmp.client_list ci
+ LEFT JOIN tmp.risk r ON r.Id_Cliente = ci.Id_Cliente
+ JOIN client c ON c.id = ci.Id_Cliente
+ JOIN bs.clientAnnualConsumption cac ON c.id = cac.clientFk
+ JOIN country c2 ON c2.id = c.countryFk
+ GROUP BY c.id;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.risk;
+ DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/crypt.sql b/db/routines/vn/procedures/crypt.sql
new file mode 100644
index 000000000..b3517b1ad
--- /dev/null
+++ b/db/routines/vn/procedures/crypt.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`crypt`(vText VARCHAR(255), vKey VARCHAR(255), OUT vResult VARCHAR(255) )
+BEGIN
+
+ DECLARE vEncryptedText VARCHAR(255) DEFAULT '';
+
+ DECLARE vKeyLength INT;
+ DECLARE vKeyPosition INT DEFAULT 1;
+ DECLARE vKeyChar VARCHAR(1);
+
+ DECLARE vTextLength INT;
+ DECLARE vTextPosition INT DEFAULT 1;
+ DECLARE vTextChar VARCHAR(1);
+
+ DECLARE vEncryptedChar VARCHAR(1);
+ DECLARE vEncryptedCharPosition INT;
+
+ DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz';
+ DECLARE vChainTextPosition INT;
+ DECLARE vChainKeyPosition INT;
+ DECLARE vChainLength INT;
+
+ DECLARE vInvalidadChars VARCHAR(255) DEFAULT '';
+
+ SET vTextLength = LENGTH(vText);
+ SET vKeyLength = LENGTH(vKey);
+ SET vChainLength = LENGTH(vChain);
+
+ WHILE vTextPosition <= vTextLength DO
+
+ SET vTextChar = MID(vText,vTextPosition,1);
+ SET vKeyChar = MID(vKey,vKeyPosition,1);
+
+ SET vChainTextPosition = LOCATE(vTextChar, vChain);
+ SET vInvalidadChars = IF(vChainTextPosition, vInvalidadChars, CONCAT(vInvalidadChars,vTextChar));
+ SET vChainKeyPosition = LOCATE(vKeyChar, vChain);
+ SET vEncryptedCharPosition = vChainTextPosition + vChainKeyPosition;
+
+ IF vEncryptedCharPosition > vChainLength THEN
+
+ SET vEncryptedCharPosition = vEncryptedCharPosition - vChainLength;
+
+ END IF;
+
+ SET vEncryptedChar = MID(vChain, vEncryptedCharPosition,1);
+
+ SET vEncryptedText = CONCAT(vEncryptedText, vEncryptedChar);
+
+ SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1);
+ SET vTextPosition = vTextPosition + 1;
+
+ END WHILE;
+
+ SET vResult = IF(LENGTH(vInvalidadChars), CONCAT('Caracteres no válidos: ',vInvalidadChars),vEncryptedText);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/cryptOff.sql b/db/routines/vn/procedures/cryptOff.sql
new file mode 100644
index 000000000..e0677a0e2
--- /dev/null
+++ b/db/routines/vn/procedures/cryptOff.sql
@@ -0,0 +1,54 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`cryptOff`(vText VARCHAR(255), vKey VARCHAR(255), OUT vResult VARCHAR(255))
+BEGIN
+
+ DECLARE vUncryptedText VARCHAR(255) DEFAULT '';
+
+ DECLARE vKeyLength INT;
+ DECLARE vKeyPosition INT DEFAULT 1;
+ DECLARE vKeyChar VARCHAR(1);
+
+ DECLARE vTextLength INT;
+ DECLARE vTextPosition INT DEFAULT 1;
+ DECLARE vTextChar VARCHAR(1);
+
+ DECLARE vUncryptedChar VARCHAR(1);
+ DECLARE vUncryptedCharPosition INT;
+
+ DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz';
+ DECLARE vChainTextPosition INT;
+ DECLARE vChainKeyPosition INT;
+ DECLARE vChainLength INT;
+
+ SET vTextLength = LENGTH(vText);
+ SET vKeyLength = LENGTH(vKey);
+ SET vChainLength = LENGTH(vChain);
+
+ WHILE vTextPosition <= vTextLength DO
+
+ SET vTextChar = MID(vText,vTextPosition,1);
+ SET vKeyChar = MID(vKey,vKeyPosition,1);
+
+ SET vChainTextPosition = LOCATE(vTextChar, vChain);
+ SET vChainKeyPosition = LOCATE(vKeyChar, vChain);
+ SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition;
+
+ IF vUncryptedCharPosition < 1 THEN
+
+ SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength;
+
+ END IF;
+
+ SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1);
+
+ SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar);
+
+ SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1);
+ SET vTextPosition = vTextPosition + 1;
+
+ END WHILE;
+
+ SET vResult = vUncryptedText;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/department_calcTree.sql b/db/routines/vn/procedures/department_calcTree.sql
new file mode 100644
index 000000000..5a265bd41
--- /dev/null
+++ b/db/routines/vn/procedures/department_calcTree.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`department_calcTree`()
+BEGIN
+/**
+ * Calculates the #path, #lft, #rgt, #sons and #depth columns of
+ * the #department table. To build the tree, it uses the #parentFk
+ * column.
+ */
+ DECLARE vIndex INT DEFAULT 0;
+ DECLARE vSons INT;
+
+ DROP TEMPORARY TABLE IF EXISTS tNestedTree;
+ CREATE TEMPORARY TABLE tNestedTree
+ SELECT id, path, lft, rgt, depth, sons
+ FROM department LIMIT 0;
+
+ SET max_sp_recursion_depth = 5;
+ CALL department_calcTreeRec(NULL, '/', 0, vIndex, vSons);
+ SET max_sp_recursion_depth = 0;
+
+ UPDATE department z
+ JOIN tNestedTree t ON t.id = z.id
+ SET z.path = t.path,
+ z.lft = t.lft,
+ z.rgt = t.rgt,
+ z.depth = t.depth,
+ z.sons = t.sons;
+
+ DROP TEMPORARY TABLE tNestedTree;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/department_calcTreeRec.sql b/db/routines/vn/procedures/department_calcTreeRec.sql
new file mode 100644
index 000000000..77054b17f
--- /dev/null
+++ b/db/routines/vn/procedures/department_calcTreeRec.sql
@@ -0,0 +1,69 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`department_calcTreeRec`(
+ vSelf INT,
+ vPath VARCHAR(255),
+ vDepth INT,
+ INOUT vIndex INT,
+ OUT vSons INT
+)
+BEGIN
+/**
+ * Calculates and sets the #path, #lft, #rgt, #sons and #depth
+ * columns for all children of the passed node. Once calculated
+ * the last node rgt index and the number of sons are returned.
+ * To update it's children, this procedure calls itself recursively
+ * for each one.
+ *
+ * @vSelf The node identifier
+ * @vPath The initial path
+ * @vDepth The initial depth
+ * @vIndex The initial lft index
+ * @vSons The number of direct sons
+ */
+ DECLARE vChildFk INT;
+ DECLARE vLft INT;
+ DECLARE vMySons INT;
+ DECLARE vDone BOOL;
+ DECLARE vChildren CURSOR FOR
+ SELECT id FROM department
+ WHERE (vSelf IS NULL AND parentFk IS NULL)
+ OR (vSelf IS NOT NULL AND parentFk = vSelf);
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SET vSons = 0;
+
+ OPEN vChildren;
+ myLoop: LOOP
+ SET vDone = FALSE;
+ FETCH vChildren INTO vChildFk;
+
+ IF vDone THEN
+ LEAVE myLoop;
+ END IF;
+
+ SET vIndex = vIndex + 1;
+ SET vLft = vIndex;
+ SET vSons = vSons + 1;
+
+ CALL department_calcTreeRec(
+ vChildFk,
+ CONCAT(vPath, vChildFk, '/'),
+ vDepth + 1,
+ vIndex,
+ vMySons
+ );
+
+ SET vIndex = vIndex + 1;
+
+ INSERT INTO tNestedTree
+ SET id = vChildFk,
+ path = vPath,
+ lft = vLft,
+ rgt = vIndex,
+ depth = vDepth,
+ sons = vMySons;
+ END LOOP;
+ CLOSE vChildren;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/department_doCalc.sql b/db/routines/vn/procedures/department_doCalc.sql
new file mode 100644
index 000000000..915b9f191
--- /dev/null
+++ b/db/routines/vn/procedures/department_doCalc.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`department_doCalc`()
+proc: BEGIN
+/**
+ * Recalculates the department tree.
+ */
+ DECLARE vIsChanged BOOL;
+
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ DO RELEASE_LOCK('vn.department_doCalc');
+ RESIGNAL;
+ END;
+
+ IF !GET_LOCK('vn.department_doCalc', 0) THEN
+ LEAVE proc;
+ END IF;
+
+ SELECT isChanged INTO vIsChanged
+ FROM department_recalc;
+
+ IF vIsChanged THEN
+ UPDATE department_recalc SET isChanged = FALSE;
+ CALL vn.department_calcTree;
+ END IF;
+
+ DO RELEASE_LOCK('vn.department_doCalc');
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/department_getHasMistake.sql b/db/routines/vn/procedures/department_getHasMistake.sql
new file mode 100644
index 000000000..394105a16
--- /dev/null
+++ b/db/routines/vn/procedures/department_getHasMistake.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`department_getHasMistake`()
+BEGIN
+
+/**
+ * Obtiene los sectores a los cuales les ponemos errores
+ *
+ */
+
+ SELECT id, name
+ FROM department
+ WHERE hasToMistake <> FALSE;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/department_getLeaves.sql b/db/routines/vn/procedures/department_getLeaves.sql
new file mode 100644
index 000000000..7f1e3cc35
--- /dev/null
+++ b/db/routines/vn/procedures/department_getLeaves.sql
@@ -0,0 +1,78 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`department_getLeaves`(
+ vParentFk INT,
+ vSearch VARCHAR(255)
+)
+BEGIN
+ DECLARE vIsNumber BOOL;
+ DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != '';
+
+ DROP TEMPORARY TABLE IF EXISTS tNodes;
+ CREATE TEMPORARY TABLE tNodes
+ (UNIQUE (id))
+ ENGINE = MEMORY
+ SELECT id FROM department LIMIT 0;
+
+ IF vIsSearch THEN
+ SET vIsNumber = vSearch REGEXP '^[0-9]+$';
+
+ INSERT INTO tNodes
+ SELECT id FROM department
+ WHERE (vIsNumber AND `name` = vSearch)
+ OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%'))
+ LIMIT 1000;
+ END IF;
+
+ IF vParentFk IS NULL THEN
+ DROP TEMPORARY TABLE IF EXISTS tChilds;
+ CREATE TEMPORARY TABLE tChilds
+ ENGINE = MEMORY
+ SELECT id FROM tNodes;
+
+ DROP TEMPORARY TABLE IF EXISTS tParents;
+ CREATE TEMPORARY TABLE tParents
+ ENGINE = MEMORY
+ SELECT id FROM department LIMIT 0;
+
+ myLoop: LOOP
+ DELETE FROM tParents;
+ INSERT INTO tParents
+ SELECT parentFk id
+ FROM department g
+ JOIN tChilds c ON c.id = g.id
+ WHERE g.parentFk IS NOT NULL;
+
+ INSERT IGNORE INTO tNodes
+ SELECT id FROM tParents;
+
+ IF ROW_COUNT() = 0 THEN
+ LEAVE myLoop;
+ END IF;
+
+ DELETE FROM tChilds;
+ INSERT INTO tChilds
+ SELECT id FROM tParents;
+ END LOOP;
+
+ DROP TEMPORARY TABLE
+ tChilds,
+ tParents;
+ END IF;
+
+ IF !vIsSearch THEN
+ INSERT IGNORE INTO tNodes
+ SELECT id FROM department
+ WHERE parentFk <=> vParentFk;
+ END IF;
+
+ SELECT d.id,
+ d.`name`,
+ d.parentFk,
+ d.sons
+ FROM department d
+ JOIN tNodes n ON n.id = d.id
+ ORDER BY depth, `name`;
+
+ DROP TEMPORARY TABLE tNodes;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/deviceLog_add.sql b/db/routines/vn/procedures/deviceLog_add.sql
new file mode 100644
index 000000000..8d2310633
--- /dev/null
+++ b/db/routines/vn/procedures/deviceLog_add.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`deviceLog_add`(vWorkerFk INT, vAppName VARCHAR(45), vAppVersion VARCHAR(45), vAndroid_id VARCHAR(64))
+BEGIN
+/**
+ * Inserta registro en tabla devicelog el log del usuario conectado.
+ *
+ * @param vAppName es el nombre de la app
+ * @param vAppVersion es la versión de la app
+ * @param vAndroid_id es el android_id del dispositivo que se ha logueado
+ */
+ INSERT INTO deviceLog (userFK, nameApp, versionApp, android_id)
+ VALUES(vWorkerFk, vAppName, vAppVersion, vAndroid_id);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/deviceProductionUser_exists.sql b/db/routines/vn/procedures/deviceProductionUser_exists.sql
new file mode 100644
index 000000000..f5be6e94f
--- /dev/null
+++ b/db/routines/vn/procedures/deviceProductionUser_exists.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`deviceProductionUser_exists`(vUserFk INT)
+BEGIN
+
+/* SELECT COUNT(*) AS UserExists
+ FROM vn.deviceProductionUser dpu
+ WHERE dpu.userFk = vUserFk;*/
+ SELECT TRUE;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/deviceProductionUser_getWorker.sql b/db/routines/vn/procedures/deviceProductionUser_getWorker.sql
new file mode 100644
index 000000000..b18339108
--- /dev/null
+++ b/db/routines/vn/procedures/deviceProductionUser_getWorker.sql
@@ -0,0 +1,14 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`deviceProductionUser_getWorker`(vAndroid_id VARCHAR(64))
+BEGIN
+/**
+ * Selecciona si hay registrado un device con un android_id
+ *
+ * @param vAndroid_id el número android_id del dispositivo
+ */
+ SELECT account.user_getNameFromId(dpu.userFk)
+ FROM deviceProductionUser dpu
+ JOIN deviceProduction dp ON dpu.deviceProductionFk = dp.id
+ WHERE dp.android_id = vAndroid_id;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/deviceProduction_getnameDevice.sql b/db/routines/vn/procedures/deviceProduction_getnameDevice.sql
new file mode 100644
index 000000000..c8a5abfaf
--- /dev/null
+++ b/db/routines/vn/procedures/deviceProduction_getnameDevice.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`deviceProduction_getnameDevice`(vAndroid_id VARCHAR(64))
+BEGIN
+/**
+ * Selecciona el id del dispositivo que corresponde al vAndroid_id.
+ *
+ * @param vAndroid_id el número android_id del dispositivo
+ */
+ SELECT dp.id
+ FROM deviceProduction dp
+ WHERE dp.android_id = vAndroid_id;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/device_checkLogin.sql b/db/routines/vn/procedures/device_checkLogin.sql
new file mode 100644
index 000000000..db566a068
--- /dev/null
+++ b/db/routines/vn/procedures/device_checkLogin.sql
@@ -0,0 +1,43 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`device_checkLogin`(vUserFk INT, vAndroidID VARCHAR(50))
+BEGIN
+
+/*
+ * Comprueba si está registrado el dispositivo mediante su androidId
+ *
+ * @param vUSerFk el id del user
+ * @param vAndroidID es el identificador android_id del dispositivo
+ */
+ DECLARE vIsAuthorized BOOL DEFAULT TRUE;
+ DECLARE vIsDepartment BOOL;
+ DECLARE vIsAllUsersAllowed BOOL;
+ DECLARE vMessage VARCHAR(200);
+
+ SELECT dpc.isAllUsersallowed INTO vIsAllUsersAllowed
+ FROM vn.deviceProductionConfig dpc;
+
+ IF NOT vIsAllUsersAllowed THEN
+
+ SELECT COUNT(*) INTO vIsDepartment
+ FROM vn.workerDepartment dp
+ JOIN department d ON d.id = dp.departmentFk
+ WHERE dp.workerFk = vUserFk AND d.hasToCheckLogin;
+
+ IF vIsDepartment THEN
+ SELECT COUNT(*) INTO vIsAuthorized
+ FROM vn.deviceProductionUser dpu
+ JOIN vn.deviceProduction dp ON dp.id = dpu.deviceProductionFk
+ WHERE dpu.userFk = vUserFk
+ AND dp.android_id = vAndroidID;
+
+ IF NOT vIsAuthorized THEN
+ SET vMessage = 'Usuario no autorizado';
+ END IF;
+ END IF;
+
+ END IF;
+
+ SELECT vIsAuthorized,vMessage;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/duaEntryValueUpdate.sql b/db/routines/vn/procedures/duaEntryValueUpdate.sql
new file mode 100644
index 000000000..f688191de
--- /dev/null
+++ b/db/routines/vn/procedures/duaEntryValueUpdate.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaEntryValueUpdate`(vDuaFk INT)
+BEGIN
+
+ UPDATE duaEntry de
+ JOIN
+ ( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total
+ FROM buy b
+ JOIN duaEntry de ON de.entryFk = b.entryFk
+ WHERE duaFk = vDuaFk
+ GROUP BY b.entryFk
+ ) sub ON sub.entryFk = de.entryFk
+
+ LEFT JOIN
+ (SELECT e.id, sum(iit.taxableBase) as euros
+ FROM entry e
+ JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk
+ JOIN duaEntry de ON de.entryFk = e.id
+ WHERE de.duaFk = vDuaFk
+ GROUP BY e.id
+ ) sub2 ON sub2.id = de.entryFk
+
+ SET de.value = sub.total,
+ de.euroValue = sub2.euros
+ WHERE duaFk = vDuaFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql
new file mode 100644
index 000000000..f95e836b1
--- /dev/null
+++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql
@@ -0,0 +1,75 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaInvoiceInBooking`(vDuaFk INT)
+BEGIN
+/**
+ * Genera el asiento de un DUA y marca las entradas como confirmadas
+ *
+ * @param vDuaFk Id del dua a recalcular
+ */
+ DECLARE done BOOL DEFAULT FALSE;
+ DECLARE vInvoiceFk INT;
+ DECLARE vASIEN BIGINT DEFAULT 0;
+ DECLARE vCounter INT DEFAULT 0;
+
+ DECLARE rs CURSOR FOR
+ SELECT DISTINCT e.invoiceInFk
+ FROM entry e
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN invoiceIn ii ON ii.id = e.invoiceInFk
+ WHERE de.duaFk = vDuaFk
+ AND de.customsValue
+ AND ii.isBooked = FALSE;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+ OPEN rs;
+
+ UPDATE invoiceIn ii
+ JOIN entry e ON e.invoiceInFk = ii.id
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN dua d ON d.id = de.duaFk
+ SET ii.isBooked = TRUE,
+ ii.booked = IFNULL(ii.booked,d.booked),
+ ii.operated = IFNULL(ii.operated,d.operated),
+ ii.issued = IFNULL(ii.issued,d.issued),
+ ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried),
+ e.isBooked = TRUE,
+ e.isConfirmed = TRUE
+ WHERE d.id = vDuaFk;
+
+ SELECT IFNULL(ASIEN,0) INTO vASIEN
+ FROM dua
+ WHERE id = vDuaFk;
+
+ FETCH rs INTO vInvoiceFk;
+
+ WHILE NOT done DO
+
+ CALL invoiceIn_booking(vInvoiceFk);
+
+ IF vCounter > 0 OR vASIEN > 0 THEN
+
+ UPDATE XDiario x
+ JOIN ledgerConfig lc ON lc.lastBookEntry = x.ASIEN
+ SET x.ASIEN = vASIEN;
+
+ ELSE
+
+ SELECT lastBookEntry INTO vASIEN FROM ledgerConfig;
+
+ END IF;
+
+ SET vCounter = vCounter + 1;
+
+ FETCH rs INTO vInvoiceFk;
+
+ END WHILE;
+
+ CLOSE rs;
+
+ UPDATE dua
+ SET ASIEN = vASIEN
+ WHERE id = vDuaFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/duaParcialMake.sql b/db/routines/vn/procedures/duaParcialMake.sql
new file mode 100644
index 000000000..cbb56e16d
--- /dev/null
+++ b/db/routines/vn/procedures/duaParcialMake.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaParcialMake`(vDuaFk INT)
+BEGIN
+
+ DECLARE vNewDuaFk INT;
+
+ INSERT INTO dua(companyFk)
+ SELECT companyFk
+ FROM dua
+ WHERE id = vDuaFk;
+
+ SELECT LAST_INSERT_ID() INTO vNewDuaFk;
+
+ INSERT INTO duaEntry(duaFk, entryFk, value, customsValue)
+ SELECT vNewDuaFk, entryFk, value, value - customsValue
+ FROM duaEntry
+ WHERE duaFk = vDuaFk
+ AND value != customsValue;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/duaTaxBooking.sql b/db/routines/vn/procedures/duaTaxBooking.sql
new file mode 100644
index 000000000..1fef11e96
--- /dev/null
+++ b/db/routines/vn/procedures/duaTaxBooking.sql
@@ -0,0 +1,136 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaTaxBooking`(vDuaFk INT)
+BEGIN
+ DECLARE vBookNumber INT;
+ DECLARE vBookDated DATE;
+ DECLARE vDiff DECIMAL(10,2);
+ DECLARE vApunte BIGINT;
+
+ SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE()) INTO vBookNumber, vBookDated
+ FROM dua
+ WHERE id = vDuaFk;
+
+ IF vBookNumber IS NULL OR NOT vBookNumber THEN
+ CALL ledger_next(vBookNumber);
+ END IF;
+
+ -- Apunte de la aduana
+
+ INSERT INTO XDiario(
+ ASIEN,
+ FECHA,
+ SUBCTA,
+ CONCEPTO,
+ EUROHABER,
+ SERIE,
+ empresa_id,
+ CLAVE,
+ FACTURA)
+
+ SELECT
+ vBookNumber,
+ d.bookEntried,
+ '4700000999',
+ CONCAT('DUA ',d.`code`),
+ sum(dt.base * dt.rate / 100) EUROHABER,
+ 'R',
+ d.companyFk,
+ vDuaFk,
+ vDuaFk
+ FROM duaTax dt
+ JOIN dua d ON d.id = dt.duaFk
+ WHERE dt.duaFk = vDuaFk;
+
+ -- Apuntes por tipo de IVA y proveedor
+
+ INSERT INTO XDiario(
+ ASIEN,
+ FECHA,
+ SUBCTA,
+ CONTRA,
+ EURODEBE,
+ BASEEURO,
+ CONCEPTO,
+ FACTURA,
+ IVA,
+ AUXILIAR,
+ SERIE,
+ FECHA_EX,
+ FECHA_OP,
+ FACTURAEX,
+ NFACTICK,
+ L340,
+ LDIFADUAN,
+ TIPOCLAVE,
+ TIPOEXENCI,
+ TIPONOSUJE,
+ TIPOFACT,
+ TIPORECTIF,
+ TERIDNIF,
+ TERNIF,
+ TERNOM,
+ empresa_id,
+ FECREGCON
+ )
+
+ SELECT
+ vBookNumber ASIEN,
+ vBookDated FECHA,
+ tr.account SUBCTA,
+ '4330002067' CONTRA,
+ sum(dt.tax) EURODEBE,
+ sum(dt.base) BASEEURO,
+ CONCAT('DUA nº',d.code) CONCEPTO,
+ d.id FACTURA,
+ dt.rate IVA,
+ '*' AUXILIAR,
+ 'D' SERIE,
+ d.issued FECHA_EX,
+ d.operated FECHA_OP,
+ d.code FACTURAEX,
+ 1 NFACTICK,
+ 1 L340,
+ TRUE LDIFADUAN,
+ 1 TIPOCLAVE,
+ 1 TIPOEXENCI,
+ 1 TIPONOSUJE,
+ 5 TIPOFACT,
+ 1 TIPORECTIF,
+ IF(c.code = 'ES', 1, 4) TERIDNIF,
+ s.nif TERNIF,
+ s.name TERNOM,
+ d.companyFk,
+ d.booked FECREGCON
+ FROM duaTax dt
+ JOIN dua d ON dt.duaFk = d.id
+ JOIN (SELECT account, rate
+ FROM
+ (SELECT rate, account
+ FROM invoiceInTaxBookingAccount ta
+ WHERE ta.effectived <= vBookDated
+ AND taxAreaFk = 'WORLD'
+ ORDER BY ta.effectived DESC
+ LIMIT 10000000000000000000
+ ) tba
+ GROUP BY rate
+ ) tr ON tr.rate = dt.rate
+ JOIN supplier s ON s.id = d.companyFk
+ JOIN country c ON c.id = s.countryFk
+ WHERE d.id = vDuaFk
+ GROUP BY dt.rate;
+
+ SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte
+ FROM XDiario
+ WHERE ASIEN = vBookNumber;
+
+ UPDATE XDiario
+ SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA,
+ EURODEBE = EURODEBE - vDiff
+ WHERE id = vApunte;
+
+ UPDATE dua
+ SET ASIEN = vBookNumber
+ WHERE id = vDuaFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/duaTax_doRecalc.sql b/db/routines/vn/procedures/duaTax_doRecalc.sql
new file mode 100644
index 000000000..e2d2b347f
--- /dev/null
+++ b/db/routines/vn/procedures/duaTax_doRecalc.sql
@@ -0,0 +1,54 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaTax_doRecalc`(vDuaFk INT)
+BEGIN
+/**
+ * Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry
+ *
+ * @param vDuaFk Id del dua a recalcular
+ */
+ DELETE FROM duaTax
+ WHERE duaFk = vDuaFk;
+
+ INSERT INTO duaTax(duaFk, taxClassFk, base)
+ SELECT vDuaFk, taxClassFk, SUM(sub.totalBase)
+ FROM intrastat ist
+ JOIN
+ (SELECT i.intrastatFk,
+ CAST(SUM(b.quantity *
+ b.buyingValue *
+ de.customsValue /
+ de.value)
+ * di.totalAmount /
+ bi.totalAmount AS DECIMAL(10,2)
+ ) totalBase
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN entry e ON e.id = b.entryFk
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN(
+ SELECT i.intrastatFk,
+ CAST(SUM(b.quantity *
+ b.buyingValue *
+ de.customsValue /
+ de.value) AS DECIMAL(10,2)
+ ) totalAmount
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN entry e ON e.id = b.entryFk
+ JOIN duaEntry de ON de.entryFk = e.id
+ WHERE de.duaFk = vDuaFk
+ GROUP BY i.intrastatFk
+ ) bi ON bi.intrastatFk = i.intrastatFk
+ JOIN(
+ SELECT intrastatFk, SUM(amount) totalAmount
+ FROM duaIntrastat
+ WHERE duaFk = vDuaFk
+ GROUP BY intrastatFK
+ ) di ON di.intrastatFk = i.intrastatFk
+ WHERE de.duaFk = vDuaFk
+ GROUP BY i.intrastatFk
+ HAVING totalBase
+ )sub ON ist.id = sub.intrastatFk
+ GROUP BY ist.taxClassFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ediTables_Update.sql b/db/routines/vn/procedures/ediTables_Update.sql
new file mode 100644
index 000000000..3f0c6df04
--- /dev/null
+++ b/db/routines/vn/procedures/ediTables_Update.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ediTables_Update`()
+BEGIN
+
+ INSERT IGNORE INTO vn.genus(name)
+ SELECT latin_genus_name
+ FROM edi.genus ;
+
+ INSERT IGNORE INTO vn.specie(name)
+ SELECT LCASE(latin_species_name)
+ FROM edi.specie ;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ektEntryAssign_setEntry.sql b/db/routines/vn/procedures/ektEntryAssign_setEntry.sql
new file mode 100644
index 000000000..d80215e37
--- /dev/null
+++ b/db/routines/vn/procedures/ektEntryAssign_setEntry.sql
@@ -0,0 +1,112 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ektEntryAssign_setEntry`()
+BEGIN
+
+DECLARE done INT DEFAULT FALSE;
+DECLARE vEntryFk INT;
+DECLARE vTravelFk INT;
+DECLARE vId INT;
+DECLARE vLanded DATE DEFAULT util.VN_CURDATE();
+
+DECLARE cur1 CURSOR FOR SELECT id FROM vn.ektEntryAssign;
+
+DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+ IF HOUR(util.VN_NOW()) > 12 THEN
+
+ SET vLanded = TIMESTAMPADD(DAY,1,vLanded);
+
+ END IF;
+
+OPEN cur1;
+
+ read_loop: LOOP
+
+ SET done = FALSE;
+ SET vEntryFk = 0;
+
+ FETCH cur1 INTO vId;
+
+ IF done THEN
+ LEAVE read_loop;
+ END IF;
+
+ SELECT IFNULL(e.id,0) INTO vEntryFk
+ FROM vn.entry e
+ JOIN vn.travel tr ON tr.id = e.travelFk
+ JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
+ AND ea.warehouseInFk = tr.warehouseInFk
+ AND ea.agencyModeFk = tr.agencyModeFk
+ AND ea.supplierFk = e.supplierFk
+ WHERE ea.id = vId
+ AND tr.landed = vLanded
+ LIMIT 1;
+
+ IF NOT vEntryFk THEN
+
+ SELECT IFNULL(e.id,0) INTO vEntryFk
+ FROM vn.entry e
+ JOIN vn.travel tr ON tr.id = e.travelFk
+ JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
+ AND ea.warehouseInFk = tr.warehouseInFk
+ AND ea.agencyModeFk = tr.agencyModeFk
+ WHERE ea.id = vId
+ AND tr.landed = vLanded
+ AND ea.supplierFk IS NULL
+ LIMIT 1;
+
+ END IF;
+
+ IF NOT vEntryFk THEN
+
+ SET vTravelFk = 0;
+
+ SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
+ FROM vn.travel tr
+ JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
+ AND ea.warehouseInFk = tr.warehouseInFk
+ AND ea.agencyModeFk = tr.agencyModeFk
+ WHERE ea.id = vId
+ AND tr.landed = vLanded;
+
+ IF NOT vTravelFk THEN
+
+ INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
+ SELECT vLanded, vLanded, warehouseInFk, warehouseOutFk, agencyModeFk
+ FROM vn.ektEntryAssign
+ WHERE id = vId;
+
+ SELECT MAX(tr.id) INTO vTravelFk
+ FROM vn.travel tr
+ JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
+ AND ea.warehouseInFk = tr.warehouseInFk
+ AND ea.agencyModeFk = tr.agencyModeFk
+ WHERE ea.id = vId
+ AND tr.landed = vLanded;
+
+ END IF;
+
+ INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk)
+ SELECT vTravelFk, IFNULL(ea.supplierFk,s.id), c.id, cu.id
+ FROM vn.supplier s
+ JOIN vn.company c ON c.code = 'VNL'
+ JOIN vn.currency cu ON cu.code = 'EUR'
+ JOIN vn.ektEntryAssign ea ON ea.id = vId
+ WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN';
+
+ SELECT MAX(id) INTO vEntryFk
+ FROM vn.entry
+ WHERE travelFk = vTravelFk;
+
+ END IF;
+
+ UPDATE vn.ektEntryAssign
+ SET entryFk = vEntryFk
+ WHERE id = vId;
+
+ END LOOP;
+
+ CLOSE cur1;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/energyMeter_record.sql b/db/routines/vn/procedures/energyMeter_record.sql
new file mode 100644
index 000000000..113f73e19
--- /dev/null
+++ b/db/routines/vn/procedures/energyMeter_record.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`energyMeter_record`(vInput INT, vActiveTime INT)
+BEGIN
+ DECLARE vConsumption INT;
+
+ SELECT consumption INTO vConsumption
+ FROM energyInput
+ WHERE input = vInput;
+
+ INSERT INTO vn.energyMeter
+ SET
+ `input` = vInput,
+ `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'),
+ `activeTime` = vActiveTime,
+ `consumption` = CAST(IFNULL((vConsumption / 3600) * vActiveTime, 0) AS DECIMAL(10,2))
+ ON DUPLICATE KEY UPDATE
+ `activeTime` = `activeTime` + vActiveTime,
+ `consumption` = `consumption` + CAST(VALUES(`consumption`) AS DECIMAL(10,2));
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entryDelivered.sql b/db/routines/vn/procedures/entryDelivered.sql
new file mode 100644
index 000000000..e948770e8
--- /dev/null
+++ b/db/routines/vn/procedures/entryDelivered.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entryDelivered`(vDated DATE, vEntryFk INT)
+BEGIN
+
+ DECLARE vTravelFk INT;
+
+ SELECT travelFk INTO vTravelFk
+ FROM vn.entry
+ WHERE id = vEntryFk;
+
+ IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN
+
+ UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated
+ WHERE id = vTravelFk;
+
+ ELSE
+
+ INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, ref, isDelivered, isReceived)
+ SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyModeFk, CONCAT(account.myUser_getName(),' ', vEntryFk), TRUE, TRUE
+ FROM vn.travel WHERE id = vTravelFk;
+
+ SELECT LAST_INSERT_ID() INTO vTravelFk;
+
+ UPDATE vn.entry
+ SET travelFk = vTravelFk
+ WHERE id = vEntryFk;
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entryWithItem.sql b/db/routines/vn/procedures/entryWithItem.sql
new file mode 100644
index 000000000..30dd99fbf
--- /dev/null
+++ b/db/routines/vn/procedures/entryWithItem.sql
@@ -0,0 +1,54 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entryWithItem`(vShipmentWarehouse INT, vLandingWarehouse INT,vSale INT, vVolume INT, netCost DECIMAL(10,2), vInOutDate DATE)
+BEGIN
+
+ DECLARE vTravel INT;
+ DECLARE vEntry INT;
+ DECLARE vBucket VARCHAR(10);
+ DECLARE vSupplierFk INT;
+
+ SET vSupplierFk = IF (vLandingWarehouse = 1, 850, 963);
+ -- seleccionamos travel
+ SELECT t.id, e.id INTO vTravel, vEntry
+ FROM travel t LEFT JOIN entry e ON t.id = e.travelFk
+ WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse
+ AND t.warehouseInFk = vLandingWarehouse AND t.agencyModeFk IS NULL AND e.supplierFk = vSupplierFk
+ LIMIT 1;
+
+ -- creamos el travel si es necesario
+ IF IFNULL(vTravel, FALSE) = FALSE THEN
+ INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk)
+ VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse);
+ SELECT LAST_INSERT_ID() INTO vTravel;
+ END IF;
+
+ -- creamos la Entrada si es necesario
+ IF IFNULL(vEntry, FALSE) = FALSE THEN
+ INSERT INTO entry (supplierFk, travelFk)
+ VALUES (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL'
+ SELECT LAST_INSERT_ID() INTO vEntry;
+ END IF;
+
+ -- creamos el cubo si es necesario
+ SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1;
+ IF vBucket IS NULL THEN
+ INSERT INTO packaging (id, volume)
+ VALUES (CONCAT('dm',vVolume/1000), vVolume);
+ -- SELECT LAST_INSERT_ID() INTO vBucket;
+ SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1;
+ END IF;
+
+ INSERT INTO buy(itemFk,quantity, entryFk, packagingFk, packing, stickers, buyingValue, price2, price3)
+ SELECT itemFk,
+ quantity,
+ vEntry,
+ vBucket,
+ 1 packing,
+ quantity,
+ netCost,
+ s.price,
+ s.price
+ FROM sale s
+ WHERE s.id = vSale;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_checkBooked.sql b/db/routines/vn/procedures/entry_checkBooked.sql
new file mode 100644
index 000000000..50990cd43
--- /dev/null
+++ b/db/routines/vn/procedures/entry_checkBooked.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_checkBooked`(
+ vSelf INT
+)
+BEGIN
+/**
+ * Comprueba si una entrada está contabilizada,
+ * y si lo está retorna un throw.
+ *
+ * @param vSelf Id de entrada
+ */
+ DECLARE vIsBooked BOOL;
+
+ SELECT isBooked INTO vIsBooked
+ FROM `entry`
+ WHERE id = vSelf;
+
+ IF vIsBooked THEN
+ CALL util.throw('Entry is already booked');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_checkPackaging.sql b/db/routines/vn/procedures/entry_checkPackaging.sql
new file mode 100644
index 000000000..7ba47b3d5
--- /dev/null
+++ b/db/routines/vn/procedures/entry_checkPackaging.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_checkPackaging`(vEntryFk INT)
+BEGIN
+/**
+ * Comprueba que los campos package y packaging no sean nulos
+ *
+ * @param vEntryFk Id de entrada
+ */
+ DECLARE vpackageOrPackingNull INT;
+
+ SELECT count(*) INTO vpackageOrPackingNull
+ FROM buy b
+ WHERE b.entryFk = vEntryFk
+ AND (b.packing IS NULL OR b.packagingFk IS NULL);
+
+ IF vpackageOrPackingNull THEN
+ CALL util.throw("packageOrPackingNull");
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_clone.sql b/db/routines/vn/procedures/entry_clone.sql
new file mode 100644
index 000000000..4f38447c8
--- /dev/null
+++ b/db/routines/vn/procedures/entry_clone.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_clone`(vSelf INT)
+BEGIN
+/**
+ * clones an entry.
+ *
+ * @param vSelf The entry id
+ */
+ DECLARE vNewEntryFk INT;
+
+ START TRANSACTION;
+
+ CALL entry_cloneHeader(vSelf, vNewEntryFk, NULL);
+ CALL entry_copyBuys(vSelf, vNewEntryFk);
+
+ COMMIT;
+
+ SELECT vNewEntryFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_cloneHeader.sql b/db/routines/vn/procedures/entry_cloneHeader.sql
new file mode 100644
index 000000000..6a6df9194
--- /dev/null
+++ b/db/routines/vn/procedures/entry_cloneHeader.sql
@@ -0,0 +1,42 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_cloneHeader`(
+ vSelf INT,
+ OUT vNewEntryFk INT,
+ vTravelFk INT
+)
+BEGIN
+/**
+ * Clones an entry header.
+ *
+ * @param vSelf The entry id
+ * @param vTravelFk Travel for the new entry or %NULL to use the source entry travel
+ * @param vNewEntryFk The new entry id
+ */
+ INSERT INTO entry(
+ travelFk,
+ supplierFk,
+ dated,
+ isExcludedFromAvailable,
+ isRaid,
+ commission,
+ currencyFk,
+ companyFk,
+ clonedFrom,
+ typeFk
+ )
+ SELECT IFNULL(vTravelFk, travelFk),
+ supplierFk,
+ dated,
+ isExcludedFromAvailable,
+ isRaid,
+ commission,
+ currencyFk,
+ companyFk,
+ vSelf,
+ typeFk
+ FROM entry
+ WHERE id = vSelf;
+
+ SET vNewEntryFk = LAST_INSERT_ID();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_cloneWithoutBuy.sql b/db/routines/vn/procedures/entry_cloneWithoutBuy.sql
new file mode 100644
index 000000000..8d75d8d51
--- /dev/null
+++ b/db/routines/vn/procedures/entry_cloneWithoutBuy.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_cloneWithoutBuy`(vSelf INT, OUT vNewEntryFk INT)
+BEGIN
+/**
+ * Clona una entrada sin compras
+ *
+ * @param vSelf Identificador de vn.entry
+ * @param vNewEntryFk Identificador de la nueva entrada
+ */
+ START TRANSACTION;
+
+ CALL entry_cloneHeader(vSelf, vNewEntryFk, NULL);
+
+ UPDATE entry d JOIN entry s ON s.id = vSelf
+ SET d.`reference` = s.`reference`,
+ d.loadPriority = s.loadPriority
+ WHERE d.id = vNewEntryFk;
+
+ COMMIT;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_copyBuys.sql b/db/routines/vn/procedures/entry_copyBuys.sql
new file mode 100644
index 000000000..a00fbc846
--- /dev/null
+++ b/db/routines/vn/procedures/entry_copyBuys.sql
@@ -0,0 +1,59 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_copyBuys`(vSelf INT, vCopyTo INT)
+BEGIN
+/**
+ * Copies an entry buys to another buy.
+ *
+ * @param vSelf The entry id
+ * @param vCopyTo The destination entry id
+ */
+ INSERT INTO buy(
+ entryFk,
+ itemFk,
+ quantity,
+ buyingValue,
+ freightValue,
+ isIgnored,
+ stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ isChecked,
+ location,
+ weight,
+ itemOriginalFk
+ )
+ SELECT vCopyTo,
+ itemFk,
+ quantity,
+ buyingValue,
+ freightValue,
+ isIgnored,
+ stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ isChecked,
+ location,
+ weight,
+ itemOriginalFk
+ FROM buy
+ WHERE entryFk = vSelf;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_fixMisfit.sql b/db/routines/vn/procedures/entry_fixMisfit.sql
new file mode 100644
index 000000000..3e57d362e
--- /dev/null
+++ b/db/routines/vn/procedures/entry_fixMisfit.sql
@@ -0,0 +1,65 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_fixMisfit`(
+ vSelf INT
+)
+BEGIN
+/**
+ * Arregla el descuadre de una entrada, agregando registros en vn.buy
+ * para compensar la diferencia * entre las etiquetas impresas y las esperadas
+ *
+ * @param vSelf Identificador de la entrada
+ */
+ INSERT INTO vn.buy(entryFk, itemFk)
+ SELECT vSelf, i.id
+ FROM vn.item i
+ WHERE i.description = 'MISFIT'
+ LIMIT 1;
+
+ INSERT INTO vn.buy(
+ entryFk,
+ itemFk,
+ quantity,
+ buyingValue,
+ freightValue,
+ isIgnored,
+ stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ location,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ weight)
+ SELECT vSelf,
+ itemFk,
+ SUM(CAST(printedStickers AS INT) - stickers) * packing quantity,
+ buyingValue,
+ freightValue,
+ TRUE isIgnored,
+ CAST(printedStickers AS INT) - stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ location,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ weight
+ FROM buy b
+ WHERE b.entryFk = vSelf
+ AND b.printedStickers <> b.stickers
+ GROUP BY itemFk
+ HAVING quantity;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_getRate.sql b/db/routines/vn/procedures/entry_getRate.sql
new file mode 100644
index 000000000..2220ef999
--- /dev/null
+++ b/db/routines/vn/procedures/entry_getRate.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_getRate`(vSelf INT)
+BEGIN
+/**
+ * Prepara una tabla con las tarifas aplicables en funcion de la fecha
+ * y el almacén
+ *
+ * @param vSelf Id de la tabla entry
+ * @return tmp.rate (rate0, rate1, rate2, rate3)
+ */
+ DECLARE vDated DATE;
+ DECLARE vWarehouseFk INT;
+
+ SELECT t.landed, t.warehouseInFk INTO vDated, vWarehouseFk
+ FROM entry e
+ JOIN travel t ON t.id = e.travelFk
+ WHERE e.id = vSelf;
+
+ CALL rate_getPrices(vDated, vWarehouseFk);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql
new file mode 100644
index 000000000..b82f273ae
--- /dev/null
+++ b/db/routines/vn/procedures/entry_getTransfer.sql
@@ -0,0 +1,206 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_getTransfer`(
+ vSelf INT
+)
+BEGIN
+/**
+ * Retorna los artículos trasladables a partir de una entrada.
+ *
+ * @param vSelf Id de entrada
+ */
+ DECLARE vDateShipped DATE;
+ DECLARE vDateLanded DATE;
+ DECLARE vWarehouseIn INT;
+ DECLARE vWarehouseOut INT;
+ DECLARE vCalcVisible INT;
+ DECLARE vInventoryDate DATE DEFAULT getInventoryDate();
+
+ SELECT shipped, landed, warehouseInFk, warehouseOutFk
+ INTO vDateShipped, vDateLanded, vWarehouseIn, vWarehouseOut
+ FROM travel t
+ JOIN entry e ON e.travelFk = t.id
+ WHERE e.id = vSelf;
+
+ CALL rate_getPrices(vDateShipped, vWarehouseIn);
+
+ -- Traslado en almacen origen
+ CREATE OR REPLACE TEMPORARY TABLE tBuy
+ (PRIMARY KEY (itemFk), INDEX(buyFk))
+ ENGINE = MEMORY
+ SELECT *
+ FROM (
+ SELECT b.itemFk, b.id buyFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vInventoryDate AND vDateShipped
+ AND NOT b.isIgnored
+ AND b.price2 >= 0
+ ORDER BY (vWarehouseOut = t.warehouseInFk) DESC, t.landed DESC
+ LIMIT 10000000000000000000
+ ) sub
+ GROUP BY itemFk;
+
+ IF vDateShipped >= util.VN_CURDATE() THEN
+ CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseOut);
+
+ CREATE OR REPLACE TEMPORARY TABLE tItem (
+ `itemFk` int(10) unsigned NOT NULL,
+ `visible` int(11) NOT NULL DEFAULT 0,
+ `available` int(11) NOT NULL DEFAULT 0,
+ `visibleLanding` int(11) NOT NULL DEFAULT 0,
+ `availableLanding` int(11) NOT NULL DEFAULT 0,
+ UNIQUE INDEX i USING HASH (itemFk)
+ ) ENGINE = MEMORY;
+
+ INSERT INTO tItem(itemFk, visible)
+ SELECT item_id itemFk, visible
+ FROM `cache`.visible
+ WHERE calc_id = vCalcVisible
+ AND visible;
+
+ CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseIn);
+
+ INSERT INTO tItem(itemFk, visibleLanding)
+ SELECT item_id, `visible`
+ FROM `cache`.`visible` v
+ WHERE v.calc_id = vCalcVisible
+ AND v.`visible`
+ ON DUPLICATE KEY UPDATE visibleLanding = v.`visible`;
+
+ CALL vn2008.availableTraslate(vWarehouseOut, vDateShipped, NULL);
+
+ INSERT INTO tItem(itemFk, available)
+ SELECT a.item_id, a.available
+ FROM vn2008.availableTraslate a
+ WHERE a.available
+ ON DUPLICATE KEY UPDATE available = a.available;
+
+ CALL vn2008.availableTraslate(vWarehouseIn, vDateLanded, vWarehouseOut);
+
+ INSERT INTO tItem(itemFk, availableLanding)
+ SELECT a.item_id, a.available
+ FROM vn2008.availableTraslate a
+ WHERE a.available
+ ON DUPLICATE KEY UPDATE availableLanding = a.available;
+ ELSE
+ CALL item_getStock(vWarehouseOut, vDateShipped, NULL);
+
+ CREATE OR REPLACE TEMPORARY TABLE tItem
+ (UNIQUE INDEX i USING HASH (itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk,
+ `visible`,
+ available,
+ 0 visibleLanding,
+ 0 availableLanding
+ FROM tmp.itemList;
+ END IF;
+
+ CALL buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded);
+
+ CREATE OR REPLACE TEMPORARY TABLE tTransfer
+ ENGINE = MEMORY
+ SELECT it.code `type`,
+ it.categoryFk,
+ i.typeFk,
+ i.id itemFk,
+ i.name item,
+ i.`size`,
+ i.category,
+ i.inkFk,
+ o.code originCode,
+ b2.quantity,
+ i.stems,
+ CAST(ti.visible AS DECIMAL(10,0)) vis1,
+ CAST(ti.available AS DECIMAL(10,0)) ava1,
+ CAST(ti.visibleLanding AS DECIMAL(10,0)) vis2,
+ CAST(ti.availableLanding AS DECIMAL(10,0)) ava2,
+ COALESCE(b2.`grouping`, b.`grouping`) `grouping`,
+ COALESCE(b2.packing, b.packing) packing,
+ COALESCE(b3.groupingMode, b2.groupingMode, b.groupingMode) package,
+ IFNULL(p.name, s.nickname) productor,
+ TRUE tinta,
+ b.packagingFk,
+ b2.id buyFk,
+ b2.stickers,
+ b.ektFk,
+ it.workerFk,
+ pa.volume,
+ IFNULL(pa.width, 0) width,
+ IFNULL(pa.`depth`, 0) `depth`,
+ IFNULL(pa.height, 0) height,
+ IFNULL(b.buyingValue, 0) buyingValue,
+ IFNULL(b.comissionValue, 0) comissionValue,
+ IFNULL(b.freightValue, 0) freightValue,
+ am.m3,
+ e.commission,
+ pa.isPackageReturnable,
+ IFNULL(pa2.value, pa.value) `value`,
+ r.rate3 r3,
+ r.rate2 r2,
+ it.promo,
+ b.`grouping` groupingOrigin,
+ b.packing packingOrigin,
+ b.id buyFkOrigin,
+ pa.returnCost,
+ b.weight
+ FROM item i
+ JOIN tItem ti ON ti.itemFk = i.id
+ LEFT JOIN producer p ON p.id = i.producerFk
+ LEFT JOIN itemType it ON it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN tBuy lb ON lb.itemFk = i.id
+ LEFT JOIN buy b ON b.id = lb.buyFk
+ LEFT JOIN packaging pa ON pa.id = b.packagingFk
+ LEFT JOIN entry e2 ON e2.id = b.entryFk
+ LEFT JOIN supplier s ON s.id = e2.supplierFk
+ LEFT JOIN entry e ON e.id = vSelf
+ LEFT JOIN travel tr ON tr.id = e.travelFk
+ LEFT JOIN agencyMode am ON am.id = tr.agencyModeFk
+ LEFT JOIN buy b2 ON b2.itemFk = i.id
+ AND b2.entryFk = vSelf
+ LEFT JOIN packaging pa2 ON pa2.id = b.packagingFk
+ LEFT JOIN tmp.rate r ON TRUE
+ LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id
+ LEFT JOIN buy b3 ON b3.id = bufi.buyFk
+ WHERE ic.display
+ AND NOT e.isRaid
+ AND (ti.visible OR ti.available)
+ ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name;
+
+ CREATE INDEX tIndex USING HASH ON tTransfer (itemFk);
+
+ SELECT *,
+ quantity - MOD(quantity , `grouping`) subQuantity,
+ MOD(quantity, `grouping`) soll,
+ ROUND((IF(volume > 0,volume, width * `depth` *
+ IF(height = 0, `size` + 10, height))) /
+ packing, 0) cm3,
+ buyingValue + comissionValue + freightValue cost,
+ @carriage := ROUND((IF(volume > 0, volume, width * `depth` *
+ IF(height = 0, `size` + 10, height))) *
+ m3 / 1000000 / Packing, 3) carriage,
+ @comission := ROUND((buyingValue + comissionValue + freightValue) *
+ commission / 100, 3) commission,
+ ROUND(@packaging := (returnCost + IF(isPackageReturnable, 0, value))
+ / packing, 3) packaging,
+ @cost := IFNULL((buyingValue + comissionValue + freightValue), 0) +
+ IFNULL(@packaging, 0) +
+ IFNULL(@carriage, 0) +
+ IFNULL(@comission, 0) expense,
+ @rate3 := ROUND(@cost / ( (100 - r3 - promo) / 100), 2) rate3,
+ ROUND(@rate3 * (1 + ((r2 - r3)/100)), 2) rate2,
+ FALSE selected
+ FROM tTransfer;
+
+ DROP TEMPORARY TABLE IF EXISTS
+ tTransfer,
+ tItem,
+ tBuy,
+ tmp.buyUltimateFromInterval,
+ tmp.rate,
+ tmp.itemList;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_lock.sql b/db/routines/vn/procedures/entry_lock.sql
new file mode 100644
index 000000000..8ec50323b
--- /dev/null
+++ b/db/routines/vn/procedures/entry_lock.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_lock`(vSelf INT)
+BEGIN
+/**
+ * Lock the indicated entry
+ * @vSelf params entry id
+ */
+ UPDATE `entry`
+ SET lockerUserFk = account.myUser_getId(),
+ locked = util.VN_NOW()
+ WHERE id = vSelf;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_moveNotPrinted.sql b/db/routines/vn/procedures/entry_moveNotPrinted.sql
new file mode 100644
index 000000000..526ae9d43
--- /dev/null
+++ b/db/routines/vn/procedures/entry_moveNotPrinted.sql
@@ -0,0 +1,177 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_moveNotPrinted`(vSelf INT,
+ vDays INT,
+ vChangeEntry BOOL,
+ OUT vNewEntryFk INT)
+BEGIN
+/**
+ * Crea una entrada a futuro y divide las lineas de buy de
+ * la entrada original en función de las etiquetas impresas
+ *
+ * @param vSelf Identificador de entry
+ * @param vDays Número de dias a futuro que se quiere la nueva entrada
+ * @param vChangeEntry Si se modifica la entrada original
+ *
+ * @return vNewEntryFk Identificador de la nueva entrada
+ */
+ DECLARE vNewTravelFk INT;
+ DECLARE vTravelFk INT;
+ DECLARE vInvoiceAmountOldEntryFk DECIMAL(10,2);
+ DECLARE vInvoiceAmountNewEntry DECIMAL(10,2);
+ DECLARE vIsOrdered BOOL;
+ DECLARE vIsConfirmed BOOL;
+ DECLARE vInvoiceNumber VARCHAR(50);
+ DECLARE vTypeFk VARCHAR(100);
+
+ SELECT travelFk, isOrdered, isConfirmed, invoiceNumber, typeFk INTO vTravelFk, vIsOrdered, vIsConfirmed, vInvoiceNumber, vTypeFk
+ FROM entry
+ WHERE id = vSelf;
+
+ CALL travel_clone(vTravelFk, vDays, vNewTravelFk);
+ CALL entry_cloneWithoutBuy(vSelf, vNewEntryFk);
+
+ UPDATE entry e
+ SET e.travelFk = vNewTravelFk,
+ e.evaNotes = CONCAT('No impresas de: ', vSelf, ' ', IFNULL(e.evaNotes,'')),
+ e.isOrdered = vIsOrdered,
+ e.isConfirmed = vIsConfirmed,
+ e.invoiceNumber = vInvoiceNumber,
+ e.typeFk = vTypeFk
+ WHERE e.id = vNewEntryFk;
+
+ IF vChangeEntry THEN
+ UPDATE buy b
+ SET b.entryFk = vNewEntryFk
+ WHERE b.printedStickers = 0
+ AND b.entryFk = vSelf;
+ END IF;
+
+ INSERT INTO buy(entryFk,
+ itemFk,
+ quantity,
+ buyingValue,
+ freightValue,
+ isIgnored,
+ stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ workerFk,
+ weight,
+ itemOriginalFk)
+ SELECT vNewEntryFk,
+ itemFk,
+ ((stickers - CAST(printedStickers AS INT)) * packing) quantity,
+ buyingValue,
+ freightValue,
+ isIgnored,
+ (stickers - CAST(printedStickers AS INT)) stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ workerFk,
+ weight,
+ itemOriginalFk
+ FROM buy b
+ WHERE b.entryFk = vSelf
+ AND b.printedStickers != b.stickers;
+
+ IF vChangeEntry THEN
+ UPDATE buy
+ SET stickers = printedStickers,
+ quantity = printedStickers * packing
+ WHERE entryFk = vSelf;
+ ELSE
+ INSERT INTO buy(entryFk, itemFk)
+ SELECT vSelf, i.id
+ FROM item i
+ WHERE i.description = 'MISFIT'
+ LIMIT 1;
+
+ INSERT INTO buy(entryFk,
+ itemFk,
+ quantity,
+ buyingValue,
+ freightValue,
+ isIgnored,
+ stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ location,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice)
+ SELECT vSelf,
+ itemFk,
+ (CAST(printedStickers AS INT) - stickers) * packing quantity,
+ buyingValue,
+ freightValue,
+ TRUE isIgnored,
+ CAST(printedStickers AS INT) - stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ location,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice
+ FROM buy
+ WHERE entryFk = vSelf
+ AND printedStickers != stickers;
+ END IF;
+
+ SELECT SUM(IFNULL(b.buyingValue * b.quantity, 0)) INTO vInvoiceAmountOldEntryFk
+ FROM buy b
+ WHERE b.entryFk = vSelf;
+
+ UPDATE entry e
+ JOIN buy b ON b.entryFk = e.id
+ SET e.reference = CONCAT(e.reference,'(1)'),
+ e.invoiceAmount = vInvoiceAmountOldEntryFk
+ WHERE e.id = vSelf;
+
+ SELECT SUM(IFNULL(b.buyingValue * b.quantity, 0)) INTO vInvoiceAmountNewEntry
+ FROM buy b
+ WHERE b.entryFk = vNewEntryFk;
+
+ UPDATE entry e
+ JOIN buy b ON b.entryFk = e.id
+ SET e.reference = CONCAT(e.reference,'(2)'),
+ e.invoiceAmount = vInvoiceAmountNewEntry
+ WHERE e.id = vNewEntryFk;
+
+ UPDATE entry
+ SET gestDocFk = (SELECT gestDocFk FROM entry WHERE id = vSelf LIMIT 1)
+ WHERE id = vNewEntryFk;
+
+ INSERT INTO duaEntry (duaFk, entryFk)
+ SELECT duaFk, vNewEntryFk FROM duaEntry WHERE entryFk = vSelf LIMIT 1;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_notifyChanged.sql b/db/routines/vn/procedures/entry_notifyChanged.sql
new file mode 100644
index 000000000..11e6fe4c0
--- /dev/null
+++ b/db/routines/vn/procedures/entry_notifyChanged.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_notifyChanged`(vSelf INT, vBuyFk INT, vOldValues VARCHAR(512), vNewValues VARCHAR(512))
+BEGIN
+ DECLARE vEmail VARCHAR(255);
+ DECLARE vFields VARCHAR(100);
+ DECLARE vMessage TEXT;
+
+ SELECT e.mailToNotify INTO vEmail
+ FROM entryConfig e
+ LIMIT 1;
+
+ SET vFields = CONCAT_WS(',',
+ 'entryFk',
+ 'itemFk',
+ 'quantity',
+ 'price1',
+ 'price2',
+ 'price3'
+ );
+ SET vMessage = util.formatTable(vFields, vOldValues, vNewValues);
+
+ CALL mail_insert(
+ vEmail,
+ NULL,
+ CONCAT(
+ 'Se ha modificado una línea de la entrada ', vSelf
+ ,' siendo inventario o anterior al mismo'
+ ),
+ vMessage
+ );
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_recalc.sql b/db/routines/vn/procedures/entry_recalc.sql
new file mode 100644
index 000000000..2410d380d
--- /dev/null
+++ b/db/routines/vn/procedures/entry_recalc.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_recalc`()
+BEGIN
+/**
+ * Comprueba que las ventas creadas entre un rango de fechas tienen componentes
+ *
+ * @param vCreatedFrom inicio del rango
+ * @param vCreatedTo fin del rango
+ */
+ DECLARE v_done BOOL DEFAULT FALSE;
+ DECLARE vEntryFk INTEGER;
+
+ DECLARE vCur CURSOR FOR
+ SELECT id FROM tmp.recalcEntryCommision;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET v_done = TRUE;
+
+ OPEN vCur;
+
+ l: LOOP
+ SET v_done = FALSE;
+ FETCH vCur INTO vEntryFk;
+
+ IF v_done THEN
+ LEAVE l;
+ END IF;
+
+ CALL vn2008.buy_tarifas_entry(vEntryFk);
+ END LOOP;
+
+ CLOSE vCur;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql
new file mode 100644
index 000000000..b7d9c77b3
--- /dev/null
+++ b/db/routines/vn/procedures/entry_splitByShelving.sql
@@ -0,0 +1,131 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_splitByShelving`(vShelvingFk VARCHAR(3), vFromEntryFk INT, vToEntryFk INT)
+BEGIN
+/**
+ * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula
+ *
+ * @param vShelvingFk Identificador de vn.shelving
+ * @param vFromEntryFk Entrada origen
+ * @param vToEntryFk Entrada destino
+ */
+ DECLARE vBuyFk INT;
+ DECLARE vIshStickers INT;
+ DECLARE vBuyStickers INT;
+ DECLARE vDone BOOLEAN DEFAULT FALSE;
+
+ DECLARE cur CURSOR FOR
+ SELECT bb.id buyFk,
+ FLOOR(ish.visible / ish.packing) ishStickers,
+ bb.stickers buyStickers
+ FROM vn.itemShelving ish
+ JOIN (SELECT b.id, b.itemFk, b.stickers
+ FROM vn.buy b
+ WHERE b.entryFk = vFromEntryFk
+ ORDER BY b.stickers DESC
+ LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
+ AND bb.stickers >= FLOOR(ish.visible / ish.packing)
+ WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci
+ GROUP BY ish.id;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ -- Cantidades de la matrícula que exceden la de las entradas
+ SELECT ish.itemFk,
+ i.longName,
+ FLOOR(ish.visible / ish.packing) AS etiEnMatricula,
+ bb.stickers etiEnEntrada
+ FROM vn.itemShelving ish
+ JOIN vn.item i ON i.id = ish.itemFk
+ LEFT JOIN (SELECT b.id, b.itemFk, b.stickers
+ FROM vn.buy b
+ WHERE b.entryFk = vFromEntryFk
+ ORDER BY b.stickers DESC
+ LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
+ WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci
+ AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing)
+ GROUP BY ish.id;
+
+ OPEN cur;
+
+ read_loop: LOOP
+ SET vDone = FALSE;
+
+ FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ IF vIshStickers = vBuyStickers THEN
+ UPDATE vn.buy
+ SET entryFk = vToEntryFk
+ WHERE id = vBuyFk;
+ ELSE
+ UPDATE vn.buy
+ SET stickers = stickers - vIshStickers,
+ quantity = stickers * packing
+ WHERE id = vBuyFk;
+
+ INSERT INTO vn.buy(entryFk,
+ itemFk,
+ quantity,
+ buyingValue,
+ freightValue,
+ isIgnored,
+ stickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ location,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ workerFk,
+ isChecked,
+ isPickedOff,
+ ektFk,
+ weight,
+ deliveryFk,
+ itemOriginalFk)
+ SELECT
+ vToEntryFk,
+ itemFk,
+ vIshStickers * packing,
+ buyingValue,
+ freightValue,
+ isIgnored,
+ vIshStickers,
+ packing,
+ `grouping`,
+ groupingMode,
+ containerFk,
+ comissionValue,
+ packageValue,
+ location,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ workerFk,
+ isChecked,
+ isPickedOff,
+ ektFk,
+ weight,
+ deliveryFk,
+ itemOriginalFk
+ FROM vn.buy
+ WHERE id = vBuyFk;
+
+ UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID();
+ END IF;
+ END LOOP;
+
+ CLOSE cur;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_splitMisfit.sql b/db/routines/vn/procedures/entry_splitMisfit.sql
new file mode 100644
index 000000000..476c52689
--- /dev/null
+++ b/db/routines/vn/procedures/entry_splitMisfit.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_splitMisfit`(vSelf INT)
+BEGIN
+
+ /* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original
+ * a la nueva
+ */
+
+ DECLARE vNewEntryFk INT;
+ DECLARE vBuyFk INT;
+
+ SELECT MAX(b.id) INTO vBuyFk
+ FROM vn.buy b
+ JOIN vn.item i ON i.id = b.itemFk
+ WHERE b.entryFk = vSelf
+ AND i.description = 'MISFIT';
+
+ INSERT INTO vn.entry(supplierFk, dated, travelFk, currencyFk, companyFk)
+ SELECT supplierFk, dated, travelFk, currencyFk, companyFk
+ FROM vn.entry e
+ WHERE e.id = vSelf;
+
+ SET vNewEntryFk = LAST_INSERT_ID();
+
+ UPDATE vn.buy b
+ SET b.entryFk = vNewEntryFk
+ WHERE b.entryFk = vSelf
+ AND b.id > vBuyFk;
+
+ SELECT vNewEntryFk;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_unlock.sql b/db/routines/vn/procedures/entry_unlock.sql
new file mode 100644
index 000000000..1dab48974
--- /dev/null
+++ b/db/routines/vn/procedures/entry_unlock.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_unlock`(vSelf INT)
+BEGIN
+/**
+ * Unlock the indicated entry
+ * @vSelf params entry id
+ */
+ UPDATE `entry`
+ SET lockerUserFk = NULL,
+ locked = NULL
+ WHERE id = vSelf;
+END$$
+DELIMITER ;
diff --git a/db/changes/232601/00-entry_updateComission.sql b/db/routines/vn/procedures/entry_updateComission.sql
similarity index 96%
rename from db/changes/232601/00-entry_updateComission.sql
rename to db/routines/vn/procedures/entry_updateComission.sql
index 5a25d72e8..1bef79bd3 100644
--- a/db/changes/232601/00-entry_updateComission.sql
+++ b/db/routines/vn/procedures/entry_updateComission.sql
@@ -1,5 +1,4 @@
DELIMITER $$
-$$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_updateComission`(vCurrency INT)
BEGIN
/**
@@ -32,9 +31,9 @@ BEGIN
SELECT util.notification_send(
'entry-update-comission',
JSON_OBJECT('currencyName', vCurrencyName, 'referenceCurrent', vComission),
- account.myUser_getId()
+ NULL
);
DROP TEMPORARY TABLE tmp.recalcEntryCommision;
END$$
-DELIMITER ;
\ No newline at end of file
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionGetFromRoute.sql b/db/routines/vn/procedures/expeditionGetFromRoute.sql
new file mode 100644
index 000000000..46c3c5d70
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionGetFromRoute.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionGetFromRoute`(
+ vExpeditionFk INT)
+BEGIN
+/**
+ * Get all expeditions from route
+ */
+ DECLARE vRouteFk INT DEFAULT 0;
+
+ SELECT t.routeFk INTO vRouteFk
+ FROM vn.expedition exp
+ INNER JOIN ticket t on t.id = exp.ticketFk
+ WHERE exp.id = vExpeditionFk;
+
+ SELECT exp.id,
+ exp.ticketFk,
+ t.routeFk,
+ t.packages bultos,
+ ts.alertLevel,
+ a.street,
+ a.city,
+ a.postalCode,
+ a.id addressFk,
+ w.name warehouse
+ FROM vn.expedition exp
+ INNER JOIN ticket t ON t.id = exp.ticketFk
+ INNER JOIN vn.ticketState ts ON ts.ticketFk = exp.ticketFk
+ LEFT JOIN vn.address a ON t.addressFk = a.id
+ LEFT JOIN vn.warehouse w ON t.warehouseFk = w.id
+ WHERE t.routeFk = vRouteFk AND exp.freightItemFk > 0;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionPallet_Del.sql b/db/routines/vn/procedures/expeditionPallet_Del.sql
new file mode 100644
index 000000000..451815ca0
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionPallet_Del.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionPallet_Del`(vPalletFk INT)
+BEGIN
+
+ DELETE FROM vn.expeditionPallet
+ WHERE id = vPalletFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionPallet_List.sql b/db/routines/vn/procedures/expeditionPallet_List.sql
new file mode 100644
index 000000000..db7cd6f0e
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionPallet_List.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionPallet_List`(vTruckFk INT)
+BEGIN
+
+ SELECT ep.id Pallet,
+ count(DISTINCT t.routeFk) Rutas,
+ count(DISTINCT e.id) Eti
+ FROM vn.expeditionPallet ep
+ LEFT JOIN vn.expeditionScan es ON es.palletFk = ep.id
+ LEFT JOIN vn.expedition e ON e.id = es.expeditionFk
+ LEFT JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE ep.truckFk = vTruckFk
+ GROUP BY ep.id;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionPallet_View.sql b/db/routines/vn/procedures/expeditionPallet_View.sql
new file mode 100644
index 000000000..fe410b2fb
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionPallet_View.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionPallet_View`(vPalletFk INT)
+BEGIN
+
+ SELECT ep.id Pallet,
+ t.routeFk Rutas,
+ count(*) Cajas
+ FROM vn.expeditionPallet ep
+ LEFT JOIN vn.expeditionScan es ON es.palletFk = ep.id
+ LEFT JOIN vn.expedition e ON e.id = es.expeditionFk
+ LEFT JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE ep.id = vPalletFk
+ GROUP BY t.routeFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionPallet_build.sql b/db/routines/vn/procedures/expeditionPallet_build.sql
new file mode 100644
index 000000000..9fbb60100
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionPallet_build.sql
@@ -0,0 +1,100 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionPallet_build`(IN vExpeditions JSON, IN vArcId INT, IN vWorkerFk INT, OUT vPalletFk INT)
+BEGIN
+/** Construye un pallet de expediciones.
+ *
+ * Primero comprueba si esas expediciones ya pertenecen a otro pallet,
+ * en cuyo caso actualiza ese pallet.
+ *
+ * @param vExpeditions JSON_ARRAY con esta estructura [exp1, exp2, exp3, ...]
+ * @param vArcId INT Identificador de vn.arcRead
+ * @param vWorkerFk INT Identificador de vn.worker
+ * @param out vPalletFk Identificador de vn.expeditionPallet
+ */
+ DECLARE vCounter INT;
+ DECLARE vExpeditionFk INT;
+ DECLARE vTruckFk INT;
+ DECLARE vPrinterFk INT;
+
+ DROP TEMPORARY TABLE IF EXISTS tExpedition;
+ CREATE TEMPORARY TABLE tExpedition
+ SELECT
+ e.id expeditionFk,
+ r.id routeFk,
+ ep.id palletFk
+ FROM
+ vn.expedition e,
+ vn.route r,
+ vn.expeditionPallet ep
+ LIMIT 0;
+
+ ALTER TABLE tExpedition ADD PRIMARY KEY (expeditionFk);
+
+ SET vCounter = JSON_LENGTH(vExpeditions);
+
+ WHILE vCounter DO
+ SET vCounter = vCounter - 1;
+
+ SET vExpeditionFk = JSON_EXTRACT(vExpeditions,CONCAT("$[", vCounter, "]"));
+
+ INSERT IGNORE INTO tExpedition(expeditionFk, routeFk, palletFk)
+ SELECT vExpeditionFk, t.routeFk, es.palletFk
+ FROM vn.expedition e
+ LEFT JOIN vn.ticket t ON t.id = e.ticketFk
+ LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id
+ WHERE e.id = vExpeditionFk;
+ END WHILE;
+
+ SELECT palletFk INTO vPalletFk
+ FROM (
+ SELECT palletFk, count(*) n
+ FROM tExpedition
+ WHERE palletFk > 0
+ GROUP BY palletFk
+ ORDER BY n DESC
+ LIMIT 100 ) sub
+ LIMIT 1;
+
+ IF vPalletFk IS NULL THEN
+ SELECT expeditionTruckFk
+ INTO vTruckFk
+ FROM (
+ SELECT rm.expeditionTruckFk, count(*) n
+ FROM vn.routesMonitor rm
+ JOIN tExpedition e ON e.routeFk = rm.routeFk
+ GROUP BY expeditionTruckFk
+ ORDER BY n DESC
+ LIMIT 1) sub;
+
+ IF vTruckFk IS NULL THEN
+ CALL util.throw ('TRUCK_NOT_AVAILABLE');
+ END IF;
+
+ INSERT INTO vn.expeditionPallet(truckFk)
+ VALUES(vTruckFk);
+
+ SET vPalletFk = LAST_INSERT_ID();
+ END IF;
+
+ INSERT INTO vn.expeditionScan(expeditionFk, palletFk, workerFk)
+ SELECT expeditionFk, vPalletFk, vWorkerFk
+ FROM tExpedition
+ ON DUPLICATE KEY UPDATE palletFk = vPalletFk, workerFk = vWorkerFk;
+
+ SELECT printerFk INTO vPrinterFk
+ FROM vn.arcRead
+ WHERE id = vArcId;
+
+ CALL vn.report_print(
+ 'LabelPalletExpedition',
+ vPrinterFk,
+ account.myUser_getId(),
+ JSON_OBJECT('palletFk', vPalletFk, 'userFk', account.myUser_getId()),
+ 'high'
+ );
+
+ UPDATE vn.expeditionPallet SET isPrint = TRUE WHERE id = vPalletFk;
+
+ DROP TEMPORARY TABLE tExpedition;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionPallet_printLabel.sql b/db/routines/vn/procedures/expeditionPallet_printLabel.sql
new file mode 100644
index 000000000..ada11daab
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionPallet_printLabel.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionPallet_printLabel`(vSelf INT)
+BEGIN
+/**
+ * Calls the report_print procedure and passes it
+ * the necessary parameters for printing.
+ *
+ * @param vSelf expeditioPallet id.
+ */
+ DECLARE vPrinterFk INT;
+ DECLARE vUserFk INT DEFAULT account.myUser_getId();
+
+ SELECT o.labelerFk INTO vPrinterFk
+ FROM operator o
+ WHERE o.workerFk = vUserFk;
+
+ CALL vn.report_print(
+ 'LabelPalletExpedition',
+ vPrinterFk,
+ account.myUser_getId(),
+ JSON_OBJECT('palletFk', vSelf, 'userFk', vUserFk),
+ 'high'
+ );
+
+ UPDATE vn.expeditionPallet
+ SET isPrint = TRUE
+ WHERE id = vSelf;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionScan_Add.sql b/db/routines/vn/procedures/expeditionScan_Add.sql
new file mode 100644
index 000000000..6ab19e8d0
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionScan_Add.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionScan_Add`(vPalletFk INT, vTruckFk INT)
+BEGIN
+
+ DECLARE vTotal INT DEFAULT 0;
+
+ IF vPalletFk = 0 THEN -- Nuevo pallet
+
+ INSERT INTO vn.expeditionPallet(truckFk)
+ VALUES(vTruckFk);
+
+ SELECT LAST_INSERT_ID() INTO vPalletFk;
+
+ END IF;
+
+ SELECT COUNT(expeditionFk) INTO vTotal FROM vn.expeditionScan WHERE palletFk = vPalletFk;
+
+ IF vTotal <> 0 THEN
+ SELECT expeditionFk,
+ palletFk
+ FROM vn.expeditionScan
+ WHERE palletFk = vPalletFk;
+ ELSE
+ SELECT 0 expeditionFk,vPalletFk palletFk;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionScan_Del.sql b/db/routines/vn/procedures/expeditionScan_Del.sql
new file mode 100644
index 000000000..ecbfdad4b
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionScan_Del.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionScan_Del`(vScanFk INT)
+BEGIN
+
+ DELETE FROM vn.expeditionScan
+ WHERE id = vScanFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionScan_List.sql b/db/routines/vn/procedures/expeditionScan_List.sql
new file mode 100644
index 000000000..b0d53053f
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionScan_List.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionScan_List`(vPalletFk INT)
+BEGIN
+
+ SELECT es.id,
+ t.routeFk Ruta,
+ t.id Ticket,
+ e.counter Caja,
+ es.expeditionFk
+ FROM vn.expeditionScan es
+ JOIN vn.expedition e ON e.id = es.expeditionFk
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE es.palletFk = vPalletFk
+ ORDER BY Ruta, Ticket, Caja;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionScan_Put.sql b/db/routines/vn/procedures/expeditionScan_Put.sql
new file mode 100644
index 000000000..9744a7cd7
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionScan_Put.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT)
+BEGIN
+
+ REPLACE vn.expeditionScan(expeditionFk, palletFk)
+ VALUES(vExpeditionFk, vPalletFk);
+
+ SELECT LAST_INSERT_ID() INTO vPalletFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionState_add.sql b/db/routines/vn/procedures/expeditionState_add.sql
new file mode 100644
index 000000000..299f11b04
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionState_add.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionState_add`(vParam INT, vStateCode VARCHAR(100))
+BEGIN
+
+ /**
+ * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro
+ *
+ * @param vParam Identificador de vn.expedition o de vn.route
+ * @param vStateCode Corresponde a vn.expeditionStateType.code
+ */
+
+ IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN
+
+ INSERT INTO vn.expeditionState(expeditionFk, typeFk)
+ SELECT e.id, est.id
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.expeditionStateType est ON est.code = vStateCode
+ WHERE t.routeFk = vParam;
+
+ ELSE
+
+ INSERT INTO vn.expeditionState(expeditionFk, typeFk)
+ SELECT vParam, est.id
+ FROM vn.expeditionStateType est
+ WHERE est.code = vStateCode;
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionState_addByAdress.sql b/db/routines/vn/procedures/expeditionState_addByAdress.sql
new file mode 100644
index 000000000..1d8de9745
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionState_addByAdress.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionState_addByAdress`(vAdressFk INT, vRouteFk INT, vStateCode VARCHAR(100))
+BEGIN
+
+ /**
+ * Inserta nuevos registros en la tabla vn.expeditionState
+ *
+ * @param vAdressFk Identificador de vn.ticket
+ * @param vRouteFk Identificador de vn.route
+ * @param vStateCode Corresponde a vn.expeditionStateType.code
+ */
+
+ INSERT INTO vn.expeditionState(expeditionFk, typeFk)
+ SELECT e.id, est.id
+ FROM vn.expedition e
+ JOIN vn.expeditionStateType est ON est.code = vStateCode
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE t.addressFk = vAdressFk AND t.routeFk = vRouteFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionState_addByExpedition.sql b/db/routines/vn/procedures/expeditionState_addByExpedition.sql
new file mode 100644
index 000000000..6fbc205e5
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionState_addByExpedition.sql
@@ -0,0 +1,18 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionState_addByExpedition`(vExpeditionFk INT, vStateCode VARCHAR(100))
+BEGIN
+
+ /**
+ * Inserta nuevos registros en la tabla vn.expeditionState
+ *
+ * @param vExpeditionFk Identificador de vn.expedition
+ * @param vStateCode Corresponde a vn.expeditionStateType.code
+ */
+
+ INSERT INTO vn.expeditionState(expeditionFk, typeFk)
+ SELECT vExpeditionFk, est.id
+ FROM vn.expeditionStateType est
+ WHERE est.code = vStateCode;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionState_addByPallet.sql b/db/routines/vn/procedures/expeditionState_addByPallet.sql
new file mode 100644
index 000000000..af99b444d
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionState_addByPallet.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionState_addByPallet`(vPalletFk INT, vStateCode VARCHAR(100))
+BEGIN
+/**
+ * Inserta nuevos registros en la tabla vn.expeditionState
+ *
+ * @param vPalletFk Identificador de vn.expedition
+ * @param vStateCode Corresponde a vn.expeditionStateType.code
+ */
+ DECLARE hasExpeditions BOOL;
+
+ DROP TEMPORARY TABLE IF EXISTS tExpeditionScan;
+ CREATE TEMPORARY TABLE tExpeditionScan
+ SELECT expeditionFk, est.id typeFk
+ FROM vn.expeditionScan e
+ JOIN vn.expeditionStateType est ON est.code = vStateCode
+ WHERE e.palletFk = vPalletFk;
+
+ SELECT COUNT(*) INTO hasExpeditions FROM tExpeditionScan;
+
+ IF NOT hasExpeditions THEN
+ DROP TEMPORARY TABLE tExpeditionScan;
+ CALL util.throw('palletDoesNotExist');
+ END IF;
+
+ INSERT INTO vn.expeditionState(expeditionFk, typeFk)
+ SELECT expeditionFk, typeFk
+ FROM tExpeditionScan;
+ DROP TEMPORARY TABLE tExpeditionScan;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionState_addByRoute.sql b/db/routines/vn/procedures/expeditionState_addByRoute.sql
new file mode 100644
index 000000000..5e438287b
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionState_addByRoute.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionState_addByRoute`(vRouteFk INT, vStateCode VARCHAR(100))
+BEGIN
+
+ /**
+ * Inserta nuevos registros en la tabla vn.expeditionState, por rutas
+ *
+ * @param vRouteFk Identificador de vn.route
+ * @param vStateCode Corresponde a vn.expeditionStateType.code
+ */
+
+ INSERT INTO vn.expeditionState(expeditionFk, typeFk)
+ SELECT e.id, est.id
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.expeditionStateType est ON est.code = vStateCode
+ WHERE t.routeFk = vRouteFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionTruck_Add.sql b/db/routines/vn/procedures/expeditionTruck_Add.sql
new file mode 100644
index 000000000..e4009ca47
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionTruck_Add.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionTruck_Add`(vHour VARCHAR(5), vDescription VARCHAR(45))
+BEGIN
+
+ INSERT INTO vn.expeditionTruck(eta,description)
+ VALUES(CONCAT(util.VN_CURDATE(), ' ', vHour), vDescription);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expeditionTruck_List.sql b/db/routines/vn/procedures/expeditionTruck_List.sql
new file mode 100644
index 000000000..2434f9274
--- /dev/null
+++ b/db/routines/vn/procedures/expeditionTruck_List.sql
@@ -0,0 +1,12 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionTruck_List`()
+BEGIN
+
+ SELECT id truckFk,
+ eta,
+ description Destino
+ FROM expeditionTruck
+ WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ ORDER BY eta;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expedition_StateGet.sql b/db/routines/vn/procedures/expedition_StateGet.sql
new file mode 100644
index 000000000..17fcf91e5
--- /dev/null
+++ b/db/routines/vn/procedures/expedition_StateGet.sql
@@ -0,0 +1,74 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expedition_StateGet`(vExpeditionFk INT)
+BEGIN
+
+ /* Devuelve una "ficha" con todos los datos relativos a la expedición
+ *
+ * param vExpeditionFk
+ */
+
+ DECLARE vTicketsPendientes INT;
+ DECLARE vEtiquetasTotales INT;
+ DECLARE vEtiquetasEscaneadas INT;
+ DECLARE vEtiquetasLeidasSorter INT;
+ DECLARE vRouteFk INT;
+
+ SELECT t.routeFk INTO vRouteFk
+ FROM vn.ticket t
+ JOIN vn.expedition e ON e.ticketFk = t.id
+ WHERE e.id = vExpeditionFk;
+
+ SELECT COUNT(*) INTO vTicketsPendientes
+ FROM vn.ticket t
+ LEFT JOIN vn.expedition e ON e.ticketFk = t.id
+ WHERE t.routeFk = vRouteFk
+ AND ISNULL(e.id);
+
+ SELECT COUNT(*) INTO vEtiquetasTotales
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE t.routeFk = vRouteFk;
+
+ SELECT COUNT(*) INTO vEtiquetasEscaneadas
+ FROM vn.expeditionScan es
+ JOIN vn.expedition e ON e.id = es.expeditionFk
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE t.routeFk = vRouteFk;
+
+ SELECT COUNT(*) INTO vEtiquetasLeidasSorter
+ FROM srt.expedition e
+ JOIN vn.expedition ve ON ve.id = e.id
+ LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id
+ JOIN vn.ticket t ON t.id = ve.ticketFk
+ WHERE t.routeFk = vRouteFk
+ AND e.created != e.updated
+ AND ISNULL(es.expeditionFk);
+
+
+ SELECT e.ticketFk ticket,
+ t.nickname cliente,
+ a.city ciudad,
+ p.name provincia,
+ z.name zonaTicket,
+ am.name zonaRuta,
+ t.routeFk ruta,
+ rm.beachFk ubicacion,
+ et.eta ,
+ et.description camion,
+ vTicketsPendientes AS ticketsPendientes,
+ vEtiquetasTotales AS etiquetasTotales,
+ vEtiquetasEscaneadas AS etiquetasEscaneadas,
+ vEtiquetasLeidasSorter AS etiquetasSorter
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.address a ON a.id = t.addressFk
+ JOIN vn.province p ON p.id = a.provinceFk
+ JOIN vn.`zone`z ON z.id = t.zoneFk
+ LEFT JOIN vn.route r ON r.id = t.routeFk
+ LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
+ LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
+ LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ WHERE e.id = vExpeditionFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expedition_getFromRoute.sql b/db/routines/vn/procedures/expedition_getFromRoute.sql
new file mode 100644
index 000000000..2b4de5662
--- /dev/null
+++ b/db/routines/vn/procedures/expedition_getFromRoute.sql
@@ -0,0 +1,39 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expedition_getFromRoute`(vRouteFk INT)
+BEGIN
+/**
+ * Obtiene las expediciones a partir de una ruta
+ * @param vRouteFk Id de la ruta
+ */
+ SELECT e.id,
+ e.ticketFk,
+ t.routeFk,
+ ts.alertLevel,
+ a.street,
+ a.city,
+ a.postalCode,
+ t.addressFk,
+ a.nickname,
+ sub2.itemPackingTypeConcat,
+ est.code
+ FROM expedition e
+ JOIN ticket t ON t.id = e.ticketFk
+ JOIN ticketState ts ON ts.ticketFk = e.ticketFk
+ JOIN address a ON t.addressFk = a.id
+ JOIN route r ON r.id = t.routeFk
+ LEFT JOIN warehouse w ON t.warehouseFk = w.id
+ LEFT JOIN (SELECT sub.ticketFk,
+ CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeConcat
+ FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ WHERE t.routeFk = vRouteFk
+ GROUP BY t.id,i.itemPackingTypeFk)sub
+ GROUP BY sub.ticketFk
+ ) sub2 ON sub2.ticketFk = t.id
+ LEFT JOIN expeditionStateType est ON est.id = e.stateTypeFk
+ WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE
+ ORDER BY r.created, t.priority DESC;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/expedition_getState.sql b/db/routines/vn/procedures/expedition_getState.sql
new file mode 100644
index 000000000..96e247e4d
--- /dev/null
+++ b/db/routines/vn/procedures/expedition_getState.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expedition_getState`(vExpeditionFk INT)
+BEGIN
+
+ DECLARE vTicketsPendientes INT;
+ DECLARE vEtiquetasTotales INT;
+ DECLARE vEtiquetasEscaneadas INT;
+ DECLARE vRouteFk INT;
+
+ SELECT t.routeFk INTO vRouteFk
+ FROM vn.ticket t
+ JOIN vn.expedition e ON e.ticketFk = t.id
+ WHERE e.id = vExpeditionFk;
+
+ SELECT COUNT(*) INTO vTicketsPendientes
+ FROM vn.ticket t
+ LEFT JOIN vn.expedition e ON e.ticketFk = t.id
+ WHERE t.routeFk = vRouteFk
+ AND ISNULL(e.id);
+
+ SELECT COUNT(*) INTO vEtiquetasTotales
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE t.routeFk = vRouteFk;
+
+ SELECT COUNT(*) INTO vEtiquetasEscaneadas
+ FROM vn.expeditionScan es
+ JOIN vn.expedition e ON e.id = es.expeditionFk
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE t.routeFk = vRouteFk;
+
+ SELECT e.ticketFk ticket,
+ t.nickname cliente,
+ a.city ciudad,
+ p.name provincia,
+ z.name zonaTicket,
+ am.name zonaRuta,
+ t.routeFk ruta,
+ rm.beachFk ubicacion,
+ et.eta ,
+ et.description camion,
+ vTicketsPendientes AS ticketsPendientes,
+ vEtiquetasTotales AS etiquetasTotales,
+ vEtiquetasEscaneadas AS etiquetasEscaneadas
+ FROM vn.expedition e
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ JOIN vn.address a ON a.id = t.addressFk
+ JOIN vn.province p ON p.id = a.provinceFk
+ JOIN vn.`zone`z ON z.id = t.zoneFk
+ LEFT JOIN vn.route r ON r.id = t.routeFk
+ LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
+ LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
+ LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ WHERE e.id = vExpeditionFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/freelance_getInfo.sql b/db/routines/vn/procedures/freelance_getInfo.sql
new file mode 100644
index 000000000..0f85ab4bd
--- /dev/null
+++ b/db/routines/vn/procedures/freelance_getInfo.sql
@@ -0,0 +1,14 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`freelance_getInfo`(workerFk INT)
+BEGIN
+ SELECT s.name, s.street, s.city, s.nif, s.postCode
+ FROM route r
+ JOIN agencyMode am ON r.agencyModeFk = am.id
+ JOIN agency a ON am.agencyFk = a.id
+ JOIN supplierAgencyTerm sat ON a.id = sat.agencyFk
+ JOIN supplier s ON sat.supplierFk = s.id
+ WHERE r.workerFk = workerFk
+ ORDER BY r.id DESC
+ LIMIT 1;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/fv_pca.sql b/db/routines/vn/procedures/fv_pca.sql
new file mode 100644
index 000000000..b8e7343ef
--- /dev/null
+++ b/db/routines/vn/procedures/fv_pca.sql
@@ -0,0 +1,101 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`fv_pca`()
+BEGIN
+
+DECLARE done INT DEFAULT FALSE;
+
+DECLARE vTicketFk INT;
+DECLARE vSaleFk INT;
+DECLARE vClonTicket INT DEFAULT 0;
+
+DECLARE cur1 CURSOR FOR
+SELECT s.ticketFk, s.id
+ FROM vn.sale s
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ WHERE t.shipped BETWEEN '2020-10-18' AND '2020-10-31'
+ AND it.code IN ('ANT','ANS','ORQ','TRO')
+ and t.warehouseFk = 1;
+
+DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+OPEN cur1;
+
+FETCH cur1 INTO vTicketFk, vSaleFk;
+
+ WHILE done = 0 DO
+
+ SELECT t.id INTO vClonTicket
+ FROM vn.ticket t
+ JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped)
+ WHERE t.warehouseFk = 44
+ LIMIT 1;
+
+ SELECT vTicketFk, vClonTicket;
+
+ IF vClonTicket = 0 THEN
+
+ INSERT INTO ticket (
+ clientFk,
+ shipped,
+ addressFk,
+ agencyModeFk,
+ nickname,
+ warehouseFk,
+ companyFk,
+ landed,
+ zoneFk,
+ zonePrice,
+ zoneBonus,
+ routeFk
+ )
+ SELECT
+ clientFk,
+ shipped,
+ addressFk,
+ agencyModeFk,
+ nickname,
+ 44,
+ companyFk,
+ landed,
+ zoneFk,
+ zonePrice,
+ zoneBonus,
+ routeFk
+
+ FROM ticket
+ WHERE id = vTicketFk;
+
+ SET vClonTicket = LAST_INSERT_ID();
+
+ SELECT 'lstID', vClonTicket;
+ /*
+ INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
+ SELECT vTicketFk, ao.observationTypeFk, ao.description
+ FROM addressObservation ao
+ JOIN ticket t ON t.addressFk = ao.addressFk
+ WHERE t.id = vClonTicket;
+*/
+ INSERT INTO ticketLog
+ SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert',
+ description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk);
+
+ END IF;
+
+ UPDATE vn.sale
+ SET ticketFk = vClonTicket
+ WHERE id = vSaleFk;
+
+ SET vClonTicket = 0;
+
+ SET done = 0;
+ FETCH cur1 INTO vTicketFk, vSaleFk;
+
+ END WHILE;
+
+ CLOSE cur1;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/getDayExpeditions.sql b/db/routines/vn/procedures/getDayExpeditions.sql
new file mode 100644
index 000000000..b708c8b0e
--- /dev/null
+++ b/db/routines/vn/procedures/getDayExpeditions.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`getDayExpeditions`()
+BEGIN
+
+ SELECT
+ e.id as expeditionFk,
+ date_format(e.created,'%Y-%m-%d') as expeditionDate,
+ e.ticketFk,
+ t.routeFk as routeFk
+ FROM expedition e
+ INNER JOIN ticket t ON t.id = e.ticketFk
+ WHERE DATE(e.created) = util.VN_CURDATE();
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/getInfoDelivery.sql b/db/routines/vn/procedures/getInfoDelivery.sql
new file mode 100644
index 000000000..c240560e9
--- /dev/null
+++ b/db/routines/vn/procedures/getInfoDelivery.sql
@@ -0,0 +1,10 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`getInfoDelivery`(vRouteFk INT)
+BEGIN
+ SELECT s.name, s.street, s.city, s.nif, s.postCode FROM vn.route r
+ JOIN vn.agencyMode am ON r.agencyModeFk = am.id
+ JOIN vn.agency a ON am.agencyFk = a.id
+ JOIN vn.supplier s ON a.supplierFk = s.id
+ WHERE r.id = vRouteFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/getPedidosInternos.sql b/db/routines/vn/procedures/getPedidosInternos.sql
new file mode 100644
index 000000000..973e110ef
--- /dev/null
+++ b/db/routines/vn/procedures/getPedidosInternos.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`getPedidosInternos`()
+BEGIN
+
+ SELECT id,name as description,upToDown as quantity FROM vn.item WHERE upToDown;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/getTaxBases.sql b/db/routines/vn/procedures/getTaxBases.sql
new file mode 100644
index 000000000..54932aa4f
--- /dev/null
+++ b/db/routines/vn/procedures/getTaxBases.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`getTaxBases`()
+BEGIN
+/**
+* Calcula y devuelve en número de bases imponibles postivas y negativas
+* Requiere la tabla temporal tmp.ticketToInvoice(id)
+*
+* returns tmp.taxBases
+*/
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
+ (KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT id ticketFk
+ FROM tmp.ticketToInvoice;
+
+ CALL ticket_getTax(NULL);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.taxBases;
+ CREATE TEMPORARY TABLE tmp.taxBases
+ ENGINE = MEMORY
+ SELECT
+ SUM(taxableBase > 0) as positive,
+ SUM(taxableBase < 0) as negative
+ FROM(
+ SELECT SUM(taxableBase) taxableBase
+ FROM tmp.ticketTax
+ GROUP BY pgcFk
+ ) t;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/greuge_add.sql b/db/routines/vn/procedures/greuge_add.sql
new file mode 100644
index 000000000..b2241ab83
--- /dev/null
+++ b/db/routines/vn/procedures/greuge_add.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`greuge_add`()
+BEGIN
+/**
+ * Group inserts into vn.greuge and then deletes the records just inserted
+ */
+ DECLARE vDated DATE;
+
+ SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL yearsToDelete YEAR) INTO vDated
+ FROM vn.greugeConfig;
+
+ INSERT INTO vn.greuge(clientFk, description, amount, shipped, created, greugeTypeFk)
+ SELECT clientFk, 'Suma agrupada', SUM(amount), MAX(shipped), MAX(created), greugeTypeFk
+ FROM vn.greuge
+ WHERE shipped <= vDated AND description <> 'Suma agrupada'
+ GROUP BY clientFk, greugeTypeFk;
+
+ DELETE
+ FROM vn.greuge
+ WHERE shipped <= vDated AND description <> 'Suma agrupada';
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/greuge_notifyEvents.sql b/db/routines/vn/procedures/greuge_notifyEvents.sql
new file mode 100644
index 000000000..ec00c1bde
--- /dev/null
+++ b/db/routines/vn/procedures/greuge_notifyEvents.sql
@@ -0,0 +1,72 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`greuge_notifyEvents`()
+BEGIN
+/**
+ * Notify to detect wrong greuges.
+ */
+ DECLARE vTimeStart DATETIME;
+ DECLARE vTimeEnd DATETIME;
+ DECLARE vMaxPercentToWrong DECIMAL(10,2);
+ DECLARE vJSON JSON;
+ DECLARE vArray JSON;
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vHasData BOOL DEFAULT FALSE;
+ DECLARE vCounter INT DEFAULT 0;
+ DECLARE myCur CURSOR FOR
+ SELECT JSON_OBJECT(
+ 'ticketId', g.ticketFk,
+ 'clientId', g.clientFk,
+ 'description', g.description,
+ 'amount', g.amount
+ )
+ FROM greuge g
+ JOIN greugeType gt ON gt.id = g.greugeTypeFk
+ JOIN ticket t ON t.id = g.ticketFk
+ WHERE g.created BETWEEN vTimeStart AND util.dayEnd(vTimeEnd)
+ AND g.amount > (t.totalWithVat * (vMaxPercentToWrong / 100))
+ AND gt.code = 'freightDifference'
+ AND SIGN(t.totalWithVat)
+ ORDER BY g.clientFk;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SELECT IFNULL(DATE(lastNotifyCheck), util.VN_CURDATE()) INTO vTimeStart
+ FROM greugeConfig;
+
+ SET vTimeEnd = util.VN_NOW();
+
+ SELECT maxPercentToWrong INTO vMaxPercentToWrong
+ FROM greugeConfig
+ LIMIT 1;
+
+ IF vMaxPercentToWrong IS NULL THEN
+ CALL util.throw('Greuge max percent to wrong is not configured');
+ END IF;
+
+ SET vArray = JSON_ARRAY();
+
+ OPEN myCur;
+ myCur: LOOP
+ FETCH myCur INTO vJSON;
+
+ IF vDone THEN
+ LEAVE myCur;
+ END IF;
+
+ SET vArray = JSON_MERGE(vArray, vJSON);
+ SET vCounter = vCounter + 1;
+ SET vHasData = TRUE;
+ END LOOP;
+ CLOSE myCur;
+
+ IF vHasData THEN
+ SELECT util.notification_send(
+ 'greuge-wrong',
+ JSON_OBJECT('tickets', JSON_EXTRACT(vArray, '$')),
+ account.myUser_getId()
+ );
+ END IF;
+
+ UPDATE greugeConfig
+ SET lastNotifyCheck = vTimeEnd;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/inventoryFailureAdd.sql b/db/routines/vn/procedures/inventoryFailureAdd.sql
new file mode 100644
index 000000000..38765cbda
--- /dev/null
+++ b/db/routines/vn/procedures/inventoryFailureAdd.sql
@@ -0,0 +1,48 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryFailureAdd`()
+BEGIN
+
+DECLARE done BOOL DEFAULT FALSE;
+DECLARE vTicketFk INT;
+
+DECLARE rs CURSOR FOR
+ SELECT id FROM vn.ticket
+ WHERE shipped = util.yesterday()
+ AND clientFk = 400
+ AND warehouseFk IN (1,44);
+
+DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+OPEN rs;
+
+FETCH rs INTO vTicketFk;
+
+WHILE NOT done DO
+
+ INSERT INTO vn.inventoryFailure(dated, itemFk, quantity, value, warehouseFk, throwerFk)
+ SELECT t.shipped,
+ s.itemFk,
+ s.quantity,
+ b.buyingValue + b.freightValue + b.packageValue + b.comissionValue,
+ t.warehouseFk,
+ w.id
+ FROM vn.ticket t
+ JOIN vn.sale s ON s.ticketFk = t.id
+ LEFT JOIN cache.last_buy lb ON lb.warehouse_id = t.warehouseFk AND item_id = s.itemFk
+ LEFT JOIN vn.buy b ON b.id = lb.buy_id
+ LEFT JOIN vn.worker w ON w.code = LEFT(s.concept, 3)
+ WHERE t.id = vTicketFk
+ AND s.quantity > 0;
+
+ FETCH rs INTO vTicketFk;
+
+END WHILE;
+
+
+CLOSE rs;
+
+
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/inventoryMake.sql b/db/routines/vn/procedures/inventoryMake.sql
new file mode 100644
index 000000000..a40093679
--- /dev/null
+++ b/db/routines/vn/procedures/inventoryMake.sql
@@ -0,0 +1,269 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryMake`(vInventoryDate DATE)
+BEGIN
+/**
+* Recalculate the inventories
+*
+* @param vInventoryDate date for the new inventory
+*/
+ DECLARE vDone BOOL;
+ DECLARE vEntryFk INT;
+ DECLARE vTravelFk INT;
+ DECLARE vDateLastInventory DATE;
+ DECLARE vDateYesterday DATETIME DEFAULT vInventoryDate - INTERVAL 1 SECOND;
+ DECLARE vWarehouseOutFkInventory INT;
+ DECLARE vInventorySupplierFk INT;
+ DECLARE vAgencyModeFkInventory INT;
+ DECLARE vMaxRecentInventories INT;
+ DECLARE vWarehouseFk INT;
+
+ DECLARE cWarehouses CURSOR FOR
+ SELECT id
+ FROM warehouse
+ WHERE isInventory;
+
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SELECT inventorySupplierFk INTO vInventorySupplierFk FROM entryConfig LIMIT 1;
+ SELECT inventoried INTO vDateLastInventory FROM config LIMIT 1;
+ SELECT maxRecentInventories,
+ warehouseOutFk,
+ agencyModeFk
+ INTO vMaxRecentInventories,
+ vWarehouseOutFkInventory,
+ vAgencyModeFkInventory
+ FROM inventoryConfig
+ LIMIT 1;
+
+ IF vDateLastInventory IS NULL
+ OR vInventorySupplierFk IS NULL
+ OR vMaxRecentInventories IS NULL
+ OR vInventoryDate IS NULL
+ OR vWarehouseOutFkInventory IS NULL
+ OR vAgencyModeFkInventory IS NULL THEN
+ CALL util.throw('Some config parameters are not set');
+ END IF;
+
+ START TRANSACTION;
+
+ OPEN cWarehouses;
+ -- Environment variable to disable the triggers of the affected tables
+ SET @isModeInventory := TRUE;
+ l: LOOP
+ SET vDone = FALSE;
+ SET vEntryFk = NULL;
+ SET vTravelFk = NULL;
+
+ FETCH cWarehouses INTO vWarehouseFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ -- Generate travel, if it does not exist
+ SELECT id INTO vTravelFk
+ FROM travel
+ WHERE warehouseOutFk = vWarehouseOutFkInventory
+ AND warehouseInFk = vWarehouseFk
+ AND landed = vInventoryDate
+ AND agencyModeFk = vAgencyModeFkInventory
+ AND ref = 'inventario'
+ LIMIT 1;
+
+ IF vTravelFk IS NULL THEN
+ INSERT INTO travel
+ SET warehouseOutFk = vWarehouseOutFkInventory,
+ warehouseInFk = vWarehouseFk,
+ shipped = vInventoryDate,
+ landed = vInventoryDate,
+ agencyModeFk = vAgencyModeFkInventory,
+ ref = 'inventario',
+ isDelivered = TRUE,
+ isReceived = TRUE;
+
+ SELECT LAST_INSERT_ID() INTO vTravelFk;
+ END IF;
+
+ -- Generate an entry if it does not exist, or we empty it
+ SELECT id INTO vEntryFk
+ FROM entry
+ WHERE supplierFk = vInventorySupplierFk
+ AND travelFk = vTravelFk;
+
+ IF vEntryFk IS NULL THEN
+ INSERT INTO entry
+ SET supplierFk = vInventorySupplierFk,
+ isConfirmed = TRUE,
+ isOrdered = TRUE,
+ travelFk = vTravelFk;
+
+ SELECT LAST_INSERT_ID() INTO vEntryFk;
+ ELSE
+ DELETE FROM buy WHERE entryFk = vEntryFk;
+ END IF;
+
+ -- Prepare the auxiliary table
+ CREATE OR REPLACE TEMPORARY TABLE tInventory (
+ itemFk INT(11) NOT NULL PRIMARY KEY,
+ quantity int(11) DEFAULT '0',
+ buyingValue decimal(10,4) DEFAULT '0.0000',
+ freightValue decimal(10,3) DEFAULT '0.000',
+ packing int(11) DEFAULT '1',
+ `grouping` smallint(5) unsigned NOT NULL DEFAULT '1',
+ groupingMode tinyint(4) NOT NULL DEFAULT 0 ,
+ comissionValue decimal(10,3) DEFAULT '0.000',
+ packageValue decimal(10,3) DEFAULT '0.000',
+ packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--',
+ price1 decimal(10,2) DEFAULT '0.00',
+ price2 decimal(10,2) DEFAULT '0.00',
+ price3 decimal(10,2) DEFAULT '0.00',
+ minPrice decimal(10,2) DEFAULT '0.00',
+ producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
+ INDEX (itemFK)
+ ) ENGINE = MEMORY;
+
+ -- Buys
+ INSERT INTO tInventory(itemFk, quantity)
+ SELECT b.itemFk, SUM(b.quantity)
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ WHERE tr.warehouseInFk = vWarehouseFk
+ AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday
+ AND NOT isRaid
+ GROUP BY b.itemFk;
+
+ -- Transfers
+ INSERT INTO tInventory(itemFk, quantity)
+ SELECT itemFk, quantityOut
+ FROM (
+ SELECT b.itemFk,- SUM(b.quantity) quantityOut
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ WHERE tr.warehouseOutFk = vWarehouseFk
+ AND tr.shipped BETWEEN vDateLastInventory AND vDateYesterday
+ AND NOT isRaid
+ GROUP BY b.itemFk
+ ) sub
+ ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut;
+
+ -- Sales
+ INSERT INTO tInventory(itemFk, quantity)
+ SELECT itemFk, saleOut
+ FROM (
+ SELECT s.itemFk, - SUM(s.quantity) saleOut
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE t.warehouseFk = vWarehouseFk
+ AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday
+ GROUP BY s.itemFk
+ ) sub
+ ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut;
+
+ -- Update values of the last purchase
+ UPDATE tInventory inv
+ JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWarehouseFk
+ JOIN buy b ON b.id = lb.buy_id
+ JOIN item i ON i.id = b.itemFk
+ LEFT JOIN producer p ON p.id = i.producerFk
+ SET inv.buyingValue = b.buyingValue,
+ inv.freightValue = b.freightValue,
+ inv.packing = b.packing,
+ inv.`grouping`= b.`grouping`,
+ inv.groupingMode = b.groupingMode,
+ inv.comissionValue = b.comissionValue,
+ inv.packageValue = b.packageValue,
+ inv.packageFk = b.packagingFk,
+ inv.price1 = b.price1,
+ inv.price2 = b.price2,
+ inv.price3 = b.price3,
+ inv.minPrice = b.minPrice,
+ inv.producer = p.name;
+
+ INSERT INTO buy(itemFk,
+ quantity,
+ buyingValue,
+ freightValue,
+ packing,
+ `grouping`,
+ groupingMode,
+ comissionValue,
+ packageValue,
+ packagingFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ entryFk)
+ SELECT itemFk,
+ GREATEST(quantity, 0),
+ buyingValue,
+ freightValue,
+ packing,
+ `grouping`,
+ groupingMode,
+ comissionValue,
+ packageValue,
+ packageFk,
+ price1,
+ price2,
+ price3,
+ minPrice,
+ vEntryFk
+ FROM tInventory;
+
+ -- Update the 'lastUsed' field of the item
+ UPDATE item i
+ JOIN tInventory i2 ON i2.itemFk = i.id
+ SET i.lastUsed = NOW()
+ WHERE i2.quantity;
+
+ DROP TEMPORARY TABLE tInventory;
+
+ END LOOP;
+
+ CLOSE cWarehouses;
+
+ UPDATE config SET inventoried = vInventoryDate;
+
+ SET @isModeInventory := FALSE;
+
+ CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete
+ (INDEX(entryId)) ENGINE = MEMORY
+ SELECT e.id entryId,
+ t.id travelId
+ FROM travel t
+ JOIN `entry` e ON e.travelFk = t.id
+ JOIN (
+ SELECT t.shipped
+ FROM travel t
+ JOIN `entry` e ON e.travelFk = t.id
+ WHERE e.supplierFk = vInventorySupplierFk
+ AND t.shipped <= vInventoryDate
+ GROUP BY t.shipped
+ ORDER BY t.shipped DESC
+ OFFSET vMaxRecentInventories ROWS
+ ) sub
+ WHERE e.supplierFk = vInventorySupplierFk
+ AND t.shipped IN (sub.shipped);
+
+ DELETE e
+ FROM `entry` e
+ JOIN tEntryToDelete tmp ON tmp.entryId = e.id;
+
+ DELETE IGNORE t
+ FROM travel t
+ JOIN tEntryToDelete tmp ON tmp.travelId = t.id;
+
+ DROP TEMPORARY TABLE IF EXISTS tEntryToDelete;
+
+ COMMIT;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/inventoryMakeLauncher.sql b/db/routines/vn/procedures/inventoryMakeLauncher.sql
new file mode 100644
index 000000000..717e3c163
--- /dev/null
+++ b/db/routines/vn/procedures/inventoryMakeLauncher.sql
@@ -0,0 +1,12 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryMakeLauncher`()
+BEGIN
+/**
+ * Recalculate the inventories of all warehouses
+ */
+ CALL inventoryMake(
+ util.VN_CURDATE() -
+ INTERVAL (SELECT daysInPastForInventory FROM inventoryConfig LIMIT 1) DAY
+ );
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/inventory_repair.sql b/db/routines/vn/procedures/inventory_repair.sql
new file mode 100644
index 000000000..93527d84b
--- /dev/null
+++ b/db/routines/vn/procedures/inventory_repair.sql
@@ -0,0 +1,106 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventory_repair`()
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.lastEntry;
+ CREATE TEMPORARY TABLE tmp.lastEntry
+ (PRIMARY KEY (buyFk))
+ SELECT
+ i.id AS itemFk,
+ w.id AS warehouseFk,
+ w.name AS warehouse,
+ tr.landed,
+ b.id AS buyFk,
+ b.entryFk,
+ b.isIgnored,
+ b.price2,
+ b.price3,
+ b.stickers,
+ b.packing,
+ b.grouping,
+ b.groupingMode,
+ b.weight,
+ i.stems,
+ b.quantity,
+ b.buyingValue,
+ b.packagingFk ,
+ s.id AS supplierFk,
+ s.name AS supplier
+ FROM itemType it
+ RIGHT JOIN (entry e
+ LEFT JOIN supplier s ON s.id = e.supplierFk
+ RIGHT JOIN buy b ON b.entryFk = e.id
+ LEFT JOIN item i ON i.id = b.itemFk
+ LEFT JOIN ink ON ink.id = i.inkFk
+ LEFT JOIN travel tr ON tr.id = e.travelFk
+ LEFT JOIN warehouse w ON w.id = tr.warehouseInFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ ) ON it.id = i.typeFk
+ LEFT JOIN edi.ekt ek ON b.ektFk = ek.id
+ WHERE (b.packagingFk = "--" OR b.price2 = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO';
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk;
+ CREATE TEMPORARY TABLE tmp.lastEntryOk
+ (PRIMARY KEY (buyFk))
+ SELECT
+ i.id AS itemFk,
+ w.id AS warehouseFk,
+ w.name AS warehouse,
+ tr.landed,
+ b.id AS buyFk,
+ b.entryFk,
+ b.isIgnored,
+ b.price2,
+ b.price3,
+ b.stickers,
+ b.packing,
+ b.grouping,
+ b.groupingMode,
+ b.weight,
+ i.stems,
+ b.quantity,
+ b.buyingValue,
+ b.packagingFk,
+ s.id AS supplierFk,
+ s.name AS supplier
+ FROM itemType it
+ RIGHT JOIN (entry e
+ LEFT JOIN supplier s ON s.id = e.supplierFk
+ RIGHT JOIN buy b ON b.entryFk = e.id
+ LEFT JOIN item i ON i.id = b.itemFk
+ LEFT JOIN ink ON ink.id = i.inkFk
+ LEFT JOIN travel tr ON tr.id = e.travelFk
+ LEFT JOIN warehouse w ON w.id = tr.warehouseInFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ ) ON it.id = i.typeFk
+ LEFT JOIN edi.ekt ek ON b.ektFk = ek.id
+ WHERE b.packagingFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE()))
+ ORDER BY tr.landed DESC;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup;
+ CREATE TEMPORARY TABLE tmp.lastEntryOkGroup
+ (INDEX (warehouseFk,itemFk))
+ SELECT *
+ FROM tmp.lastEntryOk tmp
+ GROUP BY tmp.itemFk,tmp.warehouseFk;
+
+ UPDATE buy b
+ JOIN tmp.lastEntry lt ON lt.buyFk = b.id
+ JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
+ SET b.packagingFk = eo.packagingFk WHERE b.packagingFk = "--";
+
+ UPDATE buy b
+ JOIN tmp.lastEntry lt ON lt.buyFk = b.id
+ JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
+ SET b.price2 = eo.price2 WHERE b.price2 = 0 ;
+
+ UPDATE buy b
+ JOIN tmp.lastEntry lt ON lt.buyFk = b.id
+ JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
+ SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0;
+
+ DROP TEMPORARY TABLE tmp.lastEntry;
+ DROP TEMPORARY TABLE tmp.lastEntryOk;
+ DROP TEMPORARY TABLE tmp.lastEntryOkGroup;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceExpenseMake.sql b/db/routines/vn/procedures/invoiceExpenseMake.sql
new file mode 100644
index 000000000..a1fe69ff5
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceExpenseMake.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceExpenseMake`(IN vInvoice INT)
+BEGIN
+/* Inserta las partidas de gasto correspondientes a la factura
+ * REQUIERE tabla tmp.ticketToInvoice
+ * @param vInvoice Numero de factura
+ */
+ DELETE FROM invoiceOutExpense
+ WHERE invoiceOutFk = vInvoice;
+
+ INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount)
+ SELECT vInvoice,
+ expenseFk,
+ SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount
+ FROM tmp.ticketToInvoice t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ GROUP BY i.expenseFk
+ HAVING amount != 0;
+
+ INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount)
+ SELECT vInvoice,
+ tst.expenseFk,
+ SUM(ROUND(ts.quantity * ts.price ,2)) amount
+ FROM tmp.ticketToInvoice t
+ JOIN ticketService ts ON ts.ticketFk = t.id
+ JOIN ticketServiceType tst ON tst.id = ts.ticketServiceTypeFk
+ HAVING amount != 0;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceFromAddress.sql b/db/routines/vn/procedures/invoiceFromAddress.sql
new file mode 100644
index 000000000..bde7afd8c
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceFromAddress.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceFromAddress`(vMaxTicketDate DATETIME,vAddress INT,vCompany INT)
+BEGIN
+
+ DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(MONTH, -3, util.VN_CURDATE());
+
+ SET vMaxTicketDate = util.dayEnd(vMaxTicketDate);
+
+ DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
+
+ CREATE TEMPORARY TABLE `tmp.``ticketToInvoice`
+ (PRIMARY KEY (`id`))
+ ENGINE = MEMORY
+ SELECT Id_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 ;
diff --git a/db/routines/vn/procedures/invoiceFromClient.sql b/db/routines/vn/procedures/invoiceFromClient.sql
new file mode 100644
index 000000000..29cee5d4f
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceFromClient.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceFromClient`(
+ IN vMaxTicketDate datetime,
+ IN vClientFk INT,
+ IN vCompanyFk INT)
+BEGIN
+ DECLARE vMinTicketDate DATE;
+
+ SET vMinTicketDate = util.firstDayOfYear(vMaxTicketDate - INTERVAL 1 YEAR);
+ SET vMaxTicketDate = util.dayend(vMaxTicketDate);
+
+ DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
+ CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice`
+ (PRIMARY KEY (`id`))
+ ENGINE = MEMORY
+ SELECT id FROM ticket t
+ WHERE t.clientFk = vClientFk
+ AND t.refFk IS NULL
+ AND t.companyFk = vCompanyFk
+ AND t.shipped BETWEEN vMinTicketDate AND vMaxTicketDate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceFromTicket.sql b/db/routines/vn/procedures/invoiceFromTicket.sql
new file mode 100644
index 000000000..e5ea00e62
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceFromTicket.sql
@@ -0,0 +1,14 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceFromTicket`(IN vTicket INT)
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
+
+ CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice`
+ (PRIMARY KEY (`id`))
+ ENGINE = MEMORY
+ SELECT id FROM vn.ticket
+ WHERE id = vTicket AND refFk IS NULL;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceInDueDay_calculate.sql b/db/routines/vn/procedures/invoiceInDueDay_calculate.sql
new file mode 100644
index 000000000..e51b5f64d
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInDueDay_calculate.sql
@@ -0,0 +1,73 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInDueDay_calculate`(vInvoiceInFk INT)
+BEGIN
+/**
+ * Calcula los vctos. de una factura recibida
+ * En caso de haberlos informado previamente o que el proveedor sea español, no los recalculará
+ *
+ * @param vInvoiceInFk Factura recibida
+ */
+ DECLARE vCompanyCountryCode VARCHAR(3);
+ DECLARE vHasDueDayTax BOOL;
+ DECLARE vHasDueDay BOOL;
+
+ SELECT c.code, IFNULL(a.isUeeMember, TRUE AND co.code ='ES')
+ INTO vCompanyCountryCode, vHasDueDayTax
+ FROM invoiceIn ii
+ JOIN supplier su ON su.id = ii.companyFk
+ LEFT JOIN country c ON c.id = su.countryFk
+ LEFT JOIN supplier s ON s.id = ii.supplierFk
+ LEFT JOIN country co ON co.id = s.countryFk
+ LEFT JOIN province p ON p.id = s.provinceFk
+ LEFT JOIN autonomy a ON a.id = p.autonomyFk
+ WHERE ii.id = vInvoiceInFk;
+
+ SELECT COUNT(*) INTO vHasDueDay
+ FROM invoiceInDueDay iid
+ WHERE iid.invoiceInFk = vInvoiceInFk;
+
+ IF NOT vHasDueDay AND vCompanyCountryCode = 'ES' THEN
+
+ SET @cont := 0;
+ INSERT INTO invoiceInDueDay (
+ invoiceInFk,
+ dueDated,
+ amount,
+ foreignValue
+ )
+ SELECT vInvoiceInFk,
+ IF(payDay,
+ IF(getNextDueDate(issued, pdd.detail, payDay) < created,
+ created,
+ getNextDueDate(issued, pdd.detail, payDay)),
+ GREATEST(created, issued + INTERVAL pdd.detail DAY)),
+ IF((@cont := @cont + 1) < cont,
+ TRUNCATE(venc / cont, 2),
+ venc - (TRUNCATE(venc / cont, 2) * (cont - 1))),
+ IF(@cont < cont,
+ TRUNCATE(foreignValue / cont, 2),
+ foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1)))
+ FROM (
+ SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax)
+ * iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc,
+ SUM(iit.foreignValue) / COUNT(DISTINCT(pdd.detail)) foreignValue,
+ s.payDemFk,
+ ii.companyFk,
+ COUNT(DISTINCT(pdd.detail)) cont,
+ s.payDay,
+ ii.issued,
+ DATE(ii.created) + INTERVAL 2 DAY created
+ FROM invoiceIn ii
+ JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
+ LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk
+ JOIN supplier s ON s.id = ii.supplierFk
+ JOIN payDemDetail pdd ON pdd.id = s.payDemFk
+ WHERE ii.id = vInvoiceInFk
+ GROUP BY ii.id
+ )sub
+ JOIN payDemDetail pdd ON pdd.id = sub.payDemFk
+ GROUP BY pdd.detail;
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceInDueDay_recalc.sql b/db/routines/vn/procedures/invoiceInDueDay_recalc.sql
new file mode 100644
index 000000000..7d2b0a5ed
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInDueDay_recalc.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInDueDay_recalc`(vInvoiceInFk INT)
+BEGIN
+
+ DELETE FROM invoiceInDueDay
+ WHERE invoiceInFk = vInvoiceInFk;
+
+ CALL invoiceInDueDay_calculate(vInvoiceInFk);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceInTaxMakeByDua.sql b/db/routines/vn/procedures/invoiceInTaxMakeByDua.sql
new file mode 100644
index 000000000..3453516cc
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInTaxMakeByDua.sql
@@ -0,0 +1,38 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTaxMakeByDua`(
+ vDuaFk INT
+)
+BEGIN
+/**
+ * Borra los valores de duaTax y sus vctos. y los vuelve a
+ * crear en base a la tabla duaEntry.
+ *
+ * @param vDuaFk Id del dua a recalcular
+ */
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vInvoiceInFk INT;
+
+ DECLARE vInvoices CURSOR FOR
+ SELECT DISTINCT invoiceInFk
+ FROM entry e
+ JOIN duaEntry de ON de.entryFk = e.id
+ WHERE de.duaFk = vDuaFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vInvoices;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vInvoices INTO vInvoiceInFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL invoiceInTax_recalc(vInvoiceInFk);
+ CALL invoiceInDueDay_recalc(vInvoiceInFk);
+
+ END LOOP;
+ CLOSE vInvoices;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql b/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql
new file mode 100644
index 000000000..60ec34696
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql
@@ -0,0 +1,36 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTax_afterUpsert`(vInvoiceInFk INT)
+BEGIN
+/**
+ * Triggered actions when a invoiceInTax is updated or inserted.
+ *
+ * @param vInvoiceInFk The invoiceIn id
+ */
+ DECLARE vTaxRowLimit INT;
+ DECLARE vLines INT;
+ DECLARE vHasDistinctTransactions INT;
+
+ SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig;
+
+ SELECT COUNT(*) INTO vLines
+ FROM invoiceInTax
+ WHERE invoiceInFk = vInvoiceInFk
+ AND (taxTypeSageFk OR transactionTypeSageFk);
+
+ IF vLines >= vTaxRowLimit THEN
+ CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit));
+ END IF;
+
+ SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions
+ FROM invoiceIn ii
+ JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
+ JOIN invoiceInSerial iis ON iis.code = ii.serial
+ WHERE ii.id = vInvoiceInFk
+ AND iis.taxAreaFk = 'CEE'
+ AND transactionTypeSageFk;
+
+ IF vHasDistinctTransactions > 1 THEN
+ CALL util.throw ('This invoice does not allow different types of transactions');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceInTax_getFromDua.sql b/db/routines/vn/procedures/invoiceInTax_getFromDua.sql
new file mode 100644
index 000000000..bf2cbe61e
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInTax_getFromDua.sql
@@ -0,0 +1,35 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTax_getFromDua`(vDuaFk INT)
+BEGIN
+/**
+ * Borra los valores de duaTax y sus vctos. y los vuelve a crear en base a la tabla duaEntry
+ *
+ * @param vDuaFk Id del dua a recalcular
+ */
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vInvoiceInFk INT;
+
+ DECLARE vInvoices CURSOR FOR
+ SELECT DISTINCT invoiceInFk
+ FROM entry e
+ JOIN duaEntry de ON de.entryFk = e.id
+ WHERE de.duaFk = vDuaFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vInvoices;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vInvoices INTO vInvoiceInFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL invoiceInTax_getFromEntries(vInvoiceInFk);
+ CALL invoiceInDueDay_calculate(vInvoiceInFk);
+
+ END LOOP;
+ CLOSE vInvoices;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceInTax_getFromEntries.sql b/db/routines/vn/procedures/invoiceInTax_getFromEntries.sql
new file mode 100644
index 000000000..5a53b7543
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInTax_getFromEntries.sql
@@ -0,0 +1,54 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTax_getFromEntries`(IN vInvoiceInFk INT)
+BEGIN
+ DECLARE vRate DOUBLE DEFAULT 1;
+ DECLARE vDated DATE;
+ DECLARE vExpenseFk VARCHAR(10);
+ DECLARE vIsBooked BOOLEAN DEFAULT FALSE;
+
+ SELECT isBooked INTO vIsBooked
+ FROM invoiceIn ii
+ WHERE id = vInvoiceInFk;
+
+ IF vIsBooked THEN
+ CALL util.throw('A booked invoice cannot be modified');
+ END IF;
+
+ SELECT MAX(rr.dated) INTO vDated
+ FROM referenceRate rr
+ JOIN invoiceIn ii ON ii.id = vInvoiceInFk
+ WHERE rr.dated <= ii.issued
+ AND rr.currencyFk = ii.currencyFk ;
+
+ IF vDated THEN
+ SELECT `value` INTO vRate
+ FROM referenceRate
+ WHERE dated = vDated;
+ END IF;
+
+ SELECT id INTO vExpenseFk
+ FROM vn.expense
+ WHERE `name` = 'Adquisición mercancia Extracomunitaria'
+ GROUP BY id
+ LIMIT 1;
+
+ DELETE FROM invoiceInTax
+ WHERE invoiceInFk = vInvoiceInFk;
+
+ INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, foreignValue, taxTypeSageFk, transactionTypeSageFk)
+ SELECT ii.id,
+ SUM(b.buyingValue * b.quantity) / IFNULL(vRate,1) taxableBase,
+ vExpenseFk,
+ IF(ii.currencyFk = 1,NULL,SUM(b.buyingValue * b.quantity )) divisa,
+ taxTypeSageFk,
+ transactionTypeSageFk
+ FROM invoiceIn ii
+ JOIN entry e ON e.invoiceInFk = ii.id
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN buy b ON b.entryFk = e.id
+ LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk
+ AND rr.dated = ii.issued
+ WHERE ii.id = vInvoiceInFk
+ HAVING taxableBase IS NOT NULL;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceInTax_recalc.sql b/db/routines/vn/procedures/invoiceInTax_recalc.sql
new file mode 100644
index 000000000..4e20b01d3
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInTax_recalc.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTax_recalc`(
+ vInvoiceInFk INT
+)
+BEGIN
+/**
+ * Recalcula y actualiza los impuestos de la factura
+ * usando la última tasa de cambio y detalles de compra.
+ *
+ * @param vInvoiceInFk Id de factura recibida
+ */
+ DECLARE vRate DOUBLE DEFAULT 1;
+ DECLARE vExpenseFk VARCHAR(10);
+
+ SELECT `value` INTO vRate
+ FROM referenceRate rr
+ JOIN invoiceIn ii ON ii.id = vInvoiceInFk
+ WHERE rr.dated <= ii.issued
+ AND rr.currencyFk = ii.currencyFk
+ ORDER BY dated DESC
+ LIMIT 1;
+
+ DELETE FROM invoiceInTax WHERE invoiceInFk = vInvoiceInFk;
+
+ SELECT id INTO vExpenseFk
+ FROM expense
+ WHERE code = 'extraCommGoodsAcquisition';
+
+ IF vExpenseFk IS NULL THEN
+ CALL util.throw('Expense extraCommGoodsAcquisition not exists');
+ END IF;
+
+ INSERT INTO invoiceInTax(
+ invoiceInFk,
+ taxableBase,
+ expenseFk,
+ foreignValue,
+ taxTypeSageFk,
+ transactionTypeSageFk
+ )
+ SELECT ii.id,
+ SUM(b.buyingValue * b.quantity) / vRate bi,
+ vExpenseFk,
+ IF(c.code = 'EUR', NULL, SUM(b.buyingValue * b.quantity)),
+ s.taxTypeSageFk,
+ s.transactionTypeSageFk
+ FROM invoiceIn ii
+ JOIN currency c ON c.id = ii.currencyFk
+ JOIN `entry` e ON e.invoiceInFk = ii.id
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN buy b ON b.entryFk = e.id
+ LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk
+ AND rr.dated = ii.issued
+ WHERE ii.id = vInvoiceInFk
+ HAVING bi IS NOT NULL;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql
new file mode 100644
index 000000000..a75b2269a
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceIn_booking.sql
@@ -0,0 +1,283 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceIn_booking`(vSelf INT)
+BEGIN
+ DECLARE vBookNumber INT;
+
+ CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn
+ ENGINE = MEMORY
+ SELECT ii.bookEntried,
+ iit.foreignValue,
+ ii.companyFk,
+ ii.expenseFkDeductible,
+ iit.taxableBase,
+ iit.transactionTypeSageFk,
+ ii.serial,
+ ii.issued,
+ ii.operated,
+ ii.supplierRef,
+ ii.siiTrascendencyInvoiceInFk,
+ ii.cplusTaxBreakFk,
+ ii.cplusSubjectOpFk,
+ ii.siiTypeInvoiceInFk,
+ ii.cplusRectificationTypeFk,
+ ii.booked,
+ IFNULL(a.isUeeMember, c.isUeeMember) isUeeMember,
+ (c.id = cc.id) isSameCountry,
+ s.account supplierAccount,
+ s.name supplierName,
+ s.nif,
+ s.IsVies,
+ iit.taxTypeSageFk,
+ tt.code taxCode,
+ ti.Iva,
+ ti.CuentaIvaSoportado,
+ ti.PorcentajeIva,
+ ti.CuentaIvaRepercutido,
+ ttr.ClaveOperacionDefecto,
+ iis.cplusTerIdNifFk,
+ cit.id invoicesCount,
+ e.code,
+ e.isWithheld,
+ e.id expenseFk,
+ e.name expenseName
+ FROM invoiceIn ii
+ JOIN supplier s ON s.id = ii.supplierFk
+ LEFT JOIN province p ON p.id = s.provinceFk
+ LEFT JOIN autonomy a ON a.id = p.autonomyFk
+ JOIN country c ON c.id = s.countryFk
+ JOIN supplier sc ON sc.id = ii.companyFk
+ JOIN country cc ON cc.id = sc.countryFk
+ JOIN invoiceInSerial iis ON iis.code = ii.serial
+ JOIN siiTypeInvoiceIn cit ON cit.id = ii.siiTypeInvoiceInFk
+ LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
+ LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk
+ LEFT JOIN expense e ON e.id = iit.expenseFk
+ LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
+ LEFT JOIN sage.taxType tt ON tt.id = ti.CodigoIva
+ WHERE ii.id = vSelf;
+
+ CALL vn.ledger_next(vBookNumber);
+
+ -- Apunte del proveedor
+ INSERT INTO XDiario(
+ ASIEN,
+ FECHA,
+ SUBCTA,
+ EUROHABER,
+ CONCEPTO,
+ CAMBIO,
+ HABERME,
+ NFACTICK,
+ CLAVE,
+ empresa_id)
+ SELECT
+ vBookNumber ASIEN,
+ tii.bookEntried FECHA,
+ tii.supplierAccount SUBCTA,
+ SUM(tii.taxableBase *
+ IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21')
+ AND tii.taxTypeSageFk IS NOT NULL),
+ 1 + (tii.PorcentajeIva / 100),
+ 1)) EUROHABER,
+ CONCAT('s/fra',
+ RIGHT(tii.supplierRef, 8),
+ ':',
+ LEFT(tii.supplierName, 10)) CONCEPTO,
+ CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10,4)) CAMBIO,
+ SUM(tii.foreignValue * IF(tii.serial = 'R', 1 + (tii.PorcentajeIva / 100), 1)) HABERME,
+ tii.invoicesCount NFACTICK,
+ vSelf CLAVE,
+ tii.companyFk empresa_id
+ FROM tInvoiceIn tii;
+
+ -- Línea de Gastos
+ INSERT INTO XDiario(
+ ASIEN,
+ FECHA,
+ SUBCTA,
+ CONTRA,
+ EURODEBE,
+ EUROHABER,
+ CONCEPTO,
+ CAMBIO,
+ DEBEME,
+ HABERME,
+ NFACTICK,
+ empresa_id)
+ SELECT vBookNumber ASIEN,
+ tii.bookEntried FECHA,
+ IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenseFk),tii.expenseFk) SUBCTA,
+ tii.supplierAccount CONTRA,
+ IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE,
+ IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER,
+ CONCAT('s/fra',
+ RIGHT(tii.supplierRef, 8),
+ ':',
+ LEFT(tii.supplierName, 10)) CONCEPTO,
+ CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10, 4)) CAMBIO,
+ IF(tii.isWithheld, NULL,ABS(ROUND(SUM(tii.foreignValue), 2))) DEBEME,
+ IF(tii.isWithheld, ABS(ROUND(SUM(tii.foreignValue), 2)) ,NULL) HABERME,
+ tii.invoicesCount NFACTICK,
+ tii.companyFk empresa_id
+ FROM tInvoiceIn tii
+ WHERE tii.code IS NULL OR tii.code <> 'suplido'
+ GROUP BY tii.expenseFk;
+
+ -- Líneas de IVA
+ INSERT INTO XDiario(
+ ASIEN,
+ FECHA,
+ SUBCTA,
+ CONTRA,
+ EURODEBE,
+ BASEEURO,
+ CONCEPTO,
+ FACTURA,
+ IVA,
+ AUXILIAR,
+ SERIE,
+ TIPOOPE,
+ FECHA_EX,
+ FECHA_OP,
+ NFACTICK,
+ FACTURAEX,
+ L340,
+ LRECT349,
+ TIPOCLAVE,
+ TIPOEXENCI,
+ TIPONOSUJE,
+ TIPOFACT,
+ TIPORECTIF,
+ TERIDNIF,
+ TERNIF,
+ TERNOM,
+ FECREGCON,
+ empresa_id)
+ SELECT vBookNumber ASIEN,
+ tii.bookEntried FECHA,
+ IF(tii.expenseFkDeductible>0, tii.expenseFkDeductible, tii.CuentaIvaSoportado) SUBCTA,
+ tii.supplierAccount CONTRA,
+ SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100, 2)) EURODEBE,
+ SUM(tii.taxableBase) BASEEURO,
+ GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO,
+ vSelf FACTURA,
+ tii.PorcentajeIva IVA,
+ IF(tii.isUeeMember AND eWithheld.id IS NULL, '', '*') AUXILIAR,
+ tii.serial SERIE,
+ tii.ClaveOperacionDefecto,
+ tii.issued FECHA_EX,
+ tii.operated FECHA_OP,
+ tii.invoicesCount NFACTICK,
+ tii.supplierRef FACTURAEX,
+ TRUE L340,
+ (tii.isSameCountry OR NOT tii.isUeeMember) LRECT349,
+ tii.siiTrascendencyInvoiceInFk TIPOCLAVE,
+ tii.cplusTaxBreakFk TIPOEXENCI,
+ tii.cplusSubjectOpFk TIPONOSUJE,
+ tii.siiTypeInvoiceInFk TIPOFACT,
+ tii.cplusRectificationTypeFk TIPORECTIF,
+ tii.cplusTerIdNifFk TERIDNIF,
+ tii.nif TERNIF,
+ tii.supplierName TERNOM,
+ tii.booked FECREGCON,
+ tii.companyFk
+ FROM tInvoiceIn tii
+ LEFT JOIN (
+ SELECT e.id
+ FROM tInvoiceIn tii
+ JOIN expense e ON e.id = tii.expenseFk
+ WHERE e.isWithheld
+ LIMIT 1
+ ) eWithheld ON TRUE
+ WHERE tii.taxTypeSageFk IS NOT NULL
+ AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21'))
+ GROUP BY tii.PorcentajeIva, tii.expenseFk;
+
+ -- Línea iva inversor sujeto pasivo
+ INSERT INTO XDiario(
+ ASIEN,
+ FECHA,
+ SUBCTA,
+ CONTRA,
+ EUROHABER,
+ BASEEURO,
+ CONCEPTO,
+ FACTURA,
+ IVA,
+ AUXILIAR,
+ SERIE,
+ TIPOOPE,
+ FECHA_EX,
+ FECHA_OP,
+ NFACTICK,
+ FACTURAEX,
+ L340,
+ LRECT349,
+ TIPOCLAVE,
+ TIPOEXENCI,
+ TIPONOSUJE,
+ TIPOFACT,
+ TIPORECTIF,
+ TERIDNIF,
+ TERNIF,
+ TERNOM,
+ empresa_id)
+ SELECT vBookNumber ASIEN,
+ tii.bookEntried FECHA,
+ tii.CuentaIvaRepercutido SUBCTA,
+ tii.supplierAccount CONTRA,
+ SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100,2)) EUROHABER,
+ ROUND(SUM(tii.taxableBase),2) BASEEURO,
+ GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO,
+ vSelf FACTURA,
+ tii.PorcentajeIva IVA,
+ '*' AUXILIAR,
+ tii.serial SERIE,
+ tii.ClaveOperacionDefecto,
+ tii.issued FECHA_EX,
+ tii.operated FECHA_OP,
+ tii.invoicesCount NFACTICK,
+ tii.supplierRef FACTURAEX,
+ FALSE L340,
+ (tii.isSameCountry OR NOT tii.isUeeMember) LRECT349,
+ 1 TIPOCLAVE,
+ tii.cplusTaxBreakFk TIPOEXENCI,
+ tii.cplusSubjectOpFk TIPONOSUJE,
+ tii.siiTypeInvoiceInFk TIPOFACT,
+ tii.cplusRectificationTypeFk TIPORECTIF,
+ tii.cplusTerIdNifFk TERIDNIF,
+ tii.nif TERNIF,
+ tii.supplierName TERNOM,
+ tii.companyFk
+ FROM tInvoiceIn tii
+ JOIN sage.config c
+ WHERE tii.taxCode = 'ISP21' OR MID(tii.supplierAccount, 4, 1) = '1'
+ AND tii.taxTypeSageFk IS NOT NULL
+ AND NOT(tii.isVies
+ AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk
+ AND tii.taxCode = 'nonTaxable')
+ GROUP BY tii.PorcentajeIva, tii.expenseFk;
+
+ -- Actualización del registro original
+ UPDATE invoiceIn ii
+ SET ii.isBooked = TRUE
+ WHERE ii.id = vSelf;
+
+ -- Problemas derivados de la precisión en los decimales al calcular los impuestos
+ UPDATE XDiario
+ SET EURODEBE = EURODEBE -
+ (SELECT IF(ABS(sub.difference) = 0.01, sub.difference, 0)
+ FROM(
+ SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference
+ FROM XDiario
+ WHERE ASIEN = vBookNumber
+ )sub
+ )
+ WHERE ASIEN = vBookNumber
+ AND EURODEBE <> 0
+ ORDER BY id DESC
+ LIMIT 1;
+
+ DROP TEMPORARY TABLE tInvoiceIn;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceOutAgain.sql b/db/routines/vn/procedures/invoiceOutAgain.sql
new file mode 100644
index 000000000..82cebc18d
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceOutAgain.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOutAgain`(IN vInvoiceRef VARCHAR(15), vTaxArea VARCHAR(25))
+BEGIN
+
+/* Para tickets ya facturados, vuelve a repetir el proceso de facturación.
+*
+* @param vInvoiceFk Numero de factura
+* @param vTaxArea Numero de factura
+*/
+
+ DECLARE vInvoiceFk INT;
+ DECLARE vCountry INT;
+ DECLARE vTaxArea VARCHAR(15);
+ DECLARE vSpainCountryCode INT DEFAULT 1;
+
+ SELECT id INTO vInvoiceFk
+ FROM invoiceOut
+ WHERE ref = vInvoiceRef;
+
+ UPDATE invoiceOut
+ SET hasPdf = 0
+ WHERE id = vInvoiceFk;
+
+ SELECT s.countryFk INTO vCountry
+ FROM supplier s
+ JOIN invoiceOut io ON io.companyFk = s.id
+ WHERE io.id = vInvoiceFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketToInvoice;
+
+ CREATE TEMPORARY TABLE tmp.ticketToInvoice
+ SELECT id
+ FROM ticket
+ WHERE refFk = vInvoiceRef;
+
+ CALL invoiceExpenseMake(vInvoiceFk);
+
+ CALL invoiceTaxMake(vInvoiceFk,vTaxArea);
+
+ UPDATE invoiceOut io
+ JOIN (
+ SELECT SUM(amount) AS total
+ FROM invoiceOutExpense
+ WHERE invoiceOutFk = vInvoiceFk
+ ) base
+ JOIN (
+ SELECT SUM(vat) AS total
+ FROM invoiceOutTax
+ WHERE invoiceOutFk = vInvoiceFk
+ ) vat
+ SET io.amount = base.total + vat.total
+ WHERE io.id = vInvoiceFk;
+
+ CALL vn.invoiceOutBooking(vInvoiceFk);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceOutBooking.sql b/db/routines/vn/procedures/invoiceOutBooking.sql
new file mode 100644
index 000000000..bd109e1ec
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceOutBooking.sql
@@ -0,0 +1,194 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOutBooking`(IN vInvoice INT)
+BEGIN
+/* Asienta la factura emitida
+*
+* param vInvoice factura_id
+*/
+ DECLARE vBookNumber INT;
+ DECLARE vExpenseConcept VARCHAR(50);
+ DECLARE vSpainCountryFk INT;
+ DECLARE vOldBookNumber INT;
+
+ SELECT id INTO vSpainCountryFk FROM country WHERE code = 'ES';
+
+ SELECT ASIEN
+ INTO vOldBookNumber
+ FROM XDiario x
+ JOIN invoiceOut io ON io.id = vInvoice
+ WHERE x.SERIE = io.serial
+ AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1)
+ LIMIT 1;
+
+ DELETE
+ FROM XDiario
+ WHERE ASIEN = vOldBookNumber;
+
+ DROP TEMPORARY TABLE IF EXISTS rs;
+ CREATE TEMPORARY TABLE rs
+ SELECT
+ c.accountingAccount AS clientBookingAccount,
+ io.amount as totalAmount,
+ CONCAT('n/fra ', io.ref) as simpleConcept,
+ CONCAT('n/fra ', io.ref, ' ', c.name) as Concept,
+ io.serial AS SERIE,
+ io.issued AS FECHA_EX,
+ io.issued AS FECHA_OP,
+ io.issued AS FECHA,
+ 1 AS NFACTICK,
+ IF(ic.correctingFk,'D','') AS TIPOOPE,
+ io.siiTrascendencyInvoiceOutFk AS TIPOCLAVE,
+ io.cplusTaxBreakFk AS TIPOEXENCI,
+ io.cplusSubjectOpFk AS TIPONOSUJE,
+ io.siiTypeInvoiceOutFk AS TIPOFACT,
+ ic.cplusRectificationTypeFk AS TIPORECTIF,
+ io.companyFk,
+ RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum,
+ IF(c.countryFk = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember,2,4)) AS TERIDNIF,
+ CONCAT(IF(ct.isUeeMember AND c.countryFk <> vSpainCountryFk,ct.code,''),c.fi) AS TERNIF,
+ c.socialName AS TERNOM,
+ ior.serial AS SERIE_RT,
+ RIGHT(ior.ref, LENGTH(ior.ref) - 1) AS FACTU_RT,
+ ior.issued AS FECHA_RT,
+ IF(ior.id,TRUE,FALSE) AS RECTIFICA
+ FROM invoiceOut io
+ JOIN invoiceOutSerial ios ON ios.code = io.serial
+ JOIN client c ON c.id = io.clientFk
+ JOIN country ct ON ct.id = c.countryFk
+ LEFT JOIN invoiceCorrection ic ON ic.correctingFk = io.id
+ LEFT JOIN invoiceOut ior ON ior.id = ic.correctedFk
+ WHERE io.id = vInvoice;
+
+ CALL vn.ledger_next(vBookNumber);
+
+ -- Linea del cliente
+ INSERT INTO XDiario(
+ ASIEN,
+ FECHA,
+ SUBCTA,
+ EURODEBE,
+ CONCEPTO,
+ FECHA_EX,
+ FECHA_OP,
+ empresa_id
+ )
+ SELECT
+ vBookNumber AS ASIEN,
+ rs.FECHA,
+ rs.clientBookingAccount AS SUBCTA,
+ rs.totalAmount AS EURODEBE,
+ rs.simpleConcept AS CONCEPTO,
+ rs.FECHA_EX,
+ rs.FECHA_OP,
+ rs.companyFk AS empresa_id
+ FROM rs;
+
+ -- Lineas de gasto
+ INSERT INTO XDiario(
+ ASIEN,
+ FECHA,
+ SUBCTA,
+ CONTRA,
+ EUROHABER,
+ CONCEPTO,
+ FECHA_EX,
+ FECHA_OP,
+ empresa_id
+ )
+ SELECT
+ vBookNumber AS ASIEN,
+ rs.FECHA,
+ ioe.expenseFk AS SUBCTA,
+ rs.clientBookingAccount AS CONTRA,
+ ioe.amount AS EUROHABER,
+ rs.Concept AS CONCEPTO,
+ rs.FECHA_EX,
+ rs.FECHA_OP,
+ rs.companyFk AS empresa_id
+ FROM rs
+ JOIN invoiceOutExpense ioe
+ WHERE ioe.invoiceOutFk = vInvoice;
+
+ SELECT GROUP_CONCAT(`name` SEPARATOR ',')
+ INTO vExpenseConcept
+ FROM expense e
+ JOIN invoiceOutExpense ioe ON ioe.expenseFk = e.id
+ WHERE ioe.invoiceOutFk = vInvoice;
+
+ -- Lineas de IVA
+ INSERT INTO XDiario(
+ ASIEN,
+ FECHA,
+ SUBCTA,
+ CONTRA,
+ EUROHABER,
+ BASEEURO,
+ CONCEPTO,
+ FACTURA,
+ IVA,
+ RECEQUIV,
+ AUXILIAR,
+ SERIE,
+ SERIE_RT,
+ FACTU_RT,
+ RECTIFICA,
+ FECHA_RT,
+ FECHA_OP,
+ FECHA_EX,
+ TIPOOPE,
+ NFACTICK,
+ TERIDNIF,
+ TERNIF,
+ TERNOM,
+ L340,
+ TIPOCLAVE,
+ TIPOEXENCI,
+ TIPONOSUJE,
+ TIPOFACT,
+ TIPORECTIF,
+ empresa_id
+ )
+ SELECT
+ vBookNumber AS ASIEN,
+ rs.FECHA,
+ iot.pgcFk AS SUBCTA,
+ rs.clientBookingAccount AS CONTRA,
+ iot.vat AS EUROHABER,
+ iot.taxableBase AS BASEEURO,
+ CONCAT(vExpenseConcept,' : ',rs.Concept) AS CONCEPTO,
+ rs.invoiceNum AS FACTURA,
+ IF(pe2.equFk,0,pgc.rate) AS IVA,
+ IF(pe2.equFk,0,pgce.rate) AS RECEQUIV,
+ IF(pgc.mod347,'','*') AS AUXILIAR,
+ rs.SERIE,
+ rs.SERIE_RT,
+ rs.FACTU_RT,
+ rs.RECTIFICA,
+ rs.FECHA_RT,
+ rs.FECHA_OP,
+ rs.FECHA_EX,
+ rs.TIPOOPE,
+ rs.NFACTICK,
+ rs.TERIDNIF,
+ rs.TERNIF,
+ rs.TERNOM,
+ pgc.mod340 AS L340,
+ pgc.siiTrascendencyInvoiceOutFk AS TIPOCLAVE,
+ pgc.cplusTaxBreakFk as TIPOEXENCI,
+ rs.TIPONOSUJE,
+ rs.TIPOFACT,
+ rs.TIPORECTIF,
+ rs.companyFk AS empresa_id
+ FROM rs
+ JOIN invoiceOutTax iot
+ JOIN pgc ON pgc.code = iot.pgcFk
+ LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk -- --------------- Comprueba si la linea es de iva con rec.equiv. asociado
+ LEFT JOIN pgc pgce ON pgce.code = pe.equFk
+ LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk -- --------------- Comprueba si la linea es de rec.equiv.
+ WHERE iot.invoiceOutFk = vInvoice;
+
+ UPDATE invoiceOut
+ SET booked = util.VN_CURDATE()
+ WHERE id = vInvoice;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceOutBookingRange.sql b/db/routines/vn/procedures/invoiceOutBookingRange.sql
new file mode 100644
index 000000000..57d973f01
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceOutBookingRange.sql
@@ -0,0 +1,47 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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 ;
diff --git a/db/routines/vn/procedures/invoiceOutListByCompany.sql b/db/routines/vn/procedures/invoiceOutListByCompany.sql
new file mode 100644
index 000000000..09ebfc1a4
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceOutListByCompany.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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 ;
diff --git a/db/routines/vn/procedures/invoiceOutTaxAndExpense.sql b/db/routines/vn/procedures/invoiceOutTaxAndExpense.sql
new file mode 100644
index 000000000..c263fe8d3
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceOutTaxAndExpense.sql
@@ -0,0 +1,76 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOutTaxAndExpense`()
+BEGIN
+
+/* Para tickets ya facturados, vuelve a repetir el proceso de facturación.
+*
+* @param vInvoice Numero de factura
+*/
+
+ DECLARE vInvoice INT;
+ DECLARE vInvoiceRef VARCHAR(15);
+ DECLARE vCountry INT;
+ DECLARE vTaxArea VARCHAR(15);
+ DECLARE vContador INT DEFAULT 0;
+
+ DECLARE done BOOL DEFAULT FALSE;
+
+ DECLARE rs CURSOR FOR
+ SELECT id,ref
+ FROM invoiceOut io
+
+ WHERE issued >= '2017-07-01'
+ AND companyFk = 1381
+ AND io.amount IS NULL
+ ;
+
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+ OPEN rs;
+
+ FETCH rs INTO vInvoice ,vInvoiceRef;
+
+ WHILE NOT done DO
+
+ SELECT s.countryFk
+ INTO vCountry
+ FROM supplier s
+ JOIN invoiceOut io ON io.companyFk = s.id
+ WHERE io.id = vInvoice;
+
+ SELECT IF(c.isEqualizated AND i.taxAreaFk = 'NATIONAL','EQU',i.taxAreaFk)
+ INTO vTaxArea
+ FROM invoiceOutSerial i
+ JOIN invoiceOut io ON io.serial = i.code
+ JOIN client c ON c.id = io.clientFk
+ WHERE io.id = vInvoice;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketToInvoice;
+
+ CREATE TEMPORARY TABLE tmp.ticketToInvoice
+ SELECT id
+ FROM ticket
+ WHERE refFk = vInvoiceRef;
+
+ CALL invoiceExpenseMake(vInvoice);
+ CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea);
+
+ FETCH rs INTO vInvoice ,vInvoiceRef;
+
+ SET vContador = vContador + 1;
+
+ IF vContador MOD 50 = 0 THEN
+
+ SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS;
+
+ END IF;
+
+ END WHILE;
+
+ CLOSE rs;
+
+ SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceOut_exportationFromClient.sql b/db/routines/vn/procedures/invoiceOut_exportationFromClient.sql
new file mode 100644
index 000000000..5fce7c428
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceOut_exportationFromClient.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOut_exportationFromClient`(
+ vMaxTicketDate DATETIME,
+ vClientFk INT,
+ vCompanyFk INT)
+BEGIN
+/**
+ * Genera tabla temporal tmp.ticketToInvoice necesaría para el proceso de facturación
+ * Los abonos quedan excluidos en las exportaciones
+ *
+ * @param vMaxTicketDate Fecha hasta la cual cogerá tickets para facturar
+ * @param vClientFk Id del cliente a facturar
+ * @param vCompanyFk Id de la empresa desde la que se factura
+ */
+ DECLARE vMinTicketDate DATE;
+ SET vMinTicketDate = util.firstDayOfYear(vMaxTicketDate - INTERVAL 1 YEAR);
+ SET vMaxTicketDate = util.dayend(vMaxTicketDate);
+
+ DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
+ CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice`
+ (PRIMARY KEY (`id`))
+ ENGINE = MEMORY
+ SELECT t.id
+ FROM ticket t
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ WHERE t.clientFk = vClientFk
+ AND t.refFk IS NULL
+ AND t.companyFk = vCompanyFk
+ AND t.shipped BETWEEN vMinTicketDate AND vMaxTicketDate
+ AND (am.`code` IS NULL OR am.`code` <> 'refund');
+END$$
+DELIMITER ;
diff --git a/db/changes/232001/00-invoiceOut_new.sql b/db/routines/vn/procedures/invoiceOut_new.sql
similarity index 86%
rename from db/changes/232001/00-invoiceOut_new.sql
rename to db/routines/vn/procedures/invoiceOut_new.sql
index b4fc5c824..8c35ce75f 100644
--- a/db/changes/232001/00-invoiceOut_new.sql
+++ b/db/routines/vn/procedures/invoiceOut_new.sql
@@ -1,8 +1,5 @@
-DROP PROCEDURE IF EXISTS `vn`.`invoiceOut_new`;
-
DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOut_new`(
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOut_new`(
vSerial VARCHAR(255),
vInvoiceDate DATE,
vTaxArea VARCHAR(25),
@@ -35,6 +32,13 @@ BEGIN
DECLARE vIsCEESerial BOOL DEFAULT FALSE;
DECLARE vIsCorrectInvoiceDate BOOL;
DECLARE vMaxShipped DATE;
+ DECLARE vDone BOOL;
+ DECLARE vTicketFk INT;
+ DECLARE vCursor CURSOR FOR
+ SELECT id
+ FROM tmp.ticketToInvoice;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vInvoiceDate = IFNULL(vInvoiceDate, util.VN_CURDATE());
@@ -96,7 +100,7 @@ BEGIN
clientFk,
dued,
companyFk,
- cplusInvoiceType477Fk
+ siiTypeInvoiceOutFk
)
SELECT
1,
@@ -120,28 +124,42 @@ BEGIN
FROM invoiceOut
WHERE id = vNewInvoiceId;
+ OPEN vCursor;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vCursor INTO vTicketFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL ticket_recalc(vTicketFk, vTaxArea);
+
+ END LOOP;
+ CLOSE vCursor;
+
UPDATE ticket t
JOIN tmp.ticketToInvoice ti ON ti.id = t.id
SET t.refFk = vNewRef;
DROP TEMPORARY TABLE IF EXISTS tmp.updateInter;
CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY
- SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador
+ SELECT s.id, ti.id ticket_id, vWorker Id_Trabajador
FROM tmp.ticketToInvoice ti
- LEFT JOIN ticketState ts ON ti.id = ts.ticket
+ LEFT JOIN ticketState ts ON ti.id = ts.ticketFk
JOIN state s
- WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = getAlert3State(ti.id);
+ WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id);
- INSERT INTO ticketTracking(stateFk,ticketFk,workerFk)
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT * FROM tmp.updateInter;
- CALL invoiceExpenceMake(vNewInvoiceId);
- CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
+ CALL invoiceExpenseMake(vNewInvoiceId);
+ CALL invoiceTaxMake(vNewInvoiceId, vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) total
- FROM invoiceOutExpence
+ FROM invoiceOutExpense
WHERE invoiceOutFk = vNewInvoiceId
) base
JOIN (
@@ -178,15 +196,15 @@ BEGIN
SET @vTaxableBaseServices := 0.00;
SET @vTaxCodeGeneral := NULL;
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
+ INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
@vTaxableBaseServices,
- sub.expenceFk,
+ sub.expenseFk,
sub.taxTypeSageFk,
sub.transactionTypeSageFk
FROM (
SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase,
- i.expenceFk,
+ i.expenseFk,
i.taxTypeSageFk,
i.transactionTypeSageFk,
@vTaxCodeGeneral := i.taxClassCodeFk
@@ -196,11 +214,11 @@ BEGIN
HAVING taxableBase
) sub;
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
+ INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral,
@vTaxableBaseServices, 0) taxableBase,
- i.expenceFk,
+ i.expenseFk,
i.taxTypeSageFk ,
i.transactionTypeSageFk
FROM tmp.ticketTax tt
diff --git a/db/routines/vn/procedures/invoiceOut_newFromClient.sql b/db/routines/vn/procedures/invoiceOut_newFromClient.sql
new file mode 100644
index 000000000..e6fc7b78a
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceOut_newFromClient.sql
@@ -0,0 +1,56 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOut_newFromClient`(
+ IN vClientFk INT,
+ IN vSerial CHAR(2),
+ IN vMaxShipped DATE,
+ IN vCompanyFk INT,
+ IN vTaxArea VARCHAR(25),
+ IN vRef VARCHAR(25),
+ OUT vInvoiceId INT)
+BEGIN
+/**
+ * Factura los tickets de un cliente hasta una fecha dada
+ * @param vClientFk Id del cliente a facturar
+ * @param vSerial Serie de factura
+ * @param vMaxShipped Fecha hasta la cual cogera tickets para facturar
+ * @param vCompanyFk Id de la empresa desde la que se factura
+ * @param vTaxArea Tipo de iva en relacion a la empresa y al cliente, NULL por defecto
+ * @param vRef Referencia de la factura en caso que se quiera forzar, NULL por defecto
+ * @return vInvoiceId factura
+ */
+ DECLARE vIsRefEditable BOOLEAN;
+ DECLARE vIsExportation BOOLEAN;
+
+ IF vRef IS NOT NULL THEN
+ SELECT isRefEditable INTO vIsRefEditable
+ FROM invoiceOutSerial
+ WHERE code = vSerial;
+
+ IF NOT vIsRefEditable THEN
+ CALL util.throw('serial non editable');
+ END IF;
+ END IF;
+
+ SELECT COUNT(*) INTO vIsExportation
+ FROM vn.invoiceOutSerial
+ WHERE taxAreaFk = 'WORLD'
+ AND `code` = vSerial;
+
+ IF vIsExportation THEN
+ CALL invoiceOut_exportationFromClient(vMaxShipped, vClientFk, vCompanyFk);
+ ELSE
+ CALL invoiceFromClient(vMaxShipped, vClientFk, vCompanyFk);
+ END IF;
+
+ CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId);
+
+ UPDATE invoiceOut
+ SET `ref` = vRef
+ WHERE id = vInvoiceId
+ AND vRef IS NOT NULL;
+
+ IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
+ CALL invoiceOutBooking(vInvoiceId);
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceOut_newFromTicket.sql b/db/routines/vn/procedures/invoiceOut_newFromTicket.sql
new file mode 100644
index 000000000..3ee7cd678
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceOut_newFromTicket.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOut_newFromTicket`(IN vTicketFk int, IN vSerial char(2), IN vTaxArea varchar(25),
+ IN vRef varchar(25), OUT vInvoiceId int)
+BEGIN
+/**
+ * Factura un ticket
+ * @param vTicketFk Id del ticket
+ * @param vSerial Serie de factura
+ * @param vTaxArea Area de la factura en caso de querer forzarlo,
+ * en la mayoria de los casos poner NULL
+ * @return vInvoiceId
+ */
+ DECLARE vIsRefEditable BOOLEAN;
+ CALL invoiceFromTicket(vTicketFk);
+ CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId);
+
+ IF vRef IS NOT NULL THEN
+ SELECT isRefEditable INTO vIsRefEditable
+ FROM invoiceOutSerial
+ WHERE code = vSerial;
+ IF NOT vIsRefEditable THEN
+ CALL util.throw('serial non editable');
+ END IF;
+
+ UPDATE invoiceOut
+ SET `ref` = vRef
+ WHERE id = vInvoiceId;
+ END IF;
+
+ IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
+ CALL invoiceOutBooking(vInvoiceId);
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceTaxMake.sql b/db/routines/vn/procedures/invoiceTaxMake.sql
new file mode 100644
index 000000000..30296dc26
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceTaxMake.sql
@@ -0,0 +1,44 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceTaxMake`(vInvoice INT, vTaxArea VARCHAR(25))
+BEGIN
+/**
+ * Factura un conjunto de tickets.
+ *
+ * @param vInvoice, vTaxAreaFk
+ * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
+ * @return tmp.ticketAmount
+ * @return tmp.ticketTax Impuesto desglosado para cada ticket.
+ */
+ DELETE FROM invoiceOutTax
+ WHERE invoiceOutFk = vInvoice;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
+ CREATE TEMPORARY TABLE tmp.ticket
+ (KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT id ticketFk
+ FROM tmp.ticketToInvoice;
+
+ CALL ticket_getTax(vTaxArea);
+
+ INSERT INTO invoiceOutTax(
+ invoiceOutFk,
+ pgcFk,
+ taxableBase,
+ vat
+ )
+ SELECT vInvoice,
+ pgcFk,
+ SUM(taxableBase) as BASE,
+ CAST(SUM(taxableBase) * rate / 100 AS DECIMAL (10,2))
+ FROM tmp.ticketTax
+ GROUP BY pgcFk
+ HAVING BASE
+ ORDER BY priority;
+
+ DROP TEMPORARY TABLE tmp.ticket;
+ DROP TEMPORARY TABLE tmp.ticketTax;
+ DROP TEMPORARY TABLE tmp.ticketAmount;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemBarcode_update.sql b/db/routines/vn/procedures/itemBarcode_update.sql
new file mode 100644
index 000000000..e2f13dc93
--- /dev/null
+++ b/db/routines/vn/procedures/itemBarcode_update.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemBarcode_update`(vItemFk INT,vCode VARCHAR(22), vDelete BOOL)
+BEGIN
+IF vDelete THEN
+ DELETE FROM vn.itemBarcode WHERE itemFk = vItemFk AND code = vCode;
+ELSE
+ INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode);
+END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemFuentesBalance.sql b/db/routines/vn/procedures/itemFuentesBalance.sql
new file mode 100644
index 000000000..e60273340
--- /dev/null
+++ b/db/routines/vn/procedures/itemFuentesBalance.sql
@@ -0,0 +1,79 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemFuentesBalance`(vDaysInFuture INT)
+BEGIN
+
+ /* Se utiliza para calcular la necesidad de mover mercancia entre el almacén de fuentes y el nuestro
+ *
+ * @param vDaysInFuture Rango de dias para calcular entradas y salidas
+ *
+ */
+
+ DECLARE vWarehouseFk INT;
+
+ SELECT s.warehouseFk INTO vWarehouseFk
+ FROM vn.sector s
+ WHERE s.code = 'FUENTES_PICASSE';
+
+ CALL cache.stock_refresh(FALSE);
+
+ SELECT i.id itemFk,
+ i.longName,
+ i.size,
+ i.subName,
+ v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible,
+ fue.Fuentes,
+ alb.Albenfruit,
+ sale.venta,
+ IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra,
+ IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0)
+ - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as saldo
+ FROM vn.item i
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN (
+ SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Fuentes
+ FROM vn.itemShelving ish
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.parking p ON p.id = sh.parkingFk
+ JOIN vn.sector s ON s.id = p.sectorFk
+ WHERE s.code = 'FUENTES_PICASSE'
+ GROUP BY ish.itemFk
+ ) fue ON fue.itemFk = i.id
+ LEFT JOIN (
+ SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Albenfruit
+ FROM vn.itemShelving ish
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.parking p ON p.id = sh.parkingFk
+ JOIN vn.sector s ON s.id = p.sectorFk
+ WHERE s.code = 'ALBENFRUIT'
+ GROUP BY ish.itemFk
+ ) alb ON alb.itemFk = i.id
+ LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk
+ LEFT JOIN (
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta
+ FROM itemTicketOut
+ WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
+ AND warehouseFk = vWarehouseFk
+ GROUP BY itemFk
+ ) sale ON sale.item_id = i.id
+ LEFT JOIN (
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra
+ FROM itemEntryIn
+ WHERE landed BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
+ AND warehouseInFk = vWarehouseFk
+ AND isVirtualStock = FALSE
+ GROUP BY itemFk
+ ) buy ON buy.item_id = i.id
+ LEFT JOIN (
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado
+ FROM itemEntryOut
+ WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
+ AND warehouseOutFk = vWarehouseFk
+ GROUP BY itemFk
+ ) mov ON mov.item_id = i.id
+ WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit)
+ AND i.itemPackingTypeFk = 'H'
+ AND ic.shortLife;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemPlacementFromTicket.sql b/db/routines/vn/procedures/itemPlacementFromTicket.sql
new file mode 100644
index 000000000..1a1a735e5
--- /dev/null
+++ b/db/routines/vn/procedures/itemPlacementFromTicket.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemPlacementFromTicket`(vTicket INT)
+BEGIN
+/**
+ * Llama a itemPlacementUpdateVisible
+ * de los articulos de la tabla temporal tmp.itemPlacement(itemFk)
+ * @treturn tmp.itemPlacement
+ * @param vTicket Id del Ticket
+ */
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.itemPlacement;
+ CREATE TEMPORARY TABLE tmp.itemPlacement
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT s.itemFk
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ WHERE t.id = vTicket;
+
+ CALL itemPlacementUpdateVisible();
+
+ DROP TEMPORARY TABLE tmp.itemPlacement;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemPlacementSupplyAiming.sql b/db/routines/vn/procedures/itemPlacementSupplyAiming.sql
new file mode 100644
index 000000000..ee9125a7b
--- /dev/null
+++ b/db/routines/vn/procedures/itemPlacementSupplyAiming.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyAiming`(vShelvingFk VARCHAR(10), quantity INT, vItemFk INT)
+BEGIN
+
+ SELECT ish.itemFk,
+ ish.longName,
+ ish.size,
+ ish.subName,
+ ish.itemShelvingFk,
+ ish.shelving,
+ ish.stock,
+ LEAST(ish.stock,quantity) as total,
+ CONCAT(
+ CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)),
+ ' x ',
+ ish.packing,
+ IF (
+ LEAST(ish.stock,quantity) MOD ish.packing,
+ CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))),
+ ''
+ ),
+ ' = ',
+ LEAST(ish.stock,quantity)
+ ) as proposal
+ FROM vn.itemShelvingPlacementSupplyStock ish
+ WHERE ish.shelving = vShelvingFk COLLATE utf8_general_ci
+ AND ish.itemFk = vItemFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemPlacementSupplyCloseOrder.sql b/db/routines/vn/procedures/itemPlacementSupplyCloseOrder.sql
new file mode 100644
index 000000000..9c4457a5e
--- /dev/null
+++ b/db/routines/vn/procedures/itemPlacementSupplyCloseOrder.sql
@@ -0,0 +1,10 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyCloseOrder`(vId INT, vQuantity INT)
+BEGIN
+
+ UPDATE vn.itemPlacementSupply
+ SET priority = 10
+ WHERE id = vId;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql b/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql
new file mode 100644
index 000000000..b23f69fe7
--- /dev/null
+++ b/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql
@@ -0,0 +1,37 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyGetOrder`(vSector INT )
+BEGIN
+
+ DECLARE vId INT;
+ DECLARE vLastParkingFk INT;
+ DECLARE vNextParkingFk INT;
+
+ SELECT sh.parkingFk INTO vLastParkingFk
+ FROM vn.itemShelvingPlacementSupply isps
+ JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ WHERE isps.userFk = getUser()
+ ORDER BY isps.created DESC
+ LIMIT 1;
+
+ SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk);
+
+ SELECT ipsl.id INTO vId
+ FROM vn.itemPlacementSupplyList ipsl
+ JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk
+ WHERE ipsl.saldo > 0
+ AND (ipsl.repoUserFk is NULL OR ipsl.repoUserFk = getUser())
+ AND ipsl.sectorFk = vSector
+ ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created
+ LIMIT 1;
+
+ UPDATE vn.itemPlacementSupply
+ SET repoUserFk = getUser()
+ WHERE id = vId;
+
+ SELECT * FROM vn.itemPlacementSupplyList
+ WHERE id = vId
+ AND sectorFk = vSector;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql
new file mode 100644
index 000000000..bdc13ae9d
--- /dev/null
+++ b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyStockGetTargetList`(vItemFk INT,vSectorFk INT)
+BEGIN
+/**
+ * Devuelve la lista de ubicaciones para itemFk en ese sector. Se utiliza en la preparación previa.
+ * Este proc se llama a continuacion de ticketToPrePrepare
+ *
+ * @param vItemFk Identificador de vn.item
+ * @param vSectorFk Identificador de vn.sector
+ */
+ SELECT ish.shelvingFk shelving,
+ p.code parking,
+ SUM(ish.visible) stockTotal,
+ ish.created,
+ p.pickingOrder
+ FROM vn.itemShelving ish
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.parking p ON p.id = sh.parkingFk
+ JOIN vn.sector sc ON sc.id = p.sectorFk
+ JOIN vn.warehouse w ON w.id = sc.warehouseFk
+ WHERE sc.id = vSectorFk
+ AND ish.visible > 0
+ AND ish.itemFk = vItemFk
+ GROUP BY ish.id
+ ORDER BY sh.priority DESC,
+ ish.created,
+ p.pickingOrder;
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/itemRefreshTags.sql b/db/routines/vn/procedures/itemRefreshTags.sql
new file mode 100644
index 000000000..21af20c0f
--- /dev/null
+++ b/db/routines/vn/procedures/itemRefreshTags.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemRefreshTags`(IN vItem INT)
+BEGIN
+/**
+ * Crea la tabla temporal necesaria para el procedimiento item_refreshTags
+ *
+ * @param vItem Articulo a modificar
+ * @param temporary table tmp.item(id) del articulo
+ **/
+ DROP TEMPORARY TABLE IF EXISTS tmp.item;
+
+ CREATE TEMPORARY TABLE tmp.item
+ SELECT vItem id;
+
+ CALL item_refreshTags();
+
+ DROP TEMPORARY TABLE tmp.item;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemSale_byWeek.sql b/db/routines/vn/procedures/itemSale_byWeek.sql
new file mode 100644
index 000000000..bc43b7b16
--- /dev/null
+++ b/db/routines/vn/procedures/itemSale_byWeek.sql
@@ -0,0 +1,45 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemSale_byWeek`(vWeek INT, IN vYear INT, vItemFk INT, vWarehouseFk INT)
+BEGIN
+
+ DECLARE vStarted DATE;
+ DECLARE vEnded DATETIME;
+
+ SELECT MIN(dated), util.dayEnd(MAX(dated)) INTO vStarted, vEnded
+ FROM `time` t
+ WHERE CONCAT(vYear, LPAD(vWeek, 2, 0)) = t.period;
+
+ SELECT t.shipped,
+ w.name warehouse,
+ s.ticketFk,
+ t.nickname client,
+ am.name agencyName,
+ wk.code salesPerson,
+ s.itemFk,
+ IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept,
+ s.quantity,
+ s.price,
+ s.priceFixed,
+ s.discount,
+ tls.name stateName,
+ sb.buyFk,
+ s.id saleFk,
+ wk.id salesPersonFk
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ JOIN address a ON a.id = t.addressFk
+ LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN `client` c ON c.id = a.clientFk
+ LEFT JOIN worker wk ON wk.id = c.salesPersonFk
+ LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id
+ LEFT JOIN saleBuy sb ON sb.saleFk = s.id
+ LEFT JOIN buy b ON b.id = sb.buyFk
+ LEFT JOIN item ig ON ig.id = b.itemOriginalFk
+ WHERE s.itemFk = vItemFk
+ AND t.shipped BETWEEN vStarted AND vEnded
+ AND IF(vWarehouseFk = 0, w.hasComission , t.warehouseFk = vWarehouseFk)
+ ORDER BY t.shipped, t.id;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemSaveMin.sql b/db/routines/vn/procedures/itemSaveMin.sql
new file mode 100644
index 000000000..510638348
--- /dev/null
+++ b/db/routines/vn/procedures/itemSaveMin.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemSaveMin`(min INT,vBarcode VARCHAR(22))
+BEGIN
+
+ DECLARE vItemFk INT;
+ SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
+
+ UPDATE vn.item SET minimum = min WHERE id = vItemFk;
+
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemSearchShelving.sql b/db/routines/vn/procedures/itemSearchShelving.sql
new file mode 100644
index 000000000..8c2c6c7c8
--- /dev/null
+++ b/db/routines/vn/procedures/itemSearchShelving.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemSearchShelving`(`vShelvingFk` VARCHAR(3))
+BEGIN
+ SELECT p.`column` AS col , p.`row`
+ FROM vn.shelving s
+ JOIN parking p ON s.parkingFk = p.id
+ WHERE s.`code` = vShelvingFk COLLATE utf8_general_ci;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingDelete.sql b/db/routines/vn/procedures/itemShelvingDelete.sql
new file mode 100644
index 000000000..f895782d3
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingDelete.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingDelete`(vId INT)
+BEGIN
+
+ DELETE FROM vn.itemShelving WHERE id = vId;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingLog_get.sql b/db/routines/vn/procedures/itemShelvingLog_get.sql
new file mode 100644
index 000000000..ad67ea5cd
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingLog_get.sql
@@ -0,0 +1,35 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`(vShelvingFk VARCHAR(10) )
+BEGIN
+
+/**
+ * Devuelve el log de los item en cada carro
+ *
+ * @param vShelvingFk Matrícula del carro
+ *
+ */
+
+ SELECT isl.itemShelvingFk,
+ isl.created,
+ isl.accion,
+ isl.itemFk,
+ isl.shelvingFk,
+ isl.quantity,
+ isl.visible,
+ isl.available,
+ isl.grouping,
+ isl.packing,
+ isl.stars,
+ item.longName,
+ item.size,
+ item.subName,
+ worker.code,
+ isl.accion
+ FROM item
+ JOIN itemShelvingLog isl ON item.id = isl.itemFk
+ JOIN worker ON isl.workerFk = worker.id
+ WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk
+ ORDER BY isl.created DESC;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingMakeFromDate.sql b/db/routines/vn/procedures/itemShelvingMakeFromDate.sql
new file mode 100644
index 000000000..2dde68829
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingMakeFromDate.sql
@@ -0,0 +1,58 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22))
+BEGIN
+
+ DECLARE vItemFk INT;
+
+ SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
+
+ SELECT itemFk INTO vItemFk
+ FROM vn.buy b
+ WHERE b.id = vItemFk;
+
+ IF (SELECT COUNT(*) FROM vn.shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN
+
+ INSERT IGNORE INTO vn.parking(`code`) VALUES(vShelvingFk);
+ INSERT INTO vn.shelving(`code`, parkingFk)
+ SELECT vShelvingFk, id
+ FROM vn.parking
+ WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci;
+
+ END IF;
+
+ IF (SELECT COUNT(*) FROM vn.itemShelving
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ AND itemFk = vItemFk
+ AND packing = vPacking) = 1 THEN
+
+ UPDATE vn.itemShelving
+ SET visible = visible+vQuantity,
+ created = vCreated
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ AND itemFk = vItemFk
+ AND packing = vPacking;
+
+ ELSE
+ CALL cache.last_buy_refresh(FALSE);
+ INSERT INTO itemShelving( itemFk,
+ shelvingFk,
+ visible,
+ created,
+ `grouping`,
+ packing,
+ packagingFk)
+ SELECT vItemFk,
+ vShelvingFk,
+ vQuantity,
+ vCreated,
+ IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`,
+ IF(vPacking = 0, b.packing, vPacking) packing,
+ IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging
+ FROM vn.item i
+ LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN vn.buy b ON b.id = lb.buy_id
+ WHERE i.id = vItemFk;
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingMatch.sql b/db/routines/vn/procedures/itemShelvingMatch.sql
new file mode 100644
index 000000000..9a10c2b87
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingMatch.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingMatch`(vEntryFk INT, vAllTravel BOOLEAN, vFromTimed DATETIME, vToTimed DATETIME)
+BEGIN
+
+ DECLARE vTravelFk INT;
+
+ SELECT travelFk INTO vTravelFk
+ FROM entry
+ WHERE id = vEntryFk;
+
+ SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas, b.printed
+ FROM item i
+ JOIN (
+ SELECT itemFk, sum(stickers) AS stickers, sum(printedStickers) as printed
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ WHERE IF(vAllTravel , travelFk = vTravelFk, b.entryFk = vEntryFk)
+ GROUP BY itemFk
+ ) b ON b.itemFk = i.id
+ LEFT JOIN (
+ SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ LEFT JOIN parking pk ON pk.id = sh.parkingFk
+ WHERE ish.created BETWEEN vFromTimed AND vToTimed
+ GROUP BY itemFk
+ ) ish ON ish.itemFk = id
+ WHERE b.stickers OR ish.etiquetas;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingPlacementSupplyAdd.sql b/db/routines/vn/procedures/itemShelvingPlacementSupplyAdd.sql
new file mode 100644
index 000000000..c3fc59624
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingPlacementSupplyAdd.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingPlacementSupplyAdd`(vItemShelvingFk INT, vItemPlacementSupplyFk INT, vQuantity INT)
+BEGIN
+
+ INSERT INTO vn.itemShelvingPlacementSupply( itemShelvingFk,
+ itemPlacementSupplyFk,
+ quantity,
+ userFk)
+ VALUES (vItemShelvingFk,
+ vItemPlacementSupplyFk,
+ vQuantity,
+ getUser());
+
+ UPDATE vn.itemShelving
+ SET visible = visible - vQuantity
+ WHERE id = vItemShelvingFk;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingProblem.sql b/db/routines/vn/procedures/itemShelvingProblem.sql
new file mode 100644
index 000000000..01d9d6b5a
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingProblem.sql
@@ -0,0 +1,49 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingProblem`(vSectorFk INT)
+BEGIN
+
+ DECLARE vVisibleCache INT;
+ DECLARE vWarehouseFk INT;
+
+ SELECT warehouseFk INTO vWarehouseFk
+ FROM vn.sector
+ WHERE id = vSectorFk;
+
+ CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouseFk);
+
+ SELECT t.id as ticketFk,
+ CAST(s.quantity AS DECIMAL(10,0)) as Cantidad,
+ s.itemFk,
+ s.concept,
+ v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho,
+ i.subName,
+ GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo,
+ s.id as saleFk,
+ IFNULL(sub3.transit,0) transit,
+ v.visible, s.isPicked, s.reserved, t.shipped, tst.productionOrder, mm.Id_Movimiento
+ FROM vn.ticket t
+ JOIN vn.ticketState tst ON tst.ticketFk = t.id
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN cache.visible v ON s.itemFk = v.item_id AND v.calc_id = vVisibleCache
+ LEFT JOIN vn2008.Movimientos_mark mm ON mm.Id_Movimiento = s.id AND mm.stateFk = 26
+ JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id
+ LEFT JOIN
+ (SELECT itemFk, sum(saldo) as transit
+ FROM vn.itemPlacementSupplyList
+ WHERE saldo > 0
+ AND sectorFk = vSectorFk
+ GROUP BY itemFk) sub3 ON sub3.itemFk = i.id
+ WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity
+ AND IFNULL(sub3.transit,0) < s.quantity
+ AND s.isPicked = FALSE
+ AND s.reserved = FALSE
+ AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE())
+ AND tst.isPreviousPreparable = TRUE
+ AND t.warehouseFk = vWarehouseFk
+ AND iss.sectorFk = vSectorFk
+ AND mm.Id_Movimiento IS NULL
+ ORDER BY itemFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingRadar.sql b/db/routines/vn/procedures/itemShelvingRadar.sql
new file mode 100644
index 000000000..c89a190ae
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingRadar.sql
@@ -0,0 +1,194 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingRadar`(
+ vSectorFk INT
+)
+proc:BEGIN
+/**
+ * Calcula la información detallada respecto un sector.
+ *
+ * @param vSectorFk Id de sector
+ */
+ DECLARE vCalcVisibleFk INT;
+ DECLARE vCalcAvailableFk INT;
+ DECLARE hasFatherSector BOOLEAN;
+ DECLARE vBuyerFk INT DEFAULT 0;
+ DECLARE vWarehouseFk INT DEFAULT 0;
+ DECLARE vSonSectorFk INT;
+ DECLARE vWorkerFk INT;
+
+ SELECT s.workerFk
+ INTO vWorkerFk
+ FROM vn.sector s
+ WHERE s.id = vSectorFk;
+
+ SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk
+ FROM vn.worker w
+ JOIN vn.sector s ON s.code = w.code
+ WHERE s.id = vSectorFk;
+
+ SELECT s.id INTO vSectorFk
+ FROM vn.sector s
+ WHERE s.warehouseFk = vWarehouseFk
+ AND s.isMain;
+
+ SELECT COUNT(*) INTO hasFatherSector
+ FROM vn.sector
+ WHERE sonFk = vSectorFk;
+
+ SELECT warehouseFk, sonFk INTO vWarehouseFk, vSonSectorFk
+ FROM vn.sector
+ WHERE id = vSectorFk;
+
+ CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk);
+ CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar;
+
+ IF hasFatherSector THEN
+ CREATE TEMPORARY TABLE tmp.itemShelvingRadar
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT *
+ FROM (
+ SELECT iss.itemFk,
+ i.longName,
+ i.size,
+ i.subName producer,
+ IFNULL(a.available,0) available,
+ SUM(IF(s.sonFk = vSectorFk, IFNULL(iss.visible,0), 0)) upstairs,
+ SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs,
+ IF(it.isPackaging, NULL, IFNULL(v.visible,0)) as visible,
+ vSectorFk sectorFk
+ FROM vn.itemShelvingStock iss
+ JOIN vn.sector s ON s.id = iss.sectorFk
+ JOIN vn.item i on i.id = iss.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk)
+ LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk
+ LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
+ WHERE vSectorFk IN (iss.sectorFk, s.sonFk)
+ GROUP BY iss.itemFk
+
+ UNION ALL
+
+ SELECT v.item_id,
+ i.longName,
+ i.size,
+ i.subName producer,
+ IFNULL(a.available,0) as available,
+ 0 upstairs,
+ 0 downstairs,
+ IF(it.isPackaging, NULL, v.visible) visible,
+ vSectorFk as sectorFk
+ FROM cache.visible v
+ JOIN vn.item i on i.id = v.item_id
+ JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk)
+ LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk
+ LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk
+ WHERE v.calc_id = vCalcVisibleFk
+ AND iss.itemFk IS NULL
+ AND it.isInventory
+ ) sub GROUP BY itemFk;
+
+ SELECT ishr.*,
+ CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho,
+ CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente
+ FROM tmp.itemShelvingRadar ishr
+ JOIN vn.item i ON i.id = ishr.itemFk
+ LEFT JOIN (SELECT s.itemFk, sum(s.quantity) as notPickedYed
+ FROM vn.ticket t
+ JOIN vn.ticketStateToday tst ON tst.ticketFk = t.id
+ JOIN vn.sale s ON s.ticketFk = t.id
+ WHERE t.warehouseFk = vWarehouseFk
+ AND tst.alertLevel = 0
+ GROUP BY s.itemFk
+ ) sub ON sub.itemFk = ishr.itemFk
+ ORDER BY i.typeFk, i.longName;
+ ELSE
+ CREATE TEMPORARY TABLE tmp.itemShelvingRadar
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT iss.itemFk,
+ 0 `hour`,
+ 0 `minute`,
+ '--' itemPlacementCode,
+ i.longName,
+ i.size,
+ i.subName producer,
+ i.upToDown,
+ IFNULL(a.available,0) available,
+ IFNULL(v.visible - iss.visible,0) dayEndVisible,
+ IFNULL(v.visible - iss.visible,0) firstNegative,
+ IFNULL(v.visible - iss.visible,0) itemPlacementVisible,
+ IFNULL(i.minimum * b.packing,0) itemPlacementSize,
+ ips.onTheWay,
+ iss.visible itemShelvingStock,
+ IFNULL(v.visible,0) visible,
+ b.isPickedOff,
+ iss.sectorFk
+ FROM vn.itemShelvingStock iss
+ JOIN vn.item i on i.id = iss.itemFk
+ LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN vn.buy b ON b.id = lb.buy_id
+ LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk
+ LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
+ LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay
+ FROM vn.itemPlacementSupplyList
+ WHERE saldo > 0
+ GROUP BY itemFk
+ ) ips ON ips.itemFk = i.id
+ WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk)
+ OR iss.sectorFk = vSectorFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime;
+ CREATE TEMPORARY TABLE tmp.itemOutTime
+ SELECT *,SUM(amount) quantity
+ FROM
+ (SELECT io.itemFk,
+ io.quantity amount,
+ IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours,
+ IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes
+ FROM itemTicketOut io
+ JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.itemFk
+ JOIN vn.ticket t on t.id= io.ticketFk
+ JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk
+ JOIN vn.state s ON s.id = ts.stateFk
+ LEFT JOIN vn.zone z ON z.id = t.zoneFk
+ LEFT JOIN (SELECT DISTINCT saleFk
+ FROM vn.saleTracking st
+ WHERE st.created > util.VN_CURDATE()
+ AND st.isChecked
+ ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk
+ WHERE t.warehouseFk = vWarehouseFk
+ AND s.isPicked = 0
+ AND NOT io.reserved
+ AND stPrevious.saleFk IS NULL
+ AND io.shipped >= util.VN_CURDATE()
+ AND io.shipped < util.VN_CURDATE() + INTERVAL 1 DAY
+ ) sub
+ GROUP BY itemFk, hours, minutes;
+
+ INSERT INTO tmp.itemShelvingRadar (itemFk)
+ SELECT itemFk FROM tmp.itemOutTime
+ ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity,
+ firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity),
+ `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0),
+ `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0);
+
+ UPDATE tmp.itemShelvingRadar isr
+ JOIN (SELECT s.itemFk, sum(s.quantity) amount
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN ticketLastState tls ON tls.ticketFk = t.id
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND tls.name = 'Prep Camara'
+ GROUP BY s.itemFk) sub ON sub.itemFk = isr.itemFk
+ SET isr.dayEndVisible = dayEndVisible + sub.amount,
+ firstNegative = firstNegative + sub.amount;
+
+ SELECT * FROM tmp.itemShelvingRadar;
+ END IF;
+
+ DROP TEMPORARY TABLE tmp.itemShelvingRadar;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingRadar_Entry.sql b/db/routines/vn/procedures/itemShelvingRadar_Entry.sql
new file mode 100644
index 000000000..c0b4fcda2
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingRadar_Entry.sql
@@ -0,0 +1,52 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingRadar_Entry`(vEntryFk INT)
+BEGIN
+
+ DECLARE vWarehouseFk INT DEFAULT 1;
+ DECLARE vCalcVisibleFk INT;
+ DECLARE vCalcAvailableFk INT;
+ DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE());
+
+ CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1);
+ CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.item;
+ CREATE TEMPORARY TABLE tmp.item
+ ENGINE = MEMORY
+ SELECT DISTINCT itemFk
+ FROM vn.buy
+ WHERE entryFk = vEntryFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.item2;
+ CREATE TEMPORARY TABLE tmp.item2
+ ENGINE = MEMORY
+ SELECT *
+ FROM tmp.item;
+
+ SELECT i.id as itemFk,
+ i.minimum,
+ CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) AS DECIMAL(10,0)) as enNicho,
+ CAST(IFNULL(a.available,0) AS DECIMAL(10,0)) as disponible,
+ CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) - ts.todaySold AS DECIMAL(10,0)) as finalDia
+ FROM vn.item i
+ JOIN tmp.item ti ON ti.itemFk = i.id
+ LEFT JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = i.id
+ LEFT JOIN cache.available a ON i.id = a.item_id AND a.calc_id = vCalcAvailableFk
+ LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id
+ LEFT JOIN ( SELECT s.itemFk, sum(s.quantity) as todaySold
+ FROM vn.sale s
+ JOIN tmp.item2 ti ON ti.itemFk = s.itemFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND vTodayDayEnd
+ AND t.warehouseFk = vWarehouseFk
+ AND IFNULL(tst.productionOrder,0) < 5
+ GROUP BY s.itemFK
+ ) ts ON ts.itemFk = i.id;
+
+
+ DROP TEMPORARY TABLE tmp.item;
+ DROP TEMPORARY TABLE tmp.item2;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingRadar_Entry_State_beta.sql b/db/routines/vn/procedures/itemShelvingRadar_Entry_State_beta.sql
new file mode 100644
index 000000000..c8b5d4bb4
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingRadar_Entry_State_beta.sql
@@ -0,0 +1,38 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingRadar_Entry_State_beta`(vEntryFk INT)
+BEGIN
+
+ DECLARE vWarehouseFk INT DEFAULT 1;
+ DECLARE vCalcVisibleFk INT;
+ DECLARE vCalcAvailableFk INT;
+ DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE());
+
+ CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1);
+ CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.item;
+ CREATE TEMPORARY TABLE tmp.item
+ ENGINE = MEMORY
+ SELECT DISTINCT itemFk
+ FROM vn.buy
+ WHERE entryFk = vEntryFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.item2;
+ CREATE TEMPORARY TABLE tmp.item2
+ ENGINE = MEMORY
+ SELECT *
+ FROM tmp.item;
+
+ SELECT i.id as itemFk,
+ CAST(IFNULL(iss.visible,0) - IFNULL(v.visible,0) AS DECIMAL(10,0)) as outShelving
+ FROM vn.item i
+ JOIN tmp.item ti ON ti.itemFk = i.id
+ LEFT JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = i.id
+ LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id;
+
+
+ DROP TEMPORARY TABLE tmp.item;
+ DROP TEMPORARY TABLE tmp.item2;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingSale_Add.sql b/db/routines/vn/procedures/itemShelvingSale_Add.sql
new file mode 100644
index 000000000..80eb4efca
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingSale_Add.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_Add`(vItemShelvingFk INT, vSaleFk INT, vQuantity INT)
+BEGIN
+/**
+ * Añade línea a itemShelvingSale y regulariza el carro
+ *
+ * @param vItemShelvingFk Id itemShelving
+ * @param vSaleFk Id de sale
+ * @param vQuantity cantidad a regularizar
+ */
+ INSERT INTO itemShelvingSale(itemShelvingFk,
+ saleFk,
+ quantity,
+ userFk)
+ VALUES (vItemShelvingFk,
+ vSaleFk,
+ vQuantity,
+ getUser());
+
+ UPDATE itemShelving
+ SET visible = visible - vQuantity
+ WHERE id = vItemShelvingFk;
+
+ UPDATE vn.saleTracking
+ SET isChecked = 1
+ WHERE saleFk = vSaleFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingSale_reserve.sql b/db/routines/vn/procedures/itemShelvingSale_reserve.sql
new file mode 100644
index 000000000..afe65bd78
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingSale_reserve.sql
@@ -0,0 +1,92 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserve`()
+BEGIN
+/**
+ * Reserva cantidades con ubicaciones para un conjunto de sales del mismo
+ * almacen.
+ *
+ * @table tmp.sale(saleFk, userFk)
+ */
+ DECLARE vCalcFk INT;
+ DECLARE vWarehouseFk INT;
+ DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW());
+ DECLARE vLastPickingOrder INT;
+
+ SELECT t.warehouseFk, MAX(p.pickingOrder)
+ INTO vWarehouseFk, vLastPickingOrder
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN tmp.sale ts ON ts.saleFk = s.id
+ LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk
+ LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ LEFT JOIN shelving sh ON sh.code = ish.shelvingFk
+ LEFT JOIN parking p ON p.id = sh.parkingFk
+ WHERE t.warehouseFk IS NOT NULL;
+
+ IF vWarehouseFk IS NULL THEN
+ CALL util.throw('Warehouse not set');
+ END IF;
+
+ CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
+
+ SET @outstanding = 0;
+ SET @oldsaleFk = 0;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity
+ (INDEX(saleFk))
+ ENGINE = MEMORY
+ SELECT saleFk, userFk, quantityToReserve, itemShelvingFk
+ FROM( SELECT saleFk,
+ sub.userFk,
+ itemShelvingFk ,
+ IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding),
+ @qtr := LEAST(@outstanding, available) quantityToReserve,
+ @outStanding := @outStanding - @qtr,
+ @oldsaleFk := saleFk
+ FROM(
+ SELECT ts.saleFk,
+ ts.userFk,
+ s.quantity,
+ ish.id itemShelvingFk,
+ ish.visible - IFNULL(ishr.reservedQuantity, 0) available
+ FROM tmp.sale ts
+ JOIN sale s ON s.id = ts.saleFk
+ JOIN itemShelving ish ON ish.itemFk = s.itemFk
+ LEFT JOIN (
+ SELECT itemShelvingFk, SUM(quantity) reservedQuantity
+ FROM itemShelvingSale
+ WHERE NOT isPicked
+ GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector sc ON sc.id = p.sectorFk
+ JOIN warehouse w ON w.id = sc.warehouseFk
+ JOIN productionConfig pc
+ WHERE w.id = vWarehouseFk
+ AND NOT sc.isHideForPickers
+ ORDER BY
+ s.id,
+ p.pickingOrder >= vLastPickingOrder,
+ sh.priority DESC,
+ ish.visible >= s.quantity DESC,
+ s.quantity MOD ish.grouping = 0 DESC,
+ ish.grouping DESC,
+ IF(pc.orderMode = 'Location', p.pickingOrder, ish.created)
+ )sub
+ )sub2
+ WHERE quantityToReserve > 0;
+
+ INSERT INTO itemShelvingSale(
+ itemShelvingFk,
+ saleFk,
+ quantity,
+ userFk)
+ SELECT itemShelvingFk,
+ saleFk,
+ quantityToReserve,
+ IFNULL(userFk, getUser())
+ FROM tSalePlacementQuantity spl;
+
+ DROP TEMPORARY TABLE tmp.sale;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql b/db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql
new file mode 100644
index 000000000..9a97130dd
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveByCollection`(
+ vCollectionFk INT(11)
+)
+BEGIN
+/**
+ * Reserva cantidades con ubicaciones para el contenido de una colección
+ *
+ * @param vCollectionFk Identificador de collection
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale
+ (INDEX(saleFk))
+ ENGINE = MEMORY
+ SELECT s.id saleFk, NULL userFk
+ FROM ticketCollection tc
+ JOIN sale s ON s.ticketFk = tc.ticketFk
+ LEFT JOIN (
+ SELECT DISTINCT saleFk
+ FROM saleTracking st
+ JOIN state s ON s.id = st.stateFk
+ WHERE st.isChecked
+ AND s.semaphore = 1)st ON st.saleFk = s.id
+ WHERE tc.collectionFk = vCollectionFk
+ AND st.saleFk IS NULL
+ AND NOT s.isPicked;
+
+ CALL itemShelvingSale_reserve();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql b/db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql
new file mode 100644
index 000000000..fb245062e
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveBySale`(
+ vSelf INT ,
+ vQuantity INT,
+ vUserFk INT
+)
+BEGIN
+/**
+ * Reserva cantida y ubicación para una saleFk
+ *
+ * @param vSelf Identificador de la venta
+ * @param vQuantity Cantidad a reservar
+ * @param vUserFk Id de usuario que realiza la reserva
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale
+ ENGINE = MEMORY
+ SELECT vSelf saleFk, vUserFk userFk;
+
+ CALL itemShelvingSale_reserve();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql
new file mode 100644
index 000000000..b792534fb
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql
@@ -0,0 +1,118 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setQuantity`(
+ vItemShelvingSaleFk INT(10),
+ vQuantity DECIMAL(10,0),
+ vIsItemShelvingSaleEmpty BOOLEAN
+)
+BEGIN
+/**
+ * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity
+ * en vn.itemShelvingSale y vn.sale.isPicked en caso necesario.
+ * Si la reserva de la ubicación es fallida, se regulariza la situación
+ *
+ * @param vItemShelvingSaleFk Id itemShelvingSaleFK
+ * @param vQuantity Cantidad real que se ha cogido de la ubicación
+ * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha
+ * quedado vacio tras el movimiento
+ */
+ DECLARE vSaleFk INT;
+ DECLARE vCursorSaleFk INT;
+ DECLARE vItemShelvingFk INT;
+ DECLARE vReservedQuantity INT;
+ DECLARE vRemainingQuantity INT;
+ DECLARE vItemFk INT;
+ DECLARE vUserFk INT;
+ DECLARE vDone BOOLEAN DEFAULT FALSE;
+ DECLARE vSales CURSOR FOR
+ SELECT iss.saleFk, iss.userFk
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.id = vItemShelvingSaleFk
+ AND s.itemFk = vItemFk
+ AND NOT iss.isPicked;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN
+ CALL util.throw('Booking completed');
+ END IF;
+
+ SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk
+ INTO vItemFk, vSaleFk, vItemShelvingFk
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.id = vItemShelvingSaleFk
+ AND NOT iss.isPicked;
+
+ UPDATE itemShelvingSale
+ SET isPicked = TRUE,
+ quantity = vQuantity
+ WHERE id = vItemShelvingSaleFk;
+
+ UPDATE itemShelving
+ SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity))
+ WHERE id = vItemShelvingFk;
+
+ IF vIsItemShelvingSaleEmpty THEN
+ OPEN vSales;
+l: LOOP
+ SET vDone = FALSE;
+ FETCH vSales INTO vCursorSaleFk, vUserFk;
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale
+ (INDEX(saleFk, userFk))
+ ENGINE = MEMORY
+ SELECT vCursorSaleFk, vUserFk;
+
+ CALL itemShelvingSale_reserveWhitUser();
+ DROP TEMPORARY TABLE tmp.sale;
+
+ END LOOP;
+ CLOSE vSales;
+
+ DELETE iss
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.id = vItemShelvingSaleFk
+ AND s.itemFk = vItemFk
+ AND NOT iss.isPicked;
+ END IF;
+
+ SELECT SUM(quantity) INTO vRemainingQuantity
+ FROM itemShelvingSale
+ WHERE saleFk = vSaleFk
+ AND NOT isPicked;
+
+ IF vRemainingQuantity THEN
+ CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL);
+
+ SELECT SUM(quantity) INTO vRemainingQuantity
+ FROM itemShelvingSale
+ WHERE saleFk = vSaleFk
+ AND NOT isPicked;
+
+ IF NOT vRemainingQuantity <=> 0 THEN
+ SELECT SUM(iss.quantity)
+ INTO vReservedQuantity
+ FROM itemShelvingSale iss
+ WHERE iss.saleFk = vSaleFk;
+
+ CALL saleTracking_new(
+ vSaleFk,
+ TRUE,
+ vReservedQuantity,
+ `account`.`myUser_getId`(),
+ NULL,
+ 'PREPARED',
+ TRUE);
+
+ UPDATE sale s
+ SET s.quantity = vReservedQuantity
+ WHERE s.id = vSaleFk ;
+ END IF;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingTransfer.sql b/db/routines/vn/procedures/itemShelvingTransfer.sql
new file mode 100644
index 000000000..326f8108b
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingTransfer.sql
@@ -0,0 +1,45 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingTransfer`(vItemShelvingFk INT, vShelvingFk VARCHAR(3))
+BEGIN
+/**
+ * Transfiere producto de una ubicación a otra, fusionando si coincide el
+ * packing y la fecha.
+ *
+ * @param vItemShelvingFk Identificador de itemShelving
+ * @param vShelvingFk Identificador de shelving
+ */
+ DECLARE vNewItemShelvingFk INT DEFAULT 0;
+
+ SELECT MAX(ish.id)
+ INTO vNewItemShelvingFk
+ FROM itemShelving ish
+ JOIN (
+ SELECT
+ itemFk,
+ packing,
+ created
+ FROM itemShelving
+ WHERE id = vItemShelvingFk
+ ) ish2
+ ON ish2.itemFk = ish.itemFk
+ AND ish2.packing = ish.packing
+ AND date(ish2.created) = date(ish.created)
+ WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci;
+
+ IF vNewItemShelvingFk THEN
+ UPDATE itemShelving ish
+ JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk
+ SET ish.visible = ish.visible + ish2.visible
+ WHERE ish.id = vNewItemShelvingFk;
+
+ DELETE FROM itemShelving
+ WHERE id = vItemShelvingFk;
+ ELSE
+ UPDATE itemShelving
+ SET shelvingFk = vShelvingFk
+ WHERE id = vItemShelvingFk;
+ END IF;
+
+ SELECT true;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_add.sql b/db/routines/vn/procedures/itemShelving_add.sql
new file mode 100644
index 000000000..2a4676b50
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_add.sql
@@ -0,0 +1,67 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT)
+BEGIN
+
+
+/**
+ * Añade registro o lo actualiza si ya existe.
+ *
+ * @param vShelvingFk matrícula del carro
+ * @param vBarcode el id del registro
+ * @param vQuantity indica la cantidad del producto
+ * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra
+ * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra
+ * @param vPacking el packing del producto, NULL para coger el de la ultima compra
+ * @param vWarehouseFk indica el sector
+ *
+ **/
+
+ DECLARE vItemFk INT;
+
+ SELECT barcodeToItem(vBarcode) INTO vItemFk;
+
+ SET vPacking = COALESCE(vPacking, GREATEST(vn.itemPacking(vBarcode,vWarehouseFk), 1));
+
+ SET vQuantity = vQuantity * vPacking;
+
+ IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN
+
+ INSERT IGNORE INTO parking(code) VALUES(vShelvingFk);
+ INSERT INTO shelving(code, parkingFk)
+ SELECT vShelvingFk, id
+ FROM parking
+ WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci;
+
+ END IF;
+
+ IF (SELECT COUNT(*) FROM itemShelving
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ AND itemFk = vItemFk
+ AND packing = vPacking) = 1 THEN
+
+ UPDATE itemShelving
+ SET visible = visible+vQuantity
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking;
+
+ ELSE
+ CALL cache.last_buy_refresh(FALSE);
+ INSERT INTO itemShelving( itemFk,
+ shelvingFk,
+ visible,
+ grouping,
+ packing,
+ packagingFk)
+
+ SELECT vItemFk,
+ vShelvingFk,
+ vQuantity,
+ IFNULL(vGrouping, b.grouping),
+ IFNULL(vPacking, b.packing),
+ IFNULL(vPackagingFk, b.packagingFk)
+ FROM item i
+ LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN buy b ON b.id = lb.buy_id
+ WHERE i.id = vItemFk;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_addByClaim.sql b/db/routines/vn/procedures/itemShelving_addByClaim.sql
new file mode 100644
index 000000000..851162952
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_addByClaim.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_addByClaim`(vClaimFk INT, vShelvingFk VARCHAR(3))
+BEGIN
+/**
+ * Insert items of claim into itemShelving.
+ *
+ * @param vClaimFk The claim
+ * @param vShelvingFk The shelving
+ * @table tmp.buyUltimate
+ */
+ DECLARE vWarehouseFk INT;
+
+ SELECT t.warehouseFk INTO vWarehouseFk
+ FROM claim c
+ JOIN ticket t ON t.id = c.ticketFk
+ WHERE c.id = vClaimFk;
+
+ CALL buyUltimate (vWarehouseFk, util.VN_CURDATE());
+
+ INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible)
+ SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible
+ FROM claim c
+ JOIN claimBeginning cb ON c.id = cb.claimFk
+ JOIN sale s ON s.id = cb.saleFk
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk AND bu.warehouseFk = t.warehouseFk
+ JOIN buy b ON b.id = bu.buyFk
+ WHERE c.id = vClaimFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_addList.sql b/db/routines/vn/procedures/itemShelving_addList.sql
new file mode 100644
index 000000000..c07dd985c
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_addList.sql
@@ -0,0 +1,47 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_addList`(vShelvingFk VARCHAR(3), vList TEXT, vIsChecking BOOL, vWarehouseFk INT)
+BEGIN
+/* Recorre cada elemento en la colección vList.
+ * Si el parámetro isChecking = FALSE, llama a itemShelving_add.
+ *
+ * Cuando es TRUE sólo inserta los elementos de la colección que no están ya en
+ * ese shelving, actualizando los valores del campo vn.itemShelving.isChecked
+ *
+ * param vShelvingFk Identificador de vn.shelving
+ * param vList JSON array con esta estructura: '[value1, value2, ...]'
+ * param vIsChecking Define si hay que añadir o comprobar los items
+ * param vWarehouseFk Identificador de vn.warehouse
+ */
+ DECLARE vListLength INT DEFAULT JSON_LENGTH(vList);
+ DECLARE vCounter INT DEFAULT 0;
+ DECLARE vBarcode VARCHAR(22);
+ DECLARE vPath VARCHAR(6);
+ DECLARE vItemFk INT;
+ DECLARE vIsChecked BOOL;
+
+ WHILE vCounter < vListLength DO
+ SET vPath = CONCAT('$[',vCounter,']');
+ SET vBarcode = JSON_EXTRACT(vList,vPath);
+ SET vIsChecked = NULL;
+ IF vIsChecking THEN
+ SELECT barcodeToItem(vBarcode) INTO vItemFk;
+
+ SELECT COUNT(*) INTO vIsChecked
+ FROM vn.itemShelving
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ AND itemFk = vItemFk;
+ END IF;
+
+ IF NOT (vIsChecking AND vIsChecked) THEN
+ CALL vn.itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk);
+ END IF;
+
+ UPDATE vn.itemShelving
+ SET isChecked = vIsChecked
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ AND itemFk = vItemFk;
+
+ SET vCounter = vCounter + 1;
+ END WHILE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_filterBuyer.sql b/db/routines/vn/procedures/itemShelving_filterBuyer.sql
new file mode 100644
index 000000000..7112aa48e
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_filterBuyer.sql
@@ -0,0 +1,84 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_filterBuyer`(vBuyerFk INT, vWarehouseFk INT)
+proc:BEGIN
+/**
+ * Lista de articulos filtrados por comprador
+ *
+ * @param vBuyerFk Comprador a filtrar
+ * @param vWarehouseFk Warehouse
+ * @return Lista de articulos
+ */
+ DECLARE vCalcVisibleFk INT;
+
+ CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk);
+
+ SELECT * FROM
+ (SELECT sub.itemFk,
+ sub.longName,
+ CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`,
+ CONCAT(IF(sub2.itemFk, IF(sub2.pendiente > (sub.upstairs + sub.downstairs),'(1) ','(2) '),'(3) ' ),sub.producer) producer,
+ sub.upstairs,
+ sub.downstairs,
+ sub.visible,
+ CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho,
+ sub.name itemColour
+ FROM (SELECT iss.itemFk,
+ CONCAT(i.longName, ' ', IFNULL(i.size, ''),' ', IFNULL(i.subName, '') ) longName,
+ '' size,
+ CONCAT(iss.parkingCode, ' ', iss.shelvingFk) producer,
+ 0 upstairs,
+ SUM(IFNULL(iss.visible,0)) downstairs,
+ IF(it.isPackaging, null, IFNULL(v.visible, 0)) visible,
+ ik.name
+ FROM itemShelvingStock iss
+ JOIN sector s ON s.id = iss.sectorFk
+ JOIN item i on i.id = iss.itemFk
+ LEFT JOIN ink ik ON ik.id = i.inkFk
+ JOIN itemType it ON it.id = i.typeFk
+ LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
+ WHERE s.warehouseFk = vWarehouseFk
+ AND it.workerFk = vBuyerFk
+ GROUP BY itemFk
+ ) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente
+ FROM sale s
+ LEFT JOIN saleTracking st ON st.saleFk = s.id
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN client c on c.id = t.clientFk
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND st.saleFk IS NULL
+ AND c.typeFk IN ('normal', 'trust')
+ GROUP BY s.itemFk
+ ) sub2 ON sub2.itemFk = sub.itemFk
+ UNION ALL
+ SELECT v.item_id,
+ i.longName,
+ CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`,
+ CONCAT(IF(sub5.pendiente,'(0) ','(3) ')) producer,
+ 0,
+ 0,
+ v.visible,
+ v.visible nicho,
+ ik.name itemColour
+ FROM cache.visible v
+ JOIN item i ON i.id = v.item_id
+ LEFT JOIN ink ik ON ik.id = i.inkFk
+ JOIN itemType it ON it.id = i.typeFk
+ LEFT JOIN itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk
+ LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente
+ FROM sale s
+ LEFT JOIN saleTracking st ON st.saleFk = s.id
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN client c on c.id = t.clientFk
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND st.saleFk IS NULL
+ AND c.typeFk IN ('normal', 'trust')
+ GROUP BY s.itemFk
+ ) sub5 ON sub5.itemFk = v.item_id
+ WHERE v.calc_id = vCalcVisibleFk
+ AND iss.itemFk IS NULL
+ AND it.workerFk = vBuyerFk
+ ) sub3
+ WHERE nicho
+ ORDER BY producer;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_get.sql b/db/routines/vn/procedures/itemShelving_get.sql
new file mode 100644
index 000000000..1be762f09
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_get.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_get`(IN vSelf VARCHAR(8))
+BEGIN
+/**
+* Lista artículos de itemshelving
+*
+* @param vSelf matrícula del carro
+**/
+ SELECT ish.itemFk item,
+ IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description,
+ ish.visible,
+ CEIL(ish.visible/ish.packing) stickers,
+ ish.packing,
+ ish.grouping,
+ p.code,
+ ish.id,
+ s.priority,
+ ish.isChecked,
+ ic.url
+ FROM itemShelving ish
+ JOIN item i ON i.id = ish.itemFk
+ JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci
+ LEFT JOIN parking p ON s.parkingFk = p.id
+ JOIN hedera.imageConfig ic
+ WHERE ish.shelvingFk COLLATE utf8_unicode_ci = vSelf;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_getAlternatives.sql b/db/routines/vn/procedures/itemShelving_getAlternatives.sql
new file mode 100644
index 000000000..de30d46ac
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_getAlternatives.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_getAlternatives`(vShelvingFk VARCHAR(10))
+BEGIN
+/**
+ * Devuelve un listado de posibles ubicaciones alternativas a ubicar los item de la matricula
+ * del carro que se le ha pasado.
+ *
+ * @param vShelvingFk matricula del carro
+ */
+ SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder
+ FROM itemShelving is2
+ JOIN shelving sh ON sh.code = is2.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector s ON s.id = p.sectorFk
+ LEFT JOIN operator o ON o.sectorFk = s.id AND o.workerFk = account.myUser_getId()
+ JOIN warehouse wh ON wh.id = s.warehouseFk
+ JOIN itemShelving is3 ON is3.itemFk = is2.itemFk AND is3.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
+ WHERE is2.shelvingFk <> vShelvingFk COLLATE utf8_unicode_ci
+ GROUP BY is2.id
+ ORDER BY p.pickingOrder DESC;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_getInfo.sql b/db/routines/vn/procedures/itemShelving_getInfo.sql
new file mode 100644
index 000000000..a5749bd26
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_getInfo.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_getInfo`(vItemFk VARCHAR(22))
+BEGIN
+/**
+ * Muestra información realtiva a la ubicación de un item
+ *
+ * @param vItemFk Id del item
+ */
+ SELECT vn.barcodeToItem(vItemFk)
+ INTO vItemFk;
+
+ SELECT pk.code Parking,
+ sh.code Matricula,
+ ish.visible visible,
+ ish.created created,
+ ish.itemFk itemFk,
+ sh.priority
+ FROM vn.itemShelving ish
+ JOIN vn.shelving sh ON sh.`code` = ish.shelvingFk
+ JOIN vn.parking pk ON pk.id = sh.parkingFk
+ WHERE ish.itemFk = vItemFk
+ ORDER BY sh.priority DESC, created ASC;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_getSaleDate.sql b/db/routines/vn/procedures/itemShelving_getSaleDate.sql
new file mode 100644
index 000000000..a9f9466cf
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_getSaleDate.sql
@@ -0,0 +1,165 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_getSaleDate`(vShelvingFk VARCHAR(3))
+BEGIN
+
+ /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula.
+ *
+ * @param vShelvingFk Matrícula del carro o pallet
+ */
+
+ DECLARE vWarehouseFk INT;
+ DECLARE vStockScopeDays INT;
+
+ SELECT s.warehouseFk, stockScopeDays
+ INTO vWarehouseFk, vStockScopeDays
+ FROM sector s
+ JOIN operator o ON s.id = o.sectorFk
+ JOIN productionConfig pc
+ WHERE o.workerFk = account.myUser_getId();
+
+ IF vWarehouseFk IS NULL
+ THEN CALL util.throw('WarehouseFk not setted');
+ END IF;
+
+ IF vStockScopeDays IS NULL
+ THEN CALL util.throw('StockScopeDays not setted');
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.tItems
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk, SUM(visible) visible
+ FROM itemShelving
+ WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
+ GROUP BY itemFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay
+ (INDEX (itemFk, dated))
+ ENGINE = MEMORY
+ SELECT dated,
+ SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock,
+ t3.itemFk
+ FROM (
+ SELECT t.itemFk, dated, SUM(amount) amount
+ FROM (
+ SELECT t2.itemFk, t2.amount, t2.dated
+ FROM (
+ SELECT item_id itemFk, amount, util.VN_CURDATE() dated
+ FROM cache.stock s
+ JOIN tmp.tItems i ON i.itemFk = s.item_id
+ WHERE s.warehouse_id = vWarehouseFk
+ UNION ALL
+ SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE()
+ FROM itemShelving ish
+ JOIN tmp.tItems i ON i.itemFk = ish.itemFk
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON sh.parkingFk = p.id
+ JOIN sector s ON s.id = p.sectorFk
+ WHERE s.isReserve
+ GROUP BY ish.itemFk
+ UNION ALL
+ SELECT iei.itemFk, SUM(quantity), landed
+ FROM itemEntryIn iei
+ JOIN tmp.tItems i ON i.itemFk = iei.itemFk
+ WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
+ AND iei.warehouseInFk = vWarehouseFk
+ AND NOT isVirtualStock
+ GROUP BY iei.itemFk, iei.landed
+ UNION ALL
+ SELECT ieo.itemFk, SUM(quantity), shipped
+ FROM itemEntryOut ieo
+ JOIN tmp.tItems i ON i.itemFk = ieo.itemFk
+ WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
+ AND ieo.warehouseOutFk = vWarehouseFk
+ GROUP BY ieo.itemFk, ieo.shipped
+ UNION ALL
+ SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped)
+ FROM itemTicketOut ito
+ JOIN tmp.tItems i ON i.itemFk = ito.itemFk
+ WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
+ AND ito.warehouseFk = vWarehouseFk
+ GROUP BY ito.itemFk, ito.shipped
+ ) t2
+ JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t
+ GROUP BY t.itemFk, dated
+ ) t3;
+
+ -- Se restan las entradas de hoy
+ UPDATE tmp.tStockByDay sbd
+ JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry
+ FROM itemEntryIn iei
+ JOIN tmp.tItems i ON i.itemFk = iei.itemFk
+ WHERE iei.landed = util.VN_CURDATE()
+ AND iei.warehouseInFk = vWarehouseFk
+ AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk
+ SET sbd.stock = sbd.stock - sub.todayEntry
+ WHERE sbd.dated = util.VN_CURDATE();
+
+ -- Se añaden las lineas de venta servidas
+ UPDATE tmp.tStockByDay sbd
+ JOIN (SELECT s.itemFK, SUM(quantity) amount
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE t.warehouseFk = vWarehouseFk
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight()
+ AND s.isPicked
+ GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk
+ SET sbd.stock = sbd.stock + sub.amount;
+
+ -- Se añaden los items ubicados hoy
+ UPDATE tmp.tStockByDay sbd
+ JOIN (SELECT ish.itemFK, SUM(ish.visible) amount
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector s ON s.id = p.sectorFk
+ WHERE s.warehouseFk = vWarehouseFk
+ AND NOT s.isReserve
+ AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight()
+ GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk
+ SET sbd.stock = sbd.stock + sub.amount;
+
+ SELECT ts.itemFk,
+ i.longName,
+ IF(ts.stock<=0, ts.dated, NULL) dated,
+ ts.stock,
+ sub4.visible,
+ sub4.shelvingFk
+ FROM(
+ SELECT IFNULL(sub2.minDated, sub.minDated) dated,
+ IFNULL(sub2.itemFk, sub.itemFk) itemFk
+ FROM(SELECT sbd.itemFk,
+ MIN(dated) minDated,
+ sbd.stock
+ FROM tmp.tItems ti
+ LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk
+ GROUP BY itemFk)sub
+ LEFT JOIN (
+ SELECT sbd.itemFk,
+ MIN(dated) minDated,
+ sbd.stock
+ FROM tmp.tItems ti
+ LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk
+ WHERE sbd.stock <= 0
+ GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk
+ WHERE sub2.itemFk IS NOT NULL
+ OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3
+ LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated
+ JOIN (SELECT ish.itemFk,
+ ish.visible,
+ p.sectorFk,
+ ish.shelvingFk
+ FROM itemShelving ish
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ LEFT JOIN parking p ON p.id = parkingFk
+ LEFT JOIN vn.sector s ON s.id = p.sectorFk
+ WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
+ ) sub4 ON sub4.itemFk = ts.itemFk
+ LEFT JOIN sector s ON s.id = sub4.sectorFk
+ LEFT JOIN item i ON i.id = ts.itemFk
+ WHERE NOT s.isReserve;
+
+ DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_inventory.sql b/db/routines/vn/procedures/itemShelving_inventory.sql
new file mode 100644
index 000000000..73e438fbb
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_inventory.sql
@@ -0,0 +1,63 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_inventory`(vParkingFromFk VARCHAR(8), vParkingToFk VARCHAR(8))
+BEGIN
+/**
+ * Devuelve un listado de ubicaciones a revisar
+ *
+ * @param vParkingFromFk Parking de partida, identificador de parking
+ * @param vParkingToFk Parking de llegada, identificador de parking
+ */
+ DECLARE vSectorFk INT;
+ DECLARE vPickingOrderFrom INT;
+ DECLARE vPickingOrderTo INT;
+
+ SELECT p.sectorFk, p.pickingOrder INTO vSectorFk, vPickingOrderFrom
+ FROM parking p
+ WHERE p.code = vParkingFromFk COLLATE 'utf8mb3_general_ci';
+
+ SELECT p.pickingOrder INTO vPickingOrderTo
+ FROM parking p
+ WHERE p.code = vParkingToFk COLLATE 'utf8mb3_general_ci';
+
+ CALL visible_getMisfit(vSectorFk);
+
+ SELECT ish.id,
+ p.pickingOrder,
+ p.code parking,
+ ish.shelvingFk,
+ ish.itemFk,
+ i.longName,
+ ish.visible,
+ p.sectorFk,
+ it.workerFk buyer,
+ ic.url,
+ i.image,
+ ish.isChecked,
+ CASE
+ WHEN IFNULL (s.notPrepared, 0) > sm.parked THEN 0
+ WHEN sm.visible > sm.parked THEN 1
+ ELSE 2
+ END priority
+ FROM itemShelving ish
+ JOIN item i ON i.id = ish.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ LEFT JOIN (
+ SELECT s.itemFk, sum(s.quantity) notPrepared
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ JOIN config c ON c.mainWarehouseFk = w.id
+ WHERE t.shipped BETWEEN util.VN_CURDATE()
+ AND util.dayEnd(util.VN_CURDATE())
+ AND s.isPicked = FALSE
+ GROUP BY s.itemFk
+ ) s ON s.itemFk = i.id
+ JOIN hedera.imageConfig ic
+ WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo
+ AND p.sectorFk = vSectorFk
+ ORDER BY p.pickingOrder;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_selfConsumption.sql b/db/routines/vn/procedures/itemShelving_selfConsumption.sql
new file mode 100644
index 000000000..c974d9903
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_selfConsumption.sql
@@ -0,0 +1,89 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_selfConsumption`(
+ vShelvingFk VARCHAR(10) COLLATE utf8_general_ci,
+ vItemFk INT,
+ vQuantity INT
+)
+BEGIN
+/**
+ * Leave the indicated amount on the shelf
+ * and create a ticket with the difference.
+ *
+ * @param vShelvingFk id of the shelf where the item is located.
+ * @param vItemFk article of which the self-consumption ticket is to be created.
+ * @param vQuantity amount that will stay on the shelf
+ */
+ DECLARE vVisible INT;
+ DECLARE vClientFk INT;
+ DECLARE vTicketFk INT;
+ DECLARE vWarehouseFk INT;
+ DECLARE vCompanyFk INT;
+ DECLARE vAgencyModeFk INT;
+ DECLARE vItemShelvingFk INT;
+ DECLARE vAddressFk INT;
+
+ SELECT c.id,
+ pc.clientSelfConsumptionFk,
+ s.warehouseFk,
+ pc.addressSelfConsumptionFk
+ INTO vCompanyFk,
+ vClientFk,
+ vWarehouseFk,
+ vAddressFk
+ FROM company c
+ JOIN address a ON a.clientFk = c.clientFk
+ JOIN warehouse w ON w.addressFk = a.id
+ JOIN sector s ON s.warehouseFk = w.id
+ JOIN parking p ON p.sectorFk = s.id
+ JOIN shelving s2 ON s2.parkingFk = p.id
+ JOIN productionConfig pc
+ WHERE s2.code = vShelvingFk;
+
+ IF vClientFk IS NULL THEN
+ CALL util.throw('The company does not have a customer assigned');
+ END IF;
+
+ IF vQuantity IS NULL OR vQuantity < 0 THEN
+ CALL util.throw('The shelf cannot have NULL or negative quantities');
+ END IF;
+
+ IF vShelvingFk IS NULL THEN
+ CALL util.throw('The shelf is necessary');
+ END IF;
+
+ IF vItemFk IS NULL THEN
+ CALL util.throw('The article is required to create the ticket.');
+ END IF;
+
+ SELECT SUM(visible), id INTO vVisible, vItemShelvingFk
+ FROM itemShelving
+ WHERE shelvingFk = vShelvingFk
+ AND itemFk = vItemFk;
+
+ IF vVisible IS NULL THEN
+ CALL util.throw('The item is not on the shelf.');
+ END IF;
+
+ CALL ticket_getWithParameters(
+ vClientFk,
+ vWarehouseFk,
+ CURDATE(),
+ vAddressFk,
+ vCompanyFk,
+ NULL,
+ vTicketFk
+ );
+
+ INSERT INTO sale (itemFk, ticketFk, quantity, concept)
+ SELECT vItemFk, vTicketFk, (vVisible - vQuantity), longName
+ FROM item
+ WHERE id = vItemFk;
+
+ UPDATE itemShelving
+ SET visible = IF(id = vItemShelvingFk, vQuantity, 0)
+ WHERE shelvingFk = vShelvingFk
+ AND itemFk = vItemFk;
+
+ CALL vn.ticket_setState(vTicketFk, 'DELIVERED');
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_update.sql b/db/routines/vn/procedures/itemShelving_update.sql
new file mode 100644
index 000000000..079add704
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_update.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_update`(vVisible INT, vPacking INT, vShelf INT ,vGrouping INT )
+BEGIN
+/**
+ * Actualiza itemShelving.
+ *
+ * @param vVisible la cantidad visible del registro a actualizar
+ * @param vShelf el id del registro a actualizar
+ * @param vPacking el packing del del producto en itemShelving
+ * @param vGrouping el grouping del producto en itemShelving
+ */
+ UPDATE itemShelving
+ SET visible = vVisible,
+ packing = vPacking,
+ grouping = vGrouping
+ WHERE id = vShelf;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemTagMake.sql b/db/routines/vn/procedures/itemTagMake.sql
new file mode 100644
index 000000000..6d34ecb78
--- /dev/null
+++ b/db/routines/vn/procedures/itemTagMake.sql
@@ -0,0 +1,56 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemTagMake`(vItemFk INT)
+BEGIN
+
+/* * Crea los tags usando la tabla plantilla itemTag
+ * y si no existe a partir de la ficha del artículo.
+ * @param vItemFk El item al que se le añaden los tags
+*/
+ DECLARE vInk VARCHAR(50);
+ DECLARE vSize INTEGER;
+ DECLARE vCategory VARCHAR(3);
+ DECLARE vProducer VARCHAR(50);
+ DECLARE vOrigin VARCHAR(20);
+ DECLARE vTypeFk INTEGER;
+
+ DELETE FROM itemTag
+ WHERE itemFk = vItemFk;
+
+ SELECT typeFk INTO vTypeFk
+ FROM item
+ WHERE id = vItemFk;
+
+ INSERT INTO itemTag(itemFk, tagFk, value, priority)
+ SELECT vItemFk, itt.tagFk, NULL, itt.priority
+ FROM itemTag it
+ LEFT JOIN itemTypeTag itt ON itt.itemTypeFk = vTypeFk
+ WHERE it.itemFk = vItemFk;
+
+ IF (SELECT COUNT(*) FROM itemTag WHERE itemFk = vItemFk LIMIT 1) = 0 THEN
+
+ SELECT ik.name, i.size, i.category, p.name, o.name
+ INTO vInk, vSize, vCategory, vProducer, vOrigin
+ FROM item i
+ LEFT JOIN ink ik ON ik.id = i.inkFk
+ LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
+ LEFT JOIN origin o ON o.id = i.originFk
+ WHERE i.id = vItemFk;
+
+ INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
+ VALUES(vItemFk, 1, vInk, 1);
+
+ INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
+ VALUES (vItemFk, 8, vSize, 2);
+
+ INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
+ VALUES(vItemFk, 47, vCategory, 3);
+
+ INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
+ VALUES(vItemFk, 37, vProducer, 4);
+
+ INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
+ VALUES(vItemFk, 35, vOrigin, 5);
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemTagReorder.sql b/db/routines/vn/procedures/itemTagReorder.sql
new file mode 100644
index 000000000..bba3cfe03
--- /dev/null
+++ b/db/routines/vn/procedures/itemTagReorder.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemTagReorder`(itemTypeFk INT)
+BEGIN
+
+ SET @isTriggerDisabled = TRUE;
+
+ -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i
+ DROP TABLE IF EXISTS tmp.item;
+ CREATE TABLE tmp.item
+ SELECT DISTINCT i.id
+ FROM vn.item i
+ WHERE i.typeFk = itemTypeFk;
+
+ UPDATE itemTag it
+ JOIN tmp.item i ON i.id = it.itemFk
+ JOIN vn.item ON item.id = i.id
+ JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk
+ SET it.priority = itt.priority
+ WHERE itt.itemTypeFk = itemTypeFk;
+
+ CALL item_refreshTags();
+
+ SET @isTriggerDisabled = FALSE;
+
+ DROP TABLE tmp.item;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemTagReorderByName.sql b/db/routines/vn/procedures/itemTagReorderByName.sql
new file mode 100644
index 000000000..89dc92740
--- /dev/null
+++ b/db/routines/vn/procedures/itemTagReorderByName.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemTagReorderByName`(vName VARCHAR(255))
+BEGIN
+
+ SET @isTriggerDisabled = TRUE;
+
+ -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i
+ DROP TABLE IF EXISTS tmp.item;
+ CREATE TABLE tmp.item
+ SELECT DISTINCT i.id
+ FROM vn.item i
+ WHERE i.`name` LIKE CONCAT(vName,'%');
+
+ UPDATE itemTag it
+ JOIN tmp.item i ON i.id = it.itemFk
+ JOIN vn.item ON item.id = i.id
+ JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk
+ SET it.priority = itt.priority
+ WHERE itt.itemTypeFk = itemTypeFk;
+
+ CALL item_refreshTags();
+
+ SET @isTriggerDisabled = FALSE;
+
+ DROP TABLE tmp.item;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemTag_replace.sql b/db/routines/vn/procedures/itemTag_replace.sql
new file mode 100644
index 000000000..b32285072
--- /dev/null
+++ b/db/routines/vn/procedures/itemTag_replace.sql
@@ -0,0 +1,35 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemTag_replace`(vItemFromFk INT, vItemToFk INT, vPicture VARCHAR(100))
+BEGIN
+
+ /* Reemplaza los tags de un artículo por los de otro, así como su imagen
+ *
+ * @param vItemFromFk id de vn.item con el artículo del que se toman los tags
+ * @param vItemToFk id de vn.item con el artículo del que se toman los tags
+ * @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk
+ */
+
+ DELETE FROM vn.itemTag
+ WHERE itemFk = vItemToFk;
+
+ INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
+ SELECT vItemToFk, tagFk, value, priority
+ FROM vn.itemTag
+ WHERE itemFk = vItemFromFk;
+
+ IF ISNULL(vPicture) THEN
+
+ SELECT image INTO vPicture
+ FROM vn.item
+ WHERE id = vItemFromFk;
+
+ END IF;
+
+ UPDATE vn.item i
+ SET i.image = vPicture
+ WHERE i.id = vItemToFk;
+
+ CALL vn.itemRefreshTags(vItemToFk);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemTopSeller.sql b/db/routines/vn/procedures/itemTopSeller.sql
new file mode 100644
index 000000000..f42cf67cf
--- /dev/null
+++ b/db/routines/vn/procedures/itemTopSeller.sql
@@ -0,0 +1,63 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemTopSeller`()
+BEGIN
+ DECLARE vCategoryFk INTEGER;
+ DECLARE vDone INT DEFAULT FALSE;
+ DECLARE rs CURSOR FOR
+ SELECT DISTINCT id
+ FROM vn.itemCategory
+ WHERE merchandise <> FALSE;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
+ RESIGNAL;
+ END;
+
+ DROP TABLE IF EXISTS tmp.topSellerMin;
+ CREATE TEMPORARY TABLE tmp.topSellerMin ENGINE = MEMORY
+ SELECT s.itemFk, SUM(s.quantity) AS total, v.tipo_id typeFk
+ FROM vn.sale s
+ INNER JOIN bs.ventas v ON v.Id_Movimiento = s.id
+ WHERE v.fecha BETWEEN TIMESTAMPADD(DAY, - 7, util.VN_CURDATE()) AND util.VN_CURDATE()
+ GROUP BY s.itemFk;
+
+ DROP TABLE IF EXISTS tmp.topSeller;
+ CREATE TEMPORARY TABLE tmp.topSeller
+ (
+ `id` int(11) NOT NULL DEFAULT '0',
+ `typeFk` smallint(5) unsigned NOT NULL,
+ `itemCategoryFk` int(10) unsigned NOT NULL,
+ `total` bigint(21) NOT NULL DEFAULT '0'
+ ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
+
+ OPEN rs;
+ read_loop: LOOP
+ FETCH rs INTO vCategoryFk;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ INSERT INTO tmp.topSeller
+ SELECT tsm.itemFk, tsm.typeFk, it.categoryFk, tsm.total
+ FROM tmp.topSellerMin tsm
+ INNER JOIN vn.itemType it ON it.id = tsm.typeFk
+ WHERE it.categoryFk = vCategoryFk
+ ORDER BY tsm.itemFk ,tsm.total DESC
+ LIMIT 5;
+
+ END LOOP;
+ CLOSE rs;
+
+ SELECT i.name ,i.id, i.image, i.typeFk, it.categoryFk AS itemCategoryFk,
+ ic.name AS itemCategoryName, it.name AS itemTypeName, ts.total
+ FROM tmp.topSeller ts
+ INNER JOIN vn.item i ON i.id = ts.id
+ INNER JOIN vn.itemType it ON it.id = ts.typeFk
+ INNER JOIN vn.itemCategory ic ON ic.id = it.categoryFk;
+
+ DROP TABLE IF EXISTS topSellerMin;
+ DROP TABLE IF EXISTS tmp.topSeller;
+
+END$$
+DELIMITER ;
diff --git a/db/changes/234001/00-item_setVisibleDiscard.sql b/db/routines/vn/procedures/itemTrash.sql
similarity index 67%
rename from db/changes/234001/00-item_setVisibleDiscard.sql
rename to db/routines/vn/procedures/itemTrash.sql
index 6ee66a947..bbb30b78a 100644
--- a/db/changes/234001/00-item_setVisibleDiscard.sql
+++ b/db/routines/vn/procedures/itemTrash.sql
@@ -1,32 +1,27 @@
-
DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDiscard`(
- vItemFk INT,
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemTrash`(
+ vItemFk INT,
vWarehouseFk INT,
vQuantity INT,
- vAddressFk INT)
-
+ vIsTrash BOOLEAN)
BEGIN
DECLARE vTicketFk INT;
DECLARE vClientFk INT;
- DECLARE vCompanyVnlFk INT;
+ DECLARE vCompanyVnlFk INT DEFAULT 442;
DECLARE vCalc INT;
SELECT barcodeToItem(vItemFk) INTO vItemFk;
- SELECT DEFAULT(companyFk) INTO vCompanyVnlFk
- FROM vn.ticket LIMIT 1;
-
- SELECT a.clientFk INTO vClientFk
- FROM address a
- WHERE a.id = vAddressFk;
+ SELECT IF(vIsTrash, 200, 400) INTO vClientFk;
SELECT t.id INTO vTicketFk
FROM ticket t
- JOIN address a ON a.id = t.addressFk
+ JOIN address a ON a.id=t.addressFk
WHERE t.warehouseFk = vWarehouseFk
- AND a.id = vAddressFk
- AND DATE(t.shipped) = util.VN_CURDATE();
+ AND t.clientFk = vClientFk
+ AND DATE(t.shipped) = util.VN_CURDATE()
+ AND a.isDefaultAddress
+ LIMIT 1;
CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk);
@@ -36,7 +31,7 @@ BEGIN
util.VN_CURDATE(),
vWarehouseFk,
vCompanyVnlFk,
- vAddressFk,
+ NULL,
NULL,
NULL,
util.VN_CURDATE(),
@@ -48,7 +43,7 @@ BEGIN
INSERT INTO sale(ticketFk, itemFk, concept, quantity)
SELECT vTicketFk,
vItemFk,
- CONCAT(longName,' ', getWorkerCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)),
+ CONCAT(longName,' ',worker_getCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)),
vQuantity
FROM item
WHERE id = vItemFk;
@@ -59,4 +54,3 @@ BEGIN
AND item_id = vItemFk;
END$$
DELIMITER ;
-
diff --git a/db/routines/vn/procedures/itemUpdateTag.sql b/db/routines/vn/procedures/itemUpdateTag.sql
new file mode 100644
index 000000000..59529e2b0
--- /dev/null
+++ b/db/routines/vn/procedures/itemUpdateTag.sql
@@ -0,0 +1,41 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemUpdateTag`(IN vItem BIGINT)
+BEGIN
+
+
+UPDATE item i
+JOIN producer p ON p.id = i.producerFk
+SET i.subName = p.name
+WHERE p.isVisible
+AND (vItem IS NULL OR vItem = i.id);
+
+UPDATE item i
+JOIN itemTag it ON it.itemFk = i.id
+JOIN tag t ON t.id = it.tagFk
+SET tag5 = t.name, value5 = it.value
+WHERE it.priority = 1
+AND (vItem IS NULL OR vItem = i.id);
+
+UPDATE item i
+JOIN itemTag it ON it.itemFk = i.id
+JOIN tag t ON t.id = it.tagFk
+SET tag6 = t.name, value6 = it.value
+WHERE it.priority = 2
+AND (vItem IS NULL OR vItem = it.itemFk);
+
+UPDATE item i
+JOIN itemTag it ON it.itemFk = i.id
+JOIN tag t ON t.id = it.tagFk
+SET tag7 = t.name, value7 = it.value
+WHERE it.priority = 3
+AND (vItem IS NULL OR vItem = it.itemFk);
+
+UPDATE item i
+JOIN itemTag it ON it.itemFk = i.id
+JOIN tag t ON t.id = it.tagFk
+SET tag8 = t.name, value8 = it.value
+WHERE it.priority = 4
+AND (vItem IS NULL OR vItem = it.itemFk);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_GetVisible.sql b/db/routines/vn/procedures/item_GetVisible.sql
new file mode 100644
index 000000000..ca5e43107
--- /dev/null
+++ b/db/routines/vn/procedures/item_GetVisible.sql
@@ -0,0 +1,43 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_GetVisible`(vWarehouse SMALLINT, vItem INT)
+BEGIN
+ DECLARE vTomorrow DATETIME DEFAULT TIMESTAMPADD(DAY, 1, util.VN_CURDATE());
+
+ INSERT INTO tmp.itemVisible (item_id, visible)
+ SELECT item_id, SUM(amount) amount
+ FROM (
+ SELECT i.itemFk AS item_id, quantity AS amount
+ FROM itemTicketOut i
+ LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk
+ JOIN state s ON s.id = ts.stateFk
+ LEFT JOIN (SELECT DISTINCT saleFk
+ FROM saleTracking st
+ JOIN state s ON s.id = st.stateFk
+ WHERE st.created > util.VN_CURDATE()
+ AND (s.isPicked OR st.isChecked)
+ ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk
+ WHERE i.warehouseFk = vWarehouse
+ AND (vItem IS NULL OR i.itemFk = vItem)
+ AND (s.isPicked OR i.reserved OR stPrevious.saleFk )
+ AND i.shipped >= util.VN_CURDATE() AND i.shipped < vTomorrow
+ UNION ALL
+ SELECT iei.itemFk, quantity
+ FROM itemEntryIn iei
+ WHERE (iei.isReceived != FALSE /*OR ip.modificationDate > util.VN_CURDATE()*/)
+ AND iei.landed >= util.VN_CURDATE() AND iei.landed < vTomorrow
+ AND iei.warehouseInFk = vWarehouse
+ AND (vItem IS NULL OR iei.itemFk = vItem)
+ AND iei.isVirtualStock is FALSE
+ UNION ALL
+ SELECT itemFk, quantity
+ FROM itemEntryOut
+ WHERE isDelivered != FALSE
+ AND shipped >= util.VN_CURDATE() AND shipped < vTomorrow
+ AND warehouseOutFk = vWarehouse
+ AND (vItem IS NULL OR itemFk = vItem)
+ ) t
+ GROUP BY item_id
+ ON DUPLICATE KEY UPDATE
+ visible = IFNULL(stock,0) + VALUES(visible);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_ValuateInventory.sql b/db/routines/vn/procedures/item_ValuateInventory.sql
new file mode 100644
index 000000000..bfd96fa82
--- /dev/null
+++ b/db/routines/vn/procedures/item_ValuateInventory.sql
@@ -0,0 +1,237 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_ValuateInventory`(vDated DATE, vIsDetailed BOOLEAN)
+BEGIN
+ DECLARE vInventoried DATE;
+ DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE;
+ DECLARE vInventoryClone DATE;
+ DECLARE vDateDayEnd DATETIME;
+ DECLARE vInventorySupplierFk INT;
+
+ SELECT inventorySupplierFk INTO vInventorySupplierFk
+ FROM entryConfig;
+
+ SET vDateDayEnd = util.dayEnd(vDated);
+
+ SELECT tr.landed INTO vInventoried
+ FROM travel tr
+ JOIN `entry` e ON e.travelFk = tr.id
+ JOIN entryConfig ec
+ WHERE landed <= vDateDayEnd
+ AND e.supplierFk = vInventorySupplierFk
+ ORDER BY tr.landed DESC
+ LIMIT 1;
+
+ SET vHasNotInventory = (vInventoried IS NULL);
+
+ IF vHasNotInventory THEN
+ SELECT landed INTO vInventoryClone
+ FROM travel tr
+ JOIN `entry` e ON e.travelFk = tr.id
+ JOIN entryConfig ec
+ WHERE landed >= vDated
+ AND e.supplierFk = vInventorySupplierFk
+ ORDER BY landed ASC
+ LIMIT 1;
+
+ SET vInventoried = vDated + INTERVAL 1 DAY;
+ SET vDateDayEnd = vInventoryClone;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tInventory(
+ warehouseFk SMALLINT,
+ itemFk BIGINT,
+ quantity INT,
+ cost DOUBLE DEFAULT 0,
+ total DOUBLE DEFAULT 0,
+ warehouseInventory VARCHAR(20),
+ PRIMARY KEY (warehouseInventory, itemFk) USING HASH
+ )
+ ENGINE = MEMORY;
+
+ -- Inventario inicial
+ IF vHasNotInventory THEN
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ SUM(b.quantity),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse w ON w.id = warehouseInFk
+ JOIN entryConfig ec
+ WHERE landed = vDateDayEnd
+ AND e.supplierFk = vInventorySupplierFk
+ AND w.valuatedInventory
+ AND t.isInventory
+ GROUP BY tr.warehouseInFk, b.itemFk;
+ ELSE
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ SUM(b.quantity),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse w ON w.id = warehouseInFk
+ JOIN entryConfig ec
+ WHERE landed = vInventoried
+ AND e.supplierFk = vInventorySupplierFk
+ AND w.valuatedInventory
+ AND t.isInventory
+ GROUP BY tr.warehouseInFk, b.itemFk;
+ END IF;
+
+ -- Añadimos las entradas
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ b.quantity * IF(vHasNotInventory, -1, 1),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse w ON w.id = tr.warehouseInFk
+ JOIN entryConfig ec
+ WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
+ AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE)
+ AND NOT e.isRaid
+ AND w.valuatedInventory
+ AND t.isInventory
+ AND e.supplierFk <> vInventorySupplierFk
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory, -1, 1));
+
+ -- Descontamos las salidas
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseOutFk,
+ b.itemFk,
+ b.quantity * IF(vHasNotInventory, 1, -1),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse w ON w.id = tr.warehouseOutFk
+ WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd
+ AND NOT e.isRaid
+ AND w.valuatedInventory
+ AND t.isInventory
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory,1,-1));
+
+ -- Descontamos las lineas de venta
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT w.id,
+ s.itemFk,
+ s.quantity * IF(vHasNotInventory, 1, -1),
+ w.name
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN `client` c ON c.id = t.clientFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vInventoried AND vDateDayEnd
+ AND w.valuatedInventory
+ AND it.isInventory
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1);
+
+ -- Volver a poner lo que esta aun en las estanterias
+ IF vDated = util.VN_CURDATE() THEN
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT w.id,
+ s.itemFk,
+ s.quantity * IF(vHasNotInventory, 0, 1),
+ w.name
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN `client` c ON c.id = t.clientFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDated AND vDateDayEnd
+ AND NOT (s.isPicked OR t.isLabeled)
+ AND w.valuatedInventory
+ AND it.isInventory
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 0, 1);
+ END IF;
+
+ -- Mercancia en transito
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ b.quantity,
+ CONCAT(wOut.`name`, ' - ', wIn.`name`)
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
+ JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
+ WHERE vDated >= tr.shipped AND vDated < tr.landed
+ AND NOT isRaid
+ AND wIn.valuatedInventory
+ AND t.isInventory
+ AND e.isConfirmed
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity);
+
+ CALL vn.buyUltimate(NULL, vDateDayEnd);
+
+ UPDATE tInventory i
+ JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.itemFk = bu.itemFk
+ JOIN buy b ON b.id = bu.buyFk
+ SET total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)),
+ cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)
+ WHERE i.quantity;
+
+ DELETE FROM tInventory
+ WHERE quantity IS NULL OR NOT quantity;
+
+ IF vIsDetailed THEN
+ SELECT ti.warehouseFk,
+ i.id itemFk,
+ i.longName,
+ i.size,
+ ti.quantity,
+ tp.name Tipo,
+ ic.name Reino,
+ ti.cost,
+ CAST(ti.total AS DECIMAL(10, 2)) total,
+ ti.warehouseInventory almacen
+ FROM tInventory ti
+ JOIN warehouse w ON w.id = warehouseFk
+ JOIN item i ON i.id = ti.itemFk
+ JOIN itemType tp ON tp.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
+ WHERE w.valuatedInventory
+ AND ti.total > 0
+ ORDER BY ti.total DESC;
+ ELSE
+ SELECT i.warehouseInventory Almacen,
+ ic.name Reino,
+ CAST(i.total AS DECIMAL(10, 2)) Euros,
+ w.code Comprador,
+ it.id
+ FROM tInventory i
+ JOIN warehouse wh ON wh.id = warehouseFk
+ JOIN item it ON it.id = i.itemFk
+ JOIN itemType itp ON itp.id = it.typeFk
+ LEFT JOIN worker w ON w.id = itp.workerFk
+ JOIN itemCategory ic ON ic.id = itp.categoryFk
+ WHERE wh.valuatedInventory
+ AND i.total > 0;
+ END IF;
+
+ DROP TEMPORARY TABLE
+ tmp.buyUltimate,
+ tInventory;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_cleanFloramondo.sql b/db/routines/vn/procedures/item_cleanFloramondo.sql
new file mode 100644
index 000000000..cae06ee54
--- /dev/null
+++ b/db/routines/vn/procedures/item_cleanFloramondo.sql
@@ -0,0 +1,203 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_cleanFloramondo`()
+BEGIN
+/**
+* Elimina todos los items repetidos de floramondo
+* y los sustituye por el que tiene menor id
+*/
+ DECLARE vItemFrom INT;
+ DECLARE vItemEnd INT;
+ DECLARE vItemOld INT;
+ DECLARE vItemNew INT;
+ DECLARE vCurrentItem INT;
+ DECLARE vQuantity INT;
+ DECLARE vCounter INT DEFAULT 0;
+ DECLARE vIsStop BOOL DEFAULT FALSE;
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE curItemClean CURSOR FOR
+ SELECT GREATEST(i.id, i2.id) idOld,
+ LEAST(i.id, i2.id) idNew
+ FROM item i
+ JOIN (
+ SELECT i.id,
+ i.name,
+ i.subname,
+ i.value5,
+ i.value6,
+ i.value7,
+ i.value8,
+ i.value9,
+ i.value10,
+ i.NumberOfItemsPerCask,
+ i.EmbalageCode,
+ i.quality
+ FROM item i
+ LEFT JOIN (
+ SELECT i.id,
+ sr.NumberOfUnits,
+ MAX(di.LatestOrderDateTime) lodt
+ FROM item i
+ JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
+ JOIN edi.deliveryInformation di ON di.supplyResponseID = i.supplyResponseFk
+ GROUP BY i.id
+ )sub ON sub.id = i.id
+ WHERE i.isFloramondo
+ AND (i.supplyResponseFk IS NULL
+ OR sub.NumberOfUnits = 0
+ OR sub.lodt < util.VN_NOW())
+ GROUP BY i.name,
+ i.subname,
+ i.value5,
+ i.value6,
+ i.value7,
+ i.value8,
+ i.value9,
+ i.value10,
+ i.NumberOfItemsPerCask,
+ i.EmbalageCode,
+ i.quality
+ ) i2 ON i2.name <=> i.name
+ AND i2.subname <=> i.subname
+ AND i2.value5 <=> i.value5
+ AND i2.value6 <=> i.value6
+ AND i2.value7 <=> i.value7
+ AND i2.value8 <=> i.value8
+ AND i2.value9 <=> i.value9
+ AND i2.value10 <=> i.value10
+ AND i2.NumberOfItemsPerCask <=> i.NumberOfItemsPerCask
+ AND i2.EmbalageCode <=> i.EmbalageCode
+ AND i2.quality <=> i.quality
+ JOIN (
+ SELECT DISTINCT b.itemFk
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ WHERE i.isFloramondo
+ AND NOT b.printedStickers
+ )sub2 ON sub2.itemFk = GREATEST(i.id, i2.id)
+ WHERE i.isFloramondo
+ AND i.id <> i2.id;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION SET vDone = TRUE;
+ BEGIN
+ SET vDone = TRUE;
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ SET @isModeInventory:= TRUE;
+
+ OPEN curItemClean;
+ curItemClean: LOOP
+
+ FETCH curItemClean INTO vItemOld, vItemNew;
+
+ START TRANSACTION;
+
+ # Deletes
+ UPDATE IGNORE itemCost
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ DELETE FROM itemCost
+ WHERE itemFk = vItemOld;
+
+ DELETE FROM vn2008.rec_translator
+ WHERE Id_Article = vItemOld;
+
+ DELETE FROM bs.waste
+ WHERE itemFk = vItemOld;
+
+ DELETE FROM priceFixed
+ WHERE itemFk = vItemOld;
+
+ DELETE FROM itemMatchProperties
+ WHERE itemFk = vItemOld;
+
+ DELETE FROM itemBotanical
+ WHERE itemFk = vItemOld;
+
+ DELETE FROM itemProposal
+ WHERE itemFk = vItemOld;
+
+ SET @isTriggerDisabled := TRUE;
+ DELETE FROM itemTag
+ WHERE itemFk = vItemOld;
+ SET @isTriggerDisabled := FALSE;
+
+ DELETE FROM itemBarcode
+ WHERE itemFk = vItemOld;
+
+ DELETE FROM itemTaxCountry
+ WHERE itemFk = vItemOld;
+
+ # Updates
+ UPDATE buy
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ UPDATE sale
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ UPDATE specialPrice
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ UPDATE packaging
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ UPDATE packaging
+ SET freightItemFk = vItemNew
+ WHERE freightItemFk = vItemOld;
+
+ UPDATE hedera.orderRow
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ UPDATE itemLog
+ SET originFk = vItemNew
+ WHERE originFk = vItemOld;
+
+ UPDATE itemShelving
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ UPDATE ticketPackagingStartingStock
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ UPDATE inventoryFailure
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ UPDATE genericAllocation
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ UPDATE itemPlacementSupply
+ SET itemFk = vItemNew
+ WHERE itemFk = vItemOld;
+
+ # Mantenemos la imagen si el nuevo no tiene
+ UPDATE vn.item itemNew
+ LEFT JOIN item itemOld ON itemOld.id = vItemOld
+ AND itemOld.image IS NOT NULL
+ SET itemNew.image = itemOld.image
+ WHERE itemNew.id = vItemNew
+ AND itemNew.image IS NULL;
+
+ # Eliminamos el item sustituido
+ DELETE FROM item
+ WHERE id = vItemOld;
+
+ COMMIT;
+
+ SET vCounter = vCounter + 1;
+
+ END LOOP;
+ CLOSE curItemClean;
+
+ SET @isModeInventory:= FALSE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_comparative.sql b/db/routines/vn/procedures/item_comparative.sql
new file mode 100644
index 000000000..e72188363
--- /dev/null
+++ b/db/routines/vn/procedures/item_comparative.sql
@@ -0,0 +1,297 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_comparative`(
+ vDate DATETIME,
+ vDayRange TINYINT,
+ vWarehouseFk TINYINT,
+ vAvailableSince DATE,
+ vBuyerFk INT,
+ vIsFloramondo BOOL,
+ vCountryFk INT
+)
+proc: BEGIN
+/**
+ * Genera una tabla de comparativa de artículos por itemType/comprador/fecha.
+ * Los datos se calculan en función de los parámetros proporcionados.
+ *
+ * @param vDate La fecha para la cual se generará la comparativa.
+ * @param vDayRange El rango de días a considerar para la comparativa.
+ * @param vWarehouseFk El identificador del almacén para filtrar los artículos.
+ * @param vAvailableSince La fecha de disponibilidad desde la cual se consideran los artículos disponibles.
+ * @param vBuyerFk El identificador del comprador para filtrar los artículos.
+ * @param vIsFloramondo Indica si se deben incluir solo los artículos de Floramondo (opcional).
+ * @param vCountryFk El identificador del país.
+ * @param tmp.comparativeFilterType(filterFk INT ,itemTypeFk INT)
+ * @return tmp.comparative
+ */
+
+ DECLARE vDayRangeStart DATE;
+ DECLARE vDayRangeEnd DATE;
+ DECLARE w1, w2, w3, w4, w5, w6, w7 INT;
+ DECLARE y1, y2, y3, y4, y5, y6, y7 INT;
+ DECLARE z1, z2, z3, z4, z5, z6, z7 INT;
+ DECLARE vPeriod INT;
+ DECLARE i INT DEFAULT 0;
+ DECLARE vHasTypeFilter BOOL;
+ DECLARE vWeekRange INT;
+ DECLARE vWeekCount TINYINT;
+ DECLARE vMaxDayRange INT;
+ DECLARE vMinDayRange INT;
+ DECLARE vDefaultDayRange INT;
+
+ IF NOT(SELECT COUNT(*) FROM comparativeConfig)THEN
+ LEAVE proc;
+ END IF;
+
+ SELECT weekRange,
+ weekRange * 2 + 1,
+ maxDayRange,
+ minDayRange,
+ defaultDayRange
+ INTO vWeekRange,
+ vWeekCount,
+ vMaxDayRange,
+ vMinDayRange,
+ vDefaultDayRange
+ FROM comparativeConfig;
+
+ IF vDayRange < vMinDayRange OR vDayRange > vMaxDayRange THEN
+ SET vDayRange = vDefaultDayRange;
+ END IF;
+
+ SELECT MIN(dated) INTO vDayRangeStart
+ FROM vn.time
+ WHERE dated <= vDate
+ GROUP BY period
+ ORDER BY dated desc
+ LIMIT 1 OFFSET vWeekRange;
+
+ SELECT MAX(dated) INTO vDayRangeEnd
+ FROM vn.time
+ WHERE dated >= vDate
+ GROUP BY period
+ ORDER BY dated ASC
+ LIMIT 1 OFFSET vWeekRange;
+
+ SELECT COUNT(itemTypeFk) > 0 INTO vHasTypeFilter
+ FROM tmp.comparativeFilterType;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemInventory
+ (PRIMARY KEY (id))
+ ENGINE = MEMORY
+ SELECT i.id
+ FROM item i
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN itemCategory c ON c.id = t.categoryFk
+ LEFT JOIN worker w ON w.id = t.workerFk
+ WHERE (NOT vHasTypeFilter
+ OR t.id IN (SELECT itemTypeFk FROM tmp.comparativeFilterType))
+ AND (vBuyerFk IS NULL
+ OR t.workerFk = vBuyerFk)
+ AND (vIsFloramondo IS NULL
+ OR i.isFloramondo = vIsFloramondo);
+
+ IF vDate < util.VN_CURDATE() THEN
+ ALTER TABLE tmp.itemInventory
+ ADD `buy_id` INT NOT NULL DEFAULT 0,
+ ADD `buy_date` DATE DEFAULT '2000-01-01',
+ ADD `life` INT DEFAULT 0,
+ ADD `sd` INT DEFAULT 0,
+ ADD `avalaible` INT DEFAULT 0,
+ ADD `visible` INT DEFAULT 0;
+ ELSE
+ CALL multipleInventory(vAvailableSince, vWarehouseFk, vDayRange);
+ CALL item_multipleBuy(vDate, vWarehouseFk);
+ CALL item_multipleBuyByDate(vDate, vWarehouseFk);
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTable (
+ cy INT(6) PRIMARY KEY,
+ ly INT(6),
+ zy INT(6),
+ INDEX (ly)
+ );
+
+ REPEAT
+ SET i = i + 1;
+
+ SELECT t.period INTO vPeriod
+ FROM vn.`time` t
+ WHERE t.dated = vDayRangeStart + INTERVAL (vWeekCount * (i - 1)) DAY;
+
+ INSERT IGNORE INTO tTable(cy, ly, zy) VALUES(vPeriod, vPeriod - 100, vPeriod - 200);
+ UNTIL i = vWeekCount END REPEAT;
+
+ SELECT cy, ly, zy INTO w1, y1, z1 FROM tTable LIMIT 1;
+ SELECT cy, ly, zy INTO w2, y2, z2 FROM tTable WHERE cy > w1 LIMIT 1;
+ SELECT cy, ly, zy INTO w3, y3, z3 FROM tTable WHERE cy > w2 LIMIT 1;
+ SELECT cy, ly, zy INTO w4, y4, z4 FROM tTable WHERE cy > w3 LIMIT 1;
+ SELECT cy, ly, zy INTO w5, y5, z5 FROM tTable WHERE cy > w4 LIMIT 1;
+ SELECT cy, ly, zy INTO w6, y6, z6 FROM tTable WHERE cy > w5 LIMIT 1;
+ SELECT cy, ly, zy INTO w7, y7, z7 FROM tTable WHERE cy > w6 LIMIT 1;
+
+ -- Genera una tabla con los datos del año pasado.
+
+ CREATE OR REPLACE TEMPORARY TABLE tLastYear
+ (KEY (lItemFk))
+ ENGINE = MEMORY
+ SELECT c.itemFk lItemFk,
+ SUM(IF(c.timePeriod = y1, c.quantity, 0)) lweek1,
+ SUM(IF(c.timePeriod = y2, c.quantity, 0)) lweek2,
+ SUM(IF(c.timePeriod = y3, c.quantity, 0)) lweek3,
+ SUM(IF(c.timePeriod = y4, c.quantity, 0)) lweek4,
+ SUM(IF(c.timePeriod = y5, c.quantity, 0)) lweek5,
+ SUM(IF(c.timePeriod = y6, c.quantity, 0)) lweek6,
+ SUM(IF(c.timePeriod = y7, c.quantity, 0)) lweek7,
+ SUM(IF(c.timePeriod = y1, c.price, 0)) lprice1,
+ SUM(IF(c.timePeriod = y2, c.price, 0)) lprice2,
+ SUM(IF(c.timePeriod = y3, c.price, 0)) lprice3,
+ SUM(IF(c.timePeriod = y4, c.price, 0)) lprice4,
+ SUM(IF(c.timePeriod = y5, c.price, 0)) lprice5,
+ SUM(IF(c.timePeriod = y6, c.price, 0)) lprice6,
+ SUM(IF(c.timePeriod = y7, c.price, 0)) lprice7
+ FROM tmp.itemInventory ai
+ JOIN comparative c ON c.itemFk = ai.id
+ JOIN warehouse w on w.id = c.warehouseFk
+ JOIN tTable wt ON c.timePeriod = wt.ly
+ WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk
+ AND w.isComparative
+ AND (vCountryFk IS NULL OR c.countryFk = vCountryFk)
+ GROUP BY ai.id;
+
+ -- Genera una tabla con los datos de hace DOS años.
+
+ CREATE OR REPLACE TEMPORARY TABLE tTwoYearsAgo
+ (KEY (tItemFk))
+ ENGINE = MEMORY
+ SELECT c.itemFk tItemFk,
+ SUM(IF(c.timePeriod = z1, c.quantity, 0)) vlweek1,
+ SUM(IF(c.timePeriod = z2, c.quantity, 0)) vlweek2,
+ SUM(IF(c.timePeriod = z3, c.quantity, 0)) vlweek3,
+ SUM(IF(c.timePeriod = z4, c.quantity, 0)) vlweek4,
+ SUM(IF(c.timePeriod = z5, c.quantity, 0)) vlweek5,
+ SUM(IF(c.timePeriod = z6, c.quantity, 0)) vlweek6,
+ SUM(IF(c.timePeriod = z7, c.quantity, 0)) vlweek7,
+ SUM(IF(c.timePeriod = z1, c.price, 0)) vlprice1,
+ SUM(IF(c.timePeriod = z2, c.price, 0)) vlprice2,
+ SUM(IF(c.timePeriod = z3, c.price, 0)) vlprice3,
+ SUM(IF(c.timePeriod = z4, c.price, 0)) vlprice4,
+ SUM(IF(c.timePeriod = z5, c.price, 0)) vlprice5,
+ SUM(IF(c.timePeriod = z6, c.price, 0)) vlprice6,
+ SUM(IF(c.timePeriod = z7, c.price, 0)) vlprice7
+ FROM tmp.itemInventory ai
+ JOIN comparative c ON c.itemFk = ai.id
+ JOIN warehouse w on w.id = c.warehouseFk
+ JOIN tTable wt ON c.timePeriod = wt.zy
+ WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk
+ AND w.isComparative
+ AND (vCountryFk IS NULL OR c.countryFk = vCountryFk)
+ GROUP BY ai.id;
+
+ -- Genera una tabla con los datos de este año.ss
+
+ CREATE OR REPLACE TEMPORARY TABLE tCurrentYear
+ (KEY (cItemFk))
+ ENGINE = MEMORY
+ SELECT t.itemFk cItemFk,
+ SUM(IF(week = w1, total, 0)) cweek1,
+ SUM(IF(week = w2, total, 0)) cweek2,
+ SUM(IF(week = w3, total, 0)) cweek3,
+ SUM(IF(week = w4, total, 0)) cweek4,
+ SUM(IF(week = w5, total, 0)) cweek5,
+ SUM(IF(week = w6, total, 0)) cweek6,
+ SUM(IF(week = w7, total, 0)) cweek7,
+ SUM(IF(week = w1, price, 0)) cprice1,
+ SUM(IF(week = w2, price, 0)) cprice2,
+ SUM(IF(week = w3, price, 0)) cprice3,
+ SUM(IF(week = w4, price, 0)) cprice4,
+ SUM(IF(week = w5, price, 0)) cprice5,
+ SUM(IF(week = w6, price, 0)) cprice6,
+ SUM(IF(week = w7, price, 0)) cprice7
+ FROM (
+ SELECT s.itemFk,
+ ti.period `week`,
+ SUM(s.quantity) total,
+ TRUNCATE(SUM(s.quantity * s.priceFixed),0) price
+ FROM ticket t
+ JOIN sale s ON t.id = s.ticketFk
+ JOIN tmp.itemInventory it ON it.id = s.itemFk
+ JOIN time ti ON ti.dated = DATE(t.shipped)
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType tp ON tp.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ STRAIGHT_JOIN address ad ON ad.id = t.addressFk
+ JOIN province p ON p.id = ad.provinceFk
+ JOIN `client` c ON c.id = ad.clientFk
+ WHERE t.shipped BETWEEN vDayRangeStart AND util.dayEnd(vDayRangeEnd)
+ AND c.typeFk IN ('Normal','handMaking')
+ AND w.id = COALESCE(vWarehouseFk, w.id)
+ AND w.isComparative
+ AND (vCountryFk IS NULL OR p.countryFk = vCountryFk)
+ GROUP BY i.id, week
+ ) t
+ GROUP BY t.itemFk;
+
+ -- Genera la tabla con la comparativa.
+ CREATE OR REPLACE TEMPORARY TABLE tmp.comparative
+ ENGINE = MEMORY
+ SELECT it.subName productor,
+ b.packing,
+ b.buyingValue costefijo,
+ b.groupingMode caja,
+ it.image ArticleImage,
+ IFNULL(it.inkFk,"?") color,
+ tp.code tipo,
+ it.typeFk tipo_id,
+ o.code origen,
+ it.category categoria,
+ it.stems tallos,
+ it.size medida,
+ it.name article,
+ w.code codigoTrabajador,
+ tp.categoryFk reino_id,
+ ly.*,
+ cy.*,
+ zy.*,
+ it.*,
+ it.id Id_Article,
+ i.buy_id,
+ tp.life,
+ IFNULL(i.sd,0) sd,
+ i.avalaible,
+ i.visible,
+ i.buy_date,
+ e.id provider_id,
+ it.comment comments,
+ it.description itemDescription,
+ IF(cy.cItemFk IS NULL AND i.visible = 0 AND i.avalaible = 0
+ AND IFNULL(i.sd, 0) = 0, FALSE, TRUE) filtret,
+ IF(it.hasMinPrice, FORMAT(it.minPrice, 2), "") pvp,
+ s.company_name
+ FROM tmp.itemInventory i
+ JOIN item it ON it.id = i.id
+ LEFT JOIN itemType tp ON tp.id = it.typeFk
+ LEFT JOIN worker w ON w.id = tp.workerFk
+ LEFT JOIN buy b ON b.id = i.buy_id
+ LEFT JOIN entry e ON e.id = b.entryFk
+ LEFT JOIN origin o ON o.id = it.originFk
+ LEFT JOIN tLastYear ly ON ly.lItemFk = it.id
+ LEFT JOIN tCurrentYear cy ON cy.cItemFk = it.id
+ LEFT JOIN tTwoYearsAgo zy ON zy.tItemFk = it.id
+ LEFT JOIN edi.ekt e2 ON e2.id = b.ektFk
+ LEFT JOIN edi.supplier s ON s.supplier_id = e2.pro
+ WHERE i.avalaible
+ OR i.visible
+ OR i.sd
+ OR cy.cweek1 OR cy.cweek2 OR cy.cweek3 OR cy.cweek4 OR cy.cweek5 OR cy.cweek6 OR cy.cweek7
+ OR ly.lweek1 OR ly.lweek2 OR ly.lweek3 OR ly.lweek4 OR ly.lweek5 OR ly.lweek6 OR ly.lweek7
+ OR zy.vlweek1 OR zy.vlweek2 OR zy.vlweek3 OR zy.vlweek4 OR zy.vlweek5 OR zy.vlweek6 OR zy.vlweek7;
+
+ -- Elimina las tablas temporales creadas...
+ DROP TEMPORARY TABLE IF EXISTS tmp.itemInventory,
+ tTwoYearsAgo,
+ tLastYear,
+ tCurrentYear,
+ tTable;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_deactivateUnused.sql b/db/routines/vn/procedures/item_deactivateUnused.sql
new file mode 100644
index 000000000..68a6b4978
--- /dev/null
+++ b/db/routines/vn/procedures/item_deactivateUnused.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_deactivateUnused`()
+BEGIN
+/**
+ * Cambia a false el campo isActive de la tabla vn.item para todos aquellos
+ * items que no se han comprado en los últimos meses configurados en
+ * @vn.itemConfig.monthToDeactivate
+ */
+ DECLARE vMonthToDeactivate INT;
+
+ SELECT monthToDeactivate INTO vMonthToDeactivate
+ FROM vn.itemConfig;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.buyMaxCreated;
+ CREATE TEMPORARY TABLE tmp.buyMaxCreated
+ ENGINE = MEMORY
+ SELECT b.itemFk,
+ MAX(b.created) created
+ FROM vn.buy b
+ JOIN vn.item i ON i.id = b.itemFk
+ WHERE i.isActive
+ GROUP BY itemFk;
+
+ UPDATE vn.item i
+ JOIN tmp.buyMaxCreated bmc ON bmc.itemFk = i.id
+ SET i.isActive = FALSE
+ WHERE bmc.created < util.VN_CURDATE() - INTERVAL vMonthToDeactivate MONTH;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.buyMaxCreated;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_getAtp.sql b/db/routines/vn/procedures/item_getAtp.sql
new file mode 100644
index 000000000..bbf13d396
--- /dev/null
+++ b/db/routines/vn/procedures/item_getAtp.sql
@@ -0,0 +1,48 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getAtp`(vDated DATE)
+BEGIN
+/**
+ * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y
+ * almacén.
+ *
+ * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0
+ * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity)
+ * @return tmp.itemAtp(itemFk, warehouseFk, quantity)
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tItemOrdered
+ (UNIQUE(itemFk, warehouseFk, dated))
+ ENGINE = MEMORY
+ SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity
+ FROM (
+ SELECT itemFk, warehouseFk, dated, quantity
+ FROM tmp.itemCalc
+ UNION ALL
+ SELECT itemFk, warehouseFk, vDated, 0
+ FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2
+ ) t1
+ GROUP BY itemFk, warehouseFk, dated
+ ORDER BY itemFk, warehouseFk, dated;
+
+ SET @lastItemFk := 0;
+ SET @lastWareHouseFk := 0;
+ SET @lastQuantity := 0;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp
+ (INDEX (itemFk, wareHouseFk))
+ SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity
+ FROM (
+ SELECT
+ itemFk,
+ IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk,
+ @lastQuantity := quantity,
+ @lastQuantity := @lastQuantity + quantity) quantityAccumulated,
+ wareHouseFk,
+ @lastItemFk := itemFk,
+ @lastWareHouseFk := wareHouseFk
+ FROM tItemOrdered
+ )sub
+ GROUP BY itemFk, wareHouseFk;
+
+ DROP TEMPORARY TABLE tItemOrdered;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql
new file mode 100644
index 000000000..95596d3bc
--- /dev/null
+++ b/db/routines/vn/procedures/item_getBalance.sql
@@ -0,0 +1,223 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getBalance`(
+ vItemFk INT,
+ vWarehouseFk INT,
+ vDate DATETIME
+)
+BEGIN
+/**
+ * @vItemFk item a buscar
+ * @vWarehouseFk almacen donde buscar
+ * @vDate Si la fecha es null, muestra el histórico desde el inventario.
+ * Si la fecha no es null, muestra histórico desde la fecha pasada.
+ */
+ DECLARE vDateInventory DATETIME;
+
+ IF vDate IS NULL THEN
+ SELECT inventoried INTO vDateInventory
+ FROM config;
+ ELSE
+ SELECT mockUtcTime INTO vDateInventory
+ FROM util.config;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tItemDiary(
+ shipped DATE,
+ `in` INT(11),
+ `out` INT(11),
+ alertLevel INT(11),
+ stateName VARCHAR(20),
+ `name` VARCHAR(50),
+ reference VARCHAR(50),
+ origin INT(11),
+ clientFk INT(11),
+ isPicked INT(11),
+ isTicket TINYINT(1),
+ lineFk INT(11),
+ `order` TINYINT(3) UNSIGNED,
+ clientType VARCHAR(20),
+ claimFk INT(10) UNSIGNED,
+ inventorySupplierFk INT(10)
+ );
+
+ INSERT INTO tItemDiary
+ SELECT tr.landed shipped,
+ b.quantity `in`,
+ NULL `out`,
+ st.alertLevel ,
+ st.name stateName,
+ s.name `name`,
+ e.invoiceNumber reference,
+ e.id origin,
+ s.id clientFk,
+ IF(st.`code` = 'DELIVERED', TRUE, FALSE) isPicked,
+ FALSE isTicket,
+ b.id lineFk,
+ NULL `order`,
+ NULL clientType,
+ NULL claimFk,
+ ec.inventorySupplierFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE()
+ OR (util.VN_CURDATE() AND tr.isReceived),
+ 'DELIVERED',
+ 'FREE')
+ JOIN entryConfig ec
+ WHERE tr.landed >= vDateInventory
+ AND vWarehouseFk = tr.warehouseInFk
+ AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL)
+ AND b.itemFk = vItemFk
+ AND e.isExcludedFromAvailable = FALSE
+ AND e.isRaid = FALSE
+ UNION ALL
+ SELECT tr.shipped,
+ NULL,
+ b.quantity,
+ st.alertLevel,
+ st.name,
+ s.name,
+ e.invoiceNumber,
+ e.id,
+ s.id,
+ IF(st.`code` = 'DELIVERED' , TRUE, FALSE),
+ FALSE,
+ b.id,
+ NULL,
+ NULL,
+ NULL,
+ ec.inventorySupplierFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN warehouse w ON w.id = tr.warehouseOutFk
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE()
+ OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived),
+ 'DELIVERED',
+ 'FREE')
+ JOIN entryConfig ec
+ WHERE tr.shipped >= vDateInventory
+ AND vWarehouseFk = tr.warehouseOutFk
+ AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL)
+ AND b.itemFk = vItemFk
+ AND e.isExcludedFromAvailable = FALSE
+ AND w.isFeedStock = FALSE
+ AND e.isRaid = FALSE
+ UNION ALL
+ SELECT DATE(t.shipped),
+ NULL,
+ s.quantity,
+ st2.alertLevel,
+ st2.name,
+ t.nickname,
+ t.refFk,
+ t.id,
+ t.clientFk,
+ stk.id,
+ TRUE,
+ s.id,
+ st.`order`,
+ c.typeFk,
+ cb.claimFk,
+ NULL
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ LEFT JOIN ticketState ts ON ts.ticketFk = t.id
+ LEFT JOIN state st ON st.`code` = ts.`code`
+ JOIN client c ON c.id = t.clientFk
+ JOIN state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(),
+ 'DELIVERED',
+ IF (t.shipped > util.dayEnd(util.VN_CURDATE()),
+ 'FREE',
+ IFNULL(ts.code, 'FREE')))
+ LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED'
+ LEFT JOIN saleTracking stk ON stk.saleFk = s.id
+ AND stk.stateFk = stPrep.id
+ LEFT JOIN claimBeginning cb ON s.id = cb.saleFk
+ WHERE t.shipped >= vDateInventory
+ AND s.itemFk = vItemFk
+ AND vWarehouseFk =t.warehouseFk
+ ORDER BY shipped,
+ (inventorySupplierFk = clientFk) DESC,
+ alertLevel DESC,
+ isTicket,
+ `order` DESC,
+ isPicked DESC,
+ `in` DESC,
+ `out` DESC;
+
+ IF vDate IS NULL THEN
+
+ SET @a := 0;
+ SET @currentLineFk := 0;
+ SET @shipped := '';
+
+ SELECT DATE(@shipped:= shipped) shipped,
+ alertLevel,
+ stateName,
+ origin,
+ reference,
+ clientFk,
+ name,
+ `in` invalue,
+ `out`,
+ @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0) balance,
+ @currentLineFk := IF (@shipped < util.VN_CURDATE()
+ OR (@shipped = util.VN_CURDATE() AND (isPicked OR a.`code` >= 'ON_PREPARATION')),
+ lineFk,
+ @currentLineFk) lastPreparedLineFk,
+ isTicket,
+ lineFk,
+ isPicked,
+ clientType,
+ claimFk
+ FROM tItemDiary
+ LEFT JOIN alertLevel a ON a.id = tItemDiary.alertLevel;
+
+ ELSE
+ SELECT SUM(`in`) - SUM(`out`) INTO @a
+ FROM tItemDiary
+ WHERE shipped < vDate;
+
+ SELECT vDate shipped,
+ 0 alertLevel,
+ 0 stateName,
+ 0 origin,
+ '' reference,
+ 0 clientFk,
+ 'Inventario calculado',
+ @a invalue,
+ NULL `out`,
+ @a balance,
+ 0 lastPreparedLineFk,
+ 0 isTicket,
+ 0 lineFk,
+ 0 isPicked,
+ 0 clientType,
+ 0 claimFk
+ UNION ALL
+ SELECT shipped,
+ alertlevel,
+ stateName,
+ origin,
+ reference,
+ clientFk,
+ name, `in`,
+ `out`,
+ @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0),
+ 0,
+ isTicket,
+ lineFk,
+ isPicked,
+ clientType,
+ claimFk
+ FROM tItemDiary
+ WHERE shipped >= vDate;
+ END IF;
+
+ DROP TEMPORARY TABLE tItemDiary;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_getInfo.sql b/db/routines/vn/procedures/item_getInfo.sql
new file mode 100644
index 000000000..50ab880a0
--- /dev/null
+++ b/db/routines/vn/procedures/item_getInfo.sql
@@ -0,0 +1,72 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getInfo`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT)
+BEGIN
+/**
+ * Devuelve información relativa al item correspondiente del vBarcode pasado
+ *
+ * @param vBarcode código relativo al ítem
+ * @param vWarehouseFk código del almacén
+ */
+ DECLARE vCacheVisibleFk INT;
+ DECLARE vCacheAvailableFk INT;
+ DECLARE vVisibleItemShelving INT;
+ DECLARE vItemFk INT;
+
+ CALL cache.visible_refresh(vCacheVisibleFk, FALSE, vWarehouseFk);
+ CALL cache.available_refresh(vCacheAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
+ CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
+
+ SELECT barcodeToItem(vBarcode) INTO vItemFk;
+ SELECT SUM(visible) INTO vVisibleItemShelving
+ FROM itemShelvingStock
+ WHERE itemFk = vItemFk
+ AND warehouseFk = vWarehouseFk;
+
+ SELECT i.id,
+ i.longName,
+ i.tag5,
+ i.value5,
+ i.tag6,
+ i.value6,
+ i.tag7,
+ i.value7,
+ i.image,
+ i.`size`,
+ i.stems,
+ i.category,
+ i.minimum `min`,
+ p.name producer,
+ o.code origin,
+ v.visible - IFNULL(vVisibleItemShelving, 0) unlocated,
+ a.available,
+ vVisibleItemShelving,
+ v.visible,
+ b.`grouping`,
+ b.packing,
+ CONCAT('http:', ic.url, '/catalog/200x200/', i.image) urlImage200,
+ CONCAT('http:', ic.url, '/catalog/1600x900/', i.image) urlImage,
+ i.itemPackingTypeFk,
+ i.comment reference,
+ u.name buyer,
+ IFNULL(b.buyingValue, 0) +
+ IFNULL(b.freightValue, 0) +
+ IFNULL(b.comissionValue, 0) +
+ IFNULL(b.packageValue, 0) itemCost
+ FROM item i
+ LEFT JOIN producer p ON p.id = i.producerFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN cache.visible v ON v.calc_id = vCacheVisibleFk
+ AND v.item_id = i.id
+ LEFT JOIN cache.available a ON a.calc_id = vCacheAvailableFk
+ AND a.item_id = i.id
+ LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
+ LEFT JOIN buy b ON b.id = bu.buyFk
+ AND bu.warehouseFk = vWarehouseFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN account.user u ON u.id = it.workerFk
+ JOIN hedera.imageConfig ic
+ WHERE i.id = vItemFk;
+
+ DROP TEMPORARY TABLE tmp.buyUltimate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_getLack.sql b/db/routines/vn/procedures/item_getLack.sql
new file mode 100644
index 000000000..e0531e2ac
--- /dev/null
+++ b/db/routines/vn/procedures/item_getLack.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getLack`(IN vForce BOOLEAN, IN vDays INT)
+BEGIN
+/**
+ * Calcula una tabla con el máximo negativo visible para cada producto y almacen
+ *
+ * @param vForce Fuerza el recalculo del stock
+ * @param vDays Numero de dias a considerar
+**/
+
+ CALL `cache`.stock_refresh(vForce);
+ CALL item_getMinacum(NULL, util.VN_CURDATE(), vDays, NULL);
+ CALL item_getMinETD();
+ CALL item_zoneClosure();
+
+ SELECT i.id itemFk,
+ i.longName,
+ w.id warehouseFk,
+ p.`name` producer,
+ i.`size`,
+ i.category,
+ w.name warehouse,
+ SUM(IFNULL(sub.amount,0)) lack,
+ i.inkFk,
+ IFNULL(im.timed, util.midnight()) timed,
+ IFNULL(izc.timed, util.midnight()) minTimed,
+ o.name originFk
+ FROM (SELECT item_id,
+ warehouse_id,
+ amount
+ FROM cache.stock
+ WHERE amount > 0
+ UNION ALL
+ SELECT itemFk,
+ warehouseFk,
+ amount
+ FROM tmp.itemMinacum
+ ) sub
+ JOIN warehouse w ON w.id = sub.warehouse_id
+ JOIN item i ON i.id = sub.item_id
+ LEFT JOIN producer p ON p.id = i.producerFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id
+ LEFT JOIN tmp.itemZoneClosure izc ON izc.itemFk = i.id
+ JOIN origin o ON o.id = i.originFk
+ WHERE w.isForTicket
+ AND ic.display
+ AND it.code != 'GEN'
+ GROUP BY i.id, w.id
+ HAVING lack < 0;
+
+ DROP TEMPORARY TABLE tmp.itemMinacum;
+ DROP TEMPORARY TABLE tmp.itemMinETD;
+ DROP TEMPORARY TABLE tmp.itemZoneClosure;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_getMinETD.sql b/db/routines/vn/procedures/item_getMinETD.sql
new file mode 100644
index 000000000..3876587fe
--- /dev/null
+++ b/db/routines/vn/procedures/item_getMinETD.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getMinETD`()
+BEGIN
+
+/* Devuelve una tabla temporal con la primera ETD, para todos los artículos con salida hoy.
+ *
+ * @return tmp.itemMinETD(itemFk, timed)
+ */
+
+ DECLARE vMidnight DATETIME DEFAULT util.midnight();
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.itemMinETD;
+
+ CREATE TEMPORARY TABLE tmp.itemMinETD
+ (INDEX (itemFk))
+ ENGINE = MEMORY
+ SELECT s.itemFk, MIN(TIME(IFNULL(z.`hour`,vMidnight))) timed
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ LEFT JOIN `zone` z ON z.id = t.zoneFk
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND vMidnight
+ GROUP BY s.itemFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_getMinacum.sql b/db/routines/vn/procedures/item_getMinacum.sql
new file mode 100644
index 000000000..ed987637c
--- /dev/null
+++ b/db/routines/vn/procedures/item_getMinacum.sql
@@ -0,0 +1,79 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getMinacum`(IN vWarehouseFk TINYINT, IN vDatedFrom DATETIME, IN vRange INT, IN vItemFk INT)
+BEGIN
+/**
+ * Cálculo del mínimo acumulado, para un item/almacén especificado, en caso de
+ * NULL para todo.
+ *
+ * @param vWarehouseFk -> warehouseFk
+ * @param vDatedFrom -> fecha inicio
+ * @param vRange -> número de días a considerar
+ * @param vItemFk -> Identificador de item
+ * @return tmp.itemMinacum
+*/
+ DECLARE vDatedTo DATETIME;
+
+ SET vDatedFrom = TIMESTAMP(DATE(vDatedFrom), '00:00:00');
+ SET vDatedTo = TIMESTAMP(TIMESTAMPADD(DAY, vRange, vDatedFrom), '23:59:59');
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.itemCalc;
+ CREATE TEMPORARY TABLE tmp.itemCalc
+ (INDEX (itemFk, warehouseFk))
+ SELECT sub.itemFk,
+ sub.dated,
+ CAST(SUM(sub.quantity) AS SIGNED) quantity,
+ sub.warehouseFk
+ FROM (SELECT s.itemFk,
+ DATE(t.shipped) dated,
+ -s.quantity quantity,
+ t.warehouseFk
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ AND s.quantity != 0
+ AND (vItemFk IS NULL OR s.itemFk = vItemFk)
+ AND (vWarehouseFk IS NULL OR t.warehouseFk = vWarehouseFk)
+ UNION ALL
+ SELECT b.itemFk,
+ t.landed,
+ b.quantity,
+ t.warehouseInFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ LEFT JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vDatedFrom AND vDatedTo
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND !e.isExcludedFromAvailable
+ AND b.quantity != 0
+ AND (vItemFk IS NULL OR b.itemFk = vItemFk)
+ UNION ALL
+ SELECT b.itemFk,
+ t.shipped,
+ -b.quantity,
+ t.warehouseOutFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ LEFT JOIN travel t ON t.id = e.travelFk
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ AND (vWarehouseFk IS NULL OR t.warehouseOutFk = vWarehouseFk)
+ AND !e.isExcludedFromAvailable
+ AND b.quantity != 0
+ AND (vItemFk IS NULL OR b.itemFk = vItemFk)
+ AND !e.isRaid
+ ) sub
+ GROUP BY sub.itemFk, sub.warehouseFk, sub.dated;
+
+ CALL item_getAtp(vDatedFrom);
+ DROP TEMPORARY TABLE tmp.itemCalc;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum;
+ CREATE TEMPORARY TABLE tmp.itemMinacum
+ (INDEX(itemFk))
+ ENGINE = MEMORY
+ SELECT i.itemFk,
+ i.warehouseFk,
+ i.quantity amount
+ FROM tmp.itemAtp i
+ HAVING amount != 0;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql
new file mode 100644
index 000000000..f79bed375
--- /dev/null
+++ b/db/routines/vn/procedures/item_getSimilar.sql
@@ -0,0 +1,99 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getSimilar`(
+ vSelf INT,
+ vWarehouseFk INT,
+ vDated DATE,
+ vShowType BOOL
+)
+BEGIN
+/**
+* Propone articulos disponibles ordenados, con la cantidad
+* de veces usado y segun sus caracteristicas.
+*
+* @param vSelf Id de artículo
+* @param vWarehouseFk Id de almacen
+* @param vDated Fecha
+* @param vShowType Mostrar tipos
+*/
+ DECLARE vCalcFk INT;
+ DECLARE vTypeFk INT;
+ DECLARE vPriority INT DEFAULT 1;
+
+ CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated);
+
+ -- Añadido temporalmente para ver si ya no sucede el cuelgue de db
+ SET vShowType = TRUE;
+
+ WITH itemTags AS (
+ SELECT i.id,
+ typeFk,
+ tag5,
+ value5,
+ tag6,
+ value6,
+ tag7,
+ value7,
+ tag8,
+ value8,
+ t.name,
+ it.value
+ FROM vn.item i
+ LEFT JOIN vn.itemTag it ON it.itemFk = i.id
+ AND it.priority = vPriority
+ LEFT JOIN vn.tag t ON t.id = it.tagFk
+ WHERE i.id = vSelf
+ )
+ SELECT i.id itemFk,
+ i.longName,
+ i.subName,
+ i.tag5,
+ i.value5,
+ (i.value5 <=> its.value5) match5,
+ i.tag6,
+ i.value6,
+ (i.value6 <=> its.value6) match6,
+ i.tag7,
+ i.value7,
+ (i.value7 <=> its.value7) match7,
+ i.tag8,
+ i.value8,
+ (i.value8 <=> its.value8) match8,
+ a.available,
+ IFNULL(ip.counter, 0) `counter`,
+ CASE
+ WHEN b.groupingMode = 1 THEN b.grouping
+ WHEN b.groupingMode = 2 THEN b.packing
+ ELSE 1
+ END AS minQuantity,
+ iss.visible located
+ FROM vn.item i
+ JOIN cache.available a ON a.item_id = i.id
+ AND a.calc_id = vCalcFk
+ LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id
+ AND ip.itemFk = vSelf
+ LEFT JOIN vn.itemTag it ON it.itemFk = i.id
+ AND it.priority = vPriority
+ LEFT JOIN vn.tag t ON t.id = it.tagFk
+ LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
+ AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN vn.buy b ON b.id = lb.buy_id
+ LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id
+ AND iss.warehouseFk = vWarehouseFk
+ JOIN itemTags its
+ WHERE a.available > 0
+ AND IF(vShowType, i.typeFk = its.typeFk, TRUE)
+ AND i.id <> vSelf
+ ORDER BY `counter` DESC,
+ (t.name = its.name) DESC,
+ (it.value = its.value) DESC,
+ (i.tag5 = its.tag5) DESC,
+ match5 DESC,
+ (i.tag6 = its.tag6) DESC,
+ match6 DESC,
+ (i.tag7 = its.tag7) DESC,
+ match7 DESC,
+ (i.tag8 = its.tag8) DESC,
+ match8 DESC
+ LIMIT 100;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_getStock.sql b/db/routines/vn/procedures/item_getStock.sql
new file mode 100644
index 000000000..c7df75ef2
--- /dev/null
+++ b/db/routines/vn/procedures/item_getStock.sql
@@ -0,0 +1,72 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getStock`(
+ vWarehouseFk SMALLINT,
+ vDated DATE,
+ vItemFk INT
+)
+BEGIN
+/**
+ * Calcula el stock de un artículo de un vWarehouseFk,
+ * desde la fecha del inventario hasta vDated
+ *
+ * @param vWarehouse Warehouse id
+ * @param vDated Max date to filter
+ * @param vItemFk Item id
+ *
+ * @return tmp.itemList(itemFk, stock, visible, available)
+ */
+ DECLARE vIsLogifloraDay BOOL DEFAULT vn.isLogifloraDay(vDated, vWarehouseFk);
+
+ SET vDated = TIMESTAMP(vDated, '00:00:00');
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemList
+ (UNIQUE INDEX i USING HASH (itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk,
+ SUM(quantity) stock,
+ SUM(quantity) visible,
+ SUM(quantity) available
+ FROM (
+ SELECT itemFk, quantity
+ FROM itemTicketOut
+ WHERE shipped >= util.VN_CURDATE()
+ AND shipped < vDated
+ AND warehouseFk = vWarehouseFk
+ AND (vItemFk IS NULL OR itemFk = vItemFk)
+ UNION ALL
+ SELECT iei.itemFk, iei.quantity
+ FROM itemEntryIn iei
+ LEFT JOIN edi.warehouseFloramondo wf ON wf.entryFk = iei.entryFk
+ JOIN item i ON i.id = iei.itemFk
+ WHERE iei.landed >= util.VN_CURDATE()
+ AND iei.landed < vDated
+ AND iei.warehouseInFk = vWarehouseFk
+ AND (vItemFk IS NULL OR iei.itemFk = vItemFk)
+ AND (wf.entryFk IS NULL OR vIsLogifloraDay)
+ AND NOT (iei.landed > util.VN_CURDATE() AND i.isFloramondo)
+ UNION ALL
+ SELECT ieo.itemFk, ieo.quantity
+ FROM itemEntryOut ieo
+ JOIN item i ON i.id = ieo.itemFk
+ WHERE ieo.shipped >= util.VN_CURDATE()
+ AND ieo.shipped < vDated
+ AND ieo.warehouseOutFk = vWarehouseFk
+ AND (vItemFk IS NULL OR ieo.itemFk = vItemFk)
+ AND NOT (ieo.shipped > util.VN_CURDATE() AND i.isFloramondo)
+ ) sub
+ GROUP BY itemFk
+ HAVING stock;
+
+ CALL cache.stock_refresh(FALSE);
+
+ INSERT INTO tmp.itemList(itemFk, stock, visible, available)
+ SELECT item_id, amount, amount, amount
+ FROM cache.stock
+ WHERE warehouse_id = vWarehouseFk
+ AND (vItemFk IS NULL OR vItemFk = item_id)
+ ON DUPLICATE KEY UPDATE
+ stock = stock + VALUES(stock),
+ visible = visible + VALUES(visible),
+ available = available + VALUES(available);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_multipleBuy.sql b/db/routines/vn/procedures/item_multipleBuy.sql
new file mode 100644
index 000000000..ba49f8d36
--- /dev/null
+++ b/db/routines/vn/procedures/item_multipleBuy.sql
@@ -0,0 +1,36 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_multipleBuy`(
+ vDate DATETIME,
+ vWarehouseFk INT
+)
+BEGIN
+/**
+ * Updates the tmp.itemInventory table, adding the buy id.
+ *
+ * @param tmp.itemInventory(buy_id)
+ * @param vDate -> Date of the purchase operation.
+ * @param vWarehouseFk -> Identifier of the warehouse (warehouseId).
+ */
+ ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT;
+
+ CALL buyUltimate(vWarehouseFk, vDate);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp
+ (KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT *
+ FROM (
+ SELECT itemFk, buyFk
+ FROM tmp.buyUltimate
+ ORDER BY (vWarehouseFk = warehouseFk) DESC, landing DESC
+ LIMIT 10000000000000000000
+ ) t
+ GROUP BY itemFk;
+
+ UPDATE tmp.itemInventory ai
+ JOIN tmp t ON ai.id = t.itemFk
+ SET ai.buy_id = t.buyFk;
+
+ DROP TEMPORARY TABLE tmp, tmp.buyUltimate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_multipleBuyByDate.sql b/db/routines/vn/procedures/item_multipleBuyByDate.sql
new file mode 100644
index 000000000..d508afca4
--- /dev/null
+++ b/db/routines/vn/procedures/item_multipleBuyByDate.sql
@@ -0,0 +1,40 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_multipleBuyByDate`(
+ vDated DATETIME,
+ vWarehouseFk TINYINT(3)
+)
+BEGIN
+/**
+ * Updates the tmp.itemInventory table, adding the purchase date.
+ *
+ * @param tmp.itemInventory(buy_date)
+ * @param vDated -> end date
+ * @param vWarehouseFk -> warehouse id
+ */
+ DECLARE vLastBuyScope INT;
+ SELECT comparativeLastBuyScope INTO vLastBuyScope
+ FROM config;
+
+ ALTER TABLE tmp.itemInventory
+ ADD `buy_date` datetime NOT NULL;
+
+ CREATE OR REPLACE TEMPORARY TABLE lastBuyScope
+ SELECT i.id, MAX(t.landed) lastLanded
+ FROM item i
+ JOIN buy b ON b.itemFk = i.id
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN (vDated + INTERVAL - vLastBuyScope DAY) AND vDated
+ AND NOT s.name = 'INVENTARIO'
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND w.isComparative
+ AND NOT e.isRaid
+ GROUP BY i.id;
+
+ UPDATE tmp.itemInventory y
+ JOIN lastBuyScope lbs ON lbs.id = y.id
+ SET y.buy_date = lbs.lastLanded;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_refreshFromTags.sql b/db/routines/vn/procedures/item_refreshFromTags.sql
new file mode 100644
index 000000000..398c01d8e
--- /dev/null
+++ b/db/routines/vn/procedures/item_refreshFromTags.sql
@@ -0,0 +1,62 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_refreshFromTags`(vSelf INT)
+BEGIN
+/**
+ * Updates item attributes with its corresponding tags.
+ *
+ * @param vSelf The item id
+ */
+ DECLARE vTags JSON;
+ DECLARE vValues JSON;
+ DECLARE vAbbrs JSON;
+ DECLARE vOverwrites JSON;
+
+ SELECT JSON_OBJECTAGG(`priority`, t.`name`),
+ JSON_OBJECTAGG(`priority`, it.`value`),
+ JSON_OBJECTAGG(`priority`, IFNULL(a.abbreviation, it.`value`)),
+ JSON_OBJECTAGG(`overwrite`, it.`value`)
+ INTO vTags, vValues, vAbbrs, vOverwrites
+ FROM itemTag it
+ JOIN tag t ON t.id = it.tagFk
+ LEFT JOIN tagAbbreviation a ON a.`value` = it.`value`
+ AND (a.tagFk IS NULL OR a.tagFk = t.id)
+ WHERE it.itemFk = vSelf;
+
+ UPDATE item i
+ LEFT JOIN ink k ON k.name = JSON_VALUE(vOverwrites, '$.inkFk')
+ LEFT JOIN origin o ON o.name = JSON_VALUE(vOverwrites, '$.originFk')
+ LEFT JOIN producer p ON p.name = JSON_VALUE(vOverwrites, '$.producerFk')
+ SET i.`name` = CONCAT_WS(' ',
+ JSON_VALUE(vAbbrs, '$.1'),
+ JSON_VALUE(vAbbrs, '$.2'),
+ IF(i.isFloramondo, NULL, JSON_VALUE(vAbbrs, '$.3'))
+ ),
+ i.longName = CONCAT_WS(' ',
+ JSON_VALUE(vValues, '$.1'),
+ JSON_VALUE(vValues, '$.2'),
+ JSON_VALUE(vValues, '$.3')
+ ),
+ i.subname = JSON_VALUE(vValues, '$.4'),
+ i.size = JSON_VALUE(vOverwrites, '$.size'),
+ i.stems = IFNULL(JSON_VALUE(vOverwrites, '$.stems'),i.stems),
+ i.category = JSON_VALUE(vOverwrites, '$.category'),
+ i.tag5 = JSON_VALUE(vTags, '$.5'),
+ i.tag6 = JSON_VALUE(vTags, '$.6'),
+ i.tag7 = JSON_VALUE(vTags, '$.7'),
+ i.tag8 = JSON_VALUE(vTags, '$.8'),
+ i.tag9 = JSON_VALUE(vTags, '$.9'),
+ i.tag10 = JSON_VALUE(vTags, '$.10'),
+ i.value5 = JSON_VALUE(vValues, '$.5'),
+ i.value6 = JSON_VALUE(vValues, '$.6'),
+ i.value7 = JSON_VALUE(vValues, '$.7'),
+ i.value8 = JSON_VALUE(vValues, '$.8'),
+ i.value9 = JSON_VALUE(vValues, '$.9'),
+ i.value10 = JSON_VALUE(vValues, '$.10'),
+ i.producerFk = p.id,
+ i.inkFk = k.id,
+ i.originFk = IFNULL(o.id, i.originFk)
+ WHERE i.id = vSelf;
+
+ CALL item_setGeneric(vSelf);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_refreshTags.sql b/db/routines/vn/procedures/item_refreshTags.sql
new file mode 100644
index 000000000..84ace0883
--- /dev/null
+++ b/db/routines/vn/procedures/item_refreshTags.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_refreshTags`()
+BEGIN
+/**
+ * Update item table, tag "cache" fields
+ *
+ * @param temporary table tmp.item(id) of the article
+ */
+ DECLARE vDone BOOL;
+ DECLARE vItemFk INT;
+ DECLARE vCur CURSOR FOR SELECT id FROM tmp.item;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vCur;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vCur INTO vItemFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL item_refreshFromTags(vItemFk);
+ END LOOP;
+
+ CLOSE vCur;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_saveReference.sql b/db/routines/vn/procedures/item_saveReference.sql
new file mode 100644
index 000000000..52416b637
--- /dev/null
+++ b/db/routines/vn/procedures/item_saveReference.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_saveReference`(vBarcode VARCHAR(22), vReference VARCHAR(150))
+BEGIN
+
+/**
+ * Actualiza la referencia del item
+ *
+ * @param vBarcode del item
+ * @param vReference referencia a actualizar
+ */
+
+ DECLARE vItemFk INT;
+
+ SELECT barcodeToItem(vBarcode) INTO vItemFk;
+
+ UPDATE item SET comment = vReference WHERE id = vItemFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_setGeneric.sql b/db/routines/vn/procedures/item_setGeneric.sql
new file mode 100644
index 000000000..9a78b1349
--- /dev/null
+++ b/db/routines/vn/procedures/item_setGeneric.sql
@@ -0,0 +1,56 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setGeneric`(vSelf INT)
+BEGIN
+/**
+ * Asigna el código genérico a un item, salvo que sea un código de item genérico.
+ *
+ * @param vSelf identificador de vn.item
+ */
+ DECLARE vGenericFk INT;
+
+ SELECT itemFk INTO vGenericFk
+ FROM (
+ SELECT itemFk, SUM(matches) = maxMatches `match`
+ FROM (
+ SELECT ga.id gaid, ga.itemFk,
+ CASE
+ WHEN t.code = 'nflowers' THEN
+ it.value <=> ga.numFlores
+ WHEN t.code = 'origin' THEN
+ it.value <=> ga.origin
+ WHEN t.code = 'quality' THEN
+ it.value <=> ga.quality
+ WHEN t.code = 'color' THEN
+ it.value <=> ga.color
+ WHEN t.code = 'category' THEN
+ it.value <=> ga.category
+ WHEN t.code = 'producer' THEN
+ it.value <=> ga.productor
+ ELSE
+ 0
+ END matches,
+ (NOT ISNULL(ga.origin))
+ + (NOT ISNULL(ga.color))
+ + (NOT ISNULL(ga.quality))
+ + (NOT ISNULL(ga.numFlores))
+ + (NOT ISNULL(ga.category))
+ + (NOT ISNULL(ga.productor)) maxMatches
+ FROM vn.item i
+ JOIN vn.itemTag it ON it.itemFk = i.id
+ JOIN vn.tag t ON t.id = it.tagFk
+ JOIN vn.genericAllocation ga
+ ON (i.typeFk = ga.typeFk OR ga.typeFk IS NULL)
+ AND (i.longName = ga.longName OR ga.longName IS NULL)
+ AND (i.`size` = ga.`size` OR ga.`size` IS NULL)
+ AND i.id != ga.itemFk
+ WHERE i.id = vSelf
+ AND NOT i.isFloramondo) sub
+ GROUP BY gaid
+ HAVING `match`) sub2
+ LIMIT 1;
+
+ UPDATE vn.item
+ SET genericFk = vGenericFk
+ WHERE id = vSelf;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_setVisibleDiscard.sql b/db/routines/vn/procedures/item_setVisibleDiscard.sql
new file mode 100644
index 000000000..1cc2a8871
--- /dev/null
+++ b/db/routines/vn/procedures/item_setVisibleDiscard.sql
@@ -0,0 +1,78 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDiscard`(
+ vItemFk INT,
+ vWarehouseFk INT,
+ vQuantity INT,
+ vAddressFk INT)
+BEGIN
+/**
+ * Procedimiento para dar dar de baja/alta un item, si vAddressFk es NULL se entiende que se da de alta y se toma el addressFk de la configuración
+ *
+ * @param vItemFk Identificador del ítem
+ * @param vWarehouseFk id del warehouse
+ * @param vQuantity a dar de alta/baja
+ * @param vAddressFk id address
+ */
+ DECLARE vTicketFk INT;
+ DECLARE vClientFk INT;
+ DECLARE vDefaultCompanyFk INT;
+ DECLARE vCalc INT;
+ DECLARE vAddressShortage INT;
+
+ SELECT barcodeToItem(vItemFk) INTO vItemFk;
+
+ SELECT DEFAULT(companyFk) INTO vDefaultCompanyFk
+ FROM vn.ticket LIMIT 1;
+
+ IF vAddressFk IS NULL THEN
+ SELECT pc.shortageAddressFk INTO vAddressShortage
+ FROM productionConfig pc ;
+ ELSE
+ SET vAddressShortage = vAddressFk;
+ END IF;
+
+ SELECT a.clientFk INTO vClientFk
+ FROM address a
+ WHERE a.id = vAddressFk;
+
+ SELECT t.id INTO vTicketFk
+ FROM ticket t
+ JOIN address a ON a.id = t.addressFk
+ JOIN ticketState ts ON ts.ticketFk = t.id
+ WHERE t.warehouseFk = vWarehouseFk
+ AND a.id = vAddressShortage
+ AND DATE(t.shipped) = util.VN_CURDATE()
+ AND ts.code = 'DELIVERED'
+ LIMIT 1;
+
+ CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk);
+
+ IF vTicketFk IS NULL THEN
+ CALL ticket_add(
+ vClientFk,
+ util.VN_CURDATE(),
+ vWarehouseFk,
+ vDefaultCompanyFk,
+ vAddressFk,
+ NULL,
+ NULL,
+ util.VN_CURDATE(),
+ account.myUser_getId(),
+ FALSE,
+ vTicketFk);
+ END IF;
+
+ INSERT INTO sale(ticketFk, itemFk, concept, quantity)
+ SELECT vTicketFk,
+ vItemFk,
+ CONCAT(longName,' ', worker_getCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)),
+ vQuantity
+ FROM item
+ WHERE id = vItemFk;
+
+ UPDATE cache.visible
+ SET visible = visible - vQuantity
+ WHERE calc_id = vCalc
+ AND item_id = vItemFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_updatePackingType.sql b/db/routines/vn/procedures/item_updatePackingType.sql
new file mode 100644
index 000000000..12a5e687b
--- /dev/null
+++ b/db/routines/vn/procedures/item_updatePackingType.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_updatePackingType`(vItem INT, vItemPackingTypeFk VARCHAR(1))
+BEGIN
+/**
+ * Update the packing type of an item
+ *
+ * @param vItem id del item a actualizar
+ * @param vItemPackingTypeFk packing type
+ */
+ UPDATE item SET itemPackingTypeFk = vItemPackingTypeFk WHERE id = vItem;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/item_zoneClosure.sql b/db/routines/vn/procedures/item_zoneClosure.sql
new file mode 100644
index 000000000..c555e5df2
--- /dev/null
+++ b/db/routines/vn/procedures/item_zoneClosure.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_zoneClosure`()
+BEGIN
+
+/* Devuelve una tabla temporal con la hora minima de un ticket sino tiene el de la zoneClosure y
+ * si tampoco hay el de la zona , para todos los artículos con salida hoy.
+ *
+ * @return tmp.itemZoneClosure(itemFk, timed)
+ */
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemZoneClosure
+ (INDEX (itemFk))
+ ENGINE = MEMORY
+ SELECT s.itemFk,
+ MIN(DATE_FORMAT(IF(HOUR(t.shipped),t.shipped,
+ IFNULL(zc.hour, z.HOUR)), '%H:%i')
+ )timed
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ LEFT JOIN `zone` z ON z.id = t.zoneFk
+ LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND CONCAT(util.VN_CURDATE(), ' 23:59:59')
+ GROUP BY s.itemFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ledger_doCompensation.sql b/db/routines/vn/procedures/ledger_doCompensation.sql
new file mode 100644
index 000000000..e45db376c
--- /dev/null
+++ b/db/routines/vn/procedures/ledger_doCompensation.sql
@@ -0,0 +1,78 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_doCompensation`(vDated DATE, vCompensationAccount VARCHAR(10) , vBankFk VARCHAR(10), vConcept VARCHAR(255), vAmount DECIMAL(10,2), vCompanyFk INT, vOriginalAccount VARCHAR(10))
+BEGIN
+/**
+ * Compensa un pago o un recibo insertando en contabilidad
+ *
+ * @param vDated fecha en la cual se anota
+ * @param vCompensationAccount cuenta contable contra la que se compensa
+ * @param vBankFk banco de la compensacion
+ * @param vConcept descripcion
+ * @param vAmount cantidad que se compensa
+ * @param vCompany empresa
+ * @param vOriginalAccount cuenta contable desde la cual se compensa
+ *
+ */
+ DECLARE vNewBookEntry INT;
+ DECLARE vIsClientCompensation INT;
+ DECLARE vClientFk INT;
+ DECLARE vSupplierFk INT;
+ DECLARE vIsOriginalAClient BOOL;
+ DECLARE vPayMethodCompensation INT;
+
+ CALL ledger_next(vNewBookEntry);
+
+ SELECT COUNT(id) INTO vIsOriginalAClient FROM client WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci;
+
+ SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation
+ FROM client
+ WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci;
+
+ SET @vAmount1:= 0.0;
+ SET @vAmount2:= 0.0;
+
+ INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id)
+ VALUES ( vNewBookEntry,
+ vDated,
+ vOriginalAccount,
+ vCompensationAccount,
+ vConcept,
+ @vAmount1:= IF(
+ (vIsOriginalAClient AND vAmount > 0) OR
+ (NOT vIsOriginalAClient AND vAmount < 0),
+ 0,
+ ABS(vAmount)
+ ),
+ @vAmount2:= IF(@vAmount1,
+ 0,
+ ABS(vAmount)
+ ),
+ vCompanyFk
+ ),
+ ( vNewBookEntry,
+ vDated,
+ vCompensationAccount,
+ vOriginalAccount,
+ vConcept,
+ @vAmount2,
+ @vAmount1,
+ vCompanyFk);
+
+ IF vIsClientCompensation THEN
+ IF vIsOriginalAClient THEN
+ SET vAmount = -vAmount;
+ END IF;
+ INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate)
+ VALUES (vConcept, vAmount, vDated, vBankFk, vCompanyFk, vClientFk, TRUE);
+ ELSE
+ IF NOT vIsOriginalAClient THEN
+ SET vAmount = -vAmount;
+ END IF;
+ SELECT id INTO vSupplierFk FROM supplier WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci;
+ SELECT id INTO vPayMethodCompensation FROM payMethod WHERE `code` = 'compensation';
+
+ INSERT INTO payment (received, dueDated, supplierFk, amount, bankFk, payMethodFk, concept, companyFk, isConciliated)
+ VALUES(vDated, vDated, vSupplierFk, vAmount, vBankFk, vPayMethodCompensation, vConcept, vCompanyFk, TRUE);
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ledger_next.sql b/db/routines/vn/procedures/ledger_next.sql
new file mode 100644
index 000000000..a45ebdd29
--- /dev/null
+++ b/db/routines/vn/procedures/ledger_next.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_next`(OUT vNewBookEntry INT)
+BEGIN
+
+ UPDATE vn.ledgerConfig SET lastBookEntry = LAST_INSERT_ID(lastBookEntry + 1);
+ SET vNewBookEntry = LAST_INSERT_ID();
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/logShow.sql b/db/routines/vn/procedures/logShow.sql
new file mode 100644
index 000000000..836d3b0c4
--- /dev/null
+++ b/db/routines/vn/procedures/logShow.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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 ;
diff --git a/db/routines/vn/procedures/lungSize_generator.sql b/db/routines/vn/procedures/lungSize_generator.sql
new file mode 100644
index 000000000..e13e83650
--- /dev/null
+++ b/db/routines/vn/procedures/lungSize_generator.sql
@@ -0,0 +1,48 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`lungSize_generator`(vDate DATE)
+BEGIN
+
+SET @buildingOrder := 0;
+SET @route := 0;
+set @cajas := 0;
+
+ UPDATE tmp.sorter
+ SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1
+ where date(created) = vDate
+ order by routeFk, created, weight DESC;
+
+ update tmp.sorter
+ SET palletOrder = buildingOrder mod 14, lungGrow = buildingOrder mod 14
+ WHERE date(created) = vDate;
+
+ UPDATE tmp.sorter
+ JOIN (
+ SELECT routeFk, max(id) maxid
+ FROM tmp.sorter
+ where date(created) = vDate
+ GROUP BY routeFk) sub ON sub.maxid = id
+ SET lungGrow = 1 - palletOrder ;
+
+ UPDATE tmp.sorter
+ SET lungGrow = IF(palletOrder = 0, -13, lungGrow);
+
+ DELETE FROM tmp.lungSize WHERE dia = vDate;
+
+ INSERT INTO tmp.lungSize(dia, hora,size)
+ select vDate,hora, @cajas := @cajas + cajas as size
+ from
+ (
+ select IF(lungGrow BETWEEN -12 AND -1, ETD,time_format(created,"%H:%i")) as hora, sum(if(lungGrow <= 0, lungGrow, 1)) as cajas, @cajas := 0
+ from tmp.sorter
+ where date(created) = vDate
+ group by hora
+ ) sub;
+
+ SELECT * FROM tmp.lungSize
+ WHERE dia = vDate;
+
+
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/machineWorker_add.sql b/db/routines/vn/procedures/machineWorker_add.sql
new file mode 100644
index 000000000..b2a7c7e19
--- /dev/null
+++ b/db/routines/vn/procedures/machineWorker_add.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`machineWorker_add`(vPlate VARCHAR(10), vWorkerFk INT)
+BEGIN
+
+/**
+ * Inserta registro si el vWorkerFk no ha registrado nada en las últimas 12 horas
+ * @param vPlate número de matrícula
+ * @param vWorkerFk id del worker
+ *
+*/
+ UPDATE vn.machineWorker mw
+ JOIN vn.machine m ON m.id = mw.machineFk
+ SET mw.outTimed = util.VN_NOW()
+ WHERE (mw.workerFk = vWorkerFk OR m.plate = vPlate)
+ AND ISNULL(mw.outTimed);
+
+ INSERT INTO machineWorker (machineFk, workerFk)
+ SELECT m.id, vWorkerFk
+ FROM machine m
+ WHERE m.plate= vPlate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/machineWorker_getHistorical.sql b/db/routines/vn/procedures/machineWorker_getHistorical.sql
new file mode 100644
index 000000000..47fcec5b6
--- /dev/null
+++ b/db/routines/vn/procedures/machineWorker_getHistorical.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`machineWorker_getHistorical`(vPlate VARCHAR(20), vWorkerFk INT)
+BEGIN
+/**
+ * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea,
+ * si es jefe de producción muestra el historial completo.
+ *
+ * @param vPlate número de matrícula
+ * @param vWorkerFk id del trabajador
+ *
+*/
+ DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vWorkerFk);
+
+ SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed
+ FROM machineWorker mw
+ JOIN machine m ON m.plate = vPlate
+ WHERE mw.machineFk = m.id
+ AND mw.workerFk = IF(account.user_hasRole(vWorkerName, 'coolerAssist'), mw.workerFk, vWorkerFk)
+ ORDER BY mw.inTimed DESC;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/machineWorker_update.sql b/db/routines/vn/procedures/machineWorker_update.sql
new file mode 100644
index 000000000..064aa8931
--- /dev/null
+++ b/db/routines/vn/procedures/machineWorker_update.sql
@@ -0,0 +1,38 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT)
+BEGIN
+
+/**
+ * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate,
+ *
+ * @param vPlate número de matrícula
+ * @param vWorkerFk id del trabajador
+ *
+*/
+
+ DECLARE vMachineFk INT(10);
+ DECLARE vMaxHours INT(10);
+
+ SELECT m.id INTO vMachineFk
+ FROM machine m
+ WHERE m.plate = vPlate;
+
+ SELECT maxHours INTO vMaxHours
+ FROM machineWorkerConfig;
+
+ IF (SELECT COUNT(*)
+ FROM machineWorker m
+ WHERE m.workerFk = vWorkerFk
+ AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN
+
+ UPDATE machineWorker m
+ SET m.outTimed = CURRENT_TIMESTAMP()
+ WHERE m.workerFk = vWorkerFk
+ AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW())
+ AND ISNULL(m.outTimed)
+ AND m.machineFk = vMachineFk;
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/machine_getWorkerPlate.sql b/db/routines/vn/procedures/machine_getWorkerPlate.sql
new file mode 100644
index 000000000..4a50e0334
--- /dev/null
+++ b/db/routines/vn/procedures/machine_getWorkerPlate.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`machine_getWorkerPlate`(vWorkerFk INT)
+BEGIN
+/**
+ * Selecciona la matrícula del vehículo del workerfk
+ *
+ * @param vWorkerFk el id del trabajador
+ */
+ SELECT m.plate
+ FROM machine m
+ JOIN machineWorker mw ON mw.machineFk = m.id
+ WHERE mw.inTimed >= TIMESTAMPADD(HOUR , -12,util.VN_NOW())
+ AND ISNULL(mw.outTimed)
+ AND mw.workerFk = vWorkerFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/mail_insert.sql b/db/routines/vn/procedures/mail_insert.sql
new file mode 100644
index 000000000..5c5c2e9fd
--- /dev/null
+++ b/db/routines/vn/procedures/mail_insert.sql
@@ -0,0 +1,38 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`mail_insert`(
+ vReceiver VARCHAR(255),
+ vReplyTo VARCHAR(50),
+ vSubject VARCHAR(100),
+ vBody TEXT)
+BEGIN
+/**
+ * Inserta en la tabla vn.mail
+ *
+ * @param vReceiver Receptor del correo
+ * @param vReplyTo A quién contestar el correo
+ * @param vSubject Título del correo
+ * @param vBody Cuerpo del correo
+ */
+
+ DECLARE vIsRepeated BOOLEAN;
+
+ SELECT COUNT(*) INTO vIsRepeated
+ FROM vn.mail
+ WHERE creationDate >= util.VN_CURDATE()
+ AND `receiver` = vReceiver
+ AND `replyTo` = vReplyTo
+ AND `subject` = vSubject
+ AND !sent;
+
+ IF NOT vIsRepeated THEN
+
+ INSERT INTO vn.mail SET
+ `receiver` = vReceiver,
+ `replyTo` = vReplyTo,
+ `subject` = vSubject,
+ `body` = IFNULL(vBody,vSubject);
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/makeNewItem.sql b/db/routines/vn/procedures/makeNewItem.sql
new file mode 100644
index 000000000..5995f43b7
--- /dev/null
+++ b/db/routines/vn/procedures/makeNewItem.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`makeNewItem`()
+BEGIN
+
+ DECLARE newItemFk INT;
+
+ SELECT getNewItemId() INTO newItemFk;
+
+ INSERT INTO item(id,name,typeFk,originFk)
+ SELECT newItemFk, 'Nuevo artículo', 78,39;
+
+ SELECT newItemFk;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/makePCSGraf.sql b/db/routines/vn/procedures/makePCSGraf.sql
new file mode 100644
index 000000000..31b4a42e7
--- /dev/null
+++ b/db/routines/vn/procedures/makePCSGraf.sql
@@ -0,0 +1,39 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`makePCSGraf`(vDated DATE)
+BEGIN
+
+
+ DECLARE vHour INT DEFAULT 0;
+ DECLARE vMinute INT DEFAULT 0;
+ DECLARE vBoxes INT;
+
+
+ DROP TEMPORARY TABLE IF EXISTS vn.pcsDay;
+ CREATE TEMPORARY TABLE vn.pcsDay
+ SELECT 0 as hh, 0 as mm, 0 as boxes;
+
+ -- Creamos una tabla soporte para acumular las cajas a lo largo del dia
+ WHILE vHour < 24 DO
+
+ WHILE vMinute < 59 DO
+
+ SET vMinute = vMinute + 1;
+
+ INSERT INTO vn.pcsDay(hh,mm) VALUES(vHour, vMinute);
+
+ END WHILE;
+
+ SET vMinute = -1;
+ SET vHour = vHour + 1;
+
+ END WHILE;
+
+ -- Acumulamos
+ UPDATE vn.pcsDay pd
+ LEFT JOIN (SELECT * FROM vn.pcs_graf WHERE dia = vDated) pg USING(hh,mm)
+ SET pd.boxes = pd.boxes + pg.box;
+
+ SELECT * FROM vn.pcsDay;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/manaSpellersRequery.sql b/db/routines/vn/procedures/manaSpellersRequery.sql
new file mode 100644
index 000000000..30b91b4f1
--- /dev/null
+++ b/db/routines/vn/procedures/manaSpellersRequery.sql
@@ -0,0 +1,36 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`manaSpellersRequery`(vWorkerFk INTEGER)
+`whole_proc`:
+BEGIN
+/**
+ * Guarda en workerMana el mana consumido por un trabajador
+ *
+ * @param vWorkerFk Id Trabajador
+ */
+ DECLARE vWorkerIsExcluded BOOLEAN;
+
+ SELECT COUNT(*) INTO vWorkerIsExcluded
+ FROM workerManaExcluded
+ WHERE workerFk = vWorkerFk;
+
+ IF vWorkerIsExcluded THEN
+ LEAVE whole_proc;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.client
+ SELECT id
+ FROM client
+ WHERE salesPersonFk = vWorkerFk;
+
+ CALL client_getMana();
+
+ INSERT INTO workerMana (workerFk, amount)
+ SELECT vWorkerFk, sum(mana)
+ FROM tmp.clientMana
+ ON DUPLICATE KEY UPDATE amount = VALUES(amount);
+
+ DROP TEMPORARY TABLE
+ tmp.client,
+ tmp.clientMana;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql
new file mode 100644
index 000000000..2a28aa9a0
--- /dev/null
+++ b/db/routines/vn/procedures/multipleInventory.sql
@@ -0,0 +1,194 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`multipleInventory`(
+ vDate DATE,
+ vWarehouseFk TINYINT,
+ vMaxDays TINYINT
+)
+proc: BEGIN
+ DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY;
+ DECLARE vDateFrom DATE DEFAULT vDate;
+ DECLARE vDateTo DATETIME;
+ DECLARE vDateToTomorrow DATETIME;
+ DECLARE vDefaultDayRange INT;
+
+ IF vDate < util.VN_CURDATE() THEN
+ LEAVE proc;
+ END IF;
+
+ IF vDate = util.VN_CURDATE() THEN
+ SELECT inventoried INTO vDateFrom
+ FROM config;
+ END IF;
+
+ SELECT defaultDayRange INTO vDefaultDayRange
+ FROM comparativeConfig;
+
+ SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY;
+ SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY;
+
+ ALTER TABLE tmp.itemInventory
+ ADD `avalaible` INT NOT NULL,
+ ADD `sd` INT NOT NULL,
+ ADD `rest` INT NOT NULL,
+ ADD `expected` INT NOT NULL,
+ ADD `inventory` INT NOT NULL,
+ ADD `visible` INT NOT NULL,
+ ADD `life` TINYINT NOT NULL DEFAULT '0';
+
+ -- Calculo del inventario
+ UPDATE tmp.itemInventory ai
+ JOIN (
+ SELECT itemFk Id_Article, SUM(quantity) Subtotal
+ FROM (
+ SELECT s.itemFk, - s.quantity quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ UNION ALL
+ SELECT b.itemFk, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ ) sub2
+ GROUP BY itemFk
+ ) sub ON ai.id = sub.Id_Article
+ SET ai.inventory = sub.Subtotal,
+ ai.visible = sub.Subtotal,
+ ai.avalaible = sub.Subtotal,
+ ai.sd = sub.Subtotal;
+
+ -- Cálculo del visible
+ UPDATE tmp.itemInventory ai
+ JOIN (
+ SELECT itemFk Id_Article, SUM(quantity) Subtotal
+ FROM (
+ SELECT s.itemFk, s.quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped >= vDate
+ AND t.shipped < vDateTomorrow
+ AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL)
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed = vDate
+ AND NOT t.isReceived
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped = vDate
+ AND NOT t.isReceived
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ ) sub2
+ GROUP BY itemFk
+ ) sub ON ai.id = sub.Id_Article
+ SET ai.visible = ai.visible + sub.Subtotal;
+
+ -- Calculo del disponible
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
+ (INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT sub.itemFk,
+ vWarehouseFk warehouseFk,
+ sub.dated,
+ SUM(sub.quantity) quantity
+ FROM (
+ SELECT s.itemFk,
+ DATE(t.shipped) dated,
+ - s.quantity quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, t.landed, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ UNION ALL
+ SELECT b.itemFk, t.shipped, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT e.isRaid
+ ) sub
+ GROUP BY sub.itemFk, sub.dated;
+
+ CALL item_getAtp(vDate);
+ CALL travel_upcomingArrivals(vWarehouseFk, vDate);
+
+ UPDATE tmp.itemInventory ai
+ JOIN (
+ SELECT it.itemFk,
+ SUM(it.quantity) quantity,
+ im.quantity minQuantity
+ FROM tmp.itemCalc it
+ JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
+ JOIN item i ON i.id = it.itemFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
+ WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
+ t.landing,
+ vDateToTomorrow)
+ GROUP BY it.itemFk
+ ) sub ON sub.itemFk = ai.id
+ SET ai.avalaible = IF(sub.minQuantity > 0,
+ ai.avalaible,
+ ai.avalaible + sub.minQuantity),
+ ai.sd = ai.inventory + sub.quantity;
+
+ DROP TEMPORARY TABLE
+ tmp.itemTravel,
+ tmp.itemCalc,
+ tmp.itemAtp;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/mysqlConnectionsSorter_kill.sql b/db/routines/vn/procedures/mysqlConnectionsSorter_kill.sql
new file mode 100644
index 000000000..129b356f2
--- /dev/null
+++ b/db/routines/vn/procedures/mysqlConnectionsSorter_kill.sql
@@ -0,0 +1,37 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`mysqlConnectionsSorter_kill`()
+BEGIN
+
+/**
+ * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre
+ */
+
+ DECLARE vDone INT DEFAULT 0;
+ DECLARE vProcesId INT;
+
+ DECLARE vCursor CURSOR FOR
+ SELECT p.id
+ FROM information_schema.processlist p
+ WHERE USER = 'sorter'
+ AND TIME >= 30;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vCursor;
+
+ l: LOOP
+
+ FETCH vCursor INTO vProcesId;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ KILL vProcesId;
+
+ END LOOP;
+
+ CLOSE vCursor;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/mysqlPreparedCount_check.sql b/db/routines/vn/procedures/mysqlPreparedCount_check.sql
new file mode 100644
index 000000000..b0c78946d
--- /dev/null
+++ b/db/routines/vn/procedures/mysqlPreparedCount_check.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`mysqlPreparedCount_check`()
+BEGIN
+ DECLARE vPreparedCount INTEGER;
+
+ SELECT VARIABLE_VALUE INTO vPreparedCount
+ FROM INFORMATION_SCHEMA.GLOBAL_STATUS
+ WHERE VARIABLE_NAME LIKE '%prepared_stmt_count%';
+
+ IF(vPreparedCount >= 40000) THEN
+ CALL `vn`.`mail_insert`('cau@verdnatura.es',
+ NULL,
+ 'Problemas BBDD prepared_stmt_count',
+ CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ',
+ vPreparedCount,
+ ', está próximo a exceder su límite. \r\n Hay que reiniciar el servicio LF.VMP.Service del servidor a3.')
+ );
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/nextShelvingCodeMake.sql b/db/routines/vn/procedures/nextShelvingCodeMake.sql
new file mode 100644
index 000000000..d76d6276b
--- /dev/null
+++ b/db/routines/vn/procedures/nextShelvingCodeMake.sql
@@ -0,0 +1,41 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`nextShelvingCodeMake`()
+BEGIN
+
+ DECLARE newShelving VARCHAR(3);
+ DECLARE vCode VARCHAR(3);
+
+ SELECT MAX(code) INTO vCode
+ FROM vn.shelving
+ WHERE isPrinted = FALSE;
+
+ SET @a1 := ASCII(MID(vCode,1,1));
+ SET @a2 := ASCII(MID(vCode,2,1));
+ SET @a3 := ASCII(MID(vCode,3,1)) + 1;
+
+ IF @a3 > 90 THEN
+
+ SET @a3 = 65;
+ SET @a2 = @a2 + 1;
+
+ IF @a2 > 90 THEN
+
+ SET @a2 = 65;
+ SET @a1 = @a1 + 1;
+
+ IF @a1 > 90 THEN
+
+ SET @a1 = 65;
+
+ END IF;
+
+ END IF;
+
+ END IF;
+
+ SET newShelving = CHAR(@a1,@a2,@a3 USING utf8);
+
+ INSERT INTO vn.shelving(code) VALUES(newShelving);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/observationAdd.sql b/db/routines/vn/procedures/observationAdd.sql
new file mode 100644
index 000000000..960cf0bfe
--- /dev/null
+++ b/db/routines/vn/procedures/observationAdd.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`observationAdd`(vOriginFk INT, vTableCode VARCHAR(45), vDescription TEXT)
+BEGIN
+/**
+ * Guarda las observaciones realizadas por el usuario
+ *
+ * @param vOriginFk Id del registro de origen
+ * @param vTypeCode Código que referencia a la tabla.
+ * @param descripcion Texto de la observacion
+ */
+ DECLARE vTableName VARCHAR(45);
+
+ SET vTableName = CONCAT(vTableCode,'Observation');
+
+ IF ISNULL(vTableName) THEN
+ CALL util.throw('CODE_NOT_FOUND');
+ END IF;
+
+ SET @qryLog := CONCAT(
+ 'INSERT INTO ', vTableName, ' (originFk, userFk, description)',
+ ' VALUES (', vOriginFk, ', ', account.myUser_getId(), ', "', vDescription, '")'
+ );
+
+ PREPARE stmt FROM @qryLog;
+ EXECUTE stmt;
+ DEALLOCATE PREPARE stmt;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/orderCreate.sql b/db/routines/vn/procedures/orderCreate.sql
new file mode 100644
index 000000000..8f732dad6
--- /dev/null
+++ b/db/routines/vn/procedures/orderCreate.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`orderCreate`(
+ vLanded DATE,
+ vAgencyMode INT,
+ vAddress INT,
+ vSourceApp VARCHAR(10),
+ OUT vOrderId INT)
+BEGIN
+
+ DECLARE vDeliveryMethod INT;
+ DECLARE vClient INT;
+
+ SELECT deliveryMethodFk INTO vDeliveryMethod
+ FROM vn.agencyMode
+ WHERE id = vAgencyMode;
+
+ SELECT clientFk INTO vClient
+ FROM vn.address
+ WHERE id = vAddress;
+
+ INSERT INTO hedera.order(date_send,customer_id,delivery_method_id,agency_id,address_id,source_app)
+ VALUES( vLanded,vClient ,vDeliveryMethod,vAgencyMode ,vAddress ,vSourceApp);
+
+ SET vOrderId = LAST_INSERT_ID();
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/orderDelete.sql b/db/routines/vn/procedures/orderDelete.sql
new file mode 100644
index 000000000..4264191da
--- /dev/null
+++ b/db/routines/vn/procedures/orderDelete.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`orderDelete`(IN vId INT)
+BEGIN
+
+ DELETE FROM hedera.`order` where id = vId;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/orderListCreate.sql b/db/routines/vn/procedures/orderListCreate.sql
new file mode 100644
index 000000000..12396ea90
--- /dev/null
+++ b/db/routines/vn/procedures/orderListCreate.sql
@@ -0,0 +1,14 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`orderListCreate`(
+ vLanded DATE,
+ vAgencyMode INT,
+ vAddress INT,
+ vSourceApp VARCHAR(10))
+BEGIN
+
+ DECLARE vOrderId INT;
+ CALL vn.orderCreate(vLanded,vAgencyMode,vAddress,vSourceApp,vOrderId);
+ SELECT vOrderId;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/orderListVolume.sql b/db/routines/vn/procedures/orderListVolume.sql
new file mode 100644
index 000000000..6eb641f83
--- /dev/null
+++ b/db/routines/vn/procedures/orderListVolume.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`orderListVolume`(IN vOrderId INT)
+BEGIN
+
+ SELECT
+ o.id,
+ o.itemFk,
+ i.description,
+ o.amount,
+ round(ic.cm3delivery * o.amount / 1000000,3) as volume
+ FROM hedera.orderRow o
+ JOIN item i ON i.id = o.itemFk
+ JOIN itemCost ic ON ic.itemFk = o.itemFk AND ic.warehouseFk = o.warehouseFk
+ WHERE o.orderFk = vOrderId;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/packageInvoicing.sql b/db/routines/vn/procedures/packageInvoicing.sql
new file mode 100644
index 000000000..7dae8dcf2
--- /dev/null
+++ b/db/routines/vn/procedures/packageInvoicing.sql
@@ -0,0 +1,121 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`packageInvoicing`(
+ IN vClient INT,
+ IN vDate DATE,
+ IN vCompany INT,
+ IN vIsAllInvoiceable BOOLEAN,
+ OUT vNewTicket INT(11)
+ )
+BEGIN
+
+ DECLARE vGraceDays INT;
+ DECLARE vDateStart DATE DEFAULT '2017-11-21';
+ DECLARE vIsInvoiceable BOOLEAN;
+ DECLARE vWarehouse INT DEFAULT 13;
+ DECLARE vComponentCost INT DEFAULT 28;
+ DECLARE vGraceDate DATE;
+ DECLARE vDateEnd DATE;
+
+ SET vGraceDays = IF(vIsAllInvoiceable ,0, 30);
+ SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate);
+
+ /* Clientes especiales:
+ 3240 MADEFLOR
+ 992 JAVIER FELIU
+ 4 TONI VENDRELL
+ */
+
+ IF vClient IN (992, 3240, 4) THEN
+
+ SET vGraceDays = 365;
+
+ END IF;
+ /* Fin clientes especiales */
+
+ SET vDateEnd = DATE_ADD(vDate, INTERVAL 1 DAY);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice;
+
+ CREATE TEMPORARY TABLE tmp.packageToInvoice
+ SELECT p.itemFk,
+ tp.packagingFk,
+ IF(tp.quantity < 0 OR t.shipped < vGraceDate, tp.quantity, 0) quantity,
+ tp.ticketFk,
+ p.price
+ FROM ticketPackaging tp
+ JOIN packaging p ON p.id = tp.packagingFk
+ JOIN ticket t ON t.id = tp.ticketFk
+ WHERE t.shipped BETWEEN vDateStart AND vDateEnd
+ AND t.clientFk = vClient;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoicePositives;
+
+ CREATE TEMPORARY TABLE tmp.packageToInvoicePositives
+ SELECT itemFk, sum(quantity) as totalQuantity
+ FROM tmp.packageToInvoice
+ GROUP BY itemFk
+ HAVING totalQuantity > 0;
+
+ SELECT COUNT(*)
+ INTO vIsInvoiceable
+ FROM tmp.packageToInvoicePositives;
+
+ IF vIsInvoiceable THEN
+
+ CALL ticket_add(vClient,
+ vDateEnd,
+ vWarehouse,
+ vCompany,
+ NULL,
+ NULL,
+ NULL,
+ vDateEnd,
+ account.myUser_getId(),
+ TRUE,
+ vNewTicket);
+
+ INSERT INTO ticketPackaging(
+ ticketFk,
+ packagingFk,
+ quantity,
+ pvp)
+ SELECT vNewTicket,
+ pti.packagingFk,
+ - SUM(pti.quantity) AS totalQuantity,
+ pti.price
+ FROM tmp.packageToInvoice pti
+ LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk
+ WHERE ptip.itemFK IS NOT NULL
+ OR vIsAllInvoiceable
+ GROUP BY packagingFk
+ HAVING totalQuantity;
+
+ INSERT INTO sale(
+ ticketFk,
+ itemFk,
+ concept,
+ quantity,
+ price
+ )
+ SELECT vNewTicket,
+ pti.itemFk,
+ i.name as concept,
+ sum(pti.quantity) as totalQuantity,
+ pti.price
+ FROM tmp.packageToInvoice pti
+ JOIN item i ON i.id = pti.itemFk
+ LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk
+ WHERE ptip.itemFK IS NOT NULL
+ OR vIsAllInvoiceable
+ GROUP BY pti.itemFk
+ HAVING totalQuantity;
+
+ INSERT INTO saleComponent(saleFk, componentFk, value)
+ SELECT id, vComponentCost, price
+ FROM sale
+ WHERE ticketFk = vNewTicket;
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/packingListPrinted.sql b/db/routines/vn/procedures/packingListPrinted.sql
new file mode 100644
index 000000000..473ead5be
--- /dev/null
+++ b/db/routines/vn/procedures/packingListPrinted.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`packingListPrinted`(ticketFk INT)
+BEGIN
+
+ UPDATE vn2008.Movimientos_mark mm
+ JOIN vn2008.Movimientos m ON m.Id_Movimiento = mm.Id_Movimiento
+ SET mm.valor = 2 -- Impreso
+ WHERE mm.valor = 1 -- Listo para imprimir
+ AND mm.stateFk = 9 -- Encajando
+ AND m.Id_Ticket = ticketFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/packingListSwitch.sql b/db/routines/vn/procedures/packingListSwitch.sql
new file mode 100644
index 000000000..65384827c
--- /dev/null
+++ b/db/routines/vn/procedures/packingListSwitch.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`packingListSwitch`(saleFk INT)
+BEGIN
+
+ DECLARE valueFk INT;
+ DECLARE encajando INT DEFAULT 9;
+
+ SELECT valor INTO valueFk
+ FROM vn2008.Movimientos_mark
+ WHERE Id_Movimiento = saleFk
+ AND stateFk = encajando;
+
+ SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3;
+
+ REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk)
+ VALUES(saleFk,valueFk,account.myUser_getId(),encajando);
+
+
+END$$
+DELIMITER ;
diff --git a/db/changes/232601/00-packingSiteAdvanced.sql b/db/routines/vn/procedures/packingSite_startCollection.sql
similarity index 60%
rename from db/changes/232601/00-packingSiteAdvanced.sql
rename to db/routines/vn/procedures/packingSite_startCollection.sql
index 0e33744cd..53edd89f1 100644
--- a/db/changes/232601/00-packingSiteAdvanced.sql
+++ b/db/routines/vn/procedures/packingSite_startCollection.sql
@@ -1,22 +1,5 @@
-CREATE TABLE `vn`.`packingSiteAdvanced` (
- `ticketFk` int(11),
- `workerFk` int(10) unsigned,
- PRIMARY KEY (`ticketFk`),
- KEY `packingSiteAdvanced_FK_1` (`workerFk`),
- CONSTRAINT `packingSiteAdvanced_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `packingSiteAdvanced_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('PackingSiteAdvanced', '*', '*', 'ALLOW', 'ROLE', 'production');
-
- DROP PROCEDURE IF EXISTS `vn`.`packingSite_startCollection`;
-
DELIMITER $$
-$$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`packingSite_startCollection`(vSelf INT, vTicketFk INT)
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`packingSite_startCollection`(vSelf INT, vTicketFk INT)
proc: BEGIN
/**
* @param vSelf packingSite id
@@ -66,6 +49,3 @@ proc: BEGIN
WHERE id = vSelf;
END$$
DELIMITER ;
-
-
-
diff --git a/db/routines/vn/procedures/parking_add.sql b/db/routines/vn/procedures/parking_add.sql
new file mode 100644
index 000000000..17772424e
--- /dev/null
+++ b/db/routines/vn/procedures/parking_add.sql
@@ -0,0 +1,41 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`parking_add`(vFromColumn INT, vToColumn INT, vFromRow INT, vToRow INT, vSectorFk INT, vIsLetterMode BOOLEAN)
+BEGIN
+
+ DECLARE vColumn INT;
+ DECLARE vRow INT;
+ DECLARE vLetters VARCHAR(26) DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ DECLARE vMaxId INT;
+ DECLARE vCode VARCHAR(8);
+
+ SET vColumn = vFromColumn;
+ SET vRow = vFromRow;
+ SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0')));
+
+ SELECT MAX(id) INTO vMaxId
+ FROM vn.parking;
+
+ WHILE vColumn <= vToColumn DO
+
+ WHILE vRow <= vToRow DO
+
+ INSERT IGNORE INTO vn.parking(`column`, `row`, sectorFk, `code`, pickingOrder)
+ VALUES (vColumn, vRow, vSectorFk, vCode, vColumn * 100 + vRow )
+ ON DUPLICATE KEY UPDATE `code` = vCode;
+
+ SET vRow = vRow + 1;
+ SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0')));
+
+ END WHILE;
+
+ SET vRow = vFromRow;
+ SET vColumn = vColumn + 1;
+
+ SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0')));
+
+ END WHILE;
+
+ SELECT * FROM vn.parking WHERE `column` BETWEEN vFromColumn AND vToColumn;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/parking_algemesi.sql b/db/routines/vn/procedures/parking_algemesi.sql
new file mode 100644
index 000000000..6ea13193d
--- /dev/null
+++ b/db/routines/vn/procedures/parking_algemesi.sql
@@ -0,0 +1,62 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`parking_algemesi`(vFromRow INT, vToRow INT, vSectorFk INT, vLetter VARCHAR(1), vPickingOrder INT, vTrolleysByLine INT)
+BEGIN
+
+ DECLARE vRow INT;
+ DECLARE vCode VARCHAR(8);
+ DECLARE i INT;
+
+ IF vToRow < vFromRow THEN
+
+ SET vRow = vFromRow;
+
+ WHILE vRow >= vToRow DO
+
+ SET i = 1;
+
+ WHILE i <= vTrolleysByLine DO
+
+ SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i);
+
+ INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder)
+ VALUES (vSectorFk, vCode, vPickingOrder + (i * 10))
+ ON DUPLICATE KEY UPDATE `code` = vCode;
+
+ SET i = i + 1;
+
+ END WHILE;
+
+ SET vRow = vRow - 1;
+
+ END WHILE;
+
+ ELSE
+
+ SET vRow = vFromRow;
+
+ WHILE vRow <= vToRow DO
+
+ SET i = 1;
+
+ WHILE i <= vTrolleysByLine DO
+
+ SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i);
+
+ INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder)
+ VALUES (vSectorFk, vCode, vPickingOrder + (i * 10) )
+ ON DUPLICATE KEY UPDATE `code` = vCode;
+
+ SET i = i + 1;
+
+ END WHILE;
+
+ SET vRow = vRow + 1;
+
+ END WHILE;
+
+
+ END IF;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/parking_new.sql b/db/routines/vn/procedures/parking_new.sql
new file mode 100644
index 000000000..327e3a4b0
--- /dev/null
+++ b/db/routines/vn/procedures/parking_new.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`parking_new`(vStart INT, vEnd INT, vSectorFk INT)
+BEGIN
+
+ DECLARE vRow INT;
+ DECLARE vColumn INT;
+ DECLARE vLetters VARCHAR(200);
+ DECLARE vLettersLength INT;
+
+ SET vColumn = vStart;
+ SET vRow = 1;
+ SET vLetters = 'ABCDEF';
+ SET vLettersLength = LENGTH(vLetters);
+
+ WHILE vColumn <= vEnd DO
+
+ REPLACE vn.parking(`column`, `row`, `code`, sectorFk)
+ VALUES(vColumn, vRow, CONCAT(vColumn,MID(vLetters,vRow,1)), vSectorFk);
+
+ SET vRow = vRow + 1;
+
+ IF vRow > vLettersLength THEN
+
+ SET vRow = 1;
+ SET vColumn = vColumn + 1;
+
+ END IF;
+
+ END WHILE;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/parking_setOrder.sql b/db/routines/vn/procedures/parking_setOrder.sql
new file mode 100644
index 000000000..241f855f7
--- /dev/null
+++ b/db/routines/vn/procedures/parking_setOrder.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`parking_setOrder`(vWarehouseFk INT)
+BEGIN
+
+ /*
+ * Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor
+ */
+
+ UPDATE vn.parking p
+ JOIN (
+ SELECT code,
+ @orden := @orden + 10 AS po
+ FROM (
+ SELECT c.prepOrder,
+ p.code,
+ @orden := 0,
+ IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor ,
+ CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication
+ FROM vn.parking p
+ JOIN vn.sector s ON s.id = p.sectorFk
+ JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci
+ WHERE s.warehouseFk = vWarehouseFk) sub
+ ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code
+ SET p.pickingOrder = sub2.po;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/payment_add.sql b/db/routines/vn/procedures/payment_add.sql
new file mode 100644
index 000000000..061a75848
--- /dev/null
+++ b/db/routines/vn/procedures/payment_add.sql
@@ -0,0 +1,84 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`payment_add`(
+ vDated DATE,
+ vSupplierFk INT,
+ vAmount DOUBLE,
+ vCurrencyFk INT,
+ vForeignValue DOUBLE,
+ vBankFk INT,
+ vPayMethodFk INT,
+ vExpenseFk DOUBLE,
+ vConcept VARCHAR(40),
+ vCompanyFk INT)
+BEGIN
+/**
+ * Registra un pago realizado a un proveedor y
+ * su correspondiente registro en caja.
+ *
+ * @param vDated Fecha del pago
+ * @param vSupplierFk Id del proveedor
+ * @param vAmount Cantidad a pagar
+ * @param vCurrencyFk Id de la moneda
+ * @param vForeignValue Tipo de cambio utilizado
+ * @param vBankFk Id del banco
+ * @param vPayMethodFk Id del método de pago
+ * @param vExpenseFk Id de gasto
+ * @param vConcept Concepto del pago
+ * @param vCompanyFk Id de la empresa
+ * @return paymentFk Id de pago insertado
+ */
+ INSERT INTO till(
+ concept,
+ serie,
+ `number`,
+ `out`,
+ dated,
+ isAccountable,
+ bankFk,
+ workerFk,
+ companyFk,
+ isConciliate
+ )
+ SELECT CONCAT('n/pago a ', `name`),
+ 'R',
+ vSupplierFk,
+ vAmount,
+ vDated,
+ 1,
+ vBankFk,
+ account.myUser_getId(),
+ vCompanyFk,
+ 1
+ FROM supplier
+ WHERE id = vSupplierFk;
+
+ INSERT INTO payment(
+ received,
+ dueDated,
+ supplierFk,
+ amount,
+ currencyFk,
+ divisa,
+ bankFk,
+ payMethodFk,
+ bankingFees,
+ concept,
+ companyFk
+ )
+ VALUES(
+ vDated,
+ vDated,
+ vSupplierFk,
+ vAmount,
+ vCurrencyFk,
+ IF(NOT vForeignValue, NULL, vForeignValue),
+ vBankFk,
+ vPayMethodFk,
+ vExpenseFk,
+ vConcept,
+ vCompanyFk
+ );
+
+ SELECT LAST_INSERT_ID() paymentFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/prepareClientList.sql b/db/routines/vn/procedures/prepareClientList.sql
new file mode 100644
index 000000000..486152fd6
--- /dev/null
+++ b/db/routines/vn/procedures/prepareClientList.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`prepareClientList`()
+BEGIN
+
+ /*
+ * Require la tabla tmp.ticket(id,clientFk)
+ */
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.client;
+ CREATE TEMPORARY TABLE tmp.client
+ (PRIMARY KEY (id))
+ ENGINE = MEMORY
+ SELECT DISTINCT clientFk id
+ FROM tmp.ticket;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/prepareTicketList.sql b/db/routines/vn/procedures/prepareTicketList.sql
new file mode 100644
index 000000000..f0f47f9a2
--- /dev/null
+++ b/db/routines/vn/procedures/prepareTicketList.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`prepareTicketList`(vStartingDate DATETIME, vEndingDate DATETIME)
+BEGIN
+ DROP TEMPORARY TABLE IF EXISTS tmp.productionTicket;
+ CREATE TEMPORARY TABLE tmp.productionTicket
+ (PRIMARY KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT t.id ticketFk, t.clientFk
+ FROM vn.ticket t
+ LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id
+ JOIN vn.client c ON c.id = t.clientFk
+ WHERE c.typeFk IN ('normal','handMaking','internalUse')
+ AND (
+ t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate
+ OR (
+ ts.alertLevel < 3
+ AND t.shipped >= vStartingDate
+ AND t.shipped < util.VN_CURDATE()
+ )
+ );
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/previousSticker_get.sql b/db/routines/vn/procedures/previousSticker_get.sql
new file mode 100644
index 000000000..05f7de250
--- /dev/null
+++ b/db/routines/vn/procedures/previousSticker_get.sql
@@ -0,0 +1,58 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`previousSticker_get`(vSaleGroupFk INT)
+BEGIN
+/**
+ * Devuelve los campos a imprimir en una etiqueta de preparación previa.
+ * Actualiza el valor de vn.saleGroup.parkingFk en el caso de que exista un
+ * saleGroup del mismo ticket con parking, del mismo sector, para que todos se
+ * pongan juntos.
+ *
+ * @param vSaleGroupFk Identificador de vn.saleGroup
+ */
+ DECLARE vTicketFk INT;
+ DECLARE vParkingFk INT;
+ DECLARE vSectorFk INT;
+
+ SELECT s.ticketFk
+ INTO vTicketFk
+ FROM vn.saleGroupDetail sgd
+ JOIN vn.sale s ON s.id = sgd.saleFk
+ WHERE sgd.saleGroupFk = vSaleGroupFk
+ LIMIT 1;
+
+ SELECT sg.parkingFk, sc.sectorFk
+ INTO vParkingFk, vSectorFk
+ FROM vn.saleGroup sg
+ JOIN vn.sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
+ JOIN vn.sectorCollection sc ON sc.id = scsg.sectorCollectionFk
+ JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = sg.id
+ JOIN vn.sale s ON s.id = sgd.saleFk
+ WHERE s.ticketFk = vTicketFk
+ AND sg.parkingFk IS NOT NULL
+ LIMIT 1;
+
+ UPDATE vn.saleGroup sg
+ SET sg.parkingFk = vParkingFk
+ WHERE sg.id = vSaleGroupFk
+ AND sg.sectorFk = vSectorFk;
+
+ SELECT sgd.saleGroupFk,
+ t.id ticketFk,
+ p.code as location,
+ t.observations,
+ IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) shippingHour,
+ IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) shippingMinute ,
+ IFNULL(MAX(i.itemPackingTypeFk),'H') itemPackingTypeFk ,
+ count(*) items,
+ sc.description sector
+ FROM vn.sale s
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
+ JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
+ JOIN vn.sector sc ON sc.id = sg.sectorFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ LEFT JOIN vn.parking p ON p.id = sg.parkingFk
+ LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
+ WHERE sgd.saleGroupFk = vSaleGroupFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/printer_checkSector.sql b/db/routines/vn/procedures/printer_checkSector.sql
new file mode 100644
index 000000000..40728a81a
--- /dev/null
+++ b/db/routines/vn/procedures/printer_checkSector.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`printer_checkSector`(vLabelerFk tinyint(3) unsigned, vSector INT(11))
+BEGIN
+/**
+ * Comprueba si la impresora pertenece al sector
+ *
+ * @param vLabelerFk id de la impresora
+ * @param vSector sector a comprobar
+ */
+ DECLARE isPrinterInNewSector BOOL;
+
+ IF vLabelerFk IS NOT NULL THEN
+ SELECT COUNT(sectorFK) INTO isPrinterInNewSector
+ FROM vn.printer p
+ WHERE id = vLabelerFk AND sectorFk = vSector;
+
+ IF !isPrinterInNewSector THEN
+ CALL util.throw("PrinterNotInSameSector");
+ END IF;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql
new file mode 100644
index 000000000..b42645d1e
--- /dev/null
+++ b/db/routines/vn/procedures/productionControl.sql
@@ -0,0 +1,263 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`productionControl`(
+ vWarehouseFk INT,
+ vScopeDays INT
+)
+proc: BEGIN
+/**
+ * Devuelve un listado de tickets con parámetros relativos a la producción de los días en rango.
+ *
+ * @param vWarehouseFk Identificador de warehouse
+ * @param vScopeDays Número de días desde hoy en adelante que entran en el cálculo.
+ *
+ * @return Table tmp.productionBuffer
+ */
+ DECLARE vEndingDate DATETIME;
+ DECLARE vIsTodayRelative BOOLEAN;
+
+ SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY
+ INTO vEndingDate
+ FROM productionConfig;
+
+ SELECT isTodayRelative INTO vIsTodayRelative
+ FROM worker
+ WHERE id = getUser(); -- Cambiar por account.myUser_getId(), falta dar permisos
+
+ CALL prepareTicketList(util.yesterday(), vEndingDate);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
+ SELECT * FROM tmp.productionTicket;
+
+ CALL prepareClientList();
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems
+ (INDEX (ticketFk)) ENGINE = MEMORY
+ SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped
+ FROM tmp.productionTicket tt
+ JOIN ticket t ON t.id = tt.ticketFk;
+
+ CALL ticket_getProblems(vIsTodayRelative);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.productionBuffer
+ (PRIMARY KEY(ticketFk), previaParking VARCHAR(255))
+ ENGINE = MEMORY
+ SELECT tt.ticketFk,
+ tt.clientFk,
+ t.warehouseFk,
+ t.nickname,
+ t.packages,
+ IF(HOUR(t.shipped), HOUR(t.shipped), COALESCE(HOUR(zc.hour),HOUR(z.hour))) HH,
+ COALESCE(HOUR(zc.hour), HOUR(z.hour)) Departure,
+ COALESCE(MINUTE(t.shipped), MINUTE(zc.hour), MINUTE(z.hour)) mm,
+ t.routeFk,
+ IF(dm.code = 'DELIVERY', z.`id`, 0) zona,
+ t.nickname addressNickname,
+ a.postalCode,
+ a.city,
+ p.name province,
+ CONCAT(z.`name`,' ',IFNULL(RIGHT(t.routeFk,3),'')) agency,
+ am.id agencyModeFk,
+ 0 `lines`,
+ CAST( 0 AS DECIMAL(5,2)) m3,
+ CAST( 0 AS DECIMAL(5,2)) preparationRate,
+ "" problem,
+ IFNULL(tls.state,2) state,
+ w.code workerCode,
+ DATE(t.shipped) shipped,
+ wk.code salesPersonCode,
+ p.id provinceFk,
+ tls.productionOrder,
+ IFNULL(tls.alertLevel, 0) alertLevel,
+ t.isBoxed palletized,
+ IF(rm.isPickingAllowed, rm.bufferFk, NULL) ubicacion,
+ tlu.lastUpdated,
+ IFNULL(st.graphCategory, 0) graphCategory,
+ pk.code parking,
+ 0 H,
+ 0 V,
+ 0 N,
+ st.isOk,
+ ag.isOwn,
+ rm.bufferFk
+ FROM tmp.productionTicket tt
+ JOIN ticket t ON tt.ticketFk = t.id
+ LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id
+ LEFT JOIN `state` st ON st.id = tst.state
+ LEFT JOIN client c ON c.id = t.clientFk
+ LEFT JOIN worker wk ON wk.id = c.salesPersonFk
+ JOIN address a ON a.id = t.addressFk
+ LEFT JOIN province p ON p.id = a.provinceFk
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ JOIN agency ag ON ag.id = am.agencyFk
+ LEFT JOIN ticketState tls ON tls.ticketFk = tt.ticketFk
+ LEFT JOIN ticketLastUpdated tlu ON tlu.ticketFk = tt.ticketFk
+ LEFT JOIN worker w ON w.id = tls.userFk
+ LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk
+ LEFT JOIN `zone` z ON z.id = t.zoneFk
+ LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
+ AND DATE(t.shipped) = zc.dated
+ LEFT JOIN ticketParking tp ON tp.ticketFk = t.id
+ LEFT JOIN parking pk ON pk.id = tp.parkingFk
+ WHERE t.warehouseFk = vWarehouseFk
+ AND dm.code IN ('AGENCY', 'DELIVERY', 'PICKUP');
+
+ UPDATE tmp.productionBuffer pb
+ JOIN (
+ SELECT pb.ticketFk, GROUP_CONCAT(p.code) previaParking
+ FROM tmp.productionBuffer pb
+ JOIN sale s ON s.ticketFk = pb.ticketFk
+ JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
+ JOIN parking p ON p.id = sg.parkingFk
+ GROUP BY pb.ticketFk
+ ) t ON t.ticketFk = pb.ticketFk
+ SET pb.previaParking = t.previaParking;
+
+ -- Problemas por ticket
+ ALTER TABLE tmp.productionBuffer
+ CHANGE COLUMN `problem` `problem` VARCHAR(255),
+ ADD COLUMN `collectionH` INT,
+ ADD COLUMN `collectionV` INT,
+ ADD COLUMN `collectionN` INT;
+
+ UPDATE tmp.productionBuffer pb
+ JOIN tmp.ticket_problems tp ON tp.ticketFk = pb.ticketFk
+ SET pb.problem = TRIM(CAST(CONCAT( IFNULL(tp.itemShortage, ''),
+ IFNULL(tp.itemDelay, ''),
+ IFNULL(tp.itemLost, ''),
+ IF(tp.isFreezed, ' CONGELADO',''),
+ IF(tp.hasHighRisk, ' RIESGO',''),
+ IF(tp.hasTicketRequest, ' COD 100',''),
+ IF(tp.isTaxDataChecked, '',' FICHA INCOMPLETA'),
+ IF(tp.hasComponentLack, ' COMPONENTES', ''),
+ IF(HOUR(util.VN_NOW()) < pb.HH AND tp.isTooLittle, ' PEQUEÑO', '')
+ ) AS char(255)));
+
+ -- Clientes Nuevos o Recuperados
+ UPDATE tmp.productionBuffer pb
+ LEFT JOIN bs.clientNewBorn cnb ON cnb.clientFk = pb.clientFk
+ JOIN productionConfig pc
+ SET pb.problem = TRIM(CAST(CONCAT('NUEVO ', pb.problem) AS CHAR(255)))
+ WHERE (cnb.clientFk IS NULL OR cnb.isRookie)
+ AND pc.rookieDays;
+
+ -- Líneas y volumen por ticket
+ UPDATE tmp.productionBuffer pb
+ JOIN (
+ SELECT tt.ticketFk,
+ COUNT(*) `lines`,
+ SUM(sv.volume) m3,
+ IFNULL(SUM(IF(sv.isPicked, sv.volume, 0)) / SUM(sv.volume), 0) rate
+ FROM tmp.productionTicket tt
+ JOIN saleVolume sv ON sv.ticketFk = tt.ticketFk
+ GROUP BY tt.ticketFk
+ ) m ON m.ticketFk = pb.ticketFk
+ SET pb.`lines` = m.`lines`,
+ pb.m3 = m.m3,
+ pb.preparationRate = m.rate;
+
+ DELETE FROM tmp.productionBuffer
+ WHERE NOT `lines`;
+
+ -- Lineas por linea de encajado
+ UPDATE tmp.productionBuffer pb
+ JOIN (
+ SELECT ticketFk,
+ SUM(sub.H) H,
+ SUM(sub.V) V,
+ SUM(sub.N) N
+ FROM (
+ SELECT t.ticketFk,
+ SUM(i.itemPackingTypeFk = 'H') H,
+ SUM(i.itemPackingTypeFk = 'V') V,
+ SUM(i.itemPackingTypeFk IS NULL) N
+ FROM tmp.productionTicket t
+ JOIN sale s ON s.ticketFk = t.ticketFk
+ JOIN item i ON i.id = s.itemFk
+ GROUP BY t.ticketFk, i.itemPackingTypeFk
+ ) sub
+ GROUP BY ticketFk
+ ) sub2 ON sub2.ticketFk = pb.ticketFk
+ SET pb.H = sub2.H,
+ pb.V = sub2.V,
+ pb.N = sub2.N;
+
+ -- Colecciones segun tipo de encajado
+ UPDATE tmp.productionBuffer pb
+ JOIN ticketCollection tc ON pb.ticketFk = tc.ticketFk
+ SET pb.collectionH = IF(pb.H, tc.collectionFk, NULL),
+ pb.collectionV = IF(pb.V, tc.collectionFk, NULL),
+ pb.collectionN = IF(pb.N, tc.collectionFk, NULL);
+
+ -- Previa pendiente
+ ALTER TABLE tmp.productionBuffer
+ ADD previousWithoutParking BOOL DEFAULT FALSE;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketWithPrevia
+ (ticketFk INT PRIMARY KEY,
+ salesCount INT DEFAULT 0,
+ salesInParkingCount INT DEFAULT 0)
+ ENGINE = MEMORY;
+
+ -- Insertamos todos los tickets que tienen productos parkineados
+ -- en sectores de previa, segun el sector
+ CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock
+ (PRIMARY KEY(itemFk, sectorFk))
+ ENGINE = MEMORY
+ SELECT ish.itemFk,
+ p.sectorFk,
+ st.code = 'previousPrepared' isPreviousPrepared,
+ sc.itemPackingTypeFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector sc ON sc.id = p.sectorFk
+ JOIN sectorType st ON st.id = sc.typeFk
+ WHERE p.sectorFk
+ AND ish.visible
+ GROUP BY ish.itemFk, p.sectorFk;
+
+ INSERT INTO tmp.ticketWithPrevia(ticketFk, salesCount)
+ SELECT pb.ticketFk, COUNT(DISTINCT s.id)
+ FROM tmp.productionBuffer pb
+ JOIN sale s ON s.ticketFk = pb.ticketFk
+ JOIN tItemShelvingStock iss ON iss.itemFk = s.itemFk
+ JOIN sector sc ON sc.id = iss.sectorFk
+ JOIN item i ON i.id = iss.itemFk
+ WHERE iss.isPreviousPrepared
+ AND (sc.itemPackingTypeFk IS NULL
+ OR (i.itemPackingTypeFk IS NULL AND NOT pb.V)
+ OR sc.itemPackingTypeFk = i.itemPackingTypeFk)
+ AND s.quantity > 0
+ GROUP BY pb.ticketFk;
+
+ -- Se calcula la cantidad de productos que estan ya preparados porque su saleGroup está aparcado
+ UPDATE tmp.ticketWithPrevia twp
+ JOIN (
+ SELECT pb.ticketFk, COUNT(DISTINCT s.id) salesInParkingCount
+ FROM tmp.productionBuffer pb
+ JOIN sale s ON s.ticketFk = pb.ticketFk
+ JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
+ WHERE sg.parkingFk IS NOT NULL
+ AND s.quantity > 0
+ GROUP BY pb.ticketFk
+ ) sub ON twp.ticketFk = sub.ticketFk
+ SET twp.salesInParkingCount = sub.salesInParkingCount;
+
+ -- Marcamos como pendientes aquellos que no coinciden las cantidades
+ UPDATE tmp.productionBuffer pb
+ JOIN tmp.ticketWithPrevia twp ON twp.ticketFk = pb.ticketFk
+ SET pb.previousWithoutParking = TRUE
+ WHERE twp.salesCount > twp.salesInParkingCount;
+
+ DROP TEMPORARY TABLE
+ tmp.productionTicket,
+ tmp.ticket,
+ tmp.risk,
+ tmp.ticket_problems,
+ tmp.ticketWithPrevia,
+ tItemShelvingStock;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/productionError_add.sql b/db/routines/vn/procedures/productionError_add.sql
new file mode 100644
index 000000000..e29accac9
--- /dev/null
+++ b/db/routines/vn/procedures/productionError_add.sql
@@ -0,0 +1,164 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`productionError_add`()
+BEGIN
+ DECLARE vDatedFrom DATETIME;
+ DECLARE vDatedTo DATETIME;
+/**
+ * Rellena la tabla vn.productionError con estadisticas de encajadores, revisores y sacadores. Se ejecuta en el nightTask
+ */
+ SELECT util.VN_CURDATE() - INTERVAL 1 DAY, util.dayend(util.VN_CURDATE() - INTERVAL 1 DAY) INTO vDatedFrom, vDatedTo;
+ CALL timeControl_calculateAll(vDatedFrom, vDatedTo);
+
+ -- Rellena la tabla tmp.errorsByClaim con encajadores, revisores y sacadores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByClaim
+ ENGINE = MEMORY
+ SELECT COUNT(c.ticketFk) errors,
+ cd.workerFk
+ FROM claimDevelopment cd
+ JOIN claim c ON cd.claimFk = c.id
+ JOIN ticket t ON c.ticketFk = t.id
+ JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ AND cr.code IN ('pic', 'chk', 'pck')
+ GROUP BY cd.workerFk;
+
+ -- Genera la tabla tmp.volume con encajadores, sacadores y revisores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.volume
+ ENGINE = MEMORY
+ SELECT SUM(w.volume) volume,
+ w.workerFk
+ FROM bs.workerProductivity w
+ WHERE w.dated BETWEEN vDatedFrom AND vDatedTo
+ GROUP BY w.workerFk;
+
+ -- Rellena la tabla tmp.errorsByChecker con fallos de revisores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByChecker
+ ENGINE = MEMORY
+ WITH rankedWorkers AS (
+ SELECT sm.id,
+ st.workerFk,
+ ROW_NUMBER() OVER(PARTITION BY sm.id ORDER BY s2.`order`) rnk
+ FROM vn.saleMistake sm
+ JOIN vn.saleTracking st ON sm.saleFk = st.saleFk
+ JOIN vn.`state` s2 ON s2.id = st.stateFk
+ JOIN vn.sale s ON s.id = sm.saleFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ AND s2.code IN ('OK', 'PREVIOUS_PREPARATION', 'PREPARED', 'CHECKED')
+ )
+ SELECT workerFk, COUNT(*) errors
+ FROM rankedWorkers
+ WHERE rnk = 1
+ GROUP BY workerFk;
+
+ -- Rellena la tabla tmp.expeditionErrors con fallos de expediciones
+ CREATE OR REPLACE TEMPORARY TABLE tmp.expeditionErrors
+ ENGINE = MEMORY
+ SELECT COUNT(t.id) errors,
+ e.workerFk
+ FROM vn.expeditionMistake pm
+ JOIN vn.expedition e ON e.id = pm.expeditionFk
+ JOIN vn.ticket t ON t.id = e.ticketFk
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ GROUP BY e.workerFk;
+
+ -- Genera la tabla tmp.total para sacadores y revisores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.total
+ ENGINE = MEMORY
+ SELECT st.workerFk,
+ COUNT(DISTINCT t.id) ticketCount,
+ COUNT(s.id) lineCount
+ FROM saleTracking st
+ JOIN `state` s2 ON s2.id = st.stateFk
+ JOIN sale s ON s.id = st.saleFk
+ JOIN ticket t ON s.ticketFk = t.id
+ WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo)
+ AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED')
+ GROUP BY st.workerFk;
+
+ -- Rellena la tabla vn.productionError con sacadores
+ INSERT INTO productionError(userFk,
+ firstname,
+ lastname,
+ rol,
+ ticketNumber,
+ lineNumber,
+ error,
+ volume,
+ hourStart,
+ hourEnd,
+ hourWorked,
+ dated)
+ SELECT w.id,
+ w.firstName,
+ w.lastName,
+ "Sacadores",
+ t.ticketCount totalTickets,
+ t.lineCount,
+ IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) errors,
+ v.volume volume,
+ SUBSTRING(tc.tableTimed, 1, 5) hourStart,
+ SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd,
+ IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked,
+ vDatedFrom dated
+ FROM tmp.total t
+ LEFT JOIN worker w ON w.id = t.workerFk
+ LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk
+ LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk
+ LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk
+ LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk
+ JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores
+ FROM vn.collection c
+ JOIN vn.state s ON s.id = c.stateFk
+ JOIN vn.train tn ON tn.id = c.trainFk
+ JOIN vn.worker w ON w.id = c.workerFk
+ WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id
+ GROUP BY w.id;
+
+ CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores
+ ENGINE = MEMORY
+ SELECT COUNT(c.ticketFk) errors,
+ tt.userFk
+ FROM claimDevelopment cd
+ JOIN claim c ON cd.claimFk = c.id
+ JOIN ticket t ON c.ticketFk = t.id
+ JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
+ JOIN ticketTracking tt ON tt.ticketFk = t.id
+ JOIN `state` s ON s.id = tt.stateFk
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ AND cr.code = 'chk'
+ AND s.code = 'ON_PREPARATION'
+ GROUP BY tt.userFk;
+
+ UPDATE productionError ep
+ JOIN itemPickerErrors ipe ON ipe.userFk = ep.userFk
+ SET ep.error = ep.error + ipe.errors
+ WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores';
+
+ DROP TEMPORARY TABLE itemPickerErrors;
+
+ -- Rellena la tabla vn.productionError con revisores
+ CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Revisadores");
+
+ -- Genera la tabla tmp.total para encajadores
+ CREATE OR REPLACE TEMPORARY TABLE tmp.total
+ ENGINE = MEMORY
+ SELECT e.workerFk,
+ COUNT(DISTINCT t.id) ticketCount,
+ COUNT(s.id) lineCount
+ FROM expedition e
+ JOIN ticket t ON e.ticketFk = t.id
+ JOIN sale s ON s.ticketFk = t.id
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ GROUP BY e.workerFk;
+
+ -- Rellena la tabla vn.productionError con encajadores
+ CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Encajadores");
+
+ DROP TEMPORARY TABLE tmp.errorsByClaim,
+ tmp.volume,
+ tmp.errorsByChecker,
+ tmp.expeditionErrors,
+ tmp.total;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/productionError_addCheckerPackager.sql b/db/routines/vn/procedures/productionError_addCheckerPackager.sql
new file mode 100644
index 000000000..dd75f797b
--- /dev/null
+++ b/db/routines/vn/procedures/productionError_addCheckerPackager.sql
@@ -0,0 +1,47 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`productionError_addCheckerPackager`(
+ vDatedFrom DATETIME,
+ vDatedTo DATETIME,
+ vRol VARCHAR(50))
+BEGIN
+/**
+ * Rellena la tabla vn.productionError con rol
+ *
+ * @param vDatedFrom Fecha desde
+ * @param vDatedTo Fecha hasta
+ * @param vRol rol a insertar
+ */
+ INSERT INTO productionError(userFk,
+ firstname,
+ lastname,
+ rol,
+ ticketNumber,
+ lineNumber,
+ error,
+ volume,
+ hourStart,
+ hourEnd,
+ hourWorked,
+ dated)
+ SELECT w.id,
+ w.firstName,
+ w.lastName,
+ vRol,
+ t.ticketCount totalTickets,
+ t.lineCount,
+ IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) + IFNULL(pe.errors,0) errors,
+ NULL volume,
+ SUBSTRING(tc.tableTimed, 1, 5) hourStart,
+ SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd,
+ IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked,
+ vDatedFrom dated
+ FROM tmp.total t
+ LEFT JOIN worker w ON w.id = t.workerFk
+ LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk
+ LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk
+ LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk
+ LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk
+ LEFT JOIN tmp.expeditionErrors pe ON pe.workerFk = t.workerFk
+ GROUP BY w.id;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/productionSectorList.sql b/db/routines/vn/procedures/productionSectorList.sql
new file mode 100644
index 000000000..5447f10d0
--- /dev/null
+++ b/db/routines/vn/procedures/productionSectorList.sql
@@ -0,0 +1,108 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`productionSectorList`(vSectorFk INT)
+BEGIN
+/**
+ * Devuelve el listado de sale que se puede preparar en previa para ese sector
+ *
+ * @param vSectorFk Identificador de sector
+ */
+ DECLARE vWarehouseFk INT;
+
+ SELECT warehouseFk INTO vWarehouseFk
+ FROM sector
+ WHERE id = vSectorFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.whiteTicket;
+ CREATE TEMPORARY TABLE tmp.whiteTicket
+ (ticketFk INT PRIMARY KEY)
+ SELECT s.ticketFk , count(*) AS saleNum, sum(ISNULL(i.itemPackingTypeFk)) iptNull
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(HOUR, 23, util.VN_CURDATE())
+ GROUP BY s.ticketFk
+ HAVING saleNum = iptNull;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.sectorTypeTicket;
+ CREATE TEMPORARY TABLE tmp.sectorTypeTicket
+ (ticketFk INT PRIMARY KEY)
+ SELECT s.ticketFk , sum(i.itemPackingTypeFk <=> sc.itemPackingTypeFk) iptSector
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN sector sc ON sc.id = vSectorFk
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(HOUR, 23, util.VN_CURDATE())
+ GROUP BY s.ticketFk
+ HAVING iptSector;
+
+ CALL productionControl(vWarehouseFk, 0);
+
+ SELECT 0,999999,0 INTO @sameTicket, @ticket, @litrosTicket;
+
+ SELECT @litrosTicket := IF(sub.ticketFk = @ticket, @litrosTicket + Litros, Litros) as LitrosTicket,
+ @sameTicket := IF(sub.ticketFk = @ticket, @sameTicket, IF(@sameTicket, 0 , 1)) as sameTicket,
+ sub.*,
+ @ticket := ticketFk AS lastTicket
+ FROM (
+ SELECT * FROM (
+ SELECT isa.saleFk,
+ isa.Modificado,
+ isa.ticketFk,
+ isa.isPicked,
+ isa.itemFk,
+ isa.quantity,
+ isa.concept,
+ i.itemPackingTypeFk,
+ isa.`size`,
+ isa.Estado,
+ isa.sectorProdPriority,
+ isa.available,
+ isa.sectorFk,
+ isa.matricula,
+ isa.parking,
+ isa.itemShelving,
+ isa.Agency,
+ isa.shipped,
+ isa.`grouping`,
+ isa.packing,
+ isa.`hour`,
+ isa.isPreviousPreparable,
+ isa.physicalVolume,
+ isa.warehouseFk ,
+ sum(isa.available) as totalAvailable,
+ IF (HOUR(isa.shipped),HOUR(isa.shipped), HOUR(isa.`hour`)) Hora,
+ IF (MINUTE(isa.shipped),MINUTE(isa.shipped), MINUTE(isa.`hour`)) Minuto,
+ i.subName,
+ CAST(isa.physicalVolume * 1000 AS DECIMAL(10,0)) as Litros
+ FROM itemShelvingAvailable isa
+ JOIN item i ON i.id = isa.itemFk
+ JOIN sector s ON s.id = isa.sectorFk AND s.warehouseFk = isa.warehouseFk
+ JOIN sectorType st ON st.id = s.typeFk
+ JOIN ticket t ON t.id = isa.ticketFk
+ LEFT JOIN tmp.whiteTicket wt ON wt.ticketFk = isa.ticketFk
+ LEFT JOIN tmp.sectorTypeTicket stt ON stt.ticketFk = isa.ticketFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = isa.saleFk
+ JOIN client c ON c.id = t.clientFk
+ JOIN tmp.productionBuffer pb ON pb.ticketFk = t.id
+ JOIN packagingConfig pc
+ WHERE IF(st.code = 'previousByPacking',
+ i.`size` > pc.previousPreparationMinimumSize
+ AND (MOD(TRUNCATE(isa.quantity,0), isa.packing)= 0 ),
+ TRUE)
+ AND sgd.saleFk IS NULL
+ AND isa.sectorFk = vSectorFk
+ AND isa.quantity > 0
+ AND pb.problem = ""
+ AND (i.itemPackingTypeFk <=> s.itemPackingTypeFk
+ OR ISNULL(s.itemPackingTypeFk)
+ OR wt.ticketFk
+ OR (stt.ticketFk AND ISNULL(i.itemPackingTypeFk)))
+ GROUP BY saleFk
+ HAVING isa.quantity <= totalAvailable
+ ) sub2
+ ORDER BY Hora, Minuto, ticketFk LIMIT 10000000000000000000
+ ) sub;
+ DROP TEMPORARY TABLE tmp.whiteTicket;
+ DROP TEMPORARY TABLE tmp.sectorTypeTicket;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/rangeDateInfo.sql b/db/routines/vn/procedures/rangeDateInfo.sql
new file mode 100644
index 000000000..502248686
--- /dev/null
+++ b/db/routines/vn/procedures/rangeDateInfo.sql
@@ -0,0 +1,37 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`rangeDateInfo`(vStarted DATE, vEnded DATE)
+BEGIN
+/**
+ * Crea una tabla temporal con las fechas
+ * desde una fecha inicial a una final
+ * @param vStarted fecha inicial
+ * @param vEnded fecha final
+ */
+ DECLARE vDated DATE DEFAULT vStarted;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate;
+ CREATE TEMPORARY TABLE tmp.rangeDate(
+ `dated` DATE,
+ `period` INT,
+ `month` INT,
+ `year` INT,
+ `day` INT,
+ `week` INT,
+ `yearMonth` INT
+ )
+ ENGINE = MEMORY;
+
+ WHILE vDated <= vEnded DO
+ INSERT INTO tmp.rangeDate
+ SET `dated` = vDated,
+ `period` = YEAR(vDated) * 100 + WEEK(vDated, 1),
+ `month` = MONTH(vDated),
+ `year` = YEAR(vDated),
+ `day` = DAY(vDated),
+ `week` = WEEK(vDated, 1),
+ `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated);
+
+ SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY);
+ END WHILE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/rate_getPrices.sql b/db/routines/vn/procedures/rate_getPrices.sql
new file mode 100644
index 000000000..c82ad918e
--- /dev/null
+++ b/db/routines/vn/procedures/rate_getPrices.sql
@@ -0,0 +1,45 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`rate_getPrices`(
+ vDated DATE,
+ vWarehouseFk INT
+)
+BEGIN
+/**
+ * Prepara una tabla con las tarifas aplicables
+ * en funcion de la fecha y el almacén.
+ *
+ * @param vDated Fecha para la cual calcula la tarifa
+ * @param vWarehouseFk Warehouse para el cual calcula la tarifa
+ * @return tmp.rate (rate0, rate1, rate2, rate3)
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tmp.rate
+ ENGINE = MEMORY
+ SELECT rate0,
+ rate1,
+ rate2,
+ rate3
+ FROM(
+ (SELECT 1 `order`,
+ rate0,
+ rate1,
+ rate2,
+ rate3
+ FROM rate
+ WHERE dated <= vDated
+ AND warehouseFk = vWarehouseFk
+ ORDER BY dated DESC
+ LIMIT 1
+ )
+ UNION
+ (SELECT 2,
+ rate0,
+ rate1,
+ rate2,
+ rate3
+ FROM rateConfig
+ )
+ ORDER BY `order` ASC
+ LIMIT 1
+ )sub;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/recipe_Cook.sql b/db/routines/vn/procedures/recipe_Cook.sql
new file mode 100644
index 000000000..9371ef820
--- /dev/null
+++ b/db/routines/vn/procedures/recipe_Cook.sql
@@ -0,0 +1,74 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`recipe_Cook`(vItemFk INT, vBunchesQuantity INT, vDate DATE)
+BEGIN
+
+ DECLARE vCalc INT;
+ DECLARE vWarehouseFk INT DEFAULT 1; -- Silla FV
+
+ SET @element := '';
+ SET @counter := 0;
+
+ CALL cache.available_refresh(vCalc, FALSE, vWarehouseFk, vDate);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.recipeCook;
+
+ CREATE TEMPORARY TABLE tmp.recipeCook
+ SELECT *,
+ @counter := IF(@element = element COLLATE utf8_general_ci , @counter + 1, 1) as counter,
+ @element := element COLLATE utf8_general_ci
+ FROM
+ (
+ SELECT i.id itemFk,
+ CONCAT(i.longName, ' (ref: ',i.id,')') longName,
+ i.size,
+ i.inkFk,
+ a.available,
+ r.element,
+ vBunchesQuantity * r.quantity as quantity,
+ r.itemFk as bunchItemFk,
+ IFNULL((i.inkFk = r.inkFk ) ,0)
+ + IFNULL((i.size = r.size) ,0)
+ + IFNULL((i.name LIKE CONCAT('%',r.name,'%')) ,0)
+ + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0)
+ + IFNULL((i.typeFk = r.typeFk),0) as matches,
+ i.typeFk,
+ rl.previousSelected
+ FROM vn.recipe r
+ JOIN vn.item i ON (IFNULL(i.name LIKE CONCAT('%',r.name,'%'), 0)
+ OR IFNULL(i.longName LIKE CONCAT('%',r.longName,'%'),0))
+ OR i.typeFk <=> r.typeFk
+ JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vCalc
+ LEFT JOIN (SELECT recipe_ItemFk, element as log_element, selected_ItemFk, count(*) as previousSelected
+ FROM vn.recipe_log
+ GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk
+ AND rl.log_element = r.element
+ AND rl.selected_ItemFk = i.id
+ WHERE r.itemFk = vItemFk
+ AND a.available > vBunchesQuantity * r.quantity
+ UNION ALL
+ SELECT 100 itemFk,
+ CONCAT('? ',r.element,' ',IFNULL(r.size,''),' ',IFNULL(r.inkFk,'')) as longName,
+ NULL,
+ NULL,
+ 0,
+ r.element,
+ vBunchesQuantity * r.quantity as quantity,
+ r.itemFk as bunchItemFk,
+ -1 as matches,
+ r.typeFk,
+ NULL
+ FROM vn.recipe r
+ WHERE r.itemFk = vItemFk
+ GROUP BY r.element
+ ) sub
+
+ ORDER BY element, matches DESC, previousSelected DESC;
+
+ SELECT *
+ FROM tmp.recipeCook
+ WHERE counter < 6
+ OR itemFk = 100
+ ;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/recipe_Plaster.sql b/db/routines/vn/procedures/recipe_Plaster.sql
new file mode 100644
index 000000000..18fdf55c8
--- /dev/null
+++ b/db/routines/vn/procedures/recipe_Plaster.sql
@@ -0,0 +1,35 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`recipe_Plaster`(vItemFk INT, vTicketFk INT, vQuantity INT)
+BEGIN
+
+ DECLARE vLastCost DECIMAL(10,2);
+ DECLARE vWarehouseFk INT;
+ DECLARE vShipped DATE;
+ DECLARE vEntryFk INT;
+ DECLARE vTravelFk INT;
+
+ CALL cache.last_buy_refresh(FALSE);
+
+ SELECT warehouseFk, shipped
+ INTO vWarehouseFk, vShipped
+ FROM vn.ticket
+ WHERE id = vTicketFk;
+
+ UPDATE vn.ticket t
+ JOIN vn.item i ON i.id = vItemFk
+ SET t.nickname = CONCAT(vQuantity,' ',i.longName)
+ WHERE t.id = vTicketFk;
+
+ SELECT b.buyingValue INTO vLastCost
+ FROM vn.buy b
+ JOIN cache.last_buy lb ON lb.buy_id = b.id
+ WHERE lb.item_id = vItemFk
+ ORDER BY (lb.warehouse_id = vWarehouseFk) DESC
+ LIMIT 1;
+
+ INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price)
+ SELECT vTicketFk, 98, - vQuantity, i.longName, vLastCost
+ FROM vn.item i
+ WHERE i.id = vItemFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/remittance_calc.sql b/db/routines/vn/procedures/remittance_calc.sql
new file mode 100644
index 000000000..ed0a18662
--- /dev/null
+++ b/db/routines/vn/procedures/remittance_calc.sql
@@ -0,0 +1,70 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`remittance_calc`(
+ vDated DATE
+)
+BEGIN
+/**
+* Calcula los datos de remesa, incluyendo el importe,
+* el vencimiento, y otros datos relevantes.
+*
+* @param vDated Fecha a calcular
+* @return tmp.remittance
+*/
+ CREATE OR REPLACE TEMPORARY TABLE tmp.remittance
+ SELECT CONCAT(s.nif, REPEAT('0', 12 - LENGTH(s.nif))) cif,
+ c.id clientFk,
+ c.name client,
+ c.fi,
+ sub.paymentDate,
+ 0 invoiceAmount,
+ CAST(sub.receipt AS DECIMAL(10,2)) receiptAmount,
+ 0 currentAmount,
+ sub.companyFk,
+ c.socialName,
+ CAST(sub.receipt AS DECIMAL(10,2)) totalAmount,
+ CAST(sub.receipt AS DECIMAL(10,2)) balance,
+ s.name company,
+ co.code companyCode,
+ c.accountingAccount,
+ c.iban,
+ c.hasSepaVnl,
+ c.hasCoreVnl,
+ c.hasLcr,
+ be.bic,
+ be.`name` entityName
+ FROM client c
+ JOIN (
+ SELECT risk.companyFk,
+ c.id,
+ SUM(risk.amount) receipt,
+ IF((c.dueDay + graceDays) MOD 30.001 <= DAY(vDated),
+ LAST_DAY(vDated - INTERVAL 1 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY,
+ LAST_DAY(vDated - INTERVAL 2 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY
+ ) paymentDate
+ FROM client c
+ JOIN payMethod pm ON pm.id = c.payMethodFk
+ JOIN (
+ SELECT cr.companyFk, cr.clientFk, cr.amount
+ FROM client c
+ JOIN clientRisk cr ON cr.clientFk = c.id
+ JOIN payMethod pm ON pm.id = c.payMethodFk
+ WHERE pm.code = 'bankDraft'
+ UNION ALL
+ SELECT io.companyFk, io.clientFk, - io.amount
+ FROM invoiceOut io
+ JOIN client c ON c.id = io.clientFk
+ JOIN payMethod pm ON pm.id = c.payMethodFk
+ WHERE io.dued > vDated
+ AND pm.code = 'bankDraft'
+ AND pm.outstandingDebt
+ AND io.amount > 0
+
+ ) risk ON risk.clientFk = c.id
+ GROUP BY risk.companyFk, c.id
+ HAVING receipt > 10
+ ) sub ON sub.id = c.id
+ JOIN supplier s ON s.id = sub.companyFk
+ JOIN company co ON co.id = sub.companyFk
+ LEFT JOIN bankEntity be ON be.id = c.bankEntityFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/reportLabelCollection_get.sql b/db/routines/vn/procedures/reportLabelCollection_get.sql
new file mode 100644
index 000000000..6ad5ae964
--- /dev/null
+++ b/db/routines/vn/procedures/reportLabelCollection_get.sql
@@ -0,0 +1,55 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`reportLabelCollection_get`(
+ vParam INT,
+ vLabelCount INT
+)
+BEGIN
+/**
+ * Obtains tag data from a ticket or collection.
+ *
+ * @param vParam Ticket/Collection from which data is to be taken.
+ * @param vLabelCount number of times the collection has been printed.
+ */
+ DECLARE vIsCollection BOOL;
+
+ SELECT IF(id, TRUE, FALSE) INTO vIsCollection
+ FROM vn.collection c
+ WHERE id = vParam;
+
+ SELECT c.itemPackingTypeFk,
+ CONCAT(tc.collectionFk, ' ', LEFT(cc.code, 4)) color,
+ CONCAT(tc.collectionFk, ' ', SUBSTRING('ABCDEFGH',tc.wagon, 1), '-', tc.level) levelV,
+ tc.ticketFk,
+ LEFT(COALESCE(et.description, zo.name, am.name),12) agencyDescription,
+ am.name,
+ t.clientFk,
+ CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5, 2)), 'm³') m3 ,
+ CAST(IF(ic.code = 'plant', CONCAT(MAX(i.size), ' cm'), COUNT(*)) AS CHAR) size,
+ w.code workerCode,
+ IF(vLabelCount IS NULL, tt.labelCount, vLabelCount) labelCount,
+ IF(HOUR(t.shipped), TIME(t.shipped), TIME(zo.hour)) agencyHour,
+ t.shipped,
+ COUNT(*) lineCount,
+ t.nickName
+ FROM ticket t
+ JOIN ticketCollection tc ON tc.ticketFk = t.id
+ JOIN collection c ON c.id = tc.collectionFk
+ LEFT JOIN collectionColors cc ON cc.shelve = tc.level
+ AND cc.wagon = tc.wagon
+ AND cc.trainFk = c.trainFk
+ JOIN sale s ON s.ticketFk = t.id
+ LEFT JOIN saleVolume sv ON sv.saleFk = s.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ JOIN worker w ON w.id = c.workerFk
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ LEFT JOIN ticketTrolley tt ON tt.ticket = t.id
+ LEFT JOIN zone zo ON t.zoneFk = zo.id
+ LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk
+ LEFT JOIN expeditionTruck et ON et.id = rm.expeditionTruckFk
+ WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam)
+ GROUP BY t.id
+ ORDER BY cc.code;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/report_print.sql b/db/routines/vn/procedures/report_print.sql
new file mode 100644
index 000000000..5d399dedf
--- /dev/null
+++ b/db/routines/vn/procedures/report_print.sql
@@ -0,0 +1,83 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`report_print`(
+ vReportName VARCHAR(100),
+ vPrinterFk INT,
+ vUserFk INT,
+ vParams JSON,
+ vPriorityName VARCHAR(100)
+ )
+BEGIN
+/**
+ * Inserts in the print queue the report to be printed and the necessary parameters for this
+ * one taking into account the paper size of both the printer and the report.
+ *
+ * @param vReportName the report to be printed.
+ * @param vPrinterFk the printer selected.
+ * @param vUserFk user id.
+ * @param vParams JSON with report parameters.
+ * @param vPriorityName the printing priority.
+ */
+ DECLARE vI INT DEFAULT 0;
+ DECLARE vKeys TEXT DEFAULT JSON_KEYS(vParams);
+ DECLARE vLength INT DEFAULT JSON_LENGTH(vKeys);
+ DECLARE vKey VARCHAR(255);
+ DECLARE vVal VARCHAR(255);
+ DECLARE vPrintQueueFk INT;
+ DECLARE vReportSize VARCHAR(255);
+ DECLARE vIsThePrinterReal INT;
+ DECLARE vPrinteSize VARCHAR(255);
+ DECLARE vPriorityFk INT;
+ DECLARE vReportFk INT;
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ SELECT id, paperSizeFk INTO vReportFk, vReportSize
+ FROM report
+ WHERE name = vReportName;
+
+ SELECT id, paperSizeFk INTO vIsThePrinterReal, vPrinteSize
+ FROM printer
+ WHERE id = vPrinterFk;
+
+ SELECT id INTO vPriorityFk
+ FROM queuePriority
+ WHERE code = vPriorityName;
+
+ IF vIsThePrinterReal IS NULL THEN
+ CALL util.throw('printerNotExists');
+ END IF;
+
+ IF vReportFk IS NULL THEN
+ CALL util.throw('reportNotExists');
+ END IF;
+
+ IF vReportSize <> vPrinteSize THEN
+ CALL util.throw('incorrectSize');
+ END IF;
+
+ START TRANSACTION;
+ INSERT INTO printQueue
+ SET printerFk = vPrinterFk,
+ priorityFk = vPriorityFk,
+ reportFk = vReportFk,
+ workerFk = vUserFk;
+
+ SET vPrintQueueFk = LAST_INSERT_ID();
+
+ WHILE vI < vLength DO
+ SET vKey = JSON_VALUE(vKeys, CONCAT('$[', vI ,']'));
+ SET vVal = JSON_VALUE(vParams, CONCAT('$.', vKey));
+
+ INSERT INTO printQueueArgs
+ SET printQueueFk = vPrintQueueFk,
+ name = vKey,
+ value = vVal;
+
+ SET vI = vI + 1;
+ END WHILE;
+ COMMIT;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/riskAllClients.sql b/db/routines/vn/procedures/riskAllClients.sql
new file mode 100644
index 000000000..66c0a0dd5
--- /dev/null
+++ b/db/routines/vn/procedures/riskAllClients.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`riskAllClients`(maxRiskDate DATE)
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
+ CREATE TEMPORARY TABLE tmp.client_list
+ (PRIMARY KEY (Id_Cliente))
+ ENGINE = MEMORY
+ SELECT id Id_Cliente, null grade FROM vn.client;
+
+ CALL vn2008.risk_vs_client_list(maxRiskDate);
+
+ SELECT
+ c.RazonSocial,
+ c.Id_Cliente,
+ c.Credito,
+ CAST(r.risk as DECIMAL (10,2)) risk,
+ CAST(c.Credito - r.risk as DECIMAL (10,2)) Diferencia,
+ c.Id_Pais
+ FROM
+ vn2008.Clientes c
+ JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente
+ JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente
+ GROUP BY c.Id_cliente;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.risk;
+ DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/routeGuessPriority.sql b/db/routines/vn/procedures/routeGuessPriority.sql
new file mode 100644
index 000000000..7208fcbcf
--- /dev/null
+++ b/db/routines/vn/procedures/routeGuessPriority.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`routeGuessPriority`(IN vRuta INT)
+BEGIN
+/* Usa los valores del ultimo año para adivinar el orden de los tickets en la ruta
+ * vRuta id ruta
+*/
+
+UPDATE ticket mt
+ JOIN (
+ SELECT tt.addressFk, ROUND(IFNULL(AVG(t.priority),0),0) AS priority
+ FROM ticket t
+ JOIN ticket tt ON tt.addressFk = t.addressFk
+ WHERE t.shipped > TIMESTAMPADD(YEAR,-1,util.VN_CURDATE())
+ AND tt.routeFk = vRuta
+ GROUP BY addressFk
+ ) sub ON sub.addressFk = mt.addressFk
+ SET mt.priority = sub.priority
+ WHERE mt.routeFk = vRuta;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/routeInfo.sql b/db/routines/vn/procedures/routeInfo.sql
new file mode 100644
index 000000000..1f25b1429
--- /dev/null
+++ b/db/routines/vn/procedures/routeInfo.sql
@@ -0,0 +1,33 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`routeInfo`(vRouteFk INT)
+BEGIN
+
+ DECLARE vPackages INT;
+ DECLARE vM3 INT;
+ DECLARE vKg INT;
+ DECLARE vMatricula varchar(50);
+
+ SELECT sum(packages) as bultos
+ INTO vPackages
+ FROM vn.ticket t
+ WHERE routeFk = vRouteFk;
+
+ SELECT SUM(sv.physicalVolume), SUM(sv.physicalWeight)
+ INTO vM3, vKg
+ FROM vn.saleVolume sv
+ WHERE sv.routeFk = vRouteFk;
+
+ SELECT v.numberPlate as matricula
+ INTO vMatricula
+ FROM vn.route r
+ JOIN vn.vehicle v ON r.vehicleFk = v.id
+ WHERE r.id = vRouteFk;
+
+ SELECT vRouteFk as Ruta,
+ vPackages as Bultos,
+ vM3 as m3,
+ vKg as Kg,
+ vMatricula as Matricula;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/routeMonitor_calculate.sql b/db/routines/vn/procedures/routeMonitor_calculate.sql
new file mode 100644
index 000000000..af7f5297e
--- /dev/null
+++ b/db/routines/vn/procedures/routeMonitor_calculate.sql
@@ -0,0 +1,114 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`routeMonitor_calculate`(
+ vDate DATE,
+ vDaysAgo INT
+)
+BEGIN
+ DECLARE vDateEnd DATETIME;
+ SET vDate = vDate - INTERVAL vDaysAgo DAY;
+ SET vDateEnd = util.dayend(vDate);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.routesMonitor
+ (INDEX (routeFk))
+ ENGINE = MEMORY
+ SELECT DISTINCT(t.routeFk) routeFk
+ FROM vn.ticket t
+ WHERE t.shipped BETWEEN vDate AND vDateEnd
+ AND t.routeFk IS NOT NULL;
+
+ INSERT IGNORE INTO routesMonitor(routeFk)
+ SELECT routeFk
+ FROM tmp.routesMonitor;
+
+ UPDATE routesMonitor rm
+ JOIN route r ON r.id = rm.routeFk
+ JOIN agencyMode a ON a.id = r.agencyModeFk
+ SET rm.`name` = a.name,
+ rm.ticketFree = 0,
+ rm.ticketProduction = 0,
+ rm.ticketPacked = 0,
+ rm.dated = r.created;
+
+ UPDATE routesMonitor rm
+ JOIN (
+ SELECT t.routeFk, COUNT(*) AS ticketFree
+ FROM vn.ticket t
+ JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
+ JOIN ticketLastState ts ON t.id = ts.ticketFk
+ JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk
+ JOIN state s ON s.id = tt.stateFk
+ JOIN vn.alertLevel al ON al.id = s.alertLevel
+ AND al.code = "FREE"
+ GROUP BY t.routeFk
+ ) sub ON sub.routeFk = rm.routeFk
+ SET rm.ticketFree = sub.ticketFree;
+
+ UPDATE routesMonitor rm
+ JOIN(
+ SELECT t.routeFk, COUNT(*) AS ticketPacked
+ FROM vn.ticket t
+ JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
+ JOIN ticketLastState ts ON t.id = ts.ticketFk
+ JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk
+ JOIN state s ON s.id = tt.stateFk
+ JOIN vn.alertLevel al ON al.id = s.alertLevel
+ AND al.code = "PACKED"
+ GROUP BY t.routeFk
+ ) sub ON sub.routeFk = rm.routeFk
+ SET rm.ticketPacked = sub.ticketPacked;
+
+ UPDATE routesMonitor rm
+ JOIN(
+ SELECT t.routeFk, COUNT(*) AS ticketProduction
+ FROM vn.ticket t
+ JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
+ JOIN ticketLastState ts ON t.id = ts.ticketFk
+ JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk
+ JOIN state s ON s.id = tt.stateFk
+ JOIN vn.alertLevel al ON al.id = s.alertLevel
+ AND al.code = "DELIVERED"
+ GROUP BY t.routeFk
+ ) sub ON sub.routeFk = rm.routeFk
+ SET rm.ticketProduction = sub.ticketProduction;
+
+ UPDATE routesMonitor rm
+ JOIN (
+ SELECT t.routeFk, COUNT(*) packages
+ FROM vn.ticket t
+ JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
+ JOIN expedition e ON e.ticketFk = t.id
+ GROUP BY t.routeFk
+ ) sub ON sub.routeFk = rm.routeFk
+ SET rm.packages = sub.packages;
+
+ UPDATE routesMonitor rm
+ JOIN( SELECT t.routeFk, SUM(sv.volume) m3
+ FROM vn.ticket t
+ JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
+ JOIN vn.saleVolume sv ON sv.ticketFk = t.id
+ GROUP BY t.routeFk
+ ) sub ON sub.routeFk = rm.routeFk
+ SET rm.m3 = sub.m3;
+
+ UPDATE routesMonitor rm
+ JOIN (
+ SELECT t.routeFk,
+ SUM(IFNULL(pk.volume,
+ pk.width * pk.height * pk.`depth`
+ )
+ ) / 1000000 m3boxes
+ FROM vn.ticket t
+ JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
+ JOIN vn.expedition e ON e.ticketFk = t.id
+ JOIN vn.packaging pk ON pk.id = e.packagingFk
+ GROUP BY t.routeFk
+ ) sub ON sub.routeFk = rm.routeFk
+ SET rm.m3boxes = sub.m3boxes;
+
+ UPDATE routesMonitor rm
+ JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ SET rm.etd = et.eta;
+
+ DROP TEMPORARY TABLE tmp.routesMonitor;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/routeSetOk.sql b/db/routines/vn/procedures/routeSetOk.sql
new file mode 100644
index 000000000..86b32fe7b
--- /dev/null
+++ b/db/routines/vn/procedures/routeSetOk.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`routeSetOk`(
+ vRouteFk INT)
+BEGIN
+
+ UPDATE vn.route r
+ SET r.isOk = 1
+ WHERE r.id = vRouteFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/routeUpdateM3.sql b/db/routines/vn/procedures/routeUpdateM3.sql
new file mode 100644
index 000000000..7dbf5a194
--- /dev/null
+++ b/db/routines/vn/procedures/routeUpdateM3.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`routeUpdateM3`(vRoute INT)
+BEGIN
+/**
+ * @deprecated Use vn.route_updateM3()
+ */
+ call route_updateM3(vRoute);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/route_calcCommission.sql b/db/routines/vn/procedures/route_calcCommission.sql
new file mode 100644
index 000000000..63f702bee
--- /dev/null
+++ b/db/routines/vn/procedures/route_calcCommission.sql
@@ -0,0 +1,94 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_calcCommission`(
+ vSelf INT
+)
+BEGIN
+/**
+ * Calcula las comisión para una ruta y guarda los valores
+ * en la tabla vn.routeCommission.
+ *
+ * @param vSelf Id de ruta
+ */
+ DECLARE vIsUpdatable, vIsFreelance BOOL DEFAULT 0;
+ DECLARE vAgencyModePricePercentage DOUBLE;
+
+ SELECT r.created >= rc.cutoffDated INTO vIsUpdatable
+ FROM route r
+ JOIN routeConfig rc
+ WHERE r.id = vSelf;
+
+ IF vIsUpdatable THEN
+ DELETE FROM routeCommission
+ WHERE routeFk = vSelf;
+
+ SELECT w.isFreelance INTO vIsFreelance
+ FROM route r
+ JOIN worker w ON w.id = r.workerFk
+ WHERE r.id = vSelf;
+
+ SELECT ampp.percentage INTO vAgencyModePricePercentage
+ FROM route r
+ JOIN agencyMode am ON am.id = r.agencyModeFk
+ JOIN agencyModePricePercentage ampp ON ampp.agencyModeFk = am.id
+ WHERE r.id = vSelf;
+
+ -- Falta calcular el precio, a la espera de saber el/los campo/s exacto/s al que aplicarlo/s
+ IF vIsFreelance THEN
+ INSERT INTO routeCommission (
+ routeFk,
+ workCenterFk,
+ freelanceYearlyM3,
+ cat4m3,
+ cat5m3
+ )
+ SELECT vSelf,
+ r.commissionWorkCenterFk,
+ IF(vAgencyModePricePercentage IS NOT NULL,
+ vAgencyModePricePercentage / 100,
+ rc.freelanceM3
+ ) *
+ IF(IFNULL(r.m3, 0) >= rc.freelanceMinM3,
+ IFNULL(r.m3, 0),
+ 0
+ ),
+ rc.distributionCat4M3 * IFNULL(r.m3, 0),
+ rc.distributionCat5M3 * IFNULL(r.m3, 0)
+ FROM route r
+ JOIN vehicle v ON v.id = r.vehicleFk
+ JOIN routeConfig rc
+ WHERE r.id = vSelf
+ AND r.workerFk
+ AND r.commissionWorkCenterFk;
+ ELSE
+ INSERT INTO routeCommission (
+ routeFk,
+ workCenterFk,
+ km,
+ m3,
+ yearlyKm,
+ yearlyM3,
+ cat4m3,
+ cat5m3
+ )
+ SELECT vSelf,
+ r.commissionWorkCenterFk,
+ (r.kmEnd - r.kmStart) *
+ IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight),
+ IFNULL(r.m3, 0) *
+ IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4),
+ (r.kmEnd - r.kmStart) * rc.kmYearly,
+ IFNULL(r.m3, 0) * rc.m3Yearly,
+ rc.distributionCat4M3 * IFNULL(r.m3, 0),
+ rc.distributionCat5M3 * IFNULL(r.m3, 0)
+ FROM route r
+ JOIN vehicle v ON v.id = r.vehicleFk
+ JOIN routeConfig rc
+ WHERE r.id = vSelf
+ AND r.kmStart
+ AND r.kmEnd
+ AND r.workerFk
+ AND r.commissionWorkCenterFk;
+ END IF;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/route_doRecalc.sql b/db/routines/vn/procedures/route_doRecalc.sql
new file mode 100644
index 000000000..365796f7e
--- /dev/null
+++ b/db/routines/vn/procedures/route_doRecalc.sql
@@ -0,0 +1,48 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_doRecalc`()
+proc: BEGIN
+/**
+ * Recalculates modified route.
+ */
+
+ DECLARE vDone BOOL;
+ DECLARE vRouteFk INT;
+
+ DECLARE cCur CURSOR FOR
+ SELECT routeFk FROM routeRecalc;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ DO RELEASE_LOCK('vn.route_doRecalc');
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ IF !GET_LOCK('vn.route_doRecalc', 0) THEN
+ LEAVE proc;
+ END IF;
+
+ OPEN cCur;
+
+ myLoop: LOOP
+ SET vDone = FALSE;
+ FETCH cCur INTO vRouteFk;
+
+ IF vDone THEN
+ LEAVE myLoop;
+ END IF;
+
+ START TRANSACTION;
+ CALL route_updateM3(vRouteFk);
+ COMMIT;
+
+ DELETE FROM routeRecalc WHERE routeFk = vRouteFk;
+ END LOOP;
+
+ CLOSE cCur;
+ DO RELEASE_LOCK('vn.route_doRecalc');
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/route_getTickets.sql b/db/routines/vn/procedures/route_getTickets.sql
new file mode 100644
index 000000000..55b08208f
--- /dev/null
+++ b/db/routines/vn/procedures/route_getTickets.sql
@@ -0,0 +1,72 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_getTickets`(vRouteFk INT)
+BEGIN
+/**
+ * Pasado un RouteFk devuelve la información
+ * de sus tickets.
+ *
+ * @param vRouteFk
+ * @select Información de los tickets
+ */
+SELECT t.id Id,
+ t.clientFk Client,
+ a.id Address,
+ a.nickname ClientName,
+ t.packages Packages,
+ a.street AddressName,
+ a.postalCode PostalCode,
+ a.city City,
+ sub3.itemPackingTypeFk PackingType,
+ c.phone ClientPhone,
+ c.mobile ClientMobile,
+ a.phone AddressPhone,
+ a.mobile AddressMobile,
+ d.longitude Longitude,
+ d.latitude Latitude,
+ wm.mediaValue SalePersonPhone,
+ tob.description Note,
+ t.isSigned Signed,
+ t.priority,
+ t.cmrFk
+ FROM ticket t
+ JOIN client c ON t.clientFk = c.id
+ JOIN address a ON t.addressFk = a.id
+ LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk
+ LEFT JOIN (
+ SELECT t.addressFk, MAX(d.ticketFk) lastTicketFk
+ FROM ticket t
+ JOIN delivery d ON t.id = d.ticketFk
+ JOIN ticket ti ON ti.routeFk = vRouteFk
+ AND ti.id = t.id
+ AND ti.clientFk = t.clientFk
+ GROUP BY addressFk
+ )sub ON sub.addressFk = a.id
+ LEFT JOIN delivery d ON d.ticketFk = sub.lastTicketFk
+ LEFT JOIN(
+ SELECT t.id ticketFk, tob.description
+ FROM ticketObservation tob
+ JOIN ticket t ON tob.ticketFk = t.id
+ JOIN observationType ot ON ot.id = tob.observationTypeFk
+ WHERE t.routeFk = vRouteFk
+ AND ot.code = 'delivery'
+ )tob ON tob.ticketFk = t.id
+ LEFT JOIN(
+ SELECT sub2.ticketFk,
+ CONCAT('(',
+ GROUP_CONCAT(DISTINCT sub2.itemPackingTypeFk
+ ORDER BY sub2.items DESC SEPARATOR ','),
+ ') ') itemPackingTypeFk
+ FROM (
+ SELECT s.ticketFk, i.itemPackingTypeFk, COUNT(*) items
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ WHERE t.routeFk = vRouteFk
+ GROUP BY t.id, i.itemPackingTypeFk
+ )sub2
+ GROUP BY sub2.ticketFk
+ )sub3 ON sub3.ticketFk = t.id
+ WHERE t.routeFk = vRouteFk
+ ORDER BY priority, Id;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/route_updateM3.sql b/db/routines/vn/procedures/route_updateM3.sql
new file mode 100644
index 000000000..92d26b753
--- /dev/null
+++ b/db/routines/vn/procedures/route_updateM3.sql
@@ -0,0 +1,14 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_updateM3`(vRoute INT)
+BEGIN
+
+ UPDATE vn.route r
+ LEFT JOIN (
+ SELECT routeFk, SUM(volume) AS m3
+ FROM saleVolume
+ WHERE routeFk = vRoute
+ ) v ON v.routeFk = r.id
+ SET r.m3 = IFNULL(v.m3,0)
+ WHERE r.id =vRoute;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleBuy_Add.sql b/db/routines/vn/procedures/saleBuy_Add.sql
new file mode 100644
index 000000000..2f689ad2a
--- /dev/null
+++ b/db/routines/vn/procedures/saleBuy_Add.sql
@@ -0,0 +1,26 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleBuy_Add`(vSaleFk INT, vBuyFk INT)
+BEGIN
+
+ /* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad
+ *
+ * @param vSaleFk clave primaria de vn.sale
+ * @param vBuyFk clave primaria de vn.buy
+ */
+ /*IF (SELECT COUNT(*)
+ FROM vn.sale s
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ WHERE s.id = vSaleFk
+ AND ic.code = 'fruit') THEN */
+
+ IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN
+
+ INSERT INTO vn.saleBuy (saleFk, buyFk)
+ VALUES(vSaleFk, vBuyFk);
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleGroup_add.sql b/db/routines/vn/procedures/saleGroup_add.sql
new file mode 100644
index 000000000..63e3bdedd
--- /dev/null
+++ b/db/routines/vn/procedures/saleGroup_add.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleGroup_add`(vSectorFk INT,vTicketFk INT)
+BEGIN
+/**
+ * Añade un nuevo registro a la tabla y devuelve su id.
+ *
+ * @param vSectorFk Identificador de vn.sector
+ */
+ INSERT INTO vn.saleGroup
+ SET `userFk` = account.myUser_getId(),
+ `sectorFk` = vSectorFk,
+ `ticketFk` = vTicketFk;
+
+ SELECT LAST_INSERT_ID();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleGroup_setParking.sql b/db/routines/vn/procedures/saleGroup_setParking.sql
new file mode 100644
index 000000000..4872f74c6
--- /dev/null
+++ b/db/routines/vn/procedures/saleGroup_setParking.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleGroup_setParking`(IN `vSaleGroupFk` VARCHAR(8), IN `vParkingFk` INT)
+proc: BEGIN
+/**
+ * Aparca una preparación previa en un parking
+ *
+ * @param vSaleGroupFk id de la preparación previa
+ * @param vParkingFk id del parking
+ */
+ UPDATE vn.saleGroup sg
+ SET sg.parkingFk = vParkingFk
+ WHERE sg.id = vSaleGroupFk
+ AND sg.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
+
+ CALL vn.ticket_setNextState(vn.ticket_get(vSaleGroupFk));
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleMistake_Add.sql b/db/routines/vn/procedures/saleMistake_Add.sql
new file mode 100644
index 000000000..cc174993e
--- /dev/null
+++ b/db/routines/vn/procedures/saleMistake_Add.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleMistake_Add`(vSaleFk INT, vUserFk INT, vTypeFk INT)
+BEGIN
+
+ INSERT INTO vn.saleMistake(saleFk, userFk, typeFk)
+ VALUES(vSaleFk, vUserFk, vTypeFk);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/salePreparingList.sql b/db/routines/vn/procedures/salePreparingList.sql
new file mode 100644
index 000000000..ae3a267f3
--- /dev/null
+++ b/db/routines/vn/procedures/salePreparingList.sql
@@ -0,0 +1,46 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`salePreparingList`(IN vTicketFk BIGINT)
+BEGIN
+/**
+ * Devuelve un listado con las lineas de vn.sale y los distintos estados de prepacion
+ *
+ * @param vTicketFk Identificador de vn.ticket
+ */
+ CALL cache.last_buy_refresh(FALSE);
+
+ SELECT t.clientFk,
+ t.shipped,
+ a.nickname,
+ s.ticketFk,
+ s.itemFk,
+ s.quantity,
+ s.concept,
+ s.reserved,
+ s.id saleFk,
+ i.size,
+ i.inkFk,
+ i.stems,
+ i.image,
+ i.subName,
+ b.`grouping`,
+ IF(stPrevious.saleFk,TRUE,FALSE) as isPreviousSelected,
+ stPrevious.isChecked as isPrevious,
+ stPrepared.isChecked as isPrepared,
+ stControled.isChecked as isControled,
+ ib.code as barcode,
+ (MAX(sgd.id) IS NOT NULL) AS hasSaleGroupDetail
+ FROM vn.ticket t
+ JOIN vn.address a ON a.id = t.addressFk
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.item i ON i.id = s.itemFk
+ LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = t.warehouseFk
+ LEFT JOIN vn.buy b ON b.id = lb.buy_id
+ LEFT JOIN vn.saleTracking stPrevious ON stPrevious.saleFk = s.id AND stPrevious.stateFk = 26
+ LEFT JOIN vn.saleTracking stPrepared ON stPrepared.saleFk = s.id AND stPrepared.stateFk = 14
+ LEFT JOIN vn.saleTracking stControled ON stControled.saleFk = s.id AND stControled.stateFk = 8
+ LEFT JOIN vn.itemBarcode ib ON ib.itemFk = i.id
+ LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
+ WHERE t.id = vTicketFk
+ GROUP BY s.id;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleSplit.sql b/db/routines/vn/procedures/saleSplit.sql
new file mode 100644
index 000000000..dab78d811
--- /dev/null
+++ b/db/routines/vn/procedures/saleSplit.sql
@@ -0,0 +1,43 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleSplit`(vSaleFk INT, vQuantity INT)
+BEGIN
+
+
+ DECLARE vNewSaleFk INT;
+
+ INSERT INTO vn.sale(itemFk,
+ concept,
+ price,
+ discount,
+ quantity,
+ ticketFk,
+ isPriceFixed)
+ SELECT s.itemFk,
+ i.longName,
+ s.price,
+ s.discount,
+ vQuantity,
+ s.ticketFk,
+ s.isPriceFixed
+ FROM vn.sale s
+ JOIN vn.item i ON i.id = s.itemFk
+ WHERE s.id = vSaleFk;
+
+ UPDATE vn.sale s
+ JOIN vn.item i ON i.id = s.itemFk
+ SET s.quantity = s.quantity - vQuantity, s.concept = i.longName
+ WHERE s.id = vSaleFk;
+
+ SELECT LAST_INSERT_ID() INTO vNewSaleFk;
+
+ INSERT INTO vn.saleComponent( saleFk,
+ componentFk,
+ value)
+ SELECT vNewSaleFk,
+ componentFk,
+ value
+ FROM vn.saleComponent
+ WHERE saleFk = vSaleFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleTracking_add.sql b/db/routines/vn/procedures/saleTracking_add.sql
new file mode 100644
index 000000000..dc347b0e3
--- /dev/null
+++ b/db/routines/vn/procedures/saleTracking_add.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleTracking_add`(vSaleGroupFk INT)
+BEGIN
+/** Inserta en vn.saleTracking las lineas de una previa
+ *
+ * @param vSaleGroupFk Identificador de vn.saleGroup
+ */
+ REPLACE vn.saleTracking(
+ saleFk,
+ isChecked,
+ workerFk,
+ stateFk
+ )
+ SELECT sgd.saleFk ,
+ TRUE,
+ account.myUser_getId(),
+ s.id
+ FROM vn.saleGroupDetail sgd
+ JOIN vn.state s ON s.code = 'ON_PREPARATION'
+ WHERE sgd.saleGroupFk = vSaleGroupFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleTracking_addPreparedSaleGroup.sql b/db/routines/vn/procedures/saleTracking_addPreparedSaleGroup.sql
new file mode 100644
index 000000000..b9475433c
--- /dev/null
+++ b/db/routines/vn/procedures/saleTracking_addPreparedSaleGroup.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleTracking_addPreparedSaleGroup`(vSaleGroupFk INT)
+BEGIN
+/**
+ * Inserta lineas de vn.saleTracking para un saleGroup (previa) que escanea un sacador
+ *
+ * @param vSaleGroupFk Identificador de vn.saleGroup
+ */
+ REPLACE vn.saleTracking(saleFk, isChecked, workerFk, stateFk)
+ SELECT sgd.saleFk, TRUE, account.myUser_getId(), s.id
+ FROM vn.saleGroupDetail sgd
+ JOIN vn.state s ON s.code = 'PREPARED'
+ WHERE sgd.saleGroupFk = vSaleGroupFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleTracking_addPrevOK.sql b/db/routines/vn/procedures/saleTracking_addPrevOK.sql
new file mode 100644
index 000000000..84cea965f
--- /dev/null
+++ b/db/routines/vn/procedures/saleTracking_addPrevOK.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleTracking_addPrevOK`(vSectorCollectionFk INT)
+BEGIN
+/**
+ * Inserta los registros de la colección de sector con el estado PREVIA OK
+ *
+ * @param vSectorCollectionFk Identificador de vn.sectorCollection
+ */
+ REPLACE vn.saleTracking(
+ saleFk,
+ isChecked,
+ workerFk,
+ stateFk
+ )
+ SELECT sgd.saleFk,
+ TRUE,
+ sc.userFk,
+ s.id
+ FROM vn.sectorCollection sc
+ JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
+ JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk
+ JOIN vn.state s ON s.code = 'OK PREVIOUS'
+ WHERE sc.id = vSectorCollectionFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleTracking_del.sql b/db/routines/vn/procedures/saleTracking_del.sql
new file mode 100644
index 000000000..263bd68a1
--- /dev/null
+++ b/db/routines/vn/procedures/saleTracking_del.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleTracking_del`(vSaleFk INT, vState VARCHAR(50))
+BEGIN
+
+ DELETE FROM itemShelvingSale
+ WHERE saleFk = vSaleFk;
+
+ DELETE st.*
+ FROM vn.saleTracking st
+ JOIN vn.state s ON s.id = st.stateFk
+ WHERE st.saleFk = vSaleFk
+ AND s.code = vState COLLATE utf8_unicode_ci;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleTracking_new.sql b/db/routines/vn/procedures/saleTracking_new.sql
new file mode 100644
index 000000000..5982f8df0
--- /dev/null
+++ b/db/routines/vn/procedures/saleTracking_new.sql
@@ -0,0 +1,38 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleTracking_new`(
+ vSaleFK INT,
+ vIsChecked BOOLEAN,
+ vOriginalQuantity INT,
+ vWorkerFk INT,
+ vAction VARCHAR(50),
+ vState VARCHAR(50),
+ vIsScanned BOOLEAN)
+BEGIN
+/**
+ * Modifica registro de saleTracking
+ *
+ * @param vSaleFK Identificador del registro a modificar
+ * @param vIsChecked Indica si la línea ha sido pulsada
+ * @param vOriginalQuantity Cantidad original
+ * @param vWorkerFk Identificador del trabajador
+ * @param vAction Identificador de la acción realizada
+ * @param vState Identificador del estado a modificar
+ * @param vIsScanned Identificador si se ha escaneado automáticamente o manual
+ */
+
+ REPLACE vn.saleTracking(saleFk,
+ isChecked,
+ originalQuantity,
+ workerFk,
+ stateFk,
+ isScanned)
+ SELECT vSaleFK,
+ vIsChecked,
+ vOriginalQuantity,
+ IFNULL(vWorkerFk, vn.getUser()),
+ s.id,
+ vIsScanned
+ FROM vn.state s
+ WHERE s.code = vState COLLATE utf8_unicode_ci;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/saleTracking_updateIsChecked.sql b/db/routines/vn/procedures/saleTracking_updateIsChecked.sql
new file mode 100644
index 000000000..57d8df701
--- /dev/null
+++ b/db/routines/vn/procedures/saleTracking_updateIsChecked.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleTracking_updateIsChecked`(vSaleFK INT, vIsChecked BOOL, vIsScanned BOOL)
+BEGIN
+
+ /**
+ * Actualiza el estado del campo vn.saleTracking.isChecked y elimina las lineas de vn.itemShelving
+ * si procede, en el caso de las preparaciones previas, por usuario
+ *
+ * @param vSaleFk Identificador de vn.sale
+ * @param vIsChecked Estado del registro
+ */
+
+ UPDATE vn.saleTracking st
+ JOIN vn.state s ON s.id = st.stateFk AND s.code = 'PREVIOUS_PREPARATION'
+ SET st.isChecked = vIsChecked,
+ st.isScanned = vIsScanned
+ WHERE st.saleFk = vSaleFK
+ AND st.workerFk = account.myUser_getId();
+
+ IF vIsChecked = FALSE THEN
+
+ DELETE FROM vn.itemShelvingSale
+ WHERE saleFk = vSaleFK;
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sale_PriceFix.sql b/db/routines/vn/procedures/sale_PriceFix.sql
new file mode 100644
index 000000000..8ffa77070
--- /dev/null
+++ b/db/routines/vn/procedures/sale_PriceFix.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_PriceFix`(vTicketFk INT)
+BEGIN
+
+ DELETE sc.*
+ FROM vn.saleComponent sc
+ JOIN vn.sale s ON s.id = sc.saleFk
+ JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk
+ WHERE s.ticketFk = vTicketFk
+ AND ct.`type` = 'otros';
+
+ UPDATE vn.sale s
+ JOIN (
+ SELECT sc.saleFk, sum(sc.value ) price
+ FROM vn.saleComponent sc
+ JOIN vn.sale s ON s.id = sc.saleFk
+ WHERE s.ticketFk = vTicketFk
+ GROUP BY sc.saleFk) sub ON sub.saleFk = s.id
+ SET s.price = sub.price;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sale_boxPickingPrint.sql b/db/routines/vn/procedures/sale_boxPickingPrint.sql
new file mode 100644
index 000000000..dbb3b6c14
--- /dev/null
+++ b/db/routines/vn/procedures/sale_boxPickingPrint.sql
@@ -0,0 +1,286 @@
+DELIMITER $$
+$$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE vn.sale_boxPickingPrint(
+ IN vPrinterFk INT,
+ IN vSaleFk INT,
+ IN vPacking INT,
+ IN vSectorFk INT,
+ IN vUserFk INT,
+ IN vPackagingFk VARCHAR(10),
+ IN vPackingSiteFk INT)
+BEGIN
+/** Splits a line of sale to a different ticket and prints the transport sticker
+ */
+ DECLARE vAgencyModeFk INT;
+ DECLARE vConcept VARCHAR(30);
+ DECLARE vExpeditionFk INT;
+ DECLARE vItemFk INT;
+ DECLARE vItemShelvingFk INT;
+ DECLARE vItemShelvingSaleFk INT;
+ DECLARE vItemShelvingSaleFk_old INT;
+ DECLARE vLastExpeditionTimeStamp DATETIME;
+ DECLARE vMaxPhoneLength INT DEFAULT 11;
+ DECLARE vMaxStreetLength INT DEFAULT 36;
+ DECLARE vNewSaleFk INT;
+ DECLARE vNewTicketFk INT;
+ DECLARE vParkingCode VARCHAR(10);
+ DECLARE vQuantity INT;
+ DECLARE vRemainder INT DEFAULT 0;
+ DECLARE vRemainderSaleFk INT;
+ DECLARE vShelving VARCHAR(10);
+ DECLARE vTicketFk INT;
+
+ SELECT s.quantity,
+ s.quantity MOD vPacking,
+ s.ticketFk,
+ s.itemFk,
+ s.concept
+ INTO vQuantity,
+ vRemainder,
+ vTicketFk,
+ vItemFk,
+ vConcept
+ FROM sale s
+ WHERE s.id = vSaleFk;
+
+ IF vRemainder THEN
+ UPDATE sale SET quantity = quantity - vRemainder WHERE id = vSaleFk;
+
+ INSERT INTO sale(ticketFk, itemFk, quantity, price, discount, concept)
+ SELECT ticketFk, itemFk, vRemainder, price, discount, concept
+ FROM sale
+ WHERE id = vSaleFk;
+
+ SET vRemainderSaleFk = LAST_INSERT_ID();
+
+ INSERT INTO saleComponent(saleFk, componentFk, value)
+ SELECT vRemainderSaleFk, componentFk, value
+ FROM saleComponent
+ WHERE saleFk = vSaleFk;
+ END IF;
+
+w1: WHILE vQuantity >= vPacking DO
+
+ SET vQuantity = vQuantity - vPacking;
+
+ SET vItemShelvingFk = NULL;
+
+ SELECT sub.id
+ INTO vItemShelvingFk
+ FROM productionConfig pc
+ JOIN (
+ SELECT ish.id,
+ ish.visible - IFNULL(SUM(iss.quantity),0) available,
+ p.pickingOrder,
+ ish.created
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ LEFT JOIN itemShelvingSale iss
+ ON iss.itemShelvingFk = ish.id
+ AND iss.created >= CURDATE()
+ AND iss.isPicked = FALSE
+ WHERE ish.itemFk = vItemFk
+ AND p.sectorFk = vSectorFk
+ GROUP BY ish.id
+ HAVING available >= vPacking) sub
+ ORDER BY IF(pc.orderMode = 'Location',sub.pickingOrder, sub.created)
+ LIMIT 1;
+
+ IF vItemShelvingFk THEN
+ INSERT INTO itemShelvingSale
+ SET itemShelvingFk = vItemShelvingFk,
+ saleFk = vSaleFk,
+ quantity = vPacking,
+ userFk = vUserFk,
+ isPicked = TRUE;
+
+ SET vItemShelvingSaleFk = LAST_INSERT_ID();
+
+ UPDATE sale SET isPicked = FALSE WHERE id = vSaleFk;
+ ELSE
+ LEAVE w1;
+ END IF;
+
+ SET vNewTicketFk = NULL;
+
+ SELECT MAX(t.id) INTO vNewTicketFk
+ FROM ticket t
+ JOIN ticketLastState tls ON tls.ticketFk = t.id
+ JOIN (SELECT addressFk, clientFk, date(shipped) shipped, warehouseFk
+ FROM ticket
+ WHERE id = vTicketFk) tt
+ ON tt.addressFk = t.addressFk
+ AND tt.clientFk = t.clientFk
+ AND t.shipped BETWEEN tt.shipped AND util.dayend(tt.shipped)
+ AND t.warehouseFk = tt.warehouseFk
+ WHERE tls.name = 'Encajado' ;
+
+ IF ISNULL(vNewTicketFk) THEN
+ INSERT INTO ticket( clientFk,
+ shipped,
+ addressFk,
+ agencyModeFk,
+ nickname,
+ warehouseFk,
+ companyFk,
+ landed,
+ zoneFk,
+ zonePrice,
+ zoneBonus,
+ routeFk,
+ priority,
+ hasPriority,
+ clonedFrom)
+ SELECT clientFk,
+ shipped,
+ addressFk,
+ agencyModeFk,
+ nickname,
+ warehouseFk,
+ companyFk,
+ landed,
+ zoneFk,
+ zonePrice,
+ zoneBonus,
+ routeFk,
+ priority,
+ hasPriority,
+ id
+ FROM ticket
+ WHERE id = vTicketFk;
+
+ SET vNewTicketFk = LAST_INSERT_ID();
+
+ INSERT INTO ticketTracking(ticketFk, stateFk, userFk)
+ SELECT vNewTicketFk, id, vUserFk
+ FROM state
+ WHERE code = 'PACKED';
+ END IF;
+
+ UPDATE sale SET quantity = quantity - vPacking WHERE id = vSaleFk;
+
+ UPDATE itemShelving SET visible = visible - vPacking WHERE id = vItemShelvingFk;
+
+ SET vNewSaleFk = NULL;
+
+ SELECT MAX(id) INTO vNewSaleFk
+ FROM sale
+ WHERE ticketFk = vNewTicketFk
+ AND itemFk = vItemFk;
+
+ IF vNewSaleFk THEN
+ UPDATE sale
+ SET quantity = quantity + vPacking
+ WHERE id = vNewSaleFk;
+
+ SET vItemShelvingSaleFk_old = NULL;
+
+ SELECT MAX(id) INTO vItemShelvingSaleFk_old
+ FROM itemShelvingSale
+ WHERE itemShelvingFk = vItemShelvingFk
+ AND saleFk = vNewSaleFk;
+
+ IF vItemShelvingSaleFk_old THEN
+ UPDATE itemShelvingSale
+ SET quantity = quantity + vPacking
+ WHERE id = vItemShelvingSaleFk_old;
+
+ DELETE FROM itemShelvingSale
+ WHERE id = vItemShelvingSaleFk;
+
+ SET vItemShelvingSaleFk = vItemShelvingSaleFk_old;
+ ELSE
+ UPDATE itemShelvingSale
+ SET saleFk = vNewSaleFk
+ WHERE id = vItemShelvingSaleFk;
+ END IF;
+ ELSE
+ INSERT INTO sale(ticketFk, itemFk, concept, quantity, discount, price)
+ SELECT vNewTicketFk, itemFk, concept, vPacking, discount, price
+ FROM sale
+ WHERE id = vSaleFk;
+
+ SET vNewSaleFk = LAST_INSERT_ID();
+
+ INSERT INTO saleComponent(saleFk, componentFk, value, isGreuge)
+ SELECT vNewSaleFk, componentFk, value, isGreuge
+ FROM saleComponent
+ WHERE saleFk = vSaleFk;
+
+ UPDATE itemShelvingSale
+ SET saleFk = vNewSaleFk
+ WHERE id = vItemShelvingSaleFk;
+
+ END IF;
+
+ INSERT IGNORE INTO saleTracking(saleFk, isChecked, workerFk, stateFk)
+ SELECT vNewSaleFk, TRUE, vUserFk, id
+ FROM state
+ WHERE code = 'PREPARED';
+
+ SELECT agencyModeFk INTO vAgencyModeFk
+ FROM ticket
+ WHERE id = vNewTicketFk;
+
+ INSERT INTO expedition(
+ agencyModeFk,
+ ticketFk,
+ freightItemFk,
+ workerFk,
+ packagingFk,
+ itemPackingTypeFk,
+ hostFk,
+ packingSiteFk,
+ monitorId,
+ started,
+ ended
+ )
+ SELECT vAgencyModeFk,
+ vNewTicketFk,
+ pc.defaultFreightItemFk,
+ vUserFk,
+ vPackagingFk,
+ ps.code,
+ h.code,
+ vPackingSiteFk,
+ ps.monitorId,
+ IFNULL(vLastExpeditionTimeStamp, NOW()),
+ NOW()
+ FROM packingSite ps
+ JOIN host h ON h.id = ps.hostFk
+ JOIN productionConfig pc
+ WHERE ps.id = vPackingSiteFk;
+
+ SET vExpeditionFk = LAST_INSERT_ID();
+
+ SET vLastExpeditionTimeStamp = NOW();
+
+ CALL dipole.expedition_Add(vExpeditionFk,vPrinterFk, TRUE);
+
+ SELECT shelvingFk, p.code
+ INTO vShelving, vParkingCode
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ WHERE ish.id = vItemShelvingFk;
+
+ UPDATE dipole.expedition_PrintOut
+ SET isPrinted = FALSE,
+ itemFk = vItemFk,
+ quantity = vPacking,
+ longName = vConcept,
+ shelvingFk = vShelving,
+ parkingCode = vParkingCode,
+ phone = RIGHT(phone,vMaxPhoneLength),
+ street = RIGHT(street, vMAxStreetLength)
+ WHERE expeditionFk = vExpeditionFk;
+
+ DELETE FROM sale
+ WHERE quantity = 0
+ AND id = vSaleFk;
+
+ END WHILE;
+
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/sale_calculateComponent.sql b/db/routines/vn/procedures/sale_calculateComponent.sql
new file mode 100644
index 000000000..63786c75c
--- /dev/null
+++ b/db/routines/vn/procedures/sale_calculateComponent.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_calculateComponent`(vSelf INT, vOption VARCHAR(25))
+proc: BEGIN
+/**
+ * Crea tabla temporal para vn.sale_recalcComponent() para recalcular los componentes
+ *
+ * @param vSelf Id de la venta
+ * @param vOption indica en que componente pone el descuadre, NULL en casos habituales
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
+ SELECT s.id
+ FROM sale s
+ WHERE s.id = vSelf;
+
+ CALL sale_recalcComponent(vOption);
+
+ DROP TEMPORARY TABLE tmp.recalculateSales;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sale_getBoxPickingList.sql b/db/routines/vn/procedures/sale_getBoxPickingList.sql
new file mode 100644
index 000000000..7466eb9be
--- /dev/null
+++ b/db/routines/vn/procedures/sale_getBoxPickingList.sql
@@ -0,0 +1,75 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_getBoxPickingList`(vSectorFk INT, vDated DATE)
+BEGIN
+/**
+* Returns a suitable boxPicking sales list
+*
+* @param vSectorFk Identifier for vn.sector table
+* @param vDated Date for vn.tickets.shipping
+*
+* @return tmp.sale
+*/
+ DECLARE vWarehouseFk INT;
+
+ SELECT warehouseFk INTO vWarehouseFk
+ FROM sector
+ WHERE id = vSectorFk;
+
+ CALL productionControl(vWarehouseFk, 0);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale
+ (saleFk INT PRIMARY KEY)
+ SELECT
+ s.ticketFk,
+ s.id saleFk,
+ s.itemFk,
+ s.concept,
+ s.quantity,
+ MAKETIME(pb.HH,pb.mm,0) etd,
+ pb.routeFk,
+ FLOOR(s.quantity / IF(i.isBoxPickingMode, ish.packing, i.packingOut)) stickers,
+ IF(i.isBoxPickingMode, ish.packing, i.packingOut) packing,
+ b.packagingFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemShelving ish ON ish.itemFk = s.itemFk
+ LEFT JOIN ( SELECT iss.itemShelvingFk,
+ s.itemFk,
+ SUM(iss.quantity) reserve
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.isPicked = FALSE
+ AND iss.created >= vDated
+ GROUP BY iss.itemShelvingFk, s.itemFk) tISS
+ ON tISS.itemFk = ish.itemFk AND tISS.itemShelvingFk = ish.id
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk
+ JOIN agencyMode am ON am.id = pb.agencyModeFk
+ JOIN agency a ON a .id = am.agencyFk
+ LEFT JOIN routesMonitor rm ON rm.routeFk = pb.routeFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk
+ LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN buy b ON b.id = lb.buy_id
+ WHERE IF(i.isBoxPickingMode, ish.packing, i.packingOut)
+ <= LEAST(s.quantity, ish.visible - IFNULL(tISS.reserve,0))
+ AND NOT pb.problem
+ AND sgd.saleFk IS NULL
+ AND p.sectorFk = vSectorFk
+ AND ts.isPreviousPreparable
+ AND ((rm.bufferFk AND rm.isPickingAllowed)
+ OR am.code = 'REC_ALG')
+ AND pb.shipped = vDated
+ AND a.isOwn
+ GROUP BY s.id
+ ORDER BY etd;
+
+ SELECT *
+ FROM tmp.sale
+ WHERE stickers;
+
+ DROP TEMPORARY TABLE tmp.productionBuffer;
+ DROP TEMPORARY TABLE tmp.sale;
+ END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql b/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql
new file mode 100644
index 000000000..5308bdd28
--- /dev/null
+++ b/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql
@@ -0,0 +1,117 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_getFromTicketOrCollection`(vParam INT)
+BEGIN
+/**
+ * Visualizar lineas de la tabla sale a través del parámetro vParam que puede
+ * ser ticket o collection.
+ *
+ * @param vParam Identificador de ticket o collection
+ */
+DECLARE vIsCollection BOOL;
+
+ SELECT COUNT(*) INTO vIsCollection
+ FROM collection c
+ WHERE c.id = vParam;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket2;
+
+ IF vIsCollection THEN
+ CREATE TEMPORARY TABLE tmp.ticket
+ (INDEX (id))
+ ENGINE = MEMORY
+ SELECT tc.ticketFk id
+ FROM ticketCollection tc
+ JOIN ticket t ON t.id = tc.ticketFk
+ WHERE tc.collectionFk = vParam;
+
+ CREATE TEMPORARY TABLE tmp.ticket2
+ (INDEX (id))
+ ENGINE = MEMORY
+ SELECT tc.ticketFk id
+ FROM ticketCollection tc
+ JOIN ticket t ON t.id = tc.ticketFk
+ WHERE tc.collectionFk = vParam;
+ ELSE
+ CREATE TEMPORARY TABLE tmp.ticket
+ (INDEX (id))
+ ENGINE = MEMORY
+ SELECT vParam id;
+
+ CREATE TEMPORARY TABLE tmp.ticket2
+ (INDEX (id))
+ ENGINE = MEMORY
+ SELECT vParam id;
+ END IF;
+
+ SELECT s.ticketFk,
+ sgd.saleGroupFk,
+ s.id saleFk,
+ s.itemFk,
+ s.quantity,
+ i.longName,
+ i.size,
+ s.reserved,
+ MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) isPreviousPrepared,
+ MAX(IF(st.semaphore <=> 2, TRUE, FALSE)) isPrepared,
+ MAX(IF(st.semaphore <=> 3, TRUE, FALSE)) isControlled,
+ MAX(IF(st.semaphore <=> 4, TRUE, FALSE)) isPreControlled,
+ ic.color,
+ ip.productor,
+ s.discount,
+ s.price,
+ i.stems,
+ i.category,
+ o.code origin,
+ tt.clientFk,
+ s.originalQuantity,
+ TRIM(CONCAT(LPAD(s.concept,30,' '), ' ',
+ RPAD(IFNULL(i.size,''),5,' '))) line1,
+ '' cel1,
+ TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2,
+ IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1),
+ CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)),
+ CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2,
+ TRIM(CONCAT(ic.color)) line3,
+ p.code cel3,
+ s.isAdded,
+ IF(c.workerFk IS NULL, getUser(), c.workerFk) workerFk,
+ IF(SUM(iss.quantity) IS NULL, 0, SUM(iss.quantity)) pickedQuantity,
+ MIN(iss.created) picked,
+ IF(sm.id, TRUE, FALSE) hasMistake,
+ sg.sectorFk,
+ b.packing,
+ b.grouping,
+ o.code
+ FROM tmp.ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN ticket tt ON tt.id = t.id
+ LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk
+ LEFT JOIN buy b ON b.id = lb.buy_id
+ JOIN item i ON i.id = s.itemFk
+ LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id
+ LEFT JOIN collection c ON c.id = tc.collectionFk
+ LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity
+ FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity
+ FROM tmp.ticket2 t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN saleTracking st ON st.saleFk = s.id
+ ORDER BY st.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY sub.saleFk, sub.stateFK) sub2 ON sub2.saleFk = s.id AND sub2.isChecked = 1
+ LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id
+ LEFT JOIN state st ON st.id = sub2.stateFk
+ LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
+ LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
+ LEFT JOIN parking p ON p.id = sg.parkingFk
+ LEFT JOIN saleMistake sm ON sm.saleFk = s.id
+ GROUP BY s.id;
+
+ DROP TEMPORARY TABLE
+ tmp.ticket,
+ tmp.ticket2;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql
new file mode 100644
index 000000000..bf02e2401
--- /dev/null
+++ b/db/routines/vn/procedures/sale_getProblems.sql
@@ -0,0 +1,299 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_getProblems`(IN vIsTodayRelative tinyint(1))
+BEGIN
+/**
+ * Calcula los problemas de cada venta para un conjunto de tickets.
+ *
+ * @param vIsTodayRelative Indica si se calcula el disponible como si todo saliera hoy
+ * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular
+ * @return tmp.sale_problems
+ */
+ DECLARE vWarehouseFk INT;
+ DECLARE vDate DATE;
+ DECLARE vAvailableCache INT;
+ DECLARE vVisibleCache INT;
+ DECLARE vDone BOOL;
+ DECLARE vComponentCount INT;
+
+ DECLARE vCursor CURSOR FOR
+ SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), DATE(tt.shipped))
+ FROM tmp.sale_getProblems tt
+ WHERE DATE(tt.shipped) BETWEEN util.VN_CURDATE()
+ AND util.VN_CURDATE() + INTERVAL IF(vIsTodayRelative, 9.9, 1.9) DAY;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DELETE tt.*
+ FROM tmp.sale_getProblems tt
+ JOIN ticketObservation tto ON tto.ticketFk = tt.ticketFk
+ JOIN observationType ot ON ot.id = tto.observationTypeFk
+ WHERE ot.code = 'administrative'
+ AND tto.description = 'Miriam';
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale_problems (
+ ticketFk INT(11),
+ saleFk INT(11),
+ isFreezed INTEGER(1) DEFAULT 0,
+ risk DECIMAL(10,2) DEFAULT 0,
+ hasHighRisk TINYINT(1) DEFAULT 0,
+ hasTicketRequest INTEGER(1) DEFAULT 0,
+ itemShortage VARCHAR(255),
+ isTaxDataChecked INTEGER(1) DEFAULT 1,
+ itemDelay VARCHAR(255),
+ itemLost VARCHAR(255),
+ hasComponentLack INTEGER(1),
+ hasRounding VARCHAR(255),
+ isTooLittle BOOL DEFAULT FALSE,
+ PRIMARY KEY (ticketFk, saleFk)
+ ) ENGINE = MEMORY;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_list
+ (PRIMARY KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT ticketFk, clientFk
+ FROM tmp.sale_getProblems;
+
+ SELECT COUNT(*) INTO vComponentCount
+ FROM component
+ WHERE isRequired;
+
+ -- Too Little
+ INSERT INTO tmp.sale_problems(ticketFk, isTooLittle)
+ SELECT tp.ticketFk, TRUE
+ FROM tmp.sale_getProblems tp
+ JOIN ticket t ON t.id = tp.ticketFk
+ JOIN (
+ SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat
+ FROM tmp.ticket_list tl
+ JOIN saleVolume sv ON sv.ticketFk = tl.ticketFk
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
+ AND zc.dated = util.VN_CURDATE()
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ WHERE util.VN_NOW() < (util.VN_CURDATE() + INTERVAL HOUR(zc.`hour`) HOUR) + INTERVAL MINUTE(zc.`hour`) MINUTE
+ AND dm.code IN ('AGENCY','DELIVERY','PICKUP')
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight()
+ GROUP BY t.addressFk
+ ) sub ON sub.addressFk = t.addressFk
+ JOIN volumeConfig vc
+ WHERE sub.litros < vc.minTicketVolume
+ AND sub.totalWithoutVat < vc.minTicketValue;
+
+ -- Faltan componentes
+ INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk)
+ SELECT ticketFk, (vComponentCount > nComp) hasComponentLack, saleFk
+ FROM (
+ SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk
+ FROM tmp.ticket_list tl
+ JOIN vn.sale s ON s.ticketFk = tl.ticketFk
+ LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id
+ LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired
+ JOIN vn.ticket t ON t.id = tl.ticketFk
+ JOIN vn.agencyMode am ON am.id = t.agencyModeFk
+ JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP')
+ AND s.quantity > 0
+ GROUP BY s.id
+ ) sub
+ HAVING hasComponentLack;
+
+ -- Cliente congelado
+ INSERT INTO tmp.sale_problems(ticketFk, isFreezed)
+ SELECT DISTINCT tl.ticketFk, TRUE
+ FROM tmp.ticket_list tl
+ JOIN client c ON c.id = tl.clientFk
+ WHERE c.isFreezed
+ ON DUPLICATE KEY UPDATE isFreezed = c.isFreezed;
+
+ -- Credit exceeded
+ CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt
+ (PRIMARY KEY (clientFk))
+ ENGINE = MEMORY
+ SELECT DISTINCT clientFk
+ FROM tmp.ticket_list;
+
+ CALL client_getDebt(util.VN_CURDATE());
+
+ INSERT INTO tmp.sale_problems(ticketFk, risk, hasHighRisk)
+ SELECT DISTINCT tl.ticketFk, r.risk, ((r.risk - cc.riskTolerance) > c.credit + 10)
+ FROM tmp.ticket_list tl
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN agencyMode a ON t.agencyModeFk = a.id
+ JOIN tmp.risk r ON r.clientFk = t.clientFk
+ JOIN client c ON c.id = t.clientFk
+ JOIN clientConfig cc
+ WHERE r.risk > c.credit + 10
+ AND NOT a.isRiskFree
+ ON DUPLICATE KEY UPDATE
+ risk = r.risk, hasHighRisk = ((r.risk - cc.riskTolerance) > c.credit + 10);
+
+ -- Antiguo COD 100, son peticiones de compra sin terminar
+ INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest)
+ SELECT DISTINCT tl.ticketFk, TRUE
+ FROM tmp.ticket_list tl
+ JOIN ticketRequest tr ON tr.ticketFk = tl.ticketFk
+ WHERE tr.isOK IS NULL
+ ON DUPLICATE KEY UPDATE hasTicketRequest = TRUE;
+
+ CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock_byWarehouse
+ (INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT ish.itemFk itemFk,
+ SUM(ish.visible) visible,
+ s.warehouseFk warehouseFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector s ON s.id = p.sectorFk
+ GROUP BY ish.itemFk,
+ s.warehouseFk;
+
+ -- Disponible, Faltas, Inventario y Retrasos
+ OPEN vCursor;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vCursor INTO vWarehouseFk, vDate;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ -- Disponible: no va a haber suficiente producto para preparar todos los pedidos
+ CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouseFk, vDate);
+
+ -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida
+ CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk);
+
+ INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk)
+ SELECT ticketFk, problem, saleFk
+ FROM (
+ SELECT tl.ticketFk,
+ LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem,
+ s.id AS saleFk
+ FROM tmp.ticket_list tl
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = i.id
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN cache.available av ON av.item_id = i.id
+ AND av.calc_id = vAvailableCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible,0) < s.quantity
+ AND IFNULL(av.available ,0) < s.quantity
+ AND IFNULL(issw.visible, 0) < s.quantity
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate)
+ AND NOT i.generic
+ AND util.VN_CURDATE() = vDate
+ AND t.warehouseFk = vWarehouseFk
+ GROUP BY tl.ticketFk) sub
+ ON DUPLICATE KEY UPDATE itemShortage = sub.problem, saleFk = sub.saleFk;
+
+ -- Inventario: Visible suficiente, pero ubicado menor a la cantidad vendida
+ INSERT INTO tmp.sale_problems(ticketFk, itemLost, saleFk)
+ SELECT ticketFk, problem, saleFk
+ FROM (
+ SELECT tl.ticketFk,
+ LEFT(GROUP_CONCAT('I: ', i.id, ' ', i.longName, ' '), 250) problem,
+ s.id saleFk
+ FROM tmp.ticket_list tl
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = s.itemFk
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible,0) >= s.quantity
+ AND IFNULL(issw.visible, 0) < s.quantity
+ AND s.quantity > 0
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate)
+ AND NOT i.generic
+ AND util.VN_CURDATE() = vDate
+ AND t.warehouseFk = vWarehouseFk
+ GROUP BY tl.ticketFk
+ ) sub
+ ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
+
+ -- Retraso: Disponible suficiente, pero no visible ni ubicado
+ INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk)
+ SELECT ticketFk, problem, saleFk
+ FROM (
+ SELECT tl.ticketFk,
+ LEFT(GROUP_CONCAT('R: ', i.id, ' ', i.longName, ' '), 250) problem,
+ s.id saleFk
+ FROM tmp.ticket_list tl
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = s.itemFk
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN cache.available av ON av.item_id = i.id
+ AND av.calc_id = vAvailableCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible, 0) < s.quantity
+ AND IFNULL(av.available, 0) >= s.quantity
+ AND IFNULL(issw.visible, 0) < s.quantity
+ AND s.quantity > 0
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate)
+ AND NOT i.generic
+ AND util.VN_CURDATE() = vDate
+ AND t.warehouseFk = vWarehouseFk
+ GROUP BY tl.ticketFk
+ ) sub
+ ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
+
+ -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra
+ CALL buyUltimate(vWarehouseFk, vDate);
+ INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
+ SELECT ticketFk, problem, saleFk
+ FROM (
+ SELECT tl.ticketFk,
+ s.id saleFk ,
+ LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem,
+ MOD(s.quantity, b.`grouping`) hasRounding
+ FROM tmp.ticket_list tl
+ JOIN ticket t ON t.id = tl.ticketFk
+ AND t.warehouseFk = vWarehouseFk
+ JOIN sale s ON s.ticketFk = tl.ticketFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
+ JOIN buy b ON b.id = bu.buyFk
+ GROUP BY tl.ticketFk
+ HAVING hasRounding
+ ) sub
+ ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk;
+ END LOOP;
+ CLOSE vCursor;
+
+ INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked)
+ SELECT DISTINCT tl.ticketFk, FALSE
+ FROM tmp.ticket_list tl
+ JOIN client c ON c.id = tl.clientFk
+ WHERE NOT c.isTaxDataChecked
+ ON DUPLICATE KEY UPDATE isTaxDataChecked = FALSE;
+
+ DROP TEMPORARY TABLE
+ tmp.clientGetDebt,
+ tmp.ticket_list,
+ tItemShelvingStock_byWarehouse;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sale_getProblemsByTicket.sql b/db/routines/vn/procedures/sale_getProblemsByTicket.sql
new file mode 100644
index 000000000..b4aaad7de
--- /dev/null
+++ b/db/routines/vn/procedures/sale_getProblemsByTicket.sql
@@ -0,0 +1,26 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_getProblemsByTicket`(IN vTicketFk INT, IN vIsTodayRelative TINYINT(1))
+BEGIN
+/**
+ * Calcula los problemas de cada venta
+ * para un conjunto de tickets.
+ *
+ * @return Problems result
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems;
+ CREATE TEMPORARY TABLE tmp.sale_getProblems
+ (INDEX (ticketFk))
+ ENGINE = MEMORY
+ SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped
+ FROM ticket t
+ WHERE t.id = vTicketFk;
+
+ CALL sale_getProblems(vIsTodayRelative);
+
+ SELECT * FROM tmp.sale_problems;
+
+ DROP TEMPORARY TABLE
+ tmp.sale_getProblems,
+ tmp.sale_problems;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sale_recalcComponent.sql b/db/routines/vn/procedures/sale_recalcComponent.sql
new file mode 100644
index 000000000..54297571a
--- /dev/null
+++ b/db/routines/vn/procedures/sale_recalcComponent.sql
@@ -0,0 +1,115 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_recalcComponent`(vOption VARCHAR(25))
+proc: BEGIN
+/**
+ * Este procedimiento recalcula los componentes de un conjunto de sales,
+ * eliminando los componentes existentes e insertandolos de nuevo
+ *
+ * @param vOption si no se quiere forzar llamar con NULL
+ * @table tmp.recalculateSales (id)
+ */
+ DECLARE vShipped DATE;
+ DECLARE vWarehouseFk SMALLINT;
+ DECLARE vAgencyModeFk INT;
+ DECLARE vAddressFk INT;
+ DECLARE vTicketFk INT;
+ DECLARE vLanded DATE;
+ DECLARE vIsEditable BOOLEAN;
+ DECLARE vZoneFk INTEGER;
+ DECLARE vDone BOOL DEFAULT FALSE;
+
+ DECLARE vCur CURSOR FOR
+ SELECT DISTINCT s.ticketFk
+ FROM tmp.recalculateSales rs
+ JOIN vn.sale s ON s.id = rs.id;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vCur;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vCur INTO vTicketFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL,
+ t.zoneFk,
+ t.warehouseFk,
+ t.shipped,
+ t.addressFk,
+ t.agencyModeFk,
+ t.landed
+ INTO vIsEditable,
+ vZoneFk,
+ vWarehouseFk,
+ vShipped,
+ vAddressFk,
+ vAgencyModeFk,
+ vLanded
+ FROM ticket t
+ LEFT JOIN ticketState ts ON t.id = ts.ticketFk
+ LEFT JOIN alertLevel al ON al.id = ts.alertLevel
+ WHERE t.id = vTicketFk;
+
+ CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE);
+
+ IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN
+ CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk));
+ END IF;
+
+ IF vLanded IS NULL OR vZoneFk IS NULL THEN
+
+ UPDATE ticket t
+ SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1)
+ WHERE t.id = vTicketFk AND t.landed IS NULL;
+
+ IF vZoneFk IS NULL THEN
+ SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1;
+ UPDATE ticket t
+ SET t.zoneFk = vZoneFk
+ WHERE t.id = vTicketFk AND t.zoneFk IS NULL;
+ END IF;
+
+ END IF;
+
+ DROP TEMPORARY TABLE tmp.zoneGetLanded;
+
+ -- rellena la tabla buyUltimate con la ultima compra
+ CALL buyUltimate (vWarehouseFk, vShipped);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.sale
+ (PRIMARY KEY (saleFk)) ENGINE = MEMORY
+ SELECT s.id saleFk, vWarehouseFk warehouseFk
+ FROM sale s
+ JOIN tmp.recalculateSales rs ON s.id = rs.id
+ WHERE s.ticketFk = vTicketFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot
+ SELECT vWarehouseFk warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk
+ FROM sale s
+ JOIN tmp.recalculateSales rs ON s.id = rs.id
+ LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
+ WHERE s.ticketFk = vTicketFk
+ GROUP BY s.itemFk;
+
+ CALL catalog_componentPrepare();
+ CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
+
+ IF vOption IS NULL THEN
+ SET vOption = IF(vIsEditable, 'renewPrices', 'imbalance');
+ END IF;
+
+ CALL ticketComponentUpdateSale(vOption);
+ CALL catalog_componentPurge();
+
+ DROP TEMPORARY TABLE tmp.buyUltimate;
+ DROP TEMPORARY TABLE tmp.sale;
+
+ END LOOP;
+ CLOSE vCur;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sale_replaceItem.sql b/db/routines/vn/procedures/sale_replaceItem.sql
new file mode 100644
index 000000000..82c5d1ec2
--- /dev/null
+++ b/db/routines/vn/procedures/sale_replaceItem.sql
@@ -0,0 +1,132 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_replaceItem`(vSaleFk INT, vNewItemFk INT, vQuantity INT)
+BEGIN
+/**
+ * Añade un nuevo articulo para sustituir a otro, y actualiza la memoria de sustituciones.
+ *
+ * @param vSaleFk id de la tabla sale
+ * @param vNewItemFk articulo sustituto
+ * @param vQuantity cantidad que se va a sustituir
+ */
+ DECLARE vTicketFk INT;
+ DECLARE vItemFk INT;
+ DECLARE vWarehouseFk SMALLINT;
+ DECLARE vDate DATE;
+ DECLARE vGrouping INT;
+ DECLARE vGroupingModeFk INT;
+ DECLARE vPacking INT;
+ DECLARE vRoundQuantity INT DEFAULT 1;
+ DECLARE vLanded DATE;
+ DECLARE vAddressFk INT;
+ DECLARE vAgencyModeFk INT;
+ DECLARE vNewPrice DECIMAL(10,2);
+ DECLARE vOldPrice DECIMAL(10,2);
+ DECLARE vOption VARCHAR(255);
+ DECLARE vNewSaleFk INT;
+ DECLARE vForceToGrouping INT DEFAULT 1;
+ DECLARE vForceToPacking INT DEFAULT 2;
+ DECLARE vFinalPrice DECIMAL(10,2);
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ SELECT s.ticketFk,
+ LEAST(s.quantity, vQuantity),
+ s.itemFk,
+ t.shipped,
+ t.warehouseFk,
+ t.landed,
+ t.addressFk,
+ t.agencyModeFk,
+ s.price
+ INTO vTicketFk,
+ vQuantity,
+ vItemFk,
+ vDate,
+ vWarehouseFk,
+ vLanded,
+ vAddressFk,
+ vAgencyModeFk,
+ vOldPrice
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE s.id = vSaleFk;
+
+ CALL buyUltimate(vWarehouseFk, vDate);
+
+ SELECT `grouping`, groupingMode, packing
+ INTO vGrouping,vGroupingModeFk,vPacking
+ FROM buy b
+ JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk
+ WHERE tmp.itemFk = vNewItemFk AND tmp.WarehouseFk = vWarehouseFk;
+
+ IF vGroupingModeFk = vForceToPacking AND vPacking > 0 THEN
+ SET vRoundQuantity = vPacking;
+ END IF;
+ IF vGroupingModeFk = vForceToGrouping AND vGrouping > 0 THEN
+ SET vRoundQuantity = vGrouping;
+ END IF;
+
+ CALL catalog_calcFromItem(
+ vLanded,
+ vAddressFk,
+ vAgencyModeFk,
+ vNewItemFk);
+
+ SELECT price INTO vNewPrice
+ FROM tmp.ticketComponentPrice
+ ORDER BY (vQuantity % `grouping`) ASC
+ LIMIT 1;
+
+ IF vNewPrice IS NULL THEN
+ CALL util.throw('price retrieval failed');
+ END IF;
+
+ IF vNewPrice > vOldPrice THEN
+ SET vFinalPrice = vOldPrice;
+ SET vOption = 'substitution';
+ ELSE
+ SET vFinalPrice = vNewPrice;
+ SET vOption = 'renewPrices';
+ END IF;
+
+ START TRANSACTION;
+
+ UPDATE sale
+ SET quantity = quantity - vQuantity
+ WHERE id = vSaleFk;
+
+ INSERT INTO vn.sale(ticketFk,
+ itemFk,
+ quantity,
+ concept,
+ price)
+ SELECT vTicketFk,
+ vNewItemFk,
+ CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ', i.name),
+ vFinalPrice
+ FROM vn.item i
+ WHERE id = vNewItemFk;
+
+ SELECT LAST_INSERT_ID() INTO vNewSaleFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.sale;
+ CREATE TEMPORARY TABLE tmp.sale
+ (PRIMARY KEY (saleFk))
+ ENGINE = MEMORY
+ SELECT id saleFk, vWarehouseFk warehouseFk
+ FROM sale s WHERE id = vNewSaleFk;
+
+ CALL ticketComponentUpdateSale(vOption);
+ CALL catalog_componentPurge();
+
+ INSERT INTO itemProposal(itemFk, mateFk, counter)
+ VALUES(vItemFk, vNewItemFk, 1)
+ ON DUPLICATE KEY UPDATE counter = counter + 1;
+
+ COMMIT;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sales_merge.sql b/db/routines/vn/procedures/sales_merge.sql
new file mode 100644
index 000000000..a91268c2f
--- /dev/null
+++ b/db/routines/vn/procedures/sales_merge.sql
@@ -0,0 +1,39 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sales_merge`(vTicketFk INT)
+BEGIN
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve
+ SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ WHERE s.ticketFk = vTicketFk
+ AND it.isMergeable
+ GROUP BY s.itemFk, s.price, s.discount;
+
+ START TRANSACTION;
+
+ UPDATE sale s
+ JOIN tSalesToPreserve stp ON stp.id = s.id
+ SET quantity = newQuantity
+ WHERE s.ticketFk = vTicketFk;
+
+ DELETE s.*
+ FROM sale s
+ LEFT JOIN tSalesToPreserve stp ON stp.id = s.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ WHERE s.ticketFk = vTicketFk
+ AND stp.id IS NULL
+ AND it.isMergeable;
+
+ COMMIT;
+
+ DROP TEMPORARY TABLE tSalesToPreserve;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sales_mergeByCollection.sql b/db/routines/vn/procedures/sales_mergeByCollection.sql
new file mode 100644
index 000000000..4c0693753
--- /dev/null
+++ b/db/routines/vn/procedures/sales_mergeByCollection.sql
@@ -0,0 +1,36 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sales_mergeByCollection`(vCollectionFk INT)
+BEGIN
+
+ DECLARE vDone BOOL;
+ -- Fetch variables
+ DECLARE vTicketFk INT;
+
+ DECLARE cCur CURSOR FOR
+ SELECT ticketFk
+ FROM vn.ticketCollection
+ WHERE collectionFk = vCollectionFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ OPEN cCur;
+
+ myLoop: LOOP
+
+ SET vDone = FALSE;
+
+ FETCH cCur INTO vTicketFk;
+
+ IF vDone THEN
+ LEAVE myLoop;
+ END IF;
+
+ CALL vn.sales_merge(vTicketFk);
+
+ END LOOP;
+
+ CLOSE cCur;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sectorCollectionSaleGroup_add.sql b/db/routines/vn/procedures/sectorCollectionSaleGroup_add.sql
new file mode 100644
index 000000000..5ffb30635
--- /dev/null
+++ b/db/routines/vn/procedures/sectorCollectionSaleGroup_add.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorCollectionSaleGroup_add`(vSaleGroupFk INT, vSectorCollectionFk INT)
+BEGIN
+/**
+ * Inserta un nuevo registro en vn.sectorCollectionSaleGroup
+ * Actualiza el usuario en vn.saleGroup y reemplaza los registros de vn.saleTracking
+ *
+ * @param vSaleGroupFk Identificador de vn.saleGroup
+ * @param vSectorCollectionFk Identificador de vn.sectorCollection
+ */
+ DECLARE vHasSaleGroup INT;
+ DECLARE vHasSectorCollection INT;
+
+ SELECT COUNT(id) INTO vHasSaleGroup
+ FROM saleGroup
+ WHERE id = vSaleGroupFk;
+
+ IF !vHasSaleGroup THEN
+ CALL util.throw ("invalid saleGroup");
+ END IF;
+
+ SELECT COUNT(id) INTO vHasSectorCollection
+ FROM sectorCollection
+ WHERE id = vSectorCollectionFk;
+
+ IF !vHasSectorCollection THEN
+ CALL util.throw ("invalid sectorCollection");
+ END IF;
+
+ REPLACE sectorCollectionSaleGroup
+ SET sectorCollectionFk = vSectorCollectionFk,
+ saleGroupFk = vSaleGroupFk;
+
+ UPDATE saleGroup sg
+ JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
+ JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
+ SET sg.userFk = sc.userFk
+ WHERE sg.id = vSaleGroupFk;
+
+ INSERT IGNORE saleTracking(
+ saleFk,
+ isChecked,
+ workerFk,
+ stateFk
+ )
+ SELECT sgd.saleFk ,
+ FALSE,
+ sc.userFk,
+ s.id
+ FROM saleGroupDetail sgd
+ JOIN sectorCollectionSaleGroup scsg
+ ON scsg.saleGroupFk = sgd.saleGroupFk
+ JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
+ JOIN state s ON s.code = 'PREVIOUS_PREPARATION'
+ WHERE sgd.saleGroupFk = vSaleGroupFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sectorCollection_get.sql b/db/routines/vn/procedures/sectorCollection_get.sql
new file mode 100644
index 000000000..e518e05f8
--- /dev/null
+++ b/db/routines/vn/procedures/sectorCollection_get.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorCollection_get`()
+BEGIN
+/**
+ * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas
+ *
+ */
+ SELECT DISTINCT sc.id collectionFk, sc.created
+ FROM vn.sectorCollection sc
+ JOIN vn.state s ON s.code = 'PREVIOUS_PREPARATION'
+ LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
+ LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk
+ LEFT JOIN vn.saleTracking st ON st.saleFk = sgd.saleFk AND st.stateFk = s.id AND st.workerFk = sc.userFk
+ LEFT JOIN vn.sale sl ON sl.id = st.saleFk
+ WHERE sc.userFk = account.myUser_getId()
+ AND (
+ ISNULL(scsg.sectorCollectionFk)
+ OR (NOT st.isChecked AND sl.quantity > 0)
+ )
+ AND sc.created > util.VN_CURDATE();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sectorCollection_getSale.sql b/db/routines/vn/procedures/sectorCollection_getSale.sql
new file mode 100644
index 000000000..e1636895b
--- /dev/null
+++ b/db/routines/vn/procedures/sectorCollection_getSale.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorCollection_getSale`(vSelf INT)
+BEGIN
+/**
+ * Devuelve las lineas de venta correspondientes a esa coleccion de sector
+ *
+ * @param vSelf Identificador de vn.sectorCollection
+ */
+ SELECT s.ticketFk,
+ s.itemFk,
+ i.longName,
+ itemPackingTypeFk,
+ subName,
+ s.quantity,
+ w.code workerCode,
+ sgd.saleFk,
+ iss.quantity pickedQuantity,
+ c.salesPersonFk
+ FROM vn.sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sgd.saleGroupFk
+ JOIN saleTracking st ON st.saleFk = s.id
+ JOIN `state` stt ON stt.id = st.stateFk AND stt.code = 'PREVIOUS_PREPARATION'
+ JOIN worker w ON w.id = st.workerFk
+ JOIN ticket t ON t.id= s.ticketFk
+ JOIN client c ON c.id=t.clientFk
+ LEFT JOIN itemShelvingSaleSum iss ON iss.saleFk = s.id
+ WHERE scsg.sectorCollectionFk = vSelf
+ AND st.workerFk = account.myUser_getId();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sectorCollection_new.sql b/db/routines/vn/procedures/sectorCollection_new.sql
new file mode 100644
index 000000000..fae8eba31
--- /dev/null
+++ b/db/routines/vn/procedures/sectorCollection_new.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorCollection_new`(vSectorFk INT)
+BEGIN
+/**
+ * Inserta una nueva colección, si el usuario no tiene ninguna vacia.
+ * Esto se hace para evitar que por error se generen colecciones sin sentido.
+ *
+ * @param vSectorFk Identificador de #vn.sector
+ */
+ DECLARE hasEmptyCollections BOOL;
+ DECLARE vUserFk INT;
+
+ SET vUserFk = account.myUser_getId();
+
+ SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections
+ FROM vn.sectorCollection sc
+ LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
+ WHERE ISNULL(scsg.id)
+ AND sc.userFk = vUserFk
+ AND sc.sectorFk = vSectorFk
+ AND sc.created >= util.VN_CURDATE();
+
+ IF NOT hasEmptyCollections THEN
+ INSERT INTO vn.sectorCollection(userFk, sectorFk)
+ VALUES(vUserFk, vSectorFk);
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sectorProductivity_add.sql b/db/routines/vn/procedures/sectorProductivity_add.sql
new file mode 100644
index 000000000..be75c842d
--- /dev/null
+++ b/db/routines/vn/procedures/sectorProductivity_add.sql
@@ -0,0 +1,74 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorProductivity_add`()
+BEGIN
+ DECLARE vDatedFrom DATETIME;
+ DECLARE vDatedTo DATETIME;
+
+ SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate;
+ DROP TEMPORARY TABLE IF EXISTS tmp.errorsByChecker;
+ DROP TEMPORARY TABLE IF EXISTS tmp.previousErrors;
+
+ CALL timeControl_calculateAll(vDatedFrom, vDatedTo);
+
+ CREATE TEMPORARY TABLE tmp.errorsByChecker
+ ENGINE = MEMORY
+ SELECT sc.userFk workerFk, COUNT(DISTINCT s.ticketFk) errorsByChecker
+ FROM saleMistake sm
+ JOIN vn.saleGroupDetail sgd on sgd.saleFk = sm.saleFk
+ JOIN vn.sectorCollectionSaleGroup scsg on scsg.saleGroupFk = sgd.saleGroupFk
+ JOIN vn.sectorCollection sc on sc.id = scsg.sectorCollectionFk
+ JOIN sale s ON s.id = sm.saleFk
+ JOIN ticket t on t.id = s.ticketFk
+ WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo)
+ GROUP BY sc.userFk ;
+
+ CREATE TEMPORARY TABLE tmp.previousErrors -- Errores de previa, derivadores de los revisadores (por reclamación)
+ ENGINE = MEMORY
+ SELECT tt.userFk, COUNT(c.ticketFk) errorsByClaim
+ FROM claimDevelopment cd
+ JOIN claim c ON cd.claimFk = c.id
+ JOIN ticket t ON c.ticketFk = t.id
+ JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
+ JOIN ticketTracking tt ON tt.ticketFk = t.id
+ JOIN `state` s ON s.id = tt.stateFk
+ WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = 'Revisadores' AND s.code = 'OK PREVIOUS'
+ GROUP BY tt.userFk;
+
+ DELETE FROM sectorProductivity
+ WHERE dated = vDatedFrom
+ AND sector IN ('Algemesi Artificial','Algemesi Complementos');
+
+ INSERT INTO sectorProductivity(workerFk, firstName, lastName, sector, ticketCount, saleCount, error, volume, hourWorked, dated)
+ SELECT w.id workerFk,
+ w.firstName,
+ w.lastName,
+ se.description sector,
+ COUNT(DISTINCT s.ticketFk) ticketCount,
+ COUNT(sgd.id) saleCount,
+ IFNULL(ec2.errorsByChecker,0) + IFNULL(pe.errorsByClaim, 0) errors,
+ wp.volume,
+ IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) AS hourWorked,
+ DATE(vDatedFrom) dated
+ FROM vn.saleGroupDetail sgd
+ JOIN vn.saleGroup sg on sg.id = sgd.saleGroupFk
+ JOIN vn.sectorCollectionSaleGroup scsg on scsg.saleGroupFk = sgd.saleGroupFk
+ JOIN vn.sectorCollection sc on sc.id = scsg.sectorCollectionFk
+ join vn.sector se on se.id = sc.sectorFk
+ JOIN vn.worker w ON w.id = sc.userFk
+ LEFT JOIN vn.sale s ON s.id = sgd.saleFk
+ LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = w.id
+ LEFT JOIN bs.workerProductivity wp ON wp.workerFk = w.id
+ LEFT JOIN `state` s2 ON s2.id = wp.stateFk AND s2.code = 'OK PREVIOUS'
+ LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = w.id
+ LEFT JOIN tmp.previousErrors pe ON pe.userFk = w.id
+ WHERE DATE(sc.created) = vDatedFrom
+ AND wp.dated = vDatedFrom
+ GROUP BY w.id;
+
+ DROP TEMPORARY TABLE tmp.timeControlCalculate;
+ DROP TEMPORARY TABLE tmp.errorsByChecker;
+ DROP TEMPORARY TABLE tmp.previousErrors;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sector_getWarehouse.sql b/db/routines/vn/procedures/sector_getWarehouse.sql
new file mode 100644
index 000000000..fe363f39f
--- /dev/null
+++ b/db/routines/vn/procedures/sector_getWarehouse.sql
@@ -0,0 +1,10 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sector_getWarehouse`(vSectorFk INT)
+BEGIN
+
+ SELECT s.warehouseFk
+ FROM vn.sector s
+ WHERE s.id = vSectorFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/setParking.sql b/db/routines/vn/procedures/setParking.sql
new file mode 100644
index 000000000..97a40bbe0
--- /dev/null
+++ b/db/routines/vn/procedures/setParking.sql
@@ -0,0 +1,61 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`setParking`(IN `vParam` VARCHAR(8), IN `vParkingCode` VARCHAR(8))
+proc: BEGIN
+/**
+ * Aparca una colección, un ticket, un saleGroup o un shelving en un parking
+ *
+ * @param vParam id del ticket, colección, saleGroup o shelving
+ * @param vParkingCode código del parking
+ */
+ DECLARE vParkingFk INT;
+ DECLARE vIsSaleGroup BOOL;
+ DECLARE vIsTicket BOOL;
+ DECLARE vIsCollection BOOL;
+
+ SET vParkingCode = replace(vParkingCode,' ','');
+
+ SELECT id INTO vParkingFk
+ FROM vn.parking
+ WHERE code = vParkingCode COLLATE utf8_unicode_ci;
+
+ IF vParkingFk IS NULL THEN
+ CALL util.throw('parkingNotExist');
+ LEAVE proc;
+ END IF;
+
+ -- Se comprueba si es una preparación previa
+ SELECT COUNT(*) INTO vIsSaleGroup
+ FROM vn.saleGroup sg
+ WHERE sg.id = vParam;
+
+ IF vIsSaleGroup THEN
+ CALL vn.saleGroup_setParking(vParam, vParkingFk);
+ LEAVE proc;
+ END IF;
+
+ -- Se comprueba si es un ticket
+ SELECT COUNT(*) INTO vIsTicket
+ FROM vn.ticket t
+ WHERE t.id = vParam
+ AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
+
+ IF vIsTicket THEN
+ CALL vn.ticket_setParking(vParam, vParkingFk);
+ LEAVE proc;
+ END IF;
+
+ -- Se comprueba si es una coleccion de tickets
+ SELECT COUNT(*) INTO vIsCollection
+ FROM vn.collection c
+ WHERE c.id = vParam
+ AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
+
+ IF vIsCollection THEN
+ CALL vn.collection_setParking(vParam, vParkingFk);
+ LEAVE proc;
+ END IF;
+
+ -- Por descarte, se considera una matrícula
+ CALL vn.shelving_setParking(vParam, vParkingFk);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/shelvingChange.sql b/db/routines/vn/procedures/shelvingChange.sql
new file mode 100644
index 000000000..fde38212c
--- /dev/null
+++ b/db/routines/vn/procedures/shelvingChange.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`shelvingChange`(IN `vShelvingO` VARCHAR(8), IN `vShelvingD` VARCHAR(8))
+BEGIN
+
+ UPDATE vn.itemShelving
+ SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci
+ WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/shelvingLog_get.sql b/db/routines/vn/procedures/shelvingLog_get.sql
new file mode 100644
index 000000000..d48e38d03
--- /dev/null
+++ b/db/routines/vn/procedures/shelvingLog_get.sql
@@ -0,0 +1,18 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`shelvingLog_get`(shelvingFk VARCHAR(10))
+BEGIN
+
+ /* Lista el log de un carro
+ *
+ * @param shelvingFk matrícula del carro
+ *
+ */
+
+ SELECT originFk, name, creationDate, description
+ FROM shelvingLog sl
+ JOIN account.user u ON u.id = sl.userFk
+ WHERE sl.originFk = shelvingFk COLLATE utf8_general_ci
+ ORDER BY creationDate DESC;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/shelvingParking_get.sql b/db/routines/vn/procedures/shelvingParking_get.sql
new file mode 100644
index 000000000..0131db7d2
--- /dev/null
+++ b/db/routines/vn/procedures/shelvingParking_get.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT)
+BEGIN
+
+
+SELECT s.itemFk,
+ s.concept,
+ CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir,
+ CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado
+ FROM vn.sale s
+ LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk
+ JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci
+ WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE()))
+ AND iss.saleFk IS NULL
+ AND t.warehouseFk = vWarehouseFk
+ GROUP BY s.itemFk
+ HAVING sinServir > aparcado;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/shelvingPriority_update.sql b/db/routines/vn/procedures/shelvingPriority_update.sql
new file mode 100644
index 000000000..317f17333
--- /dev/null
+++ b/db/routines/vn/procedures/shelvingPriority_update.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`shelvingPriority_update`(priority INT,vShelvingFk VARCHAR(10))
+BEGIN
+
+ UPDATE vn.shelving SET priority = priority WHERE code=vShelvingFk COLLATE utf8_unicode_ci;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/shelving_clean.sql b/db/routines/vn/procedures/shelving_clean.sql
new file mode 100644
index 000000000..f9248a0d7
--- /dev/null
+++ b/db/routines/vn/procedures/shelving_clean.sql
@@ -0,0 +1,37 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`shelving_clean`()
+BEGIN
+
+ DELETE FROM shelving
+ WHERE length(code) > 3
+ AND parked < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
+
+ DELETE FROM itemShelving
+ WHERE visible <= 0
+ AND created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE());
+
+ DELETE ish.*
+ FROM itemShelving ish
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ WHERE sh.parkingFk IS NULL
+ AND ish.created < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
+
+UPDATE shelving sh
+ LEFT JOIN itemShelving its ON its.shelvingFk = sh.`code`
+ SET isPrinted = 0,
+ parkingFk = NULL
+ WHERE its.id IS NULL
+ AND sh.isRecyclable
+ AND (
+ sh.parked IS NULL
+ OR
+ sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())
+ )
+ AND IF(code REGEXP '^[A-Za-z]{2}[0-9]', LEFT (code, 2) NOT IN (
+ SELECT DISTINCT LEFT(its.shelvingFk, 2)
+ FROM itemShelving its
+ WHERE its.shelvingFk REGEXP '^[A-Za-z]{2}[0-9]'
+ ), TRUE);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/shelving_getSpam.sql b/db/routines/vn/procedures/shelving_getSpam.sql
new file mode 100644
index 000000000..2895470ad
--- /dev/null
+++ b/db/routines/vn/procedures/shelving_getSpam.sql
@@ -0,0 +1,84 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`shelving_getSpam`(vDated DATE, vWarehouseFk INT)
+BEGIN
+/**
+ * Devuelve las matrículas con productos que no son necesarios para la venta
+ * hasta la fecha señalada.
+ *
+ * @param vDated Fecha hasta la que se puede pasar sin esos productos
+ * @param vWarehouse Identificador único de vn.warehouse
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.stock;
+
+ CALL cache.stock_refresh(FALSE);
+
+ CREATE TEMPORARY TABLE tmp.stock
+ SELECT i.id itemFk,
+ v.amount - IFNULL(fue.reserva,0) as visible,
+ fue.reserva,
+ sale.venta,
+ IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra,
+ IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) - IFNULL(fue.reserva,0) as saldo
+ FROM vn.item i
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN (
+ SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva
+ FROM vn.itemShelving ish
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.parking p ON p.id = sh.parkingFk
+ JOIN vn.sector s ON s.id = p.sectorFk
+ WHERE s.code = 'FUENTES_PICASSE'
+ OR sh.isSpam
+ GROUP BY ish.itemFk
+ ) fue ON fue.itemFk = i.id
+ LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk
+ LEFT JOIN (
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta
+ FROM itemTicketOut
+ WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
+ AND warehouseFk = vWarehouseFk
+ GROUP BY itemFk
+ ) sale ON sale.item_id = i.id
+ LEFT JOIN (
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra
+ FROM itemEntryIn
+ WHERE landed BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
+ AND warehouseInFk = vWarehouseFk
+ AND isVirtualStock = FALSE
+ GROUP BY itemFk
+ ) buy ON buy.item_id = i.id
+ LEFT JOIN (
+ SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado
+ FROM itemEntryOut
+ WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
+ AND warehouseOutFk = vWarehouseFk
+ GROUP BY itemFk
+ ) mov ON mov.item_id = i.id
+ WHERE v.amount;
+
+ SELECT ish.shelvingFk matricula,
+ i.longName articulo,
+ ish.visible,
+ count(*) lineas,
+ sum(ish.visible <= s.saldo) spam,
+ p.code parking,
+ s.description sector ,
+ w.name AS almacen,
+ sh.isSpam
+ FROM vn.itemShelving ish
+ JOIN vn.item i ON i.id = ish.itemFk
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.parking p ON p.id = sh.parkingFk
+ JOIN vn.sector s ON s.id = p.sectorFk
+ JOIN vn.warehouse w ON w.id = s.warehouseFk
+ LEFT JOIN tmp.stock s ON s.itemFk = ish.itemFk
+ WHERE (w.name = 'Algemesi'
+ OR (w.name = 'NuncaJamas' AND ish.created < util.VN_CURDATE()))
+ AND ish.visible
+ GROUP BY ish.shelvingFk
+ HAVING lineas = spam OR isSpam;
+
+ DROP TEMPORARY TABLE tmp.stock;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/shelving_setParking.sql b/db/routines/vn/procedures/shelving_setParking.sql
new file mode 100644
index 000000000..0ff07ef5d
--- /dev/null
+++ b/db/routines/vn/procedures/shelving_setParking.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`shelving_setParking`(IN `vShelvingCode` VARCHAR(8), IN `vParkingFk` INT)
+proc: BEGIN
+/**
+ * Aparca una matrícula en un parking
+ *
+ * @param vShelvingCode code de la matrícula
+ * @param vParkingFk id del parking
+ */
+ INSERT INTO vn.shelvingLog (originFk, userFk, action , description,changedModel,changedModelId)
+ SELECT s.id, account.myUser_getId(), 'update', CONCAT("Cambio parking ",vShelvingCode," de ", p.code," a ", pNew.code),'Shelving',s.id
+ FROM parking p
+ JOIN shelving s ON s.parkingFk = p.id
+ JOIN parking pNew ON pNew.id = vParkingFk
+ WHERE s.code = vShelvingCode COLLATE utf8_unicode_ci;
+
+ UPDATE vn.shelving
+ SET parkingFk = vParkingFk,
+ parked = util.VN_NOW(),
+ isPrinted = TRUE
+ WHERE code = vShelvingCode COLLATE utf8_unicode_ci;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sleep_X_min.sql b/db/routines/vn/procedures/sleep_X_min.sql
new file mode 100644
index 000000000..39102b57d
--- /dev/null
+++ b/db/routines/vn/procedures/sleep_X_min.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sleep_X_min`()
+BEGIN
+ # Ernesto. 4.8.2020
+ # Para su uso en las tareas ejecutadas a las 2AM (visibles con: SELECT * FROM bs.nightTask order by started asc;)
+ # Simplemente esperar unos minutos para que en las graficas de rendimiento de Percona PMM y escritura a disco de vCenter se puedan ver los efectos de cada tarea.
+ do SLEEP(300);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/stockBuyedByWorker.sql b/db/routines/vn/procedures/stockBuyedByWorker.sql
new file mode 100644
index 000000000..730612db8
--- /dev/null
+++ b/db/routines/vn/procedures/stockBuyedByWorker.sql
@@ -0,0 +1,74 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBuyedByWorker`(
+ vDated DATE,
+ vWorker INT
+)
+BEGIN
+/**
+ * Inserta el volumen de compra de un comprador
+ * en stockBuyed de acuerdo con la fecha.
+ *
+ * @param vDated Fecha de compra
+ * @param vWorker Id de trabajador
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tStockBuyed
+ (INDEX (userFk))
+ ENGINE = MEMORY
+ SELECT requested, reserved, userFk
+ FROM stockBuyed
+ WHERE dated = vDated
+ AND userFk = vWorker;
+
+ DELETE FROM stockBuyed
+ WHERE dated = vDated
+ AND userFk = vWorker;
+
+ CALL stockTraslation(vDated);
+
+ INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description)
+ SELECT it.workerFk,
+ SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000,
+ vDated,
+ sb.reserved,
+ sb.requested,
+ u.name
+ FROM itemType it
+ JOIN item i ON i.typeFk = it.id
+ LEFT JOIN tmp.item ti ON ti.itemFk = i.id
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ JOIN warehouse wh ON wh.code = 'VNH'
+ JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
+ AND bu.warehouseFk = wh.id
+ JOIN buy b ON b.id = bu.buyFk
+ JOIN volumeConfig vc
+ JOIN account.`user` u ON u.id = it.workerFk
+ LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk
+ WHERE ic.display
+ AND it.workerFk = vWorker;
+
+ SELECT b.entryFk Id_Entrada,
+ i.id Id_Article,
+ i.name Article,
+ ti.quantity Cantidad,
+ (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id))
+ / (vc.trolleyM3 * 1000000) buyed,
+ b.packagingFk id_cubo,
+ b.packing
+ FROM tmp.item ti
+ JOIN item i ON i.id = ti.itemFk
+ JOIN itemType it ON i.typeFk = it.id
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ JOIN worker w ON w.id = it.workerFk
+ JOIN auctionConfig ac
+ JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
+ AND bu.warehouseFk = ac.warehouseFk
+ JOIN buy b ON b.id = bu.buyFk
+ JOIN volumeConfig vc
+ WHERE ic.display
+ AND w.id = vWorker;
+
+ DROP TEMPORARY TABLE tmp.buyUltimate,
+ tmp.item,
+ tStockBuyed;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/stockBuyed_add.sql b/db/routines/vn/procedures/stockBuyed_add.sql
new file mode 100644
index 000000000..bddb720a5
--- /dev/null
+++ b/db/routines/vn/procedures/stockBuyed_add.sql
@@ -0,0 +1,70 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBuyed_add`(
+ vDated DATE
+)
+BEGIN
+/**
+ * Inserta el volumen de compra por comprador
+ * en stockBuyed de acuerdo con la fecha.
+ *
+ * @param vDated Fecha de compra
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tStockBuyed
+ (INDEX (userFk))
+ ENGINE = MEMORY
+ SELECT requested, reserved, userFk
+ FROM stockBuyed
+ WHERE dated = vDated;
+
+ DELETE FROM stockBuyed WHERE dated = vDated;
+
+ CALL stockTraslation(vDated);
+
+ INSERT INTO stockBuyed(userFk, buyed, `dated`, description)
+ SELECT it.workerFk,
+ SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000,
+ vDated,
+ u.name
+ FROM itemType it
+ JOIN item i ON i.typeFk = it.id
+ LEFT JOIN tmp.item ti ON ti.itemFk = i.id
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ JOIN warehouse wh ON wh.code = 'VNH'
+ JOIN tmp.buyUltimate bu ON bu.itemFk = i.id AND bu.warehouseFk = wh.id
+ JOIN buy b ON b.id = bu.buyFk
+ JOIN volumeConfig vc
+ JOIN account.`user` u ON u.id = it.workerFk
+ JOIN workerDepartment wd ON wd.workerFk = u.id
+ JOIN department d ON d.id = wd.departmentFk
+ WHERE ic.display
+ AND d.code IN ('shopping', 'logistic', 'franceTeam')
+ GROUP BY it.workerFk;
+
+ INSERT INTO stockBuyed(buyed, dated, description)
+ SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000),
+ vDated,
+ IF(c.code = 'ES', p.name, c.country) destiny
+ FROM itemTicketOut ito
+ JOIN ticket t ON t.id = ito.ticketFk
+ JOIN `address` a ON a.id = t.addressFk
+ JOIN province p ON p.id = a.provinceFk
+ JOIN country c ON c.id = p.countryFk
+ JOIN warehouse wh ON wh.id = t.warehouseFk
+ JOIN itemCost ic ON ic.itemFk = ito.itemFk
+ AND ic.warehouseFk = t.warehouseFk
+ JOIN volumeConfig vc
+ WHERE ito.shipped BETWEEN vDated AND util.dayend(vDated)
+ AND wh.code = 'VNH'
+ GROUP BY destiny;
+
+ UPDATE stockBuyed s
+ JOIN tStockBuyed ts ON ts.userFk = s.userFk
+ SET s.requested = ts.requested,
+ s.reserved = ts.reserved
+ WHERE s.dated = vDated;
+
+ DROP TEMPORARY TABLE tmp.buyUltimate,
+ tmp.item,
+ tStockBuyed;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/stockTraslation.sql b/db/routines/vn/procedures/stockTraslation.sql
new file mode 100644
index 000000000..c681112f1
--- /dev/null
+++ b/db/routines/vn/procedures/stockTraslation.sql
@@ -0,0 +1,41 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockTraslation`(
+ vDated DATE
+)
+BEGIN
+/**
+ * Calcula el stock del almacén de subasta desde FechaInventario hasta vDated
+ * sin tener en cuenta las salidas del mismo dia vDated
+ * para ver el transporte a reservar
+ *
+ * @param vDated Fecha hasta la cual calcula el stock
+ * @return tmp.item
+ */
+ DECLARE vAuctionWarehouseFk INT;
+
+ SELECT warehouseFk INTO vAuctionWarehouseFk
+ FROM auctionConfig;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.item
+ (UNIQUE INDEX i USING HASH (itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk, SUM(quantity) quantity
+ FROM itemEntryIn
+ WHERE landed = vDated
+ AND vDated >= util.VN_CURDATE()
+ AND warehouseInFk = vAuctionWarehouseFk
+ AND NOT isVirtualStock
+ GROUP BY itemFk
+ HAVING quantity;
+
+ CALL `cache`.stock_refresh(FALSE);
+
+ INSERT INTO tmp.item (itemFk, quantity)
+ SELECT item_id, amount
+ FROM `cache`.stock
+ WHERE warehouse_id = vAuctionWarehouseFk
+ ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity);
+
+ CALL buyUltimate(vAuctionWarehouseFk, vDated);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/subordinateGetList.sql b/db/routines/vn/procedures/subordinateGetList.sql
new file mode 100644
index 000000000..0431afaa4
--- /dev/null
+++ b/db/routines/vn/procedures/subordinateGetList.sql
@@ -0,0 +1,50 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`subordinateGetList`(vBossFk INT)
+BEGIN
+
+ -- deprecated usar vn.worker_GetHierarch
+ DECLARE vBossId INT;
+ DECLARE vDone BOOL;
+ DECLARE workerCur CURSOR FOR
+ SELECT workerFk
+ FROM tmp.subordinate
+ WHERE NOT isChecked;
+
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE EXIT HANDLER FOR 1062 BEGIN
+ CALL util.throw('INFINITE_LOOP');
+ END;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.subordinate;
+
+ CREATE TEMPORARY TABLE tmp.subordinate
+ (PRIMARY KEY (workerFk))
+ ENGINE = MEMORY
+ SELECT vBossFk AS workerFk, 0 AS isChecked;
+
+ WHILE (SELECT COUNT(*) FROM tmp.subordinate WHERE NOT isChecked) > 0 DO
+ OPEN workerCur;
+ workerLoop: LOOP
+ SET vDone = FALSE;
+
+ FETCH workerCur INTO vBossId;
+
+ IF vDone THEN
+ LEAVE workerLoop;
+ END IF;
+
+ INSERT INTO tmp.subordinate
+ SELECT id, 0
+ FROM worker
+ WHERE bossFk = vBossId;
+
+ UPDATE tmp.subordinate
+ SET isChecked = 1
+ WHERE workerFk = vBossId;
+ END LOOP;
+
+ CLOSE workerCur;
+ END WHILE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/supplierExpenses.sql b/db/routines/vn/procedures/supplierExpenses.sql
new file mode 100644
index 000000000..11ebbd603
--- /dev/null
+++ b/db/routines/vn/procedures/supplierExpenses.sql
@@ -0,0 +1,79 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplierExpenses`(vEnded DATE)
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS openingBalance;
+
+ CREATE TEMPORARY TABLE openingBalance(
+ dueDated DATE
+ , supplierFk INT NOT NULL
+ , companyFk INT NOT NULL
+ , eurAmount DOUBLE NOT NULL
+ , foreignAmount DOUBLE NOT NULL
+ , PRIMARY KEY(supplierFk, companyFk))
+ ENGINE = MEMORY;
+
+ -- Calcula el balance inicial y final de cada proveedor
+ INSERT INTO openingBalance
+ SELECT MAX(dueDated),
+ supplierFk,
+ companyFk,
+ sum(amount) eurAmount,
+ sum(divisa) foreignAmount
+ FROM (
+ SELECT p.dueDated,
+ p.supplierFk,
+ p.companyFk,
+ p.amount,
+ p.divisa
+ FROM payment p
+ JOIN currency c ON c.id = p.currencyFk
+ JOIN company co ON co.id = p.companyFk
+ WHERE p.dueDated > '2014-12-31'
+ AND p.dueDated <= vEnded
+ AND co.`code` = 'VNL'
+ AND c.`code` <> 'EUR'
+ UNION ALL
+
+ SELECT iidd.dueDated,
+ ii.supplierFk,
+ ii.companyFk,
+ - iidd.amount,
+ - iidd.foreignValue
+ FROM invoiceIn ii
+ JOIN invoiceInDueDay iidd ON ii.id = iidd.invoiceInFk
+ JOIN currency c ON c.id = ii.currencyFk
+ JOIN company co ON co.id = ii.companyFk
+ WHERE iidd.dueDated > '2014-12-31'
+ AND iidd.dueDated <= vEnded
+ AND ii.isBooked AND co.`code` = 'VNL'
+ AND c.`code` <> 'EUR'
+ UNION ALL
+
+ SELECT se.dueDated,
+ se.supplierFk,
+ se.companyFk,
+ - se.amount,
+ 0
+ FROM supplierExpense se
+ JOIN currency c ON c.id = se.currencyFk
+ JOIN company co ON co.id = se.companyFk
+ WHERE se.dueDated > '2014-12-31'
+ AND se.dueDated <= vEnded
+ AND co.`code` = 'VNL' AND c.`code` <> 'EUR'
+ ) sub
+ GROUP BY companyFk, supplierFk;
+
+ SELECT ob.dueDated
+ , ob.supplierFk
+ , ob.companyFk
+ , ob.eurAmount
+ , s.`name`
+ FROM openingBalance ob
+ LEFT JOIN supplier s ON s.id = ob.supplierFk
+ WHERE ob.eurAmount <> 0 AND ob.foreignAmount = 0;
+
+ DROP TEMPORARY TABLE openingBalance;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql
new file mode 100644
index 000000000..f9d43f925
--- /dev/null
+++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql
@@ -0,0 +1,82 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplierPackaging_ReportSource`(
+ vFromDated DATE,
+ vSupplierFk INT
+)
+BEGIN
+/**
+* Selecciona los embalajes de un proveedor a partir de una fecha
+*
+* @param vFromDated Fecha de la que partir
+* @param vSupplierFk Id del proveedor
+*/
+ SET @vBalance = 0;
+ SET @vItemFk = NULL;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSupplierPackaging
+ SELECT supplierFk,
+ itemFk,
+ longName,
+ supplier,
+ entryFk,
+ landed,
+ `in`,
+ `out`,
+ warehouse,
+ buyingValue,
+ IF (
+ NOT (@vItemFk <=> sub.itemFk),
+ @vBalance := (`in` - `out`),
+ @vBalance := (`in` - `out` + @vBalance)
+ ) balance,
+ @vItemFk := sub.itemFk previousItemFk
+ FROM (
+ SELECT supplierFk,
+ itemFk,
+ longName,
+ supplier,
+ entryFk,
+ landed,
+ `in`,
+ `out`,
+ warehouse,
+ buyingValue
+ FROM supplierPackaging
+ WHERE supplierFk = vSupplierFk
+ AND landed >= vFromDated
+ UNION ALL
+ SELECT vSupplierFk,
+ itemFk,
+ longName,
+ supplier,
+ 'previous',
+ vFromDated,
+ SUM(`in`),
+ SUM(`out`),
+ NULL,
+ buyingValue
+ FROM supplierPackaging
+ WHERE supplierFk = vSupplierFk
+ AND landed < vFromDated
+ GROUP BY itemFk
+ ORDER BY itemFk, landed, entryFk
+ ) sub
+ WHERE `out` OR `in`;
+
+ SELECT supplierFk,
+ itemFk,
+ longName,
+ supplier,
+ entryFk,
+ landed,
+ `in`,
+ `out`,
+ warehouse,
+ buyingValue,
+ balance
+ FROM tSupplierPackaging
+ WHERE NOT (NOT balance AND landed < CURDATE() - INTERVAL 1 YEAR);
+
+ DROP TEMPORARY TABLE tSupplierPackaging;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/supplier_checkBalance.sql b/db/routines/vn/procedures/supplier_checkBalance.sql
new file mode 100644
index 000000000..04c513927
--- /dev/null
+++ b/db/routines/vn/procedures/supplier_checkBalance.sql
@@ -0,0 +1,74 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_checkBalance`(IN vDateTo DATETIME, IN vIsConciliated BOOL)
+BEGIN
+/**
+ * Compara los datos de nuestros proveedores con
+ * los que hay en la base de datos de sage
+ *
+ * @param vDateTo
+ * @param vIsConciliated
+ * @table tmp.ledgerComparative (id, date, account, debit, credit, companyFk)
+ */
+ DECLARE vDateFrom DATE;
+ DECLARE vMaxTolerance DECIMAL(10,2);
+ SET vDateTo = TIMESTAMP(vDateTo,'23:59:59');
+ SELECT util.firstDayOfYear(vDateTo) INTO vDateFrom;
+ SELECT maxTolerance INTO vMaxTolerance
+ FROM vn.ledgerConfig;
+
+ SELECT c.code,
+ s.id supplierFk,
+ s.account,
+ sub1.mysql,
+ sub1.sage,
+ sub1.mysql - sub1.sage difference,
+ sub1.companyFk,
+ s.name
+ FROM supplier s
+ JOIN (SELECT companyFk,
+ supplierFk,
+ CAST(ROUND(SUM(mysql),2) AS DECIMAL(10,2)) mysql,
+ CAST(ROUND(SUM(sage),2) AS DECIMAL(10,2)) sage
+ FROM (SELECT companyFk,
+ supplierFk,
+ - SUM(iid.amount) mysql,
+ 0 sage
+ FROM invoiceInDueDay iid
+ JOIN invoiceIn ii ON ii.id = iid.invoiceInFk
+ WHERE IFNULL(ii.bookEntried, ii.issued) BETWEEN vDateFrom AND vDateTo
+ AND ii.isBooked
+ GROUP BY ii.id
+ UNION ALL
+ SELECT p.companyFk,
+ p.supplierFk,
+ p.amount,
+ 0
+ FROM payment p
+ JOIN payMethod pm ON pm.id = p.payMethodFk
+ WHERE p.received BETWEEN vDateFrom AND vDateTo
+ AND IF(vIsConciliated, p.isConciliated, TRUE) = TRUE
+ AND NOT pm.code <=>'previousBalance'
+ UNION ALL
+ SELECT se.companyFk,
+ se.supplierFk,
+ - se.amount,
+ 0
+ FROM supplierExpense se
+ WHERE se.dated BETWEEN vDateFrom AND vDateTo
+ AND IF(vIsConciliated, se.isConciliated, TRUE) = TRUE
+ UNION ALL
+ SELECT lc.companyFk,
+ s.id,
+ 0,
+ - (IFNULL(lc.debit, 0) - IFNULL(lc.credit, 0))
+ FROM tmp.ledgerComparative lc
+ JOIN supplier s ON s.account = lc.account
+ WHERE lc.`date` BETWEEN vDateFrom AND vDateTo
+ ) sub
+ GROUP BY companyFk, supplierFk
+ ) sub1 ON sub1.supplierFk = s.id
+ JOIN company c ON c.id = sub1.companyFk
+ HAVING ABS(difference) > vMaxTolerance
+ ORDER BY s.name;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/supplier_checkIsActive.sql b/db/routines/vn/procedures/supplier_checkIsActive.sql
new file mode 100644
index 000000000..9dcb6452a
--- /dev/null
+++ b/db/routines/vn/procedures/supplier_checkIsActive.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_checkIsActive`(vSelf INT)
+BEGIN
+/**
+ * Comprueba si un proveedor esta activo.
+ */
+ DECLARE vIsActive BOOL;
+
+ SELECT isActive INTO vIsActive
+ FROM vn.supplier
+ WHERE id = vSelf;
+
+ IF NOT vIsActive THEN
+ CALL util.throw('INACTIVE_PROVIDER');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/supplier_disablePayMethodChecked.sql b/db/routines/vn/procedures/supplier_disablePayMethodChecked.sql
new file mode 100644
index 000000000..d486f6e86
--- /dev/null
+++ b/db/routines/vn/procedures/supplier_disablePayMethodChecked.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_disablePayMethodChecked`()
+BEGIN
+
+/*
+ * Deshabilita la comprobación de los datos bancarios de todos aquellos proveedores que tengan
+ * un número que no sea 0 en el campo graceMonthsDisableChecked de la tabla vn.payMethod
+ * y que no hayan recibido un pago desde el mes indicado
+ */
+
+ UPDATE vn.supplier s
+ JOIN ( SELECT p.supplierFk
+ FROM supplier s
+ JOIN payMethod pm ON pm.id = s.payMethodFk
+ JOIN (SELECT supplierFk,MAX(created) created
+ FROM payment
+ GROUP BY supplierFk) p ON p.supplierFk = s.id
+ WHERE p.created < (util.VN_CURDATE() - INTERVAL pm.graceMonthsDisableChecked MONTH)
+ AND pm.graceMonthsDisableChecked
+ AND s.isPayMethodChecked
+ GROUP BY p.supplierFk) sdpmc ON sdpmc.supplierFk = s.id
+ SET s.isPayMethodChecked = FALSE;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/supplier_statement.sql b/db/routines/vn/procedures/supplier_statement.sql
new file mode 100644
index 000000000..a03a7770c
--- /dev/null
+++ b/db/routines/vn/procedures/supplier_statement.sql
@@ -0,0 +1,139 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_statement`(
+ vSupplierFk INT,
+ vCurrencyFk INT,
+ vCompanyFk INT,
+ vOrderBy VARCHAR(15),
+ vIsConciliated BOOL
+)
+BEGIN
+/**
+ * Crea un estado de cuenta de proveedores calculando
+ * los saldos en euros y en la moneda especificada.
+ *
+ * @param vSupplierFk Id del proveedor
+ * @param vCurrencyFk Id de la moneda
+ * @param vCompanyFk Id de la empresa
+ * @param vOrderBy Criterio de ordenación
+ * @param vIsConciliated Indica si está conciliado o no
+ * @return tmp.supplierStatement
+ */
+ SET @euroBalance:= 0;
+ SET @currencyBalance:= 0;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement
+ ENGINE = MEMORY
+ SELECT *,
+ @euroBalance:= ROUND(
+ @euroBalance + IFNULL(paymentEuros, 0) -
+ IFNULL(invoiceEuros, 0), 2
+ ) euroBalance,
+ @currencyBalance:= ROUND(
+ @currencyBalance + IFNULL(paymentCurrency, 0) -
+ IFNULL(invoiceCurrency, 0), 2
+ ) currencyBalance
+ FROM (
+ SELECT * FROM
+ (
+ SELECT NULL bankFk,
+ ii.companyFk,
+ ii.serial,
+ ii.id,
+ CASE
+ WHEN vOrderBy = 'issued' THEN ii.issued
+ WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried
+ WHEN vOrderBy = 'booked' THEN ii.booked
+ WHEN vOrderBy = 'dueDate' THEN iid.dueDated
+ END dated,
+ CONCAT('S/Fra ', ii.supplierRef) sref,
+ IF(ii.currencyFk > 1,
+ ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3),
+ NULL
+ ) changeValue,
+ CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros,
+ CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency,
+ NULL paymentEuros,
+ NULL paymentCurrency,
+ ii.currencyFk,
+ ii.isBooked,
+ c.code,
+ 'invoiceIn' statementType
+ FROM invoiceIn ii
+ JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
+ JOIN currency c ON c.id = ii.currencyFk
+ WHERE ii.issued > '2014-12-31'
+ AND ii.supplierFk = vSupplierFk
+ AND vCurrencyFk IN (ii.currencyFk, 0)
+ AND vCompanyFk IN (ii.companyFk, 0)
+ AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated)
+ GROUP BY iid.id
+ UNION ALL
+ SELECT p.bankFk,
+ p.companyFk,
+ NULL,
+ p.id,
+ CASE
+ WHEN vOrderBy = 'issued' THEN p.received
+ WHEN vOrderBy = 'bookEntried' THEN p.received
+ WHEN vOrderBy = 'booked' THEN p.received
+ WHEN vOrderBy = 'dueDate' THEN p.dueDated
+ END,
+ CONCAT(IFNULL(pm.name, ''),
+ IF(pn.concept <> '',
+ CONCAT(' : ', pn.concept),
+ '')
+ ),
+ IF(p.currencyFk > 1, p.divisa / p.amount, NULL),
+ NULL,
+ NULL,
+ p.amount,
+ p.divisa,
+ p.currencyFk,
+ p.isConciliated,
+ c.code,
+ 'payment'
+ FROM payment p
+ LEFT JOIN currency c ON c.id = p.currencyFk
+ LEFT JOIN accounting a ON a.id = p.bankFk
+ LEFT JOIN payMethod pm ON pm.id = p.payMethodFk
+ LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id
+ WHERE p.received > '2014-12-31'
+ AND p.supplierFk = vSupplierFk
+ AND vCurrencyFk IN (p.currencyFk, 0)
+ AND vCompanyFk IN (p.companyFk, 0)
+ AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated)
+ UNION ALL
+ SELECT NULL,
+ companyFk,
+ NULL,
+ se.id,
+ CASE
+ WHEN vOrderBy = 'issued' THEN se.dated
+ WHEN vOrderBy = 'bookEntried' THEN se.dated
+ WHEN vOrderBy = 'booked' THEN se.dated
+ WHEN vOrderBy = 'dueDate' THEN se.dueDated
+ END,
+ se.description,
+ 1,
+ amount,
+ NULL,
+ NULL,
+ NULL,
+ currencyFk,
+ isConciliated,
+ c.`code`,
+ 'expense'
+ FROM supplierExpense se
+ JOIN currency c ON c.id = se.currencyFk
+ WHERE se.supplierFk = vSupplierFk
+ AND vCurrencyFk IN (se.currencyFk,0)
+ AND vCompanyFk IN (se.companyFk,0)
+ AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated)
+ ) sub
+ ORDER BY (dated IS NULL AND NOT isBooked),
+ dated,
+ IF(vOrderBy = 'dueDate', id, NULL)
+ LIMIT 10000000000000000000
+ ) t;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketBoxesView.sql b/db/routines/vn/procedures/ticketBoxesView.sql
new file mode 100644
index 000000000..d5fcef226
--- /dev/null
+++ b/db/routines/vn/procedures/ticketBoxesView.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketBoxesView`(IN vTicketFk INT)
+BEGIN
+
+ SELECT s.id,
+ s.itemFk,
+ s.concept,
+ floor(s.quantity / b.packing) as Cajas,
+ b.packing,
+ s.isPicked,
+ i.size
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk
+ JOIN buy b on b.id = lb.buy_id
+ JOIN packaging p on p.id = b.packagingFk
+ WHERE s.quantity >= b.packing
+ AND t.id = vTicketFk
+ AND p.isBox
+ GROUP BY s.itemFk;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketBuiltTime.sql b/db/routines/vn/procedures/ticketBuiltTime.sql
new file mode 100644
index 000000000..936e872ab
--- /dev/null
+++ b/db/routines/vn/procedures/ticketBuiltTime.sql
@@ -0,0 +1,38 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketBuiltTime`(vDate DATE)
+BEGIN
+
+ DECLARE vDateStart DATETIME DEFAULT DATE(vDate);
+ DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketBuiltTime;
+
+ CREATE TEMPORARY TABLE tmp.ticketBuiltTime
+ ENGINE = MEMORY
+ SELECT t.id as ticketFk ,t.shipped, IFNULL(builtTime, vDateEnd) as builtTime
+ FROM
+ vn.ticket t
+ LEFT JOIN
+ (
+ SELECT ticketFk, builtTime
+ FROM
+ (
+ SELECT
+ ticketFk,
+ created as builtTime
+ FROM
+ ticketTracking
+ WHERE created BETWEEN vDateStart AND vDateEnd
+ ORDER BY ticketFk, created DESC
+ LIMIT 10000000000000000000
+ ) sub
+ GROUP BY ticketFk
+ ) sub2 ON sub2.ticketFk = t.id
+ WHERE t.shipped BETWEEN vDate AND util.dayEnd(vDate)
+ AND t.clientFk NOT IN (50,400,200)
+ AND t.companyFk = 442
+
+ ;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketCalculateClon.sql b/db/routines/vn/procedures/ticketCalculateClon.sql
new file mode 100644
index 000000000..7ded84f45
--- /dev/null
+++ b/db/routines/vn/procedures/ticketCalculateClon.sql
@@ -0,0 +1,37 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT)
+BEGIN
+/*
+ * Recalcula los componentes un ticket clonado,
+ * las lineas a precio cero fuerza para que tengan precio, el resto lo respeta
+ * @param vTicketNew nuevo ticket clonado
+ * @param vTicketOld icket original, a partir del qual se clonara el nuevo
+*/
+
+ REPLACE INTO orderTicket(orderFk,ticketFk)
+ SELECT orderFk, vTicketNew
+ FROM orderTicket
+ WHERE ticketFk = vTicketOld;
+
+ -- Bionizamos lineas con Preu = 0
+ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
+ (PRIMARY KEY (id)) ENGINE = MEMORY
+ SELECT id
+ FROM sale
+ WHERE ticketFk = vTicketNew AND price = 0;
+
+ CALL sale_recalcComponent('renewPrices');
+
+ -- Bionizamos lineas con Preu > 0
+ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
+ (PRIMARY KEY (id)) ENGINE = MEMORY
+ SELECT id
+ FROM sale
+ WHERE ticketFk = vTicketNew AND price > 0;
+
+ CALL sale_recalcComponent('imbalance');
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketCalculateFromType.sql b/db/routines/vn/procedures/ticketCalculateFromType.sql
new file mode 100644
index 000000000..63f4b8941
--- /dev/null
+++ b/db/routines/vn/procedures/ticketCalculateFromType.sql
@@ -0,0 +1,18 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketCalculateFromType`( vLanded DATE,
+ vAddressFk INT,
+ vAgencyModeFk INT,
+ vTypeFk INT)
+BEGIN
+ DROP TEMPORARY TABLE IF EXISTS tmp.item;
+ CREATE TEMPORARY TABLE tmp.item
+ (INDEX (itemFk))
+ ENGINE = MEMORY
+ SELECT id itemFk FROM vn.item
+ WHERE typeFk = vTypeFk;
+
+ CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk, FALSE);
+ DROP TEMPORARY TABLE tmp.item;
+ DROP TEMPORARY TABLE tmp.ticketLot;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketCalculatePurge.sql b/db/routines/vn/procedures/ticketCalculatePurge.sql
new file mode 100644
index 000000000..86e3b0d1b
--- /dev/null
+++ b/db/routines/vn/procedures/ticketCalculatePurge.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketCalculatePurge`()
+BEGIN
+ DROP TEMPORARY TABLE
+ tmp.ticketCalculateItem,
+ tmp.ticketComponentPrice,
+ tmp.ticketComponent,
+ tmp.ticketLot,
+ tmp.zoneGetShipped;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketClon.sql b/db/routines/vn/procedures/ticketClon.sql
new file mode 100644
index 000000000..9144ac709
--- /dev/null
+++ b/db/routines/vn/procedures/ticketClon.sql
@@ -0,0 +1,10 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketClon`(vTicketFk INT, vNewShipped DATE)
+BEGIN
+
+ DECLARE vNewTicketFk INT;
+
+ CALL ticket_cloneAll(vTicketFk, vNewShipped, TRUE, vNewTicketFk);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketClon_OneYear.sql b/db/routines/vn/procedures/ticketClon_OneYear.sql
new file mode 100644
index 000000000..b0c08dec8
--- /dev/null
+++ b/db/routines/vn/procedures/ticketClon_OneYear.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketClon_OneYear`(vTicketFk INT)
+BEGIN
+
+ DECLARE vShipped DATE;
+ DECLARE vMaxDated DATE;
+
+ SELECT shipped, TIMESTAMPADD(YEAR,1,shipped)
+ INTO vShipped, vMaxDated
+ FROM vn.ticket
+ WHERE id = vTicketFk;
+
+ WHILE vShipped <= vMaxDated DO
+
+ SET vShipped = TIMESTAMPADD(WEEK, 1, vShipped);
+
+ CALL vn.ticketClon(vTicketFk, vShipped);
+
+ END WHILE;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketCollection_get.sql b/db/routines/vn/procedures/ticketCollection_get.sql
new file mode 100644
index 000000000..357471fee
--- /dev/null
+++ b/db/routines/vn/procedures/ticketCollection_get.sql
@@ -0,0 +1,10 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketCollection_get`(vTicketFk INT)
+BEGIN
+
+ SELECT tc.collectionFk
+ FROM vn.ticketCollection tc
+ WHERE ticketFk = vTicketFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketCollection_setUsedShelves.sql b/db/routines/vn/procedures/ticketCollection_setUsedShelves.sql
new file mode 100644
index 000000000..c69575ba7
--- /dev/null
+++ b/db/routines/vn/procedures/ticketCollection_setUsedShelves.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketCollection_setUsedShelves`(vTicketFk INT, vUsedShelves INT)
+BEGIN
+
+ /*
+ * Inserta número de baldas que ocupa un ticket
+ *
+ * @param vTicketFk Identificador de ticket
+ * @param vUsedShelves Número de baldas
+ */
+
+ UPDATE ticketCollection tc
+ SET tc.usedShelves = vUsedShelves
+ WHERE tc.ticketFk = vTicketFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketComponentUpdate.sql b/db/routines/vn/procedures/ticketComponentUpdate.sql
new file mode 100644
index 000000000..bdb3bf6cb
--- /dev/null
+++ b/db/routines/vn/procedures/ticketComponentUpdate.sql
@@ -0,0 +1,62 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketComponentUpdate`(
+ vTicketFk INT,
+ vClientFk INT,
+ vAgencyModeFk INT,
+ vAddressFk INT,
+ vWarehouseFk TINYINT,
+ vCompanyFk SMALLINT,
+ vShipped DATETIME,
+ vLanded DATE,
+ vIsDeleted BOOLEAN,
+ vHasToBeUnrouted BOOLEAN,
+ vOption VARCHAR(25))
+BEGIN
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN
+
+ UPDATE ticket t
+ JOIN address a ON a.id = vAddressFk
+ SET t.nickname = a.nickname
+ WHERE t.id = vTicketFk;
+ END IF;
+
+ UPDATE ticket t
+ SET
+ t.clientFk = vClientFk,
+ t.agencyModeFk = vAgencyModeFk,
+ t.addressFk = vAddressFk,
+ t.warehouseFk = vWarehouseFk,
+ t.companyFk = vCompanyFk,
+ t.landed = vLanded,
+ t.shipped = vShipped,
+ t.isDeleted = vIsDeleted
+ WHERE
+ t.id = vTicketFk;
+
+ IF vHasToBeUnrouted THEN
+ UPDATE ticket t SET t.routeFk = NULL
+ WHERE t.id = vTicketFk;
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.sale;
+ CREATE TEMPORARY TABLE tmp.sale
+ (PRIMARY KEY (saleFk))
+ ENGINE = MEMORY
+ SELECT id AS saleFk, vWarehouseFk warehouseFk
+ FROM sale s WHERE s.ticketFk = vTicketFk;
+
+ CALL ticketComponentUpdateSale (vOption);
+
+ DROP TEMPORARY TABLE tmp.sale;
+ COMMIT;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketComponentUpdateSale.sql b/db/routines/vn/procedures/ticketComponentUpdateSale.sql
new file mode 100644
index 000000000..d002655d1
--- /dev/null
+++ b/db/routines/vn/procedures/ticketComponentUpdateSale.sql
@@ -0,0 +1,111 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketComponentUpdateSale`(vCode VARCHAR(25))
+BEGIN
+/**
+ * A partir de la tabla tmp.sale, crea los Movimientos_componentes
+ * y modifica el campo Preu de la tabla Movimientos
+ *
+ * @param i_option integer tipo de actualizacion
+ * @param table tmp.sale tabla memory con el campo saleFk, warehouseFk
+ **/
+ DECLARE vComponentFk INT;
+
+ IF vCode <> 'renewPrices' THEN
+ SELECT id INTO vComponentFk FROM component WHERE `code` = vCode;
+ END IF;
+
+ DELETE sc.*
+ FROM tmp.sale tmps
+ JOIN saleComponent sc ON sc.saleFk = tmps.saleFk
+ JOIN `component` c ON c.id = sc.componentFk
+ WHERE c.isRenewable;
+
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, tc.componentFk, tc.cost
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ AND sc.componentFk = tc.componentFk
+ LEFT JOIN `component` c ON c.id = tc.componentFk
+ WHERE IF(sc.componentFk IS NULL AND NOT c.isRenewable, FALSE, TRUE);
+
+ -- Añadir componente venta por paquete
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT t.id, t.componentFk, t.cost
+ FROM (
+ SELECT s.id, tc.componentFk, tc.cost, MOD(s.quantity, b.packing) as resto
+ FROM vn.sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id
+ JOIN vn.buy b ON b.id = buy_id
+ JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
+ JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage'
+ LEFT JOIN (
+ SELECT s.id
+ FROM vn.sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
+ JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk
+ JOIN `component` c ON c.id = sc.componentFk AND c.code = 'lastUnitsDiscount'
+ ) tp ON tp.id = s.id
+ WHERE tp.id IS NULL
+ HAVING resto <> 0) t;
+
+ IF vCode <> 'renewPrices' THEN
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, vComponentFk, ROUND((s.price * (100 - s.discount) / 100) - SUM(sc.value), 3) dif
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ WHERE sc.saleFk <> vComponentFk
+ GROUP BY s.id
+ HAVING dif <> 0;
+ ELSE
+ UPDATE sale s
+ JOIN item i on i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk
+ FROM saleComponent sc
+ JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
+ GROUP BY sc.saleFk) sc ON sc.saleFk = s.id
+ SET s.price = sumValue / ((100 - s.discount) / 100)
+ WHERE it.code != 'PRT' ;
+
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, 21, ROUND((s.price * (100 - s.discount) / 100) - SUM(value), 3) saleValue
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ WHERE sc.componentFk != 21
+ GROUP BY s.id
+ HAVING ROUND(saleValue, 4) <> 0;
+ END IF;
+
+ UPDATE sale s
+ JOIN (
+ SELECT SUM(sc.value) sumValue, sc.saleFk
+ FROM saleComponent sc
+ JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
+ JOIN `component` c ON c.id = sc.componentFk
+ JOIN componentType ct on ct.id = c.typeFk AND ct.isBase
+ GROUP BY sc.saleFk) sc ON sc.saleFk = s.id
+ SET s.priceFixed = sumValue, s.isPriceFixed = 1;
+
+ DELETE sc.*
+ FROM saleComponent sc
+ JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
+ JOIN sale s on s.id = sc.saleFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ WHERE it.code = 'PRT';
+
+ INSERT INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, 15, s.price
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ JOIN item i ON i.id = s.itemFK
+ JOIN itemType it ON it.id = i.typeFk
+ WHERE it.code = 'PRT' AND s.price > 0;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketDown_PrintableSelection.sql b/db/routines/vn/procedures/ticketDown_PrintableSelection.sql
new file mode 100644
index 000000000..45002dd1f
--- /dev/null
+++ b/db/routines/vn/procedures/ticketDown_PrintableSelection.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketDown_PrintableSelection`(vSectorFk INT)
+BEGIN
+
+ UPDATE vn.ticketDown td
+ JOIN
+ (SELECT DISTINCT t.id
+ FROM vn.ticket t
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id
+ JOIN vn.itemShelving ish ON ish.id = iss.itemShelvingFk
+ JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.parking p ON p.id = sh.parkingFk
+ WHERE p.sectorFk = vSectorFk
+ ) sub ON sub.id = td.ticketFk
+ JOIN vn.ticketDown_SelectionType tdst ON tdst.description = 'FREE'
+ JOIN vn.ticketDown_SelectionType tdst2 ON tdst2.description = 'SELECTED'
+ SET td.selected = tdst2.id
+ WHERE td.selected = tdst.id;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketGetTaxAdd.sql b/db/routines/vn/procedures/ticketGetTaxAdd.sql
new file mode 100644
index 000000000..55f587d9d
--- /dev/null
+++ b/db/routines/vn/procedures/ticketGetTaxAdd.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketGetTaxAdd`(vTicketFk INT)
+BEGIN
+/**
+ * Añade un ticket a la tabla tmp.ticket para calcular
+ * el IVA y el recargo de equivalencia y devuelve el resultado.
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
+ CREATE TEMPORARY TABLE tmp.ticket
+ ENGINE = MEMORY
+ SELECT vTicketFk ticketFk;
+
+ CALL vn.ticket_getTax(NULL);
+
+ SELECT
+ tt.ticketFk,
+ CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase,
+ CAST(tt.rate * tt.taxableBase / 100 AS DECIMAL(10, 2)) AS tax,
+ pgc.*,
+ CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base,
+ pgc.rate / 100 as vatPercent
+ FROM tmp.ticketTax tt
+ JOIN vn.pgc ON pgc.code = tt.pgcFk
+ LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code;
+
+ DROP TEMPORARY TABLE tmp.ticket;
+ DROP TEMPORARY TABLE tmp.ticketTax;
+ DROP TEMPORARY TABLE tmp.ticketAmount;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketGetTax_new.sql b/db/routines/vn/procedures/ticketGetTax_new.sql
new file mode 100644
index 000000000..f7c5891cc
--- /dev/null
+++ b/db/routines/vn/procedures/ticketGetTax_new.sql
@@ -0,0 +1,66 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketGetTax_new`()
+ READS SQL DATA
+BEGIN
+/**
+ * Calcula la base imponible, el IVA y el recargo de equivalencia para
+ * un conjunto de tickets.
+ *
+ * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
+ * @return tmp.ticketTax Impuesto desglosado para cada ticket
+ * @return tmp.ticketAmount
+ */
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
+ CREATE TEMPORARY TABLE tmp.addressCompany
+ (INDEX (addressFk, companyFk))
+ ENGINE = MEMORY
+ SELECT DISTINCT t.addressFk, t.companyFk
+ FROM tmp.ticket tmpTicket
+ JOIN ticket t ON t.id = tmpTicket.ticketFk;
+
+ CALL addressTaxArea ();
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
+ CREATE TEMPORARY TABLE tmp.ticketTax
+ (INDEX (ticketFk))
+ ENGINE = MEMORY
+ SELECT tmpTicket.ticketFk,
+ bp.pgcFk,
+ SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)
+ ) AS taxableBase,
+ SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)
+ ) * pgc.rate / 100 AS tax,
+ tc.code
+
+ FROM tmp.ticket tmpTicket
+ JOIN sale s ON s.ticketFk = tmpTicket.ticketFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticket t ON t.id = tmpTicket.ticketFk
+ JOIN supplier su ON su.id = t.companyFk
+ JOIN tmp.addressTaxArea ata
+ ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk
+ JOIN itemTaxCountry itc
+ ON itc.itemFk = i.id AND itc.countryFk = su.countryFk
+ JOIN bookingPlanner bp
+ ON bp.countryFk = su.countryFk
+ AND bp.taxAreaFk = ata.areaFk
+ AND bp.taxClassFk = itc.taxClassFk
+ JOIN pgc ON pgc.code = bp.pgcFk
+ JOIN taxClass tc ON tc.id = bp.taxClassFk
+ GROUP BY tmpTicket.ticketFk, pgc.code
+ HAVING taxableBase != 0;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount;
+ CREATE TEMPORARY TABLE tmp.ticketAmount
+ (INDEX (ticketFk))
+ ENGINE = MEMORY
+ SELECT ticketFk, taxableBase, SUM(tax) tax
+ FROM tmp.ticketTax
+ GROUP BY ticketFk, code;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
+ DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketGetTotal.sql b/db/routines/vn/procedures/ticketGetTotal.sql
new file mode 100644
index 000000000..b77f261b0
--- /dev/null
+++ b/db/routines/vn/procedures/ticketGetTotal.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketGetTotal`(vTaxArea VARCHAR(25))
+BEGIN
+/**
+ * Calcula el total con IVA para un conjunto de tickets.
+ *
+ * @param vTaxArea
+ * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
+ * @return tmp.ticketTotal Total para cada ticket
+ */
+ CALL ticket_getTax(vTaxArea);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal;
+ CREATE TEMPORARY TABLE tmp.ticketTotal
+ (INDEX (ticketFk))
+ ENGINE = MEMORY
+ SELECT t.ticketFk,
+ IFNULL(SUM(ta.taxableBase + ta.tax), 0.0) AS total,
+ SUM(ta.taxableBase) totalWithoutVat
+ FROM tmp.ticket t
+ LEFT JOIN tmp.ticketAmount ta ON t.ticketFk = ta.ticketFk
+ GROUP BY ticketFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount;
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketGetVisibleAvailable.sql b/db/routines/vn/procedures/ticketGetVisibleAvailable.sql
new file mode 100644
index 000000000..07dfa69e5
--- /dev/null
+++ b/db/routines/vn/procedures/ticketGetVisibleAvailable.sql
@@ -0,0 +1,33 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketGetVisibleAvailable`(
+ vTicket INT)
+BEGIN
+ DECLARE vVisibleCalc INT;
+ DECLARE vAvailableCalc INT;
+ DECLARE vShipped DATE;
+ DECLARE vWarehouse TINYINT;
+ DECLARE vAlertLevel INT;
+
+ SELECT t.warehouseFk, t.shipped, ts.alertLevel INTO vWarehouse, vShipped, vAlertLevel
+ FROM ticket t
+ LEFT JOIN ticketState ts ON ts.ticketFk = vTicket
+ WHERE t.id = vTicket;
+
+ IF vAlertLevel IS NULL OR vAlertLevel = 0 THEN
+ IF vShipped >= util.VN_CURDATE() THEN
+ CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped);
+ END IF;
+ IF vShipped = util.VN_CURDATE() THEN
+ CALL cache.visible_refresh(vVisibleCalc, FALSE, vWarehouse);
+ END IF;
+ END IF;
+
+ SELECT s.id, s.itemFk, s.quantity, s.concept, s.price, s.reserved, s.discount, v.visible, av.available, it.image, it.subName
+ FROM sale s
+ LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCalc
+ LEFT JOIN cache.available av ON av.item_id = s.itemFk AND av.calc_id = vAvailableCalc
+ LEFT JOIN item it ON it.id = s.itemFk
+ WHERE s.ticketFk = vTicket
+ ORDER BY s.concept;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketMissed_List.sql b/db/routines/vn/procedures/ticketMissed_List.sql
new file mode 100644
index 000000000..6b0f66e6a
--- /dev/null
+++ b/db/routines/vn/procedures/ticketMissed_List.sql
@@ -0,0 +1,49 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketMissed_List`(vTicketFk INT)
+BEGIN
+
+ DECLARE vParkingFk INT;
+ DECLARE vParked DATETIME;
+ DECLARE vLevel INT;
+ DECLARE vCollectionFk INT;
+
+ SELECT IFNULL(`level`,0), IFNULL(collectionFk,0)
+ INTO vLevel, vCollectionFk
+ FROM vn.ticketCollection
+ WHERE ticketFk = vTicketFk
+ LIMIT 1;
+
+ SELECT created, parkingFk
+ INTO vParked, vParkingFk
+ FROM vn.ticketParking
+ WHERE ticketFk = vTicketFk;
+
+ SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia
+ FROM vn.ticketParking tp
+ JOIN vn.parking p ON p.id = tp.parkingFk
+ JOIN vn.sector sc ON sc.id = p.sectorFk
+ LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk
+ JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk
+ JOIN vn.ticket t ON t.id = tp.ticketFk
+ JOIN vn.zone z ON z.id = t.zoneFk
+ JOIN vn.agencyMode am ON am.id = z.agencyModeFk
+ JOIN vn.state s ON s.id = tst.state
+ WHERE (s.alertLevel < 2
+ AND tp.parkingFk = vParkingFk
+ AND sc.isPackagingArea
+ AND (
+ (
+ ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked )
+ OR
+ ( tc.collectionFk = vCollectionFk AND LEFT(tc.level,1) < LEFT(vLevel,1) )
+ )
+ )) -- Etiquetas que no se han escaneado y ya estamos con una posterior
+ OR
+ (s.alertLevel > 1
+ AND tp.parkingFk = vParkingFk
+ AND sc.isPackagingArea
+ AND tp.created < vParked
+ AND t.packages <=> 0);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketNotInvoicedByClient.sql b/db/routines/vn/procedures/ticketNotInvoicedByClient.sql
new file mode 100644
index 000000000..cb177b6d0
--- /dev/null
+++ b/db/routines/vn/procedures/ticketNotInvoicedByClient.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketNotInvoicedByClient`(vClientFk INT)
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
+
+ CREATE TEMPORARY TABLE tmp.ticket
+ SELECT id ticketFk
+ FROM ticket
+ WHERE refFk IS NULL
+ AND clientFk = vClientFk
+ AND shipped > '2001-01-01';
+
+ CALL vn.ticketGetTotal(NULL);
+
+ SELECT c.id,
+ c.name as Cliente,
+ t.shipped as Fecha,
+ t.id as Id_Ticket,
+ CAST(tt.total AS DECIMAL(10,2)) as Importe
+ FROM tmp.ticketTotal tt
+ JOIN ticket t ON t.id = tt.ticketFk
+ JOIN client c ON c.id = t.ClientFk;
+
+ DROP TEMPORARY TABLE
+ tmp.ticket,
+ tmp.ticketTotal;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketObservation_addNewBorn.sql b/db/routines/vn/procedures/ticketObservation_addNewBorn.sql
new file mode 100644
index 000000000..f70a11a48
--- /dev/null
+++ b/db/routines/vn/procedures/ticketObservation_addNewBorn.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketObservation_addNewBorn`(vTicketFk INT)
+BEGIN
+
+ /**
+ * Inserta observaciones para los tickets con clientes nuevos o recuperados
+ *
+ * @param vTicketFk Identificador de vn.ticket
+ */
+
+ DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! ';
+
+ INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description)
+ SELECT vTicketFk, ot.id, vDescription
+ FROM vn.observationType ot
+ WHERE ot.hasNewBornMessage
+ ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description);
+
+END$$
+DELIMITER ;
diff --git a/db/.archive/231001/03-ticketPackaging_add.sql b/db/routines/vn/procedures/ticketPackaging_add.sql
similarity index 98%
rename from db/.archive/231001/03-ticketPackaging_add.sql
rename to db/routines/vn/procedures/ticketPackaging_add.sql
index a7cf1d1d3..d669b95f5 100644
--- a/db/.archive/231001/03-ticketPackaging_add.sql
+++ b/db/routines/vn/procedures/ticketPackaging_add.sql
@@ -1,7 +1,4 @@
-DROP PROCEDURE IF EXISTS `vn`.`ticketPackaging_add`;
-
DELIMITER $$
-$$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketPackaging_add`(
vClientFk INT,
vDated DATE,
@@ -138,4 +135,4 @@ BEGIN
DROP TEMPORARY TABLE tmp.packagingToInvoice;
END$$
-DELIMITER ;
\ No newline at end of file
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketParking_findSkipped.sql b/db/routines/vn/procedures/ticketParking_findSkipped.sql
new file mode 100644
index 000000000..b00006ffe
--- /dev/null
+++ b/db/routines/vn/procedures/ticketParking_findSkipped.sql
@@ -0,0 +1,64 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1))
+BEGIN
+
+/**
+ * Averigua los tickets que se han saltado por un error en el proceso encajado
+ * @param vTicketFk Ticket
+ * @param vItemPackingTypeFk Modo de encajado
+ * @return un select con los tickets afectados
+ */
+
+ DECLARE vParkingFk INT;
+ DECLARE vParked DATETIME;
+ DECLARE vLevel INT;
+ DECLARE vWagon INT;
+ DECLARE vCollectionFk INT;
+
+ SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0)
+ INTO vLevel, vWagon, vCollectionFk
+ FROM vn.ticketCollection tc
+ JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk
+ WHERE ticketFk = vTicketFk
+ ORDER BY c.id DESC
+ LIMIT 1;
+
+ SELECT created, parkingFk
+ INTO vParked, vParkingFk
+ FROM vn.ticketParking tp
+ JOIN vn.parking p ON p.id = tp.parkingFk
+ JOIN vn.sector s ON s.id = p.sectorFk
+ WHERE ticketFk = vTicketFk
+ AND s.itemPackingTypeFk = vItemPackingTypeFk
+ AND s.isPackagingArea ;
+
+ SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia
+ FROM vn.ticketParking tp
+ JOIN vn.parking p ON p.id = tp.parkingFk
+ JOIN vn.sector sc ON sc.id = p.sectorFk
+ LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk
+ JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk
+ JOIN vn.ticket t ON t.id = tp.ticketFk
+ JOIN vn.zone z ON z.id = t.zoneFk
+ JOIN vn.agencyMode am ON am.id = z.agencyModeFk
+ JOIN vn.state s ON s.id = tst.state
+ WHERE (s.alertLevel < 2
+ AND tp.parkingFk = vParkingFk
+ AND sc.isPackagingArea
+ AND (
+ ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked )
+ OR
+ ( tc.collectionFk = vCollectionFk
+ AND (LEFT(tc.wagon,1) < LEFT(vWagon,1)
+ OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1)))
+ )
+ )
+ ) -- Etiquetas que no se han escaneado y ya estamos con una posterior
+ OR
+ (s.alertLevel > 1
+ AND tp.parkingFk = vParkingFk
+ AND sc.isPackagingArea
+ AND tp.created < vParked
+ AND t.packages <=> 0);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketRefund_beforeUpsert.sql b/db/routines/vn/procedures/ticketRefund_beforeUpsert.sql
new file mode 100644
index 000000000..5a0e99318
--- /dev/null
+++ b/db/routines/vn/procedures/ticketRefund_beforeUpsert.sql
@@ -0,0 +1,18 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketRefund_beforeUpsert`(vRefundTicketFk INT, vOriginalTicketFk INT)
+BEGIN
+ DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE;
+
+ IF vRefundTicketFk = vOriginalTicketFk THEN
+ CALL util.throw('Original ticket and refund ticket has same id');
+ END IF;
+
+ SELECT COUNT(*) INTO vAlreadyExists
+ FROM ticketRefund
+ WHERE refundTicketFk = vOriginalTicketFk;
+
+ IF vAlreadyExists > 0 THEN
+ CALL util.throw('This ticket is already a refund');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketRequest_Add.sql b/db/routines/vn/procedures/ticketRequest_Add.sql
new file mode 100644
index 000000000..5ba347fef
--- /dev/null
+++ b/db/routines/vn/procedures/ticketRequest_Add.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketRequest_Add`(vDescription VARCHAR(255), vQuantity INT, vPrice DOUBLE, vTicketFk INT, vBuyerCode VARCHAR(3))
+BEGIN
+
+ INSERT INTO vn.ticketRequest(description,
+ quantity,
+ price,
+ ticketFk,
+ buyerCode,
+ requesterFk)
+ VALUES(vDescription,
+ vQuantity,
+ vPrice,
+ vTicketFk,
+ vBuyerCode,
+ vn.getUser());
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketStateToday_setState.sql b/db/routines/vn/procedures/ticketStateToday_setState.sql
new file mode 100644
index 000000000..73a92bbb5
--- /dev/null
+++ b/db/routines/vn/procedures/ticketStateToday_setState.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45))
+BEGIN
+
+ /* Modifica el estado de un ticket de hoy
+ *
+ * @param vTicketFk el id del ticket
+ * @param vStateCode estado a modificar del ticket
+ *
+ */
+
+ DECLARE vAlertLevel INT;
+
+ SELECT s.alertLevel INTO vAlertLevel
+ FROM state s
+ JOIN ticketStateToday tst ON tst.state = s.id
+ WHERE tst.ticketFk = vTicketFk
+ LIMIT 1;
+
+ IF vAlertLevel < 2 THEN
+
+ CALL vn.ticket_setState(vTicketFk, vStateCode);
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketStateUpdate.sql b/db/routines/vn/procedures/ticketStateUpdate.sql
new file mode 100644
index 000000000..4e19b7eb4
--- /dev/null
+++ b/db/routines/vn/procedures/ticketStateUpdate.sql
@@ -0,0 +1,26 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45))
+BEGIN
+
+ /*
+ * @deprecated:utilizar ticket_setState
+ */
+
+ DECLARE vAlertLevel INT;
+
+ SELECT s.alertLevel INTO vAlertLevel
+ FROM vn.state s
+ JOIN vn.ticketState ts ON ts.stateFk = s.id
+ WHERE ts.ticketFk = vTicketFk;
+
+ IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN
+
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
+ SELECT id, vTicketFk, account.myUser_getId()
+ FROM vn.state
+ WHERE `code` = vStateCode collate utf8_unicode_ci;
+
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketToInvoiceByAddress.sql b/db/routines/vn/procedures/ticketToInvoiceByAddress.sql
new file mode 100644
index 000000000..ad51c761a
--- /dev/null
+++ b/db/routines/vn/procedures/ticketToInvoiceByAddress.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketToInvoiceByAddress`(
+ vStarted DATE,
+ vEnded DATETIME,
+ vAddress INT,
+ vCompany INT
+ )
+BEGIN
+
+ SET vEnded = util.dayEnd(vEnded);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketToInvoice;
+
+ CREATE TEMPORARY TABLE tmp.ticketToInvoice
+ SELECT id
+ FROM vn.ticket
+ WHERE addressFk = vAddress
+ AND companyFk = vCompany
+ AND shipped BETWEEN vStarted AND vEnded
+ AND refFk IS NULL;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketToInvoiceByDate.sql b/db/routines/vn/procedures/ticketToInvoiceByDate.sql
new file mode 100644
index 000000000..8937ab7ae
--- /dev/null
+++ b/db/routines/vn/procedures/ticketToInvoiceByDate.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketToInvoiceByDate`(
+ vStarted DATE,
+ vEnded DATETIME,
+ vClient INT,
+ vCompany INT
+ )
+BEGIN
+
+ SET vEnded = util.dayEnd(vEnded);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketToInvoice;
+
+ CREATE TEMPORARY TABLE tmp.ticketToInvoice
+ SELECT id
+ FROM vn.ticket
+ WHERE clientFk = vClient
+ AND companyFk = vCompany
+ AND shipped BETWEEN vStarted AND vEnded
+ AND refFk IS NULL;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticketToInvoiceByRef.sql b/db/routines/vn/procedures/ticketToInvoiceByRef.sql
new file mode 100644
index 000000000..4f5c23ba2
--- /dev/null
+++ b/db/routines/vn/procedures/ticketToInvoiceByRef.sql
@@ -0,0 +1,47 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketToInvoiceByRef`(IN vInvoiceRef VARCHAR(15))
+BEGIN
+
+/* Para tickets ya facturados, vuelve a repetir el proceso de facturación.
+*
+* @param vInvoiceRef Factura
+*/
+
+ DECLARE vInvoice INT;
+ DECLARE vCountry INT;
+ DECLARE vTaxArea VARCHAR(15);
+ DECLARE vSpainCountryCode INT DEFAULT 1;
+
+ SELECT id
+ INTO vInvoice
+ FROM vn.invoiceOut
+ WHERE ref = vInvoiceRef;
+
+ SELECT s.countryFk
+ INTO vCountry
+ FROM vn.supplier s
+ JOIN vn.invoiceOut io ON io.companyFk = s.id
+ WHERE io.id = vInvoice;
+
+ SELECT IF(
+ c.isEqualizated
+ AND c.countryFk = vSpainCountryCode
+ AND i.taxAreaFk = 'NATIONAL',
+ 'EQU',
+ i.taxAreaFk
+ )
+ INTO vTaxArea
+ FROM vn.invoiceOutSerial i
+ JOIN vn.invoiceOut io ON io.serial = i.code
+ JOIN vn.client c ON c.id = io.clientFk
+ WHERE io.id = vInvoice;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketToInvoice;
+
+ CREATE TEMPORARY TABLE tmp.ticketToInvoice
+ SELECT id
+ FROM vn.ticket
+ WHERE refFk = vInvoiceRef;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_Clone.sql b/db/routines/vn/procedures/ticket_Clone.sql
new file mode 100644
index 000000000..7670e832e
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_Clone.sql
@@ -0,0 +1,61 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT)
+BEGIN
+/**
+ * Clona el contenido de un ticket en otro
+ *
+ * @param vOriginalTicket ticket Original
+ * @param vNewTicket ticket creado
+ */
+ DECLARE vStateFk INT;
+
+ INSERT INTO ticket (
+ clientFk,
+ shipped,
+ addressFk,
+ agencyModeFk,
+ nickname,
+ warehouseFk,
+ companyFk,
+ landed,
+ zoneFk,
+ zonePrice,
+ zoneBonus,
+ routeFk,
+ priority,
+ hasPriority,
+ clonedFrom
+ )
+ SELECT
+ clientFk,
+ shipped,
+ addressFk,
+ agencyModeFk,
+ nickname,
+ warehouseFk,
+ companyFk,
+ landed,
+ zoneFk,
+ zonePrice,
+ zoneBonus,
+ routeFk,
+ priority,
+ hasPriority,
+ vOriginalTicket
+ FROM ticket
+ WHERE id = vOriginalTicket;
+
+ SET vNewTicket = LAST_INSERT_ID();
+
+ INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
+ SELECT vNewTicket, observationTypeFk, description
+ FROM ticketObservation
+ WHERE ticketFk = vOriginalTicket;
+
+ INSERT INTO ticketTracking(ticketFk, stateFk, userFk, created)
+ SELECT vNewTicket, stateFk, userFk, created
+ FROM ticketTracking
+ WHERE ticketFk = vOriginalTicket
+ ORDER BY created;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_DelayTruck.sql b/db/routines/vn/procedures/ticket_DelayTruck.sql
new file mode 100644
index 000000000..7a3170d68
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_DelayTruck.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruck`(vWarehouserFk INT, vHour INT, vMinute INT)
+BEGIN
+ DECLARE done INT DEFAULT FALSE;
+ DECLARE vTicketFk INT;
+ DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tmp.ticket;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+ CALL vn.productionControl(vWarehouserFk,0) ;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
+ CREATE TEMPORARY TABLE tmp.ticket
+ SELECT ticketFk
+ FROM tmp.productionBuffer
+ WHERE shipped = util.VN_CURDATE()
+ AND problem LIKE '%I:%'
+ AND (HH <= vHour OR HH = vHour AND mm < vMinute)
+ AND alertLevel = 0;
+
+ OPEN cur1;
+
+ read_loop: LOOP
+ FETCH cur1 INTO vTicketFk;
+ IF done THEN
+ LEAVE read_loop;
+ END IF;
+
+ CALL vn.ticket_DelayTruckSplit(vTicketFk);
+ END LOOP;
+
+ CLOSE cur1;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql
new file mode 100644
index 000000000..c7de6a984
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql
@@ -0,0 +1,57 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruckSplit`(vTicketFk INT)
+BEGIN
+/**
+ * Splita las lineas de ticket que no estan ubicadas
+ *
+ * @param vTicketFk Id ticket
+ */
+ DECLARE vNewTicketFk INT;
+ DECLARE vTotalLines INT;
+ DECLARE vLinesToSplit INT;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit;
+
+ SELECT COUNT(*) INTO vTotalLines
+ FROM sale
+ WHERE ticketFk = vTicketFk;
+
+ CREATE TEMPORARY TABLE tmp.SalesToSplit
+ SELECT s.id saleFk
+ FROM ticket t
+ JOIN sale s ON t.id = s.ticketFk
+ LEFT JOIN (
+ SELECT ish.itemFk itemFk,
+ SUM(ish.visible) visible,
+ s.warehouseFk warehouseFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector s ON s.id = p.sectorFk
+ GROUP BY ish.itemFk,
+ s.warehouseFk
+ ) issw ON issw.itemFk = s.itemFk
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE s.quantity > IFNULL(issw.visible, 0)
+ AND s.quantity > 0
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND t.id = vTicketFk;
+
+ SELECT COUNT(*) INTO vLinesToSplit
+ FROM tmp.SalesToSplit;
+
+ IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN
+ SET vNewTicketFk = vTicketFk;
+ ELSE
+ CALL ticket_Clone(vTicketFk, vNewTicketFk);
+ UPDATE sale s
+ JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id
+ SET s.ticketFk = vNewTicketFk;
+ END IF;
+
+ CALL ticketStateUpdate(vNewTicketFk, 'FIXING');
+
+ DROP TEMPORARY TABLE tmp.SalesToSplit;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_WeightDeclaration.sql b/db/routines/vn/procedures/ticket_WeightDeclaration.sql
new file mode 100644
index 000000000..e50290dd8
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_WeightDeclaration.sql
@@ -0,0 +1,50 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_WeightDeclaration`(vClientFk INT, vDated DATE)
+BEGIN
+
+ DECLARE vTheorycalWeight DECIMAL(10,2);
+ DECLARE vRealWeight DECIMAL(10,2);
+ DECLARE vRatio DOUBLE;
+
+ SELECT IFNULL(sum(tob.description),0) INTO vRealWeight
+ FROM vn.ticketObservation tob
+ JOIN vn.observationType ot ON ot.id = tob.observationTypeFk
+ JOIN vn.ticket t ON t.id = tob.ticketFk
+ WHERE ot.description = 'Peso Aduana'
+ AND t.clientFk = vClientFk
+ AND t.shipped BETWEEN vDated AND util.dayend(vDated);
+
+ SELECT sum(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight)) INTO vTheorycalWeight
+ FROM vn.ticket t
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.saleVolume sv ON sv.saleFk = s.id
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk
+ WHERE t.clientFk = vClientFk
+ AND t.shipped BETWEEN vDated AND util.dayend(vDated);
+
+ SET vRatio = vRealWeight / vTheorycalWeight;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketWeight;
+
+ CREATE TEMPORARY TABLE tmp.ticketWeight
+ ENGINE = MEMORY
+ SELECT i.intrastatFk,
+ ib.ediBotanic,
+ FLOOR(sum(s.quantity)) as quantity,
+ CAST(vRatio * SUM(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight) ) AS DECIMAL(10,2)) physicalWeight,
+ o.code as countryCode,
+ vDated as Dated
+ FROM vn.ticket t
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.saleVolume sv ON sv.saleFk = s.id
+ JOIN vn.item i ON i.id = s.itemFk
+ LEFT JOIN vn.itemBotanicalWithGenus ib ON ib.itemFk = i.id
+ LEFT JOIN vn.origin o ON o.id = i.originFk
+ WHERE t.clientFk = vClientFk
+ AND t.shipped BETWEEN vDated AND util.dayend(vDated)
+ GROUP BY ib.ediBotanic, o.code;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_add.sql b/db/routines/vn/procedures/ticket_add.sql
new file mode 100644
index 000000000..5c3c28081
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_add.sql
@@ -0,0 +1,123 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_add`(
+ vClientId INT
+ ,vShipped DATE
+ ,vWarehouseFk INT
+ ,vCompanyFk INT
+ ,vAddressFk INT
+ ,vAgencyModeFk INT
+ ,vRouteFk INT
+ ,vlanded DATE
+ ,vUserId INT
+ ,vIsRequiredZone INT
+ ,OUT vNewTicket INT)
+BEGIN
+/**
+* Crea un ticket,
+* ¡¡NO se debe llamar directamente, llamar a salix que hace comprobaciones previas!!
+*
+* @param vClientId id del cliente
+* @param vShipped dia preparacion
+* @param vWarehouseFk id del warehouse
+* @param vCompanyFk id la empresa
+* @param vAddressFk id del consignatario
+* @param vAgencyModeFk id de la agencia
+* @param vRouteFk id de la ruta | NULL
+* @param vlanded dia llegada
+* @param vUserId que crea el ticket
+* @param vIsRequiredZone Indica si tiene que tener zona valida para ser creado
+* @return vNewTicket id del ticket creado
+*/
+ DECLARE vZoneFk INT;
+ DECLARE vPrice DECIMAL(10,2);
+ DECLARE vBonus DECIMAL(10,2);
+ DECLARE vIsActive BOOL;
+
+ IF vClientId IS NULL THEN
+ CALL util.throw ('CLIENT_NOT_ESPECIFIED');
+ END IF;
+
+ SELECT isActive INTO vIsActive
+ FROM vn.client
+ WHERE id = vClientId;
+
+ IF NOT vIsActive THEN
+ CALL util.throw ('CLIENT_NOT_ACTIVE');
+ END IF;
+
+ IF NOT vAddressFk OR vAddressFk IS NULL THEN
+ SELECT id INTO vAddressFk
+ FROM address
+ WHERE clientFk = vClientId
+ AND isDefaultAddress;
+ END IF;
+
+ IF vAgencyModeFk IS NOT NULL THEN
+ CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE);
+
+ SELECT zoneFk, price, bonus
+ INTO vZoneFk, vPrice, vBonus
+ FROM tmp.zoneGetShipped
+ WHERE shipped = vShipped
+ AND warehouseFk = vWarehouseFk
+ LIMIT 1;
+
+ IF (vZoneFk IS NULL OR vZoneFk = 0) AND vIsRequiredZone THEN
+ CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS');
+ END IF;
+ END IF;
+
+ INSERT INTO ticket (
+ clientFk,
+ shipped,
+ addressFk,
+ agencyModeFk,
+ nickname,
+ warehouseFk,
+ routeFk,
+ companyFk,
+ landed,
+ zoneFk,
+ zonePrice,
+ zoneBonus
+ )
+ SELECT vClientId,
+ vShipped,
+ a.id,
+ vAgencyModeFk,
+ a.nickname,
+ vWarehouseFk,
+ IF(vRouteFk,vRouteFk,NULL),
+ vCompanyFk,
+ vlanded,
+ vZoneFk,
+ vPrice,
+ vBonus
+ FROM address a
+ JOIN agencyMode am ON am.id = a.agencyModeFk
+ WHERE a.id = vAddressFk;
+
+ SET vNewTicket = LAST_INSERT_ID();
+
+ INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
+ SELECT vNewTicket, ao.observationTypeFk, ao.description
+ FROM addressObservation ao
+ JOIN address a ON a.id = ao.addressFk
+ WHERE a.id = vAddressFk;
+
+ IF (SELECT COUNT(*)
+ FROM bs.clientNewBorn cnb
+ WHERE cnb.clientFk = vClientId
+ AND NOT cnb.isRookie) = 0 THEN
+
+ CALL vn.ticketObservation_addNewBorn(vNewTicket);
+ END IF;
+
+ IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
+ SELECT id, vNewTicket, account.myUser_getId()
+ FROM state
+ WHERE `code` = 'DELIVERED';
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_administrativeCopy.sql b/db/routines/vn/procedures/ticket_administrativeCopy.sql
new file mode 100644
index 000000000..f240a5fe0
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_administrativeCopy.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_administrativeCopy`(vOriginalTicket INT, OUT vNewTicket INT)
+BEGIN
+
+ INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed)
+ SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed
+ FROM vn.ticket t
+ JOIN vn.warehouse w ON w.name = 'INVENTARIO'
+ WHERE t.id = vOriginalTicket;
+
+ SELECT LAST_INSERT_ID() INTO vNewTicket;
+
+ INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount)
+ SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount
+ FROM vn.sale s
+ WHERE s.ticketFk = vOriginalTicket;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql
new file mode 100644
index 000000000..8852a3010
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_canAdvance.sql
@@ -0,0 +1,151 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT)
+BEGIN
+/**
+ * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar.
+ *
+ * @param vDateFuture Fecha de los tickets que se quieren adelantar.
+ * @param vDateToAdvance Fecha a cuando se quiere adelantar.
+ * @param vWarehouseFk Almacén
+ */
+ DECLARE vDateInventory DATE;
+
+ SELECT inventoried INTO vDateInventory FROM config;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.stock
+ (itemFk INT PRIMARY KEY,
+ amount INT)
+ ENGINE = MEMORY;
+
+ INSERT INTO tmp.stock(itemFk, amount)
+ SELECT itemFk, SUM(quantity) amount FROM
+ (
+ SELECT itemFk, quantity
+ FROM itemTicketOut
+ WHERE shipped >= vDateInventory
+ AND shipped < vDateFuture
+ AND warehouseFk = vWarehouseFk
+ UNION ALL
+ SELECT itemFk, quantity
+ FROM itemEntryIn
+ WHERE landed >= vDateInventory
+ AND landed <= vDateToAdvance
+ AND isVirtualStock = FALSE
+ AND warehouseInFk = vWarehouseFk
+ UNION ALL
+ SELECT itemFk, quantity
+ FROM itemEntryOut
+ WHERE shipped >= vDateInventory
+ AND shipped < vDateFuture
+ AND warehouseOutFk = vWarehouseFk
+ ) t
+ GROUP BY itemFk HAVING amount != 0;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.filter
+ (INDEX (id))
+ SELECT
+ origin.ticketFk futureId,
+ dest.ticketFk id,
+ dest.state,
+ origin.futureState,
+ origin.futureIpt,
+ dest.ipt,
+ origin.workerFk,
+ origin.futureLiters,
+ origin.futureLines,
+ dest.shipped,
+ origin.shipped futureShipped,
+ dest.totalWithVat,
+ origin.totalWithVat futureTotalWithVat,
+ dest.agency,
+ dest.agencyModeFk,
+ origin.futureAgency,
+ origin.agencyModeFk futureAgencyModeFk,
+ dest.lines,
+ dest.liters,
+ origin.futureLines - origin.hasStock AS notMovableLines,
+ (origin.futureLines = origin.hasStock) AS isFullMovable,
+ dest.zoneFk,
+ origin.futureZoneFk,
+ origin.futureZoneName,
+ origin.classColor futureClassColor,
+ dest.classColor,
+ origin.clientFk futureClientFk,
+ origin.addressFk futureAddressFk,
+ origin.warehouseFk futureWarehouseFk,
+ origin.companyFk futureCompanyFk,
+ IFNULL(dest.nickname, origin.nickname) nickname,
+ dest.landed
+ FROM (
+ SELECT
+ s.ticketFk,
+ c.salesPersonFk workerFk,
+ t.shipped,
+ t.totalWithVat,
+ st.name futureState,
+ am.name futureAgency,
+ count(s.id) futureLines,
+ GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
+ CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
+ SUM((s.quantity <= IFNULL(st.amount,0))) hasStock,
+ z.id futureZoneFk,
+ z.name futureZoneName,
+ st.classColor,
+ t.clientFk,
+ t.nickname,
+ t.addressFk,
+ t.warehouseFk,
+ t.companyFk,
+ t.agencyModeFk
+ FROM ticket t
+ JOIN client c ON c.id = t.clientFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN saleVolume sv ON sv.saleFk = s.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticketState ts ON ts.ticketFk = t.id
+ JOIN state st ON st.id = ts.stateFk
+ JOIN agencyMode am ON t.agencyModeFk = am.id
+ JOIN zone z ON t.zoneFk = z.id
+ LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
+ LEFT JOIN tmp.stock st ON st.itemFk = i.id
+ WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
+ AND t.warehouseFk = vWarehouseFk
+ GROUP BY t.id
+ ) origin
+ LEFT JOIN (
+ SELECT
+ t.id ticketFk,
+ st.name state,
+ GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
+ t.shipped,
+ t.totalWithVat,
+ am.name agency,
+ CAST(SUM(litros) AS DECIMAL(10,0)) liters,
+ CAST(COUNT(*) AS DECIMAL(10,0)) `lines`,
+ st.classColor,
+ t.clientFk,
+ t.nickname,
+ t.addressFk,
+ t.zoneFk,
+ t.warehouseFk,
+ t.companyFk,
+ t.landed,
+ t.agencyModeFk
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN saleVolume sv ON sv.saleFk = s.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticketState ts ON ts.ticketFk = t.id
+ JOIN state st ON st.id = ts.stateFk
+ JOIN agencyMode am ON t.agencyModeFk = am.id
+ LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
+ WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance)
+ AND t.warehouseFk = vWarehouseFk
+ AND st.order <= 5
+ GROUP BY t.id
+ ) dest ON dest.addressFk = origin.addressFk
+ WHERE origin.hasStock;
+
+ DROP TEMPORARY TABLE tmp.stock;
+END$$
+DELIMITER ;
diff --git a/db/changes/232201/00-procedurecanbePostponed.sql b/db/routines/vn/procedures/ticket_canMerge.sql
similarity index 55%
rename from db/changes/232201/00-procedurecanbePostponed.sql
rename to db/routines/vn/procedures/ticket_canMerge.sql
index 39aa35cd5..c3f211027 100644
--- a/db/changes/232201/00-procedurecanbePostponed.sql
+++ b/db/routines/vn/procedures/ticket_canMerge.sql
@@ -1,34 +1,24 @@
DELIMITER $$
-$$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canbePostponed`(vOriginDated DATE, vFutureDated DATE, vWarehouseFk INT)
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canMerge`(vDated DATE, vScopeDays INT, vLitersMax INT, vLinesMax INT, vWarehouseFk INT)
BEGIN
/**
* Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro
- *
- * @param vOriginDated Fecha en cuestión
- * @param vFutureDated Fecha en el futuro a sondear
+ *
+ * @param vDated Fecha en cuestión
+ * @param vScopeDays Dias en el futuro a sondear
+ * @param vLitersMax Volumen máximo de los tickets a catapultar
+ * @param vLinesMax Número máximo de lineas de los tickets a catapultar
* @param vWarehouseFk Identificador de vn.warehouse
*/
- DROP TEMPORARY TABLE IF EXISTS tmp.filter;
- CREATE TEMPORARY TABLE tmp.filter
- (INDEX (id))
- SELECT sv.ticketFk id,
- sub2.id futureId,
+ SELECT sv.ticketFk,
GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
- CAST(sum(litros) AS DECIMAL(10,0)) liters,
- CAST(count(*) AS DECIMAL(10,0)) `lines`,
+ CAST(SUM(litros) AS DECIMAL(10,0)) liters,
+ CAST(COUNT(*) AS DECIMAL(10,0)) `lines`,
st.name state,
- sub2.iptd futureIpt,
- sub2.state futureState,
- t.clientFk,
- t.warehouseFk,
- ts.alertLevel,
- t.shipped,
- sub2.shipped futureShipped,
- t.workerFk,
- st.code stateCode,
- sub2.code futureStateCode,
- st.classColor
+ sub2.id ticketFuture,
+ sub2.shipped,
+ sub2.iptd tfIpt,
+ sub2.state tfState
FROM vn.saleVolume sv
JOIN vn.sale s ON s.id = sv.saleFk
JOIN vn.item i ON i.id = s.itemFk
@@ -43,30 +33,33 @@ BEGIN
LEFT JOIN (
SELECT *
FROM (
- SELECT
- t.addressFk,
- t.id,
- t.shipped,
- st.name state,
- st.code code,
- GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) iptd
+ SELECT t.addressFk,
+ t.id,
+ t.shipped,
+ st.name state,
+ GROUP_CONCAT(DISTINCT i.itemPackingTypeFk
+ ORDER BY i.itemPackingTypeFk) iptd
FROM vn.ticket t
JOIN vn.ticketState ts ON ts.ticketFk = t.id
JOIN vn.state st ON st.id = ts.stateFk
JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.alertLevel al ON al.id = st.alertLevel
JOIN vn.item i ON i.id = s.itemFk
- WHERE t.shipped BETWEEN vFutureDated
- AND util.dayend(vFutureDated)
+ WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, vScopeDays,vDated)
+ AND util.dayend(TIMESTAMPADD(DAY, vScopeDays,vDated))
AND t.warehouseFk = vWarehouseFk
+ AND al.code = 'FREE'
GROUP BY t.id
) sub
GROUP BY sub.addressFk
) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id
- WHERE t.shipped BETWEEN vOriginDated AND util.dayend(vOriginDated)
+ WHERE t.shipped BETWEEN vDated AND util.dayend(vDated)
AND t.warehouseFk = vWarehouseFk
AND al.code = 'FREE'
AND tp.ticketFk IS NULL
GROUP BY sv.ticketFk
- HAVING futureId;
+ HAVING liters <= vLitersMax
+ AND `lines` <= vLinesMax
+ AND ticketFuture;
END$$
-DELIMITER ;
\ No newline at end of file
+DELIMITER ;
diff --git a/db/changes/232202/00-procedurecanbePostponed.sql b/db/routines/vn/procedures/ticket_canbePostponed.sql
similarity index 94%
rename from db/changes/232202/00-procedurecanbePostponed.sql
rename to db/routines/vn/procedures/ticket_canbePostponed.sql
index 9d42dcc4b..442059b99 100644
--- a/db/changes/232202/00-procedurecanbePostponed.sql
+++ b/db/routines/vn/procedures/ticket_canbePostponed.sql
@@ -1,5 +1,4 @@
DELIMITER $$
-$$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canbePostponed`(vOriginDated DATE, vFutureDated DATE, vWarehouseFk INT)
BEGIN
/**
@@ -9,10 +8,9 @@ BEGIN
* @param vFutureDated Fecha en el futuro a sondear
* @param vWarehouseFk Identificador de vn.warehouse
*/
- DROP TEMPORARY TABLE IF EXISTS tmp.filter;
- CREATE TEMPORARY TABLE tmp.filter
- (INDEX (id))
- SELECT sv.ticketFk id,
+ CREATE OR REPLACE TEMPORARY TABLE tmp.filter
+ (INDEX (id))
+ SELECT sv.ticketFk id,
sub2.id futureId,
GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
CAST(sum(litros) AS DECIMAL(10,0)) liters,
@@ -24,6 +22,7 @@ BEGIN
t.warehouseFk,
ts.alertLevel,
t.shipped,
+ t.totalWithVat,
sub2.shipped futureShipped,
t.workerFk,
st.code stateCode,
diff --git a/db/routines/vn/procedures/ticket_checkNoComponents.sql b/db/routines/vn/procedures/ticket_checkNoComponents.sql
new file mode 100644
index 000000000..28fe333f0
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_checkNoComponents.sql
@@ -0,0 +1,45 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_checkNoComponents`(vShippedFrom DATETIME, vShippedTo DATETIME)
+BEGIN
+
+/**
+ * Comprueba que los tickets entre un rango de fechas tienen componentes
+ * y recalcula sus componentes
+ *
+ * @param vShippedFrom rango inicial de fecha
+ * @param vShippedTo rango final de fecha
+ */
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.coste
+ (primary key (id)) ENGINE = MEMORY
+ SELECT s.id
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType tp ON tp.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
+ JOIN saleComponent sc ON sc.saleFk = s.id
+ JOIN component c ON c.id = sc.componentFk
+ JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 1
+ WHERE t.shipped BETWEEN vShippedFrom AND vShippedTo
+ AND ic.merchandise;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
+ (primary key (id)) ENGINE = MEMORY
+ SELECT DISTINCT s.id
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType tp ON tp.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
+ LEFT JOIN tmp.coste c ON c.id = s.id
+ WHERE t.shipped >= vShippedFrom AND t.shipped <= vShippedTo
+ AND c.id IS NULL
+ AND ic.merchandise;
+
+ CALL sale_recalcComponent('renewPrices');
+
+ DROP TEMPORARY TABLE tmp.recalculateSales;
+ DROP TEMPORARY TABLE tmp.coste;
+ END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_cloneAll.sql b/db/routines/vn/procedures/ticket_cloneAll.sql
new file mode 100644
index 000000000..4b3401ed7
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_cloneAll.sql
@@ -0,0 +1,55 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_cloneAll`(vTicketFk INT, vNewShipped DATE, vWithWarehouse BOOLEAN, OUT vNewTicketFk INT)
+BEGIN
+
+ DECLARE vDone BOOLEAN DEFAULT FALSE;
+ DECLARE vOldSaleFk INT;
+ DECLARE vNewSaleFk INT;
+
+ DECLARE cur1 CURSOR FOR
+ SELECT id
+ FROM sale
+ WHERE ticketFk = vTicketFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SET vNewShipped = IFNULL(vNewShipped, util.VN_CURDATE());
+
+ CALL ticket_Clone(vTicketFk, vNewTicketFk);
+
+ UPDATE ticket
+ SET landed = TIMESTAMPADD(DAY, DATEDIFF(vNewShipped, shipped), landed),
+ shipped = vNewShipped,
+ warehouseFk = IF(vWithWarehouse, warehouseFk, NULL)
+ WHERE id = vNewTicketFk;
+
+ OPEN cur1;
+
+ read_loop: LOOP
+
+ FETCH cur1 INTO vOldSaleFk;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ INSERT INTO sale(ticketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed)
+ SELECT vNewTicketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed
+ FROM sale
+ WHERE id = vOldSaleFk;
+
+ SELECT max(id) INTO vNewSaleFk
+ FROM sale
+ WHERE ticketFk = vNewTicketFk;
+
+ INSERT INTO saleComponent(saleFk, componentFk, value, isGreuge)
+ SELECT vNewSaleFk, componentFk, value, isGreuge
+ FROM saleComponent
+ WHERE saleFk = vOldSaleFk;
+
+ END LOOP;
+
+ CLOSE cur1;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_cloneWeekly.sql b/db/routines/vn/procedures/ticket_cloneWeekly.sql
new file mode 100644
index 000000000..6bceb2fdf
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_cloneWeekly.sql
@@ -0,0 +1,202 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_cloneWeekly`(vDateFrom DATE, vDateTo DATE)
+BEGIN
+ DECLARE vIsDone BOOL;
+ DECLARE vLanding DATE;
+ DECLARE vShipment DATE;
+ DECLARE vWarehouseFk INT;
+ DECLARE vTicketFk INT;
+ DECLARE vClientFk INT;
+ DECLARE vCompanyFk INT;
+ DECLARE vAddressFk INT;
+ DECLARE vAgencyModeFk INT;
+ DECLARE vNewTicket INT;
+ DECLARE vYear INT;
+ DECLARE vSalesPersonFK INT;
+ DECLARE vItemPicker INT;
+
+ DECLARE rsTicket CURSOR FOR
+ SELECT tt.ticketFk,
+ t.clientFk,
+ t.warehouseFk,
+ t.companyFk,
+ t.addressFk,
+ tt.agencyModeFk,
+ ti.dated
+ FROM ticketWeekly tt
+ JOIN ticket t ON tt.ticketFk = t.id
+ JOIN tmp.time ti
+ WHERE WEEKDAY(ti.dated) = tt.weekDay;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
+
+ CALL `util`.`time_generate`(vDateFrom,vDateTo);
+
+ OPEN rsTicket;
+ myLoop: LOOP
+ BEGIN
+ DECLARE vSalesPersonEmail VARCHAR(150);
+ DECLARE vIsDuplicateMail BOOL;
+ DECLARE vSubject VARCHAR(150);
+ DECLARE vMessage TEXT;
+
+ SET vIsDone = FALSE;
+ FETCH rsTicket INTO vTicketFk,vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk,vShipment;
+
+ IF vIsDone THEN
+ LEAVE myLoop;
+ END IF;
+
+ -- busca si el ticket ya ha sido clonado
+ IF EXISTS (SELECT TRUE FROM ticket tOrig
+ JOIN sale saleOrig ON tOrig.id = saleOrig.ticketFk
+ JOIN saleCloned sc ON sc.saleOriginalFk = saleOrig.id
+ JOIN sale saleClon ON saleClon.id = sc.saleClonedFk
+ JOIN ticket tClon ON tClon.id = saleClon.ticketFk
+ WHERE tOrig.id = vTicketFk
+ AND tClon.isDeleted = FALSE
+ AND DATE(tClon.shipped) = vShipment)
+ THEN
+ ITERATE myLoop;
+ END IF;
+
+ IF vAgencyModeFk IS NULL THEN
+ SELECT agencyModeFk INTO vAgencyModeFk
+ FROM address
+ WHERE clientFk = vClientFk
+ AND isDefaultAddress;
+ END IF;
+
+ CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk,FALSE);
+ SET vLanding = NULL;
+ SELECT landed INTO vLanding FROM tmp.zoneGetLanded LIMIT 1;
+
+ CALL ticket_add(
+ vClientFk,
+ vShipment,
+ vWarehouseFk,
+ vCompanyFk,
+ vAddressFk,
+ vAgencyModeFk,
+ NULL,
+ vLanding,
+ account.myUser_getId(),
+ FALSE,
+ vNewTicket);
+
+ UPDATE ticket
+ SET clonedFrom = vTicketFk
+ WHERE id = vNewTicket;
+
+ INSERT INTO sale (ticketFk, itemFk, concept, quantity, price,
+ discount, priceFixed, isPriceFixed)
+ SELECT vNewTicket,
+ saleOrig.itemFk,
+ saleOrig.concept,
+ saleOrig.quantity,
+ saleOrig.price,
+ saleOrig.discount,
+ saleOrig.priceFixed,
+ saleOrig.isPriceFixed
+ FROM sale saleOrig
+ WHERE saleOrig.ticketFk = vTicketFk;
+
+ INSERT IGNORE INTO saleCloned(saleOriginalFk, saleClonedFk)
+ SELECT saleOriginal.id, saleClon.id
+ FROM sale saleOriginal
+ JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk
+ AND saleOriginal.quantity = saleClon.quantity
+ WHERE saleOriginal.ticketFk = vTicketFk
+ AND saleClon.ticketFk = vNewTicket;
+
+ INSERT INTO ticketRequest (description,
+ ordered,
+ shipped,
+ quantity,
+ price,
+ itemFk,
+ clientFk,
+ response,
+ total,
+ buyed,
+ requesterFk
+ ,attenderFk,
+ ticketFk)
+ SELECT description,
+ ordered,
+ shipped,
+ quantity,
+ price,
+ itemFk,
+ clientFk,
+ response,
+ total,
+ buyed,
+ requesterFk,
+ attenderFk,
+ vNewTicket
+ FROM ticketRequest
+ WHERE ticketFk =vTicketFk;
+
+ SELECT id INTO vSalesPersonFK
+ FROM observationType
+ WHERE code = 'salesPerson';
+
+ SELECT id INTO vItemPicker
+ FROM observationType
+ WHERE code = 'itemPicker';
+
+ INSERT INTO ticketObservation(
+ ticketFk,
+ observationTypeFk,
+ description)
+ VALUES(
+ vNewTicket,
+ vSalesPersonFK,
+ CONCAT('turno desde ticket: ',vTicketFk))
+ ON DUPLICATE KEY UPDATE description =
+ CONCAT(ticketObservation.description,VALUES(description),' ');
+
+ INSERT INTO ticketObservation(ticketFk,
+ observationTypeFk,
+ description)
+ VALUES(
+ vNewTicket,
+ vItemPicker,
+ 'ATENCION: Contiene lineas de TURNO')
+ ON DUPLICATE KEY UPDATE description =
+ CONCAT(ticketObservation.description,VALUES(description),' ');
+
+ IF (vLanding IS NULL) THEN
+
+ SELECT e.email INTO vSalesPersonEmail
+ FROM client c
+ JOIN account.emailUser e ON e.userFk = c.salesPersonFk
+ WHERE c.id = vClientFk;
+
+ SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ',
+ vTicketFk,' para el dia: ', vShipment);
+ SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk,
+ ' para el dia: ', vShipment,
+ ' porque no hay una zona de envío disponible. Se ha creado el ticket: ',
+ vNewTicket, ' pero ha que revisar las fechas y la agencia');
+
+ SELECT COUNT(*) INTO vIsDuplicateMail
+ FROM mail
+ WHERE receiver = vSalesPersonEmail
+ AND subject = vSubject;
+
+ IF NOT vIsDuplicateMail THEN
+ CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage);
+ END IF;
+ CALL ticketStateUpdate (vNewTicket, 'FIXING');
+ ELSE
+ CALL ticketCalculateClon(vNewTicket, vTicketFk);
+ END IF;
+
+ END;
+ END LOOP;
+ CLOSE rsTicket;
+ DROP TEMPORARY TABLE IF EXISTS tmp.time;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_close.sql b/db/routines/vn/procedures/ticket_close.sql
new file mode 100644
index 000000000..91e0979cd
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_close.sql
@@ -0,0 +1,103 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_close`()
+BEGIN
+/**
+ * Realiza el cierre de todos los
+ * tickets de la tabla tmp.ticket_close.
+ *
+ * @table tmp.ticket_close(ticketFk) Identificadores de los tickets a cerrar
+ */
+ DECLARE vDone BOOL;
+ DECLARE vClientFk INT;
+ DECLARE vCurTicketFk INT;
+ DECLARE vIsTaxDataChecked BOOL;
+ DECLARE vCompanyFk INT;
+ DECLARE vShipped DATE;
+ DECLARE vNewInvoiceId INT;
+ DECLARE vHasDailyInvoice BOOL;
+ DECLARE vWithPackage BOOL;
+ DECLARE vHasToInvoice BOOL;
+
+ DECLARE cur CURSOR FOR
+ SELECT ticketFk FROM tmp.ticket_close;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
+ RESIGNAL;
+ END;
+
+ OPEN cur;
+
+ proc: LOOP
+ SET vDone = FALSE;
+
+ FETCH cur INTO vCurTicketFk;
+
+ IF vDone THEN
+ LEAVE proc;
+ END IF;
+
+ SELECT
+ c.id,
+ c.isTaxDataChecked,
+ t.companyFk,
+ t.shipped,
+ IFNULL(a.hasDailyInvoice, co.hasDailyInvoice),
+ w.isManaged,
+ c.hasToInvoice
+ INTO vClientFk,
+ vIsTaxDataChecked,
+ vCompanyFk,
+ vShipped,
+ vHasDailyInvoice,
+ vWithPackage,
+ vHasToInvoice
+ FROM ticket t
+ JOIN `client` c ON c.id = t.clientFk
+ JOIN province p ON p.id = c.provinceFk
+ LEFT JOIN autonomy a ON a.id = p.autonomyFk
+ JOIN country co ON co.id = p.countryFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.id = vCurTicketFk;
+
+ INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity)
+ (SELECT vCurTicketFk, p.id, COUNT(*)
+ FROM expedition e
+ JOIN packaging p ON p.itemFk = e.freightItemFk
+ WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable
+ AND vWithPackage
+ GROUP BY p.itemFk);
+
+ -- No retornables o no catalogados
+ INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed)
+ (SELECT e.freightItemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.freightItemFk, vClientFk), 1
+ FROM expedition e
+ JOIN item i ON i.id = e.freightItemFk
+ LEFT JOIN packaging p ON p.itemFk = i.id
+ WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0
+ AND getSpecialPrice(e.freightItemFk, vClientFk) > 0
+ GROUP BY e.freightItemFk);
+
+ IF(vHasDailyInvoice) AND vHasToInvoice THEN
+
+ -- Facturacion rapida
+ CALL ticket_setState(vCurTicketFk, 'DELIVERED');
+ -- Facturar si está contabilizado
+ IF vIsTaxDataChecked THEN
+ CALL invoiceOut_newFromClient(
+ vClientFk,
+ (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')),
+ vShipped,
+ vCompanyFk,
+ NULL,
+ NULL,
+ vNewInvoiceId);
+ END IF;
+ ELSE
+ CALL ticket_setState(vCurTicketFk, (SELECT vn.getAlert3State(vCurTicketFk)));
+ END IF;
+ END LOOP;
+
+ CLOSE cur;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_closeByTicket.sql b/db/routines/vn/procedures/ticket_closeByTicket.sql
new file mode 100644
index 000000000..837b809a2
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_closeByTicket.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_closeByTicket`(IN vTicketFk int)
+BEGIN
+/**
+ * Inserta el ticket en la tabla temporal
+ * para ser cerrado.
+ *
+ * @param vTicketFk Id del ticket
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket_close;
+ CREATE TEMPORARY TABLE tmp.ticket_close ENGINE = MEMORY (
+ SELECT
+ t.id AS ticketFk
+ FROM ticket t
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ LEFT JOIN ticketState ts ON ts.ticketFk = t.id
+ JOIN alertLevel al ON al.id = ts.alertLevel
+ WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered'))
+ AND t.id = vTicketFk
+ AND t.refFk IS NULL
+ GROUP BY t.id
+ );
+
+ CALL ticket_close();
+
+ DROP TEMPORARY TABLE tmp.ticket_close;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_componentMakeUpdate.sql b/db/routines/vn/procedures/ticket_componentMakeUpdate.sql
new file mode 100644
index 000000000..4b0a5bdbc
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_componentMakeUpdate.sql
@@ -0,0 +1,97 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_componentMakeUpdate`(
+ vTicketFk INT,
+ vClientFk INT,
+ vNickname VARCHAR(50),
+ vAgencyModeFk INT,
+ vAddressFk INT,
+ vZoneFk INT,
+ vWarehouseFk INT,
+ vCompanyFk INT,
+ vShipped DATETIME,
+ vLanded DATE,
+ vIsDeleted BOOLEAN,
+ vHasToBeUnrouted BOOLEAN,
+ vOption VARCHAR(25))
+BEGIN
+
+ /**
+ * Modifica en el ticket los campos que se le pasan por parámetro
+ * y cambia sus componentes
+ *
+ * @param vTicketFk Id del ticket a modificar
+ * @param vClientFk nuevo cliente
+ * @param vNickname nuevo alias
+ * @param vAgencyModeFk nueva agencia
+ * @param vAddressFk nuevo consignatario
+ * @param vZoneFk nueva zona
+ * @param vWarehouseFk nuevo almacen
+ * @param vCompanyFk nueva empresa
+ * @param vShipped nueva fecha del envio de mercancia
+ * @param vLanded nueva fecha de recepcion de mercancia
+ * @param vIsDeleted si se borra el ticket
+ * @param vHasToBeUnrouted si se le elimina la ruta al ticket
+ * @param vOption opcion para el case del proc ticketComponentUpdateSale
+ */
+
+ DECLARE vPrice DECIMAL(10,2);
+ DECLARE vBonus DECIMAL(10,2);
+
+ CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk);
+
+ IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN
+
+ UPDATE ticket t
+ JOIN address a ON a.id = vAddressFk
+ SET t.nickname = a.nickname
+ WHERE t.id = vTicketFk;
+
+ END IF;
+
+ CALL zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, TRUE);
+
+ SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus
+ FROM tmp.zoneGetShipped
+ WHERE shipped BETWEEN DATE(vShipped) AND util.dayEnd(vShipped) AND warehouseFk = vWarehouseFk LIMIT 1;
+
+ UPDATE ticket t
+ SET
+ t.clientFk = vClientFk,
+ t.nickname = vNickname,
+ t.agencyModeFk = vAgencyModeFk,
+ t.addressFk = vAddressFk,
+ t.zoneFk = vZoneFk,
+ t.zonePrice = vPrice,
+ t.zoneBonus = vBonus,
+ t.warehouseFk = vWarehouseFk,
+ t.companyFk = vCompanyFk,
+ t.landed = vLanded,
+ t.shipped = vShipped,
+ t.isDeleted = vIsDeleted
+ WHERE
+ t.id = vTicketFk;
+
+ IF vHasToBeUnrouted THEN
+ UPDATE ticket t SET t.routeFk = NULL
+ WHERE t.id = vTicketFk;
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.sale;
+ CREATE TEMPORARY TABLE tmp.sale
+ (PRIMARY KEY (saleFk))
+ ENGINE = MEMORY
+ SELECT id AS saleFk, vWarehouseFk warehouseFk
+ FROM sale s WHERE s.ticketFk = vTicketFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
+ CREATE TEMPORARY TABLE tmp.ticketComponent
+ SELECT * FROM tmp.ticketComponentPreview;
+
+ CALL ticketComponentUpdateSale (vOption);
+
+ DROP TEMPORARY TABLE tmp.sale;
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
+
+ DROP TEMPORARY TABLE tmp.zoneGetShipped, tmp.ticketComponentPreview;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_componentPreview.sql b/db/routines/vn/procedures/ticket_componentPreview.sql
new file mode 100644
index 000000000..729e3a743
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_componentPreview.sql
@@ -0,0 +1,101 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_componentPreview`(
+ vTicketFk INT,
+ vLanded DATE,
+ vAddressFk INT,
+ vZoneFk INT,
+ vWarehouseFk SMALLINT)
+BEGIN
+/**
+ * Calcula los componentes de los articulos de un ticket
+ *
+ * @param vTicketFk id del ticket
+ * @param vLanded nueva fecha de entrega
+ * @param vAddressFk nuevo consignatario
+ * @param vZoneFk nueva zona
+ * @param vWarehouseFk nuevo warehouse
+ *
+ * @return tmp.ticketComponentPreview (warehouseFk, itemFk, componentFk, cost)
+ */
+ DECLARE vHasDataChanged BOOL DEFAULT FALSE;
+ DECLARE vHasAddressChanged BOOL;
+ DECLARE vHasZoneChanged BOOL DEFAULT FALSE;
+ DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE;
+
+ DECLARE vShipped DATE;
+ DECLARE vAddressTypeRateFk INT DEFAULT NULL;
+ DECLARE vAgencyModeTypeRateFk INT DEFAULT NULL;
+
+ DECLARE vHasChangeAll BOOL DEFAULT FALSE;
+
+ SELECT DATE(landed) <> vLanded,
+ addressFk <> vAddressFk,
+ zoneFk <> vZoneFk,
+ warehouseFk <> vWarehouseFk
+ INTO
+ vHasDataChanged,
+ vHasAddressChanged,
+ vHasZoneChanged,
+ vHasWarehouseChanged
+ FROM vn.ticket t
+ WHERE t.id = vTicketFk;
+
+ IF vHasDataChanged OR vHasWarehouseChanged THEN
+ SET vHasChangeAll = TRUE;
+ END IF;
+
+ IF vHasAddressChanged THEN
+ SET vAddressTypeRateFk = 5;
+ END IF;
+
+ IF vHasZoneChanged THEN
+ SET vAgencyModeTypeRateFk = 6;
+ END IF;
+
+ SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped
+ FROM zone
+ WHERE id = vZoneFk;
+
+ CALL buyUltimate(vWarehouseFk, vShipped);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
+ CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY (
+ SELECT
+ vWarehouseFk AS warehouseFk,
+ NULL AS available,
+ s.itemFk,
+ bu.buyFk,
+ vZoneFk zoneFk
+ FROM sale s
+ LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
+ WHERE s.ticketFk = vTicketFk
+ GROUP BY bu.warehouseFk, bu.itemFk);
+
+ CALL catalog_componentPrepare();
+ CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
+
+ REPLACE INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
+ SELECT t.warehouseFk, s.itemFk, sc.componentFk, sc.value
+ FROM saleComponent sc
+ JOIN sale s ON s.id = sc.saleFk
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN `component` c ON c.id = sc.componentFk
+ WHERE s.ticketFk = vTicketFk
+ AND (c.isRenewable = FALSE
+ OR
+ (NOT vHasChangeAll
+ AND (NOT (c.typeFk <=> vAddressTypeRateFk
+ OR c.typeFk <=> vAgencyModeTypeRateFk))));
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPreview;
+ CREATE TEMPORARY TABLE tmp.ticketComponentPreview
+ SELECT * FROM tmp.ticketComponent;
+
+ CALL catalog_componentPurge();
+ DROP TEMPORARY TABLE tmp.buyUltimate;
+
+ IF vShipped IS NULL THEN
+ CALL util.throw('NO_ZONE_AVAILABLE');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_doCmr.sql b/db/routines/vn/procedures/ticket_doCmr.sql
new file mode 100644
index 000000000..5789d09de
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_doCmr.sql
@@ -0,0 +1,89 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_doCmr`(vSelf INT)
+BEGIN
+/**
+* Crea u actualiza la información del CMR asociado con
+* un ticket específico en caso de que sea necesario.
+*
+* @param vSelf El id del ticket
+*/
+ DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT;
+ SELECT cmrFk INTO vCmrFk
+ FROM ticket
+ WHERE id = vSelf;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTicket
+ SELECT wo.firstName,
+ v.numberPlate,
+ com.id companyFk,
+ a.id addressFk,
+ c2.defaultAddressFk,
+ su.id supplierFk,
+ t.landed
+ FROM ticket t
+ JOIN ticketState ts ON ts.ticketFk = t.id
+ JOIN `state` s ON s.id = ts.stateFk
+ JOIN alertLevel al ON al.id = s.alertLevel
+ JOIN client c ON c.id = t.clientFk
+ JOIN `address` a ON a.id = t.addressFk
+ JOIN province p ON p.id = a.provinceFk
+ JOIN country co ON co.id = p.countryFk
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ JOIN company com ON com.id = t.companyFk
+ JOIN client c2 ON c2.id = com.clientFk
+ JOIN supplierAccount sa ON sa.id = com.supplierAccountFk
+ JOIN supplier su ON su.id = sa.supplierFk
+ LEFT JOIN route r ON r.id = t.routeFk
+ LEFT JOIN worker wo ON wo.id = r.workerFk
+ LEFT JOIN vehicle v ON v.id = r.vehicleFk
+ WHERE t.shipped BETWEEN util.yesterday() AND util.dayEnd(util.VN_CURDATE())
+ AND al.code IN ('PACKED', 'DELIVERED')
+ AND co.code <> 'ES'
+ AND am.name <> 'ABONO'
+ AND w.code = 'ALG'
+ AND dm.code = 'DELIVERY'
+ AND t.id = vSelf
+ GROUP BY t.id;
+
+ START TRANSACTION;
+
+ IF vCmrFk THEN
+ UPDATE cmr c
+ JOIN tTicket t
+ SET c.senderInstruccions = t.firstName,
+ c.truckPlate = t.numberPlate,
+ c.companyFk = t.companyFk,
+ c.addressToFk = t.addressFk,
+ c.addressFromFk = t.defaultAddressFk,
+ c.supplierFk = t.supplierFk,
+ c.ead = t.landed
+ WHERE id = vCmrFk;
+ ELSE
+ SELECT MAX(id) INTO vPreviousCmrFk FROM cmr;
+
+ INSERT INTO cmr (
+ senderInstruccions,
+ truckPlate,
+ companyFk,
+ addressToFk,
+ addressFromFk,
+ supplierFk,
+ ead
+ )
+ SELECT * FROM tTicket;
+
+ SELECT MAX(id) INTO vCurrentCmrFk FROM cmr;
+
+ IF vPreviousCmrFk <> vCurrentCmrFk THEN
+ UPDATE ticket
+ SET cmrFk = vCurrentCmrFk
+ WHERE id = vSelf;
+ END IF;
+ END IF;
+
+ COMMIT;
+ DROP TEMPORARY TABLE tTicket;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_doRecalc.sql b/db/routines/vn/procedures/ticket_doRecalc.sql
new file mode 100644
index 000000000..1dd2a05cb
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_doRecalc.sql
@@ -0,0 +1,53 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_doRecalc`()
+proc: BEGIN
+/**
+ * Recalculates modified ticket.
+ */
+ DECLARE vDone BOOL;
+ DECLARE vTicketFk INT;
+
+ DECLARE cCur CURSOR FOR
+ SELECT DISTINCT ticketFk FROM tTicket;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ DO RELEASE_LOCK('vn.ticket_doRecalc');
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ IF !GET_LOCK('vn.ticket_doRecalc', 0) THEN
+ LEAVE proc;
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tTicket;
+ CREATE TEMPORARY TABLE tTicket
+ ENGINE = MEMORY
+ SELECT id, ticketFk FROM ticketRecalc;
+
+ OPEN cCur;
+
+ myLoop: LOOP
+ SET vDone = FALSE;
+ FETCH cCur INTO vTicketFk;
+
+ IF vDone THEN
+ LEAVE myLoop;
+ END IF;
+
+ CALL ticket_recalc(vTicketFk, NULL);
+ END LOOP;
+
+ CLOSE cCur;
+
+ DELETE tr FROM ticketRecalc tr JOIN tTicket t ON tr.id = t.id;
+
+ DROP TEMPORARY TABLE tTicket;
+
+ DO RELEASE_LOCK('vn.ticket_doRecalc');
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_getFromFloramondo.sql b/db/routines/vn/procedures/ticket_getFromFloramondo.sql
new file mode 100644
index 000000000..4d83d6dda
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_getFromFloramondo.sql
@@ -0,0 +1,127 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getFromFloramondo`(vDateFrom DATE, vDateTo DATE)
+BEGIN
+/**
+ * Genera una tabla con la lista de tickets de Floramondo
+ * para una fecha determinada.
+ *
+ * @param vDated Fecha de preparación de los pedidos
+ * @table tmp.ticketFloramondo(ticketFk, clientName, agencyName,
+ * agencyModeFk, supplierName, supplierFk, freight, expeditionCount,
+ * margin, trolleys, pallets, shipped, created)
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketFloramondo;
+ CREATE TEMPORARY TABLE tmp.ticketFloramondo
+ (ticketFk INT PRIMARY KEY,
+ clientName VARCHAR(50),
+ agencyName VARCHAR(50),
+ agencyModeFk INT,
+ supplierName VARCHAR(50),
+ supplierFk INT,
+ freight DECIMAL(10,2) DEFAULT 0,
+ expeditionCount INT,
+ margin DECIMAL(10,3) DEFAULT 0,
+ trolleys INT DEFAULT 0,
+ pallets INT DEFAULT 0,
+ shipped DATE,
+ created DATE)
+ ENGINE = MEMORY;
+
+ INSERT INTO tmp.ticketFloramondo(ticketFk,
+ clientName,
+ agencyName,
+ agencyModeFk,
+ shipped,
+ supplierName,
+ supplierFk,
+ created)
+ SELECT t.id ticketFk,
+ t.nickname,
+ am.name,
+ am.id,
+ t.shipped,
+ s.name,
+ sat.supplierFk,
+ t.created
+ FROM vn.ticket t
+ JOIN vn.agencyMode am ON am.id = t.agencyModeFk
+ JOIN vn.warehouse w ON w.id = t.warehouseFk
+ AND w.code IN ('VNH','FLM')
+ AND t.shipped BETWEEN vDateFrom AND util.dayend(vDateTo)
+ JOIN vn.agency a ON a.id = am.agencyFk
+ LEFT JOIN vn.supplierAgencyTerm sat ON sat.agencyFk = a.id
+ LEFT JOIN vn.supplier s ON s.id = sat.supplierFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
+ CREATE TEMPORARY TABLE tmp.ticket
+ (ticketFk INT(11) PRIMARY KEY)
+ SELECT ticketFk
+ FROM tmp.ticketFloramondo;
+
+ -- Freight
+ UPDATE tmp.ticketFloramondo tf
+ JOIN (SELECT SUM(sc.value * s.quantity) freight, t.ticketFk
+ FROM vn.saleComponent sc
+ JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk
+ JOIN vn.sale s ON s.id = sc.saleFk
+ JOIN tmp.ticket t ON t.ticketFk = s.ticketFk
+ WHERE ct.code = 'FREIGHT'
+ GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
+ SET tf.freight = sb.freight;
+
+ -- Freight service
+ UPDATE tmp.ticketFloramondo tf
+ JOIN (SELECT SUM(ts.price * ts.quantity) service, t.ticketFk
+ FROM vn.ticketService ts
+ JOIN tmp.ticket t ON t.ticketFk = ts.ticketFk
+ GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
+ SET tf.freight = tf.freight + sb.service;
+
+ -- Expedition Count
+ UPDATE tmp.ticketFloramondo tf
+ JOIN (SELECT COUNT(e.id) expeditionCount, t.ticketFk
+ FROM vn.expedition e
+ RIGHT JOIN tmp.ticket t ON t.ticketFk = e.ticketFk
+ GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
+ SET tf.expeditionCount = sb.expeditionCount;
+
+ -- Margin
+ UPDATE tmp.ticketFloramondo tf
+ JOIN (SELECT SUM(IF(ct.code = 'COST',sc.value, 0)) cost,
+ SUM(IF(ct.isMargin, sc.value, 0)) margin,
+ t.ticketFk
+ FROM vn.saleComponent sc
+ JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk
+ JOIN vn.sale s ON s.id = sc.saleFk
+ JOIN tmp.ticket t ON t.ticketFk = s.ticketFk
+ GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
+ SET tf.margin = sb.margin / sb.cost;
+
+ -- Trolleys
+ UPDATE tmp.ticketFloramondo tf
+ JOIN (SELECT SUM(tp.quantity) trolleys, t.ticketFk
+ FROM vn.ticketPackaging tp
+ JOIN tmp.ticket t ON t.ticketFk = tp.ticketFk
+ JOIN vn.packaging p ON p.id = tp.packagingFk
+ WHERE p.isTrolley
+ GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
+ SET tf.trolleys = sb.trolleys;
+
+ -- Pallets
+ UPDATE tmp.ticketFloramondo tf
+ JOIN (SELECT SUM(tp.quantity) pallets, t.ticketFk
+ FROM vn.ticketPackaging tp
+ JOIN tmp.ticket t ON t.ticketFk = tp.ticketFk
+ JOIN vn.packaging p ON p.id = tp.packagingFk
+ WHERE p.isPallet
+ GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
+ SET tf.pallets = sb.pallets;
+
+ SELECT * FROM tmp.ticketFloramondo;
+
+ DROP TEMPORARY TABLE tmp.ticket;
+ DROP TEMPORARY TABLE tmp.ticketFloramondo;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_getMovable.sql b/db/routines/vn/procedures/ticket_getMovable.sql
new file mode 100644
index 000000000..eee165538
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_getMovable.sql
@@ -0,0 +1,55 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getMovable`(
+ vTicketFk INT,
+ vNewShipped DATETIME,
+ vWarehouseFk INT
+)
+BEGIN
+/**
+ * Cálcula el stock movible para los artículos de un ticket
+ * vNewShipped debe ser menor que vOldShipped, en los otros casos se
+ * asume que siempre es posible
+ *
+ * @param vTicketFk -> Ticket
+ * @param vNewShipped -> Nueva fecha
+ * @return Sales con Movible
+*/
+ DECLARE vOldShipped DATETIME;
+
+ SELECT t.shipped INTO vOldShipped
+ FROM ticket t
+ WHERE t.id = vTicketFk;
+
+ -- Añadimos un dia más para calcular el stock hasta vNewShipped inclusive
+ CALL item_getStock(vWarehouseFk, DATE_ADD(vNewShipped, INTERVAL 1 DAY), NULL);
+ CALL item_getMinacum(
+ vWarehouseFk,
+ vNewShipped,
+ DATEDIFF(DATE_SUB(vOldShipped, INTERVAL 1 DAY), vNewShipped),
+ NULL
+ );
+
+ SELECT s.id,
+ s.itemFk,
+ s.quantity,
+ s.concept,
+ s.price,
+ s.reserved,
+ s.discount,
+ i.image,
+ i.subName,
+ il.stock + IFNULL(im.amount, 0) AS movable
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk
+ AND im.warehouseFk = vWarehouseFk
+ LEFT JOIN tmp.itemList il ON il.itemFk = s.itemFk
+ WHERE t.id = vTicketFk;
+
+ DROP TEMPORARY TABLE IF EXISTS
+ tmp.itemList,
+ tmp.itemMinacum;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_getProblems.sql b/db/routines/vn/procedures/ticket_getProblems.sql
new file mode 100644
index 000000000..7c57492b4
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_getProblems.sql
@@ -0,0 +1,48 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getProblems`(IN vIsTodayRelative tinyint(1))
+BEGIN
+/**
+ * Calcula los problemas para un conjunto de tickets.
+ * Agrupados por ticket
+ *
+ * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular
+ * @return tmp.ticket_problems
+ */
+ CALL sale_getProblems(vIsTodayRelative);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_problems
+ (PRIMARY KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT ticketFk,
+ MAX(isFreezed) isFreezed,
+ MAX(risk) risk,
+ MAX(hasHighRisk) hasHighRisk,
+ MAX(hasTicketRequest) hasTicketRequest,
+ MAX(itemShortage) itemShortage,
+ MIN(isTaxDataChecked) isTaxDataChecked,
+ MAX(hasComponentLack) hasComponentLack,
+ MAX(isTooLittle) isTooLittle,
+ MAX(itemDelay) itemDelay,
+ MAX(hasRounding) hasRounding,
+ MAX(itemLost) itemLost,
+ 0 totalProblems
+ FROM tmp.sale_problems
+ GROUP BY ticketFk;
+
+ UPDATE tmp.ticket_problems tp
+ SET tp.totalProblems = (
+ (tp.isFreezed) +
+ IF(tp.risk,TRUE, FALSE) +
+ (tp.hasTicketRequest) +
+ (tp.isTaxDataChecked = 0) +
+ (tp.hasComponentLack) +
+ (tp.itemDelay) +
+ (tp.isTooLittle) +
+ (tp.itemLost) +
+ (tp.hasRounding) +
+ (tp.itemShortage)
+ );
+
+ DROP TEMPORARY TABLE tmp.sale_problems;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_getSplitList.sql b/db/routines/vn/procedures/ticket_getSplitList.sql
new file mode 100644
index 000000000..10488d596
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_getSplitList.sql
@@ -0,0 +1,160 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getSplitList`(vDated DATE, vHour TIME, vWarehouseFk INT)
+BEGIN
+/**
+ * Devuelve un listado con los tickets posibles para splitar HOY.
+ *
+ * @param vDated Fecha a estudiar
+ * @param vHour Hora a partir de la cual todavía se puede enviar, si la fecha es la de hoy
+ * @param vWarehouseFk Almacén
+ */
+ DECLARE vAvailableCache INT;
+ DECLARE vVisibleCache INT;
+
+ CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouseFk, util.VN_CURDATE());
+ CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk);
+ CALL `vn`.`zoneClosure_recalc`();
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.salesToSplit
+ (saleFk INT PRIMARY KEY,
+ ticketFk INT,
+ problem VARCHAR(1),
+ INDEX(ticketFk)) ENGINE = MEMORY;
+
+ CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock_byWarehouse
+ (INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT ish.itemFk itemFk,
+ SUM(ish.visible) visible,
+ s.warehouseFk warehouseFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector s ON s.id = p.sectorFk
+ GROUP BY ish.itemFk,
+ s.warehouseFk;
+
+ INSERT INTO tmp.salesToSplit(saleFk, ticketFk, problem)
+ SELECT s.id, s.ticketFk, 'F'
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = i.id
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN cache.available av ON av.item_id = i.id
+ AND av.calc_id = vAvailableCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible,0) < s.quantity
+ AND IFNULL(av.available ,0) < s.quantity
+ AND IFNULL(issw.visible, 0) < s.quantity
+ AND s.isPicked = FALSE
+ AND s.reserved = FALSE
+ AND ic.merchandise = TRUE
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND NOT i.generic
+ AND t.warehouseFk = vWarehouseFk;
+
+ INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem)
+ SELECT s.id, s.ticketFk, 'I'
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = s.itemFk
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible,0) >= s.quantity
+ AND IFNULL(issw.visible, 0) < s.quantity
+ AND s.quantity > 0
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND NOT i.generic
+ AND t.warehouseFk = vWarehouseFk;
+
+ INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem)
+ SELECT s.id, s.ticketFk, 'R'
+ FROM ticket t
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ LEFT JOIN cache.visible v ON v.item_id = s.itemFk
+ AND v.calc_id = vVisibleCache
+ LEFT JOIN cache.available av ON av.item_id = i.id
+ AND av.calc_id = vAvailableCache
+ LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
+ AND issw.warehouseFk = t.warehouseFk
+ WHERE IFNULL(v.visible,0) < s.quantity
+ AND IFNULL(av.available ,0) >= s.quantity
+ AND IFNULL(issw.visible, 0) < s.quantity
+ AND s.quantity > 0
+ AND NOT s.isPicked
+ AND NOT s.reserved
+ AND ic.merchandise
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
+ AND NOT i.generic
+ AND t.warehouseFk = vWarehouseFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTicketsToSplit(
+ ticketFk INT PRIMARY KEY,
+ problems VARCHAR(100),
+ addressFk INT,
+ ipt VARCHAR(10),
+ etd TIME,
+ INDEX(addressFk)
+ ) ENGINE = MEMORY;
+
+ INSERT INTO tTicketsToSplit
+ SELECT ss.ticketFk,
+ GROUP_CONCAT(DISTINCT ss.problem ORDER BY ss.problem) problems,
+ t.addressFk,
+ GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
+ DATE_FORMAT(IF(HOUR(t.shipped),
+ t.shipped,
+ IFNULL(zc.hour, z.HOUR)),'%H:%i') etd
+ FROM tmp.salesToSplit ss
+ JOIN ticket t ON t.id = ss.ticketFk
+ JOIN sale s ON s.id = ss.saleFk
+ JOIN item i ON i.id = s.itemFk
+ LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
+ LEFT JOIN zone z ON z.id = t.zoneFk
+ GROUP BY ss.ticketFk;
+
+ SELECT ts.*,
+ t.id ticketFuture,
+ st.name state,
+ zc.`hour` tfEtd,
+ GROUP_CONCAT(
+ DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk
+ ) tfIpt,
+ st2.name tfState
+ FROM tTicketsToSplit ts
+ LEFT JOIN ticketState ts2 ON ts2.ticketFk = ts.ticketFk
+ LEFT JOIN `state` st ON st.id = ts2.stateFk
+ LEFT JOIN ticket t ON t.id != ts.ticketFk
+ AND t.addressFk = ts.addressFk
+ AND t.shipped BETWEEN vDated AND util.dayend(vDated)
+ LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated
+ LEFT JOIN sale s ON s.ticketFk = t.id
+ LEFT JOIN item i ON i.id = s.itemFk
+ LEFT JOIN ticketState tst ON tst.ticketFk = t.id
+ LEFT JOIN state st2 ON st2.id = tst.stateFk
+ WHERE (t.id IS NULL
+ OR (vDated > util.VN_CURDATE())
+ OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`))
+ AND ts.etd <= vHour
+ GROUP BY ts.ticketFk, t.id
+ ORDER BY ts.etd, ts.ticketFk;
+
+ DROP TEMPORARY TABLE
+ tTicketsToSplit,
+ tItemShelvingStock_byWarehouse;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_getTax.sql b/db/routines/vn/procedures/ticket_getTax.sql
new file mode 100644
index 000000000..b9f5c14e3
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_getTax.sql
@@ -0,0 +1,103 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getTax`(IN vTaxArea VARCHAR(25))
+BEGIN
+/**
+ * Calcula la base imponible, el IVA y el recargo de equivalencia para
+ * un conjunto de tickets.
+ *
+ * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
+ * @return tmp.ticketAmount (ticketFk, taxableBase, tax, code)
+ * @return tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code) Impuesto desglosado para cada ticket.
+ */
+ -- Mantengo el drop porque si no da error en los tests de back de salix
+ -- Table 'addressCompany' was locked with a READ lock and can't be updated'
+ DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
+ CREATE TEMPORARY TABLE tmp.addressCompany
+ (INDEX (addressFk, companyFk))
+ ENGINE = MEMORY
+ SELECT DISTINCT t.addressFk, t.companyFk
+ FROM tmp.ticket tmpTicket
+ JOIN ticket t ON t.id = tmpTicket.ticketFk;
+
+ CALL addressTaxArea();
+
+ IF vTaxArea IS NOT NULL THEN
+ UPDATE tmp.addressTaxArea
+ SET areaFk = vTaxArea;
+ END IF;
+
+ -- Solo se calcula la base imponible (taxableBase) y
+ -- el impuesto se calculará posteriormente
+ -- No se debería cambiar el sistema por problemas con los decimales
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketTax
+ (PRIMARY KEY (ticketFk, code, rate))
+ ENGINE = MEMORY
+ SELECT * FROM (
+ SELECT tmpTicket.ticketFk,
+ bp.pgcFk,
+ SUM(s.quantity * s.price * (100 - s.discount) / 100 ) taxableBase,
+ pgc.rate,
+ tc.code,
+ bp.priority
+ FROM tmp.ticket tmpTicket
+ JOIN sale s ON s.ticketFk = tmpTicket.ticketFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticket t ON t.id = tmpTicket.ticketFk
+ JOIN supplier su ON su.id = t.companyFk
+ JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk
+ AND ata.companyFk = t.companyFk
+ JOIN itemTaxCountry itc ON itc.itemFk = i.id
+ AND itc.countryFk = su.countryFk
+ JOIN bookingPlanner bp ON bp.countryFk = su.countryFk
+ AND bp.taxAreaFk = ata.areaFk
+ AND bp.taxClassFk = itc.taxClassFk
+ JOIN pgc ON pgc.code = bp.pgcFk
+ JOIN taxClass tc ON tc.id = bp.taxClassFk
+ GROUP BY tmpTicket.ticketFk, pgc.code, pgc.rate
+ HAVING taxableBase
+ ) t3
+ ORDER BY priority;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketServiceTax
+ (PRIMARY KEY (ticketFk, code, rate))
+ ENGINE = MEMORY
+ SELECT tt.ticketFk,
+ pgc.code pgcFk,
+ SUM(ts.quantity * ts.price) taxableBase,
+ pgc.rate,
+ tc.code
+ FROM tmp.ticket tt
+ JOIN ticketService ts ON ts.ticketFk = tt.ticketFk
+ JOIN ticket t ON t.id = tt.ticketFk
+ JOIN supplier su ON su.id = t.companyFk
+ JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk
+ AND ata.companyFk = t.companyFk
+ JOIN bookingPlanner bp ON bp.countryFk = su.countryFk
+ AND bp.taxAreaFk = ata.areaFk
+ AND bp.taxClassFk = ts.taxClassFk
+ JOIN pgc ON pgc.code = bp.pgcFk
+ JOIN taxClass tc ON tc.id = bp.taxClassFk
+ GROUP BY tt.ticketFk, pgc.code
+ HAVING taxableBase;
+
+ INSERT INTO tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code)
+ SELECT ts.ticketFk, ts.pgcFk, ts.taxableBase, ts.rate, ts.code
+ FROM tmp.ticketServiceTax ts
+ ON DUPLICATE KEY UPDATE ticketTax.taxableBase = VALUES (taxableBase) + ticketTax.taxableBase ;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketAmount
+ (INDEX (ticketFk))
+ ENGINE = MEMORY
+ SELECT ticketFk,
+ taxableBase,
+ SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax,
+ code
+ FROM tmp.ticketTax
+ GROUP BY ticketFk, code;
+
+ DROP TEMPORARY TABLE
+ tmp.addressCompany,
+ tmp.addressTaxArea;
+END$$
+DELIMITER ;
diff --git a/db/changes/231201/00-ticket_getWarnings.sql b/db/routines/vn/procedures/ticket_getWarnings.sql
similarity index 58%
rename from db/changes/231201/00-ticket_getWarnings.sql
rename to db/routines/vn/procedures/ticket_getWarnings.sql
index 5253b58ab..0bda30446 100644
--- a/db/changes/231201/00-ticket_getWarnings.sql
+++ b/db/routines/vn/procedures/ticket_getWarnings.sql
@@ -1,8 +1,5 @@
-DROP PROCEDURE IF EXISTS `vn`.`ticket_getWarnings`;
-
DELIMITER $$
-$$
-CREATE PROCEDURE `vn`.`ticket_getWarnings`()
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getWarnings`()
BEGIN
/**
* Calcula las adventencias para un conjunto de tickets.
@@ -11,16 +8,15 @@ BEGIN
* @table tmp.sale_getWarnings(ticketFk) Identificadores de los tickets a calcular
* @return tmp.ticket_warnings
*/
- DROP TEMPORARY TABLE IF EXISTS tmp.sale_warnings;
- CREATE TEMPORARY TABLE tmp.sale_warnings (
+ CREATE OR REPLACE TEMPORARY TABLE tSaleWarnings (
ticketFk INT(11),
saleFk INT(11),
isFragile INTEGER(1) DEFAULT 0,
PRIMARY KEY (ticketFk, saleFk)
) ENGINE = MEMORY;
- -- Frágil
- INSERT INTO tmp.sale_warnings(ticketFk, saleFk, isFragile)
+ -- Fragile
+ INSERT INTO tSaleWarnings(ticketFk, saleFk, isFragile)
SELECT tt.ticketFk, s.id, TRUE
FROM tmp.sale_getWarnings tt
LEFT JOIN sale s ON s.ticketFk = tt.ticketFk
@@ -31,17 +27,16 @@ BEGIN
WHERE dm.code IN ('AGENCY')
AND it.isFragile;
- DROP TEMPORARY TABLE IF EXISTS tmp.ticket_warnings;
- CREATE TEMPORARY TABLE tmp.ticket_warnings
- (PRIMARY KEY (ticketFk))
- ENGINE = MEMORY
- SELECT
- sw.ticketFk,
- MAX(sw.isFragile) AS isFragile
- FROM tmp.sale_warnings sw
- GROUP BY sw.ticketFk;
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_warnings
+ (PRIMARY KEY (ticketFk))
+ ENGINE = MEMORY
+ SELECT
+ sw.ticketFk,
+ MAX(sw.isFragile) AS isFragile
+ FROM tSaleWarnings sw
+ GROUP BY sw.ticketFk;
DROP TEMPORARY TABLE
- tmp.sale_warnings;
+ tSaleWarnings;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_getWithParameters.sql b/db/routines/vn/procedures/ticket_getWithParameters.sql
new file mode 100644
index 000000000..2d3d09311
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_getWithParameters.sql
@@ -0,0 +1,49 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getWithParameters`(
+ vClientFk INT,
+ vWarehouseFk INT,
+ vShipped DATE,
+ vAddressFk INT,
+ vCompanyFk INT,
+ vAgencyModeFk INT,
+ OUT vTicketFk INT
+ )
+BEGIN
+/**
+ * Devuelve un ticket con los parametros, en caso de no existir lo crea
+ *
+ * @param vClientFk Cliente
+ * @param vWarehouseFk almacen
+ * @param vShipped Fecha de preparacion
+ * @param vAddressFk Consignatario
+ * @param vCompanyFk Empresa
+ * @param vAgencyModeFk agencia
+ */
+
+ SELECT t.id INTO vTicketFk
+ FROM vn.ticket t
+ WHERE t.clientFk <=> vClientFk
+ AND t.warehouseFk <=> vWarehouseFk
+ AND (t.shipped <=> vShipped OR vShipped IS NULL)
+ AND (t.addressFk <=> vAddressFk OR vAddressFk IS NULL)
+ AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL)
+ AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL)
+ LIMIT 1;
+
+ IF vTicketFk IS NULL THEN
+ CALL vn.ticket_add(
+ vClientFk,
+ IFNULL(vShipped, util.VN_CURDATE()),
+ vWarehouseFk,
+ vCompanyFk,
+ vAddressFk,
+ vAgencyModeFk,
+ NULL,
+ vShipped,
+ `account`.`myUser_getId`(),
+ TRUE,
+ vTicketFk
+ );
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_insertZone.sql b/db/routines/vn/procedures/ticket_insertZone.sql
new file mode 100644
index 000000000..ee6eabdec
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_insertZone.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_insertZone`()
+BEGIN
+ DECLARE vDone INT DEFAULT 0;
+ DECLARE vFechedTicket INT;
+ DECLARE vLanded DATE;
+ DECLARE vAddressFk INT;
+ DECLARE vAgencyModeFk INT;
+ DECLARE vWarehouseFk INT;
+ DECLARE vCursor CURSOR FOR
+ SELECT id, landed, addressFk, agencyModeFk, warehouseFk
+ FROM vn.ticket WHERE shipped > '2020-01-01' AND zoneFk is null;
+ DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1;
+
+ OPEN vCursor;
+ REPEAT
+ FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk;
+ CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE);
+
+ UPDATE vn.ticket t
+ JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk
+ SET t.zoneFk = zgs.zoneFk
+ WHERE t.id = vFechedTicket;
+
+ UNTIL vDone END REPEAT;
+ DROP TEMPORARY TABLE tmp.zoneGetShipped;
+
+ CLOSE vCursor;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_priceDifference.sql b/db/routines/vn/procedures/ticket_priceDifference.sql
new file mode 100644
index 000000000..4ef168840
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_priceDifference.sql
@@ -0,0 +1,44 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_priceDifference`(
+ vTicketFk INT,
+ vLanded DATE,
+ vAddressFk INT,
+ vZoneFk INT,
+ vWarehouseFk INT)
+BEGIN
+/**
+ * Devuelve las diferencias de precio de los movimientos de un ticket.
+ *
+ * @param vTicketFk Id del ticket
+ * @param vLanded Fecha de recepcion
+ * @param vAddressFk Id del consignatario
+ * @param vZoneFk Id de la zona
+ * @param vWarehouseFk Id del almacén
+ */
+ CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk);
+
+ SELECT s.itemFk,
+ i.name,
+ i.size,
+ i.category,
+ IFNULL(s.quantity, 0) AS quantity,
+ IFNULL(s.price, 0) AS price,
+ ROUND(SUM(tc.cost), 2) AS newPrice,
+ s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference,
+ s.id AS saleFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticket t ON t.id = s.ticketFk
+ LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk
+ AND tc.warehouseFk = vWarehouseFk
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ AND sc.componentFk = tc.componentFk
+ LEFT JOIN `component` c ON c.id = tc.componentFk
+ WHERE t.id = vTicketFk
+ AND IF(sc.componentFk IS NULL
+ AND c.classRate IS NOT NULL, FALSE, TRUE)
+ GROUP BY s.id ORDER BY s.id;
+
+ DROP TEMPORARY TABLE tmp.ticketComponentPreview;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_printLabelPrevious.sql b/db/routines/vn/procedures/ticket_printLabelPrevious.sql
new file mode 100644
index 000000000..cba42ff3e
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_printLabelPrevious.sql
@@ -0,0 +1,33 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_printLabelPrevious`(vTicketFk INT)
+BEGIN
+/**
+ * Calls the report_print procedure and passes it
+ * the necessary parameters for printing.
+ *
+ * @param vTicketFk id ticket to print.
+ */
+ DECLARE vPrinterFk INT;
+ DECLARE vSaleGroup INT;
+ DECLARE vUserFk INT DEFAULT account.myUser_getId();
+
+ SELECT sg.id, o.labelerFk INTO vSaleGroup, vPrinterFk
+ FROM saleGroup sg
+ JOIN sector sc ON sc.id = sg.sectorFk
+ JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk
+ JOIN sale s ON sgd.saleFk = s.id
+ JOIN ticket t ON s.ticketFk = t.id
+ JOIN operator o ON o.workerFk = vUserFk
+ WHERE sc.id = o.sectorFk
+ AND t.id = vTicketFk
+ LIMIT 1;
+
+ CALL report_print(
+ 'LabelPrevia',
+ vPrinterFk,
+ vUserFk,
+ JSON_OBJECT('id', vSaleGroup, 'userFk', vUserFk),
+ 'high'
+ );
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_recalc.sql b/db/routines/vn/procedures/ticket_recalc.sql
new file mode 100644
index 000000000..50065d03a
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_recalc.sql
@@ -0,0 +1,37 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_recalc`(vSelf INT, vTaxArea VARCHAR(25))
+proc:BEGIN
+/**
+ * Calcula y guarda el total con/sin IVA en un ticket.
+ *
+ * @param vSelf Identificador del ticket
+ * @param vTaxArea
+ */
+ DECLARE hasInvoice BOOL;
+
+ SELECT COUNT(*) INTO hasInvoice
+ FROM ticket
+ WHERE id = vSelf
+ AND refFk IS NOT NULL;
+
+ IF hasInvoice THEN
+ LEAVE proc;
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
+ CREATE TEMPORARY TABLE tmp.ticket
+ ENGINE = MEMORY
+ SELECT vSelf ticketFk;
+
+ CALL ticketGetTotal(vTaxArea);
+
+ UPDATE ticket t
+ JOIN tmp.ticketTotal tt ON tt.ticketFk = t.id
+ SET t.totalWithVat = tt.total,
+ t.totalWithoutVat = tt.totalWithoutVat;
+
+ DROP TEMPORARY TABLE
+ tmp.ticket,
+ tmp.ticketTotal;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_recalcComponents.sql b/db/routines/vn/procedures/ticket_recalcComponents.sql
new file mode 100644
index 000000000..0282c0e42
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_recalcComponents.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_recalcComponents`(vSelf INT, vOption VARCHAR(25))
+proc: BEGIN
+
+/**
+ * Crea tabla temporal para sale_recalcComponent() para recalcular los componentes
+ *
+ * @param vSelf Id del ticket
+ * @param vOption si no se quiere forzar llamar con NULL
+ */
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
+ SELECT s.id
+ FROM sale s
+ WHERE s.ticketFk = vSelf;
+
+ CALL sale_recalcComponent(vOption);
+
+ DROP TEMPORARY TABLE tmp.recalculateSales;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_requestRecalc.sql b/db/routines/vn/procedures/ticket_requestRecalc.sql
new file mode 100644
index 000000000..6636e4c0f
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_requestRecalc.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_requestRecalc`(vSelf INT)
+proc: BEGIN
+/**
+ * Adds a request to recalculate the ticket total.
+ *
+ * @param vSelf The ticket identifier
+ */
+ IF vSelf IS NULL THEN
+ LEAVE proc;
+ END IF;
+
+ INSERT INTO ticketRecalc SET ticketFk = vSelf;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_setNextState.sql b/db/routines/vn/procedures/ticket_setNextState.sql
new file mode 100644
index 000000000..d13cd53f0
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_setNextState.sql
@@ -0,0 +1,23 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setNextState`(vSelf INT)
+BEGIN
+/**
+ * Cambia el estado del ticket al siguiente estado según la tabla state
+ *
+ * @param vSelf id dle ticket
+ */
+ DECLARE vStateFk INT;
+ DECLARE vNewStateFk INT;
+
+ SELECT stateFk INTO vStateFk
+ FROM ticketState
+ WHERE ticketFk = vSelf;
+
+ SELECT nextStateFk INTO vNewStateFk
+ FROM state
+ WHERE id = vStateFk;
+
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
+ VALUES (vNewStateFk, vSelf, account.myUser_getId());
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_setParking.sql b/db/routines/vn/procedures/ticket_setParking.sql
new file mode 100644
index 000000000..54c64daea
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_setParking.sql
@@ -0,0 +1,42 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setParking`(IN `vTicketFk` VARCHAR(8), IN `vParkingFk` INT)
+proc: BEGIN
+/**
+ * Aparca un ticket en un parking
+ *
+ * @param vTicketFk id del ticket
+ * @param vParkingFk id del parking
+ */
+ DECLARE vDone INT DEFAULT FALSE;
+ DECLARE vCollectionTicketFk INT;
+ DECLARE vCursor CURSOR FOR
+ SELECT IFNULL(tc2.ticketFk, t.id)
+ FROM ticket t
+ LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id
+ LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk
+ WHERE t.id = vTicketFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ INSERT INTO vn.ticketParking(ticketFk, parkingFk)
+ SELECT IFNULL(tc2.ticketFk, t.id), vParkingFk
+ FROM ticket t
+ LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id
+ LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk
+ WHERE t.id = vTicketFk
+ ON DUPLICATE KEY UPDATE parkingFk = vParkingFk;
+
+ OPEN vCursor;
+ l: LOOP
+ FETCH vCursor INTO vCollectionTicketFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL vn.ticket_setNextState(vCollectionTicketFk);
+ END LOOP;
+
+ CLOSE vCursor;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_setPreviousState.sql b/db/routines/vn/procedures/ticket_setPreviousState.sql
new file mode 100644
index 000000000..c03d41b09
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_setPreviousState.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setPreviousState`(vTicketFk INT)
+BEGIN
+ DECLARE vControlFk INT;
+
+ SELECT MAX(id) INTO vControlFk
+ FROM ticketTracking
+ WHERE ticketFk = vTicketFk;
+
+ IF (SELECT s.code
+ FROM vn.state s
+ JOIN ticketTracking tt ON tt.stateFk = s.id
+ WHERE tt.id = vControlFk)
+ = 'PREVIOUS_PREPARATION' THEN
+ SELECT id
+ INTO vControlFk
+ FROM ticketTracking tt
+ JOIN vn.state s ON tt.stateFk = s.id
+ WHERE ticketFk = vTicketFk
+ AND id < vControlFk
+ AND s.code != 'PREVIOUS_PREPARATION'
+ ORDER BY id DESC
+ LIMIT 1;
+
+ INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
+ SELECT s.nextStateFk, tt.ticketFk, account.myUser_getId()
+ FROM ticketTracking tt
+ JOIN vn.state s ON tt.stateFk = s.id
+ WHERE id = vControlFk;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_setState.sql b/db/routines/vn/procedures/ticket_setState.sql
new file mode 100644
index 000000000..bde8e0692
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_setState.sql
@@ -0,0 +1,56 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setState`(
+ vSelf INT,
+ vStateCode VARCHAR(255) COLLATE utf8_general_ci
+)
+BEGIN
+/**
+ * Modifica el estado de un ticket si se cumplen las condiciones necesarias.
+ *
+ * @param vSelf el id del ticket
+ * @param vStateCode estado a modificar del ticket
+ */
+ DECLARE vticketAlertLevel INT;
+ DECLARE vTicketStateCode VARCHAR(255);
+ DECLARE vCanChangeState BOOL;
+ DECLARE vPackedAlertLevel INT;
+ DECLARE vZoneFk INT;
+
+ SELECT s.alertLevel, s.`code`, t.zoneFk
+ INTO vticketAlertLevel, vTicketStateCode, vZoneFk
+ FROM state s
+ JOIN ticketTracking tt ON tt.stateFk = s.id
+ JOIN ticket t ON t.id = tt.ticketFk
+ WHERE tt.ticketFk = vSelf
+ ORDER BY tt.created DESC
+ LIMIT 1;
+
+ SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED';
+
+ IF vStateCode = 'OK' AND vZoneFk IS NULL THEN
+ CALL util.throw('ASSIGN_ZONE_FIRST');
+ END IF;
+
+ SET vCanChangeState = ((
+ vStateCode <> 'ON_CHECKING' AND vStateCode <> 'CHECKED') OR
+ vticketAlertLevel < vPackedAlertLevel
+ )AND NOT (
+ vTicketStateCode IN ('CHECKED', 'CHECKING')
+ AND vStateCode IN ('PREPARED', 'ON_PREPARATION')
+ );
+
+ IF vCanChangeState THEN
+ INSERT INTO ticketTracking (stateFk, ticketFk, userFk)
+ SELECT id, vSelf, account.myUser_getId()
+ FROM state
+ WHERE `code` = vStateCode COLLATE utf8_unicode_ci;
+
+ IF vStateCode = 'PACKED' THEN
+ CALL ticket_doCmr(vSelf);
+ END IF;
+ ELSE
+ CALL util.throw('INCORRECT_TICKET_STATE');
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_split.sql b/db/routines/vn/procedures/ticket_split.sql
new file mode 100644
index 000000000..172f6829a
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_split.sql
@@ -0,0 +1,76 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_split`(vTicketFk INT, vTicketFutureFk INT, vDated DATE)
+proc:BEGIN
+/**
+ * Mueve las lineas con problemas a otro ticket existente o a uno nuevo.
+ *
+ * @param vTicketFk Identificador del ticket a splittar
+ * @param vTicketFutureFk Identificador del ticket al que se quieren mover las lineas
+ * @param vDate Fecha a la que se va a mover
+ * @table tmp.salesToSplit(saleFk, ticketFk, problem)
+ */
+ DECLARE vHasFullProblem BOOL;
+ DECLARE vProblemLines INT;
+ DECLARE vTotalLines INT;
+
+ SELECT COUNT(*) INTO vProblemLines
+ FROM tmp.salesToSplit
+ WHERE ticketFk = vTicketFk;
+
+ SELECT count(*) INTO vTotalLines
+ FROM vn.sale s
+ WHERE s.ticketFk = vTicketFk;
+
+ SET vHasFullProblem = (vTotalLines = vProblemLines);
+
+ -- Ticket completo
+ IF vHasFullProblem THEN
+
+ UPDATE vn.ticket
+ SET landed = vDated + INTERVAL 1 DAY,
+ shipped = vDated,
+ nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname )
+ WHERE id = vTicketFk;
+
+ SELECT "moved" message, NULL ticketFuture;
+ LEAVE proc;
+
+ END IF;
+
+ -- Ticket a futuro existe
+ IF vTicketFutureFk THEN
+
+ UPDATE vn.sale s
+ JOIN tmp.salesToSplit ss ON s.id = ss.saleFk
+ SET s.ticketFk = vTicketFutureFk,
+ s.concept = CONCAT('(s) ', s.concept)
+ WHERE ss.ticketFk = vTicketFk;
+
+ SELECT "future" message, NULL ticketFuture;
+ LEAVE proc;
+
+ END IF;
+
+ -- Ticket nuevo
+ CALL vn.ticket_Clone(vTicketFk, vTicketFutureFk);
+
+ UPDATE vn.ticket t
+ JOIN vn.productionConfig pc
+ SET t.routeFk = IF(t.shipped = vDated , t.routeFk, NULL),
+ t.landed = vDated + INTERVAL 1 DAY,
+ t.shipped = vDated,
+ t.agencyModeFk = pc.defautlAgencyMode,
+ t.zoneFk = pc.defaultZone
+ WHERE t.id = vTicketFutureFk;
+
+ UPDATE vn.sale s
+ JOIN tmp.salesToSplit sts ON sts.saleFk = s.id
+ SET s.ticketFk = vTicketFutureFk,
+ s.concept = CONCAT('(s) ', s.concept)
+ WHERE sts.ticketFk = vTicketFk;
+
+ CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING');
+
+ SELECT "new" message,vTicketFutureFk ticketFuture;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql
new file mode 100644
index 000000000..d6424efad
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql
@@ -0,0 +1,106 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitItemPackingType`(vTicketFk INT, vOriginalItemPackingTypeFk VARCHAR(1))
+proc:BEGIN
+/**
+ * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado.
+ * Respeta el id inicial para el tipo propuesto.
+ *
+ * @param vTicketFk Identificador de vn.ticket
+ * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original
+ * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk)
+ */
+ DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H';
+ DECLARE vNewTicketFk INT;
+ DECLARE vPackingTypesToSplit INT;
+ DECLARE vDone INT DEFAULT FALSE;
+
+ DECLARE cur1 CURSOR FOR
+ SELECT itemPackingTypeFk
+ FROM tmp.saleGroup
+ WHERE itemPackingTypeFk IS NOT NULL
+ ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DELETE FROM vn.sale
+ WHERE quantity = 0
+ AND ticketFk = vTicketFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.sale;
+ CREATE TEMPORARY TABLE tmp.sale
+ (PRIMARY KEY (id))
+ SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros
+ FROM vn.sale s
+ JOIN vn.item i ON i.id = s.itemFk
+ LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id
+ WHERE s.ticketFk = vTicketFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.saleGroup;
+ CREATE TEMPORARY TABLE tmp.saleGroup
+ SELECT itemPackingTypeFk , sum(litros) AS totalLitros
+ FROM tmp.sale
+ GROUP BY itemPackingTypeFk;
+
+ SELECT COUNT(*) INTO vPackingTypesToSplit
+ FROM tmp.saleGroup
+ WHERE itemPackingTypeFk IS NOT NULL;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketIPT;
+ CREATE TEMPORARY TABLE tmp.ticketIPT
+ (ticketFk INT,
+ itemPackingTypeFk VARCHAR(1));
+
+ CASE vPackingTypesToSplit
+ WHEN 0 THEN
+ INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
+ VALUES(vTicketFk, vItemPackingTypeFk);
+ WHEN 1 THEN
+ INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
+ SELECT vTicketFk, itemPackingTypeFk
+ FROM tmp.saleGroup
+ WHERE itemPackingTypeFk IS NOT NULL;
+ ELSE
+ OPEN cur1;
+
+ FETCH cur1 INTO vItemPackingTypeFk;
+
+ INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
+ VALUES(vTicketFk, vItemPackingTypeFk);
+
+ read_loop: LOOP
+ FETCH cur1 INTO vItemPackingTypeFk;
+
+ IF vDone THEN
+ LEAVE read_loop;
+ END IF;
+
+ CALL vn.ticket_Clone(vTicketFk, vNewTicketFk);
+
+ INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
+ VALUES(vNewTicketFk, vItemPackingTypeFk);
+ END LOOP;
+
+ CLOSE cur1;
+
+ UPDATE vn.sale s
+ JOIN tmp.sale ts ON ts.id = s.id
+ JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk
+ SET s.ticketFk = t.ticketFk;
+
+ SELECT itemPackingTypeFk INTO vItemPackingTypeFk
+ FROM tmp.saleGroup sg
+ WHERE NOT ISNULL(sg.itemPackingTypeFk)
+ ORDER BY sg.itemPackingTypeFk
+ LIMIT 1;
+
+ UPDATE vn.sale s
+ JOIN tmp.sale ts ON ts.id = s.id
+ JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk
+ SET s.ticketFk = t.ticketFk
+ WHERE ts.itemPackingTypeFk IS NULL;
+ END CASE;
+
+ DROP TEMPORARY TABLE tmp.sale;
+ DROP TEMPORARY TABLE tmp.saleGroup;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_splitPackingComplete.sql b/db/routines/vn/procedures/ticket_splitPackingComplete.sql
new file mode 100644
index 000000000..528e8fbed
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_splitPackingComplete.sql
@@ -0,0 +1,42 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitPackingComplete`(vTicketFk INT, vSectorFk INT)
+BEGIN
+
+ DECLARE vNeedToSplit BOOLEAN;
+ DECLARE vNewTicketFk INT;
+
+ DROP TEMPORARY TABLE IF EXISTS tmpSale;
+
+ CREATE TEMPORARY TABLE tmpSale
+ SELECT DISTINCT s.id
+ FROM vn.ticket t
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.item i ON i.id = s.itemFk
+ LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = vSectorFk
+ JOIN vn.packagingConfig pc
+ WHERE t.id = vTicketFk
+ AND ( s.quantity MOD IFNULL(iss.packing,1) != 0
+ OR
+ IFNULL(iss.packing,1) = 1
+ OR
+ i.`size` <= pc.previousPreparationMinimumSize
+ );
+
+ SELECT COUNT(*)
+ INTO vNeedToSplit
+ FROM tmpSale;
+
+ IF vNeedToSplit THEN
+
+ CALL vn.ticket_Clone(vTicketFk, vNewTicketFk);
+
+ UPDATE vn.sale s
+ JOIN vn.tmpSale ts ON ts.id = s.id
+ SET s.ticketFk = vNewTicketFk;
+
+ END IF;
+
+ DROP TEMPORARY TABLE tmpSale;
+
+END$$
+DELIMITER ;
diff --git a/db/changes/234001/00-timeBusiness_calculate.sql b/db/routines/vn/procedures/timeBusiness_calculate.sql
similarity index 99%
rename from db/changes/234001/00-timeBusiness_calculate.sql
rename to db/routines/vn/procedures/timeBusiness_calculate.sql
index 599dba74a..3cb734069 100644
--- a/db/changes/234001/00-timeBusiness_calculate.sql
+++ b/db/routines/vn/procedures/timeBusiness_calculate.sql
@@ -1,5 +1,4 @@
DELIMITER $$
-$$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
/**
@@ -14,7 +13,7 @@ BEGIN
(INDEX (departmentFk))
SELECT dated,
businessFk,
- sub.id userFk,
+ sub.id userFk,
departmentFk,
hourStart,
hourEnd,
diff --git a/db/routines/vn/procedures/timeBusiness_calculateAll.sql b/db/routines/vn/procedures/timeBusiness_calculateAll.sql
new file mode 100644
index 000000000..4e0ac7da5
--- /dev/null
+++ b/db/routines/vn/procedures/timeBusiness_calculateAll.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeBusiness_calculateAll`(vDatedFrom DATETIME, vDatedTo DATETIME)
+BEGIN
+
+/**
+ * @param vDatedFrom Fecha desde
+ * @param vDatedTo Fecha hasta
+ */
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
+ SELECT w.id userFk
+ FROM vn.worker w;
+
+ CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo);
+
+ DROP TEMPORARY TABLE tmp.`user`;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/timeBusiness_calculateByDepartment.sql b/db/routines/vn/procedures/timeBusiness_calculateByDepartment.sql
new file mode 100644
index 000000000..54c587342
--- /dev/null
+++ b/db/routines/vn/procedures/timeBusiness_calculateByDepartment.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeBusiness_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
+BEGIN
+/**
+ * @param vDepartmentFk
+ * @param vDatedFrom workerTimeControl
+ * @param vDatedTo workerTimeControl
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
+
+ CREATE TEMPORARY TABLE tmp.`user`
+ SELECT DISTINCT b.workerFk userFk
+ FROM business AS b
+ WHERE (b.started BETWEEN vDatedFrom AND vDatedTo
+ OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo
+ OR (b.started <= vDatedFrom AND b.ended >= vDatedTo)
+ ) AND b.departmentFk = vDepartmentFk
+ ORDER BY b.ended DESC;
+
+ CALL timeBusiness_calculate(vDatedFrom, vDatedTo);
+
+ DROP TEMPORARY TABLE tmp.`user`;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/timeBusiness_calculateByUser.sql b/db/routines/vn/procedures/timeBusiness_calculateByUser.sql
new file mode 100644
index 000000000..a54dfcc2e
--- /dev/null
+++ b/db/routines/vn/procedures/timeBusiness_calculateByUser.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeBusiness_calculateByUser`(vUserFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
+BEGIN
+
+/**
+ * @param vUserFk
+ * @param vDatedFrom workerTimeControl
+ * @param vDatedTo workerTimeControl
+ */
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
+
+ CREATE TEMPORARY TABLE tmp.`user`
+ SELECT id userFk
+ FROM account.user
+ WHERE id = vUserFk;
+ CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo);
+
+ DROP TEMPORARY TABLE tmp.`user`;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/timeBusiness_calculateByWorker.sql b/db/routines/vn/procedures/timeBusiness_calculateByWorker.sql
new file mode 100644
index 000000000..89a4c0ab0
--- /dev/null
+++ b/db/routines/vn/procedures/timeBusiness_calculateByWorker.sql
@@ -0,0 +1,21 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeBusiness_calculateByWorker`(vWorkerFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
+BEGIN
+
+/**
+ * @param vWorkerFk
+ * @param vDatedFrom Fecha desde
+ * @param vDatedTo Fecha hasta
+ */
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
+ SELECT w.id userFk
+ FROM worker w
+ WHERE w.id = vWorkerFk;
+
+ CALL timeBusiness_calculate(vDatedFrom, vDatedTo);
+
+ DROP TEMPORARY TABLE tmp.`user`;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/timeControl_calculate.sql b/db/routines/vn/procedures/timeControl_calculate.sql
new file mode 100644
index 000000000..258960265
--- /dev/null
+++ b/db/routines/vn/procedures/timeControl_calculate.sql
@@ -0,0 +1,194 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_calculate`(
+ vDatedFrom DATETIME,
+ vDatedTo DATETIME)
+BEGIN
+/*
+ * Agrupa por trabajador y día, el tiempo de trabajo y descanso retribuido(si tiene).
+ * Los registros horarios incorrectos (tmp.timeControlError) no se considerarán.
+ * Si un trabajador ha trabajado más de un cierto umbral de tiempo (vTimeToBreakTime)
+ * y no ha tenido descansos que superen un parámetro determinado(vMaxTimeToBreak),
+ * se le añadirá un tiempo de descanso (vBreakTime) a sus horas trabajadas.
+ * El tiempo de descanso solo se añade si el trabajador realmente disfrutó del descanso.
+ * Si disfrutó de menos tiempo de descanso, solo se añade el tiempo que disfrutó.
+ *
+ * @param vDatedFrom
+ * @param vDatedTo
+ *
+ * @return tmp.timeControlCalculate
+ * (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed)
+ */
+ DECLARE vHourSeconds INTEGER;
+ DECLARE vDatedFromYesterday DATETIME;
+ DECLARE vDatedToTomorrow DATETIME;
+ DECLARE vTimeToBreakTime INT;
+ DECLARE vBreakTime INT;
+ DECLARE vMaxTimeToBreak INT;
+
+ SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY)
+ INTO vDatedFromYesterday, vDatedToTomorrow;
+
+ SELECT timeToBreakTime, breakTime, maxTimeToBreak, TIME_TO_SEC('01:00:00')
+ INTO vTimeToBreakTime, vBreakTime, vMaxTimeToBreak, vHourSeconds
+ FROM workerTimeControlConfig
+ LIMIT 1;
+
+ CALL timeControl_getError(vDatedFromYesterday, vDatedToTomorrow);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.workerTimeControl
+ (INDEX(userFk, timed), INDEX(timed), INDEX(direction))
+ ENGINE = MEMORY
+ SELECT wtc.userFk,
+ wtc.timed,
+ DATE(wtc.timed) dated,
+ wtc.direction,
+ TRUE isReal
+ FROM workerTimeControl wtc
+ JOIN tmp.`user` u ON u.userFk = wtc.userFk
+ LEFT JOIN (
+ SELECT wtc.userFk, MIN(wtc.timed) firstIn
+ FROM workerTimeControl wtc
+ JOIN tmp.`user` u ON u.userFk = wtc.userFk
+ LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
+ WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ AND wtc.direction = 'in'
+ AND tce.id IS NULL
+ GROUP BY userFk
+ ) fi ON wtc.userFk = fi.userFk
+ LEFT JOIN (
+ SELECT wtc.userFk, MAX(wtc.timed) lastOut
+ FROM workerTimeControl wtc
+ JOIN tmp.`user` u ON u.userFk = wtc.userFk
+ LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
+ WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ AND wtc.direction = 'out'
+ AND tce.id IS NULL
+ GROUP BY userFk
+ ) lo ON wtc.userFk = lo.userFk
+ LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
+ WHERE wtc.timed BETWEEN fi.firstIn AND lo.lastOut
+ AND tce.id IS NULL
+ ORDER BY wtc.userFk, wtc.timed;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.wtcToinsert
+ (INDEX(timed))
+ ENGINE = MEMORY
+ WITH wtc AS(
+ SELECT timed,
+ userFk,
+ dated,
+ direction,
+ LEAD(dated) OVER
+ (PARTITION BY userFk, dated ORDER BY timed) nextDay,
+ LEAD(userFk) OVER
+ (PARTITION BY userFk ORDER BY timed) nextUserFk,
+ ROW_NUMBER() OVER (ORDER BY userFk, timed) MOD 2 isOdd
+ FROM tmp.workerTimeControl
+ WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ ORDER BY userFk, timed
+ ), wtcToinsert AS(
+ SELECT userFk,
+ dated,
+ IF(userFk = nextUserFk
+ AND nextDay IS NULL
+ AND isOdd
+ AND direction <> 'out', TRUE, FALSE) outNextDay,
+ IF(userFk = nextUserFk
+ AND nextDay IS NULL
+ AND NOT isOdd
+ AND direction <> 'out', TRUE, FALSE) outNextDayWhitBreak
+ FROM wtc
+ HAVING outNextDay OR outNextDayWhitBreak
+ )SELECT userFk, util.dayEnd(dated) timed, 'out' direction
+ FROM wtcToinsert
+ WHERE outNextDay
+ UNION ALL
+ SELECT userFk, dated + INTERVAL 1 DAY, 'in'
+ FROM wtcToinsert
+ WHERE outNextDay
+ UNION ALL
+ SELECT userFk, util.dayEnd(dated) - INTERVAL 1 SECOND, 'middle'
+ FROM wtcToinsert
+ WHERE outNextDayWhitBreak
+ UNION ALL
+ SELECT userFk, util.dayEnd(dated), 'out'
+ FROM wtcToinsert
+ WHERE outNextDayWhitBreak
+ UNION ALL
+ SELECT userFk, dated + INTERVAL 1 DAY, 'in'
+ FROM wtcToinsert
+ WHERE outNextDayWhitBreak
+ UNION ALL
+ SELECT userFk, dated + INTERVAL 1 DAY + INTERVAL 1 SECOND, 'middle'
+ FROM wtcToinsert
+ WHERE outNextDayWhitBreak;
+
+ INSERT INTO tmp.workerTimeControl (userFk, timed, dated, direction, isReal)
+ SELECT userFk, timed, DATE(timed), direction, FALSE
+ FROM tmp.wtcToinsert;
+
+ SET @accumulatedForBreakTime = 0;
+ SET @oldrealDay = NULL;
+ CREATE OR REPLACE TEMPORARY TABLE tmp.timeControlCalculate
+ WITH workerTimed AS (
+ SELECT
+ userFk,
+ dated,
+ timed,
+ (direction ='in' AND isReal) breakPoint,
+ SUM(CASE WHEN (direction ='in' AND isReal) THEN TRUE ELSE FALSE END)
+ OVER (ORDER BY userFk, timed) AS realDay,
+ TIMESTAMPDIFF(SECOND, LAG(timed)
+ OVER (PARTITION BY userFk, dated ORDER BY timed), timed) gapTime,
+ ROW_NUMBER()
+ OVER (PARTITION BY userFk, dated ORDER BY timed) MOD 2 isOdd
+ FROM tmp.workerTimeControl
+ WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ ), accumulated AS (
+ SELECT SUM(IF(isOdd, 0, gapTime))
+ OVER (PARTITION BY userFk,dated ORDER BY userFk,timed) accumulatedWorkTime,
+ SUM(IF(NOT isOdd OR breakPoint OR gapTime >= vMaxTimeToBreak OR gapTime IS NULL, 0, gapTime))
+ OVER (PARTITION BY realDay ORDER BY realDay,timed) accumulatedBreakTime,
+ IF(realDay <> @oldrealDay OR (isOdd AND gapTime >= vMaxTimeToBreak),
+ @accumulatedForBreakTime := 0,
+ @accumulatedForBreakTime := @accumulatedForBreakTime +
+ IF(isOdd, 0, gapTime )) accumulatedForBreakTime,
+ @oldrealDay := realDay,
+ userFk,
+ dated,
+ realDay
+ FROM workerTimed
+ ), totalWorked AS (
+ SELECT userFk,
+ dated,
+ MAX(accumulatedWorkTime) +
+ IF(MAX(accumulatedForBreakTime) + LEAST(vBreakTime, MAX(accumulatedBreakTime)) >= vTimeToBreakTime,
+ LEAST(vBreakTime, MAX(accumulatedBreakTime)),
+ 0) timeWorkSeconds
+ FROM accumulated
+ GROUP BY userFk, dated
+ )SELECT tw.userFk,
+ tw.dated,
+ timeWorkSeconds,
+ SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal,
+ timeWorkSeconds / vHourSeconds timeWorkDecimal,
+ sub.tableTimed
+ FROM totalWorked tw
+ JOIN (
+ SELECT userFk,
+ dated,
+ GROUP_CONCAT(DATE_FORMAT(timed, "%H:%i") ORDER BY timed ASC
+ SEPARATOR ' - ')tableTimed
+ FROM tmp.workerTimeControl
+ WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ AND isReal
+ GROUP BY userFk, dated
+ )sub ON sub.dated = tw.dated
+ AND sub.userFk = tw.userFk
+ WHERE tw.dated BETWEEN vDatedFrom AND vDatedTo;
+
+ DROP TEMPORARY TABLE tmp.timeControlError;
+ DROP TEMPORARY TABLE tmp.wtcToinsert;
+ DROP TEMPORARY TABLE tmp.workerTimeControl;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/timeControl_calculateAll.sql b/db/routines/vn/procedures/timeControl_calculateAll.sql
new file mode 100644
index 000000000..c6354ad78
--- /dev/null
+++ b/db/routines/vn/procedures/timeControl_calculateAll.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_calculateAll`(vDatedFrom DATETIME, vDatedTo DATETIME)
+BEGIN
+
+/**
+ * @param vDatedFrom Fecha desde
+ * @param vDatedTo Fecha hasta
+ */
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
+ SELECT w.id userFk
+ FROM vn.worker w;
+
+ CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
+
+ DROP TEMPORARY TABLE tmp.`user`;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/timeControl_calculateByDepartment.sql b/db/routines/vn/procedures/timeControl_calculateByDepartment.sql
new file mode 100644
index 000000000..bb9ccec60
--- /dev/null
+++ b/db/routines/vn/procedures/timeControl_calculateByDepartment.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
+BEGIN
+/**
+ * @param vDepartmentFk
+ * @param vDatedFrom workerTimeControl
+ * @param vDatedTo workerTimeControl
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
+
+ CREATE TEMPORARY TABLE tmp.`user`
+ SELECT DISTINCT b.workerFk userFk
+ FROM business AS b
+ WHERE (b.started BETWEEN vDatedFrom AND vDatedTo
+ OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo
+ OR (b.started <= vDatedFrom AND b.ended >= vDatedTo)
+ ) AND b.departmentFk = vDepartmentFk
+ ORDER BY b.ended DESC;
+
+ CALL timeControl_calculate(vDatedFrom, vDatedTo);
+
+ DROP TEMPORARY TABLE tmp.`user`;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/timeControl_calculateByUser.sql b/db/routines/vn/procedures/timeControl_calculateByUser.sql
new file mode 100644
index 000000000..8e831cb4c
--- /dev/null
+++ b/db/routines/vn/procedures/timeControl_calculateByUser.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_calculateByUser`(vUserFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
+BEGIN
+
+/**
+ * @param vUserFk
+ * @param vDatedFrom workerTimeControl
+ * @param vDatedTo workerTimeControl
+ */
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
+
+ CREATE TEMPORARY TABLE tmp.`user`
+ SELECT id userFk
+ FROM account.user
+ WHERE id = vUserFk;
+ CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
+
+ DROP TEMPORARY TABLE tmp.`user`;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/timeControl_calculateByWorker.sql b/db/routines/vn/procedures/timeControl_calculateByWorker.sql
new file mode 100644
index 000000000..98c3dedd2
--- /dev/null
+++ b/db/routines/vn/procedures/timeControl_calculateByWorker.sql
@@ -0,0 +1,22 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_calculateByWorker`(vWorkerFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
+BEGIN
+
+/**
+ * @param vWorkerFk
+ * @param vDatedFrom workerTimeControl
+ * @param vDatedTo workerTimeControl
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
+
+ CREATE TEMPORARY TABLE tmp.`user`
+ SELECT u.id userFk
+ FROM account.user u
+ JOIN vn.worker w ON w.id = u.id
+ WHERE w.id = vWorkerFk;
+
+ CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
+
+ DROP TEMPORARY TABLE tmp.`user`;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/timeControl_getError.sql b/db/routines/vn/procedures/timeControl_getError.sql
new file mode 100644
index 000000000..6e5ca02ab
--- /dev/null
+++ b/db/routines/vn/procedures/timeControl_getError.sql
@@ -0,0 +1,70 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_getError`(vDatedFrom DATETIME, vDatedTo DATETIME)
+BEGIN
+/*
+ * @param vDatedFrom
+ * @param vDatedTo
+ * @table tmp.`user`(userFk)
+ * Fichadas incorrectas de las cuales no se puede calcular horas trabajadas
+ * @return tmp.timeControlError (id)
+ */
+ DECLARE vDayMaxTime INTEGER;
+
+ SET @journeyCounter := 0;
+ SET @lastUserFk := NULL;
+
+ SELECT dayMaxTime INTO vDayMaxTime
+ FROM workerTimeControlConfig LIMIT 1;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
+ CREATE TEMPORARY TABLE tmp.timeControl
+ (INDEX(id), INDEX(journeyCounter))
+ ENGINE = MEMORY
+ SELECT sub.id,
+ sub.direction,
+ sub.timed,
+ IF(sub.direction = 'in' OR @hasOut OR sub.userFk <> @lastUserFk, @journeyCounter := @journeyCounter + 1, @journeyCounter) journeyCounter,
+ @lastUserFk := sub.userFk workerFk,
+ IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE)
+ FROM (
+ SELECT DISTINCT wtc.id,
+ wtc.direction,
+ wtc.timed,
+ wtc.userFk
+ FROM workerTimeControl wtc
+ JOIN tmp.`user` w ON w.userFk = wtc.userFk
+ WHERE wtc.timed BETWEEN DATE_SUB(vDatedFrom, INTERVAL 1 DAY) AND DATE_ADD(vDatedTo, INTERVAL 1 DAY)
+ ORDER BY wtc.userFk, wtc.timed
+ ) sub;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
+ CREATE TEMPORARY TABLE tmp.timeControlAux
+ (INDEX(id), INDEX(journeyCounter))
+ ENGINE = MEMORY
+ SELECT * FROM tmp.timeControl;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError;
+ CREATE TEMPORARY TABLE tmp.timeControlError
+ (INDEX(id))
+ ENGINE = MEMORY
+ SELECT id
+ FROM tmp.timeControlAux tca
+ JOIN (
+ SELECT journeyCounter,
+ UNIX_TIMESTAMP(MAX(timed)) - UNIX_TIMESTAMP(MIN(timed)) timeWork,
+ SUM(direction = 'in') totalIn,
+ SUM(direction = 'out') totalOut,
+ timed
+ FROM tmp.timeControl
+ GROUP BY journeyCounter
+ HAVING COUNT(*) MOD 2 = 1
+ OR totalIn <> 1
+ OR totalOut <> 1
+ OR timeWork >= vDayMaxTime
+ )sub ON sub.journeyCounter = tca.journeyCounter
+ WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/tpvTransaction_checkStatus.sql b/db/routines/vn/procedures/tpvTransaction_checkStatus.sql
new file mode 100644
index 000000000..e16c20161
--- /dev/null
+++ b/db/routines/vn/procedures/tpvTransaction_checkStatus.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`tpvTransaction_checkStatus`()
+BEGIN
+/**
+ *
+ * Envia mail con los cobros web no
+ * trasladados a la ficha del cliente.
+ *
+ */
+ INSERT INTO mail (receiver, replyTo, subject, body)
+ SELECT 'administracion@verdnatura.es, finanzas@verdnatura.es',
+ 'noreply@verdnatura.es',
+ CONCAT('Cobro web no trasladado a la ficha del cliente ', clientFk),
+ CONCAT('Hay un importe de ', amount / 100, '€ del cliente ', clientFk, ' con fecha ', created,
+ ', que no se ha trasladado a recibos. Si nos ha llegado el importe al banco confirme el pago en
+
+ https://salix.verdnatura.es/#!/client/', clientFk, '/web-payment')
+ FROM hedera.tpvTransaction
+ WHERE receiptFk IS NULL
+ AND status = 'ok'
+ AND created < (util.VN_NOW() - INTERVAL 2 DAY)
+ GROUP BY clientFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travelVolume.sql b/db/routines/vn/procedures/travelVolume.sql
new file mode 100644
index 000000000..21eae36ac
--- /dev/null
+++ b/db/routines/vn/procedures/travelVolume.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume`(vTravelFk INT)
+BEGIN
+
+ SELECT w1.name AS ORI,
+ w2.name AS DES,
+ tr.shipped shipment,
+ tr.landed landing,
+ a.name Agencia,
+ s.name Proveedor,
+ e.id Id_Entrada,
+ e.invoiceNumber Referencia,
+ CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
+ vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC,
+ CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
+ vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais
+ FROM vn.buy b
+ JOIN vn.entry e ON e.id = b.entryFk
+ JOIN vn.supplier s ON s.id = e.supplierFk
+ JOIN vn.travel tr ON tr.id = e.travelFk
+ JOIN vn.agencyMode a ON a.id = tr.agencyModeFk
+ JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk
+ JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk
+ JOIN vn.volumeConfig vc
+ JOIN vn.item i ON i.id = b.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ WHERE tr.id = vTravelFk;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travelVolume_get.sql b/db/routines/vn/procedures/travelVolume_get.sql
new file mode 100644
index 000000000..f9d00aeb4
--- /dev/null
+++ b/db/routines/vn/procedures/travelVolume_get.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume_get`(vFromDated DATE, vToDated DATE, vWarehouseFk INT)
+BEGIN
+ SELECT tr.landed Fecha,
+ a.name Agencia,
+ count(DISTINCT e.id) numEntradas,
+ FLOOR(sum(item_getVolume(b.itemFk, b.packagingFk) * b.stickers / 1000000 )) AS m3
+ FROM vn.travel tr
+ JOIN vn.agencyMode a ON a.id = tr.agencyModeFk
+ JOIN vn.entry e ON e.travelFk = tr.id
+ JOIN vn.buy b ON b.entryFk = e.id
+ WHERE tr.landed BETWEEN vFromDated AND vToDated
+ AND e.isRaid = FALSE
+ AND tr.warehouseInFk = vWarehouseFk
+ GROUP BY tr.landed , a.name ;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_checkDates.sql b/db/routines/vn/procedures/travel_checkDates.sql
new file mode 100644
index 000000000..45690fcb4
--- /dev/null
+++ b/db/routines/vn/procedures/travel_checkDates.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_checkDates`(vShipped DATE, vLanded DATE)
+BEGIN
+/**
+ * Checks the landing/shipment dates of travel, throws an error
+ * ir they are not correct.
+ *
+ * @param vShipped The shipment date
+ * @param vLanded The landing date
+ */
+
+ IF vLanded < vShipped THEN
+ SIGNAL SQLSTATE '45000'
+ SET MESSAGE_TEXT = 'Landing cannot be lesser than shipment';
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_checkPackaging.sql b/db/routines/vn/procedures/travel_checkPackaging.sql
new file mode 100644
index 000000000..59df1b894
--- /dev/null
+++ b/db/routines/vn/procedures/travel_checkPackaging.sql
@@ -0,0 +1,30 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_checkPackaging`(vSelf INT)
+BEGIN
+ DECLARE vDone BOOL;
+ DECLARE vEntryFk INT;
+
+ DECLARE cTravelEntries CURSOR FOR
+ SELECT id
+ FROM entry
+ WHERE entry.travelFk = vSelf;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ OPEN cTravelEntries;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH cTravelEntries INTO vEntryFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL entry_checkPackaging(vEntryFk);
+ END LOOP;
+
+ CLOSE cTravelEntries;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_checkWarehouseIsFeedStock.sql b/db/routines/vn/procedures/travel_checkWarehouseIsFeedStock.sql
new file mode 100644
index 000000000..ef69d772b
--- /dev/null
+++ b/db/routines/vn/procedures/travel_checkWarehouseIsFeedStock.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_checkWarehouseIsFeedStock`(vWarehouseFk INT)
+proc: BEGIN
+/*
+ * Check that the warehouse is not Feed Stock
+ *
+ * @vWarehouseFk param warehouse id
+ */
+ IF vWarehouseFk IS NULL THEN
+ LEAVE proc;
+ END IF;
+
+ IF (SELECT isFeedStock FROM warehouse WHERE id = vWarehouseFk) THEN
+ CALL util.throw('Cannot create a travel with a source warehouse marked isFeedStock');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_clone.sql b/db/routines/vn/procedures/travel_clone.sql
new file mode 100644
index 000000000..96500baa1
--- /dev/null
+++ b/db/routines/vn/procedures/travel_clone.sql
@@ -0,0 +1,48 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_clone`(vSelf INT, vDays INT, OUT vNewTravelFk INT)
+BEGIN
+/**
+ * Clona un travel el número de dias indicado y devuelve su id.
+ *
+ * @param vSelf Identificador de vn.travel
+ * @param vDays Número de dias a futuro
+ * @return vNewTravelFk Nuevo número de travel
+ */
+ SELECT tr.id INTO vNewTravelFk
+ FROM vn.travel tr
+ JOIN vn.travel tr2 USING(shipped, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`)
+ WHERE tr2.id = vSelf
+ AND tr.landed = TIMESTAMPADD(DAY, vDays, tr2.landed);
+
+ IF ISNULL(vNewTravelFk) THEN
+ START TRANSACTION;
+
+ INSERT INTO vn.travel( shipped,
+ shipmentHour,
+ landed,
+ landingHour,
+ warehouseInFk,
+ warehouseOutFk,
+ agencyModeFk,
+ `ref`,
+ cargoSupplierFk,
+ clonedFrom)
+ SELECT shipped,
+ shipmentHour,
+ TIMESTAMPADD(DAY, vDays, landed),
+ landingHour,
+ warehouseInFk,
+ warehouseOutFk,
+ agencyModeFk,
+ `ref`,
+ cargoSupplierFk,
+ vSelf
+ FROM vn.travel
+ WHERE id = vSelf;
+
+ SELECT LAST_INSERT_ID() INTO vNewTravelFk;
+
+ COMMIT;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_cloneWithEntries.sql b/db/routines/vn/procedures/travel_cloneWithEntries.sql
new file mode 100644
index 000000000..7cf9ee5ef
--- /dev/null
+++ b/db/routines/vn/procedures/travel_cloneWithEntries.sql
@@ -0,0 +1,81 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_cloneWithEntries`(
+ IN vTravelFk INT,
+ IN vDateStart DATE,
+ IN vDateEnd DATE,
+ IN vWarehouseOutFk INT,
+ IN vWarehouseInFk INT,
+ IN vRef VARCHAR(255),
+ IN vAgencyModeFk INT,
+ OUT vNewTravelFk INT)
+BEGIN
+/**
+ * Clona un travel junto con sus entradas y compras
+ * @param vTravelFk travel plantilla a clonar
+ * @param vDateStart fecha del shipment del nuevo travel
+ * @param vDateEnd fecha del landing del nuevo travel
+ * @param vWarehouseOutFk warehouse del salida del nuevo travel
+ * @param vWarehouseInFk warehouse de landing del nuevo travel
+ * @param vRef referencia del nuevo travel
+ * @param vAgencyModeFk del nuevo travel
+ * @param vNewTravelFk id del nuevo travel
+ */
+ DECLARE vNewEntryFk INT;
+ DECLARE vEvaNotes VARCHAR(255);
+ DECLARE vDone BOOL;
+ DECLARE vAuxEntryFk INT;
+ DECLARE vTx BOOLEAN DEFAULT @@in_transaction;
+ DECLARE vRsEntry CURSOR FOR
+ SELECT e.id
+ FROM entry e
+ JOIN travel t ON t.id = e.travelFk
+ WHERE e.travelFk = vTravelFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ CALL util.tx_rollback(vTx);
+ RESIGNAL;
+ END;
+
+ CALL util.tx_start(vTx);
+
+ INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, cargoSupplierFk, kg,clonedFrom)
+ SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3,cargoSupplierFk, kg,vTravelFk
+ FROM travel
+ WHERE id = vTravelFk;
+
+ SET vNewTravelFk = LAST_INSERT_ID();
+
+ SET vDone = FALSE;
+ SET @isModeInventory = TRUE;
+
+ OPEN vRsEntry;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vRsEntry INTO vAuxEntryFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL entry_cloneHeader(vAuxEntryFk, vNewEntryFk, vNewTravelFk);
+ CALL entry_copyBuys(vAuxEntryFk, vNewEntryFk);
+
+ SELECT evaNotes INTO vEvaNotes
+ FROM entry
+ WHERE id = vAuxEntryFk;
+
+ UPDATE entry
+ SET evaNotes = vEvaNotes
+ WHERE id = vNewEntryFk;
+ END LOOP;
+
+ SET @isModeInventory = FALSE;
+ CLOSE vRsEntry;
+
+ CALL util.tx_commit(vTx);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_doRecalc.sql b/db/routines/vn/procedures/travel_doRecalc.sql
new file mode 100644
index 000000000..5d877174c
--- /dev/null
+++ b/db/routines/vn/procedures/travel_doRecalc.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_doRecalc`()
+proc: BEGIN
+/**
+* Recounts the number of entries of changed travels.
+*/
+ DECLARE vTravelFk INT;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ DO RELEASE_LOCK('vn.ticket_doRecalc');
+ END;
+
+ IF !GET_LOCK('vn.travel_doRecalc', 0) THEN
+ LEAVE proc;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTravel
+ ENGINE = MEMORY
+ SELECT travelFk FROM travelRecalc;
+
+ UPDATE travel t
+ JOIN tTravel tt ON tt.travelFk = t.id
+ SET t.totalEntries = (
+ SELECT COUNT(e.id)
+ FROM entry e
+ WHERE e.travelFk = t.id
+ );
+
+ DELETE tr FROM travelRecalc tr JOIN tTravel t ON tr.travelFk = t.travelFk;
+ DROP TEMPORARY TABLE tTravel;
+ DO RELEASE_LOCK('vn.travel_doRecalc');
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_getDetailFromContinent.sql b/db/routines/vn/procedures/travel_getDetailFromContinent.sql
new file mode 100644
index 000000000..e81e648b3
--- /dev/null
+++ b/db/routines/vn/procedures/travel_getDetailFromContinent.sql
@@ -0,0 +1,109 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_getDetailFromContinent`(
+ vContinentFk INT
+)
+BEGIN
+/**
+ * Devuelve los detalles de los vuelos que tienen
+ * un almacén de salida de un continente.
+ *
+ * @param vContinentFk Id de continente
+ */
+ DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK;
+ SELECT IFNULL(CONCAT(" ", entryFk), travelFk) travelAndEntry,
+ sub.*
+ FROM (
+ SELECT tr.id travelFk,
+ NULL entryFk,
+ TRUE isTravel,
+ am.name agency,
+ tr.ref,
+ tr.shipped,
+ wOut.name originBoxes,
+ tr.landed,
+ wIn.name destination,
+ SUM(b.stickers) stickers,
+ NULL evaNotes,
+ tr.kg,
+ CAST(SUM(b.weight * b.stickers) AS INT) loadedkg,
+ CAST(
+ SUM(vc.aerealVolumetricDensity *
+ b.stickers *
+ IF(p.volume,
+ p.volume,
+ p.width * p.depth * p.height
+ ) / 1000000
+ ) AS INT
+ ) volumeKg,
+ NULL loadPriority,
+ NULL invoiceAmount,
+ s.nickname freighter,
+ NULL reference
+ FROM travel tr
+ LEFT JOIN supplier s ON s.id = tr.cargoSupplierFk
+ LEFT JOIN entry e ON e.travelFk = tr.id
+ LEFT JOIN buy b ON b.entryFk = e.id
+ LEFT JOIN packaging p ON p.id = b.packagingFk
+ LEFT JOIN item i ON i.id = b.itemFk
+ LEFT JOIN itemType it ON it.id = i.typeFk
+ JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
+ JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
+ JOIN country co ON co.id = wOut.countryFk
+ JOIN agencyMode am ON am.id = tr.agencyModeFk
+ JOIN volumeConfig vc
+ WHERE tr.landed >= vDateFrom
+ AND co.continentFk = vContinentFk
+ GROUP BY tr.id
+ UNION ALL
+ SELECT e.travelFk,
+ e.id,
+ FALSE,
+ s.name,
+ e.invoiceNumber,
+ tr.shipped,
+ wOut.name,
+ tr.landed,
+ wIn.name,
+ SUM(b.stickers),
+ e.evaNotes,
+ NULL,
+ CAST(SUM(b.weight * b.stickers) AS INT),
+ CAST(
+ SUM(vc.aerealVolumetricDensity *
+ b.stickers *
+ IF(p.volume,
+ p.volume,
+ p.width * p.depth * p.height
+ ) / 1000000
+ ) AS INT
+ ),
+ loadPriority,
+ e.invoiceAmount,
+ s2.nickname,
+ e.reference
+ FROM entry e
+ JOIN buy b ON b.entryFk = e.id
+ JOIN packaging p ON p.id = b.packagingFk
+ JOIN item i ON i.id = b.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN supplier s ON s.id = e.supplierFk
+ JOIN travel tr ON tr.id = e.travelFk
+ LEFT JOIN supplier s2 ON s2.id = tr.cargoSupplierFk
+ JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
+ JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
+ JOIN country co ON co.id = wOut.countryFk
+ JOIN volumeConfig vc
+ WHERE tr.landed >= vDateFrom
+ AND co.continentFk = vContinentFk
+ GROUP BY e.id
+ ) sub
+ ORDER BY landed ASC,
+ shipped ASC,
+ travelFk,
+ isTravel DESC,
+ (loadPriority > 0) DESC,
+ loadPriority,
+ agency,
+ evaNotes;
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/travel_getEntriesMissingPackage.sql b/db/routines/vn/procedures/travel_getEntriesMissingPackage.sql
new file mode 100644
index 000000000..35d30e0c4
--- /dev/null
+++ b/db/routines/vn/procedures/travel_getEntriesMissingPackage.sql
@@ -0,0 +1,18 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_getEntriesMissingPackage`(vSelf INT)
+BEGIN
+ DECLARE vpackageOrPackingNull INT;
+ DECLARE vTravelFk INT;
+
+ SELECT travelfk INTO vTravelFk
+ FROM entry
+ WHERE id = vSelf;
+
+ SELECT e.id entryFk
+ FROM travel t
+ JOIN entry e ON e.travelFk = t.id
+ JOIN buy b ON b.entryFk = e.id
+ WHERE t.id = vTravelFk
+ AND (b.packing IS NULL OR b.packagingFk IS NULL);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_moveRaids.sql b/db/routines/vn/procedures/travel_moveRaids.sql
new file mode 100644
index 000000000..c7696e829
--- /dev/null
+++ b/db/routines/vn/procedures/travel_moveRaids.sql
@@ -0,0 +1,72 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_moveRaids`()
+BEGIN
+
+/*
+ * Desplaza al dia siguiente los travels que contengan redadas y avisa a los compradores
+ *
+ */
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vWorkerName VARCHAR(50);
+ DECLARE vRaid TEXT;
+ DECLARE vWorker VARCHAR(50) DEFAULT '';
+ DECLARE vMailBody TEXT DEFAULT '';
+
+ DECLARE vCur CURSOR FOR
+ SELECT GROUP_CONCAT( DISTINCT CONCAT('https://salix.verdnatura.es/#!/travel/', ttr.id, '/summary ') ORDER BY ttr.id SEPARATOR '\n\r'),
+ u.name
+ FROM tmp.travel ttr
+ JOIN entry e ON e.travelFk = ttr.id
+ JOIN buy b ON b.entryFk = e.id
+ JOIN item i ON i.id = b.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN account.user u ON u.id = it.workerFk
+ GROUP BY u.name;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.travel;
+ CREATE TEMPORARY TABLE tmp.travel
+ SELECT tr.id,tr.landed
+ FROM travel tr
+ JOIN entry e ON e.travelFk = tr.id
+ WHERE tr.landed = util.tomorrow()
+ AND e.isRaid
+ GROUP BY tr.id;
+
+ START TRANSACTION;
+
+ UPDATE travel tr
+ JOIN tmp.travel ttr ON ttr.id = tr.id
+ SET tr.landed = TIMESTAMPADD(DAY, 1, tr.landed);
+
+ OPEN vCur;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vCur INTO vRaid, vWorkerName;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL `vn`.`mail_insert`(CONCAT(vWorkerName, '@verdnatura.es'),
+ 'noreply@verdnatura.es',
+ 'Cambio de fecha en Redadas',
+ CONCAT('Se ha movido las siguientes redadas: \n\r ', vRaid)
+ );
+
+ END LOOP;
+ CLOSE vCur;
+ COMMIT;
+ DROP TEMPORARY TABLE tmp.travel;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_requestRecalc.sql b/db/routines/vn/procedures/travel_requestRecalc.sql
new file mode 100644
index 000000000..5797f2397
--- /dev/null
+++ b/db/routines/vn/procedures/travel_requestRecalc.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_requestRecalc`(vSelf INT)
+proc: BEGIN
+/**
+ * Adds a request to recount the number of entries for the travel.
+ *
+ * @param vSelf The travel reference
+ */
+ IF vSelf IS NULL THEN
+ LEAVE proc;
+ END IF;
+
+ INSERT IGNORE INTO travelRecalc SET travelFk = vSelf;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_upcomingArrivals.sql b/db/routines/vn/procedures/travel_upcomingArrivals.sql
new file mode 100644
index 000000000..a2cd3733c
--- /dev/null
+++ b/db/routines/vn/procedures/travel_upcomingArrivals.sql
@@ -0,0 +1,81 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_upcomingArrivals`(
+ vWarehouseFk INT,
+ vDate DATETIME
+)
+BEGIN
+/**
+ * Procedure to track and organize the movement of items between warehouses,
+ * where 'warehouseINFk' is @vWarehouseFk.
+ * Uses temporary tables to process and store the travel data of the items.
+ *
+ * @params vWarehouseFk warehouse id
+ * @params vDate selected landed date
+ * @return tmp.itemTravel
+ */
+ DECLARE vTravelFk INT;
+ DECLARE vWarehouseOutFk INT;
+ DECLARE vShipment DATETIME;
+ DECLARE vDateStart DATETIME;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTravelTop
+ (PRIMARY KEY (wh_in,wh_out,landing,shipment))
+ ENGINE = MEMORY
+ SELECT 0 id,
+ vWarehouseFk wh_in,
+ vWarehouseFk wh_out,
+ FALSE ok,
+ vDate landing,
+ vDate shipment;
+
+ REPEAT
+ SET vTravelFk = NULL;
+
+ SELECT id,
+ wh_out,
+ shipment,
+ landing
+ INTO vTravelFk,
+ vWarehouseOutFk,
+ vShipment,
+ vDateStart
+ FROM tTravelTop
+ WHERE ok = FALSE LIMIT 1;
+
+ UPDATE tTravelTop
+ SET ok = TRUE
+ WHERE id = vTravelFk;
+
+ INSERT IGNORE INTO tTravelTop
+ SELECT id,
+ vWarehouseFk,
+ warehouseOutFk,
+ FALSE,
+ IF(vTravelFk, vDateStart, landed),
+ shipped shipment
+ FROM travel
+ WHERE warehouseOutFk = vWarehouseOutFk
+ AND IF(vTravelFk, landed <= vShipment, landed >= vShipment)
+ AND shipped >= util.VN_CURDATE()
+ AND NOT isDelivered;
+ UNTIL vTravelFk IS NULL END REPEAT;
+
+ DELETE FROM tTravelTop WHERE id = 0;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemTravel
+ (KEY (wh))
+ ENGINE = MEMORY
+ SELECT *
+ FROM (
+ SELECT wh_out wh,
+ landing
+ FROM tTravelTop
+ WHERE wh_out <> vWarehouseFk
+ ORDER BY landing
+ LIMIT 10000000000000000000
+ ) t
+ GROUP BY wh;
+
+ DROP TEMPORARY TABLE tTravelTop;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_updatePacking.sql b/db/routines/vn/procedures/travel_updatePacking.sql
new file mode 100644
index 000000000..0f63bbf62
--- /dev/null
+++ b/db/routines/vn/procedures/travel_updatePacking.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_updatePacking`(vItemFk INT, vPacking INT)
+BEGIN
+/**
+ * Actualiza packing para los movimientos de almacén de la subasta al almacén central
+ *
+ * @param vItemFk id del item
+ * @param vPacking nuevo packing
+ */
+
+ DECLARE vAuctionWarehouseFk INT;
+ DECLARE vMainWarehouseFk INT;
+
+ SELECT warehouseFk INTO vAuctionWarehouseFk
+ FROM auctionConfig;
+
+ SELECT mainWarehouseFk INTO vMainWarehouseFk
+ FROM config;
+
+ UPDATE entry e
+ JOIN travel t ON t.id = e.travelFk
+ JOIN buy b on b.entryFk = e.id
+ SET b.packing = vPacking
+ WHERE t.shipped >= util.dayEnd(CURDATE())
+ AND t.warehouseInFk = vMainWarehouseFk
+ AND t.warehouseOutFk = vAuctionWarehouseFk
+ AND b.itemFk = vItemFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_weeklyClone.sql b/db/routines/vn/procedures/travel_weeklyClone.sql
new file mode 100644
index 000000000..a92916c10
--- /dev/null
+++ b/db/routines/vn/procedures/travel_weeklyClone.sql
@@ -0,0 +1,73 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_weeklyClone`(vSinceWeek INT, vToWeek INT)
+BEGIN
+/**
+ * Clona los traslados plantilla para las semanas pasadas por parámetros.
+ *
+ * @param vSinceWeek Número de semanas en el futuro para empezar a clonar
+ * @param vToWeek Número de semenas en el futuro hasta donde clonar
+ */
+ DECLARE vCounter INT;
+ DECLARE vCurrentTravelFk INT;
+ DECLARE vShipped DATE;
+ DECLARE vLanded DATE;
+ DECLARE vWarehouseInFk INT;
+ DECLARE vWarehouseOutFk INT;
+ DECLARE vAgencyModeFk INT;
+ DECLARE vRef VARCHAR(255);
+ DECLARE vNewTravelFk INT;
+ DECLARE vDone BOOL;
+ DECLARE vRsTravel CURSOR FOR
+ SELECT travelFk,
+ @a := TIMESTAMPADD(DAY,vCounter * 7 - WEEKDAY(util.VN_CURDATE()) - 1 + weekDay, util.VN_CURDATE()),
+ @a := TIMESTAMPADD(DAY,duration,@a),
+ warehouseOutFk,
+ warehouseInFk,
+ `ref`,
+ agencyModeFk
+ FROM travelClonedWeekly
+ WHERE travelFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SET vCounter = vSinceWeek;
+
+ vWeekLoop :LOOP
+ INSERT IGNORE INTO travel (shipped, landed, warehouseOutFk, warehouseInFk, agencyModeFk, ref, cargoSupplierFk, kg)
+ SELECT @a := TIMESTAMPADD(DAY, vCounter * 7 - WEEKDAY(util.VN_CURDATE()) - 1 + weekDay, util.VN_CURDATE()),
+ @a := TIMESTAMPADD(DAY, duration, @a),
+ warehouseOutFk,
+ warehouseInFk,
+ agencyModeFk,
+ ref,
+ supplierFk,
+ kg
+ FROM travelClonedWeekly
+ WHERE travelFk IS NULL;
+
+ OPEN vRsTravel;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vRsTravel INTO vCurrentTravelFk, vShipped, vLanded, vWarehouseOutFk, vWarehouseInFk, vRef, vAgencyModeFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ BEGIN
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION RESIGNAL SQLSTATE '01000';
+ CALL travel_cloneWithEntries(vCurrentTravelFk, vShipped, vLanded, vWarehouseOutFk, vWarehouseInFk, vRef, vAgencyModeFk, vNewTravelFk);
+ END;
+ END LOOP;
+
+ CLOSE vRsTravel;
+
+ IF vCounter = vToWeek THEN
+ LEAVE vWeekLoop;
+ END IF;
+
+ SET vCounter = vCounter + 1;
+ END LOOP vWeekLoop;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/typeTagMake.sql b/db/routines/vn/procedures/typeTagMake.sql
new file mode 100644
index 000000000..ddfc7fdb9
--- /dev/null
+++ b/db/routines/vn/procedures/typeTagMake.sql
@@ -0,0 +1,58 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`typeTagMake`(vTypeFk INT)
+BEGIN
+/*
+ * Plantilla para modificar reemplazar todos los tags
+ * por los valores que tienen los articulos
+ *
+ * @param vTypeFk tipo a modificar
+ *
+ */
+ DELETE it.*
+ FROM itemTag it
+ JOIN item i ON i.id = it.itemFk
+ WHERE i.typeFk = vTypeFk;
+
+ INSERT INTO itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id, CONCAT(i.size,' cm'), 1
+ FROM item i
+ JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci
+ WHERE i.typeFk = vTypeFk;
+
+ INSERT INTO itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id, i.category, 5
+ FROM item i
+ JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci
+ WHERE i.typeFk = vTypeFk;
+
+ INSERT INTO itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id, ink.name, 2
+ FROM item i
+ JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci
+ JOIN ink ON ink.id = i.inkFk
+ WHERE i.typeFk = vTypeFk;
+
+ INSERT INTO itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id, p.name, 3
+ FROM item i
+ JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci
+ JOIN producer p ON p.id = i.producerFk
+ WHERE i.typeFk = vTypeFk;
+
+ INSERT INTO itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id, o.name, 4
+ FROM item i
+ JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci
+ JOIN origin o ON o.id = i.originFk
+ WHERE i.typeFk = vTypeFk;
+ /*
+ INSERT INTO itemTag(itemFk, tagFk, value, priority)
+ SELECT i.id, t.id, i.stems, 6
+ FROM item i
+ JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci
+ WHERE i.typeFk = vTypeFk;
+ */
+-- CALL itemTagArrangedUpdate(NULL);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/updatePedidosInternos.sql b/db/routines/vn/procedures/updatePedidosInternos.sql
new file mode 100644
index 000000000..97b01bf8b
--- /dev/null
+++ b/db/routines/vn/procedures/updatePedidosInternos.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`updatePedidosInternos`(vItemFk INT)
+BEGIN
+
+ UPDATE vn.item SET upToDown = 0 WHERE item.id = vItemFk;
+
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/vehicle_checkNumberPlate.sql b/db/routines/vn/procedures/vehicle_checkNumberPlate.sql
new file mode 100644
index 000000000..8e3f24d76
--- /dev/null
+++ b/db/routines/vn/procedures/vehicle_checkNumberPlate.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`vehicle_checkNumberPlate`(vNumberPlate VARCHAR(10), vCountryCodeFk VARCHAR(2))
+BEGIN
+/**
+ * Comprueba si la matricula pasada tiene el formato correcto dependiendo del pais del vehiculo
+ */
+ DECLARE vRegex VARCHAR(45);
+
+ SELECT vp.regex INTO vRegex
+ FROM vehiclePlateRegex vp
+ WHERE vp.countryCodeFk = vCountryCodeFk;
+
+ IF NOT vNumberPlate REGEXP BINARY (vRegex)THEN
+ CALL util.throw(CONCAT('Error: la matricula ', vNumberPlate, ' no es valida para ',vCountryCodeFk));
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/vehicle_notifyEvents.sql b/db/routines/vn/procedures/vehicle_notifyEvents.sql
new file mode 100644
index 000000000..1a07a96e2
--- /dev/null
+++ b/db/routines/vn/procedures/vehicle_notifyEvents.sql
@@ -0,0 +1,51 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`vehicle_notifyEvents`()
+proc:BEGIN
+/**
+ * Query the vehicleEvent table to see if there are any events that need to be notified.
+ *
+ */
+ DECLARE vEventEarlyDays INT;
+ DECLARE vHasEvents INT;
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ SELECT eventEarlyDays INTO vEventEarlyDays
+ FROM vehicleConfig;
+
+ DROP TEMPORARY TABLE IF EXISTS tEvents;
+ CREATE TEMPORARY TABLE tEvents
+ SELECT e.id
+ FROM vehicleEvent e
+ JOIN vehicleState s ON e.vehicleStateFk = s.id
+ WHERE e.finished BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY, vEventEarlyDays, util.VN_CURDATE())
+ AND e.notified IS NULL
+ AND s.hasToNotify;
+
+ SELECT COUNT(id) INTO vHasEvents FROM tEvents;
+
+ IF NOT vHasEvents THEN
+ LEAVE proc;
+ END IF;
+
+ START TRANSACTION;
+
+ SELECT util.notification_send('vehicle-event-expired',
+ JSON_OBJECT('eventIds', JSON_ARRAYAGG(id)),
+ account.myUser_getId()
+ )
+ FROM tEvents;
+
+ UPDATE vehicleEvent e
+ JOIN tEvents s ON e.id = s.id
+ SET e.notified = util.VN_NOW()
+ WHERE e.id = s.id;
+ COMMIT;
+
+ DROP TEMPORARY TABLE IF EXISTS tEvents;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/visible_getMisfit.sql b/db/routines/vn/procedures/visible_getMisfit.sql
new file mode 100644
index 000000000..631f0236e
--- /dev/null
+++ b/db/routines/vn/procedures/visible_getMisfit.sql
@@ -0,0 +1,46 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`visible_getMisfit`(vSectorFk INT)
+BEGIN
+
+ /* Devuelve una tabla temporal con los descuadres entre el visible teórico y lo ubicado en la práctica
+ *
+ * @param vSectorFk Identificador de vn.sector
+ *
+ * @return tmp.stockMisfit(itemFk, visible, parked)
+ */
+
+ DECLARE vCalcVisibleFk INT;
+ DECLARE vWarehouseFk INT;
+
+ SELECT warehouseFk INTO vWarehouseFk
+ FROM vn.sector s
+ WHERE s.id = vSectorFk;
+
+ CALL cache.visible_refresh(vCalcVisibleFk, FALSE, vWarehouseFk);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit;
+
+ CREATE TEMPORARY TABLE tmp.stockMisfit(
+ itemFk INT PRIMARY KEY,
+ visible INT NOT NULL DEFAULT 0,
+ parked INT NOT NULL DEFAULT 0)
+ ENGINE = MEMORY;
+
+ INSERT INTO tmp.stockMisfit(itemFk, parked)
+ SELECT iss.itemFk , sum(iss.visible )
+ FROM vn.itemShelvingStock iss
+ JOIN vn.sector s ON s.id = iss.sectorFk
+ WHERE vSectorFk IN (s.id, s.sonFk)
+ GROUP BY iss.itemFk;
+
+ INSERT INTO tmp.stockMisfit(itemFk, visible)
+ SELECT v.item_id , v.visible
+ FROM cache.visible v
+ WHERE v.calc_id = vCalcVisibleFk
+ ON DUPLICATE KEY UPDATE visible = v.visible;
+
+ DELETE FROM tmp.stockMisfit
+ WHERE visible = parked;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/warehouseFitting.sql b/db/routines/vn/procedures/warehouseFitting.sql
new file mode 100644
index 000000000..4be35a3ee
--- /dev/null
+++ b/db/routines/vn/procedures/warehouseFitting.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`warehouseFitting`(IN vWhOrigin INT , IN vWhDestiny INT)
+BEGIN
+ DECLARE vCacheVisibleOriginFk INT;
+ DECLARE vCacheVisibleDestinyFk INT;
+
+ CALL cache.visible_refresh(vCacheVisibleOriginFk, FALSE, vWhOrigin);
+ CALL cache.visible_refresh(vCacheVisibleDestinyFk, FALSE, vWhDestiny);
+
+ SELECT i.id itemFk,
+ i.longName,
+ i.size,
+ i.subName,
+ vOrigin.visible AS Origen,
+ vDestiny.visible Destino
+
+ FROM vn.item i
+ JOIN vn.itemType it ON it.id = i.typeFk
+ LEFT JOIN cache.visible vOrigin ON vOrigin.calc_id = vCacheVisibleOriginFk AND vOrigin.item_id = i.id
+ LEFT JOIN cache.visible vDestiny ON vDestiny.calc_id = vCacheVisibleDestinyFk AND vDestiny.item_id = i.id
+ WHERE (vOrigin.visible OR vDestiny.visible)
+ AND it.categoryFk < 6
+ ORDER BY IF(vOrigin.visible,0,1), longName, size, subName;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/warehouseFitting_byTravel.sql b/db/routines/vn/procedures/warehouseFitting_byTravel.sql
new file mode 100644
index 000000000..db67c1599
--- /dev/null
+++ b/db/routines/vn/procedures/warehouseFitting_byTravel.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`warehouseFitting_byTravel`(IN vTravelFk INT)
+BEGIN
+
+ DECLARE vWhOrigin INT;
+ DECLARE vWhDestiny INT;
+
+ SELECT warehouseInFk, warehouseOutFk INTO vWhDestiny, vWhOrigin
+ FROM vn.travel
+ WHERE id = vTravelFk;
+
+ CALL vn.warehouseFitting(vWhOrigin, vWhDestiny);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerCalculateBoss.sql b/db/routines/vn/procedures/workerCalculateBoss.sql
new file mode 100644
index 000000000..0fc08ed40
--- /dev/null
+++ b/db/routines/vn/procedures/workerCalculateBoss.sql
@@ -0,0 +1,28 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerCalculateBoss`(vWorker INT)
+BEGIN
+/**
+* Actualiza la tabla workerBosses
+* vWorker: id del trabajador
+*
+*/
+ DECLARE vBoss INT;
+ DECLARE vWorkerCompare INT DEFAULT vWorker;
+
+ l: LOOP
+ SELECT bossFk INTO vBoss
+ FROM vn.worker
+ WHERE id=vWorkerCompare;
+
+ IF vBoss=0 OR vWorkerCompare=vBoss THEN
+ LEAVE l;
+ END IF;
+
+ REPLACE INTO vn.workerBosses(workerFk,bossFk)
+ VALUES(vWorker,vBoss);
+
+ SET vWorkerCompare = vBoss;
+
+ END LOOP;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerCalendar_calculateBusiness.sql b/db/routines/vn/procedures/workerCalendar_calculateBusiness.sql
new file mode 100644
index 000000000..72b461154
--- /dev/null
+++ b/db/routines/vn/procedures/workerCalendar_calculateBusiness.sql
@@ -0,0 +1,61 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerCalendar_calculateBusiness`(vYear INT, vBusinessFk INT)
+BEGIN
+/**
+ * Calcula los días y horas de vacaciones en función de un contrato y año
+ *
+ * @param vYear
+ * @param vBusinessFk
+ * @return tmp.workerCalendarCalculateBusiness (days, hours, daysEnjoyed, hoursEnjoyed)
+ */
+ DECLARE vStarted DATE;
+ DECLARE vEnded DATE;
+ DECLARE vDaysHoliday DECIMAL(5,2);
+ DECLARE vHoursWeek DECIMAL(5,2);
+ DECLARE vDaysToSubtract DECIMAL(5,2);
+ DECLARE vDaysHolidayEnjoyed DECIMAL(5,2);
+ DECLARE vPayedHolidays DECIMAL(5,2);
+ DECLARE vDifDays INT;
+
+ SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started),
+ IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended),
+ IF(wbt.hasHolidayEntitlement, w.days, 0),
+ c.hoursWeek,
+ IF(YEAR(b.ended) = vYear, b.payedHolidays, 0) payedHolidays
+ INTO vStarted,
+ vEnded,
+ vDaysHoliday,
+ vHoursWeek,
+ vPayedHolidays
+ FROM business b
+ JOIN workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
+ JOIN workCenterHoliday w ON w.workcenterFk = b.workcenterFk
+ LEFT JOIN calendarType c ON c.id = b.calendarTypeFk
+ WHERE b.id = vBusinessFk
+ AND w.year = vYear;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateBusiness;
+
+ IF vStarted < vEnded THEN
+ SET vDifDays = DAYOFYEAR(vEnded) - DAYOFYEAR(vStarted) + 1;
+
+ SELECT IFNULL(SUM(a.holidayEntitlementRate), 0),
+ SUM(-(a.discountRate - 1)) + vPayedHolidays
+ INTO vDaysToSubtract,
+ vDaysHolidayEnjoyed
+ FROM calendar c
+ JOIN absenceType a ON a.id = c.dayOffTypeFk
+ JOIN business b ON b.id = c.businessFk
+ WHERE b.id = vBusinessFk
+ AND YEAR(c.dated) = vYear;
+
+ END IF;
+
+ CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness
+ ENGINE = MEMORY
+ SELECT @days := IFNULL(ROUND((vDaysHoliday * (vDifDays - vDaysToSubtract) / IF(util.isLeapYear(vYear) , 366, 365)), 1), 0) days,
+ @days * (vHoursWeek / 5) hours,
+ @daysEnjoyed := IFNULL(ROUND(vDaysHolidayEnjoyed, 1), 0) daysEnjoyed,
+ @daysEnjoyed * (vHoursWeek / 5) hoursEnjoyed;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerCalendar_calculateYear.sql b/db/routines/vn/procedures/workerCalendar_calculateYear.sql
new file mode 100644
index 000000000..9e3baf641
--- /dev/null
+++ b/db/routines/vn/procedures/workerCalendar_calculateYear.sql
@@ -0,0 +1,59 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerCalendar_calculateYear`(vYear INT, vWorkerFk INT)
+BEGIN
+
+/**
+ * Calcula los días y horas de vacaciones en función de un trabajador y año
+ *
+ * @param vYear
+ * @param vWorkerFk
+ * @return tmp.workerCalendarCalculateYear (days, hours, daysEnjoyed, hoursEnjoyed)
+ */
+ DECLARE vDone BOOL;
+ DECLARE vBusinessFk INT;
+
+ DECLARE cur CURSOR FOR
+ SELECT b.id
+ FROM business b
+ WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear)
+ AND b.workerFk = vWorkerFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateYear;
+
+ CREATE TEMPORARY TABLE tmp.workerCalendarCalculateYear
+ (days DEC(5,2),
+ hours DEC(5,2),
+ daysEnjoyed DEC(5,2),
+ hoursEnjoyed DEC(5,2))
+ ENGINE = MEMORY;
+ INSERT INTO tmp.workerCalendarCalculateYear VALUES(0, 0, 0, 0);
+
+ OPEN cur;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH cur INTO vBusinessFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL workerCalendar_calculateBusiness(vYear, vBusinessFk);
+ UPDATE tmp.workerCalendarCalculateYear w
+ JOIN tmp.workerCalendarCalculateBusiness wc
+ SET w.days = w.days + wc.days,
+ w.hours = w.hours + wc.hours,
+ w.daysEnjoyed = w.daysEnjoyed + wc.daysEnjoyed,
+ w.hoursEnjoyed = w.hoursEnjoyed + wc.hoursEnjoyed;
+
+ DROP TEMPORARY TABLE tmp.workerCalendarCalculateBusiness;
+
+ END LOOP;
+
+ CLOSE cur;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerCreateExternal.sql b/db/routines/vn/procedures/workerCreateExternal.sql
new file mode 100644
index 000000000..f8cea70b1
--- /dev/null
+++ b/db/routines/vn/procedures/workerCreateExternal.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerCreateExternal`(
+ vFirstName VARCHAR(50),
+ vSurname1 VARCHAR(50),
+ vSurname2 VARCHAR(50),
+ vUser VARCHAR(20),
+ vPassword VARCHAR(50),
+ vWorkerCode VARCHAR(3),
+ vRole INT(2)
+ )
+BEGIN
+ DECLARE vUserId INT;
+ DECLARE vSurnames VARCHAR(100);
+
+ INSERT INTO account.`user`(name, nickname, password, `role`, hasGrant)
+ SELECT vUser, vUser, MD5(vPassword), vRole, false;
+
+ SET vUserId = LAST_INSERT_ID();
+
+ IF vSurname2 IS NULL THEN
+ SET vSurnames = vSurname1;
+ ELSE
+ SET vSurnames = CONCAT(vSurname1, ' ', vSurname2);
+ END IF;
+
+ INSERT INTO worker(id, firstName, lastName, code, isFreelance)
+ SELECT vUserId, vFirstName, vSurnames, vWorkerCode, true;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerDepartmentByDate.sql b/db/routines/vn/procedures/workerDepartmentByDate.sql
new file mode 100644
index 000000000..40a099d64
--- /dev/null
+++ b/db/routines/vn/procedures/workerDepartmentByDate.sql
@@ -0,0 +1,24 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerDepartmentByDate`(vDate DATE)
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate;
+ CREATE TEMPORARY TABLE tmp.workerDepartmentByDate
+ ENGINE = MEMORY
+ SELECT w.id userFk,
+ w.lastName name,
+ w.firstName firstname,
+ d.name department,
+ d.id departmentFk,
+ b.started,
+ d.isProduction,
+ CAST(12 * b.amount / ct.hoursWeek / 52 AS DECIMAL(10,2)) costeHora,
+ w.fi nif
+ FROM business b
+ JOIN calendarType ct ON ct.id = b.calendarTypeFk
+ JOIN department d ON d.id = b.departmentFk
+ JOIN worker w ON w.id = b.workerFk
+ WHERE b.started <= vDate
+ AND (b.ended > vDate OR b.ended IS NULL);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerDisable.sql b/db/routines/vn/procedures/workerDisable.sql
new file mode 100644
index 000000000..4b10cb7fa
--- /dev/null
+++ b/db/routines/vn/procedures/workerDisable.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerDisable`(vUserId int)
+mainLabel:BEGIN
+
+ IF (SELECT COUNT(*) FROM workerDisableExcluded WHERE workerFk = vUserId AND (dated > util.VN_CURDATE() OR dated IS NULL)) > 0 THEN
+ LEAVE mainLabel;
+ END IF;
+
+ DELETE cp FROM clientProtected cp
+ JOIN client c ON c.id = cp.clientFk
+ WHERE c.salesPersonFk = vUserId;
+
+ DELETE FROM account.account
+ WHERE id = vUserId;
+
+ UPDATE account.user
+ SET role = 2
+ WHERE id = vUserId;
+
+ DELETE FROM pbx.sip
+ WHERE user_id = vUserId;
+
+ UPDATE `client` c
+ JOIN payMethod p ON p.name = 'CONTADO'
+ SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE
+ WHERE c.id = vUserId;
+
+ UPDATE `client` c
+ SET c.salesPersonFk = null
+ WHERE c.salesPersonFk = vUserId;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerDisableAll.sql b/db/routines/vn/procedures/workerDisableAll.sql
new file mode 100644
index 000000000..e2f7740b2
--- /dev/null
+++ b/db/routines/vn/procedures/workerDisableAll.sql
@@ -0,0 +1,36 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerDisableAll`()
+BEGIN
+ DECLARE done BOOL DEFAULT FALSE;
+ DECLARE vUserFk INT;
+
+ DECLARE rs CURSOR FOR
+ SELECT b.workerFk
+ FROM business b
+ JOIN vn.worker w ON w.id = b.workerFk
+ JOIN account.account a ON a.id = b.workerFk
+ LEFT JOIN (SELECT b.workerFk
+ FROM business b
+ WHERE (ended IS NULL OR ended >=util.VN_CURDATE())
+ )sub ON sub.workerFk = a.id
+ LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk
+ WHERE sub.workerFk IS NULL
+ AND wd.workerFk IS NULL
+ GROUP BY w.id;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+ OPEN rs;
+
+ FETCH rs INTO vUserFk;
+
+ WHILE NOT done DO
+ CALL workerDisable(vUserFk);
+ FETCH rs INTO vUserFk;
+
+ END WHILE;
+
+ CLOSE rs;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerForAllCalculateBoss.sql b/db/routines/vn/procedures/workerForAllCalculateBoss.sql
new file mode 100644
index 000000000..f3574116e
--- /dev/null
+++ b/db/routines/vn/procedures/workerForAllCalculateBoss.sql
@@ -0,0 +1,33 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerForAllCalculateBoss`()
+BEGIN
+/**
+* Actualiza la tabla workerBosses utilizando el procedimiento
+* vn.workerCalculateBoss(), actualiza todos los trabajadores en esa tabla
+*
+*/
+ DECLARE vWorker INT;
+ DECLARE vDone BOOL;
+
+ DECLARE cur CURSOR FOR
+ SELECT id FROM worker;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN cur;
+
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH cur INTO vWorker;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL workerCalculateBoss(vWorker);
+ END LOOP;
+
+ CLOSE cur;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerJourney_replace.sql b/db/routines/vn/procedures/workerJourney_replace.sql
new file mode 100644
index 000000000..1fcb8c590
--- /dev/null
+++ b/db/routines/vn/procedures/workerJourney_replace.sql
@@ -0,0 +1,308 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerJourney_replace`(
+ vDatedFrom DATE,
+ vDatedTo DATE,
+ vWorkerFk INT)
+BEGIN
+/**
+ * Actualiza la tabla workerJourney para que actue como caché permanente revisable
+ * de las jornadas laborales.
+ * @param vDatedFrom workerTimeControl
+ * @param vDatedTo workerTimeControl
+ * @param vWorkerFk, en caso de pasar 0 ó NULL se aplica a todos
+ */
+ DECLARE vDatedTimeTo DATETIME;
+ DECLARE vMaxTimePerDay INT;
+ DECLARE vMinHoursToBreak DECIMAL(10,2);
+ DECLARE vBreakHours DECIMAL(10,2);
+ DECLARE vMonthByYear INT;
+ DECLARE vWeeksByYear INT DEFAULT 52;
+ DECLARE vMonthsByYear INT DEFAULT 12;
+ DECLARE vDaysByWeek INT DEFAULT 5;
+ DECLARE vDatedFromYesterday DATETIME;
+ DECLARE vDatedToTomorrow DATETIME;
+
+ SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY)
+ INTO vDatedFromYesterday, vDatedToTomorrow;
+
+ SET vDatedTimeTo = util.dayEnd(vDatedTo);
+
+ SELECT minHoursToBreak, breakHours, maxTimePerDay
+ INTO vMinHoursToBreak, vBreakHours, vMaxTimePerDay
+ FROM workerTimeControlConfig;
+
+ DELETE FROM workerJourney
+ WHERE dated BETWEEN vDatedFrom AND vDatedTo
+ AND NOT isPaid
+ AND NOT isUpdated
+ AND (vWorkerFk IS NULL OR userFK = vWorkerFk);
+
+ -- Se inserta todos los días del periodo por worker y business en el rango de fechas.
+ INSERT IGNORE INTO workerJourney(userFk, dated, businessFk)
+ SELECT b.workerFk, t.dated, b.id
+ FROM business b
+ JOIN time t ON t.dated BETWEEN b.started AND IFNULL(b.ended,util.VN_CURDATE())
+ WHERE t.dated BETWEEN vDatedFrom AND vDatedTo
+ AND (vWorkerFk IS NULL OR b.workerFk = vWorkerFk)
+ ORDER BY b.workerFk, t.dated, b.id;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
+
+ IF vWorkerFk THEN
+ CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo);
+ CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user`
+ SELECT vWorkerFk userFk;
+ ELSE
+ CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo);
+ CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user`
+ SELECT id userFk
+ FROM worker w;
+ END IF;
+
+ UPDATE workerJourney wj
+ JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk
+ SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak,
+ t.timeWorkDecimal - vBreakHours,
+ t.timeWorkDecimal) AS DECIMAL (10,2)),
+ wj.lunch = IF(t.timeWorkDecimal >= vMinHoursToBreak , vBreakHours , 0)
+ WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
+ AND NOT wj.isPaid
+ AND NOT wj.isUpdated
+ AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk);
+
+ -- NOCTURNIDAD
+ CALL timeControl_getError(vDatedFrom, vDatedTimeTo);
+
+ SET @vIsOdd := TRUE;
+ SET @vDated := NULL;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControl;
+ CREATE TEMPORARY TABLE tmp.workerTimeControl
+ (INDEX (userFk), INDEX (timed))
+ ENGINE = MEMORY
+ SELECT DISTINCT(wtc.id),
+ wtc.userFk,
+ wtc.timed,
+ wtc.direction
+ FROM workerTimeControl wtc
+ JOIN tmp.`user` w ON w.userFk = wtc.userFk
+ LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
+ WHERE wtc.timed BETWEEN vDatedFrom AND vDatedToTomorrow
+ AND tce.id IS NULL
+ AND (vWorkerFk IS NULL OR wtc.userFk = vWorkerFk)
+ ORDER BY wtc.userFk, wtc.timed ASC;
+
+ SELECT MAX(id) INTO @vCont
+ FROM tmp.workerTimeControl;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux;
+ CREATE TEMPORARY TABLE tmp.workerTimeControlAux (
+ `id` int(11) ,
+ `userFk` int(10) unsigned ,
+ `timed` datetime,
+ `direction` enum('in', 'out','middle')
+ ) ENGINE=MEMORY;
+
+ SET @vIsOdd := TRUE;
+ SET @lastUserFk := NULL;
+ SET @lastDirection := NULL;
+
+ -- Cambio de dia en medio de un descanso
+ INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
+ SELECT @vCont:= @vCont + 1,
+ lastUserFk,
+ util.dayEnd(dated),
+ 'middle'
+ FROM (SELECT IF(@lastUserFk <> userFk, @vIsOdd := TRUE, NULL),
+ DATE(@lastTimed) dated,
+ @lastUserFk lastUserFk,
+ IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd,
+ IF(@vIsOdd
+ AND @lastDirection = 'middle'
+ AND (DATE(@lastTimed) <> date(timed)
+ OR @lastUserFk <> userFk), TRUE, FALSE) hasBreak,
+ @lastTimed := wtc.timed,
+ @lastUserFk := userFk,
+ @lastDirection := direction
+ FROM tmp.workerTimeControl wtc
+ ORDER BY wtc.userFk, wtc.timed)sub
+ WHERE hasBreak;
+
+ SET @vIsOdd := TRUE;
+ SET @lastUserFk := NULL;
+ SET @lastDirection := NULL;
+
+ INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
+ SELECT @vCont:= @vCont + 1,
+ lastUserFk,
+ DATE_ADD(sub.dated, INTERVAL 1 DAY),
+ 'middle'
+ FROM (SELECT IF(@lastUserFk <> userFk, @vIsOdd := TRUE, NULL),
+ DATE(@lastTimed) dated,
+ @lastUserFk lastUserFk,
+ IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd,
+ IF(@vIsOdd
+ AND @lastDirection = 'middle'
+ AND (DATE(@lastTimed)<>date(timed)
+ OR @lastUserFk<>userFk), TRUE, FALSE) hasBreak,
+ @lastTimed := wtc.timed,
+ @lastUserFk := userFk,
+ @lastDirection := direction
+ FROM tmp.workerTimeControl wtc
+ ORDER BY wtc.userFk, wtc.timed)sub
+ WHERE hasBreak;
+
+ -- Cambio de dia
+ INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
+ SELECT @vCont:= @vCont + 1,
+ wtc.userFk,
+ util.dayEnd(date(wtc.timed)),
+ 'out'
+ FROM workerTimeControl wtc
+ JOIN tmp.`user` w ON w.userFk = wtc.userFk
+ LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
+ WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ AND wtc.direction <> 'out'
+ GROUP BY wtc.userFk, DATE(wtc.timed);
+
+ INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
+ SELECT @vCont:= @vCont + 1,
+ wtc.userFk,
+ DATE_ADD(date(wtc.timed), INTERVAL 1 DAY),
+ 'in'
+ FROM workerTimeControl wtc
+ JOIN tmp.`user` w ON w.userFk = wtc.userFk
+ LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
+ WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
+ AND wtc.direction <> 'out'
+ GROUP BY wtc.userFk, DATE(wtc.timed);
+
+ INSERT INTO tmp.workerTimeControl (id, userFk, timed, direction)
+ SELECT id, userFk, timed, direction
+ FROM tmp.workerTimeControlAux;
+
+ SET @lastUserFk := NULL;
+ SET @vIsOdd := TRUE;
+ SET @vDated := NULL;
+ SET @vLastTimed := NULL;
+
+ UPDATE workerJourney wj
+ JOIN (SELECT sub.dated, userFk, SUM(NigthlyHours) NigthlyHours
+ FROM(SELECT (@vIsOdd := NOT @vIsOdd) isOdd,
+ IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd),
+ IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed),
+ IF(direction='in', @vDated := DATE(wtc.timed), @vDated ) dated,
+ wtc.userFk,
+ IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay,
+ workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed),
+ 0) NigthlyHours,
+ @lastUserFk := userFk
+ FROM (SELECT DISTINCT(wtc.id), wtc.userFk, wtc.timed, wtc.direction
+ FROM tmp.workerTimeControl wtc
+ LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
+ WHERE wtc.timed BETWEEN vDatedFrom AND util.dayEnd(vDatedToTomorrow)
+ AND tce.id IS NULL
+ ORDER BY userFk, timed ASC
+ LIMIT 10000000000000000000
+ ) wtc
+ ORDER BY wtc.userFk, wtc.timed
+ )sub
+ WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo
+ GROUP BY userFk, sub.dated
+ )night ON night.userFk = wj.userFk AND night.dated = wj.dated
+ SET wj.nocturn = night.NigthlyHours
+ WHERE NOT wj.isPaid
+ AND NOT isUpdated
+ AND night.NigthlyHours <> 0;
+
+ -- Horas téoricas y precio de la hora ordinaria
+ UPDATE workerJourney wj
+ JOIN business b ON b.id = wj.businessFk
+ JOIN calendarType ct ON ct.id = b.calendarTypeFk
+ SET wj.priceOrdinaryHour =
+ (vMonthsByYear * b.amount) /
+ (vWeeksByYear * ct.hoursWeek),
+ wj.contractJourney = ct.hoursWeek / vDaysByWeek
+ WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
+ AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
+ AND NOT wj.isPaid
+ AND NOT isUpdated;
+
+ -- Precio Extras, Vacaciones y Nocturnas
+ UPDATE workerJourney wj
+ JOIN(SELECT MAX(w.dated), t.dated, w.holidayInc, w.nightInc, w.extraInc
+ FROM time t
+ JOIN workerHourPrice w ON w.dated <= t.dated
+ WHERE t.dated BETWEEN vDatedFrom AND vDatedTo
+ GROUP BY t.dated
+ ) sub ON sub.dated = wj.dated
+ SET wj.priceHolidayHour = wj.priceOrdinaryHour * sub.holidayInc,
+ wj.priceNocturnHour = wj.priceOrdinaryHour * sub.nightInc,
+ wj.priceExtraHour = wj.priceOrdinaryHour * sub.extraInc
+ WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
+ AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
+ AND NOT wj.isPaid
+ AND NOT wj.isUpdated;
+
+ -- Elimina el precio de las horas extras para los contratos parciales.
+ UPDATE workerJourney wj
+ JOIN business b ON b.id = wj.businessFk
+ JOIN calendarType ct ON ct.id = b.calendarTypeFk
+ SET wj.priceExtraHour = 0
+ WHERE ct.isPartial
+ AND wj.dated BETWEEN vDatedFrom AND vDatedTo
+ AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
+ AND NOT wj.isPaid
+ AND NOT wj.isUpdated;
+
+ -- Ausencias
+ UPDATE workerJourney wj
+ JOIN businessCalendar bc ON bc.businessFk = wj.businessFk
+ AND bc.dated = wj.dated
+ JOIN absenceType ab ON ab.id = bc.absenceTypeFk
+ SET wj.permission = ab.permissionRate * wj.contractJourney,
+ wj.contractJourney = IF(ab.permissionRate = 1, 0, ab.permissionRate) * wj.contractJourney
+ WHERE ab.permissionRate > 0
+ AND wj.dated BETWEEN vDatedFrom AND vDatedTo
+ AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
+ AND NOT wj.isPaid
+ AND NOT wj.isUpdated;
+
+ -- Sábados / Domingos
+ UPDATE workerJourney
+ SET holiday = IF(DAYNAME(dated)='sábado', 0, total),
+ contractJourney = 0
+ WHERE DAYNAME(dated) IN ('sábado', 'domingo')
+ AND dated BETWEEN vDatedFrom AND vDatedTo
+ AND (vWorkerFk IS NULL OR userFk = vWorkerFk)
+ AND NOT isPaid
+ AND NOT isUpdated;
+
+ -- Festivos por centro de trabajo
+ UPDATE workerJourney wj
+ JOIN calendarHolidays ch ON ch.dated = wj.dated
+ JOIN business b ON b.id = wj.businessFk
+ AND b.workcenterFk = ch.workcenterFk
+ SET wj.holiday = wj.total,
+ wj.permission = wj.contractJourney,
+ wj.contractJourney = 0
+ WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
+ AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
+ AND NOT wj.isPaid
+ AND NOT wj.isUpdated;
+
+ -- Horas extras
+ UPDATE workerJourney
+ SET extra = lunch + total - contractJourney
+ WHERE dated BETWEEN vDatedFrom AND vDatedTo
+ AND (vWorkerFk IS NULL OR userFk = vWorkerFk)
+ AND NOT isPaid
+ AND NOT isUpdated;
+
+ DROP TEMPORARY TABLE tmp.timeControlCalculate;
+ DROP TEMPORARY TABLE tmp.`user`;
+ DROP TEMPORARY TABLE tmp.timeControlError;
+ DROP TEMPORARY TABLE tmp.workerTimeControlAux;
+ DROP TEMPORARY TABLE tmp.workerTimeControl;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerMistakeType_get.sql b/db/routines/vn/procedures/workerMistakeType_get.sql
new file mode 100644
index 000000000..ae81640a1
--- /dev/null
+++ b/db/routines/vn/procedures/workerMistakeType_get.sql
@@ -0,0 +1,14 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerMistakeType_get`()
+BEGIN
+
+/**
+ * Obtiene los tipos de error para los trabajadores
+ */
+
+ SELECT code, description
+ FROM workerMistakeType
+ ORDER BY description;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerMistake_add.sql b/db/routines/vn/procedures/workerMistake_add.sql
new file mode 100644
index 000000000..c4786090b
--- /dev/null
+++ b/db/routines/vn/procedures/workerMistake_add.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerMistake_add`(vWorkerFk INT, vWorkerMistakeTypeFk VARCHAR(10))
+BEGIN
+/**
+ * Añade error al trabajador
+ *
+ * @param vWorkerFk id del trabajador al cual se le va a añadir error
+ * @param vWorkerMistakeTypeFk code del tipo de error
+ *
+ */
+ INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk)
+ VALUES(vWorkerFk, vWorkerMistakeTypeFk);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControlSOWP.sql b/db/routines/vn/procedures/workerTimeControlSOWP.sql
new file mode 100644
index 000000000..14959b942
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControlSOWP.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControlSOWP`(IN vUserFk INT, IN vDated DATE)
+BEGIN
+ SET @order := 0;
+
+ UPDATE workerTimeControl
+ SET `order` = @order := @order + 1
+ WHERE vUserFk =userFk
+ AND vDated = DATE(timed)
+ ORDER BY timed;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_calculateOddDays.sql b/db/routines/vn/procedures/workerTimeControl_calculateOddDays.sql
new file mode 100644
index 000000000..9c1e58608
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_calculateOddDays.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_calculateOddDays`()
+BEGIN
+/**
+ * Calculo de las fichadas impares por empleado y dia.
+ *
+ * @return tmp.workerTimeControlOddDays (userFk, dated)
+ */
+ SET @cont := FALSE;
+ SET @lastUserFk:= NULL;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlOddDays;
+ CREATE TEMPORARY TABLE tmp.workerTimeControlOddDays
+ SELECT sub2.userFk workerFk, sub2.dated
+ FROM (
+ SELECT userFk,
+ dated,
+ COUNT(*) cont2
+ FROM (
+ SELECT DATE(wtc.timed) dated,
+ userFk,
+ IFNULL(@cont, @cont := TRUE ),
+ IF(direction = 'in' OR userFk <> @lastUserFk, @cont := @cont+1, TRUE),
+ @cont cont,
+ @lastUserFk := userFk
+ FROM workerTimeControl wtc
+ WHERE wtc.timed BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND util.dayEnd(util.VN_CURDATE())
+ ORDER BY userFk, timed
+ LIMIT 10000000000000000000)sub
+ GROUP BY cont
+ HAVING cont2 MOD 2 = 1
+ )sub2;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_check.sql b/db/routines/vn/procedures/workerTimeControl_check.sql
new file mode 100644
index 000000000..ce0e51490
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_check.sql
@@ -0,0 +1,168 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100))
+proc: BEGIN
+/**
+ * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a workerTimeControlAdd
+ *
+ * @param vUserFk Identificador del trabajador
+ * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ;
+ * En caso de tener algun problema retorna el primero que encuentra
+ */
+ DECLARE vLastIn DATETIME ;
+ DECLARE vLastOut DATETIME ;
+ DECLARE vDayWorkMax INT;
+ DECLARE vDayBreak INT;
+ DECLARE vWeekBreak INT ;
+ DECLARE vWeekScope INT;
+ DECLARE vDayStayMax INT;
+ DECLARE vProblem VARCHAR(20) DEFAULT NULL;
+ DECLARE vTimedWorked INT;
+ DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL;
+ DECLARE vDepartmentFk INT;
+ DECLARE vTo VARCHAR(50) DEFAULT NULL;
+ DECLARE vUserName VARCHAR(50) DEFAULT NULL;
+ DECLARE vBody VARCHAR(255) DEFAULT NULL;
+
+ SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax
+ INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax
+ FROM workerTimeControlParams;
+
+ SELECT MAX(timed) INTO vLastIn
+ FROM workerTimeControl
+ WHERE userFk = vUserFk
+ AND direction = 'in';
+
+ SELECT MAX(timed) INTO vLastOut
+ FROM workerTimeControl
+ WHERE userFk = vUserFk
+ AND direction = 'out';
+
+ SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo
+ FROM account.user u
+ WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk);
+
+ SELECT CONCAT(firstName,' ',lastName) INTO vUserName
+ FROM worker w
+ WHERE w.id = vUserFk;
+
+
+ IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA
+
+ -- VERIFICAR DESCANSO DIARIO
+ IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN
+ SELECT "Descansos 12 h" AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
+ SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody;
+ CALL mail_insert(vTo,vTo,'error al fichar',vBody);
+ LEAVE proc;
+ END IF;
+
+ -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ
+ IF (SELECT MOD(COUNT(*),2) -- <>0
+ FROM workerTimeControl
+ WHERE userFk = vUserFk
+ AND timed >= vLastIn
+ ) THEN
+ SELECT "Dias con fichadas impares" AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
+ SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody;
+ CALL mail_insert(vTo,vTo,'error al fichar',vBody);
+ LEAVE proc;
+ END IF;
+
+ -- VERIFICAR VACACIONES
+ SELECT at2.name INTO vCalendarStateType
+ FROM calendar c
+ JOIN business b ON b.id = c.businessFk
+ JOIN absenceType at2 ON at2.id = c.dayOffTypeFk
+ WHERE c.dated = util.VN_CURDATE()
+ AND at2.isAllowedToWork = FALSE
+ AND b.workerFk = vUserFk
+ LIMIT 1;
+
+ IF(LENGTH(vCalendarStateType)) THEN
+ SELECT vCalendarStateType AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
+ SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody;
+ CALL mail_insert(vTo,vTo,'error al fichar',vBody);
+ LEAVE proc;
+
+ END IF;
+
+ -- VERIFICAR CONTRATO EN VIGOR
+ IF (SELECT COUNT(*)
+ FROM business b
+ WHERE b.workerFk = vUserFk
+ AND b.started <= vDated
+ AND IFNULL(b.ended, vDated) >= vDated
+ ) = 0 THEN
+ SELECT "No hay un contrato en vigor" AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
+ SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody;
+ CALL mail_insert(vTo,vTo,'error al fichar',vBody);
+ LEAVE proc;
+
+ END IF;
+
+ -- VERIFICAR DESCANSO SEMANAL
+ SET @vHasBreakWeek:= FALSE;
+ SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND));
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.trash;
+ CREATE TEMPORARY TABLE tmp.trash
+ SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias,
+ @vLastTimed:= UNIX_TIMESTAMP(timed)
+ FROM workerTimeControl
+ WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND)
+ AND userFk= vUserFk
+ AND direction IN ('in','out')
+ ORDER BY timed ASC;
+
+ IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA
+ SELECT "Descansos 36 h" AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
+ SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody;
+ CALL mail_insert(vTo,vTo,'error al fichar',vBody);
+ LEAVE proc;
+ END IF;
+
+ DROP TEMPORARY TABLE tmp.trash;
+
+ ELSE -- DIA ACTUAL
+
+ -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO
+ SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked
+ FROM workerTimeControl wtc
+ WHERE userFk = vUserFk
+ AND timed >= vLastIn
+ ORDER BY timed;
+
+ IF vTimedWorked > vDayWorkMax THEN
+ SELECT "Jornadas" AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
+ SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody;
+ CALL mail_insert(vTo,vTo,'error al fichar',vBody);
+ LEAVE proc;
+ END IF;
+
+ END IF;
+
+ -- VERIFICAR DEPARTAMENTO
+ /* IF vTabletFk IS NOT NULL THEN
+ SELECT wtcu.departmentFk INTO vDepartmentFk
+ FROM workerTimeControlUserInfo wtcu
+ WHERE wtcu.userFk = vUserFk;
+ IF (SELECT COUNT(td.tabletFk)
+ FROM tabletDepartment td
+ WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk
+ ) = 0 THEN
+ SELECT "No perteneces a este departamento." AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
+ SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody;
+ CALL mail_insert(vTo,vTo,'error al fichar',vBody);
+ LEAVE proc;
+ END IF;
+ END IF;*/
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_checkBreak.sql b/db/routines/vn/procedures/workerTimeControl_checkBreak.sql
new file mode 100644
index 000000000..15dd12373
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_checkBreak.sql
@@ -0,0 +1,154 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_checkBreak`(vStarted DATE)
+BEGIN
+/**
+ * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas
+ * El sistema verificará el descanso corto en la siguiente semana
+ * o el largo en las 2 siguientes semanas a partir de la fecha dada
+ * @param vStarted día inicio de la semana en el que se quiere verificar
+ * @return tmp.workerWithoutWeekBreak (workerFk)
+ */
+ DECLARE vShortEnded DATETIME;
+ DECLARE vLongEnded DATETIME;
+ DECLARE vShortWeekBreak INT;
+ DECLARE vLongWeekBreak INT;
+
+ SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)),
+ util.dayEnd(DATE_ADD(vStarted, INTERVAL longWeekDays DAY)),
+ shortWeekBreak,
+ longWeekBreak
+ INTO vShortEnded, vLongEnded, vShortWeekBreak, vLongWeekBreak
+ FROM workerTimeControlConfig;
+
+ SET @previousTimed:= UNIX_TIMESTAMP(vStarted);
+ SET @lastUserFk := NULL;
+
+ -- Descanso corto en la semana
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.worker;
+ CREATE TEMPORARY TABLE tmp.worker
+ (PRIMARY KEY(workerFk))
+ ENGINE = MEMORY
+ SELECT DISTINCT userFk workerFk
+ FROM workerTimeControl
+ WHERE timed BETWEEN vStarted AND vShortEnded
+ AND direction IN ('in', 'out');
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.worker2;
+ CREATE TEMPORARY TABLE tmp.worker2
+ (PRIMARY KEY(workerFk))
+ ENGINE = MEMORY
+ SELECT workerFk
+ FROM tmp.worker;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutShortWeekBreak;
+ CREATE TEMPORARY TABLE tmp.workerWithoutShortWeekBreak
+ SELECT sub2.userFk workerFk
+ FROM(SELECT sub.userFk,
+ IF(sub.userFk <> @lastUserFk,
+ @previousTimed:= sub.timed,
+ FALSE),
+ IF(sub.timed - @previousTimed >= vShortWeekBreak,
+ TRUE,
+ FALSE) hasShortWeekBreak,
+ @previousTimed:= sub.timed,
+ @lastUserFk:= sub.userFk
+ FROM (
+ SELECT userFk, UNIX_TIMESTAMP(timed) timed
+ FROM workerTimeControl
+ WHERE timed BETWEEN vStarted AND vShortEnded
+ AND direction IN ('in', 'out')
+ UNION
+ SELECT w.workerFk,
+ UNIX_TIMESTAMP(IFNULL(
+ MIN(wtc.timed),
+ DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND)))
+ FROM tmp.worker w
+ LEFT JOIN workerTimeControl wtc
+ ON wtc.userFk = w.workerFk
+ AND wtc.timed BETWEEN vShortEnded
+ AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND)
+ GROUP BY w.workerFk
+ UNION
+ SELECT w.workerFk,
+ UNIX_TIMESTAMP(IFNULL(
+ MAX(wtc.timed),
+ DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND)))
+ FROM tmp.worker2 w
+ LEFT JOIN workerTimeControl wtc
+ ON wtc.userFk = w.workerFk
+ AND wtc.timed BETWEEN
+ DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND)
+ AND vStarted
+ GROUP BY w.workerFk
+ ORDER BY userFk, timed
+ LIMIT 10000000000000000000
+ )sub
+ )sub2
+ GROUP BY sub2.userFk
+ HAVING NOT SUM(hasShortWeekBreak);
+
+ -- Descanso largo en las 2 siguientes semanas
+ DROP TEMPORARY TABLE tmp.worker;
+ CREATE TEMPORARY TABLE tmp.worker
+ (PRIMARY KEY(workerFk))
+ ENGINE = MEMORY
+ SELECT workerFk
+ FROM tmp.workerWithoutShortWeekBreak;
+
+ DROP TEMPORARY TABLE tmp.worker2;
+ CREATE TEMPORARY TABLE tmp.worker2
+ (PRIMARY KEY(workerFk))
+ ENGINE = MEMORY
+ SELECT workerFk
+ FROM tmp.workerWithoutShortWeekBreak;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreak;
+ CREATE TEMPORARY TABLE tmp.workerWithoutWeekBreak
+ (PRIMARY KEY(workerFk))
+ ENGINE = MEMORY
+ SELECT sub2.userFk workerFk
+ FROM(SELECT userFk,
+ IF(userFk <> @lastUserFk,
+ @previousTimed:= timed,
+ TRUE),
+ IF(timed - @previousTimed >= vLongWeekBreak,
+ TRUE,
+ FALSE) hasLongWeekBreak,
+ @previousTimed:= timed,
+ @lastUserFk:= userFk
+ FROM (SELECT userFk, UNIX_TIMESTAMP(timed) timed
+ FROM workerTimeControl wtc
+ JOIN tmp.workerWithoutShortWeekBreak wws ON wws.workerFk = wtc.userFk
+ WHERE timed BETWEEN vStarted AND vLongEnded
+ AND direction IN ('in', 'out')
+ UNION
+ SELECT w.workerFk,
+ UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed),
+ DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND)))
+ FROM tmp.worker w
+ LEFT JOIN workerTimeControl wtc
+ ON wtc.userFk = w.workerFk
+ AND timed BETWEEN vLongEnded
+ AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND)
+ GROUP BY w.workerFk
+ UNION
+ SELECT w.workerFk,
+ UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed),
+ DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND)))
+ FROM tmp.worker2 w
+ LEFT JOIN workerTimeControl wtc
+ ON wtc.userFk = w.workerFk
+ AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND)
+ AND vStarted
+ GROUP BY w.workerFk
+ ORDER BY userFk, timed
+ LIMIT 10000000000000000000
+ )sub
+ )sub2
+ GROUP BY userFk
+ HAVING NOT SUM(hasLongWeekBreak);
+
+ DROP TEMPORARY TABLE tmp.workerWithoutShortWeekBreak, tmp.worker, tmp.worker2;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_clockIn.sql b/db/routines/vn/procedures/workerTimeControl_clockIn.sql
new file mode 100644
index 000000000..e58528487
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_clockIn.sql
@@ -0,0 +1,288 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_clockIn`(
+ vWorkerFk INT,
+ vTimed DATETIME,
+ vDirection VARCHAR(10),
+ vDevice VARCHAR(255)
+)
+BEGIN
+/**
+* Verifica si el empleado puede fichar
+* @param vWorkerFk Identificador del trabajador
+* @param vTimed Balor de la fichada, IF vTimed IS NULL vTimed = NOW
+* @param vDirection Solo se pueden pasa los valores del campo
+* workerTimeControl.direction ENUM('in', 'out', 'middle')
+* @param vDevice Dispositivo en el que se ha fichado
+* @return Si todo es correcto, retorna el número de id la tabla workerTimeControl.
+* Si hay algún problema, devuelve el mesaje que se debe mostrar al usuario
+* Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá
+* fichada a la tabla vn.workerTimeControl
+*/
+
+ DECLARE vLastIn DATETIME;
+ DECLARE vLastOut DATETIME;
+ DECLARE vNextIn DATETIME;
+ DECLARE vNextOut DATETIME;
+ DECLARE vNextDirection ENUM('in', 'out');
+ DECLARE vLastDirection ENUM('in', 'out');
+ DECLARE vDayMaxTime INTEGER;
+ DECLARE vDayBreak INT;
+ DECLARE vShortWeekBreak INT;
+ DECLARE vLongWeekBreak INT;
+ DECLARE vWeekScope INT;
+ DECLARE vMailTo VARCHAR(50) DEFAULT NULL;
+ DECLARE vUserName VARCHAR(50) DEFAULT NULL;
+ DECLARE vIsError BOOLEAN DEFAULT FALSE;
+ DECLARE vErrorMessage VARCHAR(255) DEFAULT NULL;
+ DECLARE vErrorCode VARCHAR(50);
+ DECLARE vDated DATE;
+ DECLARE vIsAllowedToWork VARCHAR(50);
+ DECLARE vIsManual BOOLEAN DEFAULT TRUE;
+ DECLARE vMaxWorkShortCycle INT;
+ DECLARE vMaxWorkLongCycle INT;
+
+ DECLARE EXIT HANDLER FOR SQLSTATE '45000'
+ BEGIN
+
+ SELECT CONCAT(u.name, '@verdnatura.es'),
+ CONCAT(w.firstName, ' ', w.lastName)
+ INTO vMailTo, vUserName
+ FROM account.user u
+ JOIN worker w ON w.bossFk = u.id
+ WHERE w.id = vWorkerFk;
+
+ SELECT `description` INTO vErrorMessage
+ FROM workerTimeControlError
+ WHERE `code` = vErrorCode;
+
+ IF vErrorMessage IS NULL THEN
+ SET vErrorMessage = 'Error sin definir';
+ END IF;
+
+ SELECT vErrorMessage `error`;
+ SELECT CONCAT(vUserName,
+ ' no ha podido fichar por el siguiente problema: ',
+ vErrorMessage)
+ INTO vErrorMessage;
+
+ CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage);
+ END;
+
+ IF (vTimed IS NULL) THEN
+ SET vTimed = util.VN_NOW();
+ SET vIsManual = FALSE;
+ END IF;
+
+ SET vDated = DATE(vTimed);
+
+ SELECT IF(pc.code = 'driverCE',
+ wc.dayBreakDriver,
+ wc.dayBreak),
+ wc.shortWeekBreak,
+ wc.longWeekBreak,
+ wc.weekScope,
+ wc.dayMaxTime,
+ wc.maxWorkShortCycle,
+ wc.maxWorkLongCycle
+ INTO vDayBreak,
+ vShortWeekBreak,
+ vLongWeekBreak,
+ vWeekScope,
+ vDayMaxTime,
+ vMaxWorkShortCycle,
+ vMaxWorkLongCycle
+ FROM business b
+ JOIN professionalCategory pc
+ ON pc.id = b.workerBusinessProfessionalCategoryFk
+ JOIN workerTimeControlConfig wc
+ WHERE b.workerFk = vWorkerFk
+ AND vDated BETWEEN b.started AND IFNULL(b.ended, vDated);
+
+ -- CONTRATO EN VIGOR
+ IF vDayBreak IS NULL THEN
+ SET vErrorCode = 'INACTIVE_BUSINESS';
+ CALL util.throw(vErrorCode);
+ END IF;
+
+ -- FICHADAS A FUTURO
+ IF vTimed > util.VN_NOW() + INTERVAL 1 MINUTE THEN
+ SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE';
+ CALL util.throw(vErrorCode);
+ END IF;
+
+ -- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR
+ CALL timeBusiness_calculateByWorker(vWorkerFk, vDated, vDated);
+ SELECT isAllowedToWork INTO vIsAllowedToWork
+ FROM tmp.timeBusinessCalculate;
+ DROP TEMPORARY TABLE tmp.timeBusinessCalculate;
+
+ IF NOT vIsAllowedToWork THEN
+ SET vErrorCode = 'IS_NOT_ALLOWED_WORK';
+ CALL util.throw(vErrorCode);
+ END IF;
+
+ -- DIRECCION CORRECTA
+ CALL workerTimeControl_direction(vWorkerFk, vTimed);
+ IF (SELECT
+ IF(IF(option1 IN ('inMiddle', 'outMiddle'),
+ 'middle',
+ option1) <> vDirection
+ AND IF(option2 IN ('inMiddle', 'outMiddle'),
+ 'middle',
+ IFNULL(option2, '')) <> vDirection,
+ TRUE ,
+ FALSE)
+ FROM tmp.workerTimeControlDirection
+ ) THEN
+ SET vIsError = TRUE;
+ END IF;
+
+ DROP TEMPORARY TABLE tmp.workerTimeControlDirection;
+ IF vIsError THEN
+ SET vErrorCode = 'WRONG_DIRECTION';
+ CALL util.throw(vErrorCode);
+ END IF;
+
+ -- FICHADAS IMPARES
+ SELECT timed INTO vLastIn
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'in'
+ AND timed < vTimed
+ ORDER BY timed DESC
+ LIMIT 1;
+
+ IF (SELECT IF(vDirection = 'in',
+ MOD(COUNT(*), 2) ,
+ IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE))
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND timed BETWEEN vLastIn AND vTimed
+ ) THEN
+ SET vErrorCode = 'ODD_WORKERTIMECONTROL';
+ CALL util.throw(vErrorCode);
+ END IF;
+
+ -- DESCANSO DIARIO
+ SELECT timed INTO vLastOut
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'out'
+ AND timed < vTimed
+ ORDER BY timed DESC
+ LIMIT 1;
+
+ SELECT timed INTO vNextIn
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'in'
+ AND timed > vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+
+ CASE vDirection
+ WHEN 'in' THEN
+ IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN
+ SET vIsError = TRUE;
+ END IF;
+ WHEN 'out' THEN
+ IF UNIX_TIMESTAMP(vNextIn) - UNIX_TIMESTAMP(vTimed) <= vDayBreak THEN
+ SET vIsError = TRUE;
+ END IF;
+ ELSE BEGIN END;
+ END CASE;
+
+ IF vIsError THEN
+ SET vErrorCode = 'BREAK_DAY';
+ CALL util.throw(vErrorCode);
+ END IF;
+
+
+
+ IF (vDirection IN('in', 'out')) THEN
+ -- VERIFICA MAXIMO TIEMPO DESDE ENTRADA HASTA LA SALIDA
+
+ SELECT timed INTO vNextOut
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'out'
+ AND timed > vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+
+ SELECT direction INTO vNextDirection
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction IN('in','out')
+ AND timed > vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+
+ SELECT direction INTO vLastDirection
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction IN('in', 'out')
+ AND timed < vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+
+ IF (vDirection ='in'
+ AND vNextDirection = 'out'
+ AND UNIX_TIMESTAMP(vNextOut) - UNIX_TIMESTAMP(vTimed) > vDayMaxTime) OR
+ (vDirection ='out'
+ AND vLastDirection = 'in'
+ AND UNIX_TIMESTAMP(vTimed) -UNIX_TIMESTAMP(vLastIn) > vDayMaxTime) THEN
+ SET vErrorCode = 'DAY_MAX_TIME';
+ CALL util.throw(vErrorCode);
+ END IF;
+
+ -- VERIFICA DESCANSO SEMANAL
+
+ WITH wtc AS(
+ (SELECT timed
+ FROM vn.workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction IN ('in', 'out')
+ AND timed BETWEEN vTimed - INTERVAL (vWeekScope * 2) SECOND
+ AND vTimed + INTERVAL (vWeekScope * 2) SECOND )
+ UNION
+ (SELECT vTimed)
+ ), wtcGap AS(
+ SELECT timed,
+ TIMESTAMPDIFF(SECOND, LAG(timed) OVER (ORDER BY timed), timed) gap
+ FROM wtc
+ ORDER BY timed
+ ), wtcBreak AS(
+ SELECT timed,
+ IF(IFNULL(gap, 0) > vShortWeekBreak, TRUE, FALSE) hasShortBreak,
+ IF(IFNULL(gap, 0) > vLongWeekBreak, TRUE, FALSE) hasLongBreak
+ FROM wtcGap
+ ORDER BY timed
+ ), wtcBreakCounter AS(
+ SELECT timed,
+ SUM(hasShortBreak) OVER (ORDER BY timed) breakCounter ,
+ LEAD(hasLongBreak) OVER (ORDER BY timed) nextHasLongBreak
+ FROM wtcBreak
+ )SELECT TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed)) > vMaxWorkLongCycle OR
+ (TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed))> vMaxWorkShortCycle
+ AND NOT SUM(IFNULL(nextHasLongBreak, 1)))
+ hasError INTO vIsError
+ FROM wtcBreakCounter
+ GROUP BY breakCounter
+ HAVING hasError
+ LIMIT 1;
+
+ IF vIsError THEN
+ SET vErrorCode = 'BREAK_WEEK';
+ CALL util.throw(vErrorCode);
+ END IF;
+ END IF;
+
+ -- Se permite fichar
+ INSERT INTO workerTimeControl(userFk, timed, direction, device, `manual`)
+ VALUES(vWorkerFk, vTimed, vDirection, vDevice, vIsManual);
+
+ SELECT LAST_INSERT_ID() id;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_direction.sql b/db/routines/vn/procedures/workerTimeControl_direction.sql
new file mode 100644
index 000000000..ce44b9703
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_direction.sql
@@ -0,0 +1,61 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_direction`(vWorkerFk VARCHAR(10), vTimed DATETIME)
+BEGIN
+/**
+ * Devuelve que direcciones de fichadas son lógicas a partir de la anterior fichada
+ * @param vWorkerFk Identificador del trabajador
+ * @return (option1, option2)
+ * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out')
+ */
+ DECLARE vLastIn DATETIME ;
+ DECLARE vIsMiddleOdd BOOLEAN ;
+
+ IF (vTimed IS NULL) THEN
+ SET vTimed = util.VN_NOW();
+ END IF;
+
+ SELECT timed INTO vLastIn
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'in'
+ AND timed < vTimed
+ ORDER BY timed DESC
+ LIMIT 1;
+
+ SELECT (COUNT(*)mod 2 = 1) INTO vIsMiddleOdd
+ FROM workerTimeControl
+ WHERE userFk = vWorkerFk
+ AND direction = 'middle'
+ AND timed BETWEEN vLastIn AND util.VN_NOW();
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlDirection;
+ CREATE TEMPORARY TABLE tmp.workerTimeControlDirection
+ SELECT IF(isCorrect, option1, NULL) option1,
+ IF(isCorrect, option2, NULL) option2
+ FROM( SELECT IF(w.direction <> 'out' AND (UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(w.timed) > wc.dayBreak), FALSE, TRUE) isCorrect,
+ CASE WHEN w.direction ='in' THEN 'inMiddle'
+ WHEN w.direction = 'out' THEN 'in'
+ WHEN w.direction = 'middle' AND vIsMiddleOdd THEN 'outMiddle'
+ WHEN w.direction IS NULL THEN 'in'
+ ELSE 'inMiddle'
+ END option1,
+ CASE WHEN w.direction ='in' THEN 'out'
+ WHEN w.direction = 'out' THEN NULL
+ WHEN w.direction = 'middle' AND vIsMiddleOdd THEN NULL
+ WHEN w.direction IS NULL THEN NULL
+ ELSE 'out'
+ END option2
+ FROM workerTimeControl w
+ JOIN workerTimeControlConfig wc ON TRUE
+ WHERE w.timed <= vTimed
+ AND w.userFk = vWorkerFk
+ ORDER BY w.timed DESC
+ LIMIT 1)sub;
+
+ IF (SELECT IF(COUNT(*)=0, TRUE, FALSE) FROM tmp.workerTimeControlDirection ) THEN
+ INSERT INTO tmp.workerTimeControlDirection (option1, option2)
+ VALUES('in', NULL);
+ END IF;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_getClockIn.sql b/db/routines/vn/procedures/workerTimeControl_getClockIn.sql
new file mode 100644
index 000000000..11cd23fa5
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_getClockIn.sql
@@ -0,0 +1,78 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_getClockIn`(
+ vUserFk INT,
+ vDated DATE)
+BEGIN
+/**
+ * Muestra una tabla con los 7 días inmediatamente anteriores a la fecha proporcionada
+ * y las fichadas de cada día, en columnas por día
+ * @param vUserFk Identificador del trabajador
+ * @param vDated Fecha proporcionada
+ */
+ CALL timeControl_calculateByWorker(
+ vUserFk,
+ DATE_SUB(vDated, INTERVAL 6 DAY), util.dayEnd(vDated));
+
+ SET @position := 0;
+ SET @lastDated := NULL;
+
+ SELECT *
+ FROM( SELECT MAX(6daysAgo) 6daysAgo,
+ MAX(6daysAgoDirection) 6daysAgoDirection,
+ MAX(5daysAgo) 5daysAgo,
+ MAX(5daysAgoDirection) 5daysAgoDirection,
+ MAX(4daysAgo) 4daysAgo,
+ MAX(4daysAgoDirection) 4daysAgoDirection,
+ MAX(3daysAgo) 3daysAgo,
+ MAX(3daysAgoDirection) 3daysAgoDirection,
+ MAX(2daysAgo) 2daysAgo,
+ MAX(2daysAgoDirection) 2daysAgoDirection,
+ MAX(1daysAgo) 1daysAgo,
+ MAX(1daysAgoDirection) 1daysAgoDirection,
+ MAX(0daysAgo) 0daysAgo,
+ MAX(0daysAgoDirection) 0daysAgoDirection
+ FROM(SELECT IF(daysAgo = 6, timed, '') 6daysAgo,
+ IF(daysAgo = 5, timed, '') 5daysAgo,
+ IF(daysAgo = 4, timed, '') 4daysAgo,
+ IF(daysAgo = 3, timed, '') 3daysAgo,
+ IF(daysAgo = 2, timed, '') 2daysAgo,
+ IF(daysAgo = 1, timed, '') 1daysAgo,
+ IF(daysAgo = 0, timed, '') 0daysAgo,
+ IF(daysAgo = 6, direction, '') 6daysAgoDirection,
+ IF(daysAgo = 5, direction, '') 5daysAgoDirection,
+ IF(daysAgo = 4, direction, '') 4daysAgoDirection,
+ IF(daysAgo = 3, direction, '') 3daysAgoDirection,
+ IF(daysAgo = 2, direction, '') 2daysAgoDirection,
+ IF(daysAgo = 1, direction, '') 1daysAgoDirection,
+ IF(daysAgo = 0, direction, '') 0daysAgoDirection,
+
+ direction,
+ position
+ FROM(SELECT DATEDIFF(vDated, timed) daysAgo,
+ TIME_FORMAT(timed,'%H:%i') timed,
+ IF(DATE(timed) <> @lastDated, @position := 0, NULL),
+ @position := @position+1 position,
+ @lastDated := DATE(timed),
+ direction
+ FROM workerTimeControl wtc
+ WHERE wtc.userFk = vUserFk
+ AND wtc.timed >= TIMESTAMPADD(DAY, -6,vDated)
+ ORDER BY wtc.timed
+ LIMIT 10000000000000000000
+ )sub
+ )sub2
+ GROUP BY position) sub3
+ JOIN (SELECT MAX(IF(daysAgo = 6, timeWorkSeconds, 0)) 6daysAgoTotal,
+ MAX(IF(daysAgo = 5, timeWorkSeconds, 0)) 5daysAgoTotal,
+ MAX(IF(daysAgo = 4, timeWorkSeconds, 0)) 4daysAgoTotal,
+ MAX(IF(daysAgo = 3, timeWorkSeconds, 0)) 3daysAgoTotal,
+ MAX(IF(daysAgo = 2, timeWorkSeconds, 0)) 2daysAgoTotal,
+ MAX(IF(daysAgo = 1, timeWorkSeconds, 0)) 1daysAgoTotal,
+ MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal
+ FROM (SELECT DATEDIFF(vDated, dated) daysAgo,
+ timeWorkSeconds
+ FROM tmp.timeControlCalculate) sub4)sub5 ON TRUE;
+
+ DROP TEMPORARY TABLE tmp.timeControlCalculate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_login.sql b/db/routines/vn/procedures/workerTimeControl_login.sql
new file mode 100644
index 000000000..c46663e1f
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_login.sql
@@ -0,0 +1,26 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_login`(vWorkerFk VARCHAR(10))
+BEGIN
+/**
+ * Consulta la información del usuario y los botones que tiene que activar en la tablet tras hacer login
+ * Solo retornará 1 ó 2 opciones de las 4 posibles
+ * @param vWorkerFk Identificador del trabajador
+ * @return (name, surname, userFk, departmentFk, button1, button2)
+ * Los valores posibles para button son ('in', 'inMiddle', 'outMiddle', 'out')
+ */
+ CALL vn.workerTimeControl_direction(vWorkerFk, util.VN_NOW());
+
+ SELECT wi.name,
+ wi.surname,
+ wi.userFk,
+ wi.departmentFk,
+ w.option1 button1,
+ w.option2 button2
+ FROM workerTimeControlUserInfo wi
+ JOIN tmp.workerTimeControlDirection w
+ WHERE wi.userFk = vWorkerFk
+ LIMIT 1;
+
+ DROP TEMPORARY TABLE tmp.workerTimeControlDirection;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_remove.sql b/db/routines/vn/procedures/workerTimeControl_remove.sql
new file mode 100644
index 000000000..7b34cbbeb
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_remove.sql
@@ -0,0 +1,49 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_remove`(IN vUserFk INT, IN vTimed DATETIME)
+BEGIN
+
+ DECLARE vDirectionRemove VARCHAR(6);
+ DECLARE vDirectionPrevious VARCHAR(6);
+ DECLARE vTimedPrevious DATETIME;
+
+ SELECT direction INTO vDirectionRemove
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
+ AND timed = vTimed ;
+
+ IF vDirectionRemove = 'out' THEN
+
+ SELECT timed, direction INTO vTimedPrevious, vDirectionPrevious
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
+ AND timed < vTimed
+ ORDER BY timed DESC
+ LIMIT 1;
+
+ IF vDirectionPrevious = "middle" THEN
+ UPDATE vn.workerTimeControl
+ SET direction = "out"
+ WHERE userFk = vUserFk
+ AND timed = vTimedPrevious;
+ END IF;
+
+ ELSE IF vDirectionRemove = 'in' THEN
+
+ UPDATE vn.workerTimeControl
+ SET direction = "in"
+ WHERE userFk = vUserFk
+ AND timed > vTimed
+ ORDER BY timed ASC
+ LIMIT 1;
+ END IF;
+
+ END IF;
+
+ DELETE FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
+ AND timed = vTimed;
+
+ CALL vn.workerTimeControlSOWP(vUserFk, vTimed);
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_sendMailByDepartment.sql b/db/routines/vn/procedures/workerTimeControl_sendMailByDepartment.sql
new file mode 100644
index 000000000..5b276084a
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_sendMailByDepartment.sql
@@ -0,0 +1,129 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_sendMailByDepartment`(IN vDatedFrom DATETIME, IN vDatedTo DATETIME, IN vWorkerFk INT)
+BEGIN
+/**
+ * Inserta el registro de horario semanalmente de PRODUCCION, CAMARA, REPARTO, TALLER NATURAL y TALLER ARTIFICIAL en vn.mail.
+ *
+ * @param vDatedFrom
+ * @param vDatedTo
+ * @param vWorkerFk -> En el caso de querer generarlo para todos los empleados deberá de pasarse = NULL
+ */
+ SET session group_concat_max_len = 15000;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate;
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate;
+ DROP TEMPORARY TABLE IF EXISTS tmp.reportHours;
+
+ IF vWorkerFk IS NULL THEN
+ CALL timeControl_calculateAll(vDatedFrom,vDatedTo);
+ CALL timeBusiness_calculateAll(vDatedFrom,vDatedTo);
+ ELSE
+ CALL timeControl_calculateByUser(vWorkerFk,vDatedFrom,vDatedTo);
+ CALL timeBusiness_calculateByUser(vWorkerFk,vDatedFrom,vDatedTo);
+ END IF;
+
+ CREATE TEMPORARY TABLE tmp.reportHours
+ SELECT t.dated,
+ IF (tm.hoursWeek IS NULL,'', GROUP_CONCAT(DATE_FORMAT(wtc.timed,'%H:%i') ORDER BY wtc.timed ASC SEPARATOR ' ') ) timeWorkDay,
+ SEC_TO_TIME(IFNULL(tm.timeWorkSeconds, 0)) tm,
+ SEC_TO_TIME(IFNULL(tc.timeWorkSeconds, 0)) tc,
+ SEC_TO_TIME(IFNULL(tc.timeWorkSeconds, 0) - IFNULL(tm.timeWorkSeconds, 0)) balance,
+ w.lastName,
+ w.firstname,
+ c.fi,
+ w.id userFk,
+ MONTHNAME(t.dated) mes,
+ YEAR(t.dated) año,
+ w.id,
+ tm.hoursWeek,
+ tm.type,
+ b.started,
+ b.ended,
+ d.name,
+ tm.businessFk
+ FROM time t
+ LEFT JOIN tmp.timeBusinessCalculate tm ON tm.dated = t.dated
+ LEFT JOIN tmp.timeControlCalculate tc ON tc.dated = tm.dated AND tc.userFk = tm.userFk
+ LEFT JOIN vn.workerTimeControl wtc ON wtc.userFk = tm.userFk AND DATE(wtc.timed) = t.dated
+ LEFT JOIN business b ON b.workerFk = tm.userFk AND b.id = tm.businessFk
+ LEFT JOIN workCenter wc ON wc.id = b.workcenterFk
+ LEFT JOIN department d ON d.id = b.departmentFk
+ LEFT JOIN worker w ON w.id = tm.userFk
+ LEFT JOIN client c ON c.id = w.id
+ WHERE wc.name NOT IN ('VNH')
+ AND d.hasToSendMail
+ AND w.businessFk
+ GROUP BY tm.userFk,t.dated
+ ORDER BY tm.userFk,t.dated;
+
+ INSERT INTO vn.mail (receiver, replyTo, subject, body)
+ SELECT eu.email, 'laboral@verdnatura.es', CONCAT('Registro de horas semana ', WEEK(vDatedFrom), ' año ', YEAR(vDatedFrom)) ,
+ CONCAT('
+
+
+
+
+
+
+
+
REGISTRO DE LA JORNADA DE LOS TRABAJADORES
+
+
+
+ Según la información recogida en el sistema, adjuntamos la tabla con los registros. Cualquier incidencia rogamos la comunique a laboral@verdnatura.es.
+ De no recibir incidencia por su parte, se entenderá que el registro es correcto.
+
+
+
+
Empresa: Verdnatura Levante SL
+
+
+
Trabajador: ',rh.firstname,' ',rh.lastName, '
+
NIF: ',rh.fi, '
+
+
+
AÑO: ',rh.año, '
+
MES: ',UPPER(rh.mes), '
+
Calendario Laboral: ',rh.hoursWeek,' horas semanales
diff --git a/front/salix/components/user-popover/index.html b/front/salix/components/user-popover/index.html
index 0fa6800c5..06a4af1e0 100644
--- a/front/salix/components/user-popover/index.html
+++ b/front/salix/components/user-popover/index.html
@@ -58,7 +58,7 @@
label="Local bank"
id="localBank"
ng-model="$ctrl.localBankFk"
- url="Banks"
+ url="Accountings"
select-fields="['id','bank']"
show-field="bank"
order="id"
diff --git a/front/salix/locale/es.yml b/front/salix/locale/es.yml
index bed41c63b..044d0d043 100644
--- a/front/salix/locale/es.yml
+++ b/front/salix/locale/es.yml
@@ -18,6 +18,7 @@ Show summary: Mostrar vista previa
What is new: Novedades de la versión
Settings: Ajustes
There is a new version, click here to reload: Hay una nueva versión, pulse aquí para recargar
+This ticket is locked: Este ticket está bloqueado
# Actions
diff --git a/front/salix/module.js b/front/salix/module.js
index f8fa0faf0..53b718427 100644
--- a/front/salix/module.js
+++ b/front/salix/module.js
@@ -13,7 +13,7 @@ export function run($window, $rootScope, vnAuth, vnApp, vnToken, $state) {
if (!collection || !size || !id) return;
const basePath = `/api/Images/${collection}/${size}/${id}`;
- return `${basePath}/download?access_token=${vnToken.token}`;
+ return `${basePath}/download?access_token=${vnToken.tokenMultimedia}`;
};
$window.validations = {};
@@ -120,7 +120,7 @@ function $exceptionHandler(vnApp, $window, $state, $injector) {
messageT = 'Invalid login';
break;
case 403:
- messageT = 'Access denied';
+ messageT = exception.data?.error?.message || 'Access Denied';
break;
case 502:
messageT = 'It seems that the server has fall down';
diff --git a/gulpfile.js b/gulpfile.js
index d7e7d8e86..aa2b65bc1 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -1,21 +1,20 @@
+/* eslint-disable no-console */
require('require-yaml');
const gulp = require('gulp');
const PluginError = require('plugin-error');
-const argv = require('minimist')(process.argv.slice(2));
const log = require('fancy-log');
-const Docker = require('./db/docker.js');
+const Myt = require('@verdnatura/myt/myt');
+const Run = require('@verdnatura/myt/myt-run');
+const Start = require('@verdnatura/myt/myt-start');
// Configuration
let isWindows = /^win/.test(process.platform);
-if (argv.NODE_ENV)
- process.env.NODE_ENV = argv.NODE_ENV;
-
let langs = ['es', 'en'];
let srcDir = './front';
let modulesDir = './modules';
-let buildDir = 'dist';
+let buildDir = 'front/dist';
let backSources = [
'!node_modules',
@@ -65,19 +64,40 @@ back.description = `Starts backend and database service`;
const defaultTask = gulp.parallel(front, back);
defaultTask.description = `Starts all application services`;
-function install() {
- const install = require('gulp-install');
- const print = require('gulp-print');
+async function install() {
+ const spawn = require('child_process').spawn;
- let npmArgs = [];
- if (argv.ci) npmArgs = ['--no-audit', '--prefer-offline'];
+ console.log('-> Installing global packages...');
+ await pnpmInstall();
- let packageFiles = ['front/package.json', 'print/package.json'];
- return gulp.src(packageFiles)
- .pipe(print(filepath => {
- return `Installing packages in ${filepath}`;
- }))
- .pipe(install({npm: npmArgs}));
+ const modules = ['front', 'print'];
+ for (const module of modules) {
+ console.log(`-> Installing '${module}' packages...`);
+ await pnpmInstall(module);
+ }
+
+ async function pnpmInstall(prefix) {
+ let args = ['install', '--prefer-offline'];
+ if (prefix) args = args.concat(['--prefix', prefix]);
+
+ const options = {
+ stdio: [
+ process.stdin,
+ process.stdout,
+ process.stderr
+ ]
+ };
+
+ await new Promise((resolve, reject) => {
+ const child = spawn('pnpm', args, options);
+ child.on('exit', code => {
+ if (code !== 0)
+ reject(new Error(`pnpm exit code ${code}`));
+ else
+ resolve(code);
+ });
+ });
+ }
}
install.description = `Installs node dependencies in all directories`;
@@ -231,16 +251,20 @@ watch.description = `Watches for changes in routes and locale files`;
// Docker
async function dockerStart() {
- const container = new Docker('salix-db');
- await container.start();
+ const myt = new Myt();
+ await myt.init({workspace: __dirname});
+ await myt.run(Start);
+ await myt.deinit();
}
-dockerStart.description = `Starts the salix-db container`;
+dockerStart.description = `Starts the DB container`;
async function docker() {
- const container = new Docker('salix-db');
- await container.run();
+ const myt = new Myt();
+ await myt.init({workspace: __dirname});
+ await myt.run(Run);
+ await myt.deinit();
}
-docker.description = `Runs the salix-db container`;
+docker.description = `Builds and starts the DB container`;
module.exports = {
default: defaultTask,
@@ -258,5 +282,6 @@ module.exports = {
locales,
localesRoutes,
watch,
+ dockerStart,
docker
};
diff --git a/jest.front.config.js b/jest.front.config.js
index 3289df8bb..4b292801e 100644
--- a/jest.front.config.js
+++ b/jest.front.config.js
@@ -1,6 +1,8 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
/* eslint max-len: ["error", { "code": 150 }]*/
+const cpus = require('os').cpus().length;
+const maxCpus = Math.floor(cpus * 0.45);
module.exports = {
name: 'front end',
@@ -10,8 +12,9 @@ module.exports = {
},
testEnvironment: 'jsdom',
setupFilesAfterEnv: [
- './jest-front.js'
+ './front/jest-setup.js'
],
+ maxWorkers: maxCpus,
testMatch: [
'**/front/**/*.spec.js',
'**/print/**/*.spec.js',
@@ -37,7 +40,7 @@ module.exports = {
],
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy',
- '\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '/fileMock.js',
+ '\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '/front/jest-mock.js',
},
testURL: 'http://localhost',
verbose: false,
diff --git a/loopback/common/methods/application/execute.js b/loopback/common/methods/application/execute.js
new file mode 100644
index 000000000..a468dcd70
--- /dev/null
+++ b/loopback/common/methods/application/execute.js
@@ -0,0 +1,28 @@
+const UserError = require('vn-loopback/util/user-error');
+
+module.exports = Self => {
+ Self.execute = async(ctx, type, query, params, options) => {
+ const userId = ctx.req.accessToken.userId;
+ const models = Self.app.models;
+ params = params ?? [];
+
+ const myOptions = {userId: ctx.req.accessToken.userId};
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const chain = query.split(' ')[1];
+
+ const [canExecute] = await models.ProcsPriv.rawSql(
+ 'SELECT account.user_hasRoutinePriv(?,?,?)',
+ [type, chain, userId],
+ myOptions);
+
+ if (!Object.values(canExecute)[0]) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED');
+
+ const argString = params.map(() => '?').join(',');
+
+ const response = await models.ProcsPriv.rawSql(query + `(${argString})`, params, myOptions);
+ if (!Array.isArray(response)) return;
+ return response[0];
+ };
+};
diff --git a/loopback/common/methods/application/executeFunc.js b/loopback/common/methods/application/executeFunc.js
new file mode 100644
index 000000000..a42fdae67
--- /dev/null
+++ b/loopback/common/methods/application/executeFunc.js
@@ -0,0 +1,41 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('executeFunc', {
+ description: 'Return result of function',
+ accessType: 'EXECUTE',
+ accepts: [
+ {
+ arg: 'routine',
+ type: 'string',
+ description: 'The routine name',
+ required: true,
+ http: {source: 'path'}
+ },
+ {
+ arg: 'schema',
+ type: 'string',
+ description: 'The routine schema',
+ required: true,
+ },
+ {
+ arg: 'params',
+ type: ['any'],
+ description: 'The params array',
+ },
+ ],
+ returns: {
+ type: 'any',
+ root: true
+ },
+ http: {
+ path: `/:routine/execute-func`,
+ verb: 'POST'
+ }
+ });
+
+ Self.executeFunc = async(ctx, routine, schema, params, options) => {
+ const query = `SELECT ${schema}.${routine}`;
+
+ const response = await Self.execute(ctx, 'FUNCTION', query, params, options);
+ return Object.values(response)[0];
+ };
+};
diff --git a/loopback/common/methods/application/executeProc.js b/loopback/common/methods/application/executeProc.js
new file mode 100644
index 000000000..a8825da0f
--- /dev/null
+++ b/loopback/common/methods/application/executeProc.js
@@ -0,0 +1,39 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('executeProc', {
+ description: 'Return result of procedure',
+ accessType: 'EXECUTE',
+ accepts: [
+ {
+ arg: 'routine',
+ type: 'string',
+ description: 'The routine name',
+ required: true,
+ http: {source: 'path'}
+ },
+ {
+ arg: 'schema',
+ type: 'string',
+ description: 'The routine schema',
+ required: true,
+ },
+ {
+ arg: 'params',
+ type: ['any'],
+ description: 'The params array',
+ },
+ ],
+ returns: {
+ type: 'any',
+ root: true
+ },
+ http: {
+ path: `/:routine/execute-proc`,
+ verb: 'POST'
+ }
+ });
+
+ Self.executeProc = async(ctx, routine, schema, params, options) => {
+ const query = `CALL ${schema}.${routine}`;
+ return Self.execute(ctx, 'PROCEDURE', query, params, options);
+ };
+};
diff --git a/loopback/common/methods/application/spec/execute.spec.js b/loopback/common/methods/application/spec/execute.spec.js
new file mode 100644
index 000000000..1a0a8ace9
--- /dev/null
+++ b/loopback/common/methods/application/spec/execute.spec.js
@@ -0,0 +1,161 @@
+const models = require('vn-loopback/server/server').models;
+
+describe('Application execute()/executeProc()/executeFunc()', () => {
+ const userWithoutPrivileges = 1;
+ const userWithPrivileges = 9;
+ const userWithInheritedPrivileges = 120;
+ let tx;
+
+ function getCtx(userId) {
+ return {
+ req: {
+ accessToken: {userId},
+ headers: {origin: 'http://localhost'}
+ }
+ };
+ }
+
+ beforeEach(async() => {
+ tx = await models.Application.beginTransaction({});
+ const options = {transaction: tx};
+
+ await models.Application.rawSql(`
+ CREATE OR REPLACE PROCEDURE vn.myProcedure(vMyParam INT)
+ BEGIN
+ SELECT vMyParam myParam, t.*
+ FROM ticket t
+ LIMIT 2;
+ END
+ `, null, options);
+
+ await models.Application.rawSql(`
+ CREATE OR REPLACE FUNCTION bs.myFunction(vMyParam INT) RETURNS int(11)
+ BEGIN
+ RETURN vMyParam;
+ END
+ `, null, options);
+
+ await models.Application.rawSql(`
+ GRANT EXECUTE ON PROCEDURE vn.myProcedure TO developer;
+ GRANT EXECUTE ON FUNCTION bs.myFunction TO developer;
+ `, null, options);
+ });
+
+ it('should throw error when execute procedure and not have privileges', async() => {
+ const ctx = getCtx(userWithoutPrivileges);
+
+ let error;
+ try {
+ const options = {transaction: tx};
+
+ await models.Application.execute(
+ ctx,
+ 'PROCEDURE',
+ 'CALL vn.myProcedure',
+ [1],
+ options
+ );
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error.message).toEqual(`You don't have enough privileges`);
+ });
+
+ it('should execute procedure and get data', async() => {
+ const ctx = getCtx(userWithPrivileges);
+ try {
+ const options = {transaction: tx};
+
+ const response = await models.Application.execute(
+ ctx,
+ 'PROCEDURE',
+ 'CALL vn.myProcedure',
+ [1],
+ options
+ );
+
+ expect(response.length).toEqual(2);
+ expect(response[0].myParam).toEqual(1);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ describe('Application executeProc()', () => {
+ it('should execute procedure and get data (executeProc)', async() => {
+ const ctx = getCtx(userWithPrivileges);
+ try {
+ const options = {transaction: tx};
+
+ const response = await models.Application.executeProc(
+ ctx,
+ 'myProcedure',
+ 'vn',
+ [1],
+ options
+ );
+
+ expect(response.length).toEqual(2);
+ expect(response[0].myParam).toEqual(1);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+ });
+
+ describe('Application executeFunc()', () => {
+ it('should execute function and get data', async() => {
+ const ctx = getCtx(userWithPrivileges);
+ try {
+ const options = {transaction: tx};
+
+ const response = await models.Application.executeFunc(
+ ctx,
+ 'myFunction',
+ 'bs',
+ [1],
+ options
+ );
+
+ expect(response).toEqual(1);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should execute function and get data with user with inherited privileges', async() => {
+ const ctx = getCtx(userWithInheritedPrivileges);
+ try {
+ const options = {transaction: tx};
+
+ const response = await models.Application.executeFunc(
+ ctx,
+ 'myFunction',
+ 'bs',
+ [1],
+ options
+ );
+
+ expect(response).toEqual(1);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+ });
+});
diff --git a/loopback/common/methods/schema/model-info.js b/loopback/common/methods/schema/model-info.js
index 6a4db033d..0648deb80 100644
--- a/loopback/common/methods/schema/model-info.js
+++ b/loopback/common/methods/schema/model-info.js
@@ -22,7 +22,7 @@ module.exports = Self => {
});
const modelsLocale = new Map();
- const modulesDir = path.resolve(`${__dirname}/../../../../modules`);
+ const modulesDir = path.resolve(`${process.cwd()}/modules`);
const modules = fs.readdirSync(modulesDir);
for (const mod of modules) {
diff --git a/loopback/common/mixins/loggable.js b/loopback/common/mixins/loggable.js
new file mode 100644
index 000000000..24243ba68
--- /dev/null
+++ b/loopback/common/mixins/loggable.js
@@ -0,0 +1,13 @@
+const LoopBackContext = require('loopback-context');
+async function handleObserve(ctx) {
+ const httpCtx = LoopBackContext.getCurrentContext();
+ ctx.options.userId = httpCtx?.active?.accessToken?.userId;
+}
+module.exports = function(Self) {
+ let Mixin = {
+ 'before save': handleObserve,
+ 'before delete': handleObserve,
+ };
+ for (const [listener, handler] of Object.entries(Mixin))
+ Self.observe(listener, handler);
+};
diff --git a/loopback/common/models/application.js b/loopback/common/models/application.js
index 5e767fdc1..ac8ae78f0 100644
--- a/loopback/common/models/application.js
+++ b/loopback/common/models/application.js
@@ -2,4 +2,7 @@
module.exports = function(Self) {
require('../methods/application/status')(Self);
require('../methods/application/post')(Self);
+ require('../methods/application/execute')(Self);
+ require('../methods/application/executeProc')(Self);
+ require('../methods/application/executeFunc')(Self);
};
diff --git a/loopback/common/models/application.json b/loopback/common/models/application.json
index bc72df315..f79001585 100644
--- a/loopback/common/models/application.json
+++ b/loopback/common/models/application.json
@@ -13,6 +13,6 @@
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
- }
+ }
]
}
diff --git a/loopback/common/models/loggable.js b/loopback/common/models/loggable.js
deleted file mode 100644
index 360c84566..000000000
--- a/loopback/common/models/loggable.js
+++ /dev/null
@@ -1,15 +0,0 @@
-const LoopBackContext = require('loopback-context');
-
-module.exports = function(Self) {
- Self.setup = function() {
- Self.super_.setup.call(this);
- };
-
- Self.observe('before save', async function(ctx) {
- ctx.options.httpCtx = LoopBackContext.getCurrentContext();
- });
-
- Self.observe('before delete', async function(ctx) {
- ctx.options.httpCtx = LoopBackContext.getCurrentContext();
- });
-};
diff --git a/loopback/common/models/loggable.json b/loopback/common/models/loggable.json
deleted file mode 100644
index 9101532a3..000000000
--- a/loopback/common/models/loggable.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "name": "Loggable",
- "base": "VnModel",
- "validateUpsert": true
-}
diff --git a/loopback/common/models/procs-priv.json b/loopback/common/models/procs-priv.json
new file mode 100644
index 000000000..25221d586
--- /dev/null
+++ b/loopback/common/models/procs-priv.json
@@ -0,0 +1,44 @@
+{
+ "name": "ProcsPriv",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "mysql.procs_priv"
+ }
+ },
+ "properties": {
+ "name": {
+ "id": 1,
+ "type": "string",
+ "mysql": {
+ "columnName": "Routine_name"
+ }
+ },
+ "schema": {
+ "id": 3,
+ "type": "string",
+ "mysql": {
+ "columnName": "Db"
+ }
+ },
+ "role": {
+ "type": "string",
+ "mysql": {
+ "columnName": "user"
+ }
+ },
+ "type": {
+ "id": 2,
+ "type": "string",
+ "mysql": {
+ "columnName": "Routine_type"
+ }
+ },
+ "host": {
+ "type": "string",
+ "mysql": {
+ "columnName": "Host"
+ }
+ }
+ }
+}
diff --git a/loopback/locale/en.json b/loopback/locale/en.json
index 645a874e8..31b954a32 100644
--- a/loopback/locale/en.json
+++ b/loopback/locale/en.json
@@ -1,193 +1,226 @@
{
- "State cannot be blank": "State cannot be blank",
- "Cannot be blank": "Cannot be blank",
- "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero",
- "The grade must be an integer greater than or equal to zero": "The grade must be an integer greater than or equal to zero",
- "Invalid email": "Invalid email",
- "Name cannot be blank": "Name cannot be blank",
- "Phone cannot be blank": "Phone cannot be blank",
- "Description should have maximum of 45 characters": "Description should have maximum of 45 characters",
- "Period cannot be blank": "Period cannot be blank",
- "Sample type cannot be blank": "Sample type cannot be blank",
- "That payment method requires an IBAN": "That payment method requires an IBAN",
- "That payment method requires a BIC": "That payment method requires a BIC",
- "The default consignee can not be unchecked": "The default consignee can not be unchecked",
- "Enter an integer different to zero": "Enter an integer different to zero",
- "Package cannot be blank": "Package cannot be blank",
- "The new quantity should be smaller than the old one": "The new quantity should be smaller than the old one",
- "The sales of this ticket can't be modified": "The sales of this ticket can't be modified",
- "Cannot check Equalization Tax in this NIF/CIF": "Cannot check Equalization Tax in this NIF/CIF",
- "You can't create an order for a frozen client": "You can't create an order for a frozen client",
- "This address doesn't exist": "This address doesn't exist",
- "Warehouse cannot be blank": "Warehouse cannot be blank",
- "Agency cannot be blank": "Agency cannot be blank",
- "The IBAN does not have the correct format": "The IBAN does not have the correct format",
- "You can't make changes on the basic data of an confirmed order or with rows": "You can't make changes on the basic data of an confirmed order or with rows",
- "You can't create a ticket for a inactive client": "You can't create a ticket for a inactive client",
- "Worker cannot be blank": "Worker cannot be blank",
- "You must delete the claim id %d first": "You must delete the claim id %d first",
- "You don't have enough privileges": "You don't have enough privileges",
- "Tag value cannot be blank": "Tag value cannot be blank",
- "A client with that Web User name already exists": "A client with that Web User name already exists",
- "The warehouse can't be repeated": "The warehouse can't be repeated",
- "Barcode must be unique": "Barcode must be unique",
- "You don't have enough privileges to do that": "You don't have enough privileges to do that",
- "You can't create a ticket for a frozen client": "You can't create a ticket for a frozen client",
- "can't be blank": "can't be blank",
- "Street cannot be empty": "Street cannot be empty",
- "City cannot be empty": "City cannot be empty",
- "EXTENSION_INVALID_FORMAT": "Invalid extension",
- "The secret can't be blank": "The secret can't be blank",
- "Invalid TIN": "Invalid Tax number",
- "This ticket can't be invoiced": "This ticket can't be invoiced",
- "The value should be a number": "The value should be a number",
- "The current ticket can't be modified": "The current ticket can't be modified",
- "Extension format is invalid": "Extension format is invalid",
- "NO_ZONE_FOR_THIS_PARAMETERS": "NO_ZONE_FOR_THIS_PARAMETERS",
- "This client can't be invoiced": "This client can't be invoiced",
- "The introduced hour already exists": "The introduced hour already exists",
- "Invalid parameters to create a new ticket": "Invalid parameters to create a new ticket",
- "Concept cannot be blank": "Concept cannot be blank",
- "Ticket id cannot be blank": "Ticket id cannot be blank",
- "Weekday cannot be blank": "Weekday cannot be blank",
- "This ticket can not be modified": "This ticket can not be modified",
- "You can't delete a confirmed order": "You can't delete a confirmed order",
- "Value has an invalid format": "Value has an invalid format",
- "The postcode doesn't exist. Please enter a correct one": "The postcode doesn't exist. Please enter a correct one",
- "Swift / BIC can't be empty": "Swift / BIC can't be empty",
- "Deleted sales from ticket": "I have deleted the following lines from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}",
- "Added sale to ticket": "I have added the following line to the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}",
- "Changed sale discount": "I have changed the following lines discounts from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
- "Created claim": "I have created the claim [{{claimId}}]({{{claimUrl}}}) for the following lines from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
- "Changed sale price": "I have changed the price of [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) from {{oldPrice}}€ ➔ *{{newPrice}}€* of the ticket [{{ticketId}}]({{{ticketUrl}}})",
- "Changed sale quantity": "I have changed the quantity of [{{itemId}} {{concept}}]({{{itemUrl}}}) from {{oldQuantity}} ➔ *{{newQuantity}}* of the ticket [{{ticketId}}]({{{ticketUrl}}})",
- "Changed sale reserved state": "I have changed the following lines reserved state from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
- "Bought units from buy request": "Bought {{quantity}} units of [{{itemId}} {{concept}}]({{{urlItem}}}) for the ticket id [{{ticketId}}]({{{url}}})",
- "MESSAGE_INSURANCE_CHANGE": "I have changed the insurence credit of client [{{clientName}} ({{clientId}})]({{{url}}}) to *{{credit}} €*",
- "Changed client paymethod": "I have changed the pay method for client [{{clientName}} ({{clientId}})]({{{url}}})",
- "Sent units from ticket": "I sent *{{quantity}}* units of [{{concept}} ({{itemId}})]({{{itemUrl}}}) to *\"{{nickname}}\"* coming from ticket id [{{ticketId}}]({{{ticketUrl}}})",
- "Change quantity": "{{concept}} change of {{oldQuantity}} to {{newQuantity}}",
- "Claim will be picked": "The product from the claim [({{claimId}})]({{{claimUrl}}}) from the client *{{clientName}}* will be picked",
- "Claim state has changed to incomplete": "The state of the claim [({{claimId}})]({{{claimUrl}}}) from client *{{clientName}}* has changed to *incomplete*",
- "Claim state has changed to canceled": "The state of the claim [({{claimId}})]({{{claimUrl}}}) from client *{{clientName}}* has changed to *canceled*",
- "Customs agent is required for a non UEE member": "Customs agent is required for a non UEE member",
- "Incoterms is required for a non UEE member": "Incoterms is required for a non UEE member",
- "Client checked as validated despite of duplication": "Client checked as validated despite of duplication from client id {{clientId}}",
- "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment",
- "NOT_ZONE_WITH_THIS_PARAMETERS": "There's no zone available for this day",
- "Created absence": "The worker {{author}} has added an absence of type '{{absenceType}}' to {{employee}} for day {{dated}}.",
- "Deleted absence": "The worker {{author}} has deleted an absence of type '{{absenceType}}' to {{employee}} for day {{dated}}.",
- "I have deleted the ticket id": "I have deleted the ticket id [{{id}}]({{{url}}})",
- "I have restored the ticket id": "I have restored the ticket id [{{id}}]({{{url}}})",
- "Changed this data from the ticket": "I have changed the data from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
- "The grade must be similar to the last one": "The grade must be similar to the last one",
- "agencyModeFk": "Agency",
- "clientFk": "Client",
- "zoneFk": "Zone",
- "warehouseFk": "Warehouse",
- "shipped": "Shipped",
- "landed": "Landed",
- "addressFk": "Address",
- "companyFk": "Company",
- "You need to fill sage information before you check verified data": "You need to fill sage information before you check verified data",
- "The social name cannot be empty": "The social name cannot be empty",
- "The nif cannot be empty": "The nif cannot be empty",
- "Amount cannot be zero": "Amount cannot be zero",
- "Company has to be official": "Company has to be official",
- "Unable to clone this travel": "Unable to clone this travel",
- "The observation type can't be repeated": "The observation type can't be repeated",
- "New ticket request has been created with price": "New ticket request has been created *'{{description}}'* for day *{{shipped}}*, with a quantity of *{{quantity}}* and a price of *{{price}} €*",
- "New ticket request has been created": "New ticket request has been created *'{{description}}'* for day *{{shipped}}*, with a quantity of *{{quantity}}*",
- "There's a new urgent ticket": "There's a new urgent ticket: [{{title}}](https://cau.verdnatura.es/WorkOrder.do?woMode=viewWO&woID={{issueId}})",
- "Swift / BIC cannot be empty": "Swift / BIC cannot be empty",
- "Role name must be written in camelCase": "Role name must be written in camelCase",
- "Client assignment has changed": "I did change the salesperson ~*\"<{{previousWorkerName}}>\"*~ by *\"<{{currentWorkerName}}>\"* from the client [{{clientName}} ({{clientId}})]({{{url}}})",
- "None": "None",
- "error densidad = 0": "error densidad = 0",
- "This document already exists on this ticket": "This document already exists on this ticket",
- "serial non editable": "This serial doesn't allow to set a reference",
- "nickname": "nickname",
- "State": "State",
- "regular": "regular",
- "reserved": "reserved",
- "Global invoicing failed": "[Global invoicing] Wasn't able to invoice some of the clients",
- "A ticket with a negative base can't be invoiced": "A ticket with a negative base can't be invoiced",
- "This client is not invoiceable": "This client is not invoiceable",
- "INACTIVE_PROVIDER": "Inactive provider",
- "reference duplicated": "reference duplicated",
- "The PDF document does not exist": "The PDF document does not exists. Try regenerating it from 'Regenerate invoice PDF' option",
- "This item is not available": "This item is not available",
- "Deny buy request": "Purchase request for ticket id [{{ticketId}}]({{{url}}}) has been rejected. Reason: {{observation}}",
- "The type of business must be filled in basic data": "The type of business must be filled in basic data",
- "The worker has hours recorded that day": "The worker has hours recorded that day",
- "isWithoutNegatives": "isWithoutNegatives",
- "routeFk": "routeFk",
- "Not enough privileges to edit a client with verified data": "Not enough privileges to edit a client with verified data",
- "Can't change the password of another worker": "Can't change the password of another worker",
- "No hay un contrato en vigor": "There is no existing contract",
- "No está permitido trabajar": "Not allowed to work",
- "Dirección incorrecta": "Wrong direction",
- "No se permite fichar a futuro": "It is not allowed to sign in the future",
- "Descanso diario 12h.": "Daily rest 12h.",
- "Fichadas impares": "Odd signs",
- "Descanso diario 9h.": "Daily rest 9h.",
- "Descanso semanal 36h. / 72h.": "Weekly rest 36h. / 72h.",
- "Verify email": "Verify email",
- "Click on the following link to verify this email. If you haven't requested this email, just ignore it": "Click on the following link to verify this email. If you haven't requested this email, just ignore it",
- "Password does not meet requirements": "Password does not meet requirements",
- "You don't have privileges to change the zone": "You don't have privileges to change the zone or for these parameters there are more than one shipping options, talk to agencies",
- "Not enough privileges to edit a client": "Not enough privileges to edit a client",
- "Claim pickup order sent": "Claim pickup order sent [{{claimId}}]({{{claimUrl}}}) to client *{{clientName}}*",
- "You don't have grant privilege": "You don't have grant privilege",
- "You don't own the role and you can't assign it to another user": "You don't own the role and you can't assign it to another user",
- "Email verify": "Email verify",
- "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) merged with [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})",
- "App locked": "App locked by user {{userId}}",
- "The sales of the receiver ticket can't be modified": "The sales of the receiver ticket can't be modified",
- "Receipt's bank was not found": "Receipt's bank was not found",
- "This receipt was not compensated": "This receipt was not compensated",
- "Client's email was not found": "Client's email was not found",
- "Tickets with associated refunds": "Tickets with associated refunds can't be deleted. This ticket is associated with refund Nº %d",
- "It is not possible to modify tracked sales": "It is not possible to modify tracked sales",
- "It is not possible to modify sales that their articles are from Floramondo": "It is not possible to modify sales that their articles are from Floramondo",
- "It is not possible to modify cloned sales": "It is not possible to modify cloned sales",
- "Warehouse inventory not set": "Almacén inventario no está establecido",
- "Component cost not set": "Componente coste no está estabecido",
- "Description cannot be blank": "Description cannot be blank",
- "company": "Company",
- "country": "Country",
- "clientId": "Id client",
- "clientSocialName": "Client",
- "amount": "Amount",
- "taxableBase": "Taxable base",
- "ticketFk": "Id ticket",
- "isActive": "Active",
- "hasToInvoice": "Invoice",
- "isTaxDataChecked": "Data checked",
- "comercialId": "Id Comercial",
- "comercialName": "Comercial",
- "Added observation": "Added observation",
- "Comment added to client": "Comment added to client",
- "This ticket is already a refund": "This ticket is already a refund",
- "A claim with that sale already exists": "A claim with that sale already exists",
- "Pass expired": "The password has expired, change it from Salix",
- "Can't transfer claimed sales": "Can't transfer claimed sales",
- "Invalid quantity": "Invalid quantity",
- "Failed to upload delivery note": "Error to upload delivery note {{id}}",
- "Mail not sent": "There has been an error sending the invoice to the client [{{clientId}}]({{{clientUrl}}}), please check the email address",
- "The renew period has not been exceeded": "The renew period has not been exceeded",
- "You can not use the same password": "You can not use the same password",
- "Valid priorities": "Valid priorities: %d",
- "Negative basis of tickets": "Negative basis of tickets: {{ticketsIds}}",
- "This ticket cannot be left empty.": "This ticket cannot be left empty. %s",
- "Social name should be uppercase": "Social name should be uppercase",
- "Street should be uppercase": "Street should be uppercase",
- "You don't have enough privileges.": "You don't have enough privileges.",
- "This ticket is locked.": "This ticket is locked.",
- "This ticket is not editable.": "This ticket is not editable.",
- "The ticket doesn't exist.": "The ticket doesn't exist.",
- "The sales do not exists": "The sales do not exists",
- "Ticket without Route": "Ticket without route",
- "Booking completed": "Booking complete",
- "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation"
+ "State cannot be blank": "State cannot be blank",
+ "Cannot be blank": "Cannot be blank",
+ "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero",
+ "The grade must be an integer greater than or equal to zero": "The grade must be an integer greater than or equal to zero",
+ "Invalid email": "Invalid email",
+ "Name cannot be blank": "Name cannot be blank",
+ "Phone cannot be blank": "Phone cannot be blank",
+ "Description should have maximum of 45 characters": "Description should have maximum of 45 characters",
+ "Period cannot be blank": "Period cannot be blank",
+ "Sample type cannot be blank": "Sample type cannot be blank",
+ "That payment method requires an IBAN": "That payment method requires an IBAN",
+ "That payment method requires a BIC": "That payment method requires a BIC",
+ "The default consignee can not be unchecked": "The default consignee can not be unchecked",
+ "Enter an integer different to zero": "Enter an integer different to zero",
+ "Package cannot be blank": "Package cannot be blank",
+ "The price of the item changed": "The price of the item changed",
+ "The sales of this ticket can't be modified": "The sales of this ticket can't be modified",
+ "Cannot check Equalization Tax in this NIF/CIF": "Cannot check Equalization Tax in this NIF/CIF",
+ "You can't create an order for a frozen client": "You can't create an order for a frozen client",
+ "This address doesn't exist": "This address doesn't exist",
+ "Warehouse cannot be blank": "Warehouse cannot be blank",
+ "Agency cannot be blank": "Agency cannot be blank",
+ "The IBAN does not have the correct format": "The IBAN does not have the correct format",
+ "You can't make changes on the basic data of an confirmed order or with rows": "You can't make changes on the basic data of an confirmed order or with rows",
+ "You can't create a ticket for an inactive client": "You can't create a ticket for an inactive client",
+ "Worker cannot be blank": "Worker cannot be blank",
+ "You must delete the claim id %d first": "You must delete the claim id %d first",
+ "You don't have enough privileges": "You don't have enough privileges",
+ "Tag value cannot be blank": "Tag value cannot be blank",
+ "A client with that Web User name already exists": "A client with that Web User name already exists",
+ "The warehouse can't be repeated": "The warehouse can't be repeated",
+ "Barcode must be unique": "Barcode must be unique",
+ "You don't have enough privileges to do that": "You don't have enough privileges to do that",
+ "You can't create a ticket for a frozen client": "You can't create a ticket for a frozen client",
+ "can't be blank": "can't be blank",
+ "Street cannot be empty": "Street cannot be empty",
+ "City cannot be empty": "City cannot be empty",
+ "EXTENSION_INVALID_FORMAT": "Invalid extension",
+ "The secret can't be blank": "The secret can't be blank",
+ "Invalid TIN": "Invalid Tax number",
+ "This ticket can't be invoiced": "This ticket can't be invoiced",
+ "The value should be a number": "The value should be a number",
+ "The current ticket can't be modified": "The current ticket can't be modified",
+ "Extension format is invalid": "Extension format is invalid",
+ "NO_ZONE_FOR_THIS_PARAMETERS": "NO_ZONE_FOR_THIS_PARAMETERS",
+ "This client can't be invoiced": "This client can't be invoiced",
+ "You must provide the correction information to generate a corrective invoice": "You must provide the correction information to generate a corrective invoice",
+ "The introduced hour already exists": "The introduced hour already exists",
+ "Invalid parameters to create a new ticket": "Invalid parameters to create a new ticket",
+ "Concept cannot be blank": "Concept cannot be blank",
+ "Ticket id cannot be blank": "Ticket id cannot be blank",
+ "Weekday cannot be blank": "Weekday cannot be blank",
+ "This ticket can not be modified": "This ticket can not be modified",
+ "You can't delete a confirmed order": "You can't delete a confirmed order",
+ "Value has an invalid format": "Value has an invalid format",
+ "The postcode doesn't exist. Please enter a correct one": "The postcode doesn't exist. Please enter a correct one",
+ "Swift / BIC can't be empty": "Swift / BIC can't be empty",
+ "Deleted sales from ticket": "I have deleted the following lines from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}",
+ "Added sale to ticket": "I have added the following line to the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}",
+ "Changed sale discount": "I have changed the following lines discounts from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
+ "Created claim": "I have created the claim [{{claimId}}]({{{claimUrl}}}) for the following lines from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
+ "Changed sale price": "I have changed the price of [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) from {{oldPrice}}€ ➔ *{{newPrice}}€* of the ticket [{{ticketId}}]({{{ticketUrl}}})",
+ "Changed sale quantity": "I have changed the quantity of [{{itemId}} {{concept}}]({{{itemUrl}}}) from {{oldQuantity}} ➔ *{{newQuantity}}* of the ticket [{{ticketId}}]({{{ticketUrl}}})",
+ "Changed sale reserved state": "I have changed the following lines reserved state from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
+ "Bought units from buy request": "Bought {{quantity}} units of [{{itemId}} {{concept}}]({{{urlItem}}}) for the ticket id [{{ticketId}}]({{{url}}})",
+ "MESSAGE_INSURANCE_CHANGE": "I have changed the insurence credit of client [{{clientName}} ({{clientId}})]({{{url}}}) to *{{credit}} €*",
+ "Changed client paymethod": "I have changed the pay method for client [{{clientName}} ({{clientId}})]({{{url}}})",
+ "Sent units from ticket": "I sent *{{quantity}}* units of [{{concept}} ({{itemId}})]({{{itemUrl}}}) to *\"{{nickname}}\"* coming from ticket id [{{ticketId}}]({{{ticketUrl}}})",
+ "Change quantity": "{{concept}} change of {{oldQuantity}} to {{newQuantity}}",
+ "Claim will be picked": "The product from the claim [({{claimId}})]({{{claimUrl}}}) from the client *{{clientName}}* will be picked",
+ "Claim state has changed to": "The state of the claim [({{claimId}})]({{{claimUrl}}}) from client *{{clientName}}* has changed to *{{newState}}*",
+ "Customs agent is required for a non UEE member": "Customs agent is required for a non UEE member",
+ "Incoterms is required for a non UEE member": "Incoterms is required for a non UEE member",
+ "Client checked as validated despite of duplication": "Client checked as validated despite of duplication from client id {{clientId}}",
+ "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment",
+ "NOT_ZONE_WITH_THIS_PARAMETERS": "There's no zone available for this day",
+ "Created absence": "The worker {{author}} has added an absence of type '{{absenceType}}' to {{employee}} for day {{dated}}.",
+ "Deleted absence": "The worker {{author}} has deleted an absence of type '{{absenceType}}' to {{employee}} for day {{dated}}.",
+ "I have deleted the ticket id": "I have deleted the ticket id [{{id}}]({{{url}}})",
+ "I have restored the ticket id": "I have restored the ticket id [{{id}}]({{{url}}})",
+ "Changed this data from the ticket": "I have changed the data from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
+ "The grade must be similar to the last one": "The grade must be similar to the last one",
+ "agencyModeFk": "Agency",
+ "clientFk": "Client",
+ "zoneFk": "Zone",
+ "warehouseFk": "Warehouse",
+ "shipped": "Shipped",
+ "landed": "Landed",
+ "addressFk": "Address",
+ "companyFk": "Company",
+ "You need to fill sage information before you check verified data": "You need to fill sage information before you check verified data",
+ "The social name cannot be empty": "The social name cannot be empty",
+ "The nif cannot be empty": "The nif cannot be empty",
+ "Amount cannot be zero": "Amount cannot be zero",
+ "Company has to be official": "Company has to be official",
+ "Unable to clone this travel": "Unable to clone this travel",
+ "The observation type can't be repeated": "The observation type can't be repeated",
+ "New ticket request has been created with price": "New ticket request has been created *'{{description}}'* for day *{{shipped}}*, with a quantity of *{{quantity}}* and a price of *{{price}} €*",
+ "New ticket request has been created": "New ticket request has been created *'{{description}}'* for day *{{shipped}}*, with a quantity of *{{quantity}}*",
+ "There's a new urgent ticket": "There's a new urgent ticket: [{{title}}](https://cau.verdnatura.es/WorkOrder.do?woMode=viewWO&woID={{issueId}})",
+ "Swift / BIC cannot be empty": "Swift / BIC cannot be empty",
+ "Role name must be written in camelCase": "Role name must be written in camelCase",
+ "Client assignment has changed": "I did change the salesperson ~*\"<{{previousWorkerName}}>\"*~ by *\"<{{currentWorkerName}}>\"* from the client [{{clientName}} ({{clientId}})]({{{url}}})",
+ "None": "None",
+ "error densidad = 0": "error densidad = 0",
+ "This document already exists on this ticket": "This document already exists on this ticket",
+ "serial non editable": "This serial doesn't allow to set a reference",
+ "nickname": "nickname",
+ "State": "State",
+ "regular": "regular",
+ "reserved": "reserved",
+ "Global invoicing failed": "[Global invoicing] Wasn't able to invoice some of the clients",
+ "A ticket with a negative base can't be invoiced": "A ticket with a negative base can't be invoiced",
+ "This client is not invoiceable": "This client is not invoiceable",
+ "INACTIVE_PROVIDER": "Inactive provider",
+ "reference duplicated": "reference duplicated",
+ "The PDF document does not exist": "The PDF document does not exists. Try regenerating it from 'Regenerate invoice PDF' option",
+ "This item is not available": "This item is not available",
+ "Deny buy request": "Purchase request for ticket id [{{ticketId}}]({{{url}}}) has been rejected. Reason: {{observation}}",
+ "The type of business must be filled in basic data": "The type of business must be filled in basic data",
+ "The worker has hours recorded that day": "The worker has hours recorded that day",
+ "isWithoutNegatives": "isWithoutNegatives",
+ "routeFk": "routeFk",
+ "Not enough privileges to edit a client with verified data": "Not enough privileges to edit a client with verified data",
+ "Can't change the password of another worker": "Can't change the password of another worker",
+ "No hay un contrato en vigor": "There is no existing contract",
+ "No está permitido trabajar": "Not allowed to work",
+ "Dirección incorrecta": "Wrong direction",
+ "No se permite fichar a futuro": "It is not allowed to sign in the future",
+ "Descanso diario 12h.": "Daily rest 12h.",
+ "Fichadas impares": "Odd signs",
+ "Descanso diario 9h.": "Daily rest 9h.",
+ "Descanso semanal 36h. / 72h.": "Weekly rest 36h. / 72h.",
+ "Verify email": "Verify email",
+ "Click on the following link to verify this email. If you haven't requested this email, just ignore it": "Click on the following link to verify this email. If you haven't requested this email, just ignore it",
+ "Password does not meet requirements": "Password does not meet requirements",
+ "You don't have privileges to change the zone": "You don't have privileges to change the zone or for these parameters there are more than one shipping options, talk to agencies",
+ "Not enough privileges to edit a client": "Not enough privileges to edit a client",
+ "Claim pickup order sent": "Claim pickup order sent [{{claimId}}]({{{claimUrl}}}) to client *{{clientName}}*",
+ "You don't have grant privilege": "You don't have grant privilege",
+ "You don't own the role and you can't assign it to another user": "You don't own the role and you can't assign it to another user",
+ "Email verify": "Email verify",
+ "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) merged with [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})",
+ "App locked": "App locked by user {{userId}}",
+ "The sales of the receiver ticket can't be modified": "The sales of the receiver ticket can't be modified",
+ "Receipt's bank was not found": "Receipt's bank was not found",
+ "This receipt was not compensated": "This receipt was not compensated",
+ "Client's email was not found": "Client's email was not found",
+ "Tickets with associated refunds": "Tickets with associated refunds can't be deleted. This ticket is associated with refund Nº %d",
+ "It is not possible to modify tracked sales": "It is not possible to modify tracked sales",
+ "It is not possible to modify sales that their articles are from Floramondo": "It is not possible to modify sales that their articles are from Floramondo",
+ "It is not possible to modify cloned sales": "It is not possible to modify cloned sales",
+ "Warehouse inventory not set": "Almacén inventario no está establecido",
+ "Component cost not set": "Componente coste no está estabecido",
+ "Description cannot be blank": "Description cannot be blank",
+ "company": "Company",
+ "country": "Country",
+ "clientId": "Id client",
+ "clientSocialName": "Client",
+ "amount": "Amount",
+ "taxableBase": "Taxable base",
+ "ticketFk": "Id ticket",
+ "isActive": "Active",
+ "hasToInvoice": "Invoice",
+ "isTaxDataChecked": "Data checked",
+ "comercialId": "Id Comercial",
+ "comercialName": "Comercial",
+ "Added observation": "Added observation",
+ "Comment added to client": "Comment added to client",
+ "This ticket is already a refund": "This ticket is already a refund",
+ "A claim with that sale already exists": "A claim with that sale already exists",
+ "Pass expired": "The password has expired, change it from Salix",
+ "Can't transfer claimed sales": "Can't transfer claimed sales",
+ "Invalid quantity": "Invalid quantity",
+ "Failed to upload delivery note": "Error to upload delivery note {{id}}",
+ "Mail not sent": "There has been an error sending the invoice to the client [{{clientId}}]({{{clientUrl}}}), please check the email address",
+ "The renew period has not been exceeded": "The renew period has not been exceeded",
+ "You can not use the same password": "You can not use the same password",
+ "Valid priorities": "Valid priorities: %d",
+ "hasAnyNegativeBase": "Negative basis of tickets: {{ticketsIds}}",
+ "hasAnyPositiveBase": "Positive basis of tickets: {{ticketsIds}}",
+ "This ticket cannot be left empty.": "This ticket cannot be left empty. %s",
+ "Social name should be uppercase": "Social name should be uppercase",
+ "Street should be uppercase": "Street should be uppercase",
+ "You don't have enough privileges.": "You don't have enough privileges.",
+ "This ticket is locked": "This ticket is locked",
+ "This ticket is not editable.": "This ticket is not editable.",
+ "The ticket doesn't exist.": "The ticket doesn't exist.",
+ "The sales do not exists": "The sales do not exists",
+ "Ticket without Route": "Ticket without route",
+ "Select a different client": "Select a different client",
+ "Fill all the fields": "Fill all the fields",
+ "Error while generating PDF": "Error while generating PDF",
+ "Can't invoice to future": "Can't invoice to future",
+ "This ticket is already invoiced": "This ticket is already invoiced",
+ "Negative basis of tickets: 23": "Negative basis of tickets: 23",
+ "Booking completed": "Booking complete",
+ "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation",
+ "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets",
+ "Bank entity must be specified": "Bank entity must be specified",
+ "Try again": "Try again",
+ "keepPrice": "keepPrice",
+ "Cannot past travels with entries": "Cannot past travels with entries",
+ "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}",
+ "Incorrect pin": "Incorrect pin.",
+ "The notification subscription of this worker cant be modified": "The notification subscription of this worker cant be modified",
+ "Name should be uppercase": "Name should be uppercase",
+ "You cannot update these fields": "You cannot update these fields",
+ "CountryFK cannot be empty": "Country cannot be empty",
+ "You are not allowed to modify the alias": "You are not allowed to modify the alias",
+ "You already have the mailAlias": "You already have the mailAlias",
+ "This machine is already in use.": "This machine is already in use.",
+ "the plate does not exist": "The plate {{plate}} does not exist",
+ "We do not have availability for the selected item": "We do not have availability for the selected item",
+ "You are already using a machine": "You are already using a machine",
+ "this state does not exist": "This state does not exist",
+ "The line could not be marked": "The line could not be marked",
+ "The sale cannot be tracked": "The sale cannot be tracked",
+ "Shelving not valid": "Shelving not valid",
+ "printerNotExists": "The printer does not exist",
+ "There are not picking tickets": "There are not picking tickets",
+ "ticketCommercial": "The ticket {{ ticket }} for the salesperson {{ salesMan }} is in preparation. (automatically generated message)",
+ "This password can only be changed by the user themselves": "This password can only be changed by the user themselves",
+ "They're not your subordinate": "They're not your subordinate"
}
diff --git a/loopback/locale/es.json b/loopback/locale/es.json
index 6e478c000..5b13ef7a0 100644
--- a/loopback/locale/es.json
+++ b/loopback/locale/es.json
@@ -1,324 +1,353 @@
{
- "Phone format is invalid": "El formato del teléfono no es correcto",
- "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito",
- "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia",
- "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado",
- "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado",
- "Can't be blank": "No puede estar en blanco",
- "Invalid TIN": "NIF/CIF invalido",
- "TIN must be unique": "El NIF/CIF debe ser único",
- "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web",
- "Is invalid": "Is invalid",
- "Quantity cannot be zero": "La cantidad no puede ser cero",
- "Enter an integer different to zero": "Introduce un entero distinto de cero",
- "Package cannot be blank": "El embalaje no puede estar en blanco",
- "The company name must be unique": "La razón social debe ser única",
- "Invalid email": "Correo electrónico inválido",
- "The IBAN does not have the correct format": "El IBAN no tiene el formato correcto",
- "That payment method requires an IBAN": "El método de pago seleccionado requiere un IBAN",
- "That payment method requires a BIC": "El método de pago seleccionado requiere un BIC",
- "State cannot be blank": "El estado no puede estar en blanco",
- "Worker cannot be blank": "El trabajador no puede estar en blanco",
- "Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado",
- "can't be blank": "El campo no puede estar vacío",
- "Observation type must be unique": "El tipo de observación no puede repetirse",
- "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero",
- "The grade must be similar to the last one": "El grade debe ser similar al último",
- "Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente",
- "Name cannot be blank": "El nombre no puede estar en blanco",
- "Phone cannot be blank": "El teléfono no puede estar en blanco",
- "Period cannot be blank": "El periodo no puede estar en blanco",
- "Choose a company": "Selecciona una empresa",
- "Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto",
- "Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres",
- "Cannot be blank": "El campo no puede estar en blanco",
- "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero",
- "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco",
- "Description cannot be blank": "Se debe rellenar el campo de texto",
- "The new quantity should be smaller than the old one": "La nueva cantidad debe de ser menor que la anterior",
- "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%",
- "The value should be a number": "El valor debe ser un numero",
- "This order is not editable": "Esta orden no se puede modificar",
- "You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado",
- "You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda",
- "is not a valid date": "No es una fecha valida",
- "Barcode must be unique": "El código de barras debe ser único",
- "The warehouse can't be repeated": "El almacén no puede repetirse",
- "The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item",
- "The observation type can't be repeated": "El tipo de observación no puede repetirse",
- "A claim with that sale already exists": "Ya existe una reclamación para esta línea",
- "You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo",
- "Warehouse cannot be blank": "El almacén no puede quedar en blanco",
- "Agency cannot be blank": "La agencia no puede quedar en blanco",
- "Not enough privileges to edit a client with verified data": "No tienes permisos para hacer cambios en un cliente con datos comprobados",
- "This address doesn't exist": "Este consignatario no existe",
- "You must delete the claim id %d first": "Antes debes borrar la reclamación %d",
- "You don't have enough privileges": "No tienes suficientes permisos",
- "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF",
- "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos basicos de una orden con artículos",
- "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no esta permitido el uso de la letra ñ",
- "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado",
- "You can't create a ticket for a inactive client": "No puedes crear un ticket para un cliente inactivo",
- "Tag value cannot be blank": "El valor del tag no puede quedar en blanco",
- "ORDER_EMPTY": "Cesta vacía",
- "You don't have enough privileges to do that": "No tienes permisos para cambiar esto",
- "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT",
- "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido",
- "Street cannot be empty": "Dirección no puede estar en blanco",
- "City cannot be empty": "Cuidad no puede estar en blanco",
- "Code cannot be blank": "Código no puede estar en blanco",
- "You cannot remove this department": "No puedes eliminar este departamento",
- "The extension must be unique": "La extensión debe ser unica",
- "The secret can't be blank": "La contraseña no puede estar en blanco",
- "We weren't able to send this SMS": "No hemos podido enviar el SMS",
- "This client can't be invoiced": "Este cliente no puede ser facturado",
- "This ticket can't be invoiced": "Este ticket no puede ser facturado",
- "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado",
- "This ticket can not be modified": "Este ticket no puede ser modificado",
- "The introduced hour already exists": "Esta hora ya ha sido introducida",
- "INFINITE_LOOP": "Existe una dependencia entre dos Jefes",
- "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas",
- "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros",
- "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado",
- "The current ticket can't be modified": "El ticket actual no puede ser modificado",
- "The current claim can't be modified": "La reclamación actual no puede ser modificada",
- "The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas",
- "The sales do not exists": "La(s) línea(s) seleccionada(s) no existe(n)",
- "Please select at least one sale": "Por favor selecciona al menos una linea",
- "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket",
- "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada",
- "This item doesn't exists": "El artículo no existe",
- "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada",
- "Extension format is invalid": "El formato de la extensión es inválido",
- "Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket",
- "This item is not available": "Este artículo no está disponible",
- "This postcode already exists": "Este código postal ya existe",
- "Concept cannot be blank": "El concepto no puede quedar en blanco",
- "File doesn't exists": "El archivo no existe",
- "You don't have privileges to change the zone": "No tienes permisos para cambiar la zona o para esos parámetros hay más de una opción de envío, hable con las agencias",
- "This ticket is already on weekly tickets": "Este ticket ya está en tickets programados",
- "Ticket id cannot be blank": "El id de ticket no puede quedar en blanco",
- "Weekday cannot be blank": "El día de la semana no puede quedar en blanco",
- "You can't delete a confirmed order": "No puedes borrar un pedido confirmado",
- "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto",
- "Invalid quantity": "Cantidad invalida",
- "This postal code is not valid": "This postal code is not valid",
- "is invalid": "is invalid",
- "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto",
- "The department name can't be repeated": "El nombre del departamento no puede repetirse",
- "This phone already exists": "Este teléfono ya existe",
- "You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos",
- "You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado",
- "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada",
- "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero",
- "You should specify a date": "Debes especificar una fecha",
- "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fín",
- "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fín",
- "You should mark at least one week day": "Debes marcar al menos un día de la semana",
- "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío",
- "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios",
- "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios",
- "Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}",
- "Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}",
- "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
- "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
- "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})",
- "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})",
- "State": "Estado",
- "regular": "normal",
- "reserved": "reservado",
- "Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
- "Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})",
- "Deny buy request": "Se ha rechazado la petición de compra para el ticket id [{{ticketId}}]({{{url}}}). Motivo: {{observation}}",
- "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*",
- "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})",
- "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})",
- "Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}",
- "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*",
- "Claim state has changed to incomplete": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *incompleta*",
- "Claim state has changed to canceled": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *anulado*",
- "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}",
- "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto",
- "Distance must be lesser than 1000": "La distancia debe ser inferior a 1000",
- "This ticket is deleted": "Este ticket está eliminado",
- "Unable to clone this travel": "No ha sido posible clonar este travel",
- "This thermograph id already exists": "La id del termógrafo ya existe",
- "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante",
- "ORDER_ALREADY_CONFIRMED": "ORDER_ALREADY_CONFIRMED",
- "Invalid password": "Invalid password",
- "Password does not meet requirements": "La contraseña no cumple los requisitos",
- "Role already assigned": "Role already assigned",
- "Invalid role name": "Invalid role name",
- "Role name must be written in camelCase": "Role name must be written in camelCase",
- "Email already exists": "Email already exists",
- "User already exists": "User already exists",
- "Absence change notification on the labour calendar": "Notificacion de cambio de ausencia en el calendario laboral",
- "Record of hours week": "Registro de horas semana {{week}} año {{year}} ",
- "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.",
- "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.",
- "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})",
- "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})",
- "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación",
- "Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
- "agencyModeFk": "Agencia",
- "clientFk": "Cliente",
- "zoneFk": "Zona",
- "warehouseFk": "Almacén",
- "shipped": "F. envío",
- "landed": "F. entrega",
- "addressFk": "Consignatario",
- "companyFk": "Empresa",
- "The social name cannot be empty": "La razón social no puede quedar en blanco",
- "The nif cannot be empty": "El NIF no puede quedar en blanco",
- "You need to fill sage information before you check verified data": "Debes rellenar la información de sage antes de marcar datos comprobados",
- "ASSIGN_ZONE_FIRST": "Asigna una zona primero",
- "Amount cannot be zero": "El importe no puede ser cero",
- "Company has to be official": "Empresa inválida",
- "You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria",
- "Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas",
- "The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta",
- "New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*",
- "New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*",
- "Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío",
- "This BIC already exist.": "Este BIC ya existe.",
- "That item doesn't exists": "Ese artículo no existe",
- "There's a new urgent ticket:": "Hay un nuevo ticket urgente:",
- "Invalid account": "Cuenta inválida",
- "Compensation account is empty": "La cuenta para compensar está vacia",
- "This genus already exist": "Este genus ya existe",
- "This specie already exist": "Esta especie ya existe",
- "Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})",
- "None": "Ninguno",
- "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada",
- "Cannot add more than one '1/2 day vacation'": "No puedes añadir más de un 'Vacaciones 1/2 dia'",
- "This document already exists on this ticket": "Este documento ya existe en el ticket",
- "Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables",
- "You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes",
- "nickname": "nickname",
- "INACTIVE_PROVIDER": "Proveedor inactivo",
- "This client is not invoiceable": "Este cliente no es facturable",
- "serial non editable": "Esta serie no permite asignar la referencia",
- "Max shipped required": "La fecha límite es requerida",
- "Can't invoice to future": "No se puede facturar a futuro",
- "Can't invoice to past": "No se puede facturar a pasado",
- "This ticket is already invoiced": "Este ticket ya está facturado",
- "A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero",
- "A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa",
- "Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes",
- "Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes",
- "Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio",
- "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito",
- "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas",
- "Amounts do not match": "Las cantidades no coinciden",
- "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'",
- "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos",
- "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días",
- "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día",
- "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día",
- "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado",
- "The account size must be exactly 10 characters": "El tamaño de la cuenta debe ser exactamente de 10 caracteres",
- "Can't transfer claimed sales": "No puedes transferir lineas reclamadas",
- "You don't have privileges to create refund": "No tienes permisos para crear un abono",
- "The item is required": "El artículo es requerido",
- "The agency is already assigned to another autonomous": "La agencia ya está asignada a otro autónomo",
- "date in the future": "Fecha en el futuro",
- "reference duplicated": "Referencia duplicada",
- "This ticket is already a refund": "Este ticket ya es un abono",
- "isWithoutNegatives": "isWithoutNegatives",
- "routeFk": "routeFk",
- "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador",
- "No hay un contrato en vigor": "No hay un contrato en vigor",
- "No se permite fichar a futuro": "No se permite fichar a futuro",
- "No está permitido trabajar": "No está permitido trabajar",
- "Fichadas impares": "Fichadas impares",
- "Descanso diario 12h.": "Descanso diario 12h.",
- "Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.",
- "Dirección incorrecta": "Dirección incorrecta",
- "Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador",
- "Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador",
- "Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente",
- "This route does not exists": "Esta ruta no existe",
- "Claim pickup order sent": "Reclamación Orden de recogida enviada [{{claimId}}]({{{claimUrl}}}) al cliente *{{clientName}}*",
- "You don't have grant privilege": "No tienes privilegios para dar privilegios",
- "You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario",
- "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) fusionado con [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})",
- "Already has this status": "Ya tiene este estado",
- "There aren't records for this week": "No existen registros para esta semana",
- "Empty data source": "Origen de datos vacio",
- "App locked": "Aplicación bloqueada por el usuario {{userId}}",
- "Email verify": "Correo de verificación",
- "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment",
- "Receipt's bank was not found": "No se encontró el banco del recibo",
- "This receipt was not compensated": "Este recibo no ha sido compensado",
- "Client's email was not found": "No se encontró el email del cliente",
- "Negative basis": "Base negativa",
- "This worker code already exists": "Este codigo de trabajador ya existe",
- "This personal mail already exists": "Este correo personal ya existe",
- "This worker already exists": "Este trabajador ya existe",
- "App name does not exist": "El nombre de aplicación no es válido",
- "Try again": "Vuelve a intentarlo",
- "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9",
- "Failed to upload delivery note": "Error al subir albarán {{id}}",
- "The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe",
- "It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar",
- "It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo",
- "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas",
- "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.",
- "There is no assigned email for this client": "No hay correo asignado para este cliente",
- "Exists an invoice with a future date": "Existe una factura con fecha posterior",
- "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite",
- "Warehouse inventory not set": "El almacén inventario no está establecido",
- "This locker has already been assigned": "Esta taquilla ya ha sido asignada",
- "Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº %d",
- "Not exist this branch": "La rama no existe",
- "This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado",
- "Collection does not exist": "La colección no existe",
- "Cannot obtain exclusive lock": "No se puede obtener un bloqueo exclusivo",
- "Insert a date range": "Inserte un rango de fechas",
- "Added observation": "{{user}} añadió esta observacion: {{text}}",
- "Comment added to client": "Observación añadida al cliente {{clientFk}}",
- "Invalid auth code": "Código de verificación incorrecto",
- "Invalid or expired verification code": "Código de verificación incorrecto o expirado",
- "Cannot create a new claimBeginning from a different ticket": "No se puede crear una línea de reclamación de un ticket diferente al origen",
- "company": "Compañía",
- "country": "País",
- "clientId": "Id cliente",
- "clientSocialName": "Cliente",
- "amount": "Importe",
- "taxableBase": "Base",
- "ticketFk": "Id ticket",
- "isActive": "Activo",
- "hasToInvoice": "Facturar",
- "isTaxDataChecked": "Datos comprobados",
- "comercialId": "Id comercial",
- "comercialName": "Comercial",
- "Pass expired": "La contraseña ha caducado, cambiela desde Salix",
- "Invalid NIF for VIES": "Invalid NIF for VIES",
- "Ticket does not exist": "Este ticket no existe",
- "Ticket is already signed": "Este ticket ya ha sido firmado",
- "Authentication failed": "Autenticación fallida",
- "You can't use the same password": "No puedes usar la misma contraseña",
- "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono",
- "Fecha fuera de rango": "Fecha fuera de rango",
- "Error while generating PDF": "Error al generar PDF",
- "Error when sending mail to client": "Error al enviar el correo al cliente",
- "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico",
- "The renew period has not been exceeded": "El periodo de renovación no ha sido superado",
- "Valid priorities": "Prioridades válidas: %d",
- "Negative basis of tickets": "Base negativa para los tickets: {{ticketsIds}}",
- "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado",
- "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s",
- "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias",
- "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado",
- "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado",
- "You don't have enough privileges.": "No tienes suficientes permisos.",
- "This ticket is locked.": "Este ticket está bloqueado.",
- "This ticket is not editable.": "Este ticket no es editable.",
- "The ticket doesn't exist.": "No existe el ticket.",
- "Social name should be uppercase": "La razón social debe ir en mayúscula",
- "Street should be uppercase": "La dirección fiscal debe ir en mayúscula",
- "The response is not a PDF": "La respuesta no es un PDF",
- "Ticket without Route": "Ticket sin ruta",
- "Booking completed": "Reserva completada",
- "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación"
-}
+ "Phone format is invalid": "El formato del teléfono no es correcto",
+ "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito",
+ "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia",
+ "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado",
+ "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado",
+ "Can't be blank": "No puede estar en blanco",
+ "Invalid TIN": "NIF/CIF inválido",
+ "TIN must be unique": "El NIF/CIF debe ser único",
+ "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web",
+ "Is invalid": "Es inválido",
+ "Quantity cannot be zero": "La cantidad no puede ser cero",
+ "Enter an integer different to zero": "Introduce un entero distinto de cero",
+ "Package cannot be blank": "El embalaje no puede estar en blanco",
+ "The company name must be unique": "La razón social debe ser única",
+ "Invalid email": "Correo electrónico inválido",
+ "The IBAN does not have the correct format": "El IBAN no tiene el formato correcto",
+ "That payment method requires an IBAN": "El método de pago seleccionado requiere un IBAN",
+ "That payment method requires a BIC": "El método de pago seleccionado requiere un BIC",
+ "State cannot be blank": "El estado no puede estar en blanco",
+ "Worker cannot be blank": "El trabajador no puede estar en blanco",
+ "Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado",
+ "can't be blank": "El campo no puede estar vacío",
+ "Observation type must be unique": "El tipo de observación no puede repetirse",
+ "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero",
+ "The grade must be similar to the last one": "El grade debe ser similar al último",
+ "Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente",
+ "Name cannot be blank": "El nombre no puede estar en blanco",
+ "Phone cannot be blank": "El teléfono no puede estar en blanco",
+ "Period cannot be blank": "El periodo no puede estar en blanco",
+ "Choose a company": "Selecciona una empresa",
+ "Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto",
+ "Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres",
+ "Cannot be blank": "El campo no puede estar en blanco",
+ "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero",
+ "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco",
+ "Description cannot be blank": "Se debe rellenar el campo de texto",
+ "The price of the item changed": "El precio del artículo cambió",
+ "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%",
+ "The value should be a number": "El valor debe ser un numero",
+ "This order is not editable": "Esta orden no se puede modificar",
+ "You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado",
+ "You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda",
+ "is not a valid date": "No es una fecha valida",
+ "Barcode must be unique": "El código de barras debe ser único",
+ "The warehouse can't be repeated": "El almacén no puede repetirse",
+ "The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item",
+ "The observation type can't be repeated": "El tipo de observación no puede repetirse",
+ "A claim with that sale already exists": "Ya existe una reclamación para esta línea",
+ "You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo",
+ "Warehouse cannot be blank": "El almacén no puede quedar en blanco",
+ "Agency cannot be blank": "La agencia no puede quedar en blanco",
+ "Not enough privileges to edit a client with verified data": "No tienes permisos para hacer cambios en un cliente con datos comprobados",
+ "This address doesn't exist": "Este consignatario no existe",
+ "You must delete the claim id %d first": "Antes debes borrar la reclamación %d",
+ "You don't have enough privileges": "No tienes suficientes permisos",
+ "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF",
+ "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos básicos de una orden con artículos",
+ "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no está permitido el uso de la letra ñ",
+ "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado",
+ "You can't create a ticket for an inactive client": "No puedes crear un ticket para un cliente inactivo",
+ "Tag value cannot be blank": "El valor del tag no puede quedar en blanco",
+ "ORDER_EMPTY": "Cesta vacía",
+ "You don't have enough privileges to do that": "No tienes permisos para cambiar esto",
+ "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT",
+ "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido",
+ "Street cannot be empty": "Dirección no puede estar en blanco",
+ "City cannot be empty": "Ciudad no puede estar en blanco",
+ "Code cannot be blank": "Código no puede estar en blanco",
+ "You cannot remove this department": "No puedes eliminar este departamento",
+ "The extension must be unique": "La extensión debe ser unica",
+ "The secret can't be blank": "La contraseña no puede estar en blanco",
+ "We weren't able to send this SMS": "No hemos podido enviar el SMS",
+ "This client can't be invoiced": "Este cliente no puede ser facturado",
+ "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa",
+ "This ticket can't be invoiced": "Este ticket no puede ser facturado",
+ "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado",
+ "This ticket can not be modified": "Este ticket no puede ser modificado",
+ "The introduced hour already exists": "Esta hora ya ha sido introducida",
+ "INFINITE_LOOP": "Existe una dependencia entre dos Jefes",
+ "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas",
+ "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros",
+ "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado",
+ "The current ticket can't be modified": "El ticket actual no puede ser modificado",
+ "The current claim can't be modified": "La reclamación actual no puede ser modificada",
+ "The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas",
+ "The sales do not exists": "La(s) línea(s) seleccionada(s) no existe(n)",
+ "Please select at least one sale": "Por favor selecciona al menos una linea",
+ "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket",
+ "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada",
+ "This item doesn't exists": "El artículo no existe",
+ "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada",
+ "Extension format is invalid": "El formato de la extensión es inválido",
+ "Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket",
+ "This item is not available": "Este artículo no está disponible",
+ "This postcode already exists": "Este código postal ya existe",
+ "Concept cannot be blank": "El concepto no puede quedar en blanco",
+ "File doesn't exists": "El archivo no existe",
+ "You don't have privileges to change the zone": "No tienes permisos para cambiar la zona o para esos parámetros hay más de una opción de envío, hable con las agencias",
+ "This ticket is already on weekly tickets": "Este ticket ya está en tickets programados",
+ "Ticket id cannot be blank": "El id de ticket no puede quedar en blanco",
+ "Weekday cannot be blank": "El día de la semana no puede quedar en blanco",
+ "You can't delete a confirmed order": "No puedes borrar un pedido confirmado",
+ "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto",
+ "Invalid quantity": "Cantidad invalida",
+ "This postal code is not valid": "Este código postal no es válido",
+ "is invalid": "es inválido",
+ "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto",
+ "The department name can't be repeated": "El nombre del departamento no puede repetirse",
+ "This phone already exists": "Este teléfono ya existe",
+ "You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos",
+ "You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado",
+ "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada",
+ "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero",
+ "You should specify a date": "Debes especificar una fecha",
+ "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fin",
+ "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fin",
+ "You should mark at least one week day": "Debes marcar al menos un día de la semana",
+ "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío",
+ "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios",
+ "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios",
+ "Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}",
+ "Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}",
+ "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
+ "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
+ "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})",
+ "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})",
+ "State": "Estado",
+ "regular": "normal",
+ "reserved": "reservado",
+ "Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
+ "Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})",
+ "Deny buy request": "Se ha rechazado la petición de compra para el ticket id [{{ticketId}}]({{{url}}}). Motivo: {{observation}}",
+ "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*",
+ "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})",
+ "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})",
+ "Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}",
+ "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*",
+ "Claim state has changed to": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *{{newState}}*",
+ "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}",
+ "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto",
+ "Distance must be lesser than 4000": "La distancia debe ser inferior a 4000",
+ "This ticket is deleted": "Este ticket está eliminado",
+ "Unable to clone this travel": "No ha sido posible clonar este travel",
+ "This thermograph id already exists": "La id del termógrafo ya existe",
+ "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante",
+ "ORDER_ALREADY_CONFIRMED": "ORDEN YA CONFIRMADA",
+ "Invalid password": "Invalid password",
+ "Password does not meet requirements": "La contraseña no cumple los requisitos",
+ "Role already assigned": "Rol ya asignado",
+ "Invalid role name": "Nombre de rol no válido",
+ "Role name must be written in camelCase": "El nombre del rol debe escribirse en camelCase",
+ "Email already exists": "El correo ya existe",
+ "User already exists": "El/La usuario/a ya existe",
+ "Absence change notification on the labour calendar": "Notificación de cambio de ausencia en el calendario laboral",
+ "Record of hours week": "Registro de horas semana {{week}} año {{year}} ",
+ "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.",
+ "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.",
+ "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})",
+ "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})",
+ "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación",
+ "Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
+ "agencyModeFk": "Agencia",
+ "clientFk": "Cliente",
+ "zoneFk": "Zona",
+ "warehouseFk": "Almacén",
+ "shipped": "F. envío",
+ "landed": "F. entrega",
+ "addressFk": "Consignatario",
+ "companyFk": "Empresa",
+ "The social name cannot be empty": "La razón social no puede quedar en blanco",
+ "The nif cannot be empty": "El NIF no puede quedar en blanco",
+ "You need to fill sage information before you check verified data": "Debes rellenar la información de sage antes de marcar datos comprobados",
+ "ASSIGN_ZONE_FIRST": "Asigna una zona primero",
+ "Amount cannot be zero": "El importe no puede ser cero",
+ "Company has to be official": "Empresa inválida",
+ "You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria",
+ "Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas",
+ "The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta",
+ "New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*",
+ "New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*",
+ "Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío",
+ "This BIC already exist.": "Este BIC ya existe.",
+ "That item doesn't exists": "Ese artículo no existe",
+ "There's a new urgent ticket:": "Hay un nuevo ticket urgente:",
+ "Invalid account": "Cuenta inválida",
+ "Compensation account is empty": "La cuenta para compensar está vacia",
+ "This genus already exist": "Este genus ya existe",
+ "This specie already exist": "Esta especie ya existe",
+ "Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})",
+ "None": "Ninguno",
+ "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada",
+ "Cannot add more than one '1/2 day vacation'": "No puedes añadir más de un 'Vacaciones 1/2 dia'",
+ "This document already exists on this ticket": "Este documento ya existe en el ticket",
+ "Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables",
+ "You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes",
+ "nickname": "nickname",
+ "INACTIVE_PROVIDER": "Proveedor inactivo",
+ "This client is not invoiceable": "Este cliente no es facturable",
+ "serial non editable": "Esta serie no permite asignar la referencia",
+ "Max shipped required": "La fecha límite es requerida",
+ "Can't invoice to future": "No se puede facturar a futuro",
+ "Can't invoice to past": "No se puede facturar a pasado",
+ "This ticket is already invoiced": "Este ticket ya está facturado",
+ "A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero",
+ "A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa",
+ "Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes",
+ "Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes",
+ "Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio",
+ "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito",
+ "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas",
+ "Amounts do not match": "Las cantidades no coinciden",
+ "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'",
+ "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos",
+ "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días",
+ "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día",
+ "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día",
+ "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado",
+ "The account size must be exactly 10 characters": "El tamaño de la cuenta debe ser exactamente de 10 caracteres",
+ "Can't transfer claimed sales": "No puedes transferir lineas reclamadas",
+ "You don't have privileges to create refund": "No tienes permisos para crear un abono",
+ "The item is required": "El artículo es requerido",
+ "The agency is already assigned to another autonomous": "La agencia ya está asignada a otro autónomo",
+ "date in the future": "Fecha en el futuro",
+ "reference duplicated": "Referencia duplicada",
+ "This ticket is already a refund": "Este ticket ya es un abono",
+ "isWithoutNegatives": "Sin negativos",
+ "routeFk": "routeFk",
+ "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador",
+ "No hay un contrato en vigor": "No hay un contrato en vigor",
+ "No se permite fichar a futuro": "No se permite fichar a futuro",
+ "No está permitido trabajar": "No está permitido trabajar",
+ "Fichadas impares": "Fichadas impares",
+ "Descanso diario 12h.": "Descanso diario 12h.",
+ "Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.",
+ "Dirección incorrecta": "Dirección incorrecta",
+ "Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador",
+ "Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador",
+ "Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente",
+ "This route does not exists": "Esta ruta no existe",
+ "Claim pickup order sent": "Reclamación Orden de recogida enviada [{{claimId}}]({{{claimUrl}}}) al cliente *{{clientName}}*",
+ "You don't have grant privilege": "No tienes privilegios para dar privilegios",
+ "You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario",
+ "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) fusionado con [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})",
+ "Already has this status": "Ya tiene este estado",
+ "There aren't records for this week": "No existen registros para esta semana",
+ "Empty data source": "Origen de datos vacio",
+ "App locked": "Aplicación bloqueada por el usuario {{userId}}",
+ "Email verify": "Correo de verificación",
+ "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment",
+ "Receipt's bank was not found": "No se encontró el banco del recibo",
+ "This receipt was not compensated": "Este recibo no ha sido compensado",
+ "Client's email was not found": "No se encontró el email del cliente",
+ "Negative basis": "Base negativa",
+ "This worker code already exists": "Este codigo de trabajador ya existe",
+ "This personal mail already exists": "Este correo personal ya existe",
+ "This worker already exists": "Este trabajador ya existe",
+ "App name does not exist": "El nombre de aplicación no es válido",
+ "Try again": "Vuelve a intentarlo",
+ "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9",
+ "Failed to upload delivery note": "Error al subir albarán {{id}}",
+ "The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe",
+ "It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar",
+ "It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo",
+ "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas",
+ "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.",
+ "There is no assigned email for this client": "No hay correo asignado para este cliente",
+ "Exists an invoice with a future date": "Existe una factura con fecha posterior",
+ "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite",
+ "Warehouse inventory not set": "El almacén inventario no está establecido",
+ "This locker has already been assigned": "Esta taquilla ya ha sido asignada",
+ "Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº %d",
+ "Not exist this branch": "La rama no existe",
+ "This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado",
+ "Collection does not exist": "La colección no existe",
+ "Cannot obtain exclusive lock": "No se puede obtener un bloqueo exclusivo",
+ "Insert a date range": "Inserte un rango de fechas",
+ "Added observation": "{{user}} añadió esta observacion: {{text}}",
+ "Comment added to client": "Observación añadida al cliente {{clientFk}}",
+ "Invalid auth code": "Código de verificación incorrecto",
+ "Invalid or expired verification code": "Código de verificación incorrecto o expirado",
+ "Cannot create a new claimBeginning from a different ticket": "No se puede crear una línea de reclamación de un ticket diferente al origen",
+ "company": "Compañía",
+ "country": "País",
+ "clientId": "Id cliente",
+ "clientSocialName": "Cliente",
+ "amount": "Importe",
+ "taxableBase": "Base",
+ "ticketFk": "Id ticket",
+ "isActive": "Activo",
+ "hasToInvoice": "Facturar",
+ "isTaxDataChecked": "Datos comprobados",
+ "comercialId": "Id comercial",
+ "comercialName": "Comercial",
+ "Pass expired": "La contraseña ha caducado, cambiela desde Salix",
+ "Invalid NIF for VIES": "Invalid NIF for VIES",
+ "Ticket does not exist": "Este ticket no existe",
+ "Ticket is already signed": "Este ticket ya ha sido firmado",
+ "Authentication failed": "Autenticación fallida",
+ "You can't use the same password": "No puedes usar la misma contraseña",
+ "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono",
+ "Fecha fuera de rango": "Fecha fuera de rango",
+ "Error while generating PDF": "Error al generar PDF",
+ "Error when sending mail to client": "Error al enviar el correo al cliente",
+ "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico",
+ "The renew period has not been exceeded": "El periodo de renovación no ha sido superado",
+ "Valid priorities": "Prioridades válidas: %d",
+ "hasAnyNegativeBase": "Base negativa para los tickets: {{ticketsIds}}",
+ "hasAnyPositiveBase": "Base positivas para los tickets: {{ticketsIds}}",
+ "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado",
+ "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s",
+ "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias",
+ "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado",
+ "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado",
+ "You don't have enough privileges.": "No tienes suficientes permisos.",
+ "This ticket is locked": "Este ticket está bloqueado.",
+ "This ticket is not editable.": "Este ticket no es editable.",
+ "The ticket doesn't exist.": "No existe el ticket.",
+ "Social name should be uppercase": "La razón social debe ir en mayúscula",
+ "Street should be uppercase": "La dirección fiscal debe ir en mayúscula",
+ "Ticket without Route": "Ticket sin ruta",
+ "Select a different client": "Seleccione un cliente distinto",
+ "Fill all the fields": "Rellene todos los campos",
+ "The response is not a PDF": "La respuesta no es un PDF",
+ "Booking completed": "Reserva completada",
+ "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación",
+ "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada",
+ "User disabled": "Usuario desactivado",
+ "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima",
+ "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima",
+ "Cannot past travels with entries": "No se pueden pasar envíos con entradas",
+ "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}",
+ "This claim has been updated": "La reclamación con Id: {{claimId}}, ha sido actualizada",
+ "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada",
+ "Field are invalid": "El campo '{{tag}}' no es válido",
+ "Incorrect pin": "Pin incorrecto.",
+ "You already have the mailAlias": "Ya tienes este alias de correo",
+ "The alias cant be modified": "Este alias de correo no puede ser modificado",
+ "No tickets to invoice": "No hay tickets para facturar",
+ "this warehouse has not dms": "El Almacén no acepta documentos",
+ "This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado",
+ "Name should be uppercase": "El nombre debe ir en mayúscula",
+ "Bank entity must be specified": "La entidad bancaria es obligatoria",
+ "An email is necessary": "Es necesario un email",
+ "You cannot update these fields": "No puedes actualizar estos campos",
+ "CountryFK cannot be empty": "El país no puede estar vacío",
+ "Cmr file does not exist": "El archivo del cmr no existe",
+ "You are not allowed to modify the alias": "No estás autorizado a modificar el alias",
+ "The address of the customer must have information about Incoterms and Customs Agent": "El consignatario del cliente debe tener informado Incoterms y Agente de aduanas",
+ "The line could not be marked": "La linea no puede ser marcada",
+ "This password can only be changed by the user themselves": "Esta contraseña solo puede ser modificada por el propio usuario",
+ "They're not your subordinate": "No es tu subordinado/a."
+}
\ No newline at end of file
diff --git a/loopback/server/boot/date.js b/loopback/server/boot/date.js
index 810745562..d592dc416 100644
--- a/loopback/server/boot/date.js
+++ b/loopback/server/boot/date.js
@@ -1,6 +1,5 @@
module.exports = () => {
- Date.vnUTC = () => {
- const env = process.env.NODE_ENV;
+ Date.vnUTC = (env = process.env.NODE_ENV) => {
if (!env || env === 'development')
return new Date(Date.UTC(2001, 0, 1, 11));
diff --git a/loopback/server/connectors/vn-mysql.js b/loopback/server/connectors/vn-mysql.js
index 40ad78bde..5edef4395 100644
--- a/loopback/server/connectors/vn-mysql.js
+++ b/loopback/server/connectors/vn-mysql.js
@@ -270,12 +270,12 @@ class VnMySQL extends MySQL {
isLoggable(model) {
const Model = this.getModelDefinition(model).model;
- const settings = Model.definition.settings;
- return settings.base && settings.base === 'Loggable';
+ const {settings} = Model.definition;
+ return settings.mixins?.Loggable;
}
invokeMethod(method, args, model, ctx, opts, cb) {
- if (!this.isLoggable(model))
+ if (!this.isLoggable(model) && !opts?.userId)
return super[method].apply(this, args);
this.invokeMethodP(method, [...args], model, ctx, opts)
@@ -287,11 +287,11 @@ class VnMySQL extends MySQL {
let tx;
if (!opts.transaction) {
tx = await Transaction.begin(this, {});
- opts = Object.assign({transaction: tx, httpCtx: opts.httpCtx}, opts);
+ opts = Object.assign({transaction: tx}, opts);
}
try {
- const userId = opts.httpCtx && opts.httpCtx.active.accessToken.userId;
+ const {userId} = opts;
if (userId) {
const user = await Model.app.models.VnUser.findById(userId, {fields: ['name']}, opts);
await this.executeP(`CALL account.myUser_loginWithName(?)`, [user.name], opts);
diff --git a/loopback/server/datasources.json b/loopback/server/datasources.json
index aadee048c..341d5d578 100644
--- a/loopback/server/datasources.json
+++ b/loopback/server/datasources.json
@@ -103,6 +103,35 @@
"video/mp4"
]
},
+ "entryStorage": {
+ "name": "entryStorage",
+ "connector": "loopback-component-storage",
+ "provider": "filesystem",
+ "root": "./storage/dms",
+ "maxFileSize": "31457280",
+ "allowedContentTypes": [
+ "image/png",
+ "image/jpeg",
+ "image/jpg",
+ "image/webp",
+ "video/mp4"
+ ]
+ },
+ "supplierStorage": {
+ "name": "supplierStorage",
+ "connector": "loopback-component-storage",
+ "provider": "filesystem",
+ "root": "./storage/dms",
+ "maxFileSize": "31457280",
+ "allowedContentTypes": [
+ "image/png",
+ "image/jpeg",
+ "image/jpg",
+ "image/webp",
+ "video/mp4",
+ "application/pdf"
+ ]
+ },
"accessStorage": {
"name": "accessStorage",
"connector": "loopback-component-storage",
diff --git a/loopback/server/middleware.json b/loopback/server/middleware.json
index 31a2f113b..cfc693217 100644
--- a/loopback/server/middleware.json
+++ b/loopback/server/middleware.json
@@ -39,7 +39,7 @@
"./middleware/salix-version": {}
},
"parse": {
- "body-parser#json":{}
+ "body-parser#json":{}
},
"routes": {
"loopback#rest": {
diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js
index 725826ae7..cc7b81618 100644
--- a/loopback/server/middleware/error-handler.js
+++ b/loopback/server/middleware/error-handler.js
@@ -1,10 +1,11 @@
+const SalixError = require('../../util/salixError');
const UserError = require('../../util/user-error');
const logToConsole = require('strong-error-handler/lib/logger');
module.exports = function() {
return function(err, req, res, next) {
// Thrown user errors
- if (err instanceof UserError) {
+ if (err instanceof SalixError) {
err.message = req.__(err.message, ...err.translateArgs);
return next(err);
}
@@ -13,7 +14,7 @@ module.exports = function() {
if (err.statusCode == 422) {
try {
let code;
- let messages = err.details.messages;
+ let {messages} = err.details;
for (code in messages) break;
err.message = req.__(messages[code][0]);
return next(err);
diff --git a/loopback/server/middleware/salix-version.js b/loopback/server/middleware/salix-version.js
index 988a3b39c..93ed6a9c4 100644
--- a/loopback/server/middleware/salix-version.js
+++ b/loopback/server/middleware/salix-version.js
@@ -1,4 +1,4 @@
-const packageJson = require('../../../package.json');
+const packageJson = require(`${process.cwd()}/package.json`);
module.exports = function(options) {
return function(req, res, next) {
diff --git a/loopback/server/model-config.json b/loopback/server/model-config.json
index 52b539f60..56b5360e8 100644
--- a/loopback/server/model-config.json
+++ b/loopback/server/model-config.json
@@ -25,20 +25,19 @@
"FieldAcl": {
"dataSource": "vn"
},
- "Role": {
- "dataSource": "vn",
- "options": {
- "mysql": {
- "table": "salix.Role"
- }
- }
- },
"RoleMapping": {
"dataSource": "vn",
"options": {
"mysql": {
"table": "salix.RoleMapping"
}
+ },
+ "relations": {
+ "role": {
+ "type": "belongsTo",
+ "model": "VnRole",
+ "foreignKey": "roleId"
+ }
}
},
"Schema": {
@@ -49,5 +48,13 @@
},
"Container": {
"dataSource": "vn"
+ },
+ "ProcsPriv": {
+ "dataSource": "vn",
+ "options": {
+ "mysql": {
+ "table": "mysql.procs_priv"
+ }
+ }
}
-}
\ No newline at end of file
+}
diff --git a/loopback/server/server.js b/loopback/server/server.js
index 188b5eb0f..5e2f4ebd2 100644
--- a/loopback/server/server.js
+++ b/loopback/server/server.js
@@ -28,7 +28,7 @@ module.exports = app;
let rootDir = __dirname;
let lbDir = path.resolve(`${rootDir}/..`);
-let appDir = path.resolve(`${__dirname}/../..`);
+let appDir = process.cwd();
let localeDir = `${lbDir}/locale`;
let modulesDir = `${appDir}/modules`;
@@ -80,13 +80,13 @@ app.boot = function(bootOptions, callback) {
`${__dirname}/model-config.json`
];
let modelSources = [
- `loopback/common/models`,
- `loopback/server/models`,
+ `${lbDir}/common/models`,
+ `${lbDir}/server/models`,
`${__dirname}/../common/models`
];
let mixinDirs = [
- `loopback/common/mixins`,
- `loopback/server/mixins`,
+ `${lbDir}/common/mixins`,
+ `${lbDir}/server/mixins`,
`${__dirname}/../common/mixins`
];
let bootDirs = [
diff --git a/loopback/util/forbiddenError.js b/loopback/util/forbiddenError.js
index 998cb4593..8f6561059 100644
--- a/loopback/util/forbiddenError.js
+++ b/loopback/util/forbiddenError.js
@@ -1,7 +1,8 @@
-module.exports = class ForbiddenError extends Error {
+const SalixError = require('./salixError');
+module.exports = class ForbiddenError extends SalixError {
constructor(message, code, ...translateArgs) {
super(message);
- this.name = 'ForbiddenError';
+ this.name = ForbiddenError.name;
this.statusCode = 403;
this.code = code;
this.translateArgs = translateArgs;
diff --git a/loopback/util/salixError.js b/loopback/util/salixError.js
new file mode 100644
index 000000000..427b871ab
--- /dev/null
+++ b/loopback/util/salixError.js
@@ -0,0 +1,5 @@
+module.exports = class SalixError extends Error {
+ constructor(message) {
+ super(message);
+ }
+};
diff --git a/loopback/util/user-error.js b/loopback/util/user-error.js
index c2d01e080..feee208b3 100644
--- a/loopback/util/user-error.js
+++ b/loopback/util/user-error.js
@@ -4,10 +4,11 @@
* the final user, so they cannot contain sensitive data and must
* be understandable by people who do not have a technical profile.
*/
-module.exports = class UserError extends Error {
+const SalixError = require('./salixError');
+module.exports = class UserError extends SalixError {
constructor(message, code, ...translateArgs) {
super(message);
- this.name = 'UserError';
+ this.name = UserError.name;
this.statusCode = 400;
this.code = code;
this.translateArgs = translateArgs;
diff --git a/loopback/util/validateIban.js b/loopback/util/validateIban.js
index ed3e00426..2386538b5 100644
--- a/loopback/util/validateIban.js
+++ b/loopback/util/validateIban.js
@@ -3,7 +3,6 @@ module.exports = function(iban, countryCode) {
if (typeof iban != 'string') return false;
if (countryCode?.toLowerCase() != 'es') return true;
- iban = iban.toUpperCase();
iban = trim(iban);
iban = iban.replace(/\s/g, '');
diff --git a/modules/account/back/methods/account-synchronizer/test.js b/modules/account/back/methods/account-linker/test.js
similarity index 59%
rename from modules/account/back/methods/account-synchronizer/test.js
rename to modules/account/back/methods/account-linker/test.js
index a77940168..990af2df8 100644
--- a/modules/account/back/methods/account-synchronizer/test.js
+++ b/modules/account/back/methods/account-linker/test.js
@@ -1,3 +1,4 @@
+const NotFoundError = require('vn-loopback/util/not-found-error');
module.exports = Self => {
Self.remoteMethod('test', {
@@ -9,7 +10,8 @@ module.exports = Self => {
});
Self.test = async function() {
- let connector = await Self.getSynchronizer();
+ const connector = await Self.getLinker();
+ if (!connector) throw new NotFoundError('Linker not configured');
await connector.test();
};
};
diff --git a/modules/account/back/methods/account/logout.js b/modules/account/back/methods/account/logout.js
index 5db3efa33..7d2e8153e 100644
--- a/modules/account/back/methods/account/logout.js
+++ b/modules/account/back/methods/account/logout.js
@@ -15,7 +15,8 @@ module.exports = Self => {
http: {
path: `/logout`,
verb: 'POST'
- }
+ },
+ accessScopes: ['DEFAULT', 'read:multimedia']
});
Self.logout = async ctx => Self.app.models.VnUser.logout(ctx.req.accessToken.id);
diff --git a/modules/account/back/methods/account/specs/change-password.spec.js b/modules/account/back/methods/account/specs/change-password.spec.js
index 2fa3010af..c79960212 100644
--- a/modules/account/back/methods/account/specs/change-password.spec.js
+++ b/modules/account/back/methods/account/specs/change-password.spec.js
@@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server');
describe('account changePassword()', () => {
const userId = 70;
- const unauthCtx = {
+ const unAuthCtx = {
req: {
headers: {},
connection: {
@@ -79,7 +79,7 @@ describe('account changePassword()', () => {
passExpired: yesterday
}
, options);
- await models.VnUser.signIn(unauthCtx, 'trainee', 'nightmare', options);
+ await models.VnUser.signIn(unAuthCtx, 'trainee', 'nightmare', options);
} catch (e) {
if (e.message != 'Pass expired')
throw e;
diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js
index a5befc22c..1026c5020 100644
--- a/modules/account/back/methods/account/sync.js
+++ b/modules/account/back/methods/account/sync.js
@@ -1,3 +1,4 @@
+const ForbiddenError = require('vn-loopback/util/forbiddenError');
module.exports = Self => {
Self.remoteMethod('sync', {
@@ -25,21 +26,46 @@ module.exports = Self => {
});
Self.sync = async function(userName, password, force, options) {
+ const models = Self.app.models;
const myOptions = {};
-
+ let tx;
+
if (typeof options == 'object')
Object.assign(myOptions, options);
- const models = Self.app.models;
- const user = await models.VnUser.findOne({
- fields: ['id'],
- where: {name: userName}
- }, myOptions);
- const isSync = !await models.UserSync.exists(userName, myOptions);
+ if (!myOptions.transaction) {
+ tx = await Self.beginTransaction({});
+ myOptions.transaction = tx;
+ };
- if (!force && isSync && user) return;
- await models.AccountConfig.syncUser(userName, password);
- await models.UserSync.destroyById(userName, myOptions);
+ try {
+ const user = await models.VnUser.findOne({
+ fields: ['id', 'password'],
+ where: {name: userName}
+ }, myOptions);
+
+ if (user && password && !await user.hasPassword(password))
+ throw new ForbiddenError('Wrong password');
+
+ const isSync = !await models.UserSync.exists(userName, myOptions);
+
+ if (!force && isSync && user) {
+ if (tx) await tx.rollback();
+ return;
+ }
+
+ await Self.rawSql(`
+ SELECT id
+ FROM account.user
+ WHERE id = ?
+ FOR UPDATE`, [user.id], myOptions);
+
+ await models.AccountConfig.syncUser(userName, password);
+ await models.UserSync.destroyById(userName, myOptions);
+ if (tx) await tx.commit();
+ } catch (err) {
+ if (tx) await tx.rollback();
+ throw err;
+ }
};
};
-
diff --git a/modules/account/back/mixins/account-synchronizer.js b/modules/account/back/mixins/account-linker.js
similarity index 85%
rename from modules/account/back/mixins/account-synchronizer.js
rename to modules/account/back/mixins/account-linker.js
index 8ba8bfe9d..c882d0893 100644
--- a/modules/account/back/mixins/account-synchronizer.js
+++ b/modules/account/back/mixins/account-linker.js
@@ -3,14 +3,14 @@ const app = require('vn-loopback/server/server');
const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self, options) {
- require('../methods/account-synchronizer/test')(Self);
+ require('../methods/account-linker/test')(Self);
Self.once('attached', function() {
- app.models.AccountConfig.addSynchronizer(Self);
+ app.models.AccountConfig.addLinker(Self);
});
/**
- * Mixin for user synchronizers.
+ * Mixin for account linkers.
*
* @property {Array} $
* @property {Object} accountConfig
@@ -18,12 +18,12 @@ module.exports = function(Self, options) {
*/
let Mixin = {
/**
- * Initalizes the synchronizer.
+ * Initalizes the linker.
*/
async init() {},
/**
- * Deinitalizes the synchronizer.
+ * Deinitalizes the linker.
*/
async deinit() {},
@@ -57,7 +57,7 @@ module.exports = function(Self, options) {
async syncRoles() {},
/**
- * Tests synchronizer configuration.
+ * Tests linker configuration.
*/
async test() {
try {
diff --git a/modules/account/back/model-config.json b/modules/account/back/model-config.json
index a4eb9fa57..0cd43d0ce 100644
--- a/modules/account/back/model-config.json
+++ b/modules/account/back/model-config.json
@@ -14,6 +14,9 @@
"MailAliasAccount": {
"dataSource": "vn"
},
+ "MailAliasAcl": {
+ "dataSource": "vn"
+ },
"MailConfig": {
"dataSource": "vn"
},
@@ -35,6 +38,9 @@
"SambaConfig": {
"dataSource": "vn"
},
+ "SignInLog": {
+ "dataSource": "vn"
+ },
"Sip": {
"dataSource": "vn"
},
diff --git a/modules/account/back/models/account-config.js b/modules/account/back/models/account-config.js
index 0db699b99..2cc6b240d 100644
--- a/modules/account/back/models/account-config.js
+++ b/modules/account/back/models/account-config.js
@@ -3,94 +3,85 @@ const models = require('vn-loopback/server/server').models;
module.exports = Self => {
Object.assign(Self, {
- synchronizers: [],
+ linkers: [],
- addSynchronizer(synchronizer) {
- this.synchronizers.push(synchronizer);
+ addLinker(linker) {
+ this.linkers.push(linker);
},
- async getInstance() {
- let instance = await Self.findOne({
+ async initEngine() {
+ const accountConfig = await Self.findOne({
fields: ['homedir', 'shell', 'idBase']
});
- await instance.synchronizerInit();
- return instance;
+ const mailConfig = await models.MailConfig.findOne({
+ fields: ['domain']
+ });
+
+ const linkers = [];
+
+ for (const Linker of Self.linkers) {
+ const linker = await Linker.getLinker();
+ if (!linker) continue;
+ Object.assign(linker, {accountConfig});
+ await linker.init();
+ linkers.push(linker);
+ }
+
+ Object.assign(accountConfig, {
+ linkers,
+ domain: mailConfig.domain
+ });
+
+ return {
+ accountConfig,
+ linkers
+ };
+ },
+
+ async deinitEngine(engine) {
+ for (const linker of engine.linkers)
+ await linker.deinit();
+ },
+
+ async syncUser(userName, password) {
+ const engine = await Self.initEngine();
+ try {
+ await Self.syncUserBase(engine, userName, password, true);
+ } finally {
+ await Self.deinitEngine(engine);
+ }
},
async syncUsers() {
- let instance = await Self.getInstance();
+ const engine = await Self.initEngine();
+
+ let usersToSync = new Set();
+ for (const linker of engine.linkers)
+ await linker.getUsers(usersToSync);
- let usersToSync = await instance.synchronizerGetUsers();
usersToSync = Array.from(usersToSync.values())
.sort((a, b) => a.localeCompare(b));
for (let userName of usersToSync) {
try {
+ // eslint-disable-next-line no-console
console.log(`Synchronizing user '${userName}'`);
- await instance.synchronizerSyncUser(userName);
+
+ await Self.syncUserBase(engine, userName);
+
+ // eslint-disable-next-line no-console
console.log(` -> User '${userName}' sinchronized`);
} catch (err) {
+ // eslint-disable-next-line no-console
console.error(` -> User '${userName}' synchronization error:`, err.message);
}
}
- await instance.synchronizerDeinit();
+ await Self.deinitEngine(engine);
await Self.syncRoles();
},
- async syncUser(userName, password) {
- let instance = await Self.getInstance();
- try {
- await instance.synchronizerSyncUser(userName, password, true);
- } finally {
- await instance.synchronizerDeinit();
- }
- },
-
- async syncRoles() {
- let instance = await Self.getInstance();
- try {
- await instance.synchronizerSyncRoles();
- } finally {
- await instance.synchronizerDeinit();
- }
- },
-
- async getSynchronizer() {
- return await Self.findOne();
- }
- });
-
- Object.assign(Self.prototype, {
- async synchronizerInit() {
- let mailConfig = await models.MailConfig.findOne({
- fields: ['domain']
- });
-
- let synchronizers = [];
-
- for (let Synchronizer of Self.synchronizers) {
- let synchronizer = await Synchronizer.getSynchronizer();
- if (!synchronizer) continue;
- Object.assign(synchronizer, {
- accountConfig: this
- });
- await synchronizer.init();
- synchronizers.push(synchronizer);
- }
-
- Object.assign(this, {
- synchronizers,
- domain: mailConfig.domain
- });
- },
-
- async synchronizerDeinit() {
- for (let synchronizer of this.synchronizers)
- await synchronizer.deinit();
- },
-
- async synchronizerSyncUser(userName, password, syncGroups) {
+ async syncUserBase(engine, userName, password, syncGroups) {
if (!userName) return;
userName = userName.toLowerCase();
@@ -98,7 +89,7 @@ module.exports = Self => {
if (['administrator', 'root'].indexOf(userName) >= 0)
return;
- let user = await models.VnUser.findOne({
+ const user = await models.VnUser.findOne({
where: {name: userName},
fields: [
'id',
@@ -130,27 +121,28 @@ module.exports = Self => {
]
});
- let info = {
+ const info = {
user,
hasAccount: false
};
if (user) {
- let exists = await models.Account.exists(user.id);
+ const exists = await models.Account.exists(user.id);
+ const {accountConfig} = engine;
Object.assign(info, {
hasAccount: user.active && exists,
- corporateMail: `${userName}@${this.domain}`,
- uidNumber: this.idBase + user.id
+ corporateMail: `${userName}@${accountConfig.domain}`,
+ uidNumber: accountConfig.idBase + user.id
});
}
- let errs = [];
+ const errs = [];
- for (let synchronizer of this.synchronizers) {
+ for (const linker of engine.linkers) {
try {
- await synchronizer.syncUser(userName, info, password);
+ await linker.syncUser(userName, info, password);
if (syncGroups)
- await synchronizer.syncUserGroups(userName, info);
+ await linker.syncUserGroups(userName, info);
} catch (err) {
errs.push(err);
}
@@ -159,18 +151,16 @@ module.exports = Self => {
if (errs.length) throw errs[0];
},
- async synchronizerGetUsers() {
- let usersToSync = new Set();
+ async syncRoles() {
+ const engine = await Self.initEngine();
+ try {
+ await Self.rawSql(`CALL account.role_sync`);
- for (let synchronizer of this.synchronizers)
- await synchronizer.getUsers(usersToSync);
-
- return usersToSync;
- },
-
- async synchronizerSyncRoles() {
- for (let synchronizer of this.synchronizers)
- await synchronizer.syncRoles();
+ for (const linker of engine.linkers)
+ await linker.syncRoles();
+ } finally {
+ await Self.deinitEngine(engine);
+ }
}
});
};
diff --git a/modules/account/back/models/account.js b/modules/account/back/models/account.js
index 5021a5d94..ceb26053c 100644
--- a/modules/account/back/models/account.js
+++ b/modules/account/back/models/account.js
@@ -1,4 +1,7 @@
+const ForbiddenError = require('vn-loopback/util/forbiddenError');
+const {models} = require('vn-loopback/server/server');
+
module.exports = Self => {
require('../methods/account/sync')(Self);
require('../methods/account/sync-by-id')(Self);
@@ -7,4 +10,11 @@ module.exports = Self => {
require('../methods/account/logout')(Self);
require('../methods/account/change-password')(Self);
require('../methods/account/set-password')(Self);
+
+ Self.setUnverifiedPassword = async(id, pass, options) => {
+ const {emailVerified} = await models.VnUser.findById(id, {fields: ['emailVerified']}, options);
+ if (emailVerified) throw new ForbiddenError('This password can only be changed by the user themselves');
+
+ await models.VnUser.setPassword(id, pass, options);
+ };
};
diff --git a/modules/account/back/models/account.json b/modules/account/back/models/account.json
index 3c22521cb..6c2784696 100644
--- a/modules/account/back/models/account.json
+++ b/modules/account/back/models/account.json
@@ -1,49 +1,49 @@
{
- "name": "Account",
- "base": "VnModel",
- "options": {
- "mysql": {
- "table": "account.account"
- }
- },
- "properties": {
- "id": {
- "id": true
- }
- },
- "relations": {
- "user": {
- "type": "belongsTo",
- "model": "VnUser",
- "foreignKey": "id"
- },
- "aliases": {
- "type": "hasMany",
- "model": "MailAliasAccount",
- "foreignKey": "account"
- }
- },
- "acls": [
- {
- "property": "login",
- "accessType": "EXECUTE",
- "principalType": "ROLE",
- "principalId": "$everyone",
- "permission": "ALLOW"
+ "name": "Account",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "account.account"
+ }
+ },
+ "properties": {
+ "id": {
+ "id": true
+ }
+ },
+ "relations": {
+ "user": {
+ "type": "belongsTo",
+ "model": "VnUser",
+ "foreignKey": "id"
},
- {
+ "aliases": {
+ "type": "hasMany",
+ "model": "MailAliasAccount",
+ "foreignKey": "account"
+ }
+ },
+ "acls": [
+ {
+ "property": "login",
+ "accessType": "EXECUTE",
+ "principalType": "ROLE",
+ "principalId": "$everyone",
+ "permission": "ALLOW"
+ },
+ {
"property": "logout",
- "accessType": "EXECUTE",
- "principalType": "ROLE",
- "principalId": "$authenticated",
- "permission": "ALLOW"
- },
- {
+ "accessType": "EXECUTE",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ },
+ {
"property": "changePassword",
- "accessType": "EXECUTE",
- "principalType": "ROLE",
- "principalId": "$everyone",
- "permission": "ALLOW"
- }
- ]
+ "accessType": "EXECUTE",
+ "principalType": "ROLE",
+ "principalId": "$everyone",
+ "permission": "ALLOW"
+ }
+ ]
}
diff --git a/modules/account/back/models/ldap-config.js b/modules/account/back/models/ldap-config.js
index f9ae7562b..89f0add48 100644
--- a/modules/account/back/models/ldap-config.js
+++ b/modules/account/back/models/ldap-config.js
@@ -5,9 +5,9 @@ const crypto = require('crypto');
const nthash = require('smbhash').nthash;
module.exports = Self => {
- const shouldSync = process.env.NODE_ENV === 'production';
+ const shouldSync = process.env.NODE_ENV !== 'test';
- Self.getSynchronizer = async function() {
+ Self.getLinker = async function() {
return await Self.findOne({
fields: [
'server',
@@ -24,6 +24,7 @@ module.exports = Self => {
this.client = ldap.createClient({
url: this.server
});
+ this.client.on('error', () => {});
await this.client.bind(this.rdn, this.password);
},
@@ -140,6 +141,7 @@ module.exports = Self => {
try {
if (shouldSync)
await client.del(dn);
+ // eslint-disable-next-line no-console
console.log(` -> User '${userName}' removed from LDAP`);
} catch (e) {
if (e.name !== 'NoSuchObjectError') throw e;
@@ -237,7 +239,7 @@ module.exports = Self => {
// Prepare data
- let roles = await $.Role.find({
+ let roles = await $.VnRole.find({
fields: ['id', 'name', 'description']
});
let roleRoles = await $.RoleRole.find({
diff --git a/modules/account/back/models/ldap-config.json b/modules/account/back/models/ldap-config.json
index 2fd5aa901..d4d3a094d 100644
--- a/modules/account/back/models/ldap-config.json
+++ b/modules/account/back/models/ldap-config.json
@@ -7,7 +7,7 @@
}
},
"mixins": {
- "AccountSynchronizer": {}
+ "AccountLinker": {}
},
"properties": {
"id": {
diff --git a/modules/account/back/models/mail-alias-account.js b/modules/account/back/models/mail-alias-account.js
index 6f5213f24..61ca344e9 100644
--- a/modules/account/back/models/mail-alias-account.js
+++ b/modules/account/back/models/mail-alias-account.js
@@ -1,55 +1,45 @@
-const UserError = require('vn-loopback/util/user-error');
+const ForbiddenError = require('vn-loopback/util/forbiddenError');
module.exports = Self => {
- Self.observe('before save', async ctx => {
- const changes = ctx.currentInstance || ctx.instance;
-
- await Self.hasGrant(ctx, changes.mailAlias);
+ Self.rewriteDbError(function(err) {
+ if (err.code === 'ER_DUP_ENTRY')
+ return new UserError(`You already have the mailAlias`);
+ return err;
});
- Self.observe('before delete', async ctx => {
- const mailAliasAccount = await Self.findById(ctx.where.id);
-
- await Self.hasGrant(ctx, mailAliasAccount.mailAlias);
+ Self.beforeRemote('create', async function(ctx) {
+ const mailAlias = ctx.args.data?.mailAlias;
+ if (!mailAlias) return;
+ await checkModifyPermission(ctx, mailAlias);
+ });
+ Self.beforeRemote('deleteById', async function(ctx) {
+ const instance = await Self.findById(ctx.args.id,
+ {fields: ['mailAlias']}
+ );
+ await checkModifyPermission(ctx, instance.mailAlias);
});
- /**
- * Checks if current user has
- * grant to add/remove alias
- *
- * @param {Object} ctx - Request context
- * @param {Interger} mailAlias - mailAlias id
- * @return {Boolean} True for user with grant
- */
- Self.hasGrant = async function(ctx, mailAlias) {
+ async function checkModifyPermission(ctx, mailAliasFk) {
const models = Self.app.models;
- const accessToken = {req: {accessToken: ctx.options.accessToken}};
- const userId = accessToken.req.accessToken.userId;
+ const userId = ctx.req.accessToken.userId;
- const canEditAlias = await models.ACL.checkAccessAcl(accessToken, 'MailAliasAccount', 'canEditAlias', 'WRITE');
- if (canEditAlias) return true;
+ const canEditAlias = await models.ACL.checkAccessAcl(ctx,
+ 'MailAliasAccount', 'canEditAlias', 'WRITE');
+ if (canEditAlias) return;
- const user = await models.VnUser.findById(userId, {fields: ['hasGrant']});
- if (!user.hasGrant)
- throw new UserError(`You don't have grant privilege`);
-
- const account = await models.Account.findById(userId, {
- fields: ['id'],
- include: {
- relation: 'aliases',
- scope: {
- fields: ['mailAlias']
- }
- }
+ const allowedRoles = await models.MailAliasAcl.find({
+ fields: ['roleFk'],
+ where: {mailAliasFk}
});
+ const nRoles = allowedRoles.length &&
+ await models.RoleMapping.count({
+ principalId: userId,
+ principalType: 'USER',
+ roleId: {inq: allowedRoles.map(x => x.roleFk)}
+ });
- const aliases = account.aliases().map(alias => alias.mailAlias);
-
- const hasAlias = aliases.includes(mailAlias);
- if (!hasAlias)
- throw new UserError(`You cannot assign/remove an alias that you are not assigned to`);
-
- return true;
- };
+ if (!nRoles)
+ throw new ForbiddenError('You are not allowed to modify the alias');
+ }
};
diff --git a/modules/account/back/models/mail-alias-account.json b/modules/account/back/models/mail-alias-account.json
index 416c2acd8..54e986ef7 100644
--- a/modules/account/back/models/mail-alias-account.json
+++ b/modules/account/back/models/mail-alias-account.json
@@ -23,5 +23,20 @@
"model": "VnUser",
"foreignKey": "account"
}
- }
+ },
+ "acls": [
+ {
+ "property": "create",
+ "accessType": "WRITE",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ }, {
+ "property": "deleteById",
+ "accessType": "WRITE",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ }
+ ]
}
diff --git a/modules/account/back/models/mail-alias-acl.json b/modules/account/back/models/mail-alias-acl.json
new file mode 100644
index 000000000..014b95d14
--- /dev/null
+++ b/modules/account/back/models/mail-alias-acl.json
@@ -0,0 +1,31 @@
+{
+ "name": "MailAliasAcl",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "account.mailAliasAcl"
+ }
+ },
+ "properties": {
+ "mailAliasFk": {
+ "id": true,
+ "type": "number"
+ },
+ "roleFk": {
+ "id": true,
+ "type": "number"
+ }
+ },
+ "relations": {
+ "mailAlias": {
+ "type": "belongsTo",
+ "model": "MailAlias",
+ "foreignKey": "mailAliasFk"
+ },
+ "role": {
+ "type": "belongsTo",
+ "model": "Role",
+ "foreignKey": "roleFk"
+ }
+ }
+}
diff --git a/modules/account/back/models/mail-forward.json b/modules/account/back/models/mail-forward.json
index edef1bf08..874810b7a 100644
--- a/modules/account/back/models/mail-forward.json
+++ b/modules/account/back/models/mail-forward.json
@@ -21,5 +21,16 @@
"model": "VnUser",
"foreignKey": "account"
}
- }
+ },
+ "acls": [{
+ "accessType": "READ",
+ "principalType": "ROLE",
+ "principalId": "$owner",
+ "permission": "ALLOW"
+ }, {
+ "accessType": "WRITE",
+ "principalType": "ROLE",
+ "principalId": "$owner",
+ "permission": "ALLOW"
+ }]
}
diff --git a/modules/account/back/models/role-config.js b/modules/account/back/models/role-config.js
index ba7bf9d52..d6c57b70b 100644
--- a/modules/account/back/models/role-config.js
+++ b/modules/account/back/models/role-config.js
@@ -1,6 +1,6 @@
module.exports = Self => {
- Self.getSynchronizer = async function() {
+ Self.getLinker = async function() {
let NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV || NODE_ENV == 'development')
return null;
@@ -27,8 +27,7 @@ module.exports = Self => {
const [row] = await Self.rawSql(
`SELECT COUNT(*) AS nRows
FROM mysql.user
- WHERE User = ?
- AND Host = ?`,
+ WHERE User = ? AND Host = ?`,
[mysqlUser, this.userHost]
);
let userExists = row.nRows > 0;
@@ -38,8 +37,7 @@ module.exports = Self => {
const [row] = await Self.rawSql(
`SELECT Priv AS priv
FROM mysql.global_priv
- WHERE User = ?
- AND Host = ?`,
+ WHERE User = ? AND Host = ?`,
[mysqlUser, this.userHost]
);
const priv = row && JSON.parse(row.priv);
@@ -47,6 +45,7 @@ module.exports = Self => {
}
if (!isUpdatable) {
+ // eslint-disable-next-line no-console
console.warn(`RoleConfig.syncUser(): User '${userName}' cannot be updated, not managed by me`);
return;
}
@@ -84,14 +83,23 @@ module.exports = Self => {
[mysqlUser, this.userHost]);
} catch (err) {
if (err.code == 'ER_REVOKE_GRANTS')
+ // eslint-disable-next-line no-console
console.warn(`${err.code}: ${err.sqlMessage}: ${err.sql}`);
else
throw err;
}
- await Self.rawSql('GRANT ? TO ?@?',
- [role, mysqlUser, this.userHost]);
- if (role) {
+ const [row] = await Self.rawSql(
+ `SELECT COUNT(*) AS nRows
+ FROM mysql.user
+ WHERE User = ? AND Host = ''`,
+ [role]
+ );
+ const roleExists = row.nRows > 0;
+
+ if (roleExists) {
+ await Self.rawSql('GRANT ? TO ?@?',
+ [role, mysqlUser, this.userHost]);
await Self.rawSql('SET DEFAULT ROLE ? FOR ?@?',
[role, mysqlUser, this.userHost]);
} else {
diff --git a/modules/account/back/models/role-config.json b/modules/account/back/models/role-config.json
index f4138bea8..3b843eaea 100644
--- a/modules/account/back/models/role-config.json
+++ b/modules/account/back/models/role-config.json
@@ -7,7 +7,7 @@
}
},
"mixins": {
- "AccountSynchronizer": {}
+ "AccountLinker": {}
},
"properties": {
"id": {
diff --git a/modules/account/back/models/role-inherit.js b/modules/account/back/models/role-inherit.js
index 7d31e62b1..e994f844e 100644
--- a/modules/account/back/models/role-inherit.js
+++ b/modules/account/back/models/role-inherit.js
@@ -9,7 +9,7 @@ module.exports = Self => {
Self.observe(hook, async() => {
try {
await Self.rawSql(`
- CREATE EVENT account.role_sync
+ CREATE DEFINER = CURRENT_ROLE EVENT account.role_sync
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 SECOND
DO CALL role_sync;
`);
diff --git a/modules/account/back/models/role-inherit.json b/modules/account/back/models/role-inherit.json
index 4b69ffdc2..a89f47b77 100644
--- a/modules/account/back/models/role-inherit.json
+++ b/modules/account/back/models/role-inherit.json
@@ -15,12 +15,12 @@
"relations": {
"owner": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "role"
},
"inherits": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "inheritsFrom"
}
}
diff --git a/modules/account/back/models/role-role.json b/modules/account/back/models/role-role.json
index 77df7a920..e59351c59 100644
--- a/modules/account/back/models/role-role.json
+++ b/modules/account/back/models/role-role.json
@@ -14,12 +14,12 @@
"relations": {
"owner": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "role"
},
"inherits": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "inheritsFrom"
}
}
diff --git a/modules/account/back/models/samba-config.js b/modules/account/back/models/samba-config.js
index 168b5ffb4..927510a29 100644
--- a/modules/account/back/models/samba-config.js
+++ b/modules/account/back/models/samba-config.js
@@ -1,17 +1,20 @@
const ldap = require('../util/ldapjs-extra');
-const ssh = require('node-ssh');
+const execFile = require('child_process').execFile;
/**
* Summary of userAccountControl flags:
* https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/useraccountcontrol-manipulate-account-properties
*/
const UserAccountControlFlags = {
- ACCOUNTDISABLE: 2
+ ACCOUNTDISABLE: 0x2,
+ DONT_EXPIRE_PASSWD: 0x10000
};
module.exports = Self => {
- Self.getSynchronizer = async function() {
+ const shouldSync = process.env.NODE_ENV !== 'test';
+
+ Self.getLinker = async function() {
return await Self.findOne({
fields: [
'host',
@@ -19,6 +22,7 @@ module.exports = Self => {
'adController',
'adUser',
'adPassword',
+ 'userDn',
'verifyCert'
]
});
@@ -26,88 +30,125 @@ module.exports = Self => {
Object.assign(Self.prototype, {
async init() {
- let sshClient = new ssh.NodeSSH();
- await sshClient.connect({
- host: this.adController,
- username: this.adUser,
- password: this.adPassword
- });
+ const baseDn = this.adDomain
+ .split('.')
+ .map(part => `dc=${part}`)
+ .join(',');
+ const bindDn = `cn=${this.adUser},cn=Users,${baseDn}`;
- let adUser = `cn=${this.adUser},${this.usersDn()}`;
-
- let adClient = ldap.createClient({
+ const adClient = ldap.createClient({
url: `ldaps://${this.adController}:636`,
tlsOptions: {rejectUnauthorized: this.verifyCert}
});
- await adClient.bind(adUser, this.adPassword);
-
+ adClient.on('error', () => {});
+ await adClient.bind(bindDn, this.adPassword);
Object.assign(this, {
- sshClient,
- adClient
+ adClient,
+ fullUsersDn: `${this.userDn},${baseDn}`,
+ bindDn
});
},
async deinit() {
- await this.sshClient.dispose();
await this.adClient.unbind();
},
- usersDn() {
- let dnBase = this.adDomain
- .split('.')
- .map(part => `dc=${part}`)
- .join(',');
- return `cn=Users,${dnBase}`;
+ async sambaTool(command, args = []) {
+ let authArgs = [
+ '--URL', `ldaps://${this.adController}`,
+ '--simple-bind-dn', this.bindDn,
+ '--password', this.adPassword
+ ];
+ if (!this.verifyCert)
+ authArgs.push('--option', 'tls verify peer = no_check');
+
+ const allArgs = [command].concat(
+ args, authArgs
+ );
+
+ if (!shouldSync) return;
+ return await new Promise((resolve, reject) => {
+ execFile('samba-tool', allArgs, (err, stdout, stderr) => {
+ if (err)
+ reject(err);
+ else
+ resolve({stdout, stderr});
+ });
+ });
},
- async syncUser(userName, info, password) {
- let {sshClient} = this;
-
- let sambaUser = await this.adClient.searchOne(this.usersDn(), {
+ async getAdUser(userName) {
+ const sambaUser = await this.adClient.searchOne(this.fullUsersDn, {
scope: 'sub',
- attributes: ['userAccountControl'],
+ attributes: [
+ 'dn',
+ 'userAccountControl',
+ 'uidNumber',
+ 'accountExpires',
+ 'mail'
+ ],
filter: `(&(objectClass=user)(sAMAccountName=${userName}))`
});
- let isEnabled = sambaUser
- && !(sambaUser.userAccountControl & UserAccountControlFlags.ACCOUNTDISABLE);
-
- if (process.env.NODE_ENV === 'test')
- return;
+ if (sambaUser) {
+ for (const intProp of ['uidNumber', 'userAccountControl']) {
+ if (sambaUser[intProp] != null)
+ sambaUser[intProp] = parseInt(sambaUser[intProp]);
+ }
+ }
+ return sambaUser;
+ },
+
+ async syncUser(userName, info, password) {
+ let sambaUser = await this.getAdUser(userName);
+ let entry;
if (info.hasAccount) {
if (!sambaUser) {
- await sshClient.exec('samba-tool user create', [
- userName,
- '--uid-number', `${info.uidNumber}`,
- '--mail-address', info.corporateMail,
+ await this.sambaTool('user', [
+ 'create', userName,
+ '--userou', this.userDn,
'--random-password'
]);
- await sshClient.exec('samba-tool user setexpiry', [
- userName,
- '--noexpiry'
- ]);
- await sshClient.exec('mkhomedir_helper', [
- userName,
- '0027'
- ]);
- }
- if (!isEnabled) {
- await sshClient.exec('samba-tool user enable', [
- userName
- ]);
+ sambaUser = await this.getAdUser(userName);
}
if (password) {
- await sshClient.exec('samba-tool user setpassword', [
- userName,
+ await this.sambaTool('user', [
+ 'setpassword', userName,
'--newpassword', password
]);
}
- } else if (isEnabled) {
- await sshClient.exec('samba-tool user disable', [
- userName
- ]);
+
+ entry = {
+ userAccountControl: (sambaUser.userAccountControl
+ | UserAccountControlFlags.DONT_EXPIRE_PASSWD)
+ & ~UserAccountControlFlags.ACCOUNTDISABLE,
+ uidNumber: info.uidNumber,
+ accountExpires: 0,
+ mail: info.corporateMail
+ };
+ } else if (sambaUser) {
+ entry = {
+ userAccountControl: sambaUser.userAccountControl
+ | UserAccountControlFlags.ACCOUNTDISABLE
+ };
+ // eslint-disable-next-line no-console
console.log(` -> User '${userName}' disabled on Samba`);
}
+
+ if (sambaUser && entry) {
+ const changes = [];
+ for (const prop in entry) {
+ if (sambaUser[prop] == entry[prop]) continue;
+ changes.push(new ldap.Change({
+ operation: 'replace',
+ modification: {
+ [prop]: entry[prop]
+ }
+ }));
+ }
+ if (changes.length && shouldSync)
+ await this.adClient.modify(sambaUser.dn, changes);
+ }
},
/**
@@ -117,14 +158,15 @@ module.exports = Self => {
*/
async getUsers(usersToSync) {
const LDAP_MATCHING_RULE_BIT_AND = '1.2.840.113556.1.4.803';
- let filter = `!(userAccountControl:${LDAP_MATCHING_RULE_BIT_AND}:=${UserAccountControlFlags.ACCOUNTDISABLE})`;
+ const filter = `!(userAccountControl:${LDAP_MATCHING_RULE_BIT_AND}`
+ + `:=${UserAccountControlFlags.ACCOUNTDISABLE})`;
- let opts = {
+ const opts = {
scope: 'sub',
attributes: ['sAMAccountName'],
filter: `(&(objectClass=user)(${filter}))`
};
- await this.adClient.searchForeach(this.usersDn(), opts,
+ await this.adClient.searchForeach(this.fullUsersDn, opts,
o => usersToSync.add(o.sAMAccountName));
}
});
diff --git a/modules/account/back/models/samba-config.json b/modules/account/back/models/samba-config.json
index 732c9b071..4c9e0a794 100644
--- a/modules/account/back/models/samba-config.json
+++ b/modules/account/back/models/samba-config.json
@@ -7,7 +7,7 @@
}
},
"mixins": {
- "AccountSynchronizer": {}
+ "AccountLinker": {}
},
"properties": {
"id": {
@@ -28,6 +28,10 @@
"adPassword": {
"type": "string"
},
+ "userDn": {
+ "type": "string",
+ "required": true
+ },
"verifyCert": {
"type": "boolean"
}
diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json
new file mode 100644
index 000000000..8656e92dc
--- /dev/null
+++ b/modules/account/back/models/sign_in-log.json
@@ -0,0 +1,49 @@
+{
+ "name": "SignInLog",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "account.signInLog"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true,
+ "description": "Identifier"
+ },
+ "token": {
+ "required": true,
+ "type": "string",
+ "description": "Token's user"
+ },
+ "creationDate": {
+ "type": "date"
+ },
+ "userFk": {
+ "required": true,
+ "type": "number"
+ },
+ "ip": {
+ "type": "string"
+ },
+ "userName": {
+ "type": "string"
+ },
+ "owner": {
+ "type": "boolean",
+ "required": true,
+ "default": true
+ }
+ },
+ "relations": {
+ "user": {
+ "type": "belongsTo",
+ "model": "VnUser",
+ "foreignKey": "userFk"
+ }
+ },
+ "scope": {
+ "order": ["creationDate DESC", "id DESC"]
+ }
+}
diff --git a/modules/account/back/models/sip-config.js b/modules/account/back/models/sip-config.js
index 3b5cb2dbb..703783337 100644
--- a/modules/account/back/models/sip-config.js
+++ b/modules/account/back/models/sip-config.js
@@ -2,7 +2,7 @@
const app = require('vn-loopback/server/server');
module.exports = Self => {
- Self.getSynchronizer = async function() {
+ Self.getLinker = async function() {
return await Self.findOne({fields: ['id']});
};
diff --git a/modules/account/back/models/sip-config.json b/modules/account/back/models/sip-config.json
index 6c5ba3db3..a25d09c67 100644
--- a/modules/account/back/models/sip-config.json
+++ b/modules/account/back/models/sip-config.json
@@ -7,7 +7,7 @@
}
},
"mixins": {
- "AccountSynchronizer": {}
+ "AccountLinker": {}
},
"properties": {
"id": {
@@ -16,4 +16,3 @@
}
}
}
-
\ No newline at end of file
diff --git a/modules/account/front/accounts/index.html b/modules/account/front/accounts/index.html
index 6941bb15b..6847e68d1 100644
--- a/modules/account/front/accounts/index.html
+++ b/modules/account/front/accounts/index.html
@@ -12,40 +12,40 @@
@@ -61,10 +61,6 @@
label="Synchronize all"
ng-click="$ctrl.onSynchronizeAll()">
-
-
@@ -77,25 +73,3 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/modules/account/front/accounts/index.js b/modules/account/front/accounts/index.js
index 0e78ab8d6..ab19126a1 100644
--- a/modules/account/front/accounts/index.js
+++ b/modules/account/front/accounts/index.js
@@ -1,6 +1,5 @@
import ngModule from '../module';
import Section from 'salix/components/section';
-import UserError from 'core/lib/user-error';
export default class Controller extends Section {
onSynchronizeAll() {
@@ -8,27 +7,10 @@ export default class Controller extends Section {
this.$http.patch(`Accounts/syncAll`);
}
- onUserSync() {
- if (!this.syncUser)
- throw new UserError('Please enter the username');
-
- let params = {
- password: this.syncPassword,
- force: true
- };
- return this.$http.patch(`Accounts/${this.syncUser}/sync`, params)
- .then(() => this.vnApp.showSuccess(this.$t('User synchronized!')));
- }
-
onSynchronizeRoles() {
this.$http.patch(`RoleInherits/sync`)
.then(() => this.vnApp.showSuccess(this.$t('Roles synchronized!')));
}
-
- onSyncClose() {
- this.syncUser = '';
- this.syncPassword = '';
- }
}
ngModule.component('vnAccountAccounts', {
diff --git a/modules/account/front/accounts/locale/es.yml b/modules/account/front/accounts/locale/es.yml
index 9a6bb5073..614ade3eb 100644
--- a/modules/account/front/accounts/locale/es.yml
+++ b/modules/account/front/accounts/locale/es.yml
@@ -3,7 +3,6 @@ Homedir base: Directorio base para carpetas de usuario
Shell: Intérprete de línea de comandos
User and role base id: Id base usuarios y roles
Synchronize all: Sincronizar todo
-Synchronize user: Sincronizar usuario
Synchronize roles: Sincronizar roles
If password is not specified, just user attributes are synchronized: >-
Si la contraseña no se especifica solo se sincronizarán lo atributos del usuario
@@ -12,5 +11,4 @@ Users synchronized!: ¡Usuarios sincronizados!
Username: Nombre de usuario
Synchronize: Sincronizar
Please enter the username: Por favor introduce el nombre de usuario
-User synchronized!: ¡Usuario sincronizado!
Roles synchronized!: ¡Roles sincronizados!
diff --git a/modules/account/front/acl/create/index.html b/modules/account/front/acl/create/index.html
index 7f4fa9e46..14332f737 100644
--- a/modules/account/front/acl/create/index.html
+++ b/modules/account/front/acl/create/index.html
@@ -15,7 +15,7 @@
@@ -32,7 +32,7 @@
diff --git a/modules/account/front/acl/search-panel/index.html b/modules/account/front/acl/search-panel/index.html
index b83b9c255..a3efab440 100644
--- a/modules/account/front/acl/search-panel/index.html
+++ b/modules/account/front/acl/search-panel/index.html
@@ -4,7 +4,7 @@
-
diff --git a/modules/item/front/summary/locale/es.yml b/modules/item/front/summary/locale/es.yml
index 2e78841ae..80988c491 100644
--- a/modules/item/front/summary/locale/es.yml
+++ b/modules/item/front/summary/locale/es.yml
@@ -2,3 +2,4 @@ Barcode: Códigos de barras
Other data: Otros datos
Go to the item: Ir al artículo
WarehouseFk: Calculado sobre el almacén de {{ warehouseName }}
+Minimum sales quantity: Cantidad mínima de venta
diff --git a/modules/item/front/waste/detail/index.html b/modules/item/front/waste/detail/index.html
deleted file mode 100644
index 1b44088bf..000000000
--- a/modules/item/front/waste/detail/index.html
+++ /dev/null
@@ -1,43 +0,0 @@
-
-
-
-
-
-
-
{{detail.family}} ({{detail.buyer}})
-
-
-
-
- Item
- Percentage
- Dwindle
- Total
-
-
-
-
-
-
- {{::waste.itemFk}}
-
-
- {{::(waste.percentage / 100) | percentage: 2}}
- {{::waste.dwindle | currency: 'EUR'}}
- {{::waste.total | currency: 'EUR'}}
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/modules/item/front/waste/detail/index.js b/modules/item/front/waste/detail/index.js
deleted file mode 100644
index 2949a493b..000000000
--- a/modules/item/front/waste/detail/index.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import ngModule from '../../module';
-import Section from 'salix/components/section';
-
-ngModule.vnComponent('vnItemWasteDetail', {
- template: require('./index.html'),
- controller: Section
-});
diff --git a/modules/item/front/waste/detail/style.scss b/modules/item/front/waste/detail/style.scss
deleted file mode 100644
index 55a6eb2ef..000000000
--- a/modules/item/front/waste/detail/style.scss
+++ /dev/null
@@ -1,25 +0,0 @@
-@import "variables";
-
-vn-item-waste {
- .header {
- margin-bottom: 16px;
- text-transform: uppercase;
- font-size: 1.25rem;
- line-height: 1;
- padding: 7px;
- padding-bottom: 7px;
- padding-bottom: 4px;
- font-weight: lighter;
- background-color: #fde6ca;
- border-bottom: 1px solid #f7931e;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
-
- vn-table vn-th.waste-family,
- vn-table vn-td.waste-family {
- max-width: 64px;
- width: 64px
- }
-}
\ No newline at end of file
diff --git a/modules/item/front/waste/index/index.html b/modules/item/front/waste/index/index.html
index f1475c1b3..7fb3b870e 100644
--- a/modules/item/front/waste/index/index.html
+++ b/modules/item/front/waste/index/index.html
@@ -1,49 +1,2 @@
-
-
-
-
-
-
-
- Buyer
- Family
- Percentage
- Dwindle
- Total
-
-
-
-
-
- {{::detail.buyer}}
- {{::detail.family}}
- {{::(detail.percentage / 100) | percentage: 2}}
- {{::detail.dwindle | currency: 'EUR'}}
- {{::detail.total | currency: 'EUR'}}
-
-
-
-
-
-
-
- {{::waste.family}}
- {{::(waste.percentage / 100) | percentage: 2}}
- {{::waste.dwindle | currency: 'EUR'}}
- {{::waste.total | currency: 'EUR'}}
-
-
-
-
-
-
+
+
diff --git a/modules/item/front/waste/index/index.js b/modules/item/front/waste/index/index.js
index b11f54b08..86d9d3778 100644
--- a/modules/item/front/waste/index/index.js
+++ b/modules/item/front/waste/index/index.js
@@ -5,27 +5,11 @@ import './style.scss';
export default class Controller extends Section {
constructor($element, $) {
super($element, $);
-
- this.getWasteConfig();
}
- getWasteConfig() {
- return this.wasteConfig = JSON.parse(localStorage.getItem('wasteConfig')) || {};
- }
-
- setWasteConfig() {
- localStorage.setItem('wasteConfig', JSON.stringify(this.wasteConfig));
- }
-
- toggleHidePanel(detail) {
- if (!this.wasteConfig[detail.buyer]) {
- this.wasteConfig[detail.buyer] = {
- hidden: true
- };
- } else
- this.wasteConfig[detail.buyer].hidden = !this.wasteConfig[detail.buyer].hidden;
-
- this.setWasteConfig();
+ async $onInit() {
+ this.$state.go('item.index');
+ window.location.href = 'https://grafana.verdnatura.es/d/TTNXQAxVk';
}
}
diff --git a/modules/item/front/waste/index/index.spec.js b/modules/item/front/waste/index/index.spec.js
deleted file mode 100644
index fd7332f68..000000000
--- a/modules/item/front/waste/index/index.spec.js
+++ /dev/null
@@ -1,53 +0,0 @@
-import './index.js';
-import crudModel from 'core/mocks/crud-model';
-
-describe('Item', () => {
- describe('Component vnItemWasteIndex', () => {
- let $scope;
- let controller;
-
- beforeEach(ngModule('item'));
-
- beforeEach(inject(($componentController, $rootScope) => {
- $scope = $rootScope.$new();
- $scope.model = crudModel;
- const $element = angular.element('');
- controller = $componentController('vnItemWasteIndex', {$element, $scope});
- }));
-
- describe('getWasteConfig / setWasteConfig', () => {
- it('should return the local storage wasteConfig', () => {
- const result = controller.getWasteConfig();
-
- expect(result).toEqual({});
- });
-
- it('should set and return the local storage wasteConfig', () => {
- controller.wasteConfig = {salesPerson: {hidden: true}};
- controller.setWasteConfig();
-
- const result = controller.getWasteConfig();
-
- expect(result).toEqual(controller.wasteConfig);
- });
- });
-
- describe('toggleHidePanel()', () => {
- it('should make details hidden by default', () => {
- controller.wasteConfig = {};
-
- controller.toggleHidePanel({buyer: 'salesPerson'});
-
- expect(controller.wasteConfig.salesPerson.hidden).toEqual(true);
- });
-
- it('should toggle hidden false', () => {
- controller.wasteConfig = {salesPerson: {hidden: true}};
-
- controller.toggleHidePanel({buyer: 'salesPerson'});
-
- expect(controller.wasteConfig.salesPerson.hidden).toEqual(false);
- });
- });
- });
-});
diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js
index 693ae122f..301e4ac35 100644
--- a/modules/monitor/back/methods/sales-monitor/salesFilter.js
+++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js
@@ -162,61 +162,69 @@ module.exports = Self => {
const stmts = [];
let stmt;
-
- stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.filter');
-
+
stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`);
stmts.push(`SET SESSION optimizer_search_depth = 0`);
- stmt = new ParameterizedSQL(
- `CREATE TEMPORARY TABLE tmp.filter
+ stmt = new ParameterizedSQL(`
+ CREATE OR REPLACE TEMPORARY TABLE tmp.filter
(PRIMARY KEY (id))
ENGINE = MEMORY
- SELECT
- t.id,
- t.shipped,
- CAST(DATE(t.shipped) AS CHAR) AS shippedDate,
- t.nickname,
- t.refFk,
- t.routeFk,
- t.warehouseFk,
- t.clientFk,
- t.totalWithoutVat,
- t.totalWithVat,
- io.id AS invoiceOutId,
- a.provinceFk,
- p.name AS province,
- w.name AS warehouse,
- am.name AS agencyMode,
- am.id AS agencyModeFk,
- st.name AS state,
- wk.lastName AS salesPerson,
- ts.stateFk AS stateFk,
- ts.alertLevel AS alertLevel,
- ts.code AS alertLevelCode,
- u.name AS userName,
- c.salesPersonFk,
- c.credit,
- z.hour AS zoneLanding,
- z.name AS zoneName,
- z.id AS zoneFk,
- st.classColor,
- TIME_FORMAT(t.shipped, '%H:%i') AS preparationHour,
- TIME_FORMAT(z.hour, '%H:%i') AS theoreticalhour,
- TIME_FORMAT(zed.etc, '%H:%i') AS practicalHour
- FROM ticket t
- LEFT JOIN invoiceOut io ON t.refFk = io.ref
- LEFT JOIN zone z ON z.id = t.zoneFk
- LEFT JOIN address a ON a.id = t.addressFk
- LEFT JOIN province p ON p.id = a.provinceFk
- LEFT JOIN warehouse w ON w.id = t.warehouseFk
- LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
- LEFT JOIN ticketState ts ON ts.ticketFk = t.id
- LEFT JOIN state st ON st.id = ts.stateFk
- LEFT JOIN client c ON c.id = t.clientFk
- LEFT JOIN worker wk ON wk.id = c.salesPersonFk
- LEFT JOIN account.user u ON u.id = wk.id
- LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`);
+ SELECT t.id,
+ t.shipped,
+ CAST(DATE(t.shipped) AS CHAR) shippedDate,
+ t.nickname,
+ t.refFk,
+ t.routeFk,
+ t.warehouseFk,
+ t.clientFk,
+ t.totalWithoutVat,
+ t.totalWithVat,
+ io.id invoiceOutId,
+ a.provinceFk,
+ p.name province,
+ w.name warehouse,
+ am.name agencyMode,
+ am.id agencyModeFk,
+ st.name state,
+ wk.lastName salesPerson,
+ ts.stateFk stateFk,
+ ts.alertLevel alertLevel,
+ ts.code alertLevelCode,
+ u.name userName,
+ c.salesPersonFk,
+ c.credit,
+ z.hour zoneLanding,
+ z.name zoneName,
+ z.id zoneFk,
+ st.classColor,
+ TIME_FORMAT(t.shipped, '%H:%i') preparationHour,
+ TIME_FORMAT(z.hour, '%H:%i') theoreticalhour,
+ TIME_FORMAT(zed.etc, '%H:%i') practicalHour
+ FROM ticket t
+ LEFT JOIN invoiceOut io ON t.refFk = io.ref
+ LEFT JOIN zone z ON z.id = t.zoneFk
+ LEFT JOIN address a ON a.id = t.addressFk
+ LEFT JOIN province p ON p.id = a.provinceFk
+ LEFT JOIN warehouse w ON w.id = t.warehouseFk
+ LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
+ LEFT JOIN ticketState ts ON ts.ticketFk = t.id
+ LEFT JOIN state st ON st.id = ts.stateFk
+ LEFT JOIN client c ON c.id = t.clientFk
+ LEFT JOIN worker wk ON wk.id = c.salesPersonFk
+ LEFT JOIN account.user u ON u.id = wk.id
+ LEFT JOIN (
+ SELECT zoneFk,
+ CAST(
+ IFNULL(zoneClosureHour, zoneHour) +
+ SUM(IF(hasToRecalcPrice, volume, 0)) * 60 /
+ GREATEST(IFNULL(m3, 0), IFNULL(minSpeed, 0))
+ AS time
+ ) etc
+ FROM zoneEstimatedDelivery
+ GROUP BY zoneFk
+ ) zed ON zed.zoneFk = t.zoneFk
+ `);
if (args.orderFk) {
stmt.merge({
diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js
index c3da7f08b..bdafd14e2 100644
--- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js
+++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js
@@ -151,7 +151,7 @@ describe('SalesMonitor salesFilter()', () => {
const result = await models.SalesMonitor.salesFilter(ctx, filter, options);
const firstRow = result[0];
- expect(result.length).toEqual(15);
+ expect(result.length).toEqual(12);
expect(firstRow.alertLevel).not.toEqual(0);
await tx.rollback();
diff --git a/modules/order/back/methods/order/catalogFilter.js b/modules/order/back/methods/order/catalogFilter.js
index 0d83f9f4a..ab1d7784e 100644
--- a/modules/order/back/methods/order/catalogFilter.js
+++ b/modules/order/back/methods/order/catalogFilter.js
@@ -50,7 +50,7 @@ module.exports = Self => {
stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.item');
stmt = new ParameterizedSQL(
- `CREATE TEMPORARY TABLE tmp.item
+ `CREATE TEMPORARY TABLE tmp.item
(PRIMARY KEY (itemFk)) ENGINE = MEMORY
SELECT DISTINCT
i.id AS itemFk,
@@ -92,45 +92,46 @@ module.exports = Self => {
// Calculate items
const order = await Self.findById(orderFk, null, myOptions);
stmts.push(new ParameterizedSQL(
- 'CALL vn.catalog_calculate(?, ?, ?)', [
+ 'CALL vn.catalog_calculate(?, ?, ?, ?)', [
order.landed,
order.address_id,
order.agency_id,
+ false
]
));
stmt = new ParameterizedSQL(`
- SELECT
- i.id,
- i.name,
- i.subName,
- i.image,
- i.tag5,
- i.value5,
- i.tag6,
- i.value6,
- i.tag7,
- i.value7,
- i.tag8,
- i.value8,
- i.stars,
- tci.price,
- tci.available,
- w.lastName AS lastName,
- w.firstName,
- tci.priceKg,
- ink.hex
+ SELECT i.id,
+ i.name,
+ i.subName,
+ i.image,
+ i.tag5,
+ i.value5,
+ i.tag6,
+ i.value6,
+ i.tag7,
+ i.value7,
+ i.tag8,
+ i.value8,
+ tci.price,
+ tci.available,
+ w.lastName,
+ w.firstName,
+ tci.priceKg,
+ ink.hex,
+ i.minQuantity
FROM tmp.ticketCalculateItem tci
JOIN vn.item i ON i.id = tci.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.worker w on w.id = it.workerFk
- LEFT JOIN vn.ink ON ink.id = i.inkFk`);
+ LEFT JOIN vn.ink ON ink.id = i.inkFk
+ `);
// Apply order by tag
if (orderBy.isTag) {
stmt.merge({
sql: `
- LEFT JOIN vn.itemTag itg
+ LEFT JOIN vn.itemTag itg
LEFT JOIN vn.tag t ON t.id = itg.tagFk
ON itg.itemFk = tci.itemFk AND itg.tagFk = ?`,
params: [orderBy.field],
@@ -139,7 +140,7 @@ module.exports = Self => {
const way = orderBy.way == 'DESC' ? 'DESC' : 'ASC';
const tag = await Self.app.models.Tag.findById(orderBy.field, null, myOptions);
const orderSql = `
- ORDER BY
+ ORDER BY
itg.value IS NULL,
${tag.isQuantitative ? 'CAST(itg.value AS SIGNED)' : 'itg.value'}
${way}`;
@@ -157,7 +158,7 @@ module.exports = Self => {
// Apply item prices
const pricesIndex = stmts.push(
- `SELECT
+ `SELECT
tcp.itemFk,
tcp.grouping,
tcp.price,
diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js
index 44d8ccb10..592ed11e6 100644
--- a/modules/order/back/methods/order/filter.js
+++ b/modules/order/back/methods/order/filter.js
@@ -139,46 +139,65 @@ module.exports = Self => {
filter = mergeFilters(filter, {where});
const stmts = [];
let stmt;
+ stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`);
+ stmts.push(`SET SESSION optimizer_search_depth = 0`);
- stmt = new ParameterizedSQL(
- `CREATE OR REPLACE TEMPORARY TABLE tmp.filter
- (INDEX (id))
- ENGINE = MEMORY
- SELECT
- o.id,
- o.total,
- o.date_send landed,
- o.date_make created,
- o.customer_id clientFk,
- o.agency_id agencyModeFk,
- o.address_id addressFk,
- o.company_id companyFk,
- o.source_app sourceApp,
- o.confirmed isConfirmed,
- c.name clientName,
- c.salesPersonFk,
- u.nickname workerNickname,
- u.name name,
- co.code companyCode,
- zed.zoneFk,
- zed.hourTheoretical,
- zed.hourEffective,
- am.name AS agencyName
- FROM hedera.order o
- LEFT JOIN address a ON a.id = o.address_id
- LEFT JOIN agencyMode am ON am.id = o.agency_id
- LEFT JOIN client c ON c.id = o.customer_id
- LEFT JOIN worker wk ON wk.id = c.salesPersonFk
- LEFT JOIN account.user u ON u.id = wk.id
- LEFT JOIN company co ON co.id = o.company_id
- LEFT JOIN orderTicket ot ON ot.orderFk = o.id
- LEFT JOIN ticket t ON t.id = ot.ticketFk
- LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`);
+ stmt = new ParameterizedSQL(`
+ CREATE OR REPLACE TEMPORARY TABLE tmp.filter
+ (INDEX (id))
+ ENGINE = MEMORY
+ SELECT o.id,
+ o.total,
+ o.date_send landed,
+ o.date_make created,
+ o.customer_id clientFk,
+ o.agency_id agencyModeFk,
+ o.address_id addressFk,
+ o.company_id companyFk,
+ o.source_app sourceApp,
+ o.confirmed isConfirmed,
+ c.name clientName,
+ c.salesPersonFk,
+ u.nickname workerNickname,
+ u.name name,
+ co.code companyCode,
+ zed.zoneFk,
+ zed.hourTheoretical,
+ zed.hourEffective,
+ am.name agencyName
+ FROM hedera.order o
+ LEFT JOIN address a ON a.id = o.address_id
+ LEFT JOIN agencyMode am ON am.id = o.agency_id
+ LEFT JOIN client c ON c.id = o.customer_id
+ LEFT JOIN worker wk ON wk.id = c.salesPersonFk
+ LEFT JOIN account.user u ON u.id = wk.id
+ LEFT JOIN company co ON co.id = o.company_id
+ LEFT JOIN orderTicket ot ON ot.orderFk = o.id
+ LEFT JOIN ticket t ON t.id = ot.ticketFk
+ LEFT JOIN (
+ SELECT zoneFk,
+ CAST(
+ util.VN_CURDATE() +
+ INTERVAL HOUR(IFNULL(zoneClosureHour, zoneHour)) * 60 +
+ MINUTE(IFNULL(zoneClosureHour, zoneHour)) MINUTE
+ AS time
+ ) hourTheoretical,
+ CAST(
+ IFNULL(zoneClosureHour, zoneHour) +
+ SUM(IF(hasToRecalcPrice, volume, 0)) * 60 /
+ GREATEST(IFNULL(m3, 0), IFNULL(minSpeed, 0))
+ AS time
+ ) hourEffective
+ FROM zoneEstimatedDelivery
+ GROUP BY zoneFk
+ ) zed ON zed.zoneFk = t.zoneFk
+ `);
stmt.merge(conn.makeWhere(filter.where));
stmt.merge(`GROUP BY id`);
stmt.merge(conn.makePagination(filter));
stmts.push(stmt);
+ stmts.push(`SET SESSION optimizer_search_depth = @_optimizer_search_depth`);
stmt = new ParameterizedSQL(`SELECT * FROM tmp.filter`);
stmt.merge(conn.makeOrderBy(filter.order));
diff --git a/modules/order/back/methods/order/getItemTypeAvailable.js b/modules/order/back/methods/order/getItemTypeAvailable.js
index b62adebb5..b84863953 100644
--- a/modules/order/back/methods/order/getItemTypeAvailable.js
+++ b/modules/order/back/methods/order/getItemTypeAvailable.js
@@ -64,10 +64,11 @@ module.exports = Self => {
stmts.push(stmt);
stmt = new ParameterizedSQL(
- 'CALL vn.catalog_calculate(?, ?, ?)', [
+ 'CALL vn.catalog_calculate(?, ?, ?,?)', [
order.landed,
order.addressFk,
order.agencyModeFk,
+ false
]
);
stmts.push(stmt);
diff --git a/modules/order/back/methods/order/isEditable.js b/modules/order/back/methods/order/isEditable.js
index 4ef76c11f..3fd2f993c 100644
--- a/modules/order/back/methods/order/isEditable.js
+++ b/modules/order/back/methods/order/isEditable.js
@@ -29,17 +29,11 @@ module.exports = Self => {
where: {id: orderId},
fields: ['isConfirmed', 'clientFk'],
include: [
- {relation: 'client',
- scope: {
- include: {
- relation: 'type'
- }
- }
- }
+ {relation: 'client'}
]
}, myOptions);
- if (exists && exists.client().type().code !== 'normal')
+ if (exists && exists.client().typeFk !== 'normal')
return true;
if (!exists || exists.isConfirmed === 1)
diff --git a/modules/order/back/methods/order/new.js b/modules/order/back/methods/order/new.js
index d65b18e12..2aad27c9a 100644
--- a/modules/order/back/methods/order/new.js
+++ b/modules/order/back/methods/order/new.js
@@ -49,17 +49,12 @@ module.exports = Self => {
where: {id: addressId},
fields: ['clientFk'],
include: [
- {relation: 'client',
- scope: {
- include: {
- relation: 'type'
- }
- }
+ {relation: 'client'
}
]
}, myOptions);
- if (address.client().type().code === 'normal') {
+ if (address.client().typeFk === 'normal') {
if (!address.client().isActive)
throw new UserError(`You can't create an order for an inactive client`);
}
diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html
index fca728855..081ce05a0 100644
--- a/modules/order/front/catalog-view/index.html
+++ b/modules/order/front/catalog-view/index.html
@@ -8,12 +8,12 @@
';
+ // Save tickets on a list of failed ids
+ failedtickets.push({
+ id: ticket.id,
+ stacktrace: error,
+ });
+ }
+ }
- for (const ticket of failedtickets) {
- body += `Ticket: ${ticket.id}
- ${ticket.stacktrace}
`;
- }
+ // Send email with failed tickets
+ if (failedtickets.length > 0) {
+ let body = 'This following tickets have failed:
';
- smtp.send({
- to: config.app.reportEmail,
- subject: '[API] Nightly ticket closure report',
- html: body
- });
- }
+ for (const ticket of failedtickets) {
+ body += `Ticket: ${ticket.id}
+ ${ticket.stacktrace}
`;
+ }
- async function invalidEmail(ticket) {
- await Self.rawSql(`UPDATE client SET email = NULL WHERE id = ?`, [
- ticket.clientFk
- ], {userId});
+ smtp.send({
+ to: config.app.reportEmail,
+ subject: '[API] Nightly ticket closure report',
+ html: body,
+ }).catch(err => console.error(err));
+ }
- const oldInstance = `{"email": "${ticket.recipient}"}`;
- const newInstance = `{"email": ""}`;
- await Self.rawSql(`
- INSERT INTO clientLog (originFk, userFk, action, changedModel, oldInstance, newInstance)
- VALUES (?, NULL, 'UPDATE', 'Client', ?, ?)`, [
- ticket.clientFk,
- oldInstance,
- newInstance
- ], {userId});
+ async function invalidEmail(ticket) {
+ await Self.rawSql(
+ `UPDATE client SET email = NULL WHERE id = ?`,
+ [ticket.clientFk],
+ {userId},
+ );
- const body = `No se ha podido enviar el albarán ${ticket.id}
- al cliente ${ticket.clientFk} - ${ticket.clientName}
- porque la dirección de email "${ticket.recipient}" no es correcta
- o no está disponible.
- Para evitar que se repita este error, se ha eliminado la dirección de email de la ficha del cliente.
- Actualiza la dirección de email con una correcta.`;
+ const oldInstance = `{"email": "${ticket.recipient}"}`;
+ const newInstance = `{"email": ""}`;
+ await Self.rawSql(
+ `
+ INSERT INTO clientLog (originFk, userFk, action, changedModel, oldInstance, newInstance)
+ VALUES (?, NULL, 'UPDATE', 'Client', ?, ?)`,
+ [ticket.clientFk, oldInstance, newInstance],
+ {userId},
+ );
- smtp.send({
- to: ticket.salesPersonEmail,
- subject: 'No se ha podido enviar el albarán',
- html: body
- });
- }
+ const body = `No se ha podido enviar el albarán ${ticket.id}
+ al cliente ${ticket.clientFk} - ${ticket.clientName}
+ porque la dirección de email "${ticket.recipient}" no es correcta
+ o no está disponible.
-
\ No newline at end of file
+
diff --git a/print/templates/email/cmr/assets/css/import.js b/print/templates/email/cmr/assets/css/import.js
new file mode 100644
index 000000000..4b4bb7086
--- /dev/null
+++ b/print/templates/email/cmr/assets/css/import.js
@@ -0,0 +1,11 @@
+const Stylesheet = require(`vn-print/core/stylesheet`);
+
+const path = require('path');
+const vnPrintPath = path.resolve('print');
+
+module.exports = new Stylesheet([
+ `${vnPrintPath}/common/css/spacing.css`,
+ `${vnPrintPath}/common/css/misc.css`,
+ `${vnPrintPath}/common/css/layout.css`,
+ `${vnPrintPath}/common/css/email.css`])
+ .mergeStyles();
diff --git a/print/templates/email/cmr/attachments.json b/print/templates/email/cmr/attachments.json
new file mode 100644
index 000000000..40845566d
--- /dev/null
+++ b/print/templates/email/cmr/attachments.json
@@ -0,0 +1,6 @@
+[
+ {
+ "filename": "cmr.pdf",
+ "component": "cmr"
+ }
+]
\ No newline at end of file
diff --git a/print/templates/email/cmr/cmr.html b/print/templates/email/cmr/cmr.html
new file mode 100644
index 000000000..2f6d9e346
--- /dev/null
+++ b/print/templates/email/cmr/cmr.html
@@ -0,0 +1,12 @@
+
+
+
+
{{ $t('title') }}
+
{{$t('dear')}},
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/print/templates/email/cmr/cmr.js b/print/templates/email/cmr/cmr.js
new file mode 100755
index 000000000..104e4d2fe
--- /dev/null
+++ b/print/templates/email/cmr/cmr.js
@@ -0,0 +1,22 @@
+const Component = require(`vn-print/core/component`);
+const emailBody = new Component('email-body');
+module.exports = {
+ name: 'cmr',
+ async serverPrefetch() {
+ this.cmr = await this.fetchCmr(this.ticketId);
+ },
+ methods: {
+ fetchCmr(ticketId) {
+ return this.findOneFromDef('cmr', [ticketId]);
+ },
+ },
+ components: {
+ 'email-body': emailBody.build(),
+ },
+ props: {
+ ticketId: {
+ type: Number,
+ required: true
+ }
+ }
+};
diff --git a/print/templates/email/cmr/locale/en.yml b/print/templates/email/cmr/locale/en.yml
new file mode 100644
index 000000000..fbfca9aaa
--- /dev/null
+++ b/print/templates/email/cmr/locale/en.yml
@@ -0,0 +1,9 @@
+subject: Your CMR
+title: Your CMR
+dear: Dear Customer
+description: The CMR {0} corresponding to order {1} is now available.
+ You can download it by clicking on the attachment in this email.
+poll: If you wish, you can respond to our satisfaction survey to
+ help us provide better service. Your opinion is very important to us!
+help: If you have any doubts, do not hesitate to ask, we are here to serve you!
+conclusion: Thank you for your attention!
\ No newline at end of file
diff --git a/print/templates/email/cmr/locale/es.yml b/print/templates/email/cmr/locale/es.yml
new file mode 100644
index 000000000..4c384edf5
--- /dev/null
+++ b/print/templates/email/cmr/locale/es.yml
@@ -0,0 +1,9 @@
+subject: Tu CMR
+title: Tu CMR
+dear: Estimado cliente
+description: Ya está disponible el CMR {0} correspondiente al pedido {1}.
+ Puedes descargarla haciendo clic en el adjunto de este correo.
+poll: Si lo deseas, puedes responder a nuestra encuesta de satisfacción para
+ ayudarnos a prestar un mejor servicio. ¡Tu opinión es muy importante para nosotros!
+help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos para atenderte!
+conclusion: ¡Gracias por tu atención!
\ No newline at end of file
diff --git a/print/templates/email/cmr/locale/fr.yml b/print/templates/email/cmr/locale/fr.yml
new file mode 100644
index 000000000..c715f4433
--- /dev/null
+++ b/print/templates/email/cmr/locale/fr.yml
@@ -0,0 +1,9 @@
+subject: Votre CMR
+title: Votre CMR
+dear: Cher client
+description: Le CMR {0} correspondant à la commande {1} est maintenant disponible.
+ Vous pouvez le télécharger en cliquant sur la pièce jointe de cet e-mail.
+poll: Si vous le souhaitez, vous pouvez répondre à notre enquête de satisfaction pour
+ nous aider à améliorer notre service. Votre avis est très important pour nous !
+help: Si vous avez des doutes, n'hésitez pas à nous consulter, nous sommes là pour vous servir !
+conclusion: Merci de votre attention !
\ No newline at end of file
diff --git a/print/templates/email/cmr/locale/pt.yml b/print/templates/email/cmr/locale/pt.yml
new file mode 100644
index 000000000..74b2b2e7a
--- /dev/null
+++ b/print/templates/email/cmr/locale/pt.yml
@@ -0,0 +1,9 @@
+subject: Seu CMR
+title: Seu CMR
+dear: Caro cliente
+description: O CMR {0} correspondente ao pedido {1} já está disponível.
+ Você pode baixá-lo clicando no anexo deste e-mail.
+poll: Se desejar, pode responder à nossa pesquisa de satisfação para
+ nos ajudar a oferecer um serviço melhor. Sua opinião é muito importante para nós!
+help: Se tiver alguma dúvida, não hesite em nos consultar, estamos aqui para atendê-lo!
+conclusion: Obrigado pela sua atenção!
\ No newline at end of file
diff --git a/print/templates/email/cmr/sql/cmr.sql b/print/templates/email/cmr/sql/cmr.sql
new file mode 100644
index 000000000..f1c0904d8
--- /dev/null
+++ b/print/templates/email/cmr/sql/cmr.sql
@@ -0,0 +1,5 @@
+SELECT t.id ticketFk,
+ c.id
+ FROM ticket t
+ JOIN cmr c ON c.id = t.cmrFk
+ WHERE t.id = ?
diff --git a/print/templates/email/invoice-electronic/invoice-electronic.js b/print/templates/email/invoice-electronic/invoice-electronic.js
index 2e1e739ac..1ec6d1374 100644
--- a/print/templates/email/invoice-electronic/invoice-electronic.js
+++ b/print/templates/email/invoice-electronic/invoice-electronic.js
@@ -10,7 +10,7 @@ module.exports = {
required: true
},
ticketId: {
- type: [Number],
+ type: [String],
required: true
},
url: {
diff --git a/print/templates/email/letter-debtor-nd/letter-debtor-nd.html b/print/templates/email/letter-debtor-nd/letter-debtor-nd.html
index 44a34a9b4..01bab7939 100644
--- a/print/templates/email/letter-debtor-nd/letter-debtor-nd.html
+++ b/print/templates/email/letter-debtor-nd/letter-debtor-nd.html
@@ -45,4 +45,4 @@
-
\ No newline at end of file
+
diff --git a/print/templates/email/letter-debtor-nd/letter-debtor-nd.js b/print/templates/email/letter-debtor-nd/letter-debtor-nd.js
index 54ed9fed6..41b6f1af8 100755
--- a/print/templates/email/letter-debtor-nd/letter-debtor-nd.js
+++ b/print/templates/email/letter-debtor-nd/letter-debtor-nd.js
@@ -1,14 +1,33 @@
const Component = require(`vn-print/core/component`);
const emailBody = new Component('email-body');
const attachment = new Component('attachment');
+const db = require('../../../core/database');
module.exports = {
name: 'letter-debtor-nd',
async serverPrefetch() {
- this.debtor = await this.fetchDebtor(this.id, this.companyId);
-
- if (!this.debtor)
- throw new Error('Something went wrong');
+ this.debtor = await db.findOne(`
+ SELECT sa.id,
+ sa.iban,
+ be.name bankName,
+ sa.countryFk,
+ c.countryFk
+ FROM supplierAccount sa
+ JOIN bankEntity be ON sa.bankEntityFk = be.id
+ LEFT JOIN company co ON co.supplierAccountFk = sa.id
+ JOIN client c ON c.countryFk = sa.countryFk
+ WHERE c.id = ?;
+ `, [this.id]);
+ if (!this.debtor) {
+ this.debtor = await db.findOne(`
+ SELECT sa.iban,
+ be.name bankName
+ FROM supplierAccount sa
+ JOIN bankEntity be ON sa.bankEntityFk = be.id
+ JOIN company co ON co.supplierAccountFk = sa.id
+ WHERE co.id = ?;
+ `, [this.companyId]);
+ }
},
data() {
return {
diff --git a/print/templates/email/letter-debtor-nd/locale/en.yml b/print/templates/email/letter-debtor-nd/locale/en.yml
new file mode 100644
index 000000000..9fb334339
--- /dev/null
+++ b/print/templates/email/letter-debtor-nd/locale/en.yml
@@ -0,0 +1,21 @@
+subject: Reminder of Outstanding Balance Notice
+title: Reminder Notice
+sections:
+ introduction:
+ title: Dear Customer
+ description: We are writing to you once again to inform you that your debt with our company remains unpaid, as you can verify in the attached statement.
+ terms: Since the agreed payment deadlines have significantly passed, there should be no further delay in settling the outstanding amount.
+ payMethod:
+ description: To do so, you have the following payment options
+ options:
+ - Online payment through our website.
+ - Deposit or transfer to the account number provided at the bottom of this letter, indicating your customer number.
+ legalAction:
+ description: If this payment reminder is not heeded, we will be compelled to initiate the necessary legal actions, which may include
+ options:
+ - Inclusion in negative credit and financial solvency records.
+ - Legal proceedings.
+ - Debt assignment to a debt collection agency.
+contactPhone: For inquiries, you can reach us at 96 324 21 00.
+conclusion: We look forward to hearing from you. Thank you for your attention.
+transferAccount: Bank Transfer Details
diff --git a/print/templates/email/letter-debtor-nd/locale/fr.yml b/print/templates/email/letter-debtor-nd/locale/fr.yml
new file mode 100644
index 000000000..3ea3501d7
--- /dev/null
+++ b/print/templates/email/letter-debtor-nd/locale/fr.yml
@@ -0,0 +1,26 @@
+subject: Réitération de l'avis de solde débiteur
+title: Avis réitéré
+sections:
+ introduction:
+ title: Cher client
+ description: Nous vous écrivons à nouveau pour vous informer qu'il est toujours en attente
+ votre dette envers notre société, comme vous pouvez le voir dans le relevé ci-joint.
+ terms: Étant donné que les délais de paiement convenus sont largement dépassés, il n'est pas approprié
+ retard plus important dans le règlement du montant dû.
+ payMethod:
+ description: Pour cela, vous disposez des modes de paiement suivants
+ options:
+ - Paiement en ligne depuis notre site internet.
+ - Revenu ou virement sur le numéro de compte que nous détaillons en bas de ce courrier,
+ indiquant le numéro de client.
+ legalAction:
+ description: Si cette obligation de paiement n'est pas remplie, nous serons contraints de
+ d'engager les actions judiciaires qui se déroulent, parmi lesquelles
+ options:
+ - Inclusion dans les dossiers négatifs sur la solvabilité financière et le crédit.
+ - Réclamation judiciaire.
+ - Cession de créance à une société de gestion de recouvrement.
+contactPhone: Pour toute demande, vous pouvez nous contacter au 96
+ 324 21 00.
+conclusion: En attente de vos nouvelles. Merci pour ton attention.
+transferAccount: Données pour virement bancaire
\ No newline at end of file
diff --git a/print/templates/email/letter-debtor-nd/locale/pt.yml b/print/templates/email/letter-debtor-nd/locale/pt.yml
new file mode 100644
index 000000000..f4acbd1d3
--- /dev/null
+++ b/print/templates/email/letter-debtor-nd/locale/pt.yml
@@ -0,0 +1,26 @@
+subject: Reiteração de aviso de saldo devedor
+title: Aviso reiterado
+sections:
+ introduction:
+ title: Estimado cliente
+ description: Estamos escrevendo para você novamente para informar que ainda está pendente
+ sua dívida para com nossa empresa, conforme demonstrativo anexo.
+ terms: Dado que os prazos de pagamento acordados são largamente excedidos, não é adequado
+ maior atraso na liquidação do valor devido.
+ payMethod:
+ description: Para isso você tem as seguintes formas de pagamento
+ options:
+ - Pagamento online em nosso site.
+ - Renda ou transferência para o número da conta que detalhamos no final desta carta,
+ indicando o número do cliente.
+ legalAction:
+ description: Se esta obrigação de pagamento não for cumprida, seremos obrigados a
+ para iniciar as ações legais que procedem, entre as quais estão
+ options:
+ - Inclusão em processos negativos de solvência financeira e de crédito.
+ - Reivindicação judicial.
+ - Cessão de dívida a uma empresa de gestão de cobranças.
+contactPhone: Para consultas, você pode entrar em contato conosco em 96
+ 324 21 00.
+conclusion: Aguardando suas notícias. Agradecimentos para sua atenção.
+transferAccount: Dados para transferência bancária
\ No newline at end of file
diff --git a/print/templates/email/letter-debtor-nd/sql/client.sql b/print/templates/email/letter-debtor-nd/sql/client.sql
index d5da5d0d5..013a3b7d6 100644
--- a/print/templates/email/letter-debtor-nd/sql/client.sql
+++ b/print/templates/email/letter-debtor-nd/sql/client.sql
@@ -1,10 +1,9 @@
-SELECT
- c.dueDay,
- c.iban,
- sa.iban,
- be.name AS bankName
-FROM client c
- JOIN company AS cny
- JOIN supplierAccount AS sa ON sa.id = cny.supplierAccountFk
- JOIN bankEntity be ON be.id = sa.bankEntityFk
-WHERE c.id = ? AND cny.id = ?
\ No newline at end of file
+SELECT c.dueDay,
+ sa.iban,
+ be.name bankName
+ FROM client c
+ JOIN supplierAccount sa ON sa.id = cny.supplierAccountFk
+ JOIN bankEntity be ON be.id = sa.bankEntityFk
+ JOIN company cny
+ WHERE c.id = ?
+ AND cny.id = ?
diff --git a/print/templates/email/letter-debtor-st/letter-debtor-st.html b/print/templates/email/letter-debtor-st/letter-debtor-st.html
index 36f300c98..6679567c0 100644
--- a/print/templates/email/letter-debtor-st/letter-debtor-st.html
+++ b/print/templates/email/letter-debtor-st/letter-debtor-st.html
@@ -28,4 +28,4 @@
-
\ No newline at end of file
+
diff --git a/print/templates/email/letter-debtor-st/letter-debtor-st.js b/print/templates/email/letter-debtor-st/letter-debtor-st.js
index e0a690f81..b168f969f 100755
--- a/print/templates/email/letter-debtor-st/letter-debtor-st.js
+++ b/print/templates/email/letter-debtor-st/letter-debtor-st.js
@@ -1,14 +1,33 @@
const Component = require(`vn-print/core/component`);
const emailBody = new Component('email-body');
const attachment = new Component('attachment');
+const db = require('../../../core/database');
module.exports = {
name: 'letter-debtor-st',
async serverPrefetch() {
- this.debtor = await this.fetchDebtor(this.id, this.companyId);
-
- if (!this.debtor)
- throw new Error('Something went wrong');
+ this.debtor = await db.findOne(`
+ SELECT sa.id,
+ sa.iban,
+ be.name bankName,
+ sa.countryFk,
+ c.countryFk
+ FROM supplierAccount sa
+ JOIN bankEntity be ON sa.bankEntityFk = be.id
+ LEFT JOIN company co ON co.supplierAccountFk = sa.id
+ JOIN client c ON c.countryFk = sa.countryFk
+ WHERE c.id = ?;
+ `, [this.id]);
+ if (!this.debtor) {
+ this.debtor = await db.findOne(`
+ SELECT sa.iban,
+ be.name bankName
+ FROM supplierAccount sa
+ JOIN bankEntity be ON sa.bankEntityFk = be.id
+ JOIN company co ON co.supplierAccountFk = sa.id
+ WHERE co.id = ?;
+ `, [this.companyId]);
+ }
},
data() {
return {
diff --git a/print/templates/email/letter-debtor-st/locale/en.yml b/print/templates/email/letter-debtor-st/locale/en.yml
new file mode 100644
index 000000000..42b3bb504
--- /dev/null
+++ b/print/templates/email/letter-debtor-st/locale/en.yml
@@ -0,0 +1,11 @@
+subject: Initial Notice for Outstanding Balance
+title: Initial Notice for Outstanding Balance
+sections:
+ introduction:
+ title: Dear Customer
+ description: Through this letter, we would like to inform you that, according to our accounting records, your account has an outstanding balance that needs to be settled.
+checkExtract: We kindly request you to verify that the attached statement corresponds to the information you have. Our administration department will be happy to clarify any questions you may have and provide any documents you may request.
+checkValidData: If, upon reviewing the provided information, everything appears to be accurate, we kindly ask you to proceed with rectifying your situation.
+payMethod: If you prefer not to visit our offices in person, you can make the payment through a bank transfer to the account listed at the bottom of this communication, indicating your customer number. Alternatively, you can make the payment online through our website.
+conclusion: We sincerely appreciate your kind cooperation.
+transferAccount: Bank Transfer Details
diff --git a/print/templates/email/letter-debtor-st/sql/client.sql b/print/templates/email/letter-debtor-st/sql/client.sql
index d5da5d0d5..013a3b7d6 100644
--- a/print/templates/email/letter-debtor-st/sql/client.sql
+++ b/print/templates/email/letter-debtor-st/sql/client.sql
@@ -1,10 +1,9 @@
-SELECT
- c.dueDay,
- c.iban,
- sa.iban,
- be.name AS bankName
-FROM client c
- JOIN company AS cny
- JOIN supplierAccount AS sa ON sa.id = cny.supplierAccountFk
- JOIN bankEntity be ON be.id = sa.bankEntityFk
-WHERE c.id = ? AND cny.id = ?
\ No newline at end of file
+SELECT c.dueDay,
+ sa.iban,
+ be.name bankName
+ FROM client c
+ JOIN supplierAccount sa ON sa.id = cny.supplierAccountFk
+ JOIN bankEntity be ON be.id = sa.bankEntityFk
+ JOIN company cny
+ WHERE c.id = ?
+ AND cny.id = ?
diff --git a/print/templates/email/zone-included/assets/css/import.js b/print/templates/email/zone-included/assets/css/import.js
new file mode 100644
index 000000000..4b4bb7086
--- /dev/null
+++ b/print/templates/email/zone-included/assets/css/import.js
@@ -0,0 +1,11 @@
+const Stylesheet = require(`vn-print/core/stylesheet`);
+
+const path = require('path');
+const vnPrintPath = path.resolve('print');
+
+module.exports = new Stylesheet([
+ `${vnPrintPath}/common/css/spacing.css`,
+ `${vnPrintPath}/common/css/misc.css`,
+ `${vnPrintPath}/common/css/layout.css`,
+ `${vnPrintPath}/common/css/email.css`])
+ .mergeStyles();
diff --git a/print/templates/email/zone-included/locale/es.yml b/print/templates/email/zone-included/locale/es.yml
new file mode 100644
index 000000000..cb35a55cc
--- /dev/null
+++ b/print/templates/email/zone-included/locale/es.yml
@@ -0,0 +1,7 @@
+subject: Colisiones en zonas
+title: "La zona {0} y localización {1} ha sido registrada en más de un sitio"
+postalCode: C. Postal
+zoneFk: Número de zona
+price: Precio
+zone: Zona
+warehouse: Almacén
diff --git a/db/changes/232401/.gitkeep b/print/templates/email/zone-included/sql/zoneIncluded.sql
similarity index 100%
rename from db/changes/232401/.gitkeep
rename to print/templates/email/zone-included/sql/zoneIncluded.sql
diff --git a/print/templates/email/zone-included/zone-included.html b/print/templates/email/zone-included/zone-included.html
new file mode 100644
index 000000000..0484e0919
--- /dev/null
+++ b/print/templates/email/zone-included/zone-included.html
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+
+
+
diff --git a/print/templates/reports/collection-label/collection-label.js b/print/templates/reports/collection-label/collection-label.js
index d45ecb2bc..db2adeb34 100644
--- a/print/templates/reports/collection-label/collection-label.js
+++ b/print/templates/reports/collection-label/collection-label.js
@@ -20,7 +20,6 @@ module.exports = {
async serverPrefetch() {
let ticketIds;
const res = await this.rawSqlFromDef('tickets', [this.id]);
-
if (res.length) {
ticketIds = [];
for (const row of res)
diff --git a/print/templates/reports/collection-label/sql/labelsData.sql b/print/templates/reports/collection-label/sql/labelsData.sql
index fef692272..61990812d 100644
--- a/print/templates/reports/collection-label/sql/labelsData.sql
+++ b/print/templates/reports/collection-label/sql/labelsData.sql
@@ -7,14 +7,16 @@ SELECT c.itemPackingTypeFk code,
cc.code color,
t.clientFk,
CAST(SUM(sv.volume) AS DECIMAL(5, 2)) volume,
- MAX(i.`size`) `size`,
+ MAX(
+ IF(sgd.id, IFNULL(pc.itemPreviousDefaultSize, i.`size`), i.`size`)
+ ) `size`,
w.code workerCode,
TIME_FORMAT(t.shipped, '%H:%i') shippedHour,
TIME_FORMAT(zo.`hour`, '%H:%i') zoneHour,
DATE_FORMAT(t.shipped, '%d/%m/%y') shipped,
tt.labelCount,
t.nickName,
- COUNT(*) lineCount,
+ SUM(IF(sgd.id IS NULL, 1, 0)) + IF(sgd.id , 1, 0) lineCount,
rm.routeFk
FROM vn.ticket t
JOIN vn.ticketCollection tc ON tc.ticketFk = t.id
@@ -23,7 +25,7 @@ SELECT c.itemPackingTypeFk code,
AND cc.wagon = tc.wagon
AND cc.trainFk = c.trainFk
JOIN vn.sale s ON s.ticketFk = t.id
- LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id
+ LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
@@ -32,7 +34,9 @@ SELECT c.itemPackingTypeFk code,
LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id
LEFT JOIN vn.`zone` zo ON t.zoneFk = zo.id
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
- LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
+ LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
+ JOIN vn.productionConfig pc
WHERE t.id IN (?)
GROUP BY t.id
- ORDER BY cc.`code`;
\ No newline at end of file
+ ORDER BY cc.`code`
\ No newline at end of file
diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html
index 0be5a30f0..92dd1b126 100644
--- a/print/templates/reports/delivery-note/delivery-note.html
+++ b/print/templates/reports/delivery-note/delivery-note.html
@@ -117,7 +117,7 @@
diff --git a/print/templates/reports/driver-route/driver-route.js b/print/templates/reports/driver-route/driver-route.js
index c166e3809..bfe04f337 100755
--- a/print/templates/reports/driver-route/driver-route.js
+++ b/print/templates/reports/driver-route/driver-route.js
@@ -5,7 +5,6 @@ module.exports = {
mixins: [vnReport],
async serverPrefetch() {
let ids = this.id;
-
const hasMultipleRoutes = String(this.id).includes(',');
if (hasMultipleRoutes)
ids = this.id.split(',');
@@ -30,7 +29,7 @@ module.exports = {
},
props: {
id: {
- type: Number,
+ type: String,
required: true,
description: 'The route id'
}
diff --git a/print/templates/reports/driver-route/sql/routes.sql b/print/templates/reports/driver-route/sql/routes.sql
index 79bede5b2..9d2dd5c13 100644
--- a/print/templates/reports/driver-route/sql/routes.sql
+++ b/print/templates/reports/driver-route/sql/routes.sql
@@ -1,19 +1,18 @@
-SELECT
- r.id,
- r.m3,
- r.created,
- r.time,
- u.nickName userNickName,
- v.tradeMark vehicleTradeMark,
- v.model vehicleModel,
- v.numberPlate plateNumber,
- IFNULL(s.name, am.name) AS agencyName
-FROM route r
- LEFT JOIN vehicle v ON v.id = r.vehicleFk
- LEFT JOIN worker w ON w.id = r.workerFk
- LEFT JOIN account.user u ON u.id = w.id
- LEFT JOIN agencyMode am ON am.id = r.agencyModeFk
- LEFT JOIN agency a ON a.id = am.agencyFk
- LEFT JOIN supplierAgencyTerm sa ON sa.agencyFk = a.id
- LEFT JOIN supplier s ON s.id = sa.supplierFk
-WHERE r.id IN(?)
+SELECT r.id,
+ r.m3,
+ r.created,
+ r.time,
+ u.nickName userNickName,
+ v.tradeMark vehicleTradeMark,
+ v.model vehicleModel,
+ v.numberPlate plateNumber,
+ IFNULL(s.name, am.name) agencyName
+ FROM route r
+ LEFT JOIN vehicle v ON v.id = r.vehicleFk
+ LEFT JOIN worker w ON w.id = r.workerFk
+ LEFT JOIN account.user u ON u.id = w.id
+ LEFT JOIN agencyMode am ON am.id = r.agencyModeFk
+ LEFT JOIN agency a ON a.id = am.agencyFk
+ LEFT JOIN supplierAgencyTerm sa ON sa.agencyFk = a.id
+ LEFT JOIN supplier s ON s.id = sa.supplierFk
+ WHERE r.id IN(?)
diff --git a/print/templates/reports/driver-route/sql/tickets.sql b/print/templates/reports/driver-route/sql/tickets.sql
index 09e73819b..1ffb4d623 100644
--- a/print/templates/reports/driver-route/sql/tickets.sql
+++ b/print/templates/reports/driver-route/sql/tickets.sql
@@ -1,43 +1,42 @@
-SELECT
- t.nickname addressName,
- t.packages,
- t.priority,
- t.id,
- t.clientFk,
- t.companyFk,
- t.routeFk,
- if(a.phone, a.phone, c.phone) AS phone,
- if(a.mobile, a.mobile, c.mobile) AS mobile,
- wh.name warehouseName,
- a.city,
- a.street,
- a.postalCode,
- LPAD(a.id, 5, '0') AS addressFk,
- p.name province,
- 0 AS import,
- am.name ticketAgency,
- tob.description,
- u.nickName salesPersonName,
- ipkg.itemPackingTypes
-FROM route r
- LEFT JOIN ticket t ON t.routeFk = r.id
- LEFT JOIN address a ON a.id = t.addressFk
- LEFT JOIN client c ON c.id = t.clientFk
- LEFT JOIN worker w ON w.id = client_getSalesPerson(t.clientFk, CURDATE())
- LEFT JOIN account.user u ON u.id = w.id
- LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 3
- LEFT JOIN province p ON a.provinceFk = p.id
- LEFT JOIN warehouse wh ON wh.id = t.warehouseFk
- LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
- LEFT JOIN (
- SELECT t.id AS ticketFk,
- GROUP_CONCAT(DISTINCT(i.itemPackingTypeFk)) AS itemPackingTypes
- FROM route r
- JOIN ticket t ON t.routeFk = r.id
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- WHERE r.id IN (?)
- GROUP BY t.id
- ) ipkg ON ipkg.ticketFk = t.id
-WHERE r.id IN (?)
-ORDER BY t.priority, t.id;
\ No newline at end of file
+SELECT t.nickname addressName,
+ t.packages,
+ t.priority,
+ t.id,
+ t.clientFk,
+ t.companyFk,
+ t.routeFk,
+ if(a.phone, a.phone, c.phone) phone,
+ if(a.mobile, a.mobile, c.mobile) mobile,
+ wh.name warehouseName,
+ a.city,
+ a.street,
+ a.postalCode,
+ LPAD(a.id, 5, '0') addressFk,
+ p.name province,
+ 0 import,
+ am.name ticketAgency,
+ tob.description,
+ u.nickName salesPersonName,
+ ipkg.itemPackingTypes
+ FROM route r
+ JOIN ticket t ON t.routeFk = r.id
+ LEFT JOIN address a ON a.id = t.addressFk
+ LEFT JOIN client c ON c.id = t.clientFk
+ LEFT JOIN worker w ON w.id = client_getSalesPerson(t.clientFk, CURDATE())
+ LEFT JOIN account.user u ON u.id = w.id
+ LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 3
+ LEFT JOIN province p ON a.provinceFk = p.id
+ LEFT JOIN warehouse wh ON wh.id = t.warehouseFk
+ LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
+ LEFT JOIN (
+ SELECT t.id AS ticketFk,
+ GROUP_CONCAT(DISTINCT(i.itemPackingTypeFk)) AS itemPackingTypes
+ FROM route r
+ JOIN ticket t ON t.routeFk = r.id
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN item i ON i.id = s.itemFk
+ WHERE r.id IN (?)
+ GROUP BY t.id
+ ) ipkg ON ipkg.ticketFk = t.id
+ WHERE r.id IN (?)
+ ORDER BY t.priority, t.id;
\ No newline at end of file
diff --git a/print/templates/reports/expedition-pallet-label/assets/css/style.css b/print/templates/reports/expedition-pallet-label/assets/css/style.css
index bd7366486..178ce79d2 100644
--- a/print/templates/reports/expedition-pallet-label/assets/css/style.css
+++ b/print/templates/reports/expedition-pallet-label/assets/css/style.css
@@ -56,9 +56,6 @@ html {
margin-left: 35px;
float:left;
}
-#barcode{
- text-align: center;
-}
#right {
float: right;
margin-top: 20px;
diff --git a/print/templates/reports/expedition-pallet-label/expedition-pallet-label.html b/print/templates/reports/expedition-pallet-label/expedition-pallet-label.html
index 0cb25613e..a34755f91 100644
--- a/print/templates/reports/expedition-pallet-label/expedition-pallet-label.html
+++ b/print/templates/reports/expedition-pallet-label/expedition-pallet-label.html
@@ -9,7 +9,6 @@
-
diff --git a/print/templates/reports/expedition-pallet-label/expedition-pallet-label.js b/print/templates/reports/expedition-pallet-label/expedition-pallet-label.js
index bcd90418f..00f1f8ba1 100644
--- a/print/templates/reports/expedition-pallet-label/expedition-pallet-label.js
+++ b/print/templates/reports/expedition-pallet-label/expedition-pallet-label.js
@@ -39,19 +39,5 @@ module.exports = {
const data = String(id);
return qrcode.toDataURL(data, {margin: 0});
},
- getBarcode(id) {
- const xmlSerializer = new XMLSerializer();
- const document = new DOMImplementation().createDocument('http://www.w3.org/1999/xhtml', 'html', null);
- const svgNode = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
-
- jsBarcode(svgNode, id, {
- xmlDocument: document,
- format: 'code128',
- displayValue: false,
- width: 6,
- height: 90,
- });
- return xmlSerializer.serializeToString(svgNode);
- },
},
};
diff --git a/print/templates/reports/invoice-incoterms/invoice-incoterms.js b/print/templates/reports/invoice-incoterms/invoice-incoterms.js
index 2c183b6cc..cfe29169b 100755
--- a/print/templates/reports/invoice-incoterms/invoice-incoterms.js
+++ b/print/templates/reports/invoice-incoterms/invoice-incoterms.js
@@ -1,4 +1,5 @@
const vnReport = require('../../../core/mixins/vn-report.js');
+const UserError = require('vn-loopback/util/user-error');
module.exports = {
name: 'invoice-incoterms',
@@ -7,7 +8,10 @@ module.exports = {
this.invoice = await this.findOneFromDef('invoice', [this.reference]);
this.checkMainEntity(this.invoice);
this.client = await this.findOneFromDef('client', [this.reference]);
- this.incoterms = await this.findOneFromDef('incoterms', [this.reference, this.reference, this.reference]);
+ this.incoterms =
+ await this.findOneFromDef('incoterms', [this.reference, this.reference, this.reference, this.reference]);
+ if (!this.incoterms)
+ throw new UserError(`The address of the customer must have information about Incoterms and Customs Agent`);
},
props: {
reference: {
diff --git a/print/templates/reports/invoice-incoterms/sql/client.sql b/print/templates/reports/invoice-incoterms/sql/client.sql
index 3e66c15c9..f3734bcd9 100644
--- a/print/templates/reports/invoice-incoterms/sql/client.sql
+++ b/print/templates/reports/invoice-incoterms/sql/client.sql
@@ -1,13 +1,12 @@
-SELECT
- c.id,
- c.socialName,
- c.street AS postalAddress,
- IF (ios.taxAreaFk IS NOT NULL, CONCAT(cty.code, c.fi), c.fi) fi,
- CONCAT(c.postcode, ' - ', c.city) postcodeCity
-FROM vn.invoiceOut io
- JOIN vn.client c ON c.id = io.clientFk
- JOIN vn.country cty ON cty.id = c.countryFk
- LEFT JOIN vn.invoiceOutSerial ios ON ios.code = io.serial
- AND ios.taxAreaFk = 'CEE'
- LEFT JOIN ticket t ON t.refFk = io.ref
-WHERE t.refFk = ?
\ No newline at end of file
+SELECT c.id,
+ c.socialName,
+ c.street postalAddress,
+ IF (ios.taxAreaFk IS NOT NULL, CONCAT(cty.code, c.fi), c.fi) fi,
+ CONCAT(c.postcode, ' - ', c.city) postcodeCity
+ FROM vn.invoiceOut io
+ JOIN vn.client c ON c.id = io.clientFk
+ JOIN vn.country cty ON cty.id = c.countryFk
+ LEFT JOIN vn.invoiceOutSerial ios ON ios.code = io.serial
+ AND ios.taxAreaFk = 'CEE'
+ LEFT JOIN ticket t ON t.refFk = io.ref
+ WHERE t.refFk = ?
\ No newline at end of file
diff --git a/print/templates/reports/invoice-incoterms/sql/incoterms.sql b/print/templates/reports/invoice-incoterms/sql/incoterms.sql
index 435b3a51a..81c0ec189 100644
--- a/print/templates/reports/invoice-incoterms/sql/incoterms.sql
+++ b/print/templates/reports/invoice-incoterms/sql/incoterms.sql
@@ -1,67 +1,52 @@
-SELECT io.issued,
- c.socialName,
- c.street postalAddress,
- IF (ios.taxAreaFk IS NOT NULL, CONCAT(cty.code, c.fi), c.fi) fi,
- io.clientFk,
- c.postcode,
- c.city,
- io.companyFk,
- io.ref,
- tc.code,
- s.concept,
- s.quantity,
- s.price,
- s.discount,
- s.ticketFk,
- t.shipped,
- t.refFk,
- a.nickname,
- s.itemFk,
- s.id saleFk,
- pm.name AS pmname,
- sa.iban,
- c.phone,
- MAX(t.packages) packages,
+SELECT pack.packages,
a.incotermsFk,
- ic.name incotermsName ,
+ ic.name incotermsName,
t.weight,
- t.observations,
ca.fiscalName customsAgentName,
ca.street customsAgentStreet,
ca.nif customsAgentNif,
ca.phone customsAgentPhone,
ca.email customsAgentEmail,
- CAST(sub2.volume AS DECIMAL (10,2)) volume,
- sub3.intrastat
+ CAST(vol.volume AS DECIMAL (10,2)) volume,
+ intr.intrastat
FROM vn.invoiceOut io
JOIN vn.supplier su ON su.id = io.companyFk
JOIN vn.client c ON c.id = io.clientFk
LEFT JOIN vn.province p ON p.id = c.provinceFk
JOIN vn.ticket t ON t.refFk = io.ref
JOIN vn.address a ON a.id = t.addressFk
- LEFT JOIN vn.incoterms ic ON ic.code = a.incotermsFk
+ JOIN vn.incoterms ic ON ic.code = a.incotermsFk
LEFT JOIN vn.customsAgent ca ON ca.id = a.customsAgentFk
JOIN vn.sale s ON s.ticketFk = t.id
- JOIN (SELECT SUM(volume) volume
- FROM vn.invoiceOut io
- JOIN vn.ticket t ON t.refFk = io.ref
- JOIN vn.saleVolume sv ON sv.ticketFk = t.id
- WHERE t.refFk = ?
- ) sub2 ON TRUE
- JOIN vn.itemTaxCountry itc ON itc.countryFk = su.countryFk AND itc.itemFk = s.itemFk
+ JOIN (
+ SELECT SUM(volume) volume, COUNT(*) packages
+ FROM vn.invoiceOut io
+ JOIN vn.ticket t ON t.refFk = io.ref
+ JOIN vn.saleVolume sv ON sv.ticketFk = t.id
+ WHERE t.refFk = ?
+ ) vol
+ JOIN vn.itemTaxCountry itc ON itc.countryFk = su.countryFk
+ AND itc.itemFk = s.itemFk
JOIN vn.taxClass tc ON tc.id = itc.taxClassFk
- LEFT JOIN vn.invoiceOutSerial ios ON ios.code = io.serial AND ios.taxAreaFk = 'CEE'
+ JOIN vn.invoiceOutSerial ios ON ios.code = io.serial
+ AND ios.taxAreaFk = 'WORLD'
JOIN vn.country cty ON cty.id = c.countryFk
JOIN vn.payMethod pm ON pm.id = c .payMethodFk
JOIN vn.company co ON co.id=io.companyFk
JOIN vn.supplierAccount sa ON sa.id=co.supplierAccountFk
- LEFT JOIN (SELECT GROUP_CONCAT(DISTINCT ir.description ORDER BY ir.description SEPARATOR '. ' ) as intrastat
- FROM vn.ticket t
- JOIN vn.invoiceOut io ON io.ref = t.refFk
- JOIN vn.sale s ON t.id = s.ticketFk
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.intrastat ir ON ir.id = i.intrastatFk
- WHERE t.refFk = ?
- )sub3 ON TRUE
- WHERE t.refFk = ?
-
+ JOIN (
+ SELECT GROUP_CONCAT(DISTINCT ir.description ORDER BY ir.description SEPARATOR '. ' ) intrastat
+ FROM vn.ticket t
+ JOIN vn.invoiceOut io ON io.ref = t.refFk
+ JOIN vn.sale s ON t.id = s.ticketFk
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.intrastat ir ON ir.id = i.intrastatFk
+ WHERE t.refFk = ?
+ ) intr
+ JOIN (
+ SELECT SUM(packages) packages
+ FROM ticket
+ WHERE refFk = ?
+ ) pack
+ WHERE t.refFk = ?
+ LIMIT 1
diff --git a/print/templates/reports/invoice-incoterms/sql/invoice.sql b/print/templates/reports/invoice-incoterms/sql/invoice.sql
index 571ea2af3..02074f5c4 100644
--- a/print/templates/reports/invoice-incoterms/sql/invoice.sql
+++ b/print/templates/reports/invoice-incoterms/sql/invoice.sql
@@ -1,18 +1,17 @@
-SELECT
- io.id,
- io.issued,
- io.clientFk,
- io.companyFk,
- io.ref,
- pm.code AS payMethodCode,
- cny.code companyCode,
- sa.iban,
- ios.footNotes
-FROM invoiceOut io
- JOIN client c ON c.id = io.clientFk
- JOIN payMethod pm ON pm.id = c.payMethodFk
- JOIN company cny ON cny.id = io.companyFk
- JOIN supplierAccount sa ON sa.id = cny.supplierAccountFk
- LEFT JOIN invoiceOutSerial ios ON ios.code = io.serial
- LEFT JOIN ticket t ON t.refFk = io.ref
-WHERE t.refFk = ?
\ No newline at end of file
+SELECT io.id,
+ io.issued,
+ io.clientFk,
+ io.companyFk,
+ io.ref,
+ pm.code payMethodCode,
+ cny.code companyCode,
+ sa.iban,
+ ios.footNotes
+ FROM invoiceOut io
+ JOIN client c ON c.id = io.clientFk
+ JOIN payMethod pm ON pm.id = c.payMethodFk
+ JOIN company cny ON cny.id = io.companyFk
+ JOIN supplierAccount sa ON sa.id = cny.supplierAccountFk
+ LEFT JOIN invoiceOutSerial ios ON ios.code = io.serial
+ LEFT JOIN ticket t ON t.refFk = io.ref
+ WHERE t.refFk = ?
\ No newline at end of file
diff --git a/print/templates/reports/invoice/invoice.html b/print/templates/reports/invoice/invoice.html
index 45b6c3934..af1aaa423 100644
--- a/print/templates/reports/invoice/invoice.html
+++ b/print/templates/reports/invoice/invoice.html
@@ -16,6 +16,7 @@
diff --git a/print/templates/reports/invoice/invoice.js b/print/templates/reports/invoice/invoice.js
index 1c9965d3b..b26472b08 100755
--- a/print/templates/reports/invoice/invoice.js
+++ b/print/templates/reports/invoice/invoice.js
@@ -7,6 +7,7 @@ module.exports = {
mixins: [vnReport],
async serverPrefetch() {
this.invoice = await this.findOneFromDef('invoice', [this.reference]);
+
this.checkMainEntity(this.invoice);
this.client = await this.findOneFromDef('client', [this.reference]);
this.taxes = await this.rawSqlFromDef(`taxes`, [this.reference]);
diff --git a/print/templates/reports/invoice/sql/hasIncoterms.sql b/print/templates/reports/invoice/sql/hasIncoterms.sql
index 40a6db384..176fb30a6 100644
--- a/print/templates/reports/invoice/sql/hasIncoterms.sql
+++ b/print/templates/reports/invoice/sql/hasIncoterms.sql
@@ -1,8 +1,5 @@
-SELECT IF(incotermsFk IS NULL, FALSE, TRUE) AS hasIncoterms
- FROM ticket t
- JOIN invoiceOut io ON io.ref = t.refFk
- JOIN client c ON c.id = t.clientFk
- JOIN address a ON a.id = t.addressFk
- WHERE t.refFk = ?
- AND IF(c.hasToinvoiceByAddress = FALSE, c.defaultAddressFk, TRUE)
- LIMIT 1
\ No newline at end of file
+SELECT COUNT(*) AS hasIncoterms
+ FROM invoiceOut io
+ JOIN vn.invoiceOutSerial ios ON ios.code = io.serial
+ AND ios.taxAreaFk = 'WORLD'
+ WHERE io.ref = ?
diff --git a/print/templates/reports/invoice/sql/sales.sql b/print/templates/reports/invoice/sql/sales.sql
index 3833a3700..8e5ad1102 100644
--- a/print/templates/reports/invoice/sql/sales.sql
+++ b/print/templates/reports/invoice/sql/sales.sql
@@ -7,7 +7,8 @@ SELECT
s.discount,
s.itemFk,
s.concept,
- tc.code vatType
+ tc.code vatType,
+ it.isPackaging
FROM vn.invoiceOut io
JOIN vn.ticket t ON t.refFk = io.ref
JOIN vn.supplier su ON su.id = io.companyFk
@@ -34,9 +35,10 @@ SELECT
ts.quantity,
ts.price,
0 discount,
- '',
- ts.description concept,
- tc.code vatType
+ NULL,
+ ts.description,
+ tc.code,
+ NULL
FROM vn.invoiceOut io
JOIN vn.ticket t ON t.refFk = io.ref
JOIN vn.ticketService ts ON ts.ticketFk = t.id
@@ -46,3 +48,4 @@ SELECT
JOIN vn.supplierAccount sa ON sa.id = co.supplierAccountFk
JOIN vn.taxClass tc ON tc.id = ts.taxClassFk
WHERE t.refFk = ?
+ORDER BY (isPackaging), concept, itemFk
diff --git a/print/templates/reports/invoice/sql/tickets.sql b/print/templates/reports/invoice/sql/tickets.sql
index a8385599c..35828c5de 100644
--- a/print/templates/reports/invoice/sql/tickets.sql
+++ b/print/templates/reports/invoice/sql/tickets.sql
@@ -2,9 +2,12 @@ SELECT
t.id,
t.shipped,
t.nickname,
- tto.description
+ tto.description,
+ t.addressFk,
+ a.street
FROM invoiceOut io
JOIN ticket t ON t.refFk = io.REF
+ JOIN `address` a ON a.id = t.addressFk
LEFT JOIN observationType ot ON ot.code = 'invoiceOut'
LEFT JOIN ticketObservation tto ON tto.ticketFk = t.id
AND tto.observationTypeFk = ot.id
diff --git a/print/templates/reports/sepa-core/locale/es.yml b/print/templates/reports/sepa-core/locale/es.yml
index 5f3f08fc3..2737dc313 100644
--- a/print/templates/reports/sepa-core/locale/es.yml
+++ b/print/templates/reports/sepa-core/locale/es.yml
@@ -45,4 +45,4 @@ instructions:
title: Instrucciones
accountFields: Rellenar los campos relativos a la cuenta bancaria
signDocument: Firmar y sellar el documento. Para que tenga validez, en el sello debe aparecer el CIF/NIF. De no ser así, deberá acompañarse la solicitud de un certificado de titularidad de la cuenta.
- thanks: ¡Gracias por su colaboración!
\ No newline at end of file
+ thanks: ¡Gracias por su colaboración!
diff --git a/print/templates/reports/sepa-core/locale/fr.yml b/print/templates/reports/sepa-core/locale/fr.yml
index 354c06114..355b880a1 100644
--- a/print/templates/reports/sepa-core/locale/fr.yml
+++ b/print/templates/reports/sepa-core/locale/fr.yml
@@ -1,11 +1,11 @@
reportName: direct-debit
title: Direct Debit
-description: En signant ce formulaire de mandat, vous autorisez VERDNATURA LEVANTE SL
- à envoyer des instructions à votre banque pour débiter votre compte, et (B) votre banque
- à débiter votre compte conformément aux instructions de VERDNATURA LEVANTE SL.
- Vous bénéficiez d’un droit au remboursement par votre banque selon les conditions décrites
- dans la convention que vous avez passée avec elle. Toute demande de remboursement doit être
- présentée dans les 8 semaines suivant la date de débit de votre compte.
+description: En signant ce formulaire de mandat, vous autorisez VERDNATURA LEVANTE SL
+ à envoyer des instructions à votre banque pour débiter votre compte, et (B) votre banque
+ à débiter votre compte conformément aux instructions de VERDNATURA LEVANTE SL.
+ Vous bénéficiez d’un droit au remboursement par votre banque selon les conditions décrites
+ dans la convention que vous avez passée avec elle. Toute demande de remboursement doit être
+ présentée dans les 8 semaines suivant la date de débit de votre compte.
Votre banque peut vous renseigner au sujet de vos droits relatifs à ce mandat.
documentCopy: Veuillez dater, signer et retourner ce document à votre banque.
mandatoryFields: TOUS LES CHAMPS DOIVENT ÊTRE REINSEGNÉS IMPÉRATIVEMENT.
@@ -42,4 +42,4 @@ instructions:
title: instructions
accountFields: Remplissez les champs relatifs au compte bancaire
signDocument: Signez et scellez le document. Pour être valide, le CIF / NIF doit apparaître sur le cachet. Sinon, la demande de certificat de propriété du compte doit être jointe.
- thanks: Merci de votre collaboration!
\ No newline at end of file
+ thanks: Merci de votre collaboration!
diff --git a/print/templates/reports/sepa-core/sepa-core.html b/print/templates/reports/sepa-core/sepa-core.html
index a8c270ad5..363ebdfe5 100644
--- a/print/templates/reports/sepa-core/sepa-core.html
+++ b/print/templates/reports/sepa-core/sepa-core.html
@@ -27,8 +27,8 @@
{{$t('supplier.identifier')}}
-
ES89000B97367486
-
B97367486-000
+
{{supplier.iban}}
+
{{supplier.nif}}
diff --git a/print/templates/reports/sepa-core/sepa-core.js b/print/templates/reports/sepa-core/sepa-core.js
index 0e19d2a6a..96c512a9d 100755
--- a/print/templates/reports/sepa-core/sepa-core.js
+++ b/print/templates/reports/sepa-core/sepa-core.js
@@ -1,4 +1,5 @@
const vnReport = require('../../../core/mixins/vn-report.js');
+const db = require('../../../core/database');
module.exports = {
name: 'sepa-core',
@@ -18,5 +19,16 @@ module.exports = {
type: Number,
required: true
}
+ },
+ methods: {
+ getSupplierCif() {
+ return db.findOne(`
+ SELECT sa.iban, s.nif
+ FROM supplierAccount sa
+ JOIN company co ON co.supplierAccountFk = sa.id
+ JOIN supplier s ON sa.supplierFk = s.id
+ WHERE co.id = ?`) [this.companyId];
+ }
}
+
};
diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql
index 55b0e49ca..80635ecf5 100644
--- a/print/templates/reports/sepa-core/sql/supplier.sql
+++ b/print/templates/reports/sepa-core/sql/supplier.sql
@@ -1,17 +1,27 @@
SELECT
- m.code mandateCode,
- s.name,
- s.street,
- sc.country,
- s.postCode,
- s.city,
- sp.name province
-FROM client c
- LEFT JOIN mandate m ON m.clientFk = c.id
- AND m.companyFk = ? AND m.finished IS NULL
+ m.code mandateCode,
+ s.name,
+ s.street,
+ sc.country,
+ s.postCode,
+ s.city,
+ sp.name province,
+ s.nif,
+ sa.iban,
+ sa.supplierFk,
+ be.name bankName
+FROM
+ client c
+ LEFT JOIN mandate m ON m.clientFk = c.id AND m.companyFk = ? AND m.finished IS NULL
LEFT JOIN supplier s ON s.id = m.companyFk
LEFT JOIN country sc ON sc.id = s.countryFk
LEFT JOIN province sp ON sp.id = s.provinceFk
LEFT JOIN province p ON p.id = c.provinceFk
-WHERE (m.companyFk = ? OR m.companyFk IS NULL) AND c.id = ?
-ORDER BY m.created DESC LIMIT 1
\ No newline at end of file
+ LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id
+ LEFT JOIN bankEntity be ON sa.bankEntityFk = be.id
+WHERE
+ (m.companyFk = ? OR m.companyFk IS NULL)
+ AND (c.id = ? OR (c.id IS NULL AND c.countryFk = sa.countryFk))
+ORDER BY
+ m.created DESC
+LIMIT 1;
diff --git a/storage/image/user/1600x1600/1101.png b/storage/image/user/1600x1600/1101.png
new file mode 100644
index 000000000..aaf3ed566
Binary files /dev/null and b/storage/image/user/1600x1600/1101.png differ
diff --git a/storage/image/user/1600x1600/1102.png b/storage/image/user/1600x1600/1102.png
new file mode 100644
index 000000000..ca4c4c8a8
Binary files /dev/null and b/storage/image/user/1600x1600/1102.png differ
diff --git a/storage/image/user/1600x1600/1103.png b/storage/image/user/1600x1600/1103.png
new file mode 100644
index 000000000..55ef28000
Binary files /dev/null and b/storage/image/user/1600x1600/1103.png differ
diff --git a/storage/image/user/1600x1600/1104.png b/storage/image/user/1600x1600/1104.png
new file mode 100644
index 000000000..f57535ac5
Binary files /dev/null and b/storage/image/user/1600x1600/1104.png differ
diff --git a/storage/image/user/1600x1600/1105.png b/storage/image/user/1600x1600/1105.png
new file mode 100644
index 000000000..3aa33f8ea
Binary files /dev/null and b/storage/image/user/1600x1600/1105.png differ
diff --git a/storage/image/user/1600x1600/1106.png b/storage/image/user/1600x1600/1106.png
new file mode 100644
index 000000000..121d2d94f
Binary files /dev/null and b/storage/image/user/1600x1600/1106.png differ
diff --git a/storage/image/user/1600x1600/1107.png b/storage/image/user/1600x1600/1107.png
new file mode 100644
index 000000000..5a04e3027
Binary files /dev/null and b/storage/image/user/1600x1600/1107.png differ
diff --git a/storage/image/user/1600x1600/1108.png b/storage/image/user/1600x1600/1108.png
new file mode 100644
index 000000000..d704ef321
Binary files /dev/null and b/storage/image/user/1600x1600/1108.png differ
diff --git a/storage/image/user/1600x1600/1109.png b/storage/image/user/1600x1600/1109.png
new file mode 100644
index 000000000..5c0fdd3e7
Binary files /dev/null and b/storage/image/user/1600x1600/1109.png differ
diff --git a/storage/image/user/1600x1600/1110.png b/storage/image/user/1600x1600/1110.png
new file mode 100644
index 000000000..ea40691bf
Binary files /dev/null and b/storage/image/user/1600x1600/1110.png differ
diff --git a/storage/image/user/1600x1600/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png b/storage/image/user/1600x1600/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png
index 52f0fb9d1..e090bc2eb 100644
Binary files a/storage/image/user/1600x1600/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png and b/storage/image/user/1600x1600/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png differ
diff --git a/storage/image/user/160x160/1101.png b/storage/image/user/160x160/1101.png
new file mode 100644
index 000000000..e4b2cf3d5
Binary files /dev/null and b/storage/image/user/160x160/1101.png differ
diff --git a/storage/image/user/160x160/1102.png b/storage/image/user/160x160/1102.png
new file mode 100644
index 000000000..220b7b572
Binary files /dev/null and b/storage/image/user/160x160/1102.png differ
diff --git a/storage/image/user/160x160/1103.png b/storage/image/user/160x160/1103.png
new file mode 100644
index 000000000..a35e5f700
Binary files /dev/null and b/storage/image/user/160x160/1103.png differ
diff --git a/storage/image/user/160x160/1104.png b/storage/image/user/160x160/1104.png
new file mode 100644
index 000000000..66997bab1
Binary files /dev/null and b/storage/image/user/160x160/1104.png differ
diff --git a/storage/image/user/160x160/1105.png b/storage/image/user/160x160/1105.png
new file mode 100644
index 000000000..71d2f32b4
Binary files /dev/null and b/storage/image/user/160x160/1105.png differ
diff --git a/storage/image/user/160x160/1106.png b/storage/image/user/160x160/1106.png
new file mode 100644
index 000000000..5da9516b1
Binary files /dev/null and b/storage/image/user/160x160/1106.png differ
diff --git a/storage/image/user/160x160/1107.png b/storage/image/user/160x160/1107.png
new file mode 100644
index 000000000..a6ce498cf
Binary files /dev/null and b/storage/image/user/160x160/1107.png differ
diff --git a/storage/image/user/160x160/1108.png b/storage/image/user/160x160/1108.png
new file mode 100644
index 000000000..dac0d6f93
Binary files /dev/null and b/storage/image/user/160x160/1108.png differ
diff --git a/storage/image/user/160x160/1109.png b/storage/image/user/160x160/1109.png
new file mode 100644
index 000000000..439964486
Binary files /dev/null and b/storage/image/user/160x160/1109.png differ
diff --git a/storage/image/user/160x160/1110.png b/storage/image/user/160x160/1110.png
new file mode 100644
index 000000000..aa49d3d30
Binary files /dev/null and b/storage/image/user/160x160/1110.png differ
diff --git a/storage/image/user/160x160/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png b/storage/image/user/160x160/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png
index 07f21ecd1..e090bc2eb 100644
Binary files a/storage/image/user/160x160/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png and b/storage/image/user/160x160/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png differ
diff --git a/storage/image/user/520x520/1101.png b/storage/image/user/520x520/1101.png
new file mode 100644
index 000000000..664be96f2
Binary files /dev/null and b/storage/image/user/520x520/1101.png differ
diff --git a/storage/image/user/520x520/1102.png b/storage/image/user/520x520/1102.png
new file mode 100644
index 000000000..11f7d4e89
Binary files /dev/null and b/storage/image/user/520x520/1102.png differ
diff --git a/storage/image/user/520x520/1103.png b/storage/image/user/520x520/1103.png
new file mode 100644
index 000000000..28825c3ea
Binary files /dev/null and b/storage/image/user/520x520/1103.png differ
diff --git a/storage/image/user/520x520/1104.png b/storage/image/user/520x520/1104.png
new file mode 100644
index 000000000..11ddc971d
Binary files /dev/null and b/storage/image/user/520x520/1104.png differ
diff --git a/storage/image/user/520x520/1105.png b/storage/image/user/520x520/1105.png
new file mode 100644
index 000000000..2c32427d4
Binary files /dev/null and b/storage/image/user/520x520/1105.png differ
diff --git a/storage/image/user/520x520/1106.png b/storage/image/user/520x520/1106.png
new file mode 100644
index 000000000..fd58c993d
Binary files /dev/null and b/storage/image/user/520x520/1106.png differ
diff --git a/storage/image/user/520x520/1107.png b/storage/image/user/520x520/1107.png
new file mode 100644
index 000000000..10e4ee6ce
Binary files /dev/null and b/storage/image/user/520x520/1107.png differ
diff --git a/storage/image/user/520x520/1108.png b/storage/image/user/520x520/1108.png
new file mode 100644
index 000000000..8a90da8d3
Binary files /dev/null and b/storage/image/user/520x520/1108.png differ
diff --git a/storage/image/user/520x520/1109.png b/storage/image/user/520x520/1109.png
new file mode 100644
index 000000000..35d419273
Binary files /dev/null and b/storage/image/user/520x520/1109.png differ
diff --git a/storage/image/user/520x520/1110.png b/storage/image/user/520x520/1110.png
new file mode 100644
index 000000000..0824380a9
Binary files /dev/null and b/storage/image/user/520x520/1110.png differ
diff --git a/storage/image/user/520x520/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png b/storage/image/user/520x520/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png
index 52f0fb9d1..e090bc2eb 100644
Binary files a/storage/image/user/520x520/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png and b/storage/image/user/520x520/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png differ
diff --git a/storage/image/user/full/1101.png b/storage/image/user/full/1101.png
new file mode 100644
index 000000000..72000f7c5
Binary files /dev/null and b/storage/image/user/full/1101.png differ
diff --git a/storage/image/user/full/1102.png b/storage/image/user/full/1102.png
new file mode 100644
index 000000000..81aa86a9f
Binary files /dev/null and b/storage/image/user/full/1102.png differ
diff --git a/storage/image/user/full/1103.png b/storage/image/user/full/1103.png
new file mode 100644
index 000000000..b0a72c286
Binary files /dev/null and b/storage/image/user/full/1103.png differ
diff --git a/storage/image/user/full/1104.png b/storage/image/user/full/1104.png
new file mode 100644
index 000000000..9c9f64587
Binary files /dev/null and b/storage/image/user/full/1104.png differ
diff --git a/storage/image/user/full/1105.png b/storage/image/user/full/1105.png
new file mode 100644
index 000000000..5a353c2dc
Binary files /dev/null and b/storage/image/user/full/1105.png differ
diff --git a/storage/image/user/full/1106.png b/storage/image/user/full/1106.png
new file mode 100644
index 000000000..9b6d746ac
Binary files /dev/null and b/storage/image/user/full/1106.png differ
diff --git a/storage/image/user/full/1107.png b/storage/image/user/full/1107.png
new file mode 100644
index 000000000..182c8af6b
Binary files /dev/null and b/storage/image/user/full/1107.png differ
diff --git a/storage/image/user/full/1108.png b/storage/image/user/full/1108.png
new file mode 100644
index 000000000..2bf1fbdb3
Binary files /dev/null and b/storage/image/user/full/1108.png differ
diff --git a/storage/image/user/full/1109.png b/storage/image/user/full/1109.png
new file mode 100644
index 000000000..78b94095f
Binary files /dev/null and b/storage/image/user/full/1109.png differ
diff --git a/storage/image/user/full/1110.png b/storage/image/user/full/1110.png
new file mode 100644
index 000000000..5b0350d36
Binary files /dev/null and b/storage/image/user/full/1110.png differ
diff --git a/storage/image/user/full/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png b/storage/image/user/full/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png
index 52f0fb9d1..e090bc2eb 100644
Binary files a/storage/image/user/full/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png and b/storage/image/user/full/4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd.png differ
diff --git a/webpack.config.js b/webpack.config.js
index a102b838e..7296a62d1 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -11,7 +11,7 @@ let baseConfig = {
entry: {salix: 'salix'},
mode,
output: {
- path: path.join(__dirname, 'dist'),
+ path: path.join(__dirname, 'front/dist'),
publicPath: '/'
},
module: {
@@ -139,7 +139,7 @@ let devConfig = {
host: '0.0.0.0',
port: 5000,
publicPath: '/',
- contentBase: 'dist',
+ contentBase: 'front/dist',
quiet: false,
noInfo: false,
hot: true,