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/.vscode/settings.json b/.vscode/settings.json
index 36b7e21d8..03479d27a 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -16,6 +16,7 @@
},
"cSpell.words": [
"salix",
- "fdescribe"
+ "fdescribe",
+ "Loggable"
]
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1907f46bd..f48811338 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,285 +5,349 @@ 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).
+## [2408.01] - 2024-02-22
+
+### Added
+
+### Changed
+
+### Fixed
+
+## [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
+- **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)
+
+- **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
+- **Tickets → RocketChat:** Arreglada detección de cambios
## [2346.01] - 2023-11-16
### Added
-### Changed
-### Fixed
+### 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
+- (Usuarios -> Foto) Se muestra la foto del trabajador
+
+### Fixed
+
+- (Usuarios -> Historial) Abre el descriptor del usuario correctamente
## [2340.01] - 2023-10-05
## [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
+
+- (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
+
+- (Trabajadores -> Calendario) Icono de check arreglado cuando pulsas un tipo de dia
## [2336.01] - 2023-09-07
## [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..2c04bcf16 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -1,144 +1,253 @@
#!/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 'npm run test:back:ci'
+ }
+ 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)
+
+ rocketSend(
+ channel: 'vn-database',
+ message: "*DB version uploaded:* ${message}"
+ +"\n$COMMITTER_EMAIL ($BRANCH_NAME)"
+ +"\n$GIT_URL/commit/$GIT_COMMIT",
+ rawMessage: true
)
- } catch (e) {
- echo e.toString()
}
}
}
+ unsuccessful {
+ setEnv()
+ sendEmail()
+ }
}
}
diff --git a/Dockerfile b/back/Dockerfile
similarity index 88%
rename from Dockerfile
rename to back/Dockerfile
index 61dd758b8..363192a0b 100644
--- a/Dockerfile
+++ b/back/Dockerfile
@@ -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
@@ -39,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/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/osticket/sendToSupport.js b/back/methods/osticket/sendToSupport.js
index 5b9ebb4e3..135774919 100644
--- a/back/methods/osticket/sendToSupport.js
+++ b/back/methods/osticket/sendToSupport.js
@@ -35,10 +35,17 @@ 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;
+ const subjectReason = httpRequest?.data?.error;
smtp.send({
to: `${config.app.reportEmail}, ${emailUser.email}`,
subject:
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/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 194747949..d00085d8a 100644
--- a/back/methods/vn-user/renew-token.js
+++ b/back/methods/vn-user/renew-token.js
@@ -1,14 +1,5 @@
-const UserError = require('vn-loopback/util/user-error');
const {models} = require('vn-loopback/server/server');
-const handlePromiseLogout = (Self, {id}, courtesyTime) => {
- new Promise(res => {
- setTimeout(() => {
- res(Self.logout(id));
- }
- , courtesyTime * 1000);
- });
-};
module.exports = Self => {
Self.remoteMethodCtx('renewToken', {
description: 'Checks if the token has more than renewPeriod seconds to live and if so, renews it',
@@ -28,14 +19,26 @@ module.exports = Self => {
const {accessToken: token} = ctx.req;
// Check if current token is valid
- const isValid = await validateToken(token);
- if (isValid)
+
+ 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 {courtesyTime} = await models.AccessTokenConfig.findOne({fields: ['courtesyTime']});
-
// Schedule to remove current token
- handlePromiseLogout(Self, token, courtesyTime);
+ setTimeout(async() => {
+ try {
+ await Self.logout(token.id);
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.error(err);
+ }
+ }, courtesyTime * 1000);
// Create new accessToken
const user = await Self.findById(token.userId);
@@ -43,14 +46,4 @@ module.exports = Self => {
return {id: accessToken.id, ttl: accessToken.ttl};
};
-
- async function validateToken(token) {
- const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod', 'courtesyTime']});
- const now = Date.now();
- const differenceMilliseconds = now - token.created;
- const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
- const isValid = differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime;
-
- return isValid;
- }
};
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/model-config.json b/back/model-config.json
index ebc0e321b..27a94498c 100644
--- a/back/model-config.json
+++ b/back/model-config.json
@@ -139,9 +139,6 @@
"Warehouse": {
"dataSource": "vn"
},
- "VnUser": {
- "dataSource": "vn"
- },
"OsTicket": {
"dataSource": "osticket"
},
@@ -156,6 +153,12 @@
},
"ViaexpressConfig": {
"dataSource": "vn"
+ },
+ "VnUser": {
+ "dataSource": "vn"
+ },
+ "VnRole": {
+ "dataSource": "vn"
}
}
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/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/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/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/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..c13cc7ae8
--- /dev/null
+++ b/back/models/specs/mailAliasAccount.spec.js
@@ -0,0 +1,73 @@
+const models = require('vn-loopback/server/server').models;
+
+describe('loopback model MailAliasAccount', () => {
+ it('should fail to add a mail Alias if the worker doesnt have ACLs', async() => {
+ const tx = await models.MailAliasAccount.beginTransaction({});
+ let error;
+
+ try {
+ const options = {transaction: tx, accessToken: {userId: 57}};
+ await models.MailAliasAccount.create({mailAlias: 2, account: 5}, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error.message).toEqual('The alias cant be modified');
+ });
+
+ 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/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 b1d09f0c0..3a416d7e3 100644
--- a/back/models/vn-user.js
+++ b/back/models/vn-user.js
@@ -79,10 +79,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)
@@ -142,7 +142,7 @@ module.exports = function(Self) {
ip: ctx.req.ip,
owner: isOwner
});
- throw new UserError('Try again');
+ throw new UserError('Try again');
}
};
@@ -258,18 +258,20 @@ module.exports = function(Self) {
class Mailer {
async send(verifyOptions, cb) {
- const url = new URL(verifyOptions.verifyHref);
- if (process.env.NODE_ENV) url.port = '';
+ try {
+ const url = new URL(verifyOptions.verifyHref);
+ if (process.env.NODE_ENV) url.port = '';
- const params = {
- url: url.href,
- recipient: verifyOptions.to
- };
+ const email = new Email('email-verify', {
+ url: url.href,
+ recipient: verifyOptions.to
+ });
+ await email.send();
- const email = new Email('email-verify', params);
- email.send();
-
- cb(null, verifyOptions.to);
+ cb(null, verifyOptions.to);
+ } catch (err) {
+ cb(err);
+ }
}
}
diff --git a/back/models/vn-user.json b/back/models/vn-user.json
index 86ffac2bb..639603643 100644
--- a/back/models/vn-user.json
+++ b/back/models/vn-user.json
@@ -7,6 +7,9 @@
"table": "account.user"
}
},
+ "mixins": {
+ "Loggable": true
+ },
"resetPasswordTokenTTL": "604800",
"properties": {
"id": {
@@ -63,7 +66,7 @@
"relations": {
"role": {
"type": "belongsTo",
- "model": "Role",
+ "model": "VnRole",
"foreignKey": "roleFk"
},
"roles": {
@@ -95,27 +98,30 @@
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
- },
- {
- "property": "recoverPassword",
- "accessType": "EXECUTE",
- "principalType": "ROLE",
- "principalId": "$everyone",
- "permission": "ALLOW"
- },
- {
- "property": "validateAuth",
+ }, {
+ "property": "recoverPassword",
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
- },
- {
+ }, {
+ "property": "validateAuth",
+ "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"
}
],
"scopes": {
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 efade4d7d..1848132f8 100644
--- a/back/tests.js
+++ b/back/tests.js
@@ -1,84 +1,121 @@
-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('SIGUSR2', async() => {
- if (container) await container.rm();
-});
+let server;
+const PARALLEL = false;
+const TIMEOUT = 900000;
-process.on('exit', async function() {
- if (container) await container.rm();
-});
+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: TIMEOUT,
+ globalTeardown: teardown,
+ globalTeardownTimeout: 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 = 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);
+ 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-acl_receiptPdf.sql b/db/.archive/224701/00-acl_receiptPdf.sql
deleted file mode 100644
index 42f84b87d..000000000
--- a/db/.archive/224701/00-acl_receiptPdf.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Receipt', 'receiptPdf', '*', 'ALLOW', 'ROLE', 'salesAssistant');
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/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 c0f6bc697..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,
- siiTypeInvoiceOutFk
- )
- 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 invoiceExpenseMake(vNewInvoiceId);
- CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
-
- UPDATE invoiceOut io
- JOIN (
- SELECT SUM(amount) AS total
- FROM invoiceOutExpense
- 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, expenseFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenseFk, sub.taxTypeSageFk , sub.transactionTypeSageFk
- FROM (
- SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk
- FROM tmp.ticketServiceTax tst
- JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code
- WHERE i.isService
- HAVING taxableBase
- ) sub;
-
- INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenseFk, 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-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 e87c44cd0..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,
- siiTypeInvoiceOutFk
- )
- SELECT
- 1,
- vSerial,
- vInvoiceDate,
- vClientFk,
- getDueDate(vInvoiceDate, dueDay),
- vCompanyFk,
- IF(vSerial = vCorrectingSerial,
- vCplusCorrectingInvoiceTypeFk,
- IF(vSerial = vSimplifiedSerial,
- vCplusSimplifiedInvoiceTypeFk,
- vCplusStandardInvoiceTypeFk))
- FROM client
- WHERE id = vClientFk;
-
- SET vNewInvoiceId = LAST_INSERT_ID();
-
- SELECT `ref`
- INTO vNewRef
- FROM invoiceOut
- WHERE id = vNewInvoiceId;
-
- 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 invoiceExpenseMake(vNewInvoiceId);
- CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
-
- UPDATE invoiceOut io
- JOIN (
- SELECT SUM(amount) total
- FROM invoiceOutExpense
- WHERE invoiceOutFk = vNewInvoiceId
- ) base
- JOIN (
- SELECT SUM(vat) total
- FROM invoiceOutTax
- WHERE invoiceOutFk = vNewInvoiceId
- ) vat
- SET io.amount = base.total + vat.total
- WHERE io.id = vNewInvoiceId;
-
- DROP TEMPORARY TABLE tmp.updateInter;
-
- SELECT COUNT(*), id
- INTO vIsInterCompany, vInterCompanyFk
- FROM company
- WHERE clientFk = vClientFk;
-
- IF (vIsInterCompany) THEN
-
- INSERT INTO invoiceIn(supplierFk, supplierRef, issued, companyFk)
- SELECT vCompanyFk, vNewRef, vInvoiceDate, vInterCompanyFk;
-
- SET vNewInvoiceInFk = LAST_INSERT_ID();
-
- DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
- CREATE TEMPORARY TABLE tmp.ticket
- (KEY (ticketFk))
- ENGINE = MEMORY
- SELECT id ticketFk
- FROM tmp.ticketToInvoice;
-
- CALL `ticket_getTax`('NATIONAL');
-
- SET @vTaxableBaseServices := 0.00;
- SET @vTaxCodeGeneral := NULL;
-
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInFk,
- @vTaxableBaseServices,
- sub.expenseFk,
- sub.taxTypeSageFk,
- sub.transactionTypeSageFk
- FROM (
- SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase,
- i.expenseFk,
- i.taxTypeSageFk,
- i.transactionTypeSageFk,
- @vTaxCodeGeneral := i.taxClassCodeFk
- FROM tmp.ticketServiceTax tst
- JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code
- WHERE i.isService
- HAVING taxableBase
- ) sub;
-
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInFk,
- SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral,
- @vTaxableBaseServices, 0) taxableBase,
- i.expenseFk,
- i.taxTypeSageFk ,
- i.transactionTypeSageFk
- FROM tmp.ticketTax tt
- JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code
- WHERE !i.isService
- GROUP BY tt.pgcFk
- HAVING taxableBase
- ORDER BY tt.priority;
-
- CALL invoiceInDueDay_calculate(vNewInvoiceInFk);
-
- SELECT COUNT(*) INTO vIsCEESerial
- FROM invoiceOutSerial
- WHERE code = vSerial;
-
- IF vIsCEESerial THEN
-
- INSERT INTO invoiceInIntrastat (
- invoiceInFk,
- intrastatFk,
- amount,
- stems,
- countryFk,
- net)
- SELECT
- vNewInvoiceInFk,
- i.intrastatFk,
- SUM(CAST((s.quantity * s.price * (100 - s.discount) / 100 ) AS DECIMAL(10, 2))),
- SUM(CAST(IFNULL(i.stems, 1) * s.quantity AS DECIMAL(10, 2))),
- su.countryFk,
- CAST(SUM(IFNULL(i.stems, 1)
- * s.quantity
- * IF(ic.grams, ic.grams, IFNULL(i.weightByPiece, 0)) / 1000) AS DECIMAL(10, 2))
- FROM sale s
- JOIN ticket t ON s.ticketFk = t.id
- JOIN supplier su ON su.id = t.companyFk
- JOIN item i ON i.id = s.itemFk
- LEFT JOIN itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk
- WHERE t.refFk = vNewRef
- GROUP BY i.intrastatFk;
-
- END IF;
- DROP TEMPORARY TABLE tmp.ticket;
- DROP TEMPORARY TABLE tmp.ticketAmount;
- DROP TEMPORARY TABLE tmp.ticketTax;
- DROP TEMPORARY TABLE tmp.ticketServiceTax;
- END IF;
- END IF;
- DROP TEMPORARY TABLE tmp.`ticketToInvoice`;
-END$$
-DELIMITER ;
diff --git a/db/.archive/231201/00-ACL.sql b/db/.archive/231201/00-ACL.sql
deleted file mode 100644
index 47a818977..000000000
--- a/db/.archive/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/.archive/231201/00-chatRefactor.sql b/db/.archive/231201/00-chatRefactor.sql
deleted file mode 100644
index 66d1bf3bf..000000000
--- a/db/.archive/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/.archive/231201/00-invoiceInSerial.sql b/db/.archive/231201/00-invoiceInSerial.sql
deleted file mode 100644
index de476027c..000000000
--- a/db/.archive/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/.archive/231201/00-itemType_isFragile.sql b/db/.archive/231201/00-itemType_isFragile.sql
deleted file mode 100644
index ecc1bfbb2..000000000
--- a/db/.archive/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/.archive/231201/00-mailACL.sql b/db/.archive/231201/00-mailACL.sql
deleted file mode 100644
index ac687818d..000000000
--- a/db/.archive/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/.archive/231201/00-operator.sql b/db/.archive/231201/00-operator.sql
deleted file mode 100644
index 9b7815b41..000000000
--- a/db/.archive/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/.archive/231201/00-supplierAccount_deleteTriggers.sql b/db/.archive/231201/00-supplierAccount_deleteTriggers.sql
deleted file mode 100644
index d7f9f734a..000000000
--- a/db/.archive/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/.archive/231201/00-wagon.sql b/db/.archive/231201/00-wagon.sql
deleted file mode 100644
index 9e817bac4..000000000
--- a/db/.archive/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/.archive/231202/00-delivery.sql b/db/.archive/231202/00-delivery.sql
deleted file mode 100644
index 3a9269183..000000000
--- a/db/.archive/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/.archive/231203/00-delivery.sql b/db/.archive/231203/00-delivery.sql
deleted file mode 100644
index 0815ec421..000000000
--- a/db/.archive/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/.archive/231204/00-rollbackDelivery.sql b/db/.archive/231204/00-rollbackDelivery.sql
deleted file mode 100644
index d7fa6b587..000000000
--- a/db/.archive/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/.archive/231205/00-printQueueArgs.sql b/db/.archive/231205/00-printQueueArgs.sql
deleted file mode 100644
index 972031325..000000000
--- a/db/.archive/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/.archive/231401/00-claimBeginningAfterInsert.sql b/db/.archive/231401/00-claimBeginningAfterInsert.sql
deleted file mode 100644
index 230b6defb..000000000
--- a/db/.archive/231401/00-claimBeginningAfterInsert.sql
+++ /dev/null
@@ -1 +0,0 @@
-DROP TRIGGER IF EXISTS `vn`.`claimBeginning_afterInsert`;
diff --git a/db/.archive/231401/00-negativeBases.sql b/db/.archive/231401/00-negativeBases.sql
deleted file mode 100644
index 0bdc6f2dc..000000000
--- a/db/.archive/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/.archive/231401/00-workerNotes.sql b/db/.archive/231401/00-workerNotes.sql
deleted file mode 100644
index 0d9eaae7e..000000000
--- a/db/.archive/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/.archive/231402/00-negativeBases.sql b/db/.archive/231402/00-negativeBases.sql
deleted file mode 100644
index f7d6cdfb0..000000000
--- a/db/.archive/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/.archive/231801/00-aclClientInforma.sql b/db/.archive/231801/00-aclClientInforma.sql
deleted file mode 100644
index 6222d2632..000000000
--- a/db/.archive/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/.archive/231801/00-acl_receiptEmail.sql b/db/.archive/231801/00-acl_receiptEmail.sql
deleted file mode 100644
index 2de8adf50..000000000
--- a/db/.archive/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/.archive/231801/00-clientInforma.sql b/db/.archive/231801/00-clientInforma.sql
deleted file mode 100644
index 9bf757fc3..000000000
--- a/db/.archive/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/.archive/231801/00-client_setRatingAcl.sql b/db/.archive/231801/00-client_setRatingAcl.sql
deleted file mode 100644
index 6687b11ec..000000000
--- a/db/.archive/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/.archive/231801/00-deleteProcs_refund.sql b/db/.archive/231801/00-deleteProcs_refund.sql
deleted file mode 100644
index 8bf8982f4..000000000
--- a/db/.archive/231801/00-deleteProcs_refund.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-DROP PROCEDURE `vn`.`refund`;
-DROP PROCEDURE `vn`.`ticket_doRefund`;
diff --git a/db/.archive/231801/00-deviceProduction.sql b/db/.archive/231801/00-deviceProduction.sql
deleted file mode 100644
index 37a2f1371..000000000
--- a/db/.archive/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/.archive/231801/00-kkearEntryNotes.sql b/db/.archive/231801/00-kkearEntryNotes.sql
deleted file mode 100644
index ff5c7ce29..000000000
--- a/db/.archive/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/.archive/231801/00-newCompanyI18n.sql b/db/.archive/231801/00-newCompanyI18n.sql
deleted file mode 100644
index 948b9cb08..000000000
--- a/db/.archive/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/.archive/231801/00-newTableWeb.sql b/db/.archive/231801/00-newTableWeb.sql
deleted file mode 100644
index 1a2402956..000000000
--- a/db/.archive/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/.archive/231801/00-observationEmailACL.sql b/db/.archive/231801/00-observationEmailACL.sql
deleted file mode 100644
index 1a5d475e8..000000000
--- a/db/.archive/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/.archive/231801/00-optimiceZoneEstimatedDelivery.sql b/db/.archive/231801/00-optimiceZoneEstimatedDelivery.sql
deleted file mode 100644
index 209e1efc3..000000000
--- a/db/.archive/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/.archive/231801/00-saleTracking.sql b/db/.archive/231801/00-saleTracking.sql
deleted file mode 100644
index d651a2447..000000000
--- a/db/.archive/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/.archive/231801/00-ticketConfig.sql b/db/.archive/231801/00-ticketConfig.sql
deleted file mode 100644
index 7c8aa83a4..000000000
--- a/db/.archive/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/.archive/231801/00-updateIsVies.sql b/db/.archive/231801/00-updateIsVies.sql
deleted file mode 100644
index 4e5277559..000000000
--- a/db/.archive/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/.archive/231801/00-updateisViesClient.sql b/db/.archive/231801/00-updateisViesClient.sql
deleted file mode 100644
index a153c5219..000000000
--- a/db/.archive/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/.archive/231801/00-userAcl.sql b/db/.archive/231801/00-userAcl.sql
deleted file mode 100644
index 9eb3ebf28..000000000
--- a/db/.archive/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/.archive/231801/00-userRoleLog.sql b/db/.archive/231801/00-userRoleLog.sql
deleted file mode 100644
index ae5da13cb..000000000
--- a/db/.archive/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/.archive/231801/01-viewCompany10L.sql b/db/.archive/231801/01-viewCompany10L.sql
deleted file mode 100644
index 335827b42..000000000
--- a/db/.archive/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/.archive/232001/00-clientWorkerName.sql b/db/.archive/232001/00-clientWorkerName.sql
deleted file mode 100644
index 676d26691..000000000
--- a/db/.archive/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/.archive/232001/00-createWorker.sql b/db/.archive/232001/00-createWorker.sql
deleted file mode 100644
index 0ea7ecbe8..000000000
--- a/db/.archive/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/.archive/232001/00-wagon.sql b/db/.archive/232001/00-wagon.sql
deleted file mode 100644
index bdb384db5..000000000
--- a/db/.archive/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/.archive/232201/00-defaulterView.sql b/db/.archive/232201/00-defaulterView.sql
deleted file mode 100644
index 8b56e5945..000000000
--- a/db/.archive/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/.archive/232201/00-procedurecanAdvance.sql b/db/.archive/232201/00-procedurecanAdvance.sql
deleted file mode 100644
index 9d5c24296..000000000
--- a/db/.archive/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/.archive/232201/00-workerConfigPayMethod.sql b/db/.archive/232201/00-workerConfigPayMethod.sql
deleted file mode 100644
index 8896f636d..000000000
--- a/db/.archive/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/.archive/232202/00-procedurecanAdvance.sql b/db/.archive/232202/00-procedurecanAdvance.sql
deleted file mode 100644
index d82294b3c..000000000
--- a/db/.archive/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/.archive/232401/00-buyConfig_travelConfig.sql b/db/.archive/232401/00-buyConfig_travelConfig.sql
deleted file mode 100644
index 0f73ddc8c..000000000
--- a/db/.archive/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/.archive/232401/00-printer.sql b/db/.archive/232401/00-printer.sql
deleted file mode 100644
index 6280c2c6d..000000000
--- a/db/.archive/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/.archive/232401/00-ticket_warehouse.sql b/db/.archive/232401/00-ticket_warehouse.sql
deleted file mode 100644
index b5255ee3f..000000000
--- a/db/.archive/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/.archive/232401/00-userPassExpired.sql b/db/.archive/232401/00-userPassExpired.sql
deleted file mode 100644
index 2d4b45937..000000000
--- a/db/.archive/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/.archive/232402/00-hotFix_travelConfig.sql b/db/.archive/232402/00-hotFix_travelConfig.sql
deleted file mode 100644
index 65450a74d..000000000
--- a/db/.archive/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/.archive/232601/00-aclAccount.sql b/db/.archive/232601/00-aclAccount.sql
deleted file mode 100644
index bf8106b98..000000000
--- a/db/.archive/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/.archive/232601/00-aclInvoiceTickets.sql b/db/.archive/232601/00-aclInvoiceTickets.sql
deleted file mode 100644
index 2c221950e..000000000
--- a/db/.archive/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/.archive/232601/00-aclMailAliasAccount.sql b/db/.archive/232601/00-aclMailAliasAccount.sql
deleted file mode 100644
index 619e9bb6e..000000000
--- a/db/.archive/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/.archive/232601/00-aclMailForward.sql b/db/.archive/232601/00-aclMailForward.sql
deleted file mode 100644
index afe2acec8..000000000
--- a/db/.archive/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/.archive/232601/00-aclRole.sql b/db/.archive/232601/00-aclRole.sql
deleted file mode 100644
index e16f052be..000000000
--- a/db/.archive/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/.archive/232601/00-aclVnUser.sql b/db/.archive/232601/00-aclVnUser.sql
deleted file mode 100644
index 39fa2cb14..000000000
--- a/db/.archive/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/.archive/232601/00-aclVnUser_renewToken.sql b/db/.archive/232601/00-aclVnUser_renewToken.sql
deleted file mode 100644
index aa20f7a82..000000000
--- a/db/.archive/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/.archive/232601/00-salix.sql b/db/.archive/232601/00-salix.sql
deleted file mode 100644
index 44366abce..000000000
--- a/db/.archive/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/.archive/232601/00-useSpecificsAcls.sql b/db/.archive/232601/00-useSpecificsAcls.sql
deleted file mode 100644
index d124786f6..000000000
--- a/db/.archive/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/.archive/232601/01-invoiceOutPdf.sql b/db/.archive/232601/01-invoiceOutPdf.sql
deleted file mode 100644
index e013736df..000000000
--- a/db/.archive/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/.archive/232602/01-aclAddAlias.sql b/db/.archive/232602/01-aclAddAlias.sql
deleted file mode 100644
index d4df3cd44..000000000
--- a/db/.archive/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/.archive/232801/00-authCode.sql b/db/.archive/232801/00-authCode.sql
deleted file mode 100644
index a256db43f..000000000
--- a/db/.archive/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/.archive/232801/00-client_create.sql b/db/.archive/232801/00-client_create.sql
deleted file mode 100644
index d21094dad..000000000
--- a/db/.archive/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/.archive/232801/00-client_create2.sql b/db/.archive/232801/00-client_create2.sql
deleted file mode 100644
index f2e660351..000000000
--- a/db/.archive/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/.archive/232801/00-department.sql b/db/.archive/232801/00-department.sql
deleted file mode 100644
index 3dcb8501d..000000000
--- a/db/.archive/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/.archive/232801/00-fix_editCredit.sql b/db/.archive/232801/00-fix_editCredit.sql
deleted file mode 100644
index ff0d9e2b3..000000000
--- a/db/.archive/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/.archive/232801/00-user.sql b/db/.archive/232801/00-user.sql
deleted file mode 100644
index 376b3dbb1..000000000
--- a/db/.archive/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/.archive/232802/01-aclWorkerDisable.sql b/db/.archive/232802/01-aclWorkerDisable.sql
deleted file mode 100644
index 149dd6f15..000000000
--- a/db/.archive/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/.archive/233001/.gitkeep b/db/.archive/233001/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/.archive/233001/00-aclSaleTracking.sql b/db/.archive/233001/00-aclSaleTracking.sql
deleted file mode 100644
index 6a699091a..000000000
--- a/db/.archive/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/.archive/233001/00-clientSms.sql b/db/.archive/233001/00-clientSms.sql
deleted file mode 100644
index e1e34f6b2..000000000
--- a/db/.archive/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/.archive/233001/00-company.sql b/db/.archive/233001/00-company.sql
deleted file mode 100644
index a3b61b9cc..000000000
--- a/db/.archive/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/.archive/233001/00-fixACLVehicle.sql b/db/.archive/233001/00-fixACLVehicle.sql
deleted file mode 100644
index 6625f0d5c..000000000
--- a/db/.archive/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/.archive/233001/00-itemRecycle.sql b/db/.archive/233001/00-itemRecycle.sql
deleted file mode 100644
index c191e5d1c..000000000
--- a/db/.archive/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/.archive/233001/00-itemShelving_inventory.sql b/db/.archive/233001/00-itemShelving_inventory.sql
deleted file mode 100644
index b0b080ef3..000000000
--- a/db/.archive/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/.archive/233001/00-noUniqueSocialName.sql b/db/.archive/233001/00-noUniqueSocialName.sql
deleted file mode 100644
index 0dc4c832f..000000000
--- a/db/.archive/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/.archive/233001/00-roadmap.sql b/db/.archive/233001/00-roadmap.sql
deleted file mode 100644
index 9b5db54eb..000000000
--- a/db/.archive/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/.archive/233001/00-roadmapACL.sql b/db/.archive/233001/00-roadmapACL.sql
deleted file mode 100644
index 4fc116f86..000000000
--- a/db/.archive/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/.archive/233001/00-ticketWeight.sql b/db/.archive/233001/00-ticketWeight.sql
deleted file mode 100644
index 0b727b434..000000000
--- a/db/.archive/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/.archive/233201/.gitkeep b/db/.archive/233201/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/.archive/233201/00-acl_viaexpressConfig.sql b/db/.archive/233201/00-acl_viaexpressConfig.sql
deleted file mode 100644
index d4c186dd4..000000000
--- a/db/.archive/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/.archive/233201/00-transferClient.sql b/db/.archive/233201/00-transferClient.sql
deleted file mode 100644
index 8a7ce0543..000000000
--- a/db/.archive/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/.archive/233201/00-updatePrice.sql b/db/.archive/233201/00-updatePrice.sql
deleted file mode 100644
index 959943d6f..000000000
--- a/db/.archive/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/.archive/233201/00-viaexpress.sql b/db/.archive/233201/00-viaexpress.sql
deleted file mode 100644
index 42cf3b647..000000000
--- a/db/.archive/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/.archive/233201/00-workerDocuware.sql b/db/.archive/233201/00-workerDocuware.sql
deleted file mode 100644
index 2f2c4a1cd..000000000
--- a/db/.archive/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/.archive/233202/00-ticketSmsACL.sql b/db/.archive/233202/00-ticketSmsACL.sql
deleted file mode 100644
index a25a876f8..000000000
--- a/db/.archive/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/.archive/233401/00-setDeleted_acl.sql b/db/.archive/233401/00-setDeleted_acl.sql
deleted file mode 100644
index cdeff9522..000000000
--- a/db/.archive/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/.archive/233601/.gitkeep b/db/.archive/233601/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/.archive/233601/00-aclWorker.sql b/db/.archive/233601/00-aclWorker.sql
deleted file mode 100644
index e79d8f738..000000000
--- a/db/.archive/233601/00-aclWorker.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('Worker', 'search', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/.archive/233601/00-addExpeditionState.sql b/db/.archive/233601/00-addExpeditionState.sql
deleted file mode 100644
index fb236b0c3..000000000
--- a/db/.archive/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/.archive/233601/00-department.sql b/db/.archive/233601/00-department.sql
deleted file mode 100644
index 777d26b9f..000000000
--- a/db/.archive/233601/00-department.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-UPDATE `vn`.`department`
- SET code='VN'
-WHERE name='VERDNATURA';
diff --git a/db/.archive/233601/00-saleGroupDetail.sql b/db/.archive/233601/00-saleGroupDetail.sql
deleted file mode 100644
index d16478716..000000000
--- a/db/.archive/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/.archive/233801/.gitkeep b/db/.archive/233801/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/.archive/233801/00-firstScript.sql b/db/.archive/233801/00-firstScript.sql
deleted file mode 100644
index 47b96b3bc..000000000
--- a/db/.archive/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/.archive/233801/01-deviceLog_acl.sql b/db/.archive/233801/01-deviceLog_acl.sql
deleted file mode 100644
index 2b646a6a3..000000000
--- a/db/.archive/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/.archive/233802/.gitkeep b/db/.archive/233802/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/.archive/233802/00-collectionGetTicketsACL.sql b/db/.archive/233802/00-collectionGetTicketsACL.sql
deleted file mode 100644
index 06b584386..000000000
--- a/db/.archive/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/.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/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/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/234003/00-ticket_canAdvance_zone.sql b/db/changes/234003/00-ticket_canAdvance_zone.sql
deleted file mode 100644
index ee07ce978..000000000
--- a/db/changes/234003/00-ticket_canAdvance_zone.sql
+++ /dev/null
@@ -1,133 +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;
-
- 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,
- origin.futureAgency,
- dest.lines,
- dest.liters,
- origin.futureLines - origin.hasStock AS notMovableLines,
- (origin.futureLines = origin.hasStock) AS isFullMovable,
- origin.futureZoneFk,
- origin.futureZoneName,
- origin.classColor futureClassColor,
- dest.classColor
- FROM (
- SELECT
- s.ticketFk,
- 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,
- z.id futureZoneFk,
- z.name futureZoneName,
- st.classColor
- 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 (
- 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/234004/.gitkeep b/db/changes/234004/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/234004/00-workerTimeControl.sql b/db/changes/234004/00-workerTimeControl.sql
deleted file mode 100644
index 8f6263533..000000000
--- a/db/changes/234004/00-workerTimeControl.sql
+++ /dev/null
@@ -1,41 +0,0 @@
-UPDATE `vn`.`workerTimeControlConfig`
- SET `timeToBreakTime` = 18000;
-
-ALTER TABLE `vn`.`workerTimeControlConfig`
- DROP COLUMN IF EXISTS `maxTimeToBreak`;
-ALTER TABLE `vn`.`workerTimeControlConfig`
- ADD COLUMN maxTimeToBreak INT DEFAULT 3600 NULL;
-
-ALTER TABLE `vn`.`workerTimeControlConfig`
- DROP COLUMN IF EXISTS `maxWorkShortCycle`;
-
-ALTER TABLE `vn`.`workerTimeControlConfig`
- ADD COLUMN `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';
-
-ALTER TABLE `vn`.`workerTimeControlConfig`
- DROP COLUMN IF EXISTS `maxWorkLongCycle`;
-
-ALTER TABLE `vn`.`workerTimeControlConfig`
- ADD COLUMN `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';
-
-CREATE TABLE IF NOT EXISTS `vn`.`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 AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-INSERT IGNORE INTO `vn`.`workerTimeControlError` (`code`, `description`)
- VALUES
- ('IS_NOT_ALLOWED_FUTURE', 'No se permite fichar a futuro'),
- ('INACTIVE_BUSINESS', 'No hay un contrato en vigor'),
- ('IS_NOT_ALLOWED_WORK', 'No está permitido trabajar'),
- ('ODD_WORKERTIMECONTROL', 'Fichadas impares'),
- ('DAY_MAX_TIME', 'Superado el tiempo máximo entre entrada y salida'),
- ('BREAK_DAY', 'Descanso diario'),
- ('BREAK_WEEK', 'Descanso semanal'),
- ('WRONG_DIRECTION', 'Dirección incorrecta'),
- ('UNDEFINED_ERROR', 'Error sin definir');
\ No newline at end of file
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-ACL_workerDepartment.sql b/db/changes/234201/00-ACL_workerDepartment.sql
deleted file mode 100644
index ceb8d5d75..000000000
--- a/db/changes/234201/00-ACL_workerDepartment.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('WorkerDepartment', '*', '*', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/234201/00-account_acl.sql b/db/changes/234201/00-account_acl.sql
deleted file mode 100644
index 8dfe1d1ec..000000000
--- a/db/changes/234201/00-account_acl.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('VnUser', 'higherPrivileges', '*', 'ALLOW', 'ROLE', 'itManagement'),
- ('VnUser', 'mediumPrivileges', '*', 'ALLOW', 'ROLE', 'hr'),
- ('VnUser', 'updateUser', '*', 'ALLOW', 'ROLE', 'employee');
-
-ALTER TABLE `account`.`user` ADD `username` varchar(30) AS (name) VIRTUAL;
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-aclSetPassword.sql b/db/changes/234201/00-aclSetPassword.sql
deleted file mode 100644
index 44b3e9de0..000000000
--- a/db/changes/234201/00-aclSetPassword.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
- VALUES ('Worker','setPassword','*','ALLOW','ROLE','employee');
-
-
diff --git a/db/changes/234201/00-aclUrlHedera.sql b/db/changes/234201/00-aclUrlHedera.sql
deleted file mode 100644
index 79d9fb4c8..000000000
--- a/db/changes/234201/00-aclUrlHedera.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-INSERT INTO `salix`.`url` (`appName`, `environment`, `url`)
- VALUES
- ('hedera', 'test', 'https://test-shop.verdnatura.es/'),
- ('hedera', 'production', 'https://shop.verdnatura.es/');
-
-INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId)
- VALUES('Url', 'getByUser', 'READ', 'ALLOW', 'ROLE', '$everyone');
diff --git a/db/changes/234201/00-dropWorkerCreate.sql b/db/changes/234201/00-dropWorkerCreate.sql
deleted file mode 100644
index b903909b6..000000000
--- a/db/changes/234201/00-dropWorkerCreate.sql
+++ /dev/null
@@ -1 +0,0 @@
-DROP PROCEDURE IF EXISTS `vn`.`workerCreate`;
diff --git a/db/changes/234201/00-packagingFk.sql b/db/changes/234201/00-packagingFk.sql
deleted file mode 100644
index 9a775ada9..000000000
--- a/db/changes/234201/00-packagingFk.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-ALTER TABLE `vn`.`buy` CHANGE `packageFk` `packagingFk` varchar(10)
-CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT '--' NULL;
-
-ALTER TABLE `vn`.`buy`
-ADD COLUMN `packageFk` varchar(10) AS (`packagingFk`) VIRTUAL;
\ No newline at end of file
diff --git a/db/changes/234201/00-packagingFkviews.sql b/db/changes/234201/00-packagingFkviews.sql
deleted file mode 100644
index 49d41c26c..000000000
--- a/db/changes/234201/00-packagingFkviews.sql
+++ /dev/null
@@ -1,150 +0,0 @@
-CREATE SCHEMA IF NOT EXISTS `vn2008`;
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `vn`.`awbVolume`
-AS SELECT `d`.`awbFk` AS `awbFk`,
- `b`.`stickers` * `i`.`density` * IF(
- `p`.`volume` > 0,
- `p`.`volume`,
- `p`.`width` * `p`.`depth` * IF(`p`.`height` = 0, `i`.`size` + 10, `p`.`height`)
- ) / (`vc`.`aerealVolumetricDensity` * 1000) AS `volume`,
- `b`.`id` AS `buyFk`
-FROM (
- (
- (
- (
- (
- (
- (
- (
- `vn`.`buy` `b`
- JOIN `vn`.`item` `i` ON(`b`.`itemFk` = `i`.`id`)
- )
- JOIN `vn`.`itemType` `it` ON(`i`.`typeFk` = `it`.`id`)
- )
- JOIN `vn`.`packaging` `p` ON(`p`.`id` = `b`.`packagingFk`)
- )
- JOIN `vn`.`entry` `e` ON(`b`.`entryFk` = `e`.`id`)
- )
- JOIN `vn`.`travel` `t` ON(`t`.`id` = `e`.`travelFk`)
- )
- JOIN `vn`.`duaEntry` `de` ON(`de`.`entryFk` = `e`.`id`)
- )
- JOIN `vn`.`dua` `d` ON(`d`.`id` = `de`.`duaFk`)
- )
- JOIN `vn`.`volumeConfig` `vc`
- )
-WHERE `t`.`shipped` > makedate(year(`util`.`VN_CURDATE`()) - 1, 1);
-
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `vn2008`.`Compres`
-AS SELECT `c`.`id` AS `Id_Compra`,
- `c`.`entryFk` AS `Id_Entrada`,
- `c`.`itemFk` AS `Id_Article`,
- `c`.`buyingValue` AS `Costefijo`,
- `c`.`quantity` AS `Cantidad`,
- `c`.`packagingFk` AS `Id_Cubo`,
- `c`.`stickers` AS `Etiquetas`,
- `c`.`freightValue` AS `Portefijo`,
- `c`.`packageValue` AS `Embalajefijo`,
- `c`.`comissionValue` AS `Comisionfija`,
- `c`.`packing` AS `Packing`,
- `c`.`grouping` AS `grouping`,
- `c`.`groupingMode` AS `caja`,
- `c`.`location` AS `Nicho`,
- `c`.`price1` AS `Tarifa1`,
- `c`.`price2` AS `Tarifa2`,
- `c`.`price3` AS `Tarifa3`,
- `c`.`minPrice` AS `PVP`,
- `c`.`printedStickers` AS `Vida`,
- `c`.`isChecked` AS `punteo`,
- `c`.`ektFk` AS `buy_edi_id`,
- `c`.`created` AS `odbc_date`,
- `c`.`isIgnored` AS `Novincular`,
- `c`.`isPickedOff` AS `isPickedOff`,
- `c`.`workerFk` AS `Id_Trabajador`,
- `c`.`weight` AS `weight`,
- `c`.`dispatched` AS `dispatched`,
- `c`.`containerFk` AS `container_id`,
- `c`.`itemOriginalFk` AS `itemOriginalFk`
-FROM `vn`.`buy` `c`;
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `vn2008`.`buySource`
-AS SELECT `b`.`entryFk` AS `Id_Entrada`,
- `b`.`isPickedOff` AS `isPickedOff`,
- NULL AS `tarifa0`,
- `e`.`kop` AS `kop`,
- `b`.`id` AS `Id_Compra`,
- `i`.`typeFk` AS `tipo_id`,
- `b`.`itemFk` AS `Id_Article`,
- `i`.`size` AS `Medida`,
- `i`.`stems` AS `Tallos`,
- `b`.`stickers` AS `Etiquetas`,
- `b`.`packagingFk` AS `Id_Cubo`,
- `b`.`buyingValue` AS `Costefijo`,
- `b`.`packing` AS `Packing`,
- `b`.`grouping` AS `Grouping`,
- `b`.`quantity` AS `Cantidad`,
- `b`.`price2` AS `Tarifa2`,
- `b`.`price3` AS `Tarifa3`,
- `b`.`isChecked` AS `Punteo`,
- `b`.`groupingMode` AS `Caja`,
- `i`.`isToPrint` AS `Imprimir`,
- `i`.`name` AS `Article`,
- `vn`.`ink`.`picture` AS `Tinta`,
- `i`.`originFk` AS `id_origen`,
- `i`.`minPrice` AS `PVP`,
- NULL AS `Id_Accion`,
- `s`.`company_name` AS `pro`,
- `i`.`hasMinPrice` AS `Min`,
- `b`.`isIgnored` AS `Novincular`,
- `b`.`freightValue` AS `Portefijo`,
- round(`b`.`buyingValue` * `b`.`quantity`, 2) AS `Importe`,
- `b`.`printedStickers` AS `Vida`,
- `i`.`comment` AS `reference`,
- `b`.`workerFk` AS `Id_Trabajador`,
- `e`.`s1` AS `S1`,
- `e`.`s2` AS `S2`,
- `e`.`s3` AS `S3`,
- `e`.`s4` AS `S4`,
- `e`.`s5` AS `S5`,
- `e`.`s6` AS `S6`,
- 0 AS `price_fixed`,
- `i`.`producerFk` AS `producer_id`,
- `i`.`subName` AS `tag1`,
- `i`.`value5` AS `tag2`,
- `i`.`value6` AS `tag3`,
- `i`.`value7` AS `tag4`,
- `i`.`value8` AS `tag5`,
- `i`.`value9` AS `tag6`,
- `s`.`company_name` AS `company_name`,
- `b`.`weight` AS `weightPacking`,
- `i`.`packingOut` AS `packingOut`,
- `b`.`itemOriginalFk` AS `itemOriginalFk`,
- `io`.`longName` AS `itemOriginalName`,
- `it`.`gramsMax` AS `gramsMax`
-FROM (
- (
- (
- (
- (
- (
- `vn`.`item` `i`
- JOIN `vn`.`itemType` `it` ON(`it`.`id` = `i`.`typeFk`)
- )
- LEFT JOIN `vn`.`ink` ON(`vn`.`ink`.`id` = `i`.`inkFk`)
- )
- LEFT JOIN `vn`.`buy` `b` ON(`b`.`itemFk` = `i`.`id`)
- )
- LEFT JOIN `vn`.`item` `io` ON(`io`.`id` = `b`.`itemOriginalFk`)
- )
- LEFT JOIN `edi`.`ekt` `e` ON(`e`.`id` = `b`.`ektFk`)
- )
- LEFT JOIN `edi`.`supplier` `s` ON(`e`.`pro` = `s`.`supplier_id`)
- );
-
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/changes/234201/00-zoneIncluded.sql b/db/changes/234201/00-zoneIncluded.sql
deleted file mode 100644
index 12d4058cf..000000000
--- a/db/changes/234201/00-zoneIncluded.sql
+++ /dev/null
@@ -1,26 +0,0 @@
-ALTER TABLE `vn`.`zoneIncluded`
- ADD COLUMN `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
- DROP PRIMARY KEY,
- DROP FOREIGN KEY `zoneFk2`,
- DROP FOREIGN KEY `zoneGeoFk2`,
- DROP KEY `geoFk_idx`,
- ADD PRIMARY KEY (`id`),
- ADD CONSTRAINT `zoneIncluded_FK_1` FOREIGN KEY (zoneFk) REFERENCES `vn`.`zone`(id) ON DELETE CASCADE ON UPDATE CASCADE,
- ADD CONSTRAINT `zoneIncluded_FK_2` FOREIGN KEY (geoFk) REFERENCES `vn`.`zoneGeo`(id) ON DELETE CASCADE ON UPDATE CASCADE,
- ADD CONSTRAINT `unique_zone_geo` UNIQUE (`zoneFk`, `geoFk`);
-
-DROP TRIGGER IF EXISTS `vn`.`zoneIncluded_afterDelete`;
-USE `vn`;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` 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 ;
diff --git a/db/changes/234201/03-packagingFkProc.sql b/db/changes/234201/03-packagingFkProc.sql
deleted file mode 100644
index 4876c270e..000000000
--- a/db/changes/234201/03-packagingFkProc.sql
+++ /dev/null
@@ -1,1381 +0,0 @@
-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 ;
-
-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 ;
-
-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 ;
-
-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 ;
-
-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 ;
-
-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 ;
-
-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;
-
- 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 ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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.packagingFk ,
- 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.packagingFk
- LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk
- WHERE ic.itemFk = vItemFk
- AND ic.warehouseFk = vWarehouseFk;
-END$$
-DELIMITER ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryMake`(vDate DATE, vWh INT)
-proc: BEGIN
-/**
-* Recalcula los inventarios de todos los almacenes, si vWh = 0
-*
-* @param vDate Fecha de los nuevos inventarios
-* @param vWh almacen al cual hacer el inventario
-*/
-
- DECLARE vDone BOOL;
- DECLARE vEntryFk INT;
- DECLARE vTravelFk INT;
- DECLARE vDateLastInventory DATE;
- DECLARE vDateYesterday DATETIME DEFAULT vDate - INTERVAL 1 SECOND;
- DECLARE vWarehouseOutFkInventory INT;
- DECLARE vInventorySupplierFk INT;
- DECLARE vAgencyModeFkInventory INT;
-
- DECLARE cWarehouses CURSOR FOR
- SELECT id
- FROM warehouse
- WHERE isInventory
- AND vWh IN (0,id);
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
- OPEN cWarehouses;
- SET @isModeInventory := TRUE;
- l: LOOP
-
- SET vDone = FALSE;
- FETCH cWarehouses INTO vWh;
-
- 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;
-
- SELECT id INTO vTravelFk
- FROM travel
- WHERE warehouseOutFk = vWarehouseOutFkInventory
- AND warehouseInFk = vWh
- AND landed = vDate
- 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;
-
- SELECT LAST_INSERT_ID() INTO vTravelFk;
-
- END IF;
-
- -- Generamos entrada si no existe, o la vaciamos.
- SET vEntryFk = 0;
-
- SELECT id INTO vEntryFk
- FROM entry
- WHERE supplierFk = vInventorySupplierFk
- AND travelFk = vTravelFk;
-
- IF NOT vEntryFk 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;
-
- -- Compras
- INSERT INTO tmp.inventory(itemFk,quantity)
- SELECT b.itemFk, SUM(b.quantity)
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel tr ON tr.id = e.travelFk
- WHERE tr.warehouseInFk = vWh
- AND tr.landed BETWEEN vDateLastInventory
- AND vDateYesterday
- AND NOT isRaid
- GROUP BY b.itemFk;
- SELECT vDateLastInventory , vDateYesterday;
-
- -- Traslados
- INSERT INTO tmp.inventory(itemFk, quantity)
- SELECT itemFk, quantityOut
- FROM (
- SELECT b.itemFk,- SUM(b.quantity) quantityOut
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel tr ON tr.id = e.travelFk
- WHERE tr.warehouseOutFk = vWh
- AND tr.shipped BETWEEN vDateLastInventory
- AND vDateYesterday
- AND NOT isRaid
- GROUP BY b.itemFk
- ) sub
- ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut;
-
- -- Ventas
- INSERT INTO tmp.inventory(itemFk,quantity)
- SELECT itemFk, saleOut
- FROM (
- SELECT s.itemFk, - SUM(s.quantity) saleOut
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- WHERE t.warehouseFk = vWh
- AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday
- GROUP BY s.itemFk
- ) sub
- ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut;
-
- -- Actualiza valores de la ultima compra
- UPDATE tmp.inventory inv
- JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh
- JOIN buy b ON b.id = lb.buy_id
- 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,
- packagingFk,
- price1,
- price2,
- price3,
- minPrice,
- vEntryFk
- FROM tmp.inventory;
-
- 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;
-
- END LOOP;
-
- CLOSE cWarehouses;
-
- UPDATE config SET inventoried = vDate;
- SET @isModeInventory := FALSE;
-
- 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
- FROM travel t
- JOIN `entry` e ON e.travelFk = t.id
- 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);
-
- DELETE e
- FROM `entry` e
- JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id;
-
- DELETE IGNORE t
- FROM travel t
- JOIN tmp.entryToDelete tmp ON tmp.travelId = t.id;
-END$$
-DELIMITER ;
-
-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.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
- (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.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;
-END$$
-DELIMITER ;
-
-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;
-
-END$$
-DELIMITER ;
-
-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 ;
-
-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,3);
- 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 ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`ekt_load`(IN `vSelf` INT)
-proc:BEGIN
-
- DECLARE vRef INT;
- DECLARE vBuy INT;
- DECLARE vItem INT;
- DECLARE vQty INT;
- 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 vHasItemGroup BOOL;
- DECLARE vDescription VARCHAR(255);
- DECLARE vSaleFk INT;
-
- -- Carga los datos necesarios del EKT
-
- SELECT e.ref, qty, package, putOrderFk MOD 1000000, i2.id , NOT ISNULL(eea.addressFk), NOT ISNULL(igto.group_code),
- CONCAT(e.`ref`, ' ', e.item, ' ', e.sub, ' EktFk:', e.id)
- INTO vRef, vQty, vPackage, vPutOrderFk, vItem, vIsFloramondoDirect, vHasItemGroup, vDescription
- FROM 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
- LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub
- LEFT JOIN edi.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;
-
- -- Asigna la entrada
- SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk;
-
- -- Inserta el cubo si no existe
-
- IF vPackage = 800 THEN
-
- SET vHasToChangePackagingFk = TRUE;
-
- IF vItem THEN
-
- SELECT vn.item_getPackage(vItem) INTO vPackage ;
-
- ELSE
-
- SET vPackage = 8000 + vQty;
-
- INSERT IGNORE INTO vn.packaging(id, width, `depth`)
- SELECT vPackage, vc.ccLength / vQty, vc.ccWidth
- FROM vn.volumeConfig vc;
-
- END IF;
-
- ELSE
-
- INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z)
- SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10)
- FROM bucket WHERE bucket_id = vPackage;
-
- IF ROW_COUNT() > 0
- THEN
- INSERT INTO vn2008.mail SET
- `subject` = 'Cubo añadido',
- `text` = CONCAT('Se ha añadido el cubo: ', vPackage),
- `to` = 'ekt@verdnatura.es';
- END IF;
- END IF;
-
- -- Si es una compra de Logiflora obtiene el articulo
- IF vPutOrderFk THEN
-
- SELECT i.id INTO vItem
- FROM edi.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
-
- -- 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
- 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 IF(t.s1, l.s1 = e.s1, TRUE)
- AND IF(t.s2, l.s2 = e.s2, TRUE)
- AND IF(t.s3, l.s3 = e.s3, TRUE)
- AND IF(t.s4, l.s4 = e.s4, TRUE)
- AND IF(t.s5, l.s5 = e.s5, TRUE)
- AND IF(t.s6, l.s6 = e.s6, TRUE)
- AND IF(t.pac, l.pac = e.pac, TRUE)
- AND IF(t.cat, l.cat = e.cat, TRUE)
- AND IF(t.ori, l.ori = e.ori, TRUE)
- AND IF(t.pro, l.pro = e.pro, TRUE)
- AND IF(t.package, l.package = e.package, TRUE)
- AND IF(t.item, l.item = e.item, TRUE)
- AND i.isFloramondo = vIsFloramondoDirect
- ORDER BY l.now DESC, b.id ASC
- LIMIT 1;
-
- END IF;
-
- -- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo
- IF ISNULL(vItem) AND vIsFloramondoDirect THEN
-
- CALL edi.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, 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.packagingFk), vPackage, b.packagingFk)
- ,(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
- SELECT buy.id
- FROM vn.buy
- WHERE ektFk = vSelf;
-
- CALL vn.buy_recalcPrices();
-
- -- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy
- IF vPutOrderFk THEN
-
- REPLACE vn.saleBuy(saleFk, buyFk, workerFk)
- SELECT po.saleFk, b.id, account.myUser_getId()
- FROM edi.putOrder po
- JOIN vn.buy b ON b.ektFk = vSelf
- WHERE po.id = vPutOrderFk;
-
- END IF;
- -- Si es una compra directa en Floramondo hay que añadirlo al ticket
-
- IF vIsFloramondoDirect THEN
-
- SELECT t.id INTO vTicketFk
- FROM vn.ticket t
- JOIN vn.ektEntryAssign eea
- ON eea.addressFk = t.addressFk
- AND t.warehouseFk = eea.warehouseInFk
- JOIN edi.ekt e
- ON e.sub = eea.sub
- AND e.id = vSelf
- WHERE e.fec = t.shipped
- LIMIT 1;
-
- IF ISNULL(vTicketFk) THEN
-
- INSERT INTO vn.ticket (
- clientFk,
- shipped,
- addressFk,
- agencyModeFk,
- nickname,
- warehouseFk,
- companyFk,
- 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
- JOIN vn.address a ON a.id = eea.addressFk
- JOIN vn.company c ON c.code = 'VNL'
- JOIN vn.`zone` z ON z.code = 'FLORAMONDO'
- WHERE e.id = vSelf
- LIMIT 1;
-
- SET vTicketFk = LAST_INSERT_ID();
-
- INSERT INTO vn.ticketLog
- SET originFk = vTicketFk,
- userFk = account.myUser_getId(),
- `action` = 'insert',
- description = CONCAT('EktLoad ha creado el ticket:', ' ', vTicketFk);
-
- 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;
-
- SELECT LAST_INSERT_ID() INTO vSaleFk;
-
- REPLACE vn.saleBuy(saleFk, buyFk, workerFk)
- SELECT vSaleFk, b.id, account.myUser_getId()
- FROM vn.buy b
- WHERE b.ektFk = vSelf;
-
- INSERT INTO vn.saleComponent(saleFk, componentFk, value)
- SELECT vSaleFk, c.id, e.pri
- FROM edi.ekt e
- JOIN vn.component c ON c.code = 'purchaseValue'
- WHERE e.id = vSelf;
-
- INSERT INTO vn.saleComponent(saleFk, componentFk, value)
- SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin
- FROM edi.ekt e
- JOIN edi.floraHollandConfig fhc
- JOIN vn.component c ON c.code = 'margin'
- WHERE e.id = vSelf;
- END IF;
- DROP TEMPORARY TABLE tmp.buyRecalc;
-END$$
-DELIMITER ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`item_getVisible`(
- vWarehouse TINYINT,
- vDate DATE,
- vType INT,
- vPrefix VARCHAR(255))
-BEGIN
-
-/**
- * Gets visible items of the specified type at specified date.
- *
- * @param vWarehouse The warehouse id
- * @param vDate The visible date
- * @param vType The type id
- * @param vPrefix The article prefix to filter or %NULL for all
- * @return tmp.itemVisible Visible items
- */
- DECLARE vPrefixLen SMALLINT;
- DECLARE vFilter VARCHAR(255) DEFAULT NULL;
- DECLARE vDateInv DATE DEFAULT vn2008.date_inv();
- DECLARE EXIT HANDLER FOR 1114
- BEGIN
- GET DIAGNOSTICS CONDITION 1
- @message = MESSAGE_TEXT;
- CALL vn.mail_insert(
- 'cau@verdnatura.es',
- NULL,
- CONCAT('hedera.item_getVisible error: ', @message),
- CONCAT(
- 'warehouse: ', IFNULL(vWarehouse, ''),
- ', Fecha:', IFNULL(vDate, ''),
- ', tipo: ', IFNULL(vType,''),
- ', prefijo: ', IFNULL(vPrefix,'')));
- RESIGNAL;
- END;
- SET vPrefixLen = IFNULL(LENGTH(vPrefix), 0) + 1;
-
- IF vPrefixLen > 1 THEN
- SET vFilter = CONCAT(vPrefix, '%');
- END IF;
-
- DROP TEMPORARY TABLE IF EXISTS `filter`;
- CREATE TEMPORARY TABLE `filter`
- (INDEX (itemFk))
- ENGINE = MEMORY
- SELECT id itemFk FROM vn.item
- WHERE typeFk = vType
- AND (vFilter IS NULL OR `name` LIKE vFilter);
-
- DROP TEMPORARY TABLE IF EXISTS currentStock;
- CREATE TEMPORARY TABLE currentStock
- (INDEX (itemFk))
- ENGINE = MEMORY
- SELECT itemFk, SUM(quantity) quantity
- FROM (
- SELECT b.itemFk, b.quantity
- FROM vn.buy b
- JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vDateInv AND vDate
- AND t.warehouseInFk = vWarehouse
- AND NOT e.isRaid
- UNION ALL
- SELECT b.itemFk, -b.quantity
- FROM vn.buy b
- JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.travel t ON t.id = e.travelFk
- WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE()
- AND t.warehouseOutFk = vWarehouse
- AND NOT e.isRaid
- AND t.isDelivered
- UNION ALL
- SELECT m.itemFk, -m.quantity
- FROM vn.sale m
- JOIN vn.ticket t ON t.id = m.ticketFk
- JOIN vn.ticketState s ON s.ticket = t.id
- WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE()
- AND t.warehouseFk = vWarehouse
- AND s.alertLevel = 3
- ) t
- GROUP BY itemFk
- HAVING quantity > 0;
-
- DROP TEMPORARY TABLE IF EXISTS tmp;
- CREATE TEMPORARY TABLE tmp
- (INDEX (itemFk))
- ENGINE = MEMORY
- SELECT *
- FROM (
- SELECT b.itemFk, b.packagingFk, b.packing
- FROM vn.buy b
- JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vDateInv AND vDate
- AND NOT b.isIgnored
- AND b.price2 >= 0
- AND b.packagingFk IS NOT NULL
- ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC
- LIMIT 10000000000000000000
- ) t GROUP BY itemFk;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.itemVisible;
- CREATE TEMPORARY TABLE tmp.itemVisible
- ENGINE = MEMORY
- SELECT i.id Id_Article,
- SUBSTRING(i.`name`, vPrefixLen) Article,
- t.packing, p.id Id_Cubo,
- IF(p.depth > 0, p.depth, 0) depth, p.width, p.height,
- CEIL(s.quantity / t.packing) etiquetas
- FROM vn.item i
- JOIN `filter` f ON f.itemFk = i.id
- JOIN currentStock s ON s.itemFk = i.id
- LEFT JOIN tmp t ON t.itemFk = i.id
- LEFT JOIN vn.packaging p ON p.id = t.packagingFk
- WHERE CEIL(s.quantity / t.packing) > 0
- -- FIXME: Column Cubos.box not included in view vn.packaging
- /* AND p.box */;
-
- DROP TEMPORARY TABLE
- `filter`,
- currentStock,
- tmp;
-END$$
-DELIMITER ;
-
-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 ;
-
-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 ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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.packagingFk) 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.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') 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 ;
-
diff --git a/db/changes/234601/.gitkeep b/db/changes/234601/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/234601/00-ACLticketTrackingState.sql b/db/changes/234601/00-ACLticketTrackingState.sql
deleted file mode 100644
index ca6dce0c9..000000000
--- a/db/changes/234601/00-ACLticketTrackingState.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-UPDATE `salix`.`ACL`
- SET `property` = 'state',
- `model` = 'Ticket'
- WHERE `property` = 'changeState';
diff --git a/db/changes/234601/00-claimViewerAcl.sql b/db/changes/234601/00-claimViewerAcl.sql
deleted file mode 100644
index 17d8d4ce0..000000000
--- a/db/changes/234601/00-claimViewerAcl.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');
diff --git a/db/changes/234601/00-clientAfterUpdate.sql b/db/changes/234601/00-clientAfterUpdate.sql
deleted file mode 100644
index c6483813f..000000000
--- a/db/changes/234601/00-clientAfterUpdate.sql
+++ /dev/null
@@ -1,95 +0,0 @@
-ALTER TABLE `vn`.`client` MODIFY COLUMN `credit` decimal(10,2) unsigned DEFAULT 0.00 NOT NULL;
-
-DELETE FROM `salix`.`ACL` WHERE `model` = 'Client' AND `property` = 'create';
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` 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();
-
- IF NOT(NEW.credit <=> OLD.credit) THEN
- INSERT INTO clientCredit
- SET clientFk = NEW.id,
- amount = NEW.credit,
- workerFk = NEW.editorFk;
- END IF;
- -- 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 ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_AfterInsert`
- AFTER INSERT ON `client`
- FOR EACH ROW
-BEGIN
- IF NEW.credit IS NOT NULL AND NEW.credit THEN
- INSERT INTO clientCredit
- SET clientFk = NEW.id,
- workerFk = NEW.editorFk,
- amount = NEW.credit;
- END IF;
-END$$
-DELIMITER ;
-
diff --git a/db/changes/234601/00-transferInvoice.sql b/db/changes/234601/00-transferInvoice.sql
deleted file mode 100644
index d9ae39464..000000000
--- a/db/changes/234601/00-transferInvoice.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'),
- ('SiiTypeInvoiceOut', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'),
- ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'),
- ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'administrative');
diff --git a/db/changes/234601/00-updateCourtesyTime.sql b/db/changes/234601/00-updateCourtesyTime.sql
deleted file mode 100644
index 4751b2e03..000000000
--- a/db/changes/234601/00-updateCourtesyTime.sql
+++ /dev/null
@@ -1,4 +0,0 @@
--- Auto-generated SQL script #202311061003
-UPDATE salix.accessTokenConfig
- SET courtesyTime=60
- WHERE id=1;
diff --git a/db/changes/234602/00-roleSync.sql b/db/changes/234602/00-roleSync.sql
deleted file mode 100644
index 7ce277748..000000000
--- a/db/changes/234602/00-roleSync.sql
+++ /dev/null
@@ -1 +0,0 @@
-CALL `account`.`role_sync`();
diff --git a/db/changes/234604/00-sambaConfigUserDn.sql b/db/changes/234604/00-sambaConfigUserDn.sql
deleted file mode 100644
index cacb30e97..000000000
--- a/db/changes/234604/00-sambaConfigUserDn.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-ALTER TABLE account.sambaConfig
- ADD userDn varchar(255) NOT NULL COMMENT 'Base DN for users without domain DN part';
diff --git a/db/changes/234801/.gitkeep b/db/changes/234801/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/234801/00-ACL_executeRoutine.sql b/db/changes/234801/00-ACL_executeRoutine.sql
deleted file mode 100644
index cfe7018e9..000000000
--- a/db/changes/234801/00-ACL_executeRoutine.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
- VALUES
- ('Application', 'executeProc', '*', 'ALLOW', 'ROLE', 'employee'),
- ('Application', 'executeFunc', '*', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/234801/00-notificationSubscription.sql b/db/changes/234801/00-notificationSubscription.sql
deleted file mode 100644
index ef081437d..000000000
--- a/db/changes/234801/00-notificationSubscription.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('NotificationSubscription', 'getList', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/234801/00-zoneIncluded_trigger.sql b/db/changes/234801/00-zoneIncluded_trigger.sql
deleted file mode 100644
index 7684e7787..000000000
--- a/db/changes/234801/00-zoneIncluded_trigger.sql
+++ /dev/null
@@ -1,70 +0,0 @@
-DROP TRIGGER IF EXISTS `vn`.`zoneIncluded_afterInsert`;
-USE `vn`;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`zoneIncluded_afterInsert`
- AFTER INSERT ON `zoneIncluded`
- FOR EACH ROW
-BEGIN
- INSERT INTO zoneLog
- SET `action` = 'insert',
- `changedModel` = 'zoneIncluded',
- `changedModelId` = NEW.zoneFk,
- `userFk` = account.myUser_getId();
- INSERT INTO zoneIncludedCheck
- SET
- `action`= 'insert',
- `zoneFk` = NEW.zoneFk,
- `geoFk` = NEW.geoFk,
- `userFk` = account.myUser_getId();
-
-END$$
-DELIMITER ;
-
-DROP TRIGGER IF EXISTS `vn`.`zoneIncluded_afterUpdate`;
-USE `vn`;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`zoneIncluded_afterUpdate`
- AFTER UPDATE ON `zoneIncluded`
- FOR EACH ROW
-BEGIN
- INSERT INTO zoneLog
- SET `action` = 'update',
- `changedModel` = 'zoneIncluded',
- `changedModelId` = OLD.zoneFk,
- `userFk` = account.myUser_getId();
- INSERT INTO zoneIncludedCheck
- SET
- `action`= 'update',
- `zoneFk` = NEW.zoneFk,
- `geoFk` = NEW.geoFk,
- `userFk` = account.myUser_getId();
-
-
-
-END$$
-DELIMITER ;
-
-DROP TRIGGER IF EXISTS `vn`.`zoneIncluded_afterDelete`;
-USE `vn`;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` 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();
- INSERT INTO zoneIncludedCheck
- SET
- `action`= 'delete',
- `zoneFk` = OLD.zoneFk,
- `geoFk` = OLD.geoFk,
- `userFk` = account.myUser_getId();
-
-END$$
-DELIMITER ;
diff --git a/db/changes/234801/01-zoneIncluded_table_zoneincludedCheck.sql b/db/changes/234801/01-zoneIncluded_table_zoneincludedCheck.sql
deleted file mode 100644
index ba52f76b0..000000000
--- a/db/changes/234801/01-zoneIncluded_table_zoneincludedCheck.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-CREATE TABLE `vn`.`zoneIncludedCheck` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `zoneFK` int(11) NOT NULL,
- `geoFK` int(11) NOT NULL,
- `userFK` int(10) unsigned NOT NULL,
- `action`set('insert','update','delete') NOT NULL,
- PRIMARY KEY (`id`),
- CONSTRAINT `user_FK` FOREIGN KEY (`userFK`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
- CONSTRAINT `zone_FK` FOREIGN KEY (`zoneFK`) REFERENCES `vn`.`zone` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
- CONSTRAINT `geo_FK` FOREIGN KEY (`geoFK`) REFERENCES `vn`.`zoneGeo` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
- UNIQUE INDEX (`zoneFK`, `geoFK`, `userFK`, `action`)
-)
-
-comment 'Table to save temporarily zone changes';
diff --git a/db/changes/234801/02-zoneIncluded_event_checkCollisions.sql b/db/changes/234801/02-zoneIncluded_event_checkCollisions.sql
deleted file mode 100644
index 3a6dd32b8..000000000
--- a/db/changes/234801/02-zoneIncluded_event_checkCollisions.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-USE vn;
-CREATE EVENT zoneCollisionsCheck
-ON SCHEDULE AT CURRENT_TIMESTAMP
-DISABLE ON SLAVE
-DO SELECT vn.zoneIncluded_checkCollisions;
diff --git a/db/changes/234801/03-zoneIncluded_procedure_checkCollisions.sql b/db/changes/234801/03-zoneIncluded_procedure_checkCollisions.sql
deleted file mode 100644
index 99cab6746..000000000
--- a/db/changes/234801/03-zoneIncluded_procedure_checkCollisions.sql
+++ /dev/null
@@ -1,107 +0,0 @@
-DROP PROCEDURE IF EXISTS vn.zoneIncluded_checkCollisions;
-
-DELIMITER $$
-CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneIncluded_checkCollisions`()
-BEGIN
-/**
- * Calcula si para un mismo codigo postal y dia
- * hay mas de una zona configurada y manda correo
- *
- */
- DECLARE vGeoFk INT DEFAULT NULL;
- DECLARE vZoneFk INT;
- DECLARE vIsDone INT DEFAULT FALSE;
- DECLARE vTableCollisions TEXT;
- DECLARE json_data JSON;
- DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.zone;
- CREATE TEMPORARY TABLE tmp.zone
- SELECT z.id
- FROM zone z
- JOIN agencyMode am ON am.id = z.agencyModeFk
- JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
- WHERE dm.code IN ('AGENCY','DELIVERY');
-
- CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE);
-
- DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes;
- CREATE TEMPORARY TABLE tmp.zoneNodes (
- geoFk INT,
- name VARCHAR(100),
- parentFk INT,
- sons INT,
- isChecked BOOL DEFAULT 0,
- zoneFk INT,
- PRIMARY KEY zoneFkk (zoneFk, geoFk),
- INDEX(geoFk))
- ENGINE = MyISAM;
-
- OPEN cur1;
- cur1Loop: LOOP
- SET vIsDone = FALSE;
- FETCH cur1 INTO vZoneFk;
- IF vIsDone THEN
- LEAVE cur1Loop;
- END IF;
-
- CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE);
-
- myLoop: LOOP
- SET vGeoFk = NULL;
- SELECT geoFk INTO vGeoFk
- FROM tmp.zoneNodes zn
- WHERE NOT isChecked
- LIMIT 1;
-
- IF vGeoFk IS NULL THEN
- LEAVE myLoop;
- END IF;
-
- CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE);
- UPDATE tmp.zoneNodes
- SET isChecked = TRUE
- WHERE geoFk = vGeoFk;
- END LOOP;
-
- END LOOP;
- CLOSE cur1;
- DELETE FROM tmp.zoneNodes
- WHERE sons > 0;
-
- DROP TEMPORARY TABLE IF EXISTS geoCollision;
- CREATE TEMPORARY TABLE geoCollision
- SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk
- FROM tmp.zoneNodes zn
- JOIN zone z ON z.id = zn.zoneFk
- JOIN zoneWarehouse zw ON z.id = zw.zoneFk
- GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk
- HAVING count(*) > 1;
-
- SELECT JSON_ARRAYAGG(
- JSON_OBJECT(
- 'zoneFk', zoneFk,
- 'zn', JSON_OBJECT('name', zn.name),
- 'z', JSON_OBJECT('name', z.name,'price', z.price),
- 'w', JSON_OBJECT('name', w.name)
- )
- ) FROM tmp.zoneNodes zn
- JOIN zone z ON z.id = zn.zoneFk
- JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk
- JOIN warehouse w ON w.id = gc.warehouseFk
- INTO json_data;
-
- SELECT util.notification_send(
- 'zone-included',
- JSON_OBJECT('zoneCollisions',json_data),
- account.myUser_getId()
- );
-
- DROP TEMPORARY TABLE
- geoCollision,
- tmp.zone,
- tmp.zoneNodes;
-END ;;
-DELIMITER ;
diff --git a/db/changes/234801/04-remove_procedure_bs_nightTask.sql b/db/changes/234801/04-remove_procedure_bs_nightTask.sql
deleted file mode 100644
index 530dc6ef5..000000000
--- a/db/changes/234801/04-remove_procedure_bs_nightTask.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-DELETE FROM bs.nightTask
- WHERE `procedure` ='zone_getCollisions';
diff --git a/db/changes/234801/05-drop_procedure_zone_getCollisions.sql b/db/changes/234801/05-drop_procedure_zone_getCollisions.sql
deleted file mode 100644
index 9d0db5465..000000000
--- a/db/changes/234801/05-drop_procedure_zone_getCollisions.sql
+++ /dev/null
@@ -1 +0,0 @@
-DROP PROCEDURE vn.zone_getCollisions;
diff --git a/db/changes/234801/06-zoneincluded_notification.sql b/db/changes/234801/06-zoneincluded_notification.sql
deleted file mode 100644
index d05902461..000000000
--- a/db/changes/234801/06-zoneincluded_notification.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-INSERT INTO util.notification (id, name,description)
- VALUES (
-(SELECT MAX(id)+1 from util.notification n) , 'zone-included','An email to notify zoneCollisions');
-
-INSERT INTO util.notificationSubscription (notificationFk,userFk)
- SELECT id, account.myUser_getId() FROM util.notification WHERE name= "zone-included";
-
-
-INSERT INTO util.notificationAcl (notificationFk,roleFk)
- SELECT id, (SELECT id from `account`.`role` where name = "system") FROM util.notification WHERE name= "zone-included";
diff --git a/db/changes/234802/00-createSignInLogTable.sql b/db/changes/234802/00-createSignInLogTable.sql
deleted file mode 100644
index 942f651c9..000000000
--- a/db/changes/234802/00-createSignInLogTable.sql
+++ /dev/null
@@ -1,21 +0,0 @@
-
---
--- Table structure for table `signInLog`
--- Description: log to debug cross-login error
---
-
-DROP TABLE IF EXISTS `account`.`signInLog`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `account`.`signInLog` (
- id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
- `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) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- `owner` tinyint(1) DEFAULT 1,
- KEY `userFk` (`userFk`),
- CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-);
-
diff --git a/db/changes/235001/.gitkeep b/db/changes/235001/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/235001/00-getRoutesByWorker.sql b/db/changes/235001/00-getRoutesByWorker.sql
deleted file mode 100644
index 00d6e658a..000000000
--- a/db/changes/235001/00-getRoutesByWorker.sql
+++ /dev/null
@@ -1,26 +0,0 @@
-DELETE FROM `salix`.`ACL`
- WHERE
- model = 'Route'
- AND property = '*'
- AND accessType = 'READ';
-
-INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
- VALUES
- ('Route', 'find', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'findById', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'findOne', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'getRoutesByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'canViewAllRoute', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'),
- ('Route', 'cmr', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'downloadCmrsZip', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'downloadZip', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'filter', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'getByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'getExternalCmrs', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'getSuggestedTickets', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'getTickets', 'READ', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'guessPriority', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'insertTicket', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
- ('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'),
- ('Route', 'summary', 'READ', 'ALLOW', 'ROLE', 'employee');
diff --git a/db/changes/235001/00-silexToSalix.sql b/db/changes/235001/00-silexToSalix.sql
deleted file mode 100644
index bad430ac2..000000000
--- a/db/changes/235001/00-silexToSalix.sql
+++ /dev/null
@@ -1,46 +0,0 @@
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeInsert`
- BEFORE INSERT ON `delivery`
- FOR EACH ROW
-BEGIN
-
- IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL)
- THEN
- UPDATE address
- SET longitude = NEW.longitude,
- latitude = NEW.latitude
- WHERE id IN (
- SELECT addressFK
- FROM ticket
- WHERE id = NEW.ticketFk
- );
- END IF;
-
-END$$
-DELIMITER ;
-
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeUpdate`
- BEFORE UPDATE ON `delivery`
- FOR EACH ROW
-BEGIN
-
-IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL)
- THEN
- UPDATE address
- SET longitude = NEW.longitude,
- latitude = NEW.latitude
- WHERE id IN (
- SELECT addressFK
- FROM ticket
- WHERE id = NEW.ticketFk
- );
- END IF;
-
-END$$
-DELIMITER ;
-
-
-ALTER TABLE `vn`.`address` MODIFY COLUMN longitude decimal(11,7) DEFAULT NULL NULL COMMENT 'Indica la última longitud proporcionada por tabla delivery';
-ALTER TABLE `vn`.`address` MODIFY COLUMN latitude decimal(11,7) DEFAULT NULL NULL COMMENT 'Indica la última latitud proporcionada por tabla delivery';
diff --git a/db/changes/240001/00-alterTable.sql b/db/changes/240001/00-alterTable.sql
deleted file mode 100644
index b6974b715..000000000
--- a/db/changes/240001/00-alterTable.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `vn`.`ticketTracking` CHANGE `workerFk` `userFk` int(10) unsigned DEFAULT NULL NULL;
\ No newline at end of file
diff --git a/db/changes/240001/00-clientCreditLimitToRoleCreditLimit.sql b/db/changes/240001/00-clientCreditLimitToRoleCreditLimit.sql
deleted file mode 100644
index 2bc0f830d..000000000
--- a/db/changes/240001/00-clientCreditLimitToRoleCreditLimit.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-RENAME TABLE `vn`.`clientCreditLimit` TO `vn`.`roleCreditLimit`;
-ALTER TABLE `vn`.`roleCreditLimit` DROP FOREIGN KEY `clientCreditLimit_FK`;
-ALTER TABLE `vn`.`roleCreditLimit` ADD CONSTRAINT `roleCreditLimit_FK` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-
diff --git a/db/changes/240001/00-truncate-where-signInLog.sql b/db/changes/240001/00-truncate-where-signInLog.sql
deleted file mode 100644
index 93d80d716..000000000
--- a/db/changes/240001/00-truncate-where-signInLog.sql
+++ /dev/null
@@ -1 +0,0 @@
-DELETE FROM `account`.`signInLog` where owner <> FALSE
diff --git a/db/changes/240001/01-procedures.sql b/db/changes/240001/01-procedures.sql
deleted file mode 100644
index 3777708d5..000000000
--- a/db/changes/240001/01-procedures.sql
+++ /dev/null
@@ -1,1129 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_confirmWithUser`(vSelf INT, vUserId INT)
-BEGIN
-/**
- * Confirms an order, creating each of its tickets on the corresponding
- * date, store and user.
- *
- * @param vSelf The order identifier
- * @param vUser The user identifier
- */
- DECLARE vOk BOOL;
- DECLARE vDone BOOL DEFAULT FALSE;
- DECLARE vWarehouse INT;
- DECLARE vShipment DATE;
- DECLARE vTicket INT;
- DECLARE vNotes VARCHAR(255);
- DECLARE vItem INT;
- DECLARE vConcept VARCHAR(30);
- DECLARE vAmount INT;
- DECLARE vPrice DECIMAL(10,2);
- DECLARE vSale INT;
- DECLARE vRate INT;
- DECLARE vRowId INT;
- DECLARE vPriceFixed DECIMAL(10,2);
- DECLARE vDelivery DATE;
- DECLARE vAddress INT;
- DECLARE vIsConfirmed BOOL;
- DECLARE vClientId INT;
- DECLARE vCompanyId INT;
- DECLARE vAgencyModeId INT;
- DECLARE TICKET_FREE INT DEFAULT 2;
- DECLARE vCalc INT;
- DECLARE vIsLogifloraItem BOOL;
- DECLARE vOldQuantity INT;
- DECLARE vNewQuantity INT;
- DECLARE vIsTaxDataChecked BOOL;
-
- DECLARE cDates CURSOR FOR
- SELECT zgs.shipped, r.warehouse_id
- FROM `order` o
- JOIN order_row r ON r.order_id = o.id
- LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id
- WHERE o.id = vSelf AND r.amount != 0
- GROUP BY r.warehouse_id;
-
- DECLARE cRows CURSOR FOR
- SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate, i.isFloramondo
- FROM order_row r
- JOIN vn.item i ON i.id = r.item_id
- WHERE r.amount != 0
- AND r.warehouse_id = vWarehouse
- AND r.order_id = vSelf
- ORDER BY r.rate DESC;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET vDone = TRUE;
-
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
- -- Carga los datos del pedido
- SELECT o.date_send, o.address_id, o.note, a.clientFk,
- o.company_id, o.agency_id, c.isTaxDataChecked
- INTO vDelivery, vAddress, vNotes, vClientId,
- vCompanyId, vAgencyModeId, vIsTaxDataChecked
- FROM hedera.`order` o
- JOIN vn.address a ON a.id = o.address_id
- JOIN vn.client c ON c.id = a.clientFk
- WHERE o.id = vSelf;
-
- -- Verifica si el cliente tiene los datos comprobados
- IF NOT vIsTaxDataChecked THEN
- CALL util.throw ('clientNotVerified');
- END IF;
-
- -- Carga las fechas de salida de cada almacen
- CALL vn.zone_getShipped (vDelivery, vAddress, vAgencyModeId, FALSE);
-
- -- Trabajador que realiza la accion
- IF vUserId IS NULL THEN
- SELECT employeeFk INTO vUserId FROM orderConfig;
- END IF;
-
- START TRANSACTION;
-
- CALL order_checkEditable(vSelf);
-
- -- Check order is not empty
-
- SELECT COUNT(*) > 0 INTO vOk
- FROM order_row WHERE order_id = vSelf AND amount > 0;
-
- IF NOT vOk THEN
- CALL util.throw ('ORDER_EMPTY');
- END IF;
-
- -- Crea los tickets del pedido
-
- OPEN cDates;
-
- lDates:
- LOOP
- SET vTicket = NULL;
- SET vDone = FALSE;
- FETCH cDates INTO vShipment, vWarehouse;
-
- IF vDone THEN
- LEAVE lDates;
- END IF;
-
- -- Busca un ticket existente que coincida con los parametros
- WITH tPrevia AS
- (SELECT DISTINCT s.ticketFk
- FROM vn.sale s
- JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
- JOIN vn.ticket t ON t.id = s.ticketFk
- WHERE t.shipped BETWEEN vShipment AND util.dayend(vShipment)
- )
- SELECT t.id INTO vTicket
- FROM vn.ticket t
- LEFT JOIN tPrevia tp ON tp.ticketFk = t.id
- LEFT JOIN vn.ticketState tls on tls.ticket = t.id
- JOIN hedera.`order` o
- ON o.address_id = t.addressFk
- AND vWarehouse = t.warehouseFk
- AND o.date_send = t.landed
- AND DATE(t.shipped) = vShipment
- WHERE o.id = vSelf
- AND t.refFk IS NULL
- AND tp.ticketFk IS NULL
- AND IFNULL(tls.alertLevel,0) = 0
- LIMIT 1;
-
- -- Crea el ticket en el caso de no existir uno adecuado
- IF vTicket IS NULL
- THEN
-
- SET vShipment = IFNULL(vShipment, util.VN_CURDATE());
-
- CALL vn.ticket_add(
- vClientId,
- vShipment,
- vWarehouse,
- vCompanyId,
- vAddress,
- vAgencyModeId,
- NULL,
- vDelivery,
- vUserId,
- TRUE,
- vTicket
- );
- ELSE
- INSERT INTO vn.ticketTracking
- SET ticketFk = vTicket,
- userFk = vUserId,
- stateFk = TICKET_FREE;
- END IF;
-
- INSERT IGNORE INTO vn.orderTicket
- SET orderFk = vSelf,
- ticketFk = vTicket;
-
- -- Añade las notas
-
- IF vNotes IS NOT NULL AND vNotes != ''
- THEN
- INSERT INTO vn.ticketObservation SET
- ticketFk = vTicket,
- observationTypeFk = 4 /* salesperson */,
- `description` = vNotes
- ON DUPLICATE KEY UPDATE
- `description` = CONCAT(VALUES(`description`),'. ', `description`);
- END IF;
-
- -- Añade los movimientos y sus componentes
-
- OPEN cRows;
-
- lRows: LOOP
- SET vDone = FALSE;
- FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate, vIsLogifloraItem;
-
- IF vDone THEN
- LEAVE lRows;
- END IF;
-
- SET vSale = NULL;
-
- SELECT s.id, s.quantity INTO vSale, vOldQuantity
- FROM vn.sale s
- WHERE ticketFk = vTicket
- AND price = vPrice
- AND itemFk = vItem
- AND discount = 0
- LIMIT 1;
-
- IF vSale THEN
- UPDATE vn.sale
- SET quantity = quantity + vAmount,
- originalQuantity = quantity
- WHERE id = vSale;
-
- SELECT s.quantity INTO vNewQuantity
- FROM vn.sale s
- WHERE id = vSale;
- ELSE
- -- Obtiene el coste
- SELECT SUM(rc.`price`) valueSum INTO vPriceFixed
- FROM orderRowComponent rc
- JOIN vn.component c ON c.id = rc.componentFk
- JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.isBase
- WHERE rc.rowFk = vRowId;
-
- INSERT INTO vn.sale
- SET itemFk = vItem,
- ticketFk = vTicket,
- concept = vConcept,
- quantity = vAmount,
- price = vPrice,
- priceFixed = vPriceFixed,
- isPriceFixed = TRUE;
-
- SET vSale = LAST_INSERT_ID();
-
- INSERT INTO vn.saleComponent
- (saleFk, componentFk, `value`)
- SELECT vSale, rc.componentFk, rc.price
- FROM orderRowComponent rc
- JOIN vn.component c ON c.id = rc.componentFk
- WHERE rc.rowFk = vRowId
- GROUP BY vSale, rc.componentFk;
- END IF;
-
- UPDATE order_row SET Id_Movimiento = vSale
- WHERE id = vRowId;
-
- -- Inserta en putOrder si la compra es de Floramondo
- IF vIsLogifloraItem THEN
- CALL cache.availableNoRaids_refresh(vCalc,FALSE,vWarehouse,vShipment);
-
- SET @available := 0;
-
- SELECT GREATEST(0,available) INTO @available
- FROM cache.availableNoRaids
- WHERE calc_id = vCalc
- AND item_id = vItem;
-
- UPDATE cache.availableNoRaids
- SET available = GREATEST(0,available - vAmount)
- WHERE item_id = vItem
- AND calc_id = vCalc;
-
- INSERT INTO edi.putOrder (
- deliveryInformationID,
- supplyResponseId,
- quantity ,
- EndUserPartyId,
- EndUserPartyGLN,
- FHAdminNumber,
- saleFk
- )
- SELECT di.ID,
- i.supplyResponseFk,
- CEIL((vAmount - @available)/ sr.NumberOfItemsPerCask),
- o.address_id ,
- vClientId,
- IFNULL(ca.fhAdminNumber, fhc.defaultAdminNumber),
- vSale
- FROM edi.deliveryInformation di
- JOIN vn.item i ON i.supplyResponseFk = di.supplyResponseID
- JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
- LEFT JOIN edi.clientFHAdminNumber ca ON ca.clientFk = vClientId
- JOIN edi.floraHollandConfig fhc
- JOIN hedera.`order` o ON o.id = vSelf
- WHERE i.id = vItem
- AND di.LatestOrderDateTime > util.VN_NOW()
- AND vAmount > @available
- LIMIT 1;
- END IF;
- END LOOP;
-
- CLOSE cRows;
- END LOOP;
-
- CLOSE cDates;
-
- UPDATE `order` SET confirmed = TRUE, confirm_date = util.VN_NOW()
- WHERE id = vSelf;
-
- COMMIT;
-END$$
-DELIMITER ;
-
-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;
- DECLARE vDone BOOL;
- DECLARE vTicketFk INT;
- DECLARE vCursor CURSOR FOR
- SELECT id
- FROM tmp.ticketToInvoice;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
- SET vInvoiceDate = IFNULL(vInvoiceDate, util.VN_CURDATE());
-
- SELECT t.clientFk,
- t.companyFk,
- MAX(DATE(t.shipped)),
- DATE(vInvoiceDate) >= invoiceOut_getMaxIssued(
- vSerial,
- t.companyFk,
- YEAR(vInvoiceDate))
- INTO vClientFk,
- vCompanyFk,
- vMaxShipped,
- vIsCorrectInvoiceDate
- FROM tmp.ticketToInvoice tt
- JOIN ticket t ON t.id = tt.id;
-
- IF(vMaxShipped > vInvoiceDate) THEN
- CALL util.throw("Invoice date can't be less than max date");
- END IF;
-
- IF NOT vIsCorrectInvoiceDate THEN
- CALL util.throw('Exists an invoice with a previous date');
- END IF;
-
- -- Eliminem de tmp.ticketToInvoice els tickets que no han de ser facturats
- DELETE ti.*
- FROM tmp.ticketToInvoice ti
- JOIN ticket t ON t.id = ti.id
- 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,
- siiTypeInvoiceOutFk
- )
- SELECT
- 1,
- vSerial,
- vInvoiceDate,
- vClientFk,
- getDueDate(vInvoiceDate, dueDay),
- vCompanyFk,
- IF(vSerial = vCorrectingSerial,
- vCplusCorrectingInvoiceTypeFk,
- IF(vSerial = vSimplifiedSerial,
- vCplusSimplifiedInvoiceTypeFk,
- vCplusStandardInvoiceTypeFk))
- FROM client
- WHERE id = vClientFk;
-
- SET vNewInvoiceId = LAST_INSERT_ID();
-
- SELECT `ref`
- INTO vNewRef
- FROM invoiceOut
- WHERE id = vNewInvoiceId;
-
- OPEN vCursor;
- l: LOOP
- SET vDone = FALSE;
- FETCH vCursor INTO vTicketFk;
-
- IF vDone THEN
- LEAVE l;
- END IF;
-
- CALL ticket_recalc(vTicketFk, vTaxArea);
-
- END LOOP;
- CLOSE vCursor;
-
- UPDATE ticket t
- JOIN tmp.ticketToInvoice ti ON ti.id = t.id
- SET t.refFk = vNewRef;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.updateInter;
- CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY
- SELECT s.id, ti.id ticket_id, vWorker Id_Trabajador
- FROM tmp.ticketToInvoice ti
- LEFT JOIN ticketState ts ON ti.id = ts.ticket
- JOIN state s
- WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id);
-
- INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
- SELECT * FROM tmp.updateInter;
-
- CALL invoiceExpenseMake(vNewInvoiceId);
- CALL invoiceTaxMake(vNewInvoiceId, vTaxArea);
-
- UPDATE invoiceOut io
- JOIN (
- SELECT SUM(amount) total
- FROM invoiceOutExpense
- WHERE invoiceOutFk = vNewInvoiceId
- ) base
- JOIN (
- SELECT SUM(vat) total
- FROM invoiceOutTax
- WHERE invoiceOutFk = vNewInvoiceId
- ) vat
- SET io.amount = base.total + vat.total
- WHERE io.id = vNewInvoiceId;
-
- DROP TEMPORARY TABLE tmp.updateInter;
-
- SELECT COUNT(*), id
- INTO vIsInterCompany, vInterCompanyFk
- FROM company
- WHERE clientFk = vClientFk;
-
- IF (vIsInterCompany) THEN
-
- INSERT INTO invoiceIn(supplierFk, supplierRef, issued, companyFk)
- SELECT vCompanyFk, vNewRef, vInvoiceDate, vInterCompanyFk;
-
- SET vNewInvoiceInFk = LAST_INSERT_ID();
-
- DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
- CREATE TEMPORARY TABLE tmp.ticket
- (KEY (ticketFk))
- ENGINE = MEMORY
- SELECT id ticketFk
- FROM tmp.ticketToInvoice;
-
- CALL `ticket_getTax`('NATIONAL');
-
- SET @vTaxableBaseServices := 0.00;
- SET @vTaxCodeGeneral := NULL;
-
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInFk,
- @vTaxableBaseServices,
- sub.expenseFk,
- sub.taxTypeSageFk,
- sub.transactionTypeSageFk
- FROM (
- SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase,
- i.expenseFk,
- i.taxTypeSageFk,
- i.transactionTypeSageFk,
- @vTaxCodeGeneral := i.taxClassCodeFk
- FROM tmp.ticketServiceTax tst
- JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code
- WHERE i.isService
- HAVING taxableBase
- ) sub;
-
- INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
- SELECT vNewInvoiceInFk,
- SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral,
- @vTaxableBaseServices, 0) taxableBase,
- i.expenseFk,
- i.taxTypeSageFk ,
- i.transactionTypeSageFk
- FROM tmp.ticketTax tt
- JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code
- WHERE !i.isService
- GROUP BY tt.pgcFk
- HAVING taxableBase
- ORDER BY tt.priority;
-
- CALL invoiceInDueDay_calculate(vNewInvoiceInFk);
-
- SELECT COUNT(*) INTO vIsCEESerial
- FROM invoiceOutSerial
- WHERE code = vSerial;
-
- IF vIsCEESerial THEN
-
- INSERT INTO invoiceInIntrastat (
- invoiceInFk,
- intrastatFk,
- amount,
- stems,
- countryFk,
- net)
- SELECT
- vNewInvoiceInFk,
- i.intrastatFk,
- SUM(CAST((s.quantity * s.price * (100 - s.discount) / 100 ) AS DECIMAL(10, 2))),
- SUM(CAST(IFNULL(i.stems, 1) * s.quantity AS DECIMAL(10, 2))),
- su.countryFk,
- CAST(SUM(IFNULL(i.stems, 1)
- * s.quantity
- * IF(ic.grams, ic.grams, IFNULL(i.weightByPiece, 0)) / 1000) AS DECIMAL(10, 2))
- FROM sale s
- JOIN ticket t ON s.ticketFk = t.id
- JOIN supplier su ON su.id = t.companyFk
- JOIN item i ON i.id = s.itemFk
- LEFT JOIN itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk
- WHERE t.refFk = vNewRef
- GROUP BY i.intrastatFk;
-
- END IF;
- DROP TEMPORARY TABLE tmp.ticket;
- DROP TEMPORARY TABLE tmp.ticketAmount;
- DROP TEMPORARY TABLE tmp.ticketTax;
- DROP TEMPORARY TABLE tmp.ticketServiceTax;
- END IF;
- END IF;
- DROP TEMPORARY TABLE `tmp`.`ticketToInvoice`;
-END$$
-DELIMITER ;
-
-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
- 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.workerFk = 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 ;
-
-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 cd.workerFk;
-
- 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.workerFk = 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 ;
-
-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 ;
-
-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 ;
-
-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 ;
-
-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 ;
-
-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 ;
-
-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' 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/changes/240001/02-views.sql b/db/changes/240001/02-views.sql
deleted file mode 100644
index 86a1049a7..000000000
--- a/db/changes/240001/02-views.sql
+++ /dev/null
@@ -1,56 +0,0 @@
-CREATE SCHEMA IF NOT EXISTS `vn2008`;
-USE `vn`;
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `ticketState`
-AS SELECT `tt`.`created` AS `updated`,
- `tt`.`stateFk` AS `stateFk`,
- `tt`.`userFk` AS `workerFk`,
- `tls`.`ticketFk` AS `ticketFk`,
- `s`.`id` AS `state`,
- `s`.`order` AS `productionOrder`,
- `s`.`alertLevel` AS `alertLevel`,
- `s`.`code` AS `code`,
- `tls`.`ticketFk` AS `ticket`,
- `tt`.`userFk` AS `worker`,
- `s`.`isPreviousPreparable` AS `isPreviousPreparable`,
- `s`.`isPicked` AS `isPicked`
-FROM (
- (
- `ticketLastState` `tls`
- JOIN `ticketTracking` `tt` ON(`tt`.`id` = `tls`.`ticketTrackingFk`)
- )
- JOIN `state` `s` ON(`s`.`id` = `tt`.`stateFk`)
- );
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `vn2008`.`v_inter`
-AS SELECT `tt`.`id` AS `inter_id`,
- `tt`.`stateFk` AS `state_id`,
- `tt`.`notes` AS `nota`,
- `tt`.`created` AS `odbc_date`,
- `tt`.`ticketFk` AS `Id_Ticket`,
- `tt`.`userFk` AS `Id_Trabajador`,
- `tt`.`supervisorFk` AS `Id_supervisor`
-FROM `vn`.`ticketTracking` `tt`;
-
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `ticketStateToday`
-AS SELECT
- `ts`.`ticket` AS `ticket`,
- `ts`.`state` AS `state`,
- `ts`.`productionOrder` AS `productionOrder`,
- `ts`.`alertLevel` AS `alertLevel`,
- `ts`.`worker` AS `worker`,
- `ts`.`code` AS `code`,
- `ts`.`updated` AS `updated`,
- `ts`.`isPicked` AS `isPicked`
-FROM
- (`ticketState` `ts`
-JOIN `ticket` `t` ON
- (`t`.`id` = `ts`.`ticket`))
-WHERE
- `t`.`shipped` BETWEEN `util`.`VN_CURDATE`() AND `MIDNIGHT`(`util`.`VN_CURDATE`());
diff --git a/db/changes/240201/.gitkeep b/db/changes/240201/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/db/changes/240201/00-tabletDocuware.sql b/db/changes/240201/00-tabletDocuware.sql
deleted file mode 100644
index ffa0226b3..000000000
--- a/db/changes/240201/00-tabletDocuware.sql
+++ /dev/null
@@ -1,10 +0,0 @@
--- vn.docuwareTablet definition
-
-CREATE TABLE `vn`.`docuwareTablet` (
- `tablet` varchar(100) NOT NULL PRIMARY KEY,
- `description` varchar(255) DEFAULT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-
-ALTER TABLE `vn`.`userConfig`
-ADD COLUMN tabletFk varchar(100) DEFAULT NULL,
-ADD FOREIGN KEY (tabletFk) REFERENCES `vn`.`docuwareTablet`(tablet);
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..8bbe54598
--- /dev/null
+++ b/db/dump/.dump/data.sql
@@ -0,0 +1,2733 @@
+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 ('salix','10230','53f69ae8e526a4a5d827c237a5b076d38507b392','2020-11-09 11:06:43',NULL);
+INSERT INTO `version` VALUES ('vn-database','10818','b7edbbe12f35d0cbc3e6b83e54977ac1c8acfc74','2024-01-25 10:00:48','10831');
+
+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','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','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','10827','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-23 12:32:13',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,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 08:44:07','2019-07-01 08:44:07',NULL);
+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,'logisticAssistant','Jefe auxiliar de logística',1,'2023-06-26 09:21:15','2023-06-26 09:21:15',NULL);
+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 `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 (147,101,35,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 (317,122,15,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 `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,'Bank','*','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','refund','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','refund','WRITE','ALLOW','ROLE','salesAssistant');
+INSERT INTO `ACL` VALUES (328,'Sale','refund','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 (681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee');
+INSERT INTO `ACL` VALUES (683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement');
+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 (694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss');
+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','refund','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 `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 `agencyTermConfig` VALUES ('6240000000','4721000015',21.0000000000,'Adquisiciones intracomunitarias de servicios');
+
+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 `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,106,763,0,0,0,0,28,NULL,'/',NULL,0,NULL,0,0,0,0,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);
+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);
+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);
+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);
+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);
+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);
+INSERT INTO `department` VALUES (37,'PROD','PRODUCCION',12,33,NULL,72,1,1,1,10,1,'/1/',NULL,0,NULL,0,1,1,1,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,0,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,0,NULL,NULL);
+INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',34,35,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (43,'VT','VENTAS',36,61,NULL,0,0,0,1,12,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (44,'management','GERENCIA',62,63,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',64,65,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (46,'delivery','REPARTO',66,67,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',68,69,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',70,71,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',72,73,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',76,77,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,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);
+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);
+INSERT INTO `department` VALUES (58,'CMP','CAMPOS',78,81,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',84,85,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,1,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (61,NULL,'VNH',86,89,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',90,91,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,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);
+INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',92,93,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (80,NULL,'EQUIPO J VALLES',37,38,4250,72,0,0,2,0,43,'/1/43/','jvp_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',94,95,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (89,NULL,'COORDINACION',96,97,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (90,NULL,'TRAILER',87,88,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,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);
+INSERT INTO `department` VALUES (92,NULL,'EQUIPO SILVERIO',39,40,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (94,NULL,'EQUIPO J BROCAL',41,42,3797,0,0,0,2,0,43,'/1/43/','jes_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (95,NULL,'EQUIPO C ZAMBRANO',43,44,4667,0,0,0,2,0,43,'/1/43/','czg_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (96,NULL,'EQUIPO C LOPEZ',45,46,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (115,NULL,'EQUIPO CLAUDI',47,48,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (123,NULL,'EQUIPO ELENA BASCUÑANA',49,50,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',98,99,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (125,NULL,'EQUIPO MIRIAM MAR',51,52,1118,0,0,0,2,0,43,'/1/43/','mir_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,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);
+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);
+INSERT INTO `department` VALUES (130,NULL,'REVISION',31,32,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',79,80,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',53,54,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',55,56,1731,72,0,0,2,0,43,'/1/43/','fra_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (134,NULL,'EQUIPO RODRI',57,58,6264,0,0,0,2,0,43,'/1/43/','rhr_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',100,101,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',102,103,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (137,'sorter','SORTER',104,105,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL);
+INSERT INTO `department` VALUES (139,NULL,'EQUIPO MIRIAM MAR 2',59,60,3803,0,0,0,2,0,43,'/1/43/','mir2_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,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..290c8a2a3
--- /dev/null
+++ b/db/dump/.dump/privileges.sql
@@ -0,0 +1,2021 @@
+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');
+/*!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','alexm@%','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','guest','warehouse','root@pc-juan.dyn.verdnatura.es','2022-08-03 23:44:43','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Vistas','juan@db-proxy1.static.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 ('','vn2008','employee','versiones','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','adminOfficer','ticketDms','alexm@%','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','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','buy_edi_k012','alexm@%','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','alexm@%','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','alexm@%','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','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','account_detail_type','alexm@%','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','alexm@%','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','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','airline','alexm@db-proxy2.static.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','alexm@%','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','buyer','Articles_botanical','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_gestdoc','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_state','alexm@%','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','administrative','Articles_botanical','alexm@%','0000-00-00 00:00:00','Select','');
+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','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb_component','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_component_template','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb_component_type','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','awb_gestdoc','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb_gestdoc','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb_recibida','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_role','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_unit','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','financialBoss','balance_nest_tree','alexm@%','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','alexm@%','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','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k03','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k04','alexm@%','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','administrative','v_compres','alexm@%','0000-00-00 00:00:00','Select','');
+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','employee','clientes_regalos_lista_enc','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','jerarquia','juan@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','warehouse','alexm@%','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','officeBoss','Vehiculos','alexm@%','0000-00-00 00:00:00','Update','');
+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','alexm@%','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','hr','workerDocument','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+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','alexm@%','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 ('','vn2008','claimManager','Vehiculos','juan@%','0000-00-00 00:00:00','Select','');
+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','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+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 ('','vn2008','financialBoss','credit','alexm@%','0000-00-00 00:00:00','Select','');
+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','alexm@%','0000-00-00 00:00:00','Select','');
+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','alexm@%','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','employee','expeditions','alexm@%','0000-00-00 00:00:00','Select','');
+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','salesPerson','Facturas','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Facturas','alexm@%','0000-00-00 00:00:00','Select','');
+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','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','warehouse_pickup','alexm@%','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','juan@%','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 ('','vn2008','administrative','invoiceCorrection','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','intrastat_data','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','intrastat_data','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+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','alexm@%','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 ('','vn2008','employee','Greuges','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','gesttip','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','gestdoc','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Gastos','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+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 ('','vn','administrative','bank','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','hr','bank','alexm@%','0000-00-00 00:00:00','Select','');
+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','alexm@%','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','gestdoc','alexm@%','0000-00-00 00:00:00','Insert,Update','');
+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','juan@%','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','palletizer','Facturas','alexm@%','0000-00-00 00:00:00','Select','');
+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','alexm@%','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','logistic','reference_min','alexm@%','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','juan@%','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 ('','vn2008','productionAssi','Rutas_Master','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Rutas_monitor','alexm@%','0000-00-00 00:00:00','Select','');
+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','financial','XDiario','alexm@%','0000-00-00 00:00:00','Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','Vehiculos_consumo','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','XDiario','alexm@%','0000-00-00 00:00:00','Select,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 ('','vn','financial','property','juan@%','0000-00-00 00:00:00','Select,Insert,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','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','awb_gestdoc','alexm@db-proxy1.static.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','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_component_type','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,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','administrative','dms','alexm@%','0000-00-00 00:00:00','Select,Update','');
+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 ('','vn','hr','dms','alexm@%','0000-00-00 00:00:00','Select,Update','');
+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','buyer','dms','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-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+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 ('','vn2008','hr','Facturas','guillermo@10.5.1.4','0000-00-00 00:00:00','Select','');
+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__','alexm@%','0000-00-00 00:00:00','Select,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','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','XDiario','alexm@%','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 ('','vn','productionAssi','component','alexm@%','0000-00-00 00:00:00','Select','');
+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','alexm@%','0000-00-00 00:00:00','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','alexm@%','0000-00-00 00:00:00','Select,Update','');
+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 ('','vn2008','buyer','tarifas','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+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 ('','vn2008','financial','Greuges_type','alexm@%','0000-00-00 00:00:00','Select','');
+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 ('','vn2008','hr','XDiario','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','juan@10.5.1.1','0000-00-00 00:00:00','Select,Update','');
+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','alexm@%','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','adminBoss','ticketDms','alexm@%','0000-00-00 00:00:00','Insert','');
+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 ('','vn2008','buyerBoss','tarifas','alexm@%','0000-00-00 00:00:00','Select,Update','');
+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 ('','vn2008','hr','gestdoc','alexm@%','0000-00-00 00:00:00','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 ('','vn2008','buyerBoss','XDiario','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+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 ('','vn2008','salesAssistant','workerTeam','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesBoss','workerTeam','juan@10.5.1.2','0000-00-00 00:00:00','Delete','');
+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 ('','srt','maintenanceBos','moving','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+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','buyerBoss','itemType','carlosap@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,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','alexm@db-proxy2.static.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 ('','vn2008','deliveryAssistant','Vehiculos','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update','');
+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');
+/*!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');
+/*!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 ('','vn2008','financial','calculoremesas','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','hr','cc_to_iban','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','financial','cc_to_iban','FUNCTION','alexm@%','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 ('','vn2008','handmadeBoss','confection_control_source','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','buyer','travelDetail','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','claimManager','traslado','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','buyer','traslado','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','administrative','supplierStatement','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','buyer','supplierStatement','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','hrBoss','supplierStatement','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','hrBoss','red','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','salesPerson','red','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','administrative','intrastat_neto','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','productionAssi','confection_control_source','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','artificialBoss','confection_control_source','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','logistic','nz','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','deliveryAssistant','preordenarruta','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','financial','pay','PROCEDURE','alexm@%','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 ('','vn2008','logistic','calculoremesas','PROCEDURE','alexm@%','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 ('','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 ('','vn','officeBoss','fustcontrol','PROCEDURE','alexm@%','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 ('','vn2008','adminBoss','nest_delete','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 ('','vn2008','adminBoss','nest_child_add','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','salesAssistant','itemproposal','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','itemproposal_add','PROCEDURE','alexm@%','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','employee','workerTimeControl_add','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','coolerAssist','itemproposal','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','company_getsuppliersdebt','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn2008','agency','desglose_volume','PROCEDURE','juan@10.5.1.2','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 ('','vn2008','adminBoss','XDiario_Quadrator','PROCEDURE','juan@10.5.1.2','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','jgallego@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\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','adminOfficer','{\"access\": 0, \"version_id\": 100707, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','administrative','{\"access\": 0, \"is_role\": true, \"version_id\": 100707}');
+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\":100707,\"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 ('','buyerBoss','{\"access\": 0, \"version_id\": 100707, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','claimManager','{\"access\":0,\"version_id\":100707,\"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\":100707,\"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\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','deliveryBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','developer','{\"access\": 5909905728, \"is_role\": true, \"version_id\": 100707}');
+INSERT IGNORE INTO `global_priv` VALUES ('','developerBoss','{\"access\":33554432,\"version_id\":100707,\"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\": 100707, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','financialBoss','{\"access\": 0, \"version_id\": 100707, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','grafana','{\"access\":0,\"version_id\":100707,\"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\": 100707}');
+INSERT IGNORE INTO `global_priv` VALUES ('','handmadeBoss','{\"access\":0,\"version_id\":100707,\"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\": 100707}');
+INSERT IGNORE INTO `global_priv` VALUES ('','hrBoss','{\"access\":0,\"version_id\":100707,\"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\": 100707}');
+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\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBos','{\"access\":0,\"version_id\":100707,\"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\":100707,\"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\":100707,\"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\":100707,\"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\":100707,\"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\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','salesBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','salesPerson','{\"access\": 0, \"is_role\": true,\"version_id\":100707}');
+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 75%
rename from db/dump/structure.sql
rename to db/dump/.dump/structure.sql
index 694f745ef..0c7966b82 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.21-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,7 +159,24 @@ 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 `mailAliasAcl`
+--
+
+DROP TABLE IF EXISTS `mailAliasAcl`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `mailAliasAcl` (
+ `mailAliasFk` int(10) unsigned NOT NULL,
+ `roleFk` int(10) unsigned NOT NULL,
+ KEY `mailAliasFk` (`mailAliasFk`),
+ KEY `roleFk` (`roleFk`),
+ CONSTRAINT `mailAliasAcl_ibfk_1` FOREIGN KEY (`mailAliasFk`) REFERENCES `mailAlias` (`id`),
+ CONSTRAINT `mailAliasAcl_ibfk_2` FOREIGN KEY (`roleFk`) REFERENCES `role` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -328,7 +193,7 @@ CREATE TABLE `mailClientAccess__` (
`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 COMMENT='@deprecated 2023-09-03';
+) 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,70 +227,6 @@ 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__`
@@ -441,7 +242,7 @@ CREATE TABLE `mailSenderAccess__` (
`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 COMMENT='@deprecated 2023-09-03';
+) 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`
@@ -694,7 +363,7 @@ CREATE TABLE `roleLog` (
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 +379,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 */;
--
@@ -729,7 +398,7 @@ CREATE TABLE `sambaConfig` (
`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 */;
--
@@ -744,11 +413,13 @@ CREATE TABLE `signInLog` (
`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=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -792,142 +463,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`
@@ -940,7 +477,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 */;
--
@@ -968,7 +505,7 @@ CREATE TABLE `userLog` (
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 */;
--
@@ -986,7 +523,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 */;
--
@@ -1005,27 +542,6 @@ CREATE TABLE `userSync` (
--
-- Dumping events for database 'account'
--
-/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
-/*!50106 DROP EVENT IF EXISTS `role_sync` */;
-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 `role_sync` ON SCHEDULE AT '2023-11-16 14:32:48' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO CALL role_sync */ ;;
-/*!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 'account'
@@ -1060,7 +576,7 @@ BEGIN
SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey);
RETURN vSignature = @userSignature;
END IF;
-
+
RETURN FALSE;
END ;;
@@ -1089,7 +605,7 @@ BEGIN
* @return The user id
*/
DECLARE vUser INT DEFAULT NULL;
-
+
IF myUser_checkLogin()
THEN
SET vUser = @userId;
@@ -1097,7 +613,7 @@ BEGIN
SELECT id INTO vUser FROM user
WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1);
END IF;
-
+
RETURN vUser;
END ;;
DELIMITER ;
@@ -1132,7 +648,7 @@ BEGIN
ELSE
SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1);
END IF;
-
+
RETURN vUser;
END ;;
DELIMITER ;
@@ -1150,7 +666,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasPriv`(vChain VARCHAR(100),
+CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasPriv`(vChain VARCHAR(100),
vPrivilege ENUM('SELECT','INSERT','UPDATE','DELETE')
) RETURNS tinyint(1)
READS SQL DATA
@@ -1285,10 +801,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);
@@ -1363,7 +879,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;
@@ -1390,16 +906,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 ;
@@ -1417,8 +933,8 @@ DELIMITER ;
/*!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'),
+CREATE DEFINER=`root`@`localhost` FUNCTION `user_hasPriv`(vChain VARCHAR(100),
+ vPrivilege ENUM('SELECT','INSERT','UPDATE','DELETE'),
vUserFk INT
) RETURNS tinyint(1)
READS SQL DATA
@@ -1440,16 +956,20 @@ BEGIN
SET vDb = SUBSTRING_INDEX(vChain, '.', 1);
SET vChain = SUBSTRING(vChain, LENGTH(vDb) + 2);
- SET vTableName = SUBSTRING_INDEX(vChain, '.', 1);
- SET vColumnName = SUBSTRING(vChain, LENGTH(vTableName) + 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
- LIMIT 1;
-
+ 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;
@@ -1474,22 +994,22 @@ BEGIN
SELECT hasPrivilege INTO vHasPrivilege
FROM (SELECT JSON_VALUE(Priv, '$.access') & vPrivilegeFlag hasPrivilege
- FROM mysql.global_priv gp
+ 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
+ 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;
@@ -1498,13 +1018,13 @@ BEGIN
IF NOT vHasPrivilege THEN
SELECT TRUE INTO vHasPrivilege
- FROM tRole tr
+ FROM tRole tr
LEFT JOIN (
SELECT User, Table_priv privilege
FROM mysql.tables_priv
WHERE Db = vDb
AND Table_name = vTableName
- UNION
+ UNION
SELECT User, Column_priv
FROM mysql.columns_priv
WHERE Db = vDb
@@ -1587,7 +1107,7 @@ BEGIN
JOIN role r ON r.id = rr.inheritsFrom
WHERE u.`name` = vUser
AND r.id = vRoleId;
-
+
RETURN vHasRole;
END ;;
DELIMITER ;
@@ -1624,7 +1144,7 @@ BEGIN
DECLARE vObject VARCHAR(50);
DECLARE vChainExists BOOL;
DECLARE vExecutePriv INT DEFAULT 262144;
- -- 262144 = CONV(1000000000000000000, 2, 10)
+ -- 262144 = CONV(1000000000000000000, 2, 10)
-- 1000000000000000000 execution permission expressed in binary base
SET vDb = SUBSTRING_INDEX(vChain, '.', 1);
@@ -1636,7 +1156,7 @@ BEGIN
WHERE db = vDb
AND `name` = vObject
AND `type` = vType
- LIMIT 1;
+ LIMIT 1;
IF NOT vChainExists THEN
RETURN FALSE;
@@ -1651,18 +1171,18 @@ BEGIN
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`
+ 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
+ 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';
@@ -1670,7 +1190,7 @@ BEGIN
IF NOT vHasPrivilege THEN
SELECT TRUE INTO vHasPrivilege
- FROM mysql.procs_priv pp
+ FROM mysql.procs_priv pp
JOIN tRole tr ON tr.name = pp.`User`
WHERE pp.Db = vDb
AND pp.Routine_name = vObject
@@ -1750,7 +1270,7 @@ BEGIN
AND password = MD5(vPassword)
AND active;
- IF vAuthIsOk
+ IF vAuthIsOk
THEN
CALL myUser_loginWithName (vUserName);
ELSE
@@ -1811,7 +1331,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
@@ -1847,7 +1367,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_logout`()
BEGIN
/**
* Logouts the user.
- */
+ */
SET @userId = NULL;
SET @userName = NULL;
SET @userSignature = NULL;
@@ -1945,9 +1465,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;
@@ -2666,7 +2186,7 @@ BEGIN
IF vChr REGEXP '[[:alpha:]]'
THEN
SET vNAlpha = vNAlpha+1;
-
+
IF vChr REGEXP '[A-Z]'
THEN
SET vNUpper = vNUpper+1;
@@ -2702,6 +2222,1967 @@ 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_clientes_jerarquia`
+--
+
+DROP TABLE IF EXISTS `v_clientes_jerarquia`;
+/*!50001 DROP VIEW IF EXISTS `v_clientes_jerarquia`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `v_clientes_jerarquia` AS SELECT
+ 1 AS `Id_Cliente`,
+ 1 AS `Cliente`,
+ 1 AS `Comercial`,
+ 1 AS `Jefe` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `v_ventas_contables`
+--
+
+DROP TABLE IF EXISTS `v_ventas_contables`;
+/*!50001 DROP VIEW IF EXISTS `v_ventas_contables`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `v_ventas_contables` AS SELECT
+ 1 AS `year`,
+ 1 AS `month`,
+ 1 AS `importe` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Dumping events for database 'bi'
+--
+
+--
+-- Dumping routines for database 'bi'
+--
+/*!50003 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`(vData DOUBLE) RETURNS double
+ DETERMINISTIC
+BEGIN
+/**
+ * Devuelve 0, si el parámetro es NULL:
+ */
+ DECLARE vResult DOUBLE;
+
+ SET vResult = IFNULL(vData,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 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,
+ v.vista AS Vista,
+ bt.importe AS Importe
+ FROM bs.ventas bt
+ LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id
+ LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id
+ LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente
+ LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador
+ LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador
+ JOIN vn2008.time tm ON tm.date = bt.fecha
+ JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento
+ LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
+ JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
+ LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista
+ LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna
+ LEFT JOIN vn2008.province p ON p.province_id = cs.province_id
+ LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id
+ WHERE bt.fecha >= vLastMonth AND r.mercancia;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 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 vn2008.Greuges(Fecha, Id_Cliente, Comentario,
+ Importe, Greuges_type_id,Id_Ticket)
+ SELECT cm.Fecha
+ , cm.Id_Cliente
+ , concat('Claim ',cm.id,' : ', m.Concepte)
+ ,round( -1 * ((sensib -1)/4) * Cantidad *
+ Preu * (100 - Descuento) / 100, 2) AS Reclamaciones
+ , 4
+ , m.Id_Ticket
+ FROM vn2008.Movimientos m
+ JOIN vn2008.cl_act ca USING(Id_Movimiento)
+ JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
+ WHERE ca.cl_sol_id NOT IN (1,5)
+ AND ca.greuge = 0
+ AND cm.cl_est_id = 3;
+
+ -- Reclamaciones que pasan a Maná
+
+ INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario,
+ Importe , Greuges_type_id,Id_Ticket)
+ SELECT cm.Fecha
+ , cm.Id_Cliente
+ , concat('Claim_mana ',cm.id,' : ', m.Concepte)
+ ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2)
+ AS Reclamaciones
+ ,3
+ ,m.Id_Ticket
+ FROM vn2008.Movimientos m
+ JOIN vn2008.cl_act ca USING(Id_Movimiento)
+ JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
+ WHERE ca.cl_sol_id NOT IN (1,5)
+ AND ca.greuge = 0
+ AND cm.cl_est_id = 3
+ AND cm.mana;
+
+ -- Marcamos para no repetir
+ UPDATE vn2008.cl_act ca
+ JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
+ SET greuge = 1
+ WHERE ca.cl_sol_id NOT IN (1,5)
+ AND ca.greuge = 0
+ AND cm.cl_est_id = 3;
+
+ -- Recobros
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
+ CREATE TEMPORARY TABLE tmp.ticket_list
+ (PRIMARY KEY (Id_Ticket))
+ SELECT DISTINCT t.Id_Ticket
+ FROM vn2008.Movimientos_componentes mc
+ JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento
+ JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
+ JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket
+ JOIN 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 vn2008.Greuges g
+ JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket
+ WHERE Greuges_type_id = 2;
+
+ INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha,
+ Greuges_type_id, Id_Ticket)
+ SELECT Id_Cliente
+ ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2)
+ AS dif
+ ,date(t.Fecha)
+ , 2
+ ,tt.Id_Ticket
+ FROM vn2008.Movimientos m
+ JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
+ JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket
+ JOIN vn2008.Movimientos_componentes mc
+ ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17
+ GROUP BY t.Id_Ticket
+ HAVING ABS(dif) > 1;
+
+ UPDATE vn2008.Movimientos_componentes mc
+ JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento
+ JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket
+ SET greuge = 1
+ WHERE Id_Componente = 17;
+
+ /*
+ * Recalculamos la ratio de las reclamaciones, que luego
+ * se va a utilizar en el recobro
+ */
+
+ REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro)
+ SELECT Id_Cliente, 0,0,0,0
+ FROM vn2008.Clientes;
+
+ REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro)
+ SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones,
+ round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0
+ FROM bi.facturacion_media_anual fm
+ LEFT JOIN(
+ SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) *
+ Cantidad * Preu * (100 - Descuento) / 100))
+ AS Reclamaciones
+ FROM vn2008.Movimientos m
+ JOIN vn2008.cl_act ca
+ ON ca.Id_Movimiento = m.Id_Movimiento
+ JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
+ WHERE ca.cl_sol_id NOT IN (1,5)
+ AND cm.cl_est_id = 3
+ AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, 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 Id_Cliente, nz(SUM(Importe)) AS Greuge
+ FROM vn2008.Greuges
+ WHERE Fecha <= util.VN_CURDATE()
+ GROUP BY Id_Cliente
+ ) g ON g.Id_Cliente = cr.Id_Cliente
+ SET recobro = GREATEST(0,round(nz(Greuge) /
+ (nz(Consumo) * vMonthToRefund / 12 ) ,3));
+
+ -- Protección neonatos
+ UPDATE bi.claims_ratio cr
+ JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente
+ SET recobro = 0, Ratio = 0
+ WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,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 Vencimiento, importe FROM vn2008.Facturas f
+ WHERE f.Fecha >= '2016-01-01' AND f.Id_Cliente = vClient ORDER BY f.Fecha DESC;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DELETE FROM bi.defaulters WHERE date = vDate;
+
+ INSERT INTO bi.defaulters(client, date, amount)
+ SELECT 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 vn2008.expeditions e ON e.ticket_id = t.id
+ JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.EsBulto
+ 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(Importe) Importe
+ FROM tmp.dp
+ JOIN vn2008.Greuges g ON g.Id_Ticket = dp.ticketFk
+ WHERE Greuges_type_id = 1 -- dif_porte
+ GROUP BY dp.ticketFk;
+
+ UPDATE tmp.dp
+ JOIN tmp.dp_aux USING(ticketFk)
+ SET greuge = IFNULL(Importe,0);
+
+ INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, Greuges_type_id, Id_Ticket)
+ 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 Id_Cliente, max(Fecha) as maxFecha
+ FROM vn2008.Facturas
+ GROUP BY Id_Cliente
+ 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 Id_Cliente, sum(Importe) as Greuge
+ FROM vn2008.Greuges
+ where Fecha <= datFEC
+ group by Id_Cliente
+ ) sub
+ RIGHT JOIN
+
+ (
+
+ SELECT Id_Cliente, sum(Ventas) as Ventas
+ FROM
+ (
+
+ SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas
+ FROM bs.ventas
+ WHERE fecha = datFEC or fecha = datFEC_LASTYEAR
+
+ UNION ALL
+
+ SELECT Id_Cliente, Ventas
+ FROM bi.Greuge_Evolution
+ WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC)
+
+ ) sub
+ group by Id_Cliente
+
+ ) v using(Id_Cliente)
+ ;
+
+ -- Ahora calcularemos el greuge muerto
+ UPDATE bi.Greuge_Evolution ge
+ JOIN maxInvoice m using(Id_Cliente)
+ SET FOSIL = GREUGE
+ WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha);
+
+ -- Recobro
+ UPDATE bi.Greuge_Evolution ge
+ JOIN (
+ SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe
+ FROM vn2008.Tickets t
+ JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna
+ JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket
+ JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento
+ WHERE t.Fecha >= datFEC
+ AND t.Fecha < datFEC_TOMORROW
+ AND mc.Id_Componente = 17 -- Recobro
+ GROUP BY cs.Id_Cliente
+ ) sub using(Id_Cliente)
+ SET Recobro = Importe
+ WHERE ge.Fecha = datFEC;
+
+ SET datFEC = datFEC_TOMORROW;
+ SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW);
+ SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC);
+
+ END WHILE;
+
+ DROP TEMPORARY TABLE IF EXISTS maxInvoice;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 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`(
+ vYear INT,
+ vMonth INT
+)
+BEGIN
+/**
+ * Analiza los costes de las rutas de reparto
+ * y lo almacena en la tabla bi.rutasBoard
+ */
+ DELETE FROM rutasBoard
+ WHERE YEAR(Fecha) = vYear
+ AND MONTH(Fecha) = vMonth;
+
+ -- 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 YEAR(r.created) = vYear AND MONTH(r.created) = vMonth
+ AND z.isVolumetric
+ GROUP BY r.id;
+
+ -- Rellenamos la tabla con los datos de las rutas NO VOLUMETRICAS, especialmente con los bultos "virtuales"
+ INSERT INTO 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 YEAR(r.created) = vYear
+ AND MONTH(r.created) = vMonth
+ 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.`time` tm ON tm.dated = r.created
+ JOIN vn.ticket t ON t.routeFk = r.id
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.saleComponent sc ON sc.saleFk = s.id
+ JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk
+ WHERE ct.code = 'FREIGHT'
+ AND tm.`year` = vYear
+ AND tm.`month` = vMonth
+ 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.`time` tm ON tm.dated = r.created
+ 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 tm.`year` = vYear
+ AND tm.`month` = vMonth
+ 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.`time` tm ON tm.dated = r.created
+ 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 tm.`year` = vYear
+ AND tm.`month` = vMonth
+ 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.`time` tm ON tm.dated = r.created
+ JOIN vn.greuge g ON g.ticketFk = t.id
+ JOIN vn.greugeType gt ON gt.id = g.greugeTypeFk
+ WHERE tm.`year` = vYear
+ AND tm.`month` = vMonth
+ AND gt.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(YEAR(util.VN_CURDATE()), MONTH(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`
--
@@ -2710,6 +4191,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`
--
@@ -2814,7 +4310,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 */;
--
@@ -2834,29 +4330,6 @@ 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__`
@@ -2959,6 +4432,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`
--
@@ -3020,7 +4508,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 */;
--
@@ -3040,7 +4528,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 */;
--
@@ -3097,7 +4585,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 */;
--
@@ -3118,60 +4606,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`
@@ -3184,7 +4620,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 */;
--
@@ -3221,7 +4657,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 */;
--
@@ -3239,7 +4675,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 */;
--
@@ -3396,7 +4832,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 */;
--
@@ -3416,7 +4852,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 */;
--
@@ -3541,7 +4977,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 */;
--
@@ -3568,7 +5004,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 */;
--
@@ -3583,7 +5019,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 */;
--
@@ -3595,14 +5031,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;
@@ -3640,7 +5076,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 */ ;;
@@ -3658,7 +5094,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 */ ;;
@@ -3686,11 +5122,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 ;
@@ -3718,7 +5154,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
@@ -3732,49 +5168,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
@@ -3784,7 +5220,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
@@ -3794,10 +5230,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
@@ -3811,12 +5247,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;
@@ -3839,14 +5275,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,
@@ -3855,11 +5291,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,
@@ -3893,21 +5329,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 */ ;
@@ -3926,18 +5370,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
@@ -3949,14 +5389,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 */ ;
@@ -4052,16 +5495,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;
@@ -4073,7 +5516,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;
@@ -4084,37 +5527,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;
@@ -4124,14 +5567,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 */ ;
@@ -4152,16 +5595,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,
@@ -4186,7 +5629,7 @@ BEGIN
FROM
vn2008.Clientes c
LEFT JOIN
- (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge
+ (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
LEFT JOIN vn.worker w ON c.salesPersonFk = w.id
@@ -4208,14 +5651,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
@@ -4276,17 +5719,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(
@@ -4307,7 +5750,7 @@ BEGIN
WHILE vDated < util.VN_CURDATE() DO
SET vCount = vCount + 1;
-
+
REPLACE compradores_evolution(
Id_Trabajador,
fecha,
@@ -4319,18 +5762,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;
@@ -4357,49 +5800,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
@@ -4407,7 +5850,7 @@ BEGIN
WHERE fecha <= datFEC
) sub
SET fondo_medio = media WHERE fecha = datFEC;
-
+
SET datFEC = TIMESTAMPADD(DAY,1,datFEC);
END WHILE;
@@ -4431,7 +5874,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
@@ -4472,40 +5915,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
@@ -4524,7 +5967,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
@@ -4533,9 +5976,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
@@ -4552,9 +5995,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
@@ -4580,7 +6023,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;
@@ -4594,12 +6037,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
@@ -4630,15 +6073,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 ;;
@@ -4667,7 +6110,7 @@ BEGIN
DECLARE vCalc INT;
DECLARE vWarehouseFk INT;
- DECLARE cWarehouses CURSOR FOR
+ DECLARE cWarehouses CURSOR FOR
SELECT id
FROM vn.warehouse
WHERE isInventory;
@@ -4680,13 +6123,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
@@ -4695,7 +6138,7 @@ BEGIN
JOIN vn.sector sc ON sc.id = p.sectorFk
WHERE sc.warehouseFk = vWarehouseFk
GROUP BY itemFk;
-
+
INSERT INTO inventoryDiscrepancyDetail(
warehouseFk,
itemFk,
@@ -4767,15 +6210,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)
@@ -4820,19 +6263,19 @@ BEGIN
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
+
+ SELECT id INTO vManaBankId
FROM vn.bank WHERE code = 'mana';
-
- SELECT id INTO vManaGreugeTypeId
+
+ SELECT id INTO vManaGreugeTypeId
FROM vn.greugeType WHERE code = 'mana';
SELECT manaFromDays, manaToDays
@@ -4840,17 +6283,17 @@ BEGIN
FROM vn.salespersonConfig;
SELECT MAX(dated)
- INTO vFromDated
+ INTO vFromDated
FROM vn.clientManaCache;
DELETE
FROM vn.clientManaCache
WHERE dated = vFromDated;
-
+
SELECT MAX(dated)
- INTO vFromDated
+ INTO vFromDated
FROM vn.clientManaCache;
-
+
IF ISNULL(vFromDated) THEN
SELECT manaDateFrom
INTO vFromDated
@@ -4860,20 +6303,20 @@ BEGIN
WHILE vFromDated + INTERVAL vManaToDays DAY < util.VN_CURDATE() DO
SELECT
vFromDated + INTERVAL vManaToDays DAY,
- vFromDated - INTERVAL vManaFromDays DAY
- INTO
+ 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,
SUM(mana),
- vToDated
- FROM
+ vToDated
+ FROM
(
SELECT cs.Id_Cliente, Cantidad * Valor as mana
FROM vn2008.Tickets t
@@ -4881,19 +6324,19 @@ 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 > vFromDated
AND Fecha <= vToDated
UNION ALL
SELECT clientFk, mana
@@ -4903,7 +6346,7 @@ BEGIN
GROUP BY Id_Cliente
HAVING Id_Cliente;
- SET vFromDated = vToDated;
+ SET vFromDated = vToDated;
END WHILE;
END ;;
DELIMITER ;
@@ -4923,26 +6366,26 @@ 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 =
+ SET wm.pricesModifierRate =
IFNULL(
GREATEST(
- spc.manaMinRate,
+ spc.manaMinRate,
LEAST(
- spc.manaMaxRate,
+ spc.manaMaxRate,
ROUND( - wm.amount / avgPortfolioWeight.amount, 3)
)
)
@@ -4964,82 +6407,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 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;
+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 */ ;
@@ -5078,7 +6521,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 */ ;
@@ -5097,22 +6540,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 */ ;
@@ -5132,12 +6575,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);
@@ -5152,19 +6595,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 */ ;
@@ -5183,21 +6626,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 */ ;
@@ -5219,7 +6662,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
*/
@@ -5227,17 +6670,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,
@@ -5246,7 +6689,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);
@@ -5419,8 +6862,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 */ ;
@@ -5440,35 +6883,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;
@@ -5476,21 +6919,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
@@ -5519,7 +6962,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 */ ;
@@ -5543,7 +6986,7 @@ BEGIN
/**
* Añade las ventas que se realizaron entre
* vStarted y vEnded
-*
+*
* @param vStarted Fecha de inicio
* @param vEnded Fecha de finalizacion
*
@@ -5551,7 +6994,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;
@@ -5560,8 +7003,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
@@ -5582,28 +7025,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);
@@ -5631,7 +7074,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();
@@ -5655,7 +7098,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT)
BEGIN
-
+
/**
* Reemplaza las ventas contables del último año.
* Es el origen de datos para el balance de Entradas
@@ -5667,8 +7110,8 @@ BEGIN
DECLARE TIPO_PATRIMONIAL INT DEFAULT 188;
- DELETE FROM bs.ventas_contables
- WHERE year = vYear
+ DELETE FROM bs.ventas_contables
+ WHERE year = vYear
AND month = vMonth;
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
@@ -5679,7 +7122,7 @@ BEGIN
FROM vn2008.Tickets t
JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura
WHERE year(f.Fecha) = vYear
- AND month(f.Fecha) = vMonth;
+ AND month(f.Fecha) = vMonth;
INSERT INTO bs.ventas_contables(year
, month
@@ -5689,7 +7132,7 @@ BEGIN
, tipo_id
, empresa_id
, gasto)
-
+
SELECT vYear
, vMonth
, round(sum(Cantidad * Preu * (100 - m.Descuento)/100))
@@ -5701,13 +7144,13 @@ BEGIN
, tp.reino_id
, a.tipo_id
, t.empresa_id
- , 7000000000
+ , 7000000000
+ IF(e.empresa_grupo = e2.empresa_grupo
,1
,IF(e2.empresa_grupo,2,0)
- ) * 1000000
+ ) * 1000000
+ tp.reino_id * 10000 as Gasto
- 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
@@ -5721,7 +7164,7 @@ BEGIN
AND m.Descuento <> 100
AND a.tipo_id != TIPO_PATRIMONIAL
GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto;
-
+
INSERT INTO bs.ventas_contables(year
, month
, venta
@@ -5740,17 +7183,17 @@ BEGIN
) as grupo
, NULL
, NULL
- , t.companyFk
+ , t.companyFk
, 7050000000
- FROM vn.ticketService ts
+ FROM vn.ticketService ts
JOIN vn.ticket t ON ts.ticketFk = t.id
- JOIN vn.address a on a.id = t.addressFk
- JOIN vn.client cl on cl.id = a.clientFk
+ JOIN vn.address a on a.id = t.addressFk
+ JOIN vn.client cl on cl.id = a.clientFk
JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id
- JOIN vn.company c on c.id = t.companyFk
+ JOIN vn.company c on c.id = t.companyFk
LEFT JOIN vn.company c2 on c2.clientFk = cl.id
- GROUP BY grupo, t.companyFk ;
-
+ GROUP BY grupo, t.companyFk ;
+
DROP TEMPORARY TABLE tmp.ticket_list;
END ;;
DELIMITER ;
@@ -5770,13 +7213,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 ;;
@@ -5797,12 +7240,12 @@ 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
@@ -5811,8 +7254,8 @@ BEGIN
FROM vn2008.Tickets t
JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura
WHERE year(f.Fecha) = vYear
- AND month(f.Fecha) = vMonth;
-
+ AND month(f.Fecha) = vMonth;
+
SELECT vYear Año,
vMonth Mes,
t.Id_Cliente,
@@ -5822,7 +7265,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
@@ -5836,9 +7279,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 */ ;
@@ -5857,7 +7300,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `vivosMuertos`()
BEGIN
-
+
/**
* Devuelve el número de clientes nuevos y muertos,
* dependiendo de la fecha actual.
@@ -5868,9 +7311,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
@@ -5886,10 +7329,10 @@ BEGIN
WHERE Fecha BETWEEN @datSTART
AND @datEND) f ON f.yearMonth = tm.yearMonth
AND f.Id_Cliente = c.Id_Cliente;
-
+
UPDATE tmp.VivosMuertos vm
JOIN
- (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente
+ (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
@@ -5897,9 +7340,9 @@ BEGIN
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
@@ -5940,23 +7383,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(value)) as total,
floor(sum(IF(clientTypeFk = 'loses', value, 0))) as mermas
- FROM vn.saleValue
+ FROM vn.saleValue
where year = vYear and week = vWeek
-
+
GROUP BY family, itemFk
-
+
) sub
ORDER BY mermas DESC;
END ;;
@@ -5988,56 +7431,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
@@ -6048,12 +7491,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
@@ -6063,8 +7506,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
@@ -6268,7 +7711,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 */;
--
@@ -6292,7 +7735,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 */;
--
@@ -6361,7 +7804,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 */;
--
@@ -6430,7 +7873,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 */ ;;
@@ -6448,7 +7891,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 */ ;;
@@ -6473,7 +7916,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `addressFriendship_Update`()
BEGIN
- REPLACE cache.addressFriendship
+ REPLACE cache.addressFriendship
SELECT addressFk1, addressFk2, count(*) friendship
FROM
(
@@ -6484,7 +7927,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
@@ -6658,12 +8101,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 ;
@@ -6842,27 +8285,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 */ ;
@@ -6880,89 +8323,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 */ ;
@@ -6992,7 +8435,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
@@ -7088,7 +8531,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;
@@ -7097,23 +8540,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);
@@ -7158,7 +8601,7 @@ proc: BEGIN
DECLARE started DATE;
DECLARE ended DATE;
DECLARE vLastRefresh DATE;
-
+
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
CALL cache_calc_unlock (vCalc);
@@ -7208,14 +8651,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;
@@ -7233,8 +8676,8 @@ proc: BEGIN
WHERE Fecha = util.VN_CURDATE()
GROUP BY wh_id, graphCategory
;
-
-
+
+
CALL cache_calc_end (v_calc);
END ;;
DELIMITER ;
@@ -7255,11 +8698,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;
@@ -7279,23 +8722,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
@@ -7325,12 +8768,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 ;
@@ -7389,6 +8832,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(100) 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`
--
@@ -7545,7 +9217,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 */;
--
@@ -7629,7 +9301,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 */;
--
@@ -7747,7 +9419,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 */;
--
@@ -7766,7 +9438,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 */;
--
@@ -7844,7 +9516,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 */;
--
@@ -7956,28 +9628,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`
@@ -8074,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 */;
--
@@ -8097,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 */;
--
@@ -8113,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 */;
--
@@ -8166,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 */;
--
@@ -8187,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 */;
--
@@ -8237,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`
@@ -8571,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`
@@ -8624,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 */;
--
@@ -8716,7 +10170,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 `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 */ ;;
@@ -8741,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,'/','');
@@ -8753,7 +10207,7 @@ BEGIN
SET vPictureReference = REPLACE(vPictureReference,'?','');
SET vPictureReference = REPLACE(vPictureReference,'=','');
-
+
RETURN vPictureReference;
END ;;
@@ -8809,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 */ ;
@@ -8848,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,
@@ -8896,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 */ ;
@@ -8914,18 +10368,23 @@ 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 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ekt_load` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = 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 */ ;
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;
@@ -8933,68 +10392,63 @@ 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;
-- 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;
-
+
-- 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
@@ -9003,29 +10457,25 @@ 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
@@ -9044,89 +10494,77 @@ 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, 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 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
+ JOIN vn2008.config cfg
+ WHERE e.id = vSelf
+ LIMIT 1;
- 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, 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.packagingFk), vPackage, b.packagingFk)
- ,(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,
@@ -9138,22 +10576,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'
@@ -9162,39 +10598,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 ;;
@@ -9331,7 +10764,7 @@ 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.
+ * 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
@@ -9370,19 +10803,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
@@ -9397,7 +10830,7 @@ 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
@@ -9418,9 +10851,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;
@@ -9430,7 +10863,7 @@ BEGIN
-- Order Number
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
- SELECT id
+ SELECT id
FROM edi.ektRecent e
WHERE e.putOrderFk = vBarcode;
@@ -9440,7 +10873,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)
@@ -9451,7 +10884,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;
@@ -9472,524 +10905,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,
- 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,
- 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 */ ;
@@ -10056,7 +11489,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
*/
@@ -10065,17 +11498,17 @@ 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,
@@ -10101,118 +11534,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;
@@ -10279,7 +11712,7 @@ BEGIN
sender = vSender,
senderFk = vSenderId,
messageId = vMessageId;
-
+
IF vIsDuplicated THEN
SELECT id INTO vSelf
FROM mail
@@ -10354,7 +11787,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 */;
--
@@ -10368,7 +11801,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 */;
--
@@ -10387,7 +11820,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 */;
--
@@ -10416,7 +11849,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 */;
--
@@ -10435,7 +11868,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 */;
--
@@ -10451,7 +11884,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 */;
--
@@ -10484,71 +11917,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`
@@ -10569,7 +11939,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 */;
--
@@ -10589,7 +11959,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 */;
--
@@ -10636,7 +12006,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 */;
--
@@ -10652,7 +12022,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 */;
--
@@ -10969,71 +12339,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`
@@ -11087,93 +12394,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`
@@ -11200,7 +12422,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 */;
--
@@ -11215,7 +12437,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 */;
--
@@ -11245,101 +12467,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`
@@ -11420,7 +12549,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 */;
--
@@ -11466,7 +12595,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 */;
--
@@ -11484,7 +12613,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 */;
--
@@ -11498,7 +12627,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 */;
--
@@ -11557,7 +12686,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 */;
--
@@ -11590,7 +12719,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 */;
--
@@ -11674,7 +12803,7 @@ CREATE TABLE `tpvTransaction` (
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 */;
--
@@ -11709,7 +12838,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 */;
--
@@ -11729,7 +12858,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 */;
--
@@ -11754,7 +12883,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 */;
--
@@ -11774,7 +12903,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 */;
--
@@ -11793,7 +12922,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 */ ;;
@@ -11857,7 +12986,7 @@ BEGIN
IF vCount = 0 THEN
RETURN FALSE;
- END IF;
+ END IF;
SELECT COUNT(*) > 0
INTO vHasRole
@@ -11938,14 +13067,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);
@@ -11958,7 +13087,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;
@@ -12060,7 +13189,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);
@@ -12085,14 +13214,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 = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getVisible` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = 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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`(
vWarehouse TINYINT,
@@ -12100,7 +13229,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`(
vType INT,
vPrefix VARCHAR(255))
BEGIN
-
+
/**
* Gets visible items of the specified type at specified date.
*
@@ -12109,22 +13238,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;
@@ -12168,7 +13297,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
@@ -12203,7 +13332,7 @@ 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.packagingFk
@@ -12680,15 +13809,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
@@ -12706,7 +13835,7 @@ BEGIN
company_id = vCompany;
SET vSelf = LAST_INSERT_ID();
-
+
CALL order_checkConfig(vSelf);
COMMIT;
@@ -12752,15 +13881,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
@@ -12778,7 +13907,7 @@ BEGIN
company_id = vCompany;
SET vSelf = LAST_INSERT_ID();
-
+
CALL order_checkConfig(vSelf);
COMMIT;
@@ -12961,7 +14090,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,
@@ -13122,7 +14251,7 @@ BEGIN
ROLLBACK;
RESIGNAL;
END;
-
+
CALL order_calcCatalogFromItem(vSelf, vItem);
START TRANSACTION;
@@ -13142,7 +14271,7 @@ BEGIN
END IF;
SELECT IFNULL(minQuantity, 0) INTO vMinQuantity
- FROM vn.item
+ FROM vn.item
WHERE id = vItem;
IF vAmount < LEAST(vMinQuantity, vAvailable) THEN
@@ -13235,10 +14364,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;
@@ -13613,7 +14742,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
@@ -13673,7 +14802,7 @@ BEGIN
SELECT t.id INTO vTicket
FROM vn.ticket t
LEFT JOIN tPrevia tp ON tp.ticketFk = t.id
- LEFT JOIN vn.ticketState tls on tls.ticket = 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
@@ -13682,11 +14811,10 @@ BEGIN
WHERE o.id = vSelf
AND t.refFk IS NULL
AND tp.ticketFk IS NULL
- AND IFNULL(tls.alertLevel,0) = 0
+ AND IFNULL(tls.alertLevel,0) = 0
LIMIT 1;
-- Crea el ticket en el caso de no existir uno adecuado
-
IF vTicket IS NULL
THEN
@@ -13708,7 +14836,7 @@ BEGIN
ELSE
INSERT INTO vn.ticketTracking
SET ticketFk = vTicket,
- workerFk = vUserId,
+ userFk = vUserId,
stateFk = TICKET_FREE;
END IF;
@@ -13722,7 +14850,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`);
@@ -13942,7 +15070,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;
@@ -13984,7 +15112,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;
@@ -14019,7 +15147,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))
@@ -14028,7 +15156,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 ;
@@ -14098,7 +15226,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)
@@ -14189,7 +15317,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
@@ -14214,7 +15342,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;
@@ -14742,13 +15870,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 ;
@@ -14781,7 +15909,7 @@ BEGIN
UPDATE userSession SET userVisitFk = vUserVisit
WHERE ssid = vSsid;
-
+
DELETE FROM userSession
WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, util.VN_NOW());
END ;;
@@ -14905,7 +16033,7 @@ BEGIN
UPDATE visitAgent SET firstAccessFk = vAccessId
WHERE id = vAgentId;
END IF;
-
+
-- Returns the visit info
SELECT vVisit visit, vAccessId access;
@@ -14936,46 +16064,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`
@@ -15009,7 +16097,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 */;
--
@@ -15051,7 +16139,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 */;
--
@@ -15068,46 +16156,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`
@@ -15140,7 +16188,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 */;
--
@@ -15175,48 +16223,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`
@@ -15252,7 +16260,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 */;
--
@@ -15271,7 +16279,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 */;
--
@@ -15303,48 +16311,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`
@@ -15362,7 +16330,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 */;
--
@@ -15383,96 +16351,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`
@@ -15542,7 +16420,7 @@ CREATE TABLE `sipConfig` (
`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 */;
--
@@ -15618,7 +16496,7 @@ BEGIN
WHILE vI < vLen
DO
SET vChr = SUBSTR(vPhone, vI + 1, 1);
-
+
IF vChr REGEXP '^[0-9]$'
THEN
SET vNewPhone = CONCAT(vNewPhone, vChr);
@@ -15626,7 +16504,7 @@ BEGIN
THEN
SET vNewPhone = CONCAT(vNewPhone, '00');
END IF;
-
+
SET vI = vI + 1;
END WHILE;
@@ -15725,18 +16603,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 */ ;
@@ -15802,6 +16680,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`
--
@@ -15962,6 +17263,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`
--
@@ -16122,7 +17436,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 */;
--
@@ -16317,30 +17631,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`
@@ -16438,7 +17730,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 */;
--
@@ -16524,22 +17816,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 ;
@@ -16558,12 +17850,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
@@ -16580,7 +17872,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
@@ -16879,8 +18170,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
@@ -16899,7 +18190,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
@@ -16917,8 +18208,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
@@ -16952,14 +18243,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);
@@ -16970,41 +18261,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 */ ;
@@ -17083,8 +18364,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,
@@ -17150,6 +18431,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 */ ;
@@ -17162,10 +18518,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_add`(vInvoiceInFk INT, vX
BEGIN
/**
* Traslada la info de contabilidad relacionada con las facturas recibidas
- *
+ *
* @vInvoiceInFk Factura recibida
* @vXDiarioFk Id tabla XDiario
- */
+ */
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vBase DOUBLE;
DECLARE vVat DOUBLE;
@@ -17182,25 +18538,25 @@ BEGIN
DECLARE vInvoiceTypeInformative VARCHAR(1);
DECLARE vIsInformativeExportation BOOL DEFAULT FALSE;
- DECLARE vCursor CURSOR FOR
+ DECLARE vCursor CURSOR FOR
SELECT it.taxableBase,
CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)),
t.PorcentajeIva,
it.transactionTypeSageFk,
it.taxTypeSageFk,
tty.isIntracommunity,
- tt.ClaveOperacionDefecto
+ tt.ClaveOperacionDefecto
FROM vn.invoiceIn i
JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id
JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk
JOIN taxType tty ON tty.id = t.CodigoIva
JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk
LEFT JOIN vn.dua d ON d.id = vInvoiceInFk
- WHERE i.id = vInvoiceInFk
+ WHERE i.id = vInvoiceInFk
AND d.id IS NULL;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
DELETE FROM movContaIVA
WHERE id = vXDiarioFk;
@@ -17223,22 +18579,22 @@ BEGIN
vTaxCode,
vIsIntracommunity,
vOperationCode;
-
- IF vDone THEN
+
+ IF vDone THEN
LEAVE l;
END IF;
- SET vTransactionCodeOld = vTransactionCode;
- SET vTaxCodeOld = vTaxCode;
+ SET vTransactionCodeOld = vTransactionCode;
+ SET vTaxCodeOld = vTaxCode;
- IF vOperationCode IS NOT NULL THEN
+ IF vOperationCode IS NOT NULL THEN
UPDATE movContaIVA
SET ClaveOperacionFactura = vOperationCode
WHERE id = vXDiarioFk;
END IF;
-
+
SET vCounter = vCounter + 1;
- CASE vCounter
+ CASE vCounter
WHEN 1 THEN
UPDATE movContaIVA
SET BaseIva1 = vBase,
@@ -17274,31 +18630,31 @@ BEGIN
WHERE id = vXDiarioFk;
ELSE
SELECT vXDiarioFk INTO vXDiarioFk;
- END CASE;
+ END CASE;
IF vIsIntracommunity THEN
UPDATE movContaIVA
SET Intracomunitaria = TRUE
WHERE id = vXDiarioFk;
END IF;
-
- SET vTransactionCodeOld = vTransactionCode;
- SET vTaxCodeOld = vTaxCode;
-
+
+ SET vTransactionCodeOld = vTransactionCode;
+ SET vTaxCodeOld = vTaxCode;
+
END LOOP;
CLOSE vCursor;
SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation
FROM vn.dua d
- LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN
+ LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN
AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci
WHERE d.ASIEN = (
SELECT ASIEN
- FROM vn.XDiario
+ FROM vn.XDiario
WHERE id = vXDiarioFk)
LIMIT 1;
-
+
UPDATE movContaIVA mci
JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk
JOIN vn.XDiario x ON x.id = mci.id
@@ -17310,13 +18666,13 @@ BEGIN
mci.Serie = ii.serial,
mci.Factura = ii.id,
mci.FechaFactura = ii.issued,
- mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) +
- IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) +
- IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) +
+ mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) +
+ IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) +
+ IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) +
IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0),
- mci.TipoFactura = IF(id.id,
- IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative),
- IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)),
+ mci.TipoFactura = IF(id.id,
+ IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative),
+ IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)),
mci.CodigoCuentaFactura = x.SUBCTA,
mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif),
mci.Nombre = s.name,
@@ -17344,7 +18700,7 @@ BEGIN
JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase
FROM vn.XDiario x1
JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN
- WHERE x2.BASEEURO <> 0
+ WHERE x2.BASEEURO <> 0
AND x1.id = vXDiarioFk
)sub
JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio'
@@ -17352,8 +18708,8 @@ BEGIN
mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura),
mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase),
mci.PorRetencion = t.PorcentajeRetencion,
- mci.ImporteRetencion = iit.taxableBase * - 1
- WHERE mci.id = vXDiarioFk
+ mci.ImporteRetencion = iit.taxableBase * - 1
+ WHERE mci.id = vXDiarioFk
AND e.name = 'Retenciones'
AND id.id IS NULL;
@@ -17376,10 +18732,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;
@@ -17391,22 +18747,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;
@@ -17420,15 +18776,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
@@ -17446,7 +18802,7 @@ BEGIN
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,
@@ -17454,8 +18810,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;
@@ -17463,7 +18819,7 @@ BEGIN
l: LOOP
FETCH vCursor INTO vInvoiceFk, vXDiarioFk;
- IF vDone THEN
+ IF vDone THEN
LEAVE l;
END IF;
CALL invoiceIn_add(vInvoiceFk, vXDiarioFk);
@@ -17551,21 +18907,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`,
@@ -17636,9 +18992,9 @@ BEGIN
`FechaGrabacion`,
`Intracomunitaria`,
`moveData`)
- SELECT *
+ SELECT *
FROM tmp.movContaIVA;
-
+
DROP TEMPORARY TABLE tmp.movContaIVA;
END ;;
@@ -17660,10 +19016,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;
@@ -17683,12 +19039,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,
@@ -17697,7 +19053,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'
@@ -17713,12 +19069,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;
@@ -17735,13 +19091,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,
@@ -17782,7 +19138,7 @@ BEGIN
CodigoTransaccion4 = vTransactionCode,
CodigoIva4 = vTaxCode
WHERE id = vXDiarioFk;
- END CASE;
+ END CASE;
UPDATE movContaIVA
SET Exclusion347 = NOT vMod347,
@@ -17793,7 +19149,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
@@ -17818,25 +19174,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,
@@ -17867,10 +19223,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;
@@ -17887,7 +19243,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
@@ -17896,19 +19252,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;
@@ -17934,7 +19290,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;
@@ -17944,25 +19300,25 @@ BEGIN
CodigoCuenta,
Cuenta,
ClienteOProveedor)
- SELECT *
+ SELECT *
FROM (SELECT company_getCode(vCompanyFk) companyFk,
e.id accountFk,
UCASE(e.name),
''
FROM vn.expense e
- UNION
+ UNION
SELECT company_getCode(vCompanyFk),
- b.account,
+ b.account,
UCASE(b.bank),
- ''
+ ''
FROM vn.bank b
WHERE b.isActive
AND b.`account`
- UNION
+ UNION
SELECT CodigoEmpresa,
CodigoCuenta,
Nombre,
- ClienteOProveedor
+ ClienteOProveedor
FROM clientesProveedores)sub
GROUP BY companyFk, accountFk;
END ;;
@@ -17999,7 +19355,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 */;
--
@@ -18102,7 +19458,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 */;
--
@@ -18149,7 +19505,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 */;
--
@@ -18177,7 +19533,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 */;
--
@@ -18209,7 +19565,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 */;
--
@@ -18228,7 +19584,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 */ ;;
@@ -18264,6 +19620,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`
--
@@ -18297,67 +23201,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`
@@ -18420,68 +23263,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`
@@ -18514,7 +23295,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 */ ;;
@@ -18646,7 +23427,7 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
-
+
SET vSupplied = 0;
OPEN vPicks;
@@ -18662,7 +23443,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
@@ -18742,7 +23523,7 @@ BEGIN
END IF;
SET vSupplied = LEAST(vAvailable, vLack);
-
+
IF vSupplied > 0 THEN
SET vAvailable = vAvailable - vSupplied;
UPDATE outbound
@@ -18755,7 +23536,7 @@ BEGIN
SET vSupplied = vSupplied + vSuppliedFromRequest;
SET vAvailable = vAvailable - vSuppliedFromRequest;
END IF;
-
+
IF vSupplied > 0 THEN
CALL inbound_addPick(vSelf, vOutboundFk, vSupplied);
END IF;
@@ -18884,7 +23665,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;
@@ -19355,7 +24136,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
@@ -19498,6 +24279,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`
--
@@ -19538,7 +24397,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 */;
--
@@ -19558,7 +24417,7 @@ CREATE TABLE `debug` (
`value` varchar(255) 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 */;
--
@@ -19575,7 +24434,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 */;
--
@@ -19637,7 +24496,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 */;
--
@@ -19660,7 +24519,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 */;
--
@@ -19680,7 +24539,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 */;
--
@@ -19711,7 +24570,7 @@ 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=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -19749,7 +24608,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 */ ;;
@@ -19809,11 +24668,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;
@@ -19850,11 +24709,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 */ ;
@@ -19876,11 +24735,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 */ ;
@@ -20048,7 +24907,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);
@@ -20077,7 +24936,7 @@ BEGIN
*/
DECLARE vHashlen INT UNSIGNED;
DECLARE vOpad, vIpad TINYBLOB;
-
+
CASE vAlg
WHEN 224 THEN SET vHashlen = 64;
WHEN 256 THEN SET vHashlen = 64;
@@ -20085,16 +24944,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 ;
@@ -20117,7 +24976,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 */ ;
@@ -20276,7 +25135,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `midnight`() RETURNS datetime
READS SQL DATA
BEGIN
-
+
RETURN TIMESTAMP(util.VN_CURDATE(), '23:59:59');
END ;;
@@ -20404,7 +25263,7 @@ BEGIN
* modo 3.
*/
DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100);
-
+
IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN
RETURN vYearWeek + 1;
ELSE
@@ -20510,16 +25369,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 ;
@@ -20790,11 +25649,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;
@@ -20877,7 +25736,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),
@@ -21261,7 +26120,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 */ ;
@@ -21269,18 +26128,41 @@ 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 */ ;
@@ -21397,94 +26279,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`
@@ -21521,7 +26317,7 @@ 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 */;
--
@@ -21563,7 +26359,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 */;
--
@@ -21623,8 +26419,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,
@@ -21646,146 +26442,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`
@@ -21812,7 +26470,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 */;
--
@@ -21847,7 +26505,7 @@ 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 */;
--
@@ -21886,28 +26544,8 @@ CREATE TABLE `agency` (
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`
@@ -21961,7 +26599,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 */;
--
@@ -21980,7 +26618,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 */;
--
@@ -22017,6 +26670,20 @@ CREATE TABLE `agencyTermConfig` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Temporary table structure for view `agencyWarehouse`
+--
+
+DROP TABLE IF EXISTS `agencyWarehouse`;
+/*!50001 DROP VIEW IF EXISTS `agencyWarehouse`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `agencyWarehouse` AS SELECT
+ 1 AS `agencyFk`,
+ 1 AS `warehouseFk`,
+ 1 AS `agencyType` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `alertLevel`
--
@@ -22077,7 +26744,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 */;
--
@@ -22094,7 +26761,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 */;
--
@@ -22147,7 +26814,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 */;
--
@@ -22169,78 +26836,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`
@@ -22294,31 +26891,8 @@ CREATE TABLE `awb` (
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());
-
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_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 `awbVolume`
@@ -22368,50 +26942,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`
@@ -22425,7 +26957,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 */;
--
@@ -22500,7 +27032,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 */;
--
@@ -22527,7 +27059,31 @@ 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__`
+--
+
+DROP TABLE IF EXISTS `botanicExport__`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `botanicExport__` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `ediGenusFk` mediumint(8) unsigned NOT NULL,
+ `ediSpecieFk` mediumint(8) unsigned DEFAULT NULL,
+ `countryFk__` mediumint(8) unsigned DEFAULT NULL,
+ `restriction` enum('Sin restriccion','Importacion Prohibida','pasaporte fitosanitario','pasaporte individual','declaracion origen') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `description` varchar(45) DEFAULT NULL,
+ `isProtectedZone` tinyint(1) NOT NULL DEFAULT 0,
+ `code` enum('importProhibited','phytosanitaryPassport','individualPassport') DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `Id_Paises` (`countryFk__`),
+ KEY `botanicExport_ibfk_2_idx` (`ediGenusFk`),
+ KEY `botanicExport_ibfk_3_idx` (`ediSpecieFk`),
+ CONSTRAINT `botanicExport___ibfk_1` FOREIGN KEY (`countryFk__`) REFERENCES `country` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #4419 Deprecated 2023-07-20';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -22561,7 +27117,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 */;
--
@@ -22580,7 +27136,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 */;
--
@@ -22601,7 +27157,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 */;
--
@@ -22622,34 +27178,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`
@@ -22664,7 +27194,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 */;
--
@@ -22719,148 +27249,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`
@@ -22888,7 +27278,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 */;
--
@@ -22908,7 +27298,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 */;
--
@@ -22938,7 +27328,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,
@@ -22986,319 +27376,8 @@ CREATE TABLE `buy` (
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 = 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`.`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.packagingFk <=> OLD.packagingFk) 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`
@@ -23378,7 +27457,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 */;
--
@@ -23402,7 +27481,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 */;
--
@@ -23416,7 +27495,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 */;
--
@@ -23431,7 +27510,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 */;
--
@@ -23448,7 +27527,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 */;
--
@@ -23465,7 +27544,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 */;
--
@@ -23480,7 +27559,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 */;
--
@@ -23498,7 +27577,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 */;
--
@@ -23522,7 +27601,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 */;
--
@@ -23539,7 +27618,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 */;
--
@@ -23575,72 +27654,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`
@@ -23662,72 +27677,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`
@@ -23757,7 +27708,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 */;
--
@@ -23794,72 +27745,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`
@@ -23880,70 +27767,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`
@@ -23970,72 +27793,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`
@@ -24062,7 +27821,7 @@ CREATE TABLE `claimLog` (
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 */;
--
@@ -24087,72 +27846,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`
@@ -24185,7 +27880,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 */;
--
@@ -24199,7 +27894,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 */;
--
@@ -24216,7 +27911,7 @@ CREATE TABLE `claimResponsible` (
`code` varchar(3) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `claimResponsible_UN` (`code`)
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Responsables de las causas';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Responsables de las causas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -24230,7 +27925,7 @@ 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 */;
--
@@ -24246,7 +27941,7 @@ CREATE TABLE `claimRma` (
`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;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -24269,72 +27964,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`
@@ -24436,217 +28067,8 @@ CREATE TABLE `client` (
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 = 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`.`client_AfterInsert`
- AFTER INSERT ON `client`
- FOR EACH ROW
-BEGIN
- IF NEW.credit IS NOT NULL AND NEW.credit THEN
- INSERT INTO clientCredit
- SET clientFk = NEW.id,
- workerFk = NEW.editorFk,
- amount = NEW.credit;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @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();
-
- IF NOT(NEW.credit <=> OLD.credit) THEN
- INSERT INTO clientCredit
- SET clientFk = NEW.id,
- amount = NEW.credit,
- workerFk = NEW.editorFk;
- END IF;
- -- 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`
@@ -24664,7 +28086,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 */;
--
@@ -24691,7 +28113,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 */;
--
@@ -24708,7 +28130,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 */;
--
@@ -24729,52 +28151,8 @@ CREATE TABLE `clientContact` (
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`
@@ -24794,61 +28172,25 @@ 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 */;
+--
+-- Temporary table structure for view `clientDefaultCompany`
+--
+
+DROP TABLE IF EXISTS `clientDefaultCompany`;
+/*!50001 DROP VIEW IF EXISTS `clientDefaultCompany`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `clientDefaultCompany` AS SELECT
+ 1 AS `id`,
+ 1 AS `clientFk`,
+ 1 AS `companyFk`,
+ 1 AS `started`,
+ 1 AS `finished` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `clientDms`
--
@@ -24869,70 +28211,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`
@@ -24953,7 +28231,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 */;
--
@@ -24973,7 +28251,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 */;
--
@@ -25001,7 +28279,7 @@ CREATE TABLE `clientLog` (
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 */;
--
@@ -25057,72 +28335,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`
@@ -25164,11 +28378,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 */;
@@ -25214,72 +28425,8 @@ CREATE TABLE `clientSample` (
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`
@@ -25292,12 +28439,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 UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -25314,7 +28464,7 @@ CREATE TABLE `clientType` (
`isCreatedAsServed` tinyint(1) DEFAULT 0,
PRIMARY KEY (`id`),
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 */;
--
@@ -25386,30 +28536,8 @@ CREATE TABLE `cmr` (
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`
@@ -25475,56 +28603,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`
@@ -25544,48 +28624,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`
@@ -25599,7 +28639,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 */;
--
@@ -25622,142 +28662,8 @@ 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 */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collectionVolumetry_afterInsert`
- AFTER INSERT ON `collectionVolumetry`
- FOR EACH ROW
-BEGIN
- DECLARE vJSON JSON DEFAULT JSON_OBJECT();
- DECLARE vUserFk INT DEFAULT account.myUser_getId();
-
- SET vJSON = JSON_MERGE(JSON_OBJECT('id', NEW.id), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('level', NEW.level), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('lines', NEW.lines), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('liters', NEW.liters), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('height', NEW.height), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('itemPackingTypeFk', NEW.itemPackingTypeFk), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('trainFk', NEW.trainFk), vJSON);
-
- SET vJSON = JSON_MERGE(JSON_OBJECT('userFk', vUserFk), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('action', 'insert'), vJSON);
-
- SET vJSON = util.notification_send(
- 'modified-collection-volumetry',
- JSON_OBJECT('data', JSON_EXTRACT(vJSON, '$')),
- 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_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collectionVolumetry_afterUpdate`
- AFTER UPDATE ON `collectionVolumetry`
- FOR EACH ROW
-BEGIN
- DECLARE vJSON JSON DEFAULT JSON_OBJECT();
- DECLARE vUserFk INT DEFAULT account.myUser_getId();
-
- IF NOT (NEW.id <=> OLD.id) THEN
- SET vJSON = JSON_MERGE(JSON_OBJECT('id', NEW.id), vJSON);
- END IF;
-
- IF NOT (NEW.`level` <=> OLD.`level`) THEN
- SET vJSON = JSON_MERGE(JSON_OBJECT('level', NEW.`level`), vJSON);
- END IF;
-
- IF NOT (NEW.`lines` <=> OLD.`lines`) THEN
- SET vJSON = JSON_MERGE(JSON_OBJECT('lines', NEW.`lines`), vJSON);
- END IF;
-
- IF NOT (NEW.liters <=> OLD.liters) THEN
- SET vJSON = JSON_MERGE(JSON_OBJECT('liters', NEW.liters), vJSON);
- END IF;
-
- IF NOT (NEW.height <=> OLD.height) THEN
- SET vJSON = JSON_MERGE(JSON_OBJECT('height', NEW.height), vJSON);
- END IF;
-
- IF NOT (NEW.itemPackingTypeFk <=> OLD.itemPackingTypeFk) THEN
- SET vJSON = JSON_MERGE(JSON_OBJECT('itemPackingTypeFk', NEW.itemPackingTypeFk), vJSON);
- END IF;
-
- IF NOT (NEW.trainFk <=> OLD.trainFk) THEN
- SET vJSON = JSON_MERGE(JSON_OBJECT('trainFk', NEW.trainFk), vJSON);
- END IF;
-
- SET vJSON = JSON_MERGE(JSON_OBJECT('userFk', vUserFk), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('action', 'update'), vJSON);
-
- SET vJSON = util.notification_send(
- 'modified-collection-volumetry',
- JSON_OBJECT('data', JSON_EXTRACT(vJSON, '$')),
- 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_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collectionVolumetry_afterDelete`
- AFTER DELETE ON `collectionVolumetry`
- FOR EACH ROW
-BEGIN
- DECLARE vJSON JSON DEFAULT JSON_OBJECT();
- DECLARE vUserFk INT DEFAULT account.myUser_getId();
-
- SET vJSON = JSON_MERGE(JSON_OBJECT('id', OLD.id), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('level', OLD.level), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('lines', OLD.lines), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('liters', OLD.liters), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('height', OLD.height), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('itemPackingTypeFk', OLD.itemPackingTypeFk), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('trainFk', OLD.trainFk), vJSON);
-
- SET vJSON = JSON_MERGE(JSON_OBJECT('userFk', vUserFk), vJSON);
- SET vJSON = JSON_MERGE(JSON_OBJECT('action', 'delete'), vJSON);
-
- SET vJSON = util.notification_send(
- 'modified-collection-volumetry',
- JSON_OBJECT('data', JSON_EXTRACT(vJSON, '$')),
- 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 */ ;
--
-- Table structure for table `collectionWagon`
@@ -25854,7 +28760,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',
@@ -25875,7 +28781,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 */;
--
@@ -25889,7 +28795,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 */;
--
@@ -25921,6 +28827,47 @@ 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`
--
@@ -25935,7 +28882,36 @@ CREATE TABLE `comparativeConfig` (
`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=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 `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 */;
--
@@ -25973,7 +28949,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 */;
--
@@ -25991,7 +28967,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 */;
--
@@ -26005,7 +28981,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 */;
--
@@ -26056,7 +29032,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 */;
--
@@ -26070,7 +29046,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 */;
--
@@ -26086,7 +29062,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 */;
--
@@ -26112,7 +29088,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 */;
--
@@ -26128,7 +29104,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 */;
--
@@ -26146,7 +29122,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 */;
--
@@ -26209,7 +29185,37 @@ 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 */;
+
+--
+-- Temporary table structure for view `coolerPath`
+--
+
+DROP TABLE IF EXISTS `coolerPath`;
+/*!50001 DROP VIEW IF EXISTS `coolerPath`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `coolerPath` AS SELECT
+ 1 AS `id`,
+ 1 AS `description` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- 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 */;
--
@@ -26258,124 +29264,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`
@@ -26388,10 +29278,9 @@ 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;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `cplusRectificationType`
--
@@ -26464,34 +29353,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`
@@ -26512,53 +29375,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`
@@ -26593,7 +29411,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 */;
--
@@ -26648,7 +29466,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 */;
--
@@ -26664,7 +29482,7 @@ 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 */;
--
@@ -26679,7 +29497,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 */;
--
@@ -26709,7 +29527,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 */;
--
@@ -26752,108 +29570,8 @@ CREATE TABLE `department` (
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 `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`
@@ -26879,7 +29597,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 */;
--
@@ -26897,7 +29615,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 */;
--
@@ -26918,7 +29636,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 */;
--
@@ -26952,72 +29670,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`
@@ -27031,33 +29685,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`
@@ -27084,7 +29713,7 @@ CREATE TABLE `deviceProductionLog` (
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 */;
--
@@ -27102,46 +29731,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`
@@ -27159,46 +29748,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`
@@ -27221,70 +29770,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`
@@ -27297,7 +29782,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 */;
--
@@ -27330,115 +29815,8 @@ 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;
-
- 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 */ ;
--
-- Table structure for table `dmsType`
@@ -27449,20 +29827,42 @@ 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 */;
+--
+-- Temporary table structure for view `doc`
+--
+
+DROP TABLE IF EXISTS `doc`;
+/*!50001 DROP VIEW IF EXISTS `doc`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `doc` AS SELECT
+ 1 AS `id`,
+ 1 AS `sref`,
+ 1 AS `brief`,
+ 1 AS `companyFk`,
+ 1 AS `order`,
+ 1 AS `file`,
+ 1 AS `original`,
+ 1 AS `workerFk`,
+ 1 AS `created`,
+ 1 AS `warehouseFk` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `dock`
--
@@ -27495,7 +29895,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 */;
--
@@ -27510,7 +29910,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 */;
--
@@ -27523,7 +29937,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,
@@ -27534,13 +29948,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 */;
--
@@ -27581,7 +29994,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 */;
--
@@ -27601,7 +30014,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 */;
--
@@ -27623,50 +30036,8 @@ CREATE TABLE `duaTax` (
KEY `duaTax_fk3_idx` (`taxClassFk`),
CONSTRAINT `duaTax_fk1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `duaTax_fk3` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE
-) ENGINE=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`.`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`
@@ -27740,48 +30111,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`
@@ -27810,7 +30141,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 */;
--
@@ -27905,190 +30236,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`
@@ -28132,7 +30281,7 @@ CREATE TABLE `entryLog` (
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 */;
--
@@ -28153,74 +30302,10 @@ 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 */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @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`
@@ -28281,7 +30366,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 */;
--
@@ -28317,7 +30402,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';
+) 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 */;
--
@@ -28341,9 +30426,47 @@ 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;
+
+--
+-- Temporary table structure for view `exchangeInsurance`
+--
+
+DROP TABLE IF EXISTS `exchangeInsurance`;
+/*!50001 DROP VIEW IF EXISTS `exchangeInsurance`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `exchangeInsurance` AS SELECT
+ 1 AS `id`,
+ 1 AS `amount`,
+ 1 AS `dated`,
+ 1 AS `finished`,
+ 1 AS `entityFk`,
+ 1 AS `ref`,
+ 1 AS `rate`,
+ 1 AS `companyFk`,
+ 1 AS `financialProductTypefk`,
+ 1 AS `upperBarrier`,
+ 1 AS `lowerBarrier`,
+ 1 AS `strike` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Temporary table structure for view `exchangeInsuranceEntry`
--
@@ -28372,6 +30495,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`
--
@@ -28386,6 +30523,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`
--
@@ -28416,7 +30572,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 */;
--
@@ -28466,124 +30622,8 @@ CREATE TABLE `expedition` (
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`
@@ -28675,36 +30715,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`
@@ -28780,30 +30792,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`
@@ -28843,52 +30833,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 = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionState_BeforeInsert`
- BEFORE INSERT ON `expeditionState`
- FOR EACH ROW
-BEGIN
- SET NEW.userFk = IFNULL(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`
@@ -28902,7 +30848,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 */;
--
@@ -28988,52 +30934,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`
@@ -29110,7 +31012,7 @@ CREATE TABLE `expense` (
`isWithheld` tinyint(4) NOT NULL DEFAULT 0,
`code` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`),
- UNIQUE KEY `expense_UN` (`code`)
+ UNIQUE KEY `expence_UN` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -29136,7 +31038,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 */;
--
@@ -29175,7 +31077,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 */;
--
@@ -29195,7 +31097,7 @@ 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 */;
--
@@ -29247,28 +31149,8 @@ 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 */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @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`
@@ -29281,7 +31163,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 */;
--
@@ -29297,7 +31179,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 */;
--
@@ -29312,7 +31194,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 */;
--
@@ -29348,7 +31230,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 */;
--
@@ -29363,7 +31245,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 */;
--
@@ -29385,7 +31267,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 */;
--
@@ -29406,6 +31288,20 @@ CREATE TABLE `glsExpedition` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Temporary table structure for view `grantGroup`
+--
+
+DROP TABLE IF EXISTS `grantGroup`;
+/*!50001 DROP VIEW IF EXISTS `grantGroup`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `grantGroup` AS SELECT
+ 1 AS `id`,
+ 1 AS `description`,
+ 1 AS `observationTypeFk` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `greuge`
--
@@ -29436,94 +31332,8 @@ CREATE TABLE `greuge` (
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`
@@ -29539,7 +31349,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 */;
--
@@ -29554,7 +31364,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 */;
--
@@ -29589,28 +31399,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`
@@ -29757,7 +31547,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 */;
--
@@ -29771,7 +31561,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 */;
--
@@ -29794,9 +31584,9 @@ CREATE TABLE `invoiceCorrection` (
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 (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`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 */;
@@ -29831,7 +31621,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 */;
--
@@ -29878,12 +31668,12 @@ CREATE TABLE `invoiceIn` (
KEY `recibida_ibfk_6` (`cplusRectificationTypeFk`),
KEY `recibida_ibfk_7` (`siiTrascendencyInvoiceInFk`),
KEY `invoiceIn_withholdingFk_idx` (`withholdingSageFk`),
- KEY `invoiceIn_expenseFkDeductible_idx` (`expenseFkDeductible`),
+ 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_expenseFkDeductible` FOREIGN KEY (`expenseFkDeductible`) REFERENCES `expense` (`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,
@@ -29892,176 +31682,8 @@ CREATE TABLE `invoiceIn` (
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`
@@ -30080,7 +31702,7 @@ CREATE TABLE `invoiceInConfig` (
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 */;
--
@@ -30106,116 +31728,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`
@@ -30239,7 +31753,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 */;
--
@@ -30267,7 +31781,7 @@ CREATE TABLE `invoiceInLog` (
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 */;
--
@@ -30294,13 +31808,13 @@ CREATE TABLE `invoiceInSage` (
KEY `invoiceInSage_taxTypeSageFk` (`taxTypeSageFk`),
KEY `invoiceInSage_transactionTypeSageFk` (`transactionTypeSageFk`),
KEY `invoiceInSage_idx` (`expenseFk`),
- CONSTRAINT `invoiceInSage_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
+ 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 */;
--
@@ -30348,82 +31862,13 @@ CREATE TABLE `invoiceInTax` (
KEY `invoiceInTax_transactionTypeSageFk_idx` (`transactionTypeSageFk`),
KEY `invoiceInTax_idx` (`expenseFk`),
KEY `invoiceInTax_fk_editor` (`editorFk`),
- CONSTRAINT `invoiceInTax_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`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
- CALL invoiceInTax_afterUpsert(NEW.invoiceInFk);
- 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
- IF NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) THEN
- CALL invoiceInTax_afterUpsert(NEW.invoiceInFk);
- END IF;
-
- 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`
@@ -30448,7 +31893,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 */;
--
@@ -30493,113 +31938,8 @@ CREATE TABLE `invoiceOut` (
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`
@@ -30611,8 +31951,9 @@ 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 */;
--
@@ -30629,11 +31970,11 @@ CREATE TABLE `invoiceOutExpense` (
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
- KEY `invoiceOutExpense_FK_1_idx` (`invoiceOutFk`),
- KEY `invoiceOutExpense_expenseFk_idx` (`expenseFk`),
- CONSTRAINT `invoiceOutExpense_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `invoiceOutExpense_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`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';
+ KEY `invoiceOutExpence_FK_1_idx` (`invoiceOutFk`),
+ KEY `invoiceOutExpence_expenceFk_idx` (`expenseFk`),
+ CONSTRAINT `invoiceOutExpence_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `invoiceOutExpence_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Desglosa la base imponible de una factura en funcion del tipo de gasto/venta';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -30679,7 +32020,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 */;
--
@@ -30703,7 +32044,7 @@ CREATE TABLE `invoiceOutTaxConfig` (
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;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -30763,7 +32104,6 @@ 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',
@@ -30793,159 +32133,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_expenseFk_idx` (`expenseFk`),
+ 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_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`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`
@@ -30966,72 +32166,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`
@@ -31055,70 +32191,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`
@@ -31158,31 +32230,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`
@@ -31224,7 +32273,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 */;
--
@@ -31289,71 +32338,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`
@@ -31452,7 +32436,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 */;
--
@@ -31480,7 +32464,7 @@ CREATE TABLE `itemLog` (
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 */;
--
@@ -31540,7 +32524,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 */;
--
@@ -31634,6 +32618,7 @@ CREATE TABLE `itemShelving` (
`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`),
@@ -31644,141 +32629,8 @@ CREATE TABLE `itemShelving` (
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 itemShelvingLog
- SET itemShelvingFk = NEW.id,
- workerFk = account.myUser_getId(),
- accion = 'CAMBIO',
- itemFk = NEW.itemFk,
- shelvingFk = NEW.shelvingFk,
- visible = NEW.visible,
- `grouping` = NEW.`grouping`,
- packing = 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`
@@ -31860,7 +32712,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 */;
--
@@ -31884,7 +32736,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 */;
--
@@ -31933,32 +32785,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 = 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`.`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`
@@ -32041,20 +32869,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`
--
@@ -32081,144 +32895,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`
@@ -32255,72 +32933,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`
@@ -32393,38 +33030,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`
@@ -32470,7 +33077,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 */;
--
@@ -32491,7 +33098,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 */;
--
@@ -32667,30 +33274,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`
@@ -32714,7 +33299,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 */;
--
@@ -32733,7 +33318,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 */;
--
@@ -32754,7 +33339,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 */;
--
@@ -32768,7 +33353,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 */;
--
@@ -32799,34 +33384,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`
@@ -32840,7 +33399,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 */;
--
@@ -32865,32 +33424,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`
@@ -32903,7 +33438,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 */;
--
@@ -32920,7 +33455,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 */;
--
@@ -32970,7 +33505,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 */;
--
@@ -33024,7 +33559,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 */;
--
@@ -33049,7 +33584,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 */;
--
@@ -33070,7 +33605,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 */;
--
@@ -33092,7 +33627,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 */;
--
@@ -33144,7 +33679,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 */;
--
@@ -33164,7 +33699,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 */;
--
@@ -33181,7 +33716,7 @@ 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 */;
--
@@ -33218,6 +33753,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`
--
@@ -33251,7 +33804,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 */;
--
@@ -33284,7 +33837,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 */;
--
@@ -33316,61 +33869,23 @@ CREATE TABLE `operator` (
`warehouseFk` smallint(6) unsigned NOT NULL DEFAULT 60,
`sectorFk` int(11) DEFAULT NULL,
`labelerFk` tinyint(3) unsigned DEFAULT NULL,
+ `linesLimit` int(11) DEFAULT NULL COMMENT 'Límite de lineas en una colección para la asignación de pedidos',
+ `volumeLimit` decimal(10,6) DEFAULT NULL 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`
@@ -33422,7 +33937,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 */;
--
@@ -33509,7 +34024,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 */;
--
@@ -33584,46 +34099,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`
@@ -33647,7 +34122,7 @@ CREATE TABLE `packagingConfig` (
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=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Altura mínima para preparar pedidos en preparacion previa';
+) 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 */;
--
@@ -33673,7 +34148,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 */;
--
@@ -33743,72 +34218,8 @@ CREATE TABLE `packingSite` (
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=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`.`packingSite_beforeInsert`
- BEFORE INSERT ON `packingSite`
- 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`.`packingSite_beforeUpdate`
- BEFORE UPDATE ON `packingSite`
- 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`.`packingSite_afterDelete`
- AFTER DELETE ON `packingSite`
- FOR EACH ROW
-BEGIN
- INSERT INTO packingSiteDeviceLog
- SET `action` = 'delete',
- `changedModel` = 'PackingSite',
- `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 `packingSiteAdvanced`
@@ -33841,7 +34252,7 @@ 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 */;
--
@@ -33898,7 +34309,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 */;
--
@@ -33948,52 +34359,8 @@ CREATE TABLE `parking` (
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`) ;
-
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @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 */ ;
--
-- Table structure for table `payDem`
@@ -34006,7 +34373,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 */;
--
@@ -34043,7 +34410,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 */;
--
@@ -34083,178 +34450,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`
@@ -34271,6 +34491,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`
--
@@ -34285,7 +34524,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 */;
--
@@ -34322,7 +34561,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 */;
--
@@ -34490,97 +34729,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`
@@ -34628,7 +34776,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 */;
--
@@ -34648,7 +34796,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 */;
--
@@ -34667,7 +34815,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 */;
--
@@ -34681,7 +34829,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 */;
--
@@ -34710,9 +34858,23 @@ 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 */;
+--
+-- Temporary table structure for view `preparationException`
+--
+
+DROP TABLE IF EXISTS `preparationException`;
+/*!50001 DROP VIEW IF EXISTS `preparationException`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `preparationException` AS SELECT
+ 1 AS `exceptionDay`,
+ 1 AS `warehouseFk`,
+ 1 AS `percentage` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `priceFixed`
--
@@ -34743,58 +34905,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`
@@ -34825,7 +34937,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 */;
--
@@ -34889,7 +35001,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 */;
--
@@ -34934,7 +35046,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 */;
--
@@ -34966,9 +35078,13 @@ CREATE TABLE `productionConfig` (
`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',
PRIMARY KEY (`id`),
KEY `productionConfig_FK` (`shortageAddressFk`),
- CONSTRAINT `productionConfig_FK` FOREIGN KEY (`shortageAddressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE
+ KEY `productionConfig_FK_1` (`clientSelfConsumptionFk`),
+ 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
) 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 */;
@@ -34994,7 +35110,7 @@ CREATE TABLE `productionError` (
`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;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35040,7 +35156,7 @@ CREATE TABLE `professionalCategory` (
`dayBreak` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `prefessionalCategory_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 */;
--
@@ -35054,7 +35170,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 */;
--
@@ -35086,7 +35202,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 */;
--
@@ -35107,34 +35223,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`
@@ -35150,6 +35240,20 @@ CREATE TABLE `projectState` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Temporary table structure for view `promissoryNote`
+--
+
+DROP TABLE IF EXISTS `promissoryNote`;
+/*!50001 DROP VIEW IF EXISTS `promissoryNote`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `promissoryNote` AS SELECT
+ 1 AS `id`,
+ 1 AS `Concept`,
+ 1 AS `paymentFk` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `property`
--
@@ -35191,7 +35295,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 */;
--
@@ -35210,7 +35314,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 */;
--
@@ -35224,7 +35328,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 */;
--
@@ -35245,7 +35349,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 */;
--
@@ -35273,107 +35377,8 @@ CREATE TABLE `province` (
CONSTRAINT `province_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `province_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `vn2008`.`zones` (`zone_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `warehouse_Id` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=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`
@@ -35439,72 +35444,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`
@@ -35548,7 +35489,7 @@ CREATE TABLE `rateLog` (
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=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -35580,122 +35521,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`
@@ -35720,7 +35547,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 */;
--
@@ -35741,7 +35568,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 */;
--
@@ -35765,72 +35592,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`
@@ -35893,7 +35656,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 */;
--
@@ -35909,7 +35672,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 */;
--
@@ -35955,6 +35718,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`
--
@@ -35965,6 +35745,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,
@@ -36001,172 +35782,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`
@@ -36181,7 +35798,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 */;
--
@@ -36195,6 +35812,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,
@@ -36205,9 +35823,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 */;
--
@@ -36228,7 +35847,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 */;
--
@@ -36334,7 +35953,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,
@@ -36345,7 +35964,7 @@ CREATE TABLE `routeLog` (
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 */;
--
@@ -36377,7 +35996,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 */;
--
@@ -36408,9 +36027,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`
--
@@ -36436,13 +36073,18 @@ 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 */;
@@ -36478,313 +36120,8 @@ CREATE TABLE `sale` (
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();
- SET NEW.originalQuantity = 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 `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`
@@ -36804,53 +36141,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`
@@ -36925,7 +36215,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 */;
--
@@ -36938,11 +36228,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 */;
--
@@ -36961,7 +36261,7 @@ CREATE TABLE `saleGroupDetail` (
UNIQUE KEY `saleGroupDetail_UN` (`saleFk`),
KEY `saleGroupDetail_FK_1` (`saleGroupFk`),
CONSTRAINT `saleGroupDetail_ibfk_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=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 */;
--
@@ -36999,7 +36299,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 */;
--
@@ -37095,37 +36395,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`
@@ -37300,7 +36571,7 @@ CREATE TABLE `salespersonConfig` (
`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 */;
--
@@ -37320,7 +36591,7 @@ 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 */;
--
@@ -37337,7 +36608,7 @@ CREATE TABLE `scanner` (
PRIMARY KEY (`id`),
KEY `scanner_FK` (`modelFk`),
CONSTRAINT `scanner_FK` FOREIGN KEY (`modelFk`) REFERENCES `scannerModel` (`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 */;
--
@@ -37367,7 +36638,7 @@ CREATE TABLE `screen` (
PRIMARY KEY (`id`),
KEY `screen_FK` (`modelFk`),
CONSTRAINT `screen_FK` FOREIGN KEY (`modelFk`) REFERENCES `screenModel` (`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 */;
--
@@ -37394,9 +36665,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,
@@ -37406,16 +36675,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,
+ `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`),
+ 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 */;
--
@@ -37435,7 +36707,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 */;
--
@@ -37456,7 +36728,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 */;
--
@@ -37479,7 +36751,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,
+ `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 */;
--
@@ -37494,7 +36780,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 */;
--
@@ -37525,7 +36811,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 */;
--
@@ -37549,89 +36835,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`
@@ -37651,7 +36854,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 */;
--
@@ -37674,48 +36877,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`
@@ -37744,85 +36905,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;
-
- IF NOT(OLD.parkingFk <=> NEW.parkingFK) THEN
- SET NEW.isMoving = 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`.`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`
@@ -37849,7 +36933,7 @@ CREATE TABLE `shelvingLog` (
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 */;
--
@@ -37926,7 +37010,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 */;
--
@@ -38020,7 +37104,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 */;
--
@@ -38036,7 +37120,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 */;
--
@@ -38056,82 +37140,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`
@@ -38174,7 +37182,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 */;
--
@@ -38195,7 +37203,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 */;
--
@@ -38210,48 +37218,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`
@@ -38273,7 +37241,7 @@ 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 */;
--
@@ -38295,7 +37263,7 @@ 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 */;
--
@@ -38315,7 +37283,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 */;
--
@@ -38349,7 +37317,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 */;
--
@@ -38387,7 +37355,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 */;
--
@@ -38431,7 +37399,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,
@@ -38472,108 +37440,8 @@ CREATE TABLE `supplier` (
CONSTRAINT `supplier_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `suppplier_supplierActivityFk` FOREIGN KEY (`supplierActivityFk`) REFERENCES `supplierActivity` (`code`) ON UPDATE CASCADE,
CONSTRAINT `supplierAccountTooShort` CHECK (octet_length(`account`) = 10)
-) ENGINE=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`.`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`
@@ -38594,80 +37462,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`
@@ -38710,70 +37518,6 @@ CREATE TABLE `supplierAddress` (
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`
@@ -38820,72 +37564,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`
@@ -38930,7 +37610,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 */;
--
@@ -38958,7 +37638,7 @@ CREATE TABLE `supplierLog` (
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;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -39035,30 +37715,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`
@@ -39133,7 +37791,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 */;
--
@@ -39182,7 +37840,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 */;
--
@@ -39204,7 +37862,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 */;
--
@@ -39303,249 +37961,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 NOT (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 NOT (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 NOT (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 NOT (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`
@@ -39574,48 +37991,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`
@@ -39632,7 +38009,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 */;
--
@@ -39654,98 +38031,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`
@@ -39779,9 +38064,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`
--
@@ -39855,7 +38156,7 @@ CREATE TABLE `ticketLog` (
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- `changedModel` enum('Ticket','Sale','TicketWeekly','TicketTracking','TicketService','TicketRequest','TicketRefund','TicketPackaging','TicketObservation','TicketDms','Expedition','Sms') NOT NULL DEFAULT 'Ticket',
+ `changedModel` enum('Ticket','Sale','TicketWeekly','TicketTracking','TicketService','TicketRequest','TicketRefund','TicketPackaging','TicketObservation','TicketDms','Expedition','Sms','SaleGroup') NOT NULL DEFAULT 'Ticket',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
@@ -39866,7 +38167,7 @@ CREATE TABLE `ticketLog` (
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 */;
--
@@ -39933,72 +38234,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`
@@ -40040,74 +38277,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`
@@ -40172,30 +38343,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`
@@ -40229,7 +38378,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 */;
--
@@ -40251,74 +38400,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`
@@ -40364,96 +38447,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`
@@ -40480,122 +38475,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`
@@ -40609,19 +38490,19 @@ CREATE TABLE `ticketServiceType` (
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`expenseFk` varchar(10) NOT NULL DEFAULT '7050000000',
PRIMARY KEY (`id`),
- KEY `ticketServiceType_expenseFk_idx` (`expenseFk`),
- CONSTRAINT `ticketServiceType_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`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`),
@@ -40642,14 +38523,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;
@@ -40673,6 +38552,35 @@ SET character_set_client = utf8;
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`
--
@@ -40687,11 +38595,11 @@ CREATE TABLE `ticketTracking` (
`notes` varchar(255) DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
`ticketFk` int(11) DEFAULT NULL,
- `workerFk` int(10) unsigned 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`),
@@ -40700,172 +38608,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 (`workerFk`) REFERENCES `account`.`user` (`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__`
@@ -40878,7 +38625,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 */;
--
@@ -40908,7 +38655,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 */;
--
@@ -40929,72 +38676,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`
@@ -41034,7 +38746,7 @@ 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 */;
--
@@ -41077,31 +38789,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`
@@ -41116,7 +38803,7 @@ CREATE TABLE `timeControlDevice` (
`key` varchar(255) DEFAULT 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 */;
--
@@ -41135,99 +38822,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`
@@ -41301,7 +38897,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 */;
--
@@ -41315,7 +38911,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 */;
--
@@ -41344,7 +38940,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 */;
--
@@ -41358,7 +38954,7 @@ 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 */;
--
@@ -41374,7 +38970,7 @@ CREATE TABLE `transitoryDuaUnified` (
PRIMARY KEY (`id`),
KEY `transitoryDuaUnified_FK` (`supplierFk`),
CONSTRAINT `transitoryDuaUnified_FK` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Transitarios que al contabilizar sus entradas sólo generan un único DUA para todos los proveedores';
+) 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 */;
--
@@ -41392,7 +38988,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,
@@ -41404,9 +39000,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`),
@@ -41414,146 +39011,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.shipped <=> OLD.shipped )
- OR (NOT NEW.landed <=> OLD.landed )
- OR (NOT NEW.warehouseInFk <=> OLD.warehouseInFk )
- OR (NOT NEW.warehouseOutFk <=> OLD.warehouseOutFk ))
- AND (OLD.totalEntries AND OLD.landed < CURDATE()) THEN
- CALL util.throw("Cannot past travels with entries");
- END IF;
-
- 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;
-
- IF NOT (NEW.warehouseInFk <=> OLD.warehouseInFk) THEN
- CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk);
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @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`
@@ -41586,7 +39051,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 */;
--
@@ -41639,7 +39104,7 @@ CREATE TABLE `travelLog` (
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 */;
--
@@ -41656,7 +39121,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 */;
--
@@ -41702,72 +39167,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`
@@ -41783,9 +39184,78 @@ 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 */;
+--
+-- Temporary table structure for view `unary`
+--
+
+DROP TABLE IF EXISTS `unary`;
+/*!50001 DROP VIEW IF EXISTS `unary`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `unary` AS SELECT
+ 1 AS `id`,
+ 1 AS `parent` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `unaryScan`
+--
+
+DROP TABLE IF EXISTS `unaryScan`;
+/*!50001 DROP VIEW IF EXISTS `unaryScan`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `unaryScan` AS SELECT
+ 1 AS `unaryFk`,
+ 1 AS `name`,
+ 1 AS `created`,
+ 1 AS `type` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `unaryScanLine`
+--
+
+DROP TABLE IF EXISTS `unaryScanLine`;
+/*!50001 DROP VIEW IF EXISTS `unaryScanLine`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `unaryScanLine` AS SELECT
+ 1 AS `id`,
+ 1 AS `code`,
+ 1 AS `created`,
+ 1 AS `unaryScanFk` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `unaryScanLineBuy`
+--
+
+DROP TABLE IF EXISTS `unaryScanLineBuy`;
+/*!50001 DROP VIEW IF EXISTS `unaryScanLineBuy`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `unaryScanLineBuy` AS SELECT
+ 1 AS `unaryScanLineFk`,
+ 1 AS `itemFk` */;
+SET character_set_client = @saved_cs_client;
+
+--
+-- Temporary table structure for view `unaryScanLineExpedition`
+--
+
+DROP TABLE IF EXISTS `unaryScanLineExpedition`;
+/*!50001 DROP VIEW IF EXISTS `unaryScanLineExpedition`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `unaryScanLineExpedition` AS SELECT
+ 1 AS `unaryScanLineFk`,
+ 1 AS `expeditionFk` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `userConfig`
--
@@ -41800,7 +39270,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 */;
@@ -41902,48 +39375,8 @@ CREATE TABLE `vehicle` (
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;
+) 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`
@@ -41973,7 +39406,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 */;
--
@@ -41997,7 +39430,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 */;
--
@@ -42017,7 +39450,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 */;
--
@@ -42038,7 +39471,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 */;
--
@@ -42067,7 +39500,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 */;
--
@@ -42085,8 +39518,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 */;
--
@@ -42162,7 +39598,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 */;
--
@@ -42219,7 +39655,7 @@ CREATE TABLE `wagonVolumetry` (
PRIMARY KEY (`id`),
KEY `wagonVolumetry_FK_1` (`wagonFk`),
CONSTRAINT `wagonVolumetry_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`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 */;
--
@@ -42272,54 +39708,8 @@ CREATE TABLE `warehouse` (
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;
+) 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`
@@ -42333,9 +39723,22 @@ CREATE TABLE `warehouseAlias` (
`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;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Temporary table structure for view `warehouseJoined`
+--
+
+DROP TABLE IF EXISTS `warehouseJoined`;
+/*!50001 DROP VIEW IF EXISTS `warehouseJoined`*/;
+SET @saved_cs_client = @@character_set_client;
+SET character_set_client = utf8;
+/*!50001 CREATE VIEW `warehouseJoined` AS SELECT
+ 1 AS `warehouseFk`,
+ 1 AS `warehouseAliasFk` */;
+SET character_set_client = @saved_cs_client;
+
--
-- Table structure for table `workCenter`
--
@@ -42427,72 +39830,8 @@ CREATE TABLE `worker` (
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 */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @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`
@@ -42526,7 +39865,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 */;
--
@@ -42544,7 +39883,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 */;
--
@@ -42616,7 +39955,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 */;
--
@@ -42661,7 +40000,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 */;
--
@@ -42684,72 +40023,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`
@@ -42763,7 +40038,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 */;
--
@@ -42780,7 +40055,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 */;
--
@@ -42803,70 +40078,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`
@@ -42928,7 +40141,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 */;
--
@@ -42974,7 +40187,7 @@ CREATE TABLE `workerLog` (
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;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -43040,7 +40253,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 */;
--
@@ -43100,7 +40313,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 */;
--
@@ -43123,7 +40336,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 */;
--
@@ -43179,7 +40392,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 */;
--
@@ -43217,30 +40430,8 @@ CREATE TABLE `workerTimeControl` (
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`
@@ -43278,7 +40469,7 @@ CREATE TABLE `workerTimeControlConfig` (
`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 */;
--
@@ -43294,7 +40485,7 @@ CREATE TABLE `workerTimeControlError` (
`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 */;
--
@@ -43333,7 +40524,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 */;
--
@@ -43359,7 +40550,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 */;
--
@@ -43389,7 +40580,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 */;
--
@@ -43457,30 +40648,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`
@@ -43509,7 +40678,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,
@@ -43523,72 +40692,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`
@@ -43606,7 +40711,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 */;
--
@@ -43636,7 +40741,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 */;
--
@@ -43649,13 +40754,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;
--
@@ -43684,72 +40788,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`
@@ -43771,76 +40811,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`
@@ -43858,7 +40830,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 */;
--
@@ -43878,7 +40850,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 */;
--
@@ -43903,50 +40875,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`
@@ -43959,7 +40889,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 */;
--
@@ -43982,72 +40912,8 @@ CREATE TABLE `zoneIncluded` (
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=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`.`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 = 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`.`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`
@@ -44093,7 +40959,7 @@ CREATE TABLE `zoneLog` (
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 */;
--
@@ -44115,72 +40981,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'
@@ -44198,7 +41000,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
@@ -44209,8 +41011,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 */ ;;
@@ -44230,7 +41032,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 */ ;;
@@ -44248,7 +41050,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 */ ;;
@@ -44266,7 +41068,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 */ ;;
@@ -44284,7 +41086,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;
@@ -44330,7 +41132,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 `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 */ ;;
@@ -44341,16 +41143,16 @@ 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 `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO BEGIN
- DELETE FROM itemImageQueue
- WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig);
+/*!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 */ ;;
@@ -44369,7 +41171,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 */ ;;
@@ -44387,7 +41189,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;
@@ -44496,7 +41298,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 */ ;;
+/*!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 */ ;;
@@ -44507,14 +41309,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 `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 `sale_checkWithoutComponents` ON SCHEDULE EVERY 10 MINUTE STARTS '2020-05-04 11:56:23' ON COMPLETION PRESERVE ENABLE DO call sale_checkNoComponents(DATE_ADD(util.VN_NOW(), INTERVAL -10 MINUTE),DATE_ADD(util.VN_NOW(), INTERVAL -1 MINUTE)) */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
@@ -44532,7 +41334,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 */ ;;
@@ -44550,7 +41352,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 */ ;;
@@ -44568,7 +41370,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 */ ;;
@@ -44586,7 +41388,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 */ ;;
@@ -44604,7 +41406,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 `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 */ ;;
@@ -44622,7 +41424,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=`salix`@`10.0.%.%`*/ /*!50106 EVENT `zoneClosure_doRecalc` ON SCHEDULE AT '2023-11-13 07:15:54' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO CALL zoneClosure_recalc */ ;;
+/*!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 */ ;;
@@ -44640,7 +41442,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 */ ;;
@@ -44715,7 +41517,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
@@ -44742,12 +41544,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
*/
@@ -44757,35 +41559,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 */ ;
@@ -44849,7 +41651,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;
@@ -44878,16 +41680,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;
@@ -44896,11 +41698,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;
@@ -44924,7 +41726,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
@@ -44933,7 +41735,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;
@@ -44950,7 +41752,7 @@ BEGIN
ROUND(
vM3
* (z.price - z.bonus)
- * z.inflation
+ * z.inflation
/ vBoxVolume, 4
)
FROM zone z
@@ -45044,7 +41846,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
@@ -45077,37 +41879,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;
-
- DROP TEMPORARY TABLE
- tmp.clientGetDebt,
- 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 */ ;
@@ -45183,8 +41985,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
@@ -45222,29 +42024,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;
@@ -45278,11 +42080,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 ;
@@ -45313,12 +42115,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;
@@ -45351,11 +42153,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 ;
@@ -45365,6 +42167,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 */ ;
@@ -45447,7 +42281,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
@@ -45478,23 +42312,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;
@@ -45519,7 +42353,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDuaFk INT, vTaxClas
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
*/
@@ -45553,24 +42387,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 +
@@ -45581,7 +42415,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
@@ -45596,13 +42430,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;
@@ -45636,7 +42470,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;
@@ -45697,36 +42531,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
@@ -45735,11 +42569,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 */ ;
@@ -45790,10 +42624,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
*/
@@ -45801,51 +42635,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 */ ;
@@ -45878,21 +42712,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);
@@ -45957,17 +42791,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 ;;
@@ -46028,27 +42862,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
@@ -46078,28 +42912,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
@@ -46153,8 +42987,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 */ ;
@@ -46207,16 +43041,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
@@ -46224,7 +43058,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 ;
@@ -46246,11 +43080,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;
@@ -46265,11 +43099,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 ;
@@ -46294,12 +43128,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 ;;
@@ -46323,7 +43157,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;
@@ -46390,48 +43224,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 */ ;
@@ -46453,17 +43322,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 */ ;
@@ -46486,7 +43355,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
@@ -46495,9 +43364,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
@@ -46527,12 +43396,12 @@ 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 invoiceOutExpense ioe
JOIN invoiceOut io ON io.id = ioe.invoiceOutFk
@@ -46563,23 +43432,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;
@@ -46605,7 +43474,7 @@ BEGIN
DECLARE vIssued DATE;
DECLARE vSerial VARCHAR(15);
- SELECT issued, ref
+ SELECT issued, ref
INTO vIssued, vSerial
FROM invoiceOut WHERE id = vSelf;
@@ -46677,9 +43546,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"]
@@ -46760,18 +43629,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 */ ;
@@ -46808,7 +43677,7 @@ BEGIN
WHERE sl.scan_id = vScanId
AND t.Id_Ruta
) t1;
-
+
RETURN vDistinctRoutesInThePallet = 1;
END ;;
DELIMITER ;
@@ -46832,20 +43701,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
@@ -46858,11 +43727,11 @@ BEGIN
) packings
ORDER BY created desc
LIMIT 1;
-
+
END IF;
-
+
RETURN vPacking;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46887,11 +43756,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
(
@@ -46901,12 +43770,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 */ ;
@@ -46928,17 +43797,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 */ ;
@@ -47011,29 +43880,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 */ ;
@@ -47070,7 +43939,7 @@ BEGIN
FROM packaging p
JOIN item i ON i.id = vSelf
WHERE p.id = vPackaging;
-
+
RETURN vVolume;
END ;;
@@ -47091,7 +43960,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
*
@@ -47130,16 +43999,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;
@@ -47166,9 +44035,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 ;
@@ -47195,9 +44064,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;
@@ -47218,7 +44087,7 @@ BEGIN
IF vCount = 0 THEN
RETURN vCount;
- END IF;
+ END IF;
SET vUuid = UUID();
@@ -47229,7 +44098,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;
@@ -47303,7 +44172,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
@@ -47380,7 +44249,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);
@@ -47441,20 +44310,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
@@ -47462,16 +44331,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
@@ -47483,7 +44352,7 @@ BEGIN
ORDER BY zoneFriendship DESC, friendshipSum DESC
) sub
LIMIT 1;
-
+
RETURN vRouteFk;
END ;;
DELIMITER ;
@@ -47508,9 +44377,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
@@ -47524,7 +44393,7 @@ BEGIN
ORDER BY friendshipSum DESC
) sub
LIMIT 1;
-
+
RETURN vRouteFk;
END ;;
DELIMITER ;
@@ -47548,20 +44417,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
@@ -47569,16 +44438,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
@@ -47590,7 +44459,7 @@ BEGIN
ORDER BY zoneFriendship DESC, friendshipSum DESC
) sub
LIMIT 1;
-
+
RETURN vRouteFk;
END ;;
DELIMITER ;
@@ -47611,26 +44480,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 */ ;
@@ -47650,7 +44519,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);
@@ -47662,60 +44531,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 */ ;
@@ -47735,7 +44604,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);
@@ -47744,45 +44613,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 */ ;
@@ -47807,23 +44676,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 */ ;
@@ -47843,21 +44712,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;
@@ -47903,9 +44772,9 @@ BEGIN
DROP TEMPORARY TABLE
tmp.ticket,
tmp.ticketTotal;
-
+
RETURN vTotal;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47925,7 +44794,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;
@@ -47937,7 +44806,7 @@ BEGIN
DECLARE vExpeditionsCount INT;
DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE;
-SELECT `order`
+SELECT `order`
INTO PACKING_ORDER
FROM state
WHERE code = 'PACKING';
@@ -47945,10 +44814,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
@@ -47962,19 +44831,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
@@ -48026,9 +44895,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 */ ;
@@ -48077,21 +44946,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 ;;
@@ -48116,7 +44985,7 @@ BEGIN
DECLARE vWarehouseFk INT;
SELECT warehouseFk INTO vWarehouseFk
- FROM ticket
+ FROM ticket
WHERE id = vTicketFk;
RETURN vWarehouseFk;
@@ -48139,18 +45008,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 ;;
@@ -48172,44 +45041,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
@@ -48217,17 +45086,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 */ ;
@@ -48253,8 +45122,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
@@ -48265,7 +45134,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 ;;
@@ -48289,16 +45158,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 ;;
@@ -48320,15 +45189,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 ;;
@@ -48477,7 +45346,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'
@@ -48490,40 +45359,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
@@ -48577,11 +45446,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
*/
@@ -48589,8 +45458,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
@@ -48601,14 +45470,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
@@ -48616,11 +45485,11 @@ BEGIN
AND wOut.name = 'Holanda'
AND landed = vLanded;
END IF;
-
+
END IF;
-
+
RETURN vTravelFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48647,21 +45516,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 */ ;
@@ -48688,21 +45557,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 */ ;
@@ -48763,15 +45632,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;
@@ -48803,47 +45672,47 @@ BEGIN
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
+ 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
+
+ SELECT COUNT(*) INTO vHasDirectionOut
FROM workerTimeControl wtc
- WHERE userFk = vUserFk
+ WHERE userFk = vUserFk
AND direction = 'out'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
+ 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);
+ 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 ;
@@ -48872,47 +45741,47 @@ BEGIN
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
+ 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
+
+ SELECT COUNT(*) INTO vHasDirectionOut
FROM workerTimeControl wtc
- WHERE userFk = vUserFk
+ WHERE userFk = vUserFk
AND direction = 'out'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
+ 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);
+ 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 ;
@@ -49006,6 +45875,45 @@ 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 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_general_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 */ ;
@@ -49023,17 +45931,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;
@@ -49127,7 +46035,7 @@ BEGIN
SET `type` = vType,
`name` = vName,
parentFk = vParentFk;
-
+
SET vSelf = LAST_INSERT_ID();
UPDATE zoneGeoRecalc SET isChanged = TRUE;
@@ -49151,7 +46059,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)
@@ -49179,23 +46087,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'
@@ -49236,27 +46144,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 ;
@@ -49307,7 +46215,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 */ ;
@@ -49330,14 +46238,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
@@ -49361,13 +46269,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
@@ -49396,7 +46304,7 @@ BEGIN
END WHILE;
CLOSE vCur;
-
+
SELECT * FROM tmp.agencyModeWarehouseList;
DROP TEMPORARY TABLE tmp.agencyModeWarehouseList;
END ;;
@@ -49422,9 +46330,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 */ ;
@@ -49462,7 +46370,7 @@ BEGIN
DECLARE cWarehouses CURSOR FOR
SELECT warehouseFk, shipped FROM tmp.zoneGetShipped;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
@@ -49471,7 +46379,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)
)
@@ -49482,7 +46390,7 @@ BEGIN
l: LOOP
SET vDone = FALSE;
FETCH cWarehouses INTO vWarehouse, vShipment;
-
+
IF vDone THEN
LEAVE l;
END IF;
@@ -49515,7 +46423,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `bankEntity_checkBic`(vBic VARCHAR(2
BEGIN
/**
* If the bic length is Incorrect throw exception
- *
+ *
* @param vBic bic code
*/
@@ -49523,7 +46431,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;
@@ -49550,14 +46458,14 @@ 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
+ FROM vn.bankPolicy bp
+ LEFT JOIN vn.supplier s
ON s.id = bp.supplierFk
LEFT JOIN vn.bank b
ON b.id = bp.bankFk
@@ -49604,13 +46512,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 */ ;
@@ -49654,11 +46565,13 @@ 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
@@ -49670,12 +46583,13 @@ BEGIN
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
@@ -49685,12 +46599,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
@@ -49699,17 +46614,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
@@ -49723,12 +46640,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
@@ -49739,12 +46657,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
@@ -49786,19 +46705,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
@@ -49806,7 +46725,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.packagingFk 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;
@@ -49823,7 +46742,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
@@ -49844,7 +46763,7 @@ BEGIN
WHERE b.id = vSelf;
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -49891,10 +46810,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
*/
@@ -49969,7 +46888,7 @@ BEGIN
WHILE vLabels >= vCounter DO
INSERT INTO tmp.split
SET
- id = vSaleFk,
+ id = vSaleFk,
labels = vLabels,
counter = vCounter;
@@ -49991,11 +46910,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
@@ -50040,12 +46959,12 @@ BEGIN
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
+ 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 ;
@@ -50065,21 +46984,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 */ ;
@@ -50098,19 +47017,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 */ ;
@@ -50118,14 +47037,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 = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_recalcPrices` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = 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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_recalcPrices`()
BEGIN
@@ -50137,7 +47056,7 @@ BEGIN
DECLARE vLanded DATE;
DECLARE vWarehouseFk INT;
DECLARE vHasNotPrice BOOL;
- DECLARE vBuyingValue DECIMAL(10,3);
+ DECLARE vBuyingValue DECIMAL(10,4);
DECLARE vPackagingFk VARCHAR(10);
DECLARE vIsWarehouseFloramondo BOOL;
@@ -50198,16 +47117,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();
@@ -50235,7 +47153,7 @@ BEGIN
* Recalcula los precios de una compra
*
* @param vBuyFk
- */
+ */
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
@@ -50266,12 +47184,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();
@@ -50311,12 +47229,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
@@ -50382,7 +47300,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
@@ -50392,8 +47310,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;
@@ -50432,7 +47350,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);
@@ -50454,7 +47372,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
*
@@ -50462,7 +47380,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
@@ -50497,22 +47415,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
@@ -50534,20 +47452,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)
@@ -50564,13 +47482,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
@@ -50663,7 +47581,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)
@@ -50677,7 +47595,7 @@ BEGIN
SELECT clientFk INTO vClientFK
FROM address
WHERE id = vAddressFk;
-
+
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate
(PRIMARY KEY (itemFk, warehouseFk))
ENGINE = MEMORY
@@ -50689,7 +47607,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
@@ -50697,7 +47615,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 (
@@ -50716,7 +47634,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
@@ -50748,10 +47666,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),
@@ -50782,29 +47700,29 @@ BEGIN
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,
@@ -50815,10 +47733,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
@@ -50830,7 +47748,7 @@ BEGIN
SELECT vZoneFk id;
CALL zone_getOptionsForShipment(vShipped, TRUE);
-
+
-- Reparto
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFK,
@@ -50844,7 +47762,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;
@@ -50897,9 +47815,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;
@@ -50936,7 +47854,7 @@ BEGIN
SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000
) t
GROUP BY itemFk, warehouseFk, `grouping`;
-
+
DROP TEMPORARY TABLE
tmp.ticketComponentCalculate,
tmp.ticketComponentSum,
@@ -50961,7 +47879,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,
@@ -50971,9 +47889,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,
@@ -50982,7 +47900,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 */ ;
@@ -51001,7 +47919,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPurge`()
BEGIN
- DROP TEMPORARY TABLE
+ DROP TEMPORARY TABLE
tmp.ticketComponentPrice,
tmp.ticketComponent,
tmp.ticketLot;
@@ -51056,7 +47974,7 @@ BEGIN
DELETE FROM sms WHERE created < v18Month;
DELETE FROM saleTracking WHERE created < vOneYearAgo;
DELETE FROM ticketTracking WHERE created < v18Month;
- DELETE tobs FROM ticketObservation tobs
+ 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;
@@ -51135,12 +48053,12 @@ BEGIN
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
+ 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
@@ -51159,7 +48077,7 @@ BEGIN
CREATE TEMPORARY TABLE tmp.routeToDelete
SELECT *
FROM vn.route r
- WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE());
+ WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE());
UPDATE tmp.routeToDelete tmp
JOIN vn.dms d ON d.id = tmp.gestdocFk
@@ -51342,21 +48260,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 ;;
@@ -51447,33 +48365,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;
@@ -51485,66 +48403,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 ;
@@ -51602,13 +48520,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
@@ -51620,7 +48538,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;
@@ -51631,7 +48549,7 @@ BEGIN
SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk;
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -51826,11 +48744,11 @@ BEGIN
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.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;
@@ -51941,7 +48859,7 @@ BEGIN
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
@@ -52218,9 +49136,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,
@@ -52228,40 +49146,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
@@ -52303,9 +49221,9 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
CREATE OR REPLACE TEMPORARY TABLE tClientList
- SELECT c.clientFk
+ 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
@@ -52413,9 +49331,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
@@ -52436,8 +49352,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,
@@ -52451,8 +49366,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,
@@ -52473,9 +49387,9 @@ BEGIN
ish.created,
ish.visible,
IFNULL(
- IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`),
+ IF(st.description = 'previousByPacking', ish.packing, g.`grouping`),
1) `grouping`,
- sc.isPreviousPrepared,
+ st.description = 'previousPrepared' isPreviousPrepared,
iss.id itemShelvingSaleFk,
ts.ticketFk,
iss.id,
@@ -52492,6 +49406,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
@@ -52504,8 +49419,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
@@ -52591,15 +49505,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;
@@ -52635,75 +49549,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 */ ;
@@ -52734,18 +49664,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);
@@ -52772,15 +49702,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,
@@ -52790,20 +49720,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,
@@ -52813,15 +49743,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;
@@ -52961,6 +49891,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;
@@ -52976,12 +49910,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,
@@ -52993,32 +49926,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;
@@ -53074,16 +50009,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
@@ -53092,23 +50027,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,
@@ -53120,90 +50064,103 @@ 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 `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;
@@ -53215,7 +50172,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
@@ -53226,24 +50182,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);
@@ -53353,7 +50308,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;
@@ -53400,25 +50355,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 ;
@@ -53475,7 +50430,7 @@ BEGIN
IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount,
p.dueDated < vStartingDate isBeforeStarting,
p.currencyFk
- FROM payment p
+ FROM payment p
WHERE p.received > vStartDate
AND p.companyFk = vSelf
UNION ALL
@@ -53483,9 +50438,9 @@ BEGIN
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
+ 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
@@ -53537,11 +50492,11 @@ 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)
@@ -53596,7 +50551,7 @@ BEGIN
FROM tPendingDuedates
WHERE balance < vInvalidBalances
AND balance > - vInvalidBalances;
-
+
DELETE vp.*
FROM tPendingDuedates vp
JOIN tRowsToDelete rd ON (
@@ -53624,9 +50579,9 @@ BEGIN
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 clientRisk cr ON cr.clientFk = c.id
AND cr.companyFk = vp.companyFk;
-
+
DROP TEMPORARY TABLE tOpeningBalances;
DROP TEMPORARY TABLE tPendingDuedates;
DROP TEMPORARY TABLE tRowsToDelete;
@@ -53638,6 +50593,79 @@ 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 `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 clientType ct ON ct.id = c.clientTypeFk
+ 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 ct.code <> '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 `conveyorExpedition_Add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -53649,7 +50677,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME)
BEGIN
-
+
DECLARE startingMinute INT;
TRUNCATE vn.conveyorExpedition;
@@ -53666,23 +50694,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
@@ -53691,8 +50719,8 @@ BEGIN
SELECT MIN(productionMinute) INTO startingMinute
FROM vn.conveyorExpedition ce ;
-
- UPDATE vn.conveyorExpedition
+
+ UPDATE vn.conveyorExpedition
SET productionMinute = productionMinute - startingMinute;
END ;;
@@ -53761,7 +50789,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `createPedidoInterno`(vItemFk INT,vQuantity INT)
BEGIN
-
+
UPDATE vn.item SET upToDown = vQuantity WHERE id = vItemFk;
END ;;
@@ -53784,52 +50812,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);
@@ -53854,49 +50882,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;
@@ -53992,7 +51020,7 @@ BEGIN
OR (vSelf IS NOT NULL AND parentFk = vSelf);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
SET vSons = 0;
OPEN vChildren;
@@ -54003,11 +51031,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, '/'),
@@ -54062,7 +51090,7 @@ proc: BEGIN
SELECT isChanged INTO vIsChanged
FROM department_recalc;
-
+
IF vIsChanged THEN
UPDATE department_recalc SET isChanged = FALSE;
CALL vn.department_calcTree;
@@ -54087,17 +51115,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 */ ;
@@ -54156,19 +51184,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;
@@ -54235,12 +51263,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 */ ;
@@ -54312,10 +51340,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
*/
@@ -54327,20 +51355,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;
@@ -54370,15 +51398,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
@@ -54386,11 +51414,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 */ ;
@@ -54414,7 +51442,7 @@ BEGIN
DECLARE vInvoiceFk INT;
DECLARE vASIEN BIGINT DEFAULT 0;
DECLARE vCounter INT DEFAULT 0;
-
+
DECLARE rs CURSOR FOR
SELECT e.invoiceInFk
FROM entry e
@@ -54427,7 +51455,7 @@ BEGIN
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
@@ -54439,41 +51467,41 @@ BEGIN
ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried),
e.isConfirmed = TRUE
WHERE d.id = vDuaFk;
-
+
SELECT IFNULL(ASIEN,0) INTO vASIEN
FROM dua
WHERE id = vDuaFk;
-
+
FETCH rs INTO vInvoiceFk;
-
+
WHILE NOT done DO
CALL invoiceIn_booking(vInvoiceFk);
-
+
IF vCounter > 0 OR vASIEN > 0 THEN
-
+
UPDATE vn2008.XDiario x
JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN
SET x.ASIEN = vASIEN;
-
+
ELSE
-
+
SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig;
-
+
END IF;
-
+
SET vCounter = vCounter + 1;
-
+
FETCH rs INTO vInvoiceFk;
END WHILE;
-
+
CLOSE rs;
-
- UPDATE dua
+
+ UPDATE dua
SET ASIEN = vASIEN
WHERE id = vDuaFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -54495,18 +51523,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 ;
@@ -54530,11 +51558,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;
@@ -54545,14 +51573,14 @@ BEGIN
ASIEN,
FECHA,
SUBCTA,
- CONCEPTO,
+ CONCEPTO,
EUROHABER,
SERIE,
empresa_id,
CLAVE,
FACTURA)
- SELECT
+ SELECT
vBookNumber,
d.bookEntried,
'4700000999',
@@ -54565,20 +51593,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,
@@ -54598,17 +51626,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,
@@ -54635,10 +51663,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
@@ -54647,16 +51675,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 */ ;
@@ -54677,36 +51705,36 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTax_doRecalc`(vDuaFk INT)
BEGIN
/**
* Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry
- *
+ *
* @param vDuaFk Id del dua a recalcular
*/
DELETE FROM duaTax
WHERE duaFk = vDuaFk;
-
- INSERT INTO duaTax(duaFk, taxClassFk, base)
+
+ 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 /
+ CAST(SUM(b.quantity *
+ b.buyingValue *
+ de.customsValue /
+ de.value)
+ * di.totalAmount /
bi.totalAmount AS DECIMAL(10,2)
) totalBase
- FROM buy b
+ 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 /
+ CAST(SUM(b.quantity *
+ b.buyingValue *
+ de.customsValue /
de.value) AS DECIMAL(10,2)
) totalAmount
- FROM buy b
+ 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
@@ -54721,7 +51749,7 @@ BEGIN
) di ON di.intrastatFk = i.intrastatFk
WHERE de.duaFk = vDuaFk
GROUP BY i.intrastatFk
- HAVING totalBase
+ HAVING totalBase
)sub ON ist.id = sub.intrastatFk
GROUP BY ist.taxClassFk;
END ;;
@@ -54742,13 +51770,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 ;
@@ -54788,71 +51816,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
@@ -54860,13 +51888,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;
@@ -54874,7 +51902,7 @@ OPEN cur1;
END LOOP;
CLOSE cur1;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -54894,18 +51922,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 ;;
@@ -54928,28 +51956,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 ;;
@@ -54975,29 +52003,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
@@ -55007,7 +52035,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,
@@ -55039,7 +52067,7 @@ 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;
@@ -55293,7 +52321,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55313,7 +52341,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55343,7 +52371,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
@@ -55353,7 +52381,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;
@@ -55460,7 +52488,7 @@ BEGIN
containerFk,
comissionValue,
packageValue,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55481,7 +52509,7 @@ BEGIN
containerFk,
comissionValue,
packageValue,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55492,7 +52520,7 @@ BEGIN
FROM buy b
WHERE b.entryFk = vSelf
AND b.printedStickers != b.stickers;
-
+
IF vChangeEntry THEN
UPDATE buy
SET stickers = printedStickers,
@@ -55504,7 +52532,7 @@ BEGIN
FROM item i
WHERE i.description = 'MISFIT'
LIMIT 1;
-
+
INSERT INTO buy(entryFk,
itemFk,
quantity,
@@ -55519,7 +52547,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55538,7 +52566,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55571,7 +52599,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 ;;
@@ -55645,12 +52673,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;
@@ -55661,7 +52689,7 @@ BEGIN
IF v_done THEN
LEAVE l;
END IF;
-
+
CALL vn2008.buy_tarifas_entry(vEntryFk);
END LOOP;
@@ -55686,7 +52714,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
@@ -55696,49 +52724,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
@@ -55746,9 +52774,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,
@@ -55763,7 +52791,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55790,7 +52818,7 @@ BEGIN
comissionValue,
packageValue,
location,
- packageFk,
+ packagingFk,
price1,
price2,
price3,
@@ -55828,16 +52856,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';
@@ -55846,17 +52874,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 */ ;
@@ -55879,7 +52907,7 @@ BEGIN
* Unlock the indicated entry
* @vSelf params entry id
*/
- UPDATE `entry`
+ UPDATE `entry`
SET lockerUserFk = NULL,
locked = NULL
WHERE id = vSelf;
@@ -55910,21 +52938,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();
@@ -55960,7 +52988,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;
@@ -56163,14 +53191,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;
@@ -56237,22 +53265,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 ;;
@@ -56325,12 +53353,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 */ ;
@@ -56349,32 +53377,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 */ ;
@@ -56406,7 +53434,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 ;;
@@ -56427,14 +53455,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
@@ -56460,7 +53488,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
*/
@@ -56477,7 +53505,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)
@@ -56502,21 +53530,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 */ ;
@@ -56558,8 +53586,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())
@@ -56603,7 +53631,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
@@ -56634,7 +53662,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_getState`(vExpeditionFk INT)
BEGIN
-
+
DECLARE vTicketsPendientes INT;
DECLARE vEtiquetasTotales INT;
DECLARE vEtiquetasEscaneadas INT;
@@ -56644,24 +53672,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,
@@ -56675,17 +53703,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 */ ;
@@ -56704,12 +53732,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;
@@ -56720,34 +53748,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,
@@ -56762,17 +53790,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 */ ;
@@ -56818,7 +53846,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControl`(vFromDated DATE, vToDated DATE)
BEGIN
-
+
DECLARE vSijsnerClientFk INT DEFAULT 19752;
DECLARE vDateStart DATETIME;
@@ -56827,68 +53855,68 @@ BEGIN
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,
+ 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.packagingFk) 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.packagingFk
+ 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.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
+ 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
+ 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
+ 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
+ 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 p.isPackageReturnable
AND c.country = 'FRANCIA'
AND t.clientFk != vSijsnerClientFk
- AND tp.quantity > 0) sub
+ 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
+ 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
+ AND p.isPackageReturnable
+ AND t.clientFk = vSijsnerClientFk) sub
GROUP BY FustCode) sj ON sj.FustCode = p.id
- WHERE sent.stucks
+ WHERE sent.stucks
OR tp.stucks
OR sj.stucks;
@@ -56910,7 +53938,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControlDetail`(vFromDated DATE, vToDated DATE)
BEGIN
-
+
DECLARE vSijsnerClientFk INT DEFAULT 19752;
DECLARE vDateStart DATETIME;
@@ -56918,29 +53946,29 @@ BEGIN
SET vDateStart = vFromDated;
SET vDateEnd = util.Dayend(vToDated);
-
+
SELECT a.nickname shopName,
- a.city ,
- IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode,
+ 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
+ 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
+ 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 p.isPackageReturnable
AND c.country = 'FRANCIA'
AND t.clientFk != vSijsnerClientFk
AND tp.quantity > 0;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -56966,8 +53994,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
@@ -56983,17 +54011,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,
@@ -57021,12 +54049,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)
@@ -57036,20 +54064,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;
@@ -57074,8 +54102,8 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `getDayExpeditions`()
BEGIN
- SELECT
- e.expeditions_id as expeditionFk,
+ SELECT
+ e.expeditions_id as expeditionFk,
date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate,
e.ticket_id as ticketFk,
t.routeFk as routeFk
@@ -57127,6 +54155,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 */ ;
@@ -57152,7 +54225,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
@@ -57270,8 +54343,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);
@@ -57282,13 +54355,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
@@ -57299,7 +54372,7 @@ WHILE NOT done DO
AND s.quantity > 0;
FETCH rs INTO vTicketFk;
-
+
END WHILE;
@@ -57442,7 +54515,7 @@ proc: BEGIN
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',
+ 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',
@@ -57640,7 +54713,7 @@ BEGIN
b.id AS buyFk,
b.entryFk,
b.isIgnored,
- b.price2,
+ b.price2,
b.price3,
b.stickers,
b.packing,
@@ -57654,20 +54727,20 @@ BEGIN
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.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,
@@ -57677,7 +54750,7 @@ BEGIN
b.id AS buyFk,
b.entryFk,
b.isIgnored,
- b.price2,
+ b.price2,
b.price3,
b.stickers,
b.packing,
@@ -57691,11 +54764,11 @@ BEGIN
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
@@ -57703,34 +54776,34 @@ BEGIN
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
+ 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.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;
@@ -57798,7 +54871,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`;
@@ -57890,7 +54963,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
@@ -57911,46 +54984,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
@@ -57978,9 +55051,9 @@ BEGIN
DELETE FROM invoiceInDueDay
WHERE invoiceInFk = vInvoiceInFk;
-
+
CALL invoiceInDueDay_calculate(vInvoiceInFk);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -58053,14 +55126,15 @@ BEGIN
DECLARE vLines INT;
SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig;
-
+
SELECT COUNT(*) INTO vLines
FROM invoiceInTax
- WHERE invoiceInFk = vInvoiceInFk;
-
- IF vLines >= vTaxRowLimit THEN
+ WHERE invoiceInFk = vInvoiceInFk
+ AND (taxTypeSageFk OR transactionTypeSageFk);
+
+ IF vLines >= vTaxRowLimit THEN
CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit));
- END IF;
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -58099,7 +55173,7 @@ BEGIN
CALL invoiceInTax_getFromEntries(vInvoiceInFk);
CALL invoiceInDueDay_calculate(vInvoiceInFk);
-
+
FETCH rs INTO vInvoiceInFk;
END WHILE;
@@ -58131,7 +55205,7 @@ BEGIN
SELECT MAX(rr.dated) INTO vDated
FROM referenceRate rr
JOIN invoiceIn ii ON ii.id = vId
- WHERE rr.dated <= ii.issued
+ WHERE rr.dated <= ii.issued
AND rr.currencyFk = ii.currencyFk ;
IF vDated THEN
@@ -58140,13 +55214,13 @@ BEGIN
WHERE dated = vDated;
END IF;
- SELECT id INTO vExpenseFk
- FROM vn.expense
- 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
+
+ DELETE FROM invoiceInTax
WHERE invoiceInFk = vId;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, foreignValue, taxTypeSageFk, transactionTypeSageFk)
@@ -58160,9 +55234,9 @@ 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
+ LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk
AND rr.dated = ii.issued
- WHERE ii.id = vId
+ WHERE ii.id = vId
HAVING taxableBase IS NOT NULL;
END ;;
DELIMITER ;
@@ -58189,7 +55263,7 @@ BEGIN
SELECT ii.bookEntried,
iit.foreignValue,
ii.companyFk,
- ii.expenseFkDeductible,
+ ii.expenseFkDeductible,
iit.taxableBase,
iit.transactionTypeSageFk,
ii.serial,
@@ -58228,7 +55302,7 @@ 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 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
@@ -58251,18 +55325,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,
@@ -58279,7 +55353,7 @@ BEGIN
CONTRA,
EURODEBE,
EUROHABER,
- CONCEPTO,
+ CONCEPTO,
CAMBIO,
DEBEME,
HABERME,
@@ -58291,9 +55365,9 @@ BEGIN
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,
@@ -58305,17 +55379,17 @@ BEGIN
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,
@@ -58364,28 +55438,28 @@ BEGIN
tii.companyFk
FROM tInvoiceIn tii
LEFT JOIN (
- SELECT e.id
+ SELECT e.id
FROM tInvoiceIn tii
- JOIN expense e ON e.id = tii.expenseFk
+ 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'))
+ ) 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,
@@ -58434,31 +55508,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.expenseFk;
-
- -- Actualización del registro original
+
+ -- 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 ;
@@ -58573,7 +55647,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,
@@ -58607,19 +55681,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,
@@ -58635,14 +55709,14 @@ BEGIN
ASIEN,
FECHA,
SUBCTA,
- CONTRA,
+ CONTRA,
EUROHABER,
- CONCEPTO,
+ CONCEPTO,
FECHA_EX,
FECHA_OP,
empresa_id
)
- SELECT
+ SELECT
vBookNumber AS ASIEN,
rs.FECHA,
ioe.expenseFk AS SUBCTA,
@@ -58656,8 +55730,8 @@ BEGIN
JOIN invoiceOutExpense ioe
WHERE ioe.invoiceOutFk = vInvoice;
- SELECT GROUP_CONCAT(`name` SEPARATOR ',')
- INTO vExpenseConcept
+ SELECT GROUP_CONCAT(`name` SEPARATOR ',')
+ INTO vExpenseConcept
FROM expense e
JOIN invoiceOutExpense ioe ON ioe.expenseFk = e.id
WHERE ioe.invoiceOutFk = vInvoice;
@@ -58667,7 +55741,7 @@ BEGIN
ASIEN,
FECHA,
SUBCTA,
- CONTRA,
+ CONTRA,
EUROHABER,
BASEEURO,
CONCEPTO,
@@ -58695,7 +55769,7 @@ BEGIN
TIPORECTIF,
empresa_id
)
- SELECT
+ SELECT
vBookNumber AS ASIEN,
rs.FECHA,
iot.pgcFk AS SUBCTA,
@@ -58715,11 +55789,11 @@ BEGIN
rs.FECHA_OP,
rs.FECHA_EX,
rs.TIPOOPE,
- rs.NFACTICK,
+ rs.NFACTICK,
rs.TERIDNIF,
rs.TERNIF,
rs.TERNOM,
- pgc.mod340 AS L340,
+ pgc.mod340 AS L340,
pgc.siiTrascendencyInvoiceOutFk AS TIPOCLAVE,
pgc.cplusTaxBreakFk as TIPOEXENCI,
rs.TIPONOSUJE,
@@ -58727,13 +55801,13 @@ BEGIN
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;
@@ -58765,7 +55839,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
@@ -58780,15 +55854,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;
@@ -58816,7 +55890,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,
@@ -58828,7 +55902,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
@@ -59132,17 +56206,17 @@ 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 invoiceExpenseMake(vNewInvoiceId);
- CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
+ CALL invoiceTaxMake(vNewInvoiceId, vTaxArea);
UPDATE invoiceOut io
JOIN (
@@ -59273,17 +56347,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
@@ -59302,11 +56376,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
@@ -59319,7 +56393,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
@@ -59348,7 +56422,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
*/
@@ -59363,11 +56437,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);
@@ -59449,7 +56523,7 @@ 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;
@@ -59473,33 +56547,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
@@ -59507,7 +56581,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
@@ -59516,7 +56590,7 @@ 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 (
@@ -59541,9 +56615,9 @@ BEGIN
AND warehouse_id = vWarehouseFk
GROUP BY item_id
) 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 ;;
@@ -59565,7 +56639,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
@@ -59579,9 +56653,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 ;
@@ -59614,7 +56688,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))),
''
@@ -59645,7 +56719,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;
@@ -59671,7 +56745,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
@@ -59679,9 +56753,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
@@ -59690,13 +56764,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 ;;
@@ -59870,54 +56944,65 @@ BEGIN
* @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 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;
+ 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;
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk
+ INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE s.id = vSaleFk;
- UPDATE vn.sale
- SET quantity = quantity - vQuantity
- WHERE id = vSaleFk;
+ CALL 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;
- 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;
+ START TRANSACTION;
+ UPDATE sale
+ SET quantity = quantity - vQuantity
+ WHERE id = vSaleFk;
+
+ INSERT INTO sale(ticketFk, itemFk, quantity, concept)
+ SELECT vTicketFk,
+ vMateFk,
+ CEIL(vQuantity / vRoundQuantity) * vRoundQuantity,
+ CONCAT('+ ',i.longName)
+ FROM item i
+ WHERE id = vMateFk;
+
SELECT LAST_INSERT_ID() INTO vSaleFk;
-
- CALL vn.sale_calculateComponent(vSaleFk, NULL);
-
- INSERT INTO vn.itemProposal(itemFk, mateFk, counter)
+
+ CALL sale_calculateComponent(vSaleFk, NULL);
+
+ INSERT INTO itemProposal(itemFk, mateFk, counter)
VALUES(vItemFk, vMateFk, 1)
- ON DUPLICATE KEY UPDATE counter = counter + 1;
+ ON DUPLICATE KEY UPDATE counter = counter + 1;
+ COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -59942,13 +57027,13 @@ BEGIN
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);
@@ -59958,16 +57043,16 @@ BEGIN
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
+ 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,
@@ -59985,7 +57070,7 @@ BEGIN
(i.value8 <=> vValue8 COLLATE utf8_general_ci) match8,
a.available,
IFNULL(ip.counter,0) counter
- FROM vn.item i
+ 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
@@ -59999,7 +57084,7 @@ BEGIN
(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.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,
@@ -60035,7 +57120,7 @@ BEGIN
CREATE TEMPORARY TABLE tmp.item
SELECT vItem id;
-
+
CALL item_refreshTags();
DROP TEMPORARY TABLE tmp.item;
@@ -60058,23 +57143,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,
@@ -60084,15 +57169,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)
@@ -60119,9 +57204,9 @@ BEGIN
DECLARE vItemFk INT;
SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
-
+
UPDATE vn.item SET minimum = min WHERE id = vItemFk;
-
+
END ;;
@@ -60143,8 +57228,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 ;
@@ -60185,36 +57270,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 */ ;
@@ -60233,7 +57318,7 @@ DELIMITER ;
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;
@@ -60252,9 +57337,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
@@ -60284,8 +57369,8 @@ BEGIN
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 */ ;
@@ -60306,9 +57391,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
@@ -60321,7 +57406,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
@@ -60361,7 +57446,7 @@ BEGIN
UPDATE vn.itemShelving
SET visible = visible - vQuantity
WHERE id = vItemShelvingFk;
-
+
END ;;
DELIMITER ;
@@ -60384,47 +57469,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 */ ;
@@ -60443,7 +57528,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar`(vSectorFk INT)
proc:BEGIN
-
+
DECLARE vCalcVisibleFk INT;
DECLARE vCalcAvailableFk INT;
DECLARE hasFatherSector BOOLEAN;
@@ -60451,17 +57536,17 @@ 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
@@ -60470,21 +57555,21 @@ proc:BEGIN
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 *
+ ENGINE = MEMORY
+ SELECT *
FROM (
SELECT iss.itemFk,
i.longName,
@@ -60503,9 +57588,9 @@ proc:BEGIN
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,
@@ -60515,7 +57600,7 @@ proc:BEGIN
0 downstairs,
IF(it.isPackaging, NULL, v.visible) visible,
vSectorFk as sectorFk
- FROM cache.visible v
+ 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
@@ -60524,8 +57609,8 @@ proc:BEGIN
AND iss.itemFk IS NULL
AND it.isInventory
) sub GROUP BY itemFk;
-
- SELECT ishr.*,
+
+ 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
@@ -60542,7 +57627,7 @@ proc:BEGIN
ELSE
CREATE TEMPORARY TABLE tmp.itemShelvingRadar
(PRIMARY KEY (itemFk))
- ENGINE = MEMORY
+ ENGINE = MEMORY
SELECT iss.itemFk,
0 `hour`,
0 `minute`,
@@ -60554,7 +57639,7 @@ 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,
@@ -60568,20 +57653,20 @@ proc:BEGIN
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
+ 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;
+ 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
+ FROM
(SELECT item_id itemFk,
- amount,
- IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours,
+ 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
@@ -60589,23 +57674,23 @@ proc:BEGIN
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.Reservado
AND stPrevious.saleFk IS NULL
- AND io.dat >= util.VN_CURDATE()
+ AND io.dat >= util.VN_CURDATE()
AND io.dat < 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);
@@ -60625,7 +57710,7 @@ proc:BEGIN
END IF;
DROP TEMPORARY TABLE tmp.itemShelvingRadar;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60649,24 +57734,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,
@@ -60686,11 +57771,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 */ ;
@@ -60714,34 +57799,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 */ ;
@@ -60762,10 +57847,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,
@@ -60948,7 +58033,7 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveBySale`(
- vSelf INT ,
+ vSelf INT ,
vQuantity INT,
vUserFk INT
)
@@ -60963,7 +58048,7 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
ENGINE = MEMORY
SELECT vSelf saleFk, vUserFk userFk;
-
+
CALL itemShelvingSale_reserve();
END ;;
DELIMITER ;
@@ -60989,12 +58074,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`(
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
+ * 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
+ * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha
* quedado vacio tras el movimiento
*/
DECLARE vSaleFk INT;
@@ -61005,7 +58090,7 @@ BEGIN
DECLARE vItemFk INT;
DECLARE vUserFk INT;
DECLARE vDone BOOLEAN DEFAULT FALSE;
- DECLARE vSales CURSOR FOR
+ DECLARE vSales CURSOR FOR
SELECT iss.saleFk, iss.userFk
FROM itemShelvingSale iss
JOIN sale s ON s.id = iss.saleFk
@@ -61019,14 +58104,14 @@ BEGIN
CALL util.throw('Booking completed');
END IF;
- SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk
+ 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
+
+ UPDATE itemShelvingSale
SET isPicked = TRUE,
quantity = vQuantity
WHERE id = vItemShelvingSaleFk;
@@ -61051,10 +58136,10 @@ l: LOOP
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
@@ -61068,32 +58153,32 @@ l: LOOP
WHERE saleFk = vSaleFk
AND NOT isPicked;
- IF vRemainingQuantity THEN
+ 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)
+ SELECT SUM(iss.quantity)
INTO vReservedQuantity
- FROM itemShelvingSale iss
+ FROM itemShelvingSale iss
WHERE iss.saleFk = vSaleFk;
-
+
CALL saleTracking_new(
vSaleFk,
- TRUE,
- vReservedQuantity,
- `account`.`myUser_getId`(),
+ TRUE,
+ vReservedQuantity,
+ `account`.`myUser_getId`(),
NULL,
'PREPARED',
TRUE);
-
+
UPDATE sale s
SET s.quantity = vReservedQuantity
- WHERE s.id = vSaleFk ;
+ WHERE s.id = vSaleFk ;
END IF;
END IF;
END ;;
@@ -61172,7 +58257,7 @@ DELIMITER ;
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.
@@ -61184,7 +58269,7 @@ BEGIN
* @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;
@@ -61194,21 +58279,21 @@ BEGIN
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)
+ INSERT INTO shelving(code, parkingFk)
SELECT vShelvingFk, id
- FROM parking
+ 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
+ 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;
+ WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking;
ELSE
CALL cache.last_buy_refresh(FALSE);
@@ -61362,7 +58447,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`,
@@ -61373,17 +58458,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
@@ -61392,7 +58477,7 @@ 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())
@@ -61401,7 +58486,7 @@ proc:BEGIN
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,
@@ -61418,7 +58503,7 @@ 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())
@@ -61451,12 +58536,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,
@@ -61494,7 +58579,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
@@ -61559,167 +58644,167 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3))
-BEGIN
-
- /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula.
- *
- * @param vShelvingFk Matrícula del carro o pallet
- */
-
- DECLARE vWarehouseFk INT;
- DECLARE vStockScopeDays INT;
-
- SELECT s.warehouseFk, stockScopeDays
- INTO vWarehouseFk, vStockScopeDays
- FROM sector s
- JOIN operator o ON s.id = o.sectorFk
- JOIN productionConfig pc
- WHERE o.workerFk = account.myUser_getId();
-
- IF vWarehouseFk IS NULL
- THEN CALL util.throw('WarehouseFk not setted');
- END IF;
-
- IF vStockScopeDays IS NULL
- THEN CALL util.throw('StockScopeDays not setted');
- END IF;
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.tItems
- (PRIMARY KEY (itemFk))
- ENGINE = MEMORY
- SELECT itemFk, SUM(visible) visible
- FROM itemShelving
- WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
- GROUP BY itemFk;
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay
- (INDEX (itemFk, dated))
- ENGINE = MEMORY
- SELECT dated,
- SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock,
- t3.itemFk
- FROM (
- SELECT t.itemFk, dated, SUM(amount) amount
- FROM (
- SELECT t2.itemFk, t2.amount, t2.dated
- FROM (
- SELECT item_id itemFk, amount, util.VN_CURDATE() dated
- FROM cache.stock s
- JOIN tmp.tItems i ON i.itemFk = s.item_id
- WHERE s.warehouse_id = vWarehouseFk
- UNION ALL
- SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE()
- FROM itemShelving ish
- JOIN tmp.tItems i ON i.itemFk = ish.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
- JOIN parking p ON sh.parkingFk = p.id
- JOIN sector s ON s.id = p.sectorFk
- WHERE s.isReserve
- GROUP BY ish.itemFk
- UNION ALL
- SELECT iei.itemFk, SUM(quantity), landed
- FROM itemEntryIn iei
- JOIN tmp.tItems i ON i.itemFk = iei.itemFk
- WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
- AND iei.warehouseInFk = vWarehouseFk
- AND NOT isVirtualStock
- GROUP BY iei.itemFk, iei.landed
- UNION ALL
- SELECT ieo.itemFk, SUM(quantity), shipped
- FROM itemEntryOut ieo
- JOIN tmp.tItems i ON i.itemFk = ieo.itemFk
- WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
- AND ieo.warehouseOutFk = vWarehouseFk
- GROUP BY ieo.itemFk, ieo.shipped
- UNION ALL
- SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped)
- FROM itemTicketOut ito
- JOIN tmp.tItems i ON i.itemFk = ito.itemFk
- WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
- AND ito.warehouseFk = vWarehouseFk
- GROUP BY ito.itemFk, ito.shipped
- ) t2
- JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t
- GROUP BY t.itemFk, dated
- ) t3;
-
- -- Se restan las entradas de hoy
- UPDATE tmp.tStockByDay sbd
- JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry
- FROM itemEntryIn iei
- JOIN tmp.tItems i ON i.itemFk = iei.itemFk
- WHERE iei.landed = util.VN_CURDATE()
- AND iei.warehouseInFk = vWarehouseFk
- AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk
- SET sbd.stock = sbd.stock - sub.todayEntry
- WHERE sbd.dated = util.VN_CURDATE();
-
- -- Se añaden las lineas de venta servidas
- UPDATE tmp.tStockByDay sbd
- JOIN (SELECT s.itemFK, SUM(quantity) amount
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- WHERE t.warehouseFk = vWarehouseFk
- AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight()
- AND s.isPicked
- GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk
- SET sbd.stock = sbd.stock + sub.amount;
-
- -- Se añaden los items ubicados hoy
- UPDATE tmp.tStockByDay sbd
- JOIN (SELECT ish.itemFK, SUM(ish.visible) amount
- FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
- JOIN parking p ON p.id = sh.parkingFk
- JOIN sector s ON s.id = p.sectorFk
- WHERE s.warehouseFk = vWarehouseFk
- AND NOT s.isReserve
- AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight()
- GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk
- SET sbd.stock = sbd.stock + sub.amount;
-
- SELECT ts.itemFk,
- i.longName,
- IF(ts.stock<=0, ts.dated, NULL) dated,
- ts.stock,
- sub4.visible,
- sub4.shelvingFk
- FROM(
- SELECT IFNULL(sub2.minDated, sub.minDated) dated,
- IFNULL(sub2.itemFk, sub.itemFk) itemFk
- FROM(SELECT sbd.itemFk,
- MIN(dated) minDated,
- sbd.stock
- FROM tmp.tItems ti
- LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk
- GROUP BY itemFk)sub
- LEFT JOIN (
- SELECT sbd.itemFk,
- MIN(dated) minDated,
- sbd.stock
- FROM tmp.tItems ti
- LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk
- WHERE sbd.stock <= 0
- GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk
- WHERE sub2.itemFk IS NOT NULL
- OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3
- LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated
- JOIN (SELECT ish.itemFk,
- ish.visible,
- p.sectorFk,
- ish.shelvingFk
- FROM itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
- LEFT JOIN parking p ON p.id = parkingFk
- LEFT JOIN vn.sector s ON s.id = p.sectorFk
- WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
- ) sub4 ON sub4.itemFk = ts.itemFk
- LEFT JOIN sector s ON s.id = sub4.sectorFk
- LEFT JOIN item i ON i.id = ts.itemFk
- WHERE NOT s.isReserve;
-
- DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems;
-
+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 */ ;
@@ -61812,15 +58897,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
@@ -61834,7 +58919,7 @@ BEGIN
DECLARE vItemShelvingFk INT;
SELECT c.id,
- c.clientFk,
+ pc.clientSelfConsumptionFk,
s.warehouseFk
INTO vCompanyFk,
vClientFk,
@@ -61845,6 +58930,7 @@ BEGIN
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 ON TRUE
WHERE s2.code = vShelvingFk;
IF vClientFk IS NULL THEN
@@ -61864,10 +58950,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;
@@ -61920,9 +59006,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 ;;
@@ -61944,7 +59030,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
*/
@@ -61954,33 +59040,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);
@@ -61989,11 +59075,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 */ ;
@@ -62014,12 +59100,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
@@ -62028,8 +59114,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;
@@ -62054,12 +59140,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
@@ -62068,8 +59154,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;
@@ -62092,36 +59178,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 */ ;
@@ -62146,9 +59232,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;
@@ -62159,45 +59245,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 */ ;
@@ -62307,7 +59393,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
@@ -62340,7 +59426,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;
@@ -62406,7 +59492,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
@@ -62414,7 +59500,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;
@@ -62545,6 +59631,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 */ ;
@@ -62598,50 +59994,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)
- */
- 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;
+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 */ ;
@@ -62667,13 +60063,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
@@ -62699,7 +60095,7 @@ BEGIN
inventorySupplierFk INT(10)
);
- INSERT INTO tItemDiary
+ INSERT INTO tItemDiary
SELECT tr.landed shipped,
b.quantity `in`,
NULL `out`,
@@ -62720,14 +60116,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
@@ -62753,14 +60149,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
@@ -62784,17 +60180,17 @@ BEGIN
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
@@ -62810,7 +60206,7 @@ BEGIN
`out` DESC;
IF vDate IS NULL THEN
-
+
SET @a := 0;
SET @currentLineFk := 0;
SET @shipped := '';
@@ -62825,9 +60221,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,
@@ -62859,25 +60255,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 ;
@@ -62984,7 +60380,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
**/
@@ -62994,32 +60390,32 @@ BEGIN
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,
IFNULL(izc.timed, util.midnight()) minTimed
- FROM (SELECT item_id,
- warehouse_id,
+ 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
@@ -63142,12 +60538,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;
@@ -63158,7 +60554,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 ;;
@@ -63188,33 +60584,33 @@ BEGIN
* @param vWarehouseFk warehouse id
* @param vDate fecha para revisar disponible
* @param vIsShowedByType para mostrar solo artículos de ese tipo
- */
+ */
DECLARE vCalcFk INT;
DECLARE vTypeFk INT;
-
+
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';
-
+
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,
@@ -63247,7 +60643,7 @@ BEGIN
ORDER BY counter DESC,
(t1.name = vTag1) DESC,
(it1.value = vValue1) DESC,
- (i.tag6 = vTag6) DESC,
+ (i.tag6 = vTag6) DESC,
(i.value6 = vValue6) DESC,
(i.tag5 = vTag5) DESC,
(i.value5 = vValue5) DESC,
@@ -63256,7 +60652,7 @@ BEGIN
(i.tag8 = vTag8) DESC,
(i.value8 = vValue8) DESC
LIMIT 30;
-
+
END ;;
DELIMITER ;
@@ -63407,6 +60803,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 */ ;
@@ -63541,11 +61039,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 ;;
@@ -63568,7 +61066,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;
@@ -63578,7 +61076,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
@@ -63609,13 +61107,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 ;
@@ -63657,11 +61155,11 @@ BEGIN
SELECT DEFAULT(companyFk) INTO vDefaultCompanyFk
FROM vn.ticket LIMIT 1;
-
- IF vAddressFk IS NULL THEN
+
+ IF vAddressFk IS NULL THEN
SELECT pc.shortageAddressFk INTO vAddressShortage
FROM productionConfig pc ;
- ELSE
+ ELSE
SET vAddressShortage = vAddressFk;
END IF;
@@ -63726,18 +61224,18 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingShelve`(vSelf INT, vPacking INT)
BEGIN
-
+
/**
* Actualiza el valor de item.packingShelve
- *
+ *
* @param vSelf Identificador de vn.item
* @param vPacking Cantidad de unidades de venta que caben en una bandeja
*/
-
- UPDATE vn.item i
+
+ UPDATE vn.item i
SET i.packingShelve = vPacking
WHERE i.id = vSelf;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63780,204 +61278,240 @@ 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;
- DECLARE vInventorySupplierFk INT;
+ SELECT inventorySupplierFk INTO vInventorySupplierFk
+ FROM entryConfig;
- SELECT inventorySupplierFk INTO vInventorySupplierFk
- FROM entryConfig;
+ SET vDateDayEnd = util.dayEnd(vDated);
- 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;
- SELECT landed INTO vInventoried
- FROM travel tr
- JOIN entry E ON E.travelFk = tr.id
- WHERE landed <= vDateDayEnd
- AND E.supplierFk = vInventorySupplierFk
- ORDER BY 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 vHasNotInventory = IF (vInventoried is null, TRUE, FALSE);
+ SET vInventoried = vDated + INTERVAL 1 DAY;
+ SET vDateDayEnd = vInventoryClone;
+ END IF;
- IF vHasNotInventory THEN
+ 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;
- SELECT landed INTO vInventoried2
- FROM travel tr
- JOIN entry E ON E.travelFk = tr.id
- WHERE landed >= vDated
- AND E.supplierFk = vInventorySupplierFk
- ORDER BY landed ASC
- LIMIT 1;
+ -- 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));
- SET vInventoried = TIMESTAMPADD(DAY,1,vDated);
- SET vDateDayEnd = vInventoried2;
+ -- 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));
- END IF;
+ -- 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);
- DROP TEMPORARY TABLE IF EXISTS inv;
+ -- 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;
- 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;
+ -- 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);
- IF vHasNotInventory = TRUE THEN
+ 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;
- 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 = vInventorySupplierFk
- AND w.valuatedInventory
- AND t.isInventory
- GROUP BY tr.warehouseInFk, b.itemFk;
+ DELETE FROM tInventory
+ WHERE quantity IS NULL OR NOT quantity;
- END IF;
-
- INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
- SELECT tr.warehouseInFk,
- b.itemFk,
- b.quantity * IF(vHasNotInventory,-1,1),
- w.`name`
- FROM buy b
- JOIN item i ON i.id = b.itemFk
- JOIN entry e ON e.id = b.entryFk
- JOIN travel tr ON tr.id = e.travelFk
- JOIN itemType t ON t.id = i.typeFk
- JOIN warehouse w ON w.id = tr.warehouseInFk
- WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
- AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, trUE)
- AND NOT e.isRaid
- AND w.valuatedInventory
- AND t.isInventory
- AND e.supplierFk <> vInventorySupplierFk
- 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 */ ;
@@ -63996,10 +61530,10 @@ DELIMITER ;
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
+
+/* 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)
*/
@@ -64010,7 +61544,7 @@ BEGIN
MIN(DATE_FORMAT(IF(HOUR(t.shipped),t.shipped,
IFNULL(zc.hour, z.HOUR)), '%H:%i')
)timed
- FROM ticket t
+ 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
@@ -64043,37 +61577,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,
@@ -64082,20 +61616,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
@@ -64103,7 +61637,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;
@@ -64125,10 +61659,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 */ ;
@@ -64154,15 +61688,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 ;;
@@ -64187,9 +61721,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;
@@ -64207,23 +61741,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 ;;
@@ -64244,23 +61778,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 */ ;
@@ -64280,21 +61814,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 */ ;
@@ -64313,13 +61847,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);
@@ -64328,24 +61862,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 */ ;
@@ -64400,12 +61934,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
@@ -64446,12 +61980,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;
@@ -64479,34 +62013,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 */ ;
@@ -64543,7 +62077,7 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.client
SELECT id
- FROM client
+ FROM client
WHERE salesPersonFk = vWorkerFk;
CALL client_getMana();
@@ -64553,7 +62087,7 @@ BEGIN
FROM tmp.clientMana
ON DUPLICATE KEY UPDATE amount = VALUES(amount);
- DROP TEMPORARY TABLE
+ DROP TEMPORARY TABLE
tmp.client,
tmp.clientMana;
END ;;
@@ -64572,196 +62106,197 @@ DELIMITER ;
/*!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
+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 vn2008.article_inventory
- ADD `avalaible` INT NOT NULL,
- ADD `sd` INT NOT NULL,
- ADD `rest` INT NOT NULL,
- ADD `expected` INT NOT NULL,
- ADD `inventory` INT NOT NULL,
- ADD `visible` INT NOT NULL,
- ADD `life` TINYINT NOT NULL DEFAULT '0';
-
- -- Calculo del inventario
- UPDATE vn2008.article_inventory 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.article_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 vn2008.article_inventory 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.article_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 vn2008.item_travel(vWarehouseFk, vDate);
- UPDATE vn2008.article_inventory 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 vn2008.item_travel 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.article_id
- SET ai.avalaible = IF(sub.minQuantity > 0,
- ai.avalaible,
- ai.avalaible + sub.minQuantity),
- ai.sd = ai.inventory + sub.quantity;
-
- DROP TEMPORARY TABLE
- vn2008.item_travel,
- tmp.itemCalc,
- tmp.itemAtp;
+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 */ ;
@@ -64782,20 +62317,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
@@ -64832,7 +62367,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%';
@@ -64840,7 +62375,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.')
);
@@ -64867,37 +62402,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 ;;
@@ -64926,18 +62461,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;
@@ -64967,15 +62502,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);
@@ -65001,7 +62536,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 */ ;
@@ -65028,7 +62563,7 @@ BEGIN
DECLARE vOrderId INT;
CALL vn.orderCreate(vLanded,vAgencyMode,vAddress,vSourceApp,vOrderId);
SELECT vOrderId;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -65048,7 +62583,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `orderListVolume`(IN vOrderId INT)
BEGIN
- SELECT
+ SELECT
o.id,
o.itemFk,
i.description,
@@ -65074,7 +62609,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,
@@ -65093,20 +62628,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;
@@ -65130,22 +62665,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);
@@ -65154,44 +62689,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 */ ;
@@ -65217,7 +62752,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 */ ;
@@ -65239,15 +62774,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);
@@ -65339,34 +62874,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 ;;
@@ -65391,59 +62926,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 */ ;
@@ -65467,28 +63002,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 */ ;
@@ -65507,11 +63042,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,
@@ -65520,15 +63055,15 @@ 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 */ ;
@@ -65547,17 +63082,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 */ ;
@@ -65582,7 +63117,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 (
@@ -65685,14 +63220,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
@@ -65716,7 +63251,7 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `productionControl`(
- vWarehouseFk INT,
+ vWarehouseFk INT,
vScopeDays INT
)
proc: BEGIN
@@ -65806,9 +63341,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
@@ -65817,7 +63352,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
@@ -65825,12 +63360,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,
@@ -65923,12 +63458,13 @@ proc: BEGIN
ENGINE = MEMORY
SELECT ish.itemFk,
p.sectorFk,
- sc.isPreviousPrepared,
+ st.description = '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;
@@ -66102,8 +63638,8 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores
ENGINE = MEMORY
- SELECT COUNT(c.ticketFk) errors,
- tt.workerFk
+ 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
@@ -66113,10 +63649,10 @@ BEGIN
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
AND cr.code = 'chk'
AND s.code = 'ON_PREPARATION'
- GROUP BY workerFk;
+ GROUP BY tt.userFk;
UPDATE productionError ep
- JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk
+ JOIN itemPickerErrors ipe ON ipe.userFk = ep.userFk
SET ep.error = ep.error + ipe.errors
WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores';
@@ -66224,23 +63760,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;
@@ -66249,15 +63785,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;
@@ -66296,19 +63832,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.description = 'previousByPacking',
i.`size` > pc.previousPreparationMinimumSize
- AND isa.packing > 1
AND (MOD(TRUNCATE(isa.quantity,0), isa.packing)= 0 ),
TRUE)
AND sgd.saleFk IS NULL
@@ -66363,7 +63899,7 @@ BEGIN
`yearMonth` INT
)
ENGINE = MEMORY;
-
+
WHILE vDated <= vEnded DO
INSERT INTO tmp.rangeDate
SET `dated` = vDated,
@@ -66373,7 +63909,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 ;;
@@ -66462,7 +63998,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,
@@ -66480,22 +64016,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,
@@ -66512,15 +64048,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 */ ;
@@ -66541,83 +64077,34 @@ 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 */ ;
@@ -66711,7 +64198,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.
@@ -66754,11 +64241,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;
@@ -66767,7 +64254,7 @@ BEGIN
priorityFk = vPriorityFk,
reportFk = vReportFk,
workerFk = vUserFk;
-
+
SET vPrintQueueFk = LAST_INSERT_ID();
WHILE vI < vLength DO
@@ -66800,16 +64287,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,
@@ -66821,7 +64308,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 ;;
@@ -66880,25 +64367,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;
@@ -66963,7 +64450,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
@@ -67049,11 +64536,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 */ ;
@@ -67092,15 +64579,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
@@ -67116,6 +64606,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,
@@ -67125,13 +64622,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
@@ -67150,15 +64651,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
@@ -67177,40 +64678,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 `route_checkDeliveryMethod` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `route_checkDeliveryMethod`(vSelf INT)
-BEGIN
-/**
-* Comprueba si el deliveryMethod del agencyMode de la ruta es reparto
-*
-* @param vSelf Id de ruta
-*/
- DECLARE vDeliveryMethod VARCHAR(45);
-
- SELECT dm.code INTO vDeliveryMethod
- FROM route r
- JOIN agencyMode am ON am.id = r.agencyModeFk
- JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
- WHERE r.id = vSelf;
-
- IF vDeliveryMethod <> 'DELIVERY' THEN
- CALL util.throw('Route tickets via delivery only');
- END IF;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `route_doRecalc` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -67224,7 +64691,7 @@ proc: BEGIN
/**
* Recalculates modified route.
*/
-
+
DECLARE vDone BOOL;
DECLARE vRouteFk INT;
@@ -67233,7 +64700,7 @@ proc: BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
-
+
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK('vn.route_doRecalc');
@@ -67311,13 +64778,13 @@ SELECT t.id Id,
t.cmrFk
FROM ticket t
JOIN client c ON t.clientFk = c.id
- JOIN address a ON t.addressFk = a.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
+ JOIN ticket ti ON ti.routeFk = vRouteFk
AND ti.id = t.id
AND ti.clientFk = t.clientFk
GROUP BY addressFk
@@ -67394,27 +64861,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 */ ;
@@ -67431,15 +64898,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 ;;
@@ -67572,41 +65041,41 @@ 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,
+
+ INSERT INTO vn.sale(itemFk,
+ concept,
+ price,
+ discount,
+ quantity,
+ ticketFk,
isPriceFixed)
- SELECT s.itemFk,
- i.longName,
- s.price,
- s.discount,
+ SELECT s.itemFk,
+ i.longName,
+ s.price,
+ s.discount,
vQuantity,
- s.ticketFk,
- s.isPriceFixed
+ 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,
+
+ INSERT INTO vn.saleComponent( saleFk,
+ componentFk,
value)
- SELECT vNewSaleFk,
- componentFk,
+ SELECT vNewSaleFk,
+ componentFk,
value
- FROM vn.saleComponent
+ FROM vn.saleComponent
WHERE saleFk = vSaleFk;
END ;;
@@ -67626,41 +65095,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 */ ;
@@ -67695,17 +65164,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;
@@ -67836,9 +65305,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 */ ;
@@ -67855,12 +65324,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
@@ -67876,12 +65345,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,
@@ -67908,27 +65377,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 ;;
@@ -67938,16 +65407,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
@@ -67955,14 +65424,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 */ ;
@@ -67970,14 +65439,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 `sale_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 `sale_checkNoComponents`(vCreatedFrom DATETIME, vCreatedTo DATETIME)
BEGIN
@@ -68008,7 +65477,7 @@ BEGIN
GROUP BY s.id;
DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET v_done = TRUE;
+ SET v_done = TRUE;
DROP TEMPORARY TABLE IF EXISTS tmp.coste;
@@ -68016,7 +65485,7 @@ BEGIN
CREATE TEMPORARY TABLE tmp.coste
(PRIMARY KEY (id)) ENGINE = MEMORY
SELECT s.id
- FROM sale s
+ 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
@@ -68035,17 +65504,17 @@ BEGIN
IF v_done THEN
LEAVE l;
END IF;
-
+
SELECT ticketFk, concept
INTO vTicketFk, vConcept
FROM sale
WHERE id = vSaleFk;
-
- CALL sale_calculateComponent(vSaleFk, 1);
+
+ CALL sale_calculateComponent(vSaleFk, 'renewPrices');
END LOOP;
CLOSE vCur;
- DROP TEMPORARY TABLE tmp.coste;
+ DROP TEMPORARY TABLE tmp.coste;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68054,6 +65523,129 @@ 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_getBoxPickingList` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getBoxPickingList`(vSectorFk INT, vDated DATE)
+BEGIN
+/**
+* Returns a suitable boxPicking sales list
+*
+* @param vSectorFk Identifier for vn.sector table
+* @param vDated Date for vn.tickets.shipping
+*
+* @return tmp.sale
+*/
+ DECLARE vWarehouseFk INT;
+
+ SELECT warehouseFk INTO vWarehouseFk
+ FROM sector
+ WHERE id = vSectorFk;
+
+ CALL productionControl(vWarehouseFk, 0);
+
+ -- Products without vn.item.packingOut, pay atention to vn.itemShelving.packing
+ 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 / ish.packing) stickers,
+ ish.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
+ 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 s.quantity BETWEEN ish.packing AND (ish.visible - IFNULL(tISS.reserve,0))
+ AND i.packingOut IS NULL
+ 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;
+
+ -- Remaining products, vn.item.packingOut
+ INSERT IGNORE INTO tmp.sale
+ SELECT
+ s.ticketFk,
+ s.id saleFk,
+ s.itemFk,
+ s.concept,
+ s.quantity,
+ MAKETIME(pb.HH,pb.mm,0) etd,
+ pb.routeFk,
+ s.quantity / i.packingOut stickers,
+ i.packingOut,
+ pc.defaultBigPackageFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemShelving ish ON ish.itemFk = s.itemFk
+ 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 packagingConfig pc
+ LEFT JOIN routesMonitor rm ON rm.routeFk = pb.routeFk
+ LEFT JOIN itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = p.sectorFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk
+ WHERE s.quantity >= i.packingOut
+ AND NOT pb.problem
+ AND s.quantity > 0
+ AND sgd.saleFk IS NULL
+ AND p.sectorFk = vSectorFk
+ AND ts.isPreviousPreparable
+ AND iss.visible >= s.quantity
+ AND ((rm.bufferFk AND rm.isPickingAllowed)
+ OR am.code = 'REC_ALG')
+ AND pb.shipped = vDated
+ GROUP BY s.id
+ ORDER BY etd;
+
+ SELECT * FROM tmp.sale;
+
+ DROP TEMPORARY TABLE tmp.productionBuffer;
+ DROP TEMPORARY TABLE tmp.sale;
+ END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_getFromTicketOrCollection` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -68131,7 +65723,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,
@@ -68148,12 +65740,12 @@ DECLARE vIsCollection BOOL;
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
@@ -68165,7 +65757,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
@@ -68217,8 +65809,8 @@ BEGIN
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'
+ JOIN observationType ot ON ot.id = tto.observationTypeFk
+ WHERE ot.code = 'administrative'
AND tto.description = 'Miriam';
CREATE OR REPLACE TEMPORARY TABLE tmp.sale_problems (
@@ -68250,7 +65842,7 @@ BEGIN
-- Too Little
INSERT INTO tmp.sale_problems(ticketFk, isTooLittle)
- SELECT tp.ticketFk, TRUE
+ SELECT tp.ticketFk, TRUE
FROM tmp.sale_getProblems tp
JOIN ticket t ON t.id = tp.ticketFk
JOIN (
@@ -68327,6 +65919,19 @@ BEGIN
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
@@ -68339,25 +65944,28 @@ 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 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 itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
+ 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
@@ -68370,20 +65978,24 @@ BEGIN
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 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 itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
+ 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
@@ -68397,21 +66009,26 @@ BEGIN
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 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 itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
+ 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
@@ -68432,12 +66049,12 @@ BEGIN
INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
- SELECT tl.ticketFk,
+ SELECT tl.ticketFk,
s.id saleFk ,
- LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem,
+ 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
@@ -68445,11 +66062,11 @@ 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
@@ -68459,7 +66076,8 @@ BEGIN
DROP TEMPORARY TABLE
tmp.clientGetDebt,
- tmp.ticket_list;
+ tmp.ticket_list,
+ tItemShelvingStock_byWarehouse;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68479,16 +66097,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;
@@ -68517,7 +66135,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
@@ -68541,80 +66159,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
@@ -68623,14 +66241,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
@@ -68638,7 +66256,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
@@ -68650,17 +66268,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 ;
@@ -68669,6 +66287,155 @@ 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 INT DEFAULT NULL;
+ DECLARE vNewSaleFk INT;
+ DECLARE vChangePrice INT DEFAULT 1;
+ DECLARE vBuyerDiscount INT DEFAULT 4;
+ DECLARE vManaDiscount INT DEFAULT 3;
+ 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;
+ IF worker_isInDepartment('vt') THEN
+ SET vOption = vManaDiscount;
+ ELSE
+ SET vOption = vBuyerDiscount;
+ END IF;
+ ELSE
+ SET vFinalPrice = vNewPrice;
+ SET vOption = vChangePrice;
+ 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 */ ;
@@ -68681,22 +66448,22 @@ 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,
+ 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,
@@ -68708,8 +66475,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;
@@ -68810,30 +66577,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 */ ;
@@ -68877,7 +66644,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
@@ -68885,7 +66652,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
@@ -68913,7 +66680,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;
@@ -68969,7 +66736,7 @@ BEGIN
SELECT s.warehouseFk
FROM vn.sector s
WHERE s.id = vSectorFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -69064,10 +66831,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 */ ;
@@ -69086,16 +66853,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;
@@ -69118,22 +66885,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 ;
@@ -69178,12 +66945,12 @@ 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.*
+ DELETE ish.*
FROM itemShelving ish
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
WHERE sh.parkingFk IS NULL
@@ -69379,20 +67146,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
@@ -69402,7 +67169,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 ;;
@@ -69652,10 +67419,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
@@ -69663,29 +67430,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;
@@ -69725,13 +67492,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
@@ -69747,7 +67514,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
@@ -69755,14 +67522,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
@@ -69772,7 +67539,7 @@ BEGIN
AND co.`code` = 'VNL' AND c.`code` <> 'EUR'
) sub
GROUP BY companyFk, supplierFk;
-
+
SELECT ob.dueDated
, ob.supplierFk
, ob.companyFk
@@ -69930,7 +67697,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
@@ -70025,8 +67792,8 @@ BEGIN
JOIN ( SELECT p.supplierFk
FROM supplier s
JOIN payMethod pm ON pm.id = s.payMethodFk
- JOIN (SELECT supplierFk,MAX(created) created
- FROM payment
+ 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
@@ -70071,15 +67838,15 @@ DELIMITER ;
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
@@ -70090,7 +67857,7 @@ BEGIN
AND p.isBox
GROUP BY s.itemFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -70112,7 +67879,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
@@ -70125,7 +67892,7 @@ BEGIN
SELECT ticketFk, builtTime
FROM
(
- SELECT
+ SELECT
ticketFk,
created as builtTime
FROM
@@ -70133,13 +67900,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 ;;
@@ -70149,14 +67916,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
@@ -70168,9 +67935,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
@@ -70179,16 +67946,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;
@@ -70214,12 +67981,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;
@@ -70241,7 +68008,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculatePurge`()
BEGIN
- DROP TEMPORARY TABLE
+ DROP TEMPORARY TABLE
tmp.ticketCalculateItem,
tmp.ticketComponentPrice,
tmp.ticketComponent,
@@ -70265,56 +68032,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 */ ;
@@ -70336,18 +68103,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 ;;
@@ -70369,10 +68136,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 */ ;
@@ -70391,18 +68158,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 */ ;
@@ -70410,76 +68177,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 ;
@@ -70488,16 +68252,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
@@ -70507,132 +68271,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
@@ -70651,11 +68342,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
@@ -70663,14 +68354,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
@@ -70739,24 +68430,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 */ ;
@@ -70794,29 +68485,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
@@ -70824,7 +68515,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))
@@ -70835,7 +68526,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 */ ;
@@ -70856,7 +68547,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
@@ -70873,7 +68564,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 ;;
@@ -70945,18 +68636,18 @@ 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
@@ -70983,7 +68674,7 @@ BEGIN
AND sc.isPackagingArea
AND tp.created < vParked
AND t.packages <=> 0);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -71004,7 +68695,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
@@ -71014,7 +68705,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,
@@ -71025,7 +68716,7 @@ BEGIN
DROP TEMPORARY TABLE
tmp.ticket,
- tmp.ticketTotal;
+ tmp.ticketTotal;
END ;;
DELIMITER ;
@@ -71045,21 +68736,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 */ ;
@@ -71099,7 +68790,7 @@ BEGIN
DECLARE vComponentCost INT;
DECLARE vDone INT DEFAULT FALSE;
DECLARE vClientId INT;
-
+
DECLARE vCursor CURSOR FOR
SELECT DISTINCT clientFk
FROM (
@@ -71116,31 +68807,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))
@@ -71153,7 +68844,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)
@@ -71161,7 +68852,7 @@ BEGIN
AND (tp.quantity < 0 OR (tp.quantity > 0 AND t.shipped < vGraceDate))
AND tp.quantity
AND p.itemFk;
-
+
OPEN vCursor;
l: LOOP
@@ -71174,25 +68865,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
@@ -71200,12 +68891,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;
@@ -71229,37 +68920,37 @@ 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
@@ -71276,9 +68967,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
@@ -71286,7 +68977,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 ;
@@ -71338,11 +69029,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,
@@ -71350,7 +69041,7 @@ BEGIN
vTicketFk,
vBuyerCode,
vn.getUser());
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -71369,26 +69060,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
+
+ SELECT s.alertLevel INTO vAlertLevel
+ FROM state s
+ JOIN ticketStateToday tst ON tst.state = s.id
WHERE tst.ticket = vTicketFk
LIMIT 1;
-
+
IF vAlertLevel < 2 THEN
-
+
CALL vn.ticket_setState(vTicketFk, vStateCode);
-
+
END IF;
END ;;
@@ -71398,34 +69089,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;
@@ -71569,14 +69260,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
@@ -71693,7 +69384,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';
@@ -71716,20 +69407,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 */ ;
@@ -71759,8 +69450,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;
@@ -71777,7 +69467,7 @@ BEGIN
SELECT itemFk, quantity
FROM itemEntryIn
WHERE landed >= vDateInventory
- AND landed < vDateFuture
+ AND landed <= vDateToAdvance
AND isVirtualStock = FALSE
AND warehouseInFk = vWarehouseFk
UNION ALL
@@ -71806,15 +69496,24 @@ 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,
@@ -71822,7 +69521,6 @@ BEGIN
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,
@@ -71830,7 +69528,13 @@ BEGIN
SUM((s.quantity <= IFNULL(st.amount,0))) hasStock,
z.id futureZoneFk,
z.name futureZoneName,
- st.classColor
+ 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
@@ -71846,10 +69550,9 @@ BEGIN
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,
@@ -71857,7 +69560,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
@@ -71871,7 +69582,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 ;;
@@ -71913,6 +69624,7 @@ BEGIN
t.warehouseFk,
ts.alertLevel,
t.shipped,
+ t.totalWithVat,
sub2.shipped futureShipped,
t.workerFk,
st.code stateCode,
@@ -71979,7 +69691,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
@@ -72044,14 +69756,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
@@ -72060,10 +69772,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
@@ -72078,9 +69790,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
@@ -72091,10 +69803,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 */ ;
@@ -72102,14 +69814,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
@@ -72164,8 +69876,8 @@ BEGIN
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;
@@ -72185,14 +69897,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;
@@ -72204,19 +69915,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
@@ -72224,36 +69937,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;
@@ -72274,8 +69982,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,
@@ -72294,7 +70002,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;
@@ -72324,7 +70032,7 @@ BEGIN
buyed,
requesterFk,
attenderFk,
- vNewTicket
+ vNewTicket
FROM ticketRequest
WHERE ticketFk =vTicketFk;
@@ -72339,26 +70047,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
@@ -72366,8 +70074,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');
@@ -72387,6 +70095,7 @@ BEGIN
END;
END LOOP;
CLOSE rsTicket;
+ DROP TEMPORARY TABLE IF EXISTS tmp.time;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -72406,7 +70115,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
@@ -72424,7 +70133,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;
@@ -72434,7 +70143,7 @@ BEGIN
proc: LOOP
SET vDone = FALSE;
-
+
FETCH cur INTO vCurTicketFk;
IF vDone THEN
@@ -72451,12 +70160,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
@@ -72466,22 +70175,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
@@ -72489,10 +70198,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);
@@ -72550,35 +70259,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
@@ -72593,29 +70302,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,
@@ -72636,23 +70345,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 ;;
@@ -72673,7 +70380,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentPreview`(
vTicketFk INT,
- vLanded DATE,
+ vLanded DATE,
vAddressFk INT,
vZoneFk INT,
vWarehouseFk SMALLINT)
@@ -72689,7 +70396,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;
@@ -72700,8 +70407,8 @@ BEGIN
DECLARE vHasChangeAll BOOL DEFAULT FALSE;
- SELECT DATE(landed) <> vLanded,
- addressFk <> vAddressFk,
+ SELECT DATE(landed) <> vLanded,
+ addressFk <> vAddressFk,
zoneFk <> vZoneFk,
warehouseFk <> vWarehouseFk
INTO
@@ -72724,15 +70431,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,
@@ -72752,9 +70459,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))));
@@ -72833,55 +70540,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 */ ;
@@ -72899,91 +70610,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 */ ;
@@ -73216,37 +70927,37 @@ BEGIN
* @param vTicketFk -> Ticket
* @param vDatedNew -> Nueva fecha
* @return Sales con Movible
-*/
+*/
DECLARE vDatedOld DATETIME;
SET vDatedNew = DATE_ADD(vDatedNew, INTERVAL 1 DAY);
SELECT t.shipped INTO vDatedOld
- FROM ticket t
+ FROM ticket t
WHERE t.id = vTicketFk;
- CALL item_getStock(vWarehouseFk, vDatedNew, NULL);
+ CALL item_getStock(vWarehouseFk, vDatedNew, NULL);
CALL item_getMinacum(vWarehouseFk, vDatedNew, DATEDIFF(DATE_SUB(vDatedOld, INTERVAL 1 DAY), vDatedNew), NULL);
-
- SELECT s.id,
- s.itemFk,
- s.quantity,
- s.concept,
- s.price,
+
+ SELECT s.id,
+ s.itemFk,
+ s.quantity,
+ s.concept,
+ s.price,
s.reserved,
- s.discount,
- i.image,
- i.subName,
+ 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
+ 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;
- DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum;
-
+ DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -73274,7 +70985,7 @@ BEGIN
*/
CALL sale_getProblems(vIsTodayRelative);
- CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_problems
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_problems
(PRIMARY KEY (ticketFk))
ENGINE = MEMORY
SELECT ticketFk,
@@ -73346,16 +71057,32 @@ BEGIN
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 itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
+ 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
@@ -73365,26 +71092,28 @@ BEGIN
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
+ 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 itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
+ 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 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
@@ -73392,20 +71121,23 @@ BEGIN
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 itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk
+ 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 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),
@@ -73420,18 +71152,18 @@ BEGIN
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,
+ 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
+ LEFT JOIN zone z ON z.id = t.zoneFk
GROUP BY ss.ticketFk;
- SELECT ts.*,
+ SELECT ts.*,
t.id ticketFuture,
st.name state,
zc.`hour` tfEtd,
@@ -73442,22 +71174,24 @@ BEGIN
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
+ 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 ticketState tst ON tst.ticketFk = t.id
LEFT JOIN state st2 ON st2.id = tst.stateFk
- WHERE (t.id IS NULL
+ 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;
+
+ DROP TEMPORARY TABLE
+ tTicketsToSplit,
+ tItemShelvingStock_byWarehouse;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -73493,7 +71227,7 @@ BEGIN
JOIN ticket t ON t.id = tmpTicket.ticketFk;
CALL addressTaxArea ();
-
+
IF vTaxArea IS NOT NULL THEN
UPDATE tmp.addressTaxArea
SET areaFk = vTaxArea;
@@ -73565,8 +71299,8 @@ BEGIN
CREATE 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
@@ -73646,11 +71380,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
)
@@ -73664,8 +71398,8 @@ BEGIN
* @param vAddressFk Consignatario
* @param vCompanyFk Empresa
* @param vAgencyModeFk agencia
- */
-
+ */
+
SELECT t.id INTO vTicketFk
FROM vn.ticket t
WHERE t.clientFk <=> vClientFk
@@ -73675,7 +71409,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,
@@ -73715,24 +71449,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 ;
@@ -73752,14 +71486,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
@@ -73768,26 +71502,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;
@@ -73810,7 +71544,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.
@@ -73818,18 +71552,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,
@@ -73863,12 +71597,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;
@@ -73894,16 +71628,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
/**
@@ -73956,14 +71690,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
@@ -73983,7 +71717,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 ;
@@ -74047,14 +71781,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
@@ -74079,7 +71813,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
@@ -74127,14 +71861,14 @@ BEGIN
ORDER BY tt.created DESC
LIMIT 1;
- SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED';
+ 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' OR
+ vStateCode <> 'ON_CHECKING' OR
vticketAlertLevel < vPackedAlertLevel
)AND NOT (
vTicketStateCode IN ('CHECKED', 'CHECKING')
@@ -74142,11 +71876,11 @@ BEGIN
);
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;
@@ -74186,40 +71920,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
@@ -74231,19 +71964,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 */ ;
@@ -74351,7 +72083,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
@@ -74381,43 +72113,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 */ ;
@@ -74448,7 +72180,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
@@ -74457,9 +72189,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
@@ -74480,7 +72212,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 */ ;
@@ -74599,18 +72331,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 */ ;
@@ -74630,21 +72362,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`;
@@ -74669,19 +72401,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 ;;
@@ -74708,14 +72440,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 ;;
@@ -74725,32 +72457,32 @@ 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 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `timeControl_calculate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = 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 */ ;
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),
+ * 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
+ * @param vDatedTo
*
- * @return tmp.timeControlCalculate
+ * @return tmp.timeControlCalculate
* (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed)
*/
DECLARE vHourSeconds INTEGER;
@@ -74882,7 +72614,7 @@ BEGIN
), accumulated AS (
SELECT SUM(IF(isOdd, 0, gapTime))
OVER (PARTITION BY userFk,dated ORDER BY userFk,timed) accumulatedWorkTime,
- SUM(IF(NOT isOdd OR breakPoint, 0, IFNULL(gapTime, 0)))
+ 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,
@@ -74897,7 +72629,7 @@ BEGIN
SELECT userFk,
dated,
MAX(accumulatedWorkTime) +
- IF(MAX(accumulatedForBreakTime) >= vTimeToBreakTime,
+ IF(MAX(accumulatedForBreakTime) + LEAST(vBreakTime, MAX(accumulatedBreakTime)) >= vTimeToBreakTime,
LEAST(vBreakTime, MAX(accumulatedBreakTime)),
0) timeWorkSeconds
FROM accumulated
@@ -74949,14 +72681,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 */ ;
@@ -74976,21 +72708,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`;
@@ -75015,19 +72747,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 ;;
@@ -75085,12 +72817,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;
@@ -75098,16 +72830,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,
@@ -75118,36 +72850,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;
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
+ DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -75170,7 +72902,7 @@ proc: BEGIN
* deprecated call workerTimeControl_check
*/
CALL vn.workerTimeControl_check(vUserFk,vDated,vTabletFk);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -75226,12 +72958,12 @@ DELIMITER ;
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,
@@ -75239,18 +72971,18 @@ BEGIN
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
+ 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 */ ;
@@ -75306,11 +73038,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 */ ;
@@ -75374,7 +73106,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
@@ -75462,13 +73194,13 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`(
- IN vTravelFk INT,
- IN vDateStart DATE,
+ IN vTravelFk INT,
+ IN vDateStart DATE,
IN vDateEnd DATE,
IN vWarehouseOutFk INT,
- IN vWarehouseInFk INT,
- IN vRef VARCHAR(255),
- IN vAgencyModeFk INT,
+ IN vWarehouseInFk INT,
+ IN vRef VARCHAR(255),
+ IN vAgencyModeFk INT,
OUT vNewTravelFk INT)
BEGIN
/**
@@ -75492,29 +73224,29 @@ BEGIN
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
+ BEGIN
ROLLBACK;
RESIGNAL;
END;
-
+
START TRANSACTION;
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;
@@ -75556,36 +73288,36 @@ DELIMITER ;
/*!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');
+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 */ ;
@@ -75612,10 +73344,10 @@ 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
+ 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 ;
@@ -75638,7 +73370,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);
@@ -75650,7 +73382,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
@@ -75658,19 +73390,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;
@@ -75728,7 +73460,7 @@ proc: BEGIN
IF vSelf IS NULL THEN
LEAVE proc;
END IF;
-
+
INSERT IGNORE INTO travelRecalc SET travelFk = vSelf;
END ;;
DELIMITER ;
@@ -75738,6 +73470,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 */ ;
@@ -75754,10 +73580,10 @@ BEGIN
* @param vItemFk id del item
* @param vPacking nuevo packing
*/
-
+
DECLARE vAuctionWarehouseFk INT;
DECLARE vMainWarehouseFk INT;
-
+
SELECT warehouseFk INTO vAuctionWarehouseFk
FROM auctionConfig;
@@ -75817,7 +73643,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;
@@ -75879,12 +73705,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;
@@ -75893,40 +73719,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 ;;
@@ -75949,7 +73775,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `updatePedidosInternos`(vItemFk INT)
BEGIN
UPDATE vn.item SET upToDown = 0 WHERE item.id = vItemFk;
-
+
END ;;
DELIMITER ;
@@ -75977,7 +73803,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;
@@ -76010,7 +73836,7 @@ proc:BEGIN
ROLLBACK;
RESIGNAL;
END;
-
+
SELECT eventEarlyDays INTO vEventEarlyDays
FROM vehicleConfig;
@@ -76028,7 +73854,7 @@ proc:BEGIN
IF NOT vHasEvents THEN
LEAVE proc;
END IF;
-
+
START TRANSACTION;
SELECT util.notification_send('vehicle-event-expired',
@@ -76063,21 +73889,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;
@@ -76090,17 +73916,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;
@@ -76124,17 +73950,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
@@ -76163,13 +73989,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 */ ;
@@ -76233,7 +74059,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;
@@ -76245,17 +74071,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
@@ -76263,23 +74089,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,
@@ -76307,32 +74133,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
@@ -76345,12 +74171,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;
@@ -76421,20 +74247,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 ;
@@ -76458,21 +74284,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;
@@ -76501,12 +74332,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;
@@ -76524,7 +74355,7 @@ BEGIN
END WHILE;
CLOSE rs;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -76588,19 +74419,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;
@@ -76608,57 +74439,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;
@@ -76668,9 +74499,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
@@ -76680,10 +74511,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 ,
@@ -76705,9 +74536,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,
@@ -76721,16 +74552,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,
@@ -76743,7 +74574,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
@@ -76754,8 +74585,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
@@ -76781,8 +74612,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
@@ -76795,7 +74626,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
@@ -76807,8 +74638,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
@@ -76816,7 +74647,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
@@ -76840,12 +74671,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,
@@ -76860,7 +74691,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
@@ -76869,8 +74700,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
@@ -76880,7 +74711,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)
@@ -76910,15 +74741,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 */ ;
@@ -76945,7 +74776,7 @@ BEGIN
*
*/
INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk)
- VALUES(vWorkerFk, vWorkerMistakeTypeFk);
+ VALUES(vWorkerFk, vWorkerMistakeTypeFk);
END ;;
DELIMITER ;
@@ -76968,11 +74799,11 @@ 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 ;
@@ -76998,8 +74829,8 @@ BEGIN
*
*/
-
-
+
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -77048,13 +74879,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 */ ;
@@ -77073,8 +74904,8 @@ DELIMITER ;
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 ;
@@ -77162,73 +74993,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
@@ -77240,44 +75071,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;
@@ -77300,10 +75131,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 */ ;
@@ -77323,7 +75154,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
@@ -77334,27 +75165,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))
@@ -77367,28 +75198,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,
@@ -77396,10 +75227,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
@@ -77409,7 +75240,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))
@@ -77429,12 +75260,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
@@ -77443,24 +75274,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
@@ -77504,14 +75335,14 @@ BEGIN
* 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 vDayMaxTime INTEGER;
DECLARE vDayBreak INT;
DECLARE vShortWeekBreak INT;
DECLARE vLongWeekBreak INT;
@@ -77538,7 +75369,7 @@ BEGIN
WHERE w.id = vWorkerFk;
SELECT `description` INTO vErrorMessage
- FROM workerTimeControlError
+ FROM workerTimeControlError
WHERE `code` = vErrorCode;
IF vErrorMessage IS NULL THEN
@@ -77550,7 +75381,7 @@ BEGIN
' no ha podido fichar por el siguiente problema: ',
vErrorMessage)
INTO vErrorMessage;
-
+
CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage);
END;
@@ -77583,19 +75414,19 @@ BEGIN
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
@@ -77622,7 +75453,7 @@ BEGIN
) THEN
SET vIsError = TRUE;
END IF;
-
+
DROP TEMPORARY TABLE tmp.workerTimeControlDirection;
IF vIsError THEN
SET vErrorCode = 'WRONG_DIRECTION';
@@ -77637,7 +75468,7 @@ BEGIN
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))
@@ -77648,7 +75479,7 @@ BEGIN
SET vErrorCode = 'ODD_WORKERTIMECONTROL';
CALL util.throw(vErrorCode);
END IF;
-
+
-- DESCANSO DIARIO
SELECT timed INTO vLastOut
FROM workerTimeControl
@@ -77657,7 +75488,7 @@ BEGIN
AND timed < vTimed
ORDER BY timed DESC
LIMIT 1;
-
+
SELECT timed INTO vNextIn
FROM workerTimeControl
WHERE userFk = vWorkerFk
@@ -77665,7 +75496,7 @@ BEGIN
AND timed > vTimed
ORDER BY timed ASC
LIMIT 1;
-
+
CASE vDirection
WHEN 'in' THEN
IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN
@@ -77687,7 +75518,7 @@ BEGIN
IF (vDirection IN('in', 'out')) THEN
-- VERIFICA MAXIMO TIEMPO DESDE ENTRADA HASTA LA SALIDA
-
+
SELECT timed INTO vNextOut
FROM workerTimeControl
WHERE userFk = vWorkerFk
@@ -77695,7 +75526,7 @@ BEGIN
AND timed > vTimed
ORDER BY timed ASC
LIMIT 1;
-
+
SELECT direction INTO vNextDirection
FROM workerTimeControl
WHERE userFk = vWorkerFk
@@ -77703,7 +75534,7 @@ BEGIN
AND timed > vTimed
ORDER BY timed ASC
LIMIT 1;
-
+
SELECT direction INTO vLastDirection
FROM workerTimeControl
WHERE userFk = vWorkerFk
@@ -77711,34 +75542,34 @@ BEGIN
AND timed < vTimed
ORDER BY timed ASC
LIMIT 1;
-
- IF (vDirection ='in'
- AND vNextDirection = 'out'
+
+ IF (vDirection ='in'
+ AND vNextDirection = 'out'
AND UNIX_TIMESTAMP(vNextOut) - UNIX_TIMESTAMP(vTimed) > vDayMaxTime) OR
- (vDirection ='out'
+ (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
+ (SELECT timed
+ FROM vn.workerTimeControl
WHERE userFk = vWorkerFk
AND direction IN ('in', 'out')
- AND timed BETWEEN vTimed - INTERVAL (vWeekScope * 2) SECOND
+ AND timed BETWEEN vTimed - INTERVAL (vWeekScope * 2) SECOND
AND vTimed + INTERVAL (vWeekScope * 2) SECOND )
- UNION
+ UNION
(SELECT vTimed)
), wtcGap AS(
SELECT timed,
- TIMESTAMPDIFF(SECOND, LAG(timed) OVER (ORDER BY timed), timed) gap
+ TIMESTAMPDIFF(SECOND, LAG(timed) OVER (ORDER BY timed), timed) gap
FROM wtc
ORDER BY timed
- ), wtcBreak AS(
+ ), wtcBreak AS(
SELECT timed,
IF(IFNULL(gap, 0) > vShortWeekBreak, TRUE, FALSE) hasShortBreak,
IF(IFNULL(gap, 0) > vLongWeekBreak, TRUE, FALSE) hasLongBreak
@@ -77749,21 +75580,21 @@ BEGIN
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
+ )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(vWorkerFk, vTimed, vDirection, vIsManual);
@@ -77792,27 +75623,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;
@@ -77861,7 +75692,7 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_getClockIn`(
- vUserFk INT,
+ vUserFk INT,
vDated DATE)
BEGIN
/**
@@ -77871,9 +75702,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;
@@ -77890,7 +75721,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,
@@ -77910,7 +75741,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),
@@ -77922,18 +75753,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 ;
@@ -77997,45 +75828,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 */ ;
@@ -78063,31 +75894,31 @@ proc: BEGIN
UPDATE vn.workerTimeControl SET direction = 'middle';
/*2- poner los out*/
-UPDATE vn.workerTimeControl wtc
- JOIN
+UPDATE vn.workerTimeControl wtc
+ JOIN
(SELECT userFk,MAX(timed) maxTimed FROM
(SELECT id, userFk, timed, date(timed) dated
- FROM vn.workerTimeControl
- ) sub
+ FROM vn.workerTimeControl
+ ) sub
GROUP BY userFk,dated
)sub
SET direction = "out"
- WHERE wtc.userFk = sub.userFk
+ WHERE wtc.userFk = sub.userFk
AND wtc.timed = sub.maxTimed;
-
- /*3- poner los in*/
-UPDATE vn.workerTimeControl wtc
- JOIN
+
+ /*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
+ FROM vn.workerTimeControl
+ ) sub
GROUP BY userFk,dated
)sub
SET direction = "in"
- WHERE wtc.userFk = sub.userFk
- AND wtc.timed = sub.maxTimed ;
-
+ WHERE wtc.userFk = sub.userFk
+ AND wtc.timed = sub.maxTimed ;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -78160,7 +75991,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('
@@ -78252,7 +76083,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 ;;
@@ -78302,9 +76133,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)
@@ -78326,10 +76157,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 ;;
@@ -78367,7 +76198,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;
@@ -78380,16 +76211,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
@@ -78397,18 +76228,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
@@ -78425,29 +76256,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
@@ -78456,9 +76287,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;
@@ -78472,7 +76303,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;
@@ -78502,11 +76333,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;
@@ -78526,46 +76357,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 */ ;
@@ -78591,7 +76406,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 ;;
@@ -78689,8 +76504,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;
@@ -78733,10 +76548,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
@@ -78805,17 +76620,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
@@ -78899,27 +76714,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 ;;
@@ -79013,7 +76828,7 @@ BEGIN
OR (vSelf IS NOT NULL AND parentFk = vSelf);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
SET vSons = 0;
OPEN vChildren;
@@ -79024,11 +76839,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, '/'),
@@ -79131,7 +76946,7 @@ proc: BEGIN
SELECT isChanged INTO vIsChanged
FROM zoneGeoRecalc;
-
+
IF vIsChanged THEN
UPDATE zoneGeoRecalc SET isChanged = FALSE;
CALL vn.zoneGeo_calcTree;
@@ -79387,7 +77202,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,
@@ -79429,7 +77244,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
*
*/
@@ -79438,16 +77253,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);
@@ -79462,7 +77277,7 @@ BEGIN
PRIMARY KEY zoneFkk (zoneFk, geoFk),
INDEX(geoFk))
ENGINE = MyISAM;
-
+
OPEN cur1;
cur1Loop: LOOP
SET vIsDone = FALSE;
@@ -79470,40 +77285,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
@@ -79513,39 +77328,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/sale_checkWithoutComponents.sql b/db/routines/vn/events/sale_checkWithoutComponents.sql
new file mode 100644
index 000000000..2a1ced6ca
--- /dev/null
+++ b/db/routines/vn/events/sale_checkWithoutComponents.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`sale_checkWithoutComponents`
+ ON SCHEDULE EVERY 10 MINUTE
+ STARTS '2020-05-04 11:56:23.000'
+ ON COMPLETION PRESERVE
+ ENABLE
+DO call sale_checkNoComponents(DATE_ADD(util.VN_NOW(), INTERVAL -10 MINUTE),DATE_ADD(util.VN_NOW(), INTERVAL -1 MINUTE))$$
+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..3586dd4ce
--- /dev/null
+++ b/db/routines/vn/functions/addressTaxArea.sql
@@ -0,0 +1,29 @@
+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/.archive/232401/.gitkeep b/db/routines/vn/functions/entry_count
similarity index 100%
rename from db/.archive/232401/.gitkeep
rename to db/routines/vn/functions/entry_count
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..f3b340cfe
--- /dev/null
+++ b/db/routines/vn/functions/getSpecialPrice.sql
@@ -0,0 +1,20 @@
+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 ;
+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..3b96a3d22
--- /dev/null
+++ b/db/routines/vn/functions/hasAnyNegativeBase.sql
@@ -0,0 +1,37 @@
+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)
+*
+* 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 ticket_getTax(NULL);
+
+ SELECT COUNT(*) INTO hasAnyNegativeBase
+ FROM(
+ SELECT SUM(taxableBase) as taxableBase
+ FROM tmp.ticketTax
+ GROUP BY pgcFk
+ HAVING taxableBase < 0
+ ) t;
+
+ DROP TEMPORARY TABLE tmp.ticketTax;
+ DROP TEMPORARY TABLE tmp.ticket;
+
+ RETURN hasAnyNegativeBase;
+
+END$$
+DELIMITER ;
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/isPalletHomogeneus.sql b/db/routines/vn/functions/isPalletHomogeneus.sql
new file mode 100644
index 000000000..39c6461ae
--- /dev/null
+++ b/db/routines/vn/functions/isPalletHomogeneus.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`isPalletHomogeneus`(vExpedition INT)
+ RETURNS tinyint(1)
+ NOT DETERMINISTIC
+ 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 ;
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/nz.sql b/db/routines/vn/functions/nz.sql
new file mode 100644
index 000000000..71c017b78
--- /dev/null
+++ b/db/routines/vn/functions/nz.sql
@@ -0,0 +1,14 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`nz`(vQuantity DOUBLE)
+ RETURNS double
+ DETERMINISTIC
+BEGIN
+
+ DECLARE vResult DOUBLE;
+
+ SET vResult = IFNULL(vQuantity,0);
+
+ RETURN vResult;
+
+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..cfca5945d
--- /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 bank WHERE id = vBank;
+
+ SELECT accountingAccount INTO vSubaccount
+ FROM `client` WHERE id = vClient;
+
+ SET vAsiento = xdiario_new
+ (
+ vAsiento
+ ,vDated
+ ,vAccount
+ ,vSubaccount
+ ,vConcept
+ ,vAmount
+ ,0
+ ,0
+ ,NULL -- Serie
+ ,NULL -- Factura
+ ,NULL -- IVA
+ ,NULL -- Recargo
+ ,FALSE -- Auxiliar
+ ,vCompany
+ );
+ DO xdiario_new
+ (
+ vAsiento
+ ,vDated
+ ,vSubaccount
+ ,vAccount
+ ,vConcept
+ ,0
+ ,vAmount
+ ,0
+ ,NULL -- Serie
+ ,NULL -- Factura
+ ,NULL -- IVA
+ ,NULL -- Recargo
+ ,FALSE -- Auxiliar
+ ,vCompany
+ );
+
+ RETURN NULL;
+END$$
+DELIMITER ;
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/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_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/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/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..6bdc6f759
--- /dev/null
+++ b/db/routines/vn/procedures/bankPolicy_notifyExpired.sql
@@ -0,0 +1,22 @@
+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 ',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
+ 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..92434a47b
--- /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
+ 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, 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..aeeaccb08
--- /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);
+ 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..698328770
--- /dev/null
+++ b/db/routines/vn/procedures/catalog_calculate.sql
@@ -0,0 +1,186 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`catalog_calculate`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT)
+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, FALSE);
+
+ 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..64bb74430
--- /dev/null
+++ b/db/routines/vn/procedures/catalog_componentCalculate.sql
@@ -0,0 +1,294 @@
+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 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 specialPrice sp ON sp.itemFk = i.id
+ AND sp.clientFk = vClientFk
+ LEFT JOIN (
+ SELECT * FROM (
+ SELECT pf.itemFk,
+ pf.`grouping`,
+ pf.packing,
+ pf.box,
+ pf.rate2,
+ pf.rate3,
+ zw.warehouseFk
+ FROM priceFixed pf
+ JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk
+ AND zw.warehouseFk 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 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
+ 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 specialPrice sp ON sp.clientFk = vClientFk AND 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 specialPrice sp ON sp.clientFk = vClientFK AND 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;
+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/.archive/230201/00-kkearSaleChecked.sql b/db/routines/vn/procedures/clean.sql
similarity index 82%
rename from db/.archive/230201/00-kkearSaleChecked.sql
rename to db/routines/vn/procedures/clean.sql
index 3ea107da5..0e60fad1d 100644
--- a/db/.archive/230201/00-kkearSaleChecked.sql
+++ b/db/routines/vn/procedures/clean.sql
@@ -1,25 +1,24 @@
-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`()
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clean`()
BEGIN
DECLARE vDateShort DATETIME;
DECLARE vOneYearAgo DATE;
DECLARE vFourYearsAgo DATE;
+ DECLARE vFiveYearsAgo DATE;
DECLARE v18Month DATE;
DECLARE v26Month DATE;
DECLARE v3Month DATE;
DECLARE vTrashId VARCHAR(15);
+ DECLARE v5Years DATE;
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;
@@ -35,13 +34,18 @@ BEGIN
DELETE FROM sms WHERE created < v18Month;
DELETE FROM saleTracking WHERE created < vOneYearAgo;
DELETE FROM ticketTracking WHERE created < v18Month;
- DELETE tobs FROM ticketObservation tobs
+ 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;
+ 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 < vFourYearsAgo;
DELETE FROM message WHERE sendDate < vDateShort;
-- Robert ubicacion anterior de trevelLog comentario para debug
@@ -52,12 +56,14 @@ BEGIN
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 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;
-- Equipos duplicados
DELETE w.*
FROM workerTeam w
@@ -80,8 +86,9 @@ BEGIN
c.created < vDateShort;
DELETE
FROM vn.expeditionTruck
- WHERE ETD < v3Month;
+ WHERE eta < v3Month;
+ DELETE FROM XDiario WHERE FECHA < v3Month OR FECHA IS NULL;
-- borrar travels sin entradas
DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete;
CREATE TEMPORARY TABLE tmp.thermographToDelete
@@ -107,12 +114,12 @@ BEGIN
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
+ 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
@@ -131,9 +138,9 @@ BEGIN
CREATE TEMPORARY TABLE tmp.routeToDelete
SELECT *
FROM vn.route r
- WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE());
+ WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE());
- UPDATE tmp.routeToDelete tmp
+ UPDATE tmp.routeToDelete tmp
JOIN vn.dms d ON d.id = tmp.gestdocFk
SET d.dmsTypeFk = vTrashId;
@@ -146,7 +153,7 @@ BEGIN
CREATE TEMPORARY TABLE tmp.duaToDelete
SELECT *
FROM vn.dua
- WHERE operated < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
+ WHERE operated < TIMESTAMPADD(YEAR,-2,CURDATE());
UPDATE tmp.duaToDelete tm
JOIN vn.dms d ON d.id = tm.gestdocFk
@@ -169,5 +176,10 @@ BEGIN
CALL shelving_clean;
+ DELETE FROM chat WHERE dated < v5Years;
+
+ DELETE tt FROM ticketTracking tt JOIN vn.ticket t ON tt.ticketFk = t.id
+ WHERE t.shipped <= vDateShort;
+
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..ca8792ba4
--- /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,
+ - (NZ(lc.credit) - NZ(lc.debit))
+ 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/.archive/233202/00-client_create_upper.sql b/db/routines/vn/procedures/client_create.sql
similarity index 100%
rename from db/.archive/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..99b00c6df
--- /dev/null
+++ b/db/routines/vn/procedures/client_getMana.sql
@@ -0,0 +1,56 @@
+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 bank b ON r.bankFk = b.id AND b.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..0918bf1da
--- /dev/null
+++ b/db/routines/vn/procedures/collection_assign.sql
@@ -0,0 +1,88 @@
+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;
+
+ -- 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..d91c63c24
--- /dev/null
+++ b/db/routines/vn/procedures/collection_new.sql
@@ -0,0 +1,328 @@
+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;
+
+ 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
+ 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 `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
+ 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..f6bfc229d
--- /dev/null
+++ b/db/routines/vn/procedures/company_getSuppliersDebt.sql
@@ -0,0 +1,197 @@
+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 vp.isPayment = FALSE;
+
+ 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
+ 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;
+
+ 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..756096e54
--- /dev/null
+++ b/db/routines/vn/procedures/comparative_add.sql
@@ -0,0 +1,60 @@
+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 clientType ct ON ct.id = c.clientTypeFk
+ 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 ct.code <> '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/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/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..77924938b
--- /dev/null
+++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql
@@ -0,0 +1,70 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaInvoiceInBooking`(vDuaFk INT)
+BEGIN
+
+ DECLARE done BOOL DEFAULT FALSE;
+ DECLARE vInvoiceFk INT;
+ DECLARE vASIEN BIGINT DEFAULT 0;
+ DECLARE vCounter INT DEFAULT 0;
+
+ DECLARE rs CURSOR FOR
+ SELECT e.invoiceInFk
+ FROM entry e
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN invoiceIn ii ON ii.id = e.invoiceInFk
+ WHERE de.duaFk = vDuaFk
+ AND de.customsValue
+ AND ii.isBooked = FALSE;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+ OPEN rs;
+
+ UPDATE invoiceIn ii
+ JOIN entry e ON e.invoiceInFk = ii.id
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN dua d ON d.id = de.duaFk
+ SET ii.isBooked = TRUE,
+ ii.booked = IFNULL(ii.booked,d.booked),
+ ii.operated = IFNULL(ii.operated,d.operated),
+ ii.issued = IFNULL(ii.issued,d.issued),
+ ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried),
+ e.isConfirmed = TRUE
+ WHERE d.id = vDuaFk;
+
+ SELECT IFNULL(ASIEN,0) INTO vASIEN
+ FROM dua
+ WHERE id = vDuaFk;
+
+ FETCH rs INTO vInvoiceFk;
+
+ WHILE NOT done DO
+
+ CALL invoiceIn_booking(vInvoiceFk);
+
+ IF vCounter > 0 OR vASIEN > 0 THEN
+
+ UPDATE vn.XDiario x
+ JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN
+ SET x.ASIEN = vASIEN;
+
+ ELSE
+
+ SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig;
+
+ END IF;
+
+ SET vCounter = vCounter + 1;
+
+ FETCH rs INTO vInvoiceFk;
+
+ END WHILE;
+
+ CLOSE rs;
+
+ UPDATE dua
+ SET ASIEN = vASIEN
+ WHERE id = vDuaFk;
+
+END$$
+DELIMITER ;
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_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_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/.archive/232601/00-entry_updateComission.sql b/db/routines/vn/procedures/entry_updateComission.sql
similarity index 96%
rename from db/.archive/232601/00-entry_updateComission.sql
rename to db/routines/vn/procedures/entry_updateComission.sql
index 5a25d72e8..1bef79bd3 100644
--- a/db/.archive/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..949cf4e5b
--- /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.expeditions_id as expeditionFk,
+ date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate,
+ e.ticket_id as ticketFk,
+ t.routeFk as routeFk
+ FROM vn2008.expeditions e
+ INNER JOIN vn.ticket t ON t.id = e.ticket_id
+ WHERE DATE(odbc_date) = 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/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..0def763dc
--- /dev/null
+++ b/db/routines/vn/procedures/inventoryMake.sql
@@ -0,0 +1,265 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryMake`(vDate DATE, vWh INT)
+proc: BEGIN
+/**
+* Recalcula los inventarios de todos los almacenes, si vWh = 0
+*
+* @param vDate Fecha de los nuevos inventarios
+* @param vWh almacen al cual hacer el inventario
+*/
+
+ DECLARE vDone BOOL;
+ DECLARE vEntryFk INT;
+ DECLARE vTravelFk INT;
+ DECLARE vDateLastInventory DATE;
+ DECLARE vDateYesterday DATETIME DEFAULT vDate - INTERVAL 1 SECOND;
+ DECLARE vWarehouseOutFkInventory INT;
+ DECLARE vInventorySupplierFk INT;
+ DECLARE vAgencyModeFkInventory INT;
+
+ DECLARE cWarehouses CURSOR FOR
+ SELECT id
+ FROM warehouse
+ WHERE isInventory
+ AND vWh IN (0,id);
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN cWarehouses;
+ SET @isModeInventory := TRUE;
+ l: LOOP
+
+ SET vDone = FALSE;
+ FETCH cWarehouses INTO vWh;
+
+ 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;
+
+ SELECT id INTO vTravelFk
+ FROM travel
+ WHERE warehouseOutFk = vWarehouseOutFkInventory
+ AND warehouseInFk = vWh
+ AND landed = vDate
+ 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;
+
+ SELECT LAST_INSERT_ID() INTO vTravelFk;
+
+ END IF;
+
+ -- Generamos entrada si no existe, o la vaciamos.
+ SET vEntryFk = 0;
+
+ SELECT id INTO vEntryFk
+ FROM entry
+ WHERE supplierFk = vInventorySupplierFk
+ AND travelFk = vTravelFk;
+
+ IF NOT vEntryFk 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,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)
+ SELECT b.itemFk, SUM(b.quantity)
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ WHERE tr.warehouseInFk = vWh
+ AND tr.landed BETWEEN vDateLastInventory
+ AND vDateYesterday
+ AND NOT isRaid
+ GROUP BY b.itemFk;
+ SELECT vDateLastInventory , vDateYesterday;
+
+ -- Traslados
+ INSERT INTO tmp.inventory(itemFk, quantity)
+ SELECT itemFk, quantityOut
+ FROM (
+ SELECT b.itemFk,- SUM(b.quantity) quantityOut
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ WHERE tr.warehouseOutFk = vWh
+ AND tr.shipped BETWEEN vDateLastInventory
+ AND vDateYesterday
+ AND NOT isRaid
+ GROUP BY b.itemFk
+ ) sub
+ ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut;
+
+ -- Ventas
+ INSERT INTO tmp.inventory(itemFk,quantity)
+ SELECT itemFk, saleOut
+ FROM (
+ SELECT s.itemFk, - SUM(s.quantity) saleOut
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ WHERE t.warehouseFk = vWh
+ AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday
+ GROUP BY s.itemFk
+ ) sub
+ ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut;
+
+ -- Actualiza valores de la ultima compra
+ UPDATE tmp.inventory inv
+ JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh
+ JOIN buy b ON b.id = lb.buy_id
+ 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 tmp.inventory;
+
+ 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;
+
+ END LOOP;
+
+ CLOSE cWarehouses;
+
+ UPDATE config SET inventoried = vDate;
+ SET @isModeInventory := FALSE;
+
+ 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
+ FROM travel t
+ JOIN `entry` e ON e.travelFk = t.id
+ 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);
+
+ DELETE e
+ FROM `entry` e
+ JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id;
+
+ DELETE IGNORE t
+ FROM travel t
+ JOIN tmp.entryToDelete tmp ON tmp.travelId = t.id;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/inventoryMakeLauncher.sql b/db/routines/vn/procedures/inventoryMakeLauncher.sql
new file mode 100644
index 000000000..6f362f70e
--- /dev/null
+++ b/db/routines/vn/procedures/inventoryMakeLauncher.sql
@@ -0,0 +1,11 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryMakeLauncher`()
+BEGIN
+/**
+ * Recalcula los inventarios de todos los almacenes.
+ */
+
+ call vn.inventoryMake(TIMESTAMPADD(DAY, -10, util.VN_CURDATE()), 0);
+
+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..ea65ac37d
--- /dev/null
+++ b/db/routines/vn/procedures/inventory_repair.sql
@@ -0,0 +1,111 @@
+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.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
+ (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.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;
+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..f41504669
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInTaxMakeByDua.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTaxMakeByDua`(vDuaFk INT)
+BEGIN
+
+ DECLARE done BOOL DEFAULT FALSE;
+ DECLARE vInvoiceInFk INT;
+
+ DECLARE rs CURSOR FOR
+ SELECT invoiceInFk
+ FROM entry e
+ JOIN duaEntry de ON de.entryFk = e.id
+ WHERE de.duaFk = vDuaFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+ OPEN rs;
+
+ FETCH rs INTO vInvoiceInFk;
+
+ WHILE NOT done DO
+
+ CALL vn2008.recibidaIvaInsert(vInvoiceInFk);
+ CALL invoiceInDueDay_recalc(vInvoiceInFk);
+
+ FETCH rs INTO vInvoiceInFk;
+
+ END WHILE;
+
+ CLOSE rs;
+
+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..77e989630
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql
@@ -0,0 +1,23 @@
+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;
+
+ 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;
+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..c7574f72f
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInTax_getFromDua.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTax_getFromDua`(vDuaFk INT)
+BEGIN
+
+ DECLARE done BOOL DEFAULT FALSE;
+ DECLARE vInvoiceInFk INT;
+
+ DECLARE rs CURSOR FOR
+ SELECT invoiceInFk
+ FROM entry e
+ JOIN duaEntry de ON de.entryFk = e.id
+ WHERE de.duaFk = vDuaFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+ OPEN rs;
+
+ FETCH rs INTO vInvoiceInFk;
+
+ WHILE NOT done DO
+
+ CALL invoiceInTax_getFromEntries(vInvoiceInFk);
+ CALL invoiceInDueDay_calculate(vInvoiceInFk);
+
+ FETCH rs INTO vInvoiceInFk;
+
+ END WHILE;
+
+ CLOSE rs;
+
+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..14cc43e15
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceInTax_getFromEntries.sql
@@ -0,0 +1,45 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTax_getFromEntries`(IN vId INT)
+BEGIN
+ DECLARE vRate DOUBLE DEFAULT 1;
+ DECLARE vDated DATE;
+ DECLARE vExpenseFk VARCHAR(10);
+
+ SELECT MAX(rr.dated) INTO vDated
+ FROM referenceRate rr
+ JOIN invoiceIn ii ON ii.id = vId
+ 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 = vId;
+
+ 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 = vId
+ HAVING taxableBase IS NOT NULL;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceIn_add.sql b/db/routines/vn/procedures/invoiceIn_add.sql
new file mode 100644
index 000000000..0898d6810
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceIn_add.sql
@@ -0,0 +1,234 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `sage`.`invoiceIn_add`(vInvoiceInFk INT, vXDiarioFk INT)
+BEGIN
+/**
+ * Traslada la info de contabilidad relacionada con las facturas recibidas
+ *
+ * @vInvoiceInFk Factura recibida
+ * @vXDiarioFk Id tabla XDiario
+ */
+ DECLARE vInvoiceInOriginalFk INT;
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vBase DOUBLE;
+ DECLARE vVat DOUBLE;
+ DECLARE vRate DOUBLE;
+ DECLARE vTransactionCode INT;
+ DECLARE vCounter INT DEFAULT 0;
+ DECLARE vTransactionCodeOld INT;
+ DECLARE vTaxCode INT;
+ DECLARE vTaxCodeOld INT;
+ DECLARE vOperationCode VARCHAR(1);
+ DECLARE vIsIntracommunity BOOL DEFAULT FALSE;
+ DECLARE vSerialDua VARCHAR(1) DEFAULT 'D';
+ DECLARE vInvoiceTypeReceived VARCHAR(1);
+ DECLARE vInvoiceTypeInformative VARCHAR(1);
+ DECLARE vIsInformativeExportation BOOL DEFAULT FALSE;
+
+ DECLARE vCursor CURSOR FOR
+ SELECT it.taxableBase,
+ CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)),
+ t.PorcentajeIva,
+ it.transactionTypeSageFk,
+ it.taxTypeSageFk,
+ tty.isIntracommunity,
+ tt.ClaveOperacionDefecto
+ FROM vn.invoiceIn i
+ JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id
+ JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk
+ JOIN taxType tty ON tty.id = t.CodigoIva
+ JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk
+ LEFT JOIN vn.dua d ON d.id = vInvoiceInFk
+ WHERE i.id = vInvoiceInFk
+ AND d.id IS NULL;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DELETE FROM movContaIVA
+ WHERE id = vXDiarioFk;
+
+ SELECT codeSage INTO vInvoiceTypeReceived
+ FROM invoiceType WHERE code ='received';
+
+ SELECT codeSage INTO vInvoiceTypeInformative
+ FROM invoiceType WHERE code ='informative';
+
+ INSERT INTO movContaIVA(id, LibreA1)
+ VALUES (vXDiarioFk, vInvoiceInFk);
+
+ OPEN vCursor;
+
+ l: LOOP
+ FETCH vCursor INTO vBase,
+ vVat,
+ vRate,
+ vTransactionCode,
+ vTaxCode,
+ vIsIntracommunity,
+ vOperationCode;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ SET vTransactionCodeOld = vTransactionCode;
+ SET vTaxCodeOld = vTaxCode;
+
+ IF vOperationCode IS NOT NULL THEN
+ UPDATE movContaIVA
+ SET ClaveOperacionFactura = vOperationCode
+ WHERE id = vXDiarioFk;
+ END IF;
+
+ SET vCounter = vCounter + 1;
+ CASE vCounter
+ WHEN 1 THEN
+ UPDATE movContaIVA
+ SET BaseIva1 = vBase,
+ PorIva1 = vRate,
+ CuotaIva1 = vVat,
+ CodigoTransaccion1 = vTransactionCode,
+ CodigoIva1 = vTaxCode
+ WHERE id = vXDiarioFk;
+
+ WHEN 2 THEN
+ UPDATE movContaIVA
+ SET BaseIva2 = vBase,
+ PorIva2 = vRate,
+ CuotaIva2 = vVat,
+ CodigoTransaccion2 = vTransactionCode,
+ CodigoIva2 = vTaxCode
+ WHERE id = vXDiarioFk;
+ WHEN 3 THEN
+ UPDATE movContaIVA
+ SET BaseIva3 = vBase,
+ PorIva3 = vRate,
+ CuotaIva3 = vVat,
+ CodigoTransaccion3 = vTransactionCode,
+ CodigoIva3 = vTaxCode
+ WHERE id = vXDiarioFk;
+ WHEN 4 THEN
+ UPDATE movContaIVA
+ SET BaseIva4 = vBase,
+ PorIva4 = vRate,
+ CuotaIva4 = vVat,
+ CodigoTransaccion4 = vTransactionCode,
+ CodigoIva4 = vTaxCode
+ WHERE id = vXDiarioFk;
+ ELSE
+ SELECT vXDiarioFk INTO vXDiarioFk;
+ END CASE;
+
+ IF vIsIntracommunity THEN
+ UPDATE movContaIVA
+ SET Intracomunitaria = TRUE
+ WHERE id = vXDiarioFk;
+ END IF;
+
+ SET vTransactionCodeOld = vTransactionCode;
+ SET vTaxCodeOld = vTaxCode;
+
+ END LOOP;
+
+ CLOSE vCursor;
+
+ SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation
+ FROM vn.dua d
+ LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN
+ AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci
+ WHERE d.ASIEN = (
+ SELECT ASIEN
+ FROM vn.XDiario
+ WHERE id = vXDiarioFk)
+ LIMIT 1;
+
+ UPDATE movContaIVA mci
+ JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk
+ JOIN vn.XDiario x ON x.id = mci.id
+ LEFT JOIN tmp.invoiceDua id ON id.id = mci.id
+ JOIN vn.supplier s ON s.id = ii.supplierFk
+ JOIN Naciones n ON n.countryFk = s.countryFk
+ SET mci.CodigoDivisa = ii.currencyFk,
+ mci.Año = YEAR(ii.issued),
+ mci.Serie = ii.serial,
+ mci.Factura = ii.id,
+ mci.FechaFactura = ii.issued,
+ mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) +
+ IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) +
+ IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) +
+ IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0),
+ mci.TipoFactura = IF(id.id,
+ IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative),
+ IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)),
+ mci.CodigoCuentaFactura = x.SUBCTA,
+ mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif),
+ mci.Nombre = s.name,
+ mci.SiglaNacion = n.SiglaNacion,
+ mci.EjercicioFactura = YEAR(ii.issued),
+ mci.FechaOperacion = ii.issued,
+ mci.MantenerAsiento = TRUE,
+ mci.SuFacturaNo = ii.supplierRef,
+ mci.IvaDeducible1 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva1, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
+ mci.IvaDeducible2 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva2, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
+ mci.IvaDeducible3 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva3, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
+ mci.IvaDeducible4 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva4, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
+ mci.FechaFacturaOriginal = x.FECHA_EX
+ WHERE mci.id = vXDiarioFk;
+
+ -- RETENCIONES
+ UPDATE movContaIVA mci
+ JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk
+ JOIN vn.XDiario x ON x.id = mci.id
+ JOIN vn.supplier s ON s.id = supplierFk
+ JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id
+ JOIN vn.expense e ON e.id = iit.expenseFk
+ JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk
+ LEFT JOIN tmp.invoiceDua id ON id.id = mci.id
+ JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase
+ FROM vn.XDiario x1
+ JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN
+ WHERE x2.BASEEURO <> 0
+ AND x1.id = vXDiarioFk
+ )sub
+ JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio'
+ SET mci.CodigoRetencion = t.CodigoRetencion,
+ mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura),
+ mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase),
+ mci.PorRetencion = t.PorcentajeRetencion,
+ mci.ImporteRetencion = iit.taxableBase * - 1
+ WHERE mci.id = vXDiarioFk
+ AND e.name = 'Retenciones'
+ AND id.id IS NULL;
+
+ SELECT correctedFk INTO vInvoiceInOriginalFk
+ FROM vn.invoiceInCorrection
+ WHERE correctingFk = vInvoiceInFk;
+
+ IF vInvoiceInOriginalFk THEN
+
+ UPDATE movContaIVA mci
+ JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk
+ JOIN (SELECT issued,
+ SUM(sub.taxableBase) taxableBase,
+ SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat
+ FROM(SELECT issued,
+ SUM(iit.taxableBase) taxableBase,
+ ti.PorcentajeIva
+ FROM vn.invoiceIn i
+ JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id
+ JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
+ WHERE i.id = vInvoiceInOriginalFk
+ GROUP BY ti.CodigoIva)sub
+ )invoiceInOriginal
+ JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
+ SET mci.TipoRectificativa = iir.refundCategoryFk,
+ mci.ClaseAbonoRectificativas = iir.refundType,
+ mci.FechaFacturaOriginal = invoiceInOriginal.issued,
+ mci.FechaOperacion = invoiceInOriginal.issued,
+ mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase,
+ mci.CuotaIvaOriginal = invoiceInOriginal.vat,
+ mci.ClaveOperacionFactura = co.ClaveOperacionFactura_
+ WHERE mci.id = vXDiarioFk;
+
+ END IF;
+END$$
+DELIMITER ;
\ No newline at end of file
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/.archive/232001/00-invoiceOut_new.sql b/db/routines/vn/procedures/invoiceOut_new.sql
similarity index 90%
rename from db/.archive/232001/00-invoiceOut_new.sql
rename to db/routines/vn/procedures/invoiceOut_new.sql
index 175c31b74..8c35ce75f 100644
--- a/db/.archive/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());
@@ -120,23 +124,37 @@ 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 invoiceExpenseMake(vNewInvoiceId);
- CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
+ CALL invoiceTaxMake(vNewInvoiceId, vTaxArea);
UPDATE invoiceOut io
JOIN (
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..d793841ee
--- /dev/null
+++ b/db/routines/vn/procedures/itemFuentesBalance.sql
@@ -0,0 +1,80 @@
+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 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
+ ) 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
+ AND isVirtualStock = FALSE
+ GROUP BY item_id
+ ) 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
+ ) 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/itemProposal.sql b/db/routines/vn/procedures/itemProposal.sql
new file mode 100644
index 000000000..74d356d77
--- /dev/null
+++ b/db/routines/vn/procedures/itemProposal.sql
@@ -0,0 +1,87 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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,
+ iss.visible located
+ FROM item i
+ JOIN cache.available a ON a.item_id = i.id
+ LEFT JOIN itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk
+ LEFT JOIN itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1
+ LEFT JOIN 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 buy b ON b.id = lb.buy_id
+ LEFT JOIN itemShelvingStock iss ON iss.itemFk = i.id AND iss.warehouseFk = vWarehouseFk
+ 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.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;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemProposal_Add.sql b/db/routines/vn/procedures/itemProposal_Add.sql
new file mode 100644
index 000000000..5a01cb67a
--- /dev/null
+++ b/db/routines/vn/procedures/itemProposal_Add.sql
@@ -0,0 +1,70 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk
+ INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk
+ 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, 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;
+
+ START TRANSACTION;
+
+ UPDATE sale
+ SET quantity = quantity - vQuantity
+ WHERE id = vSaleFk;
+
+ INSERT INTO sale(ticketFk, itemFk, quantity, concept)
+ SELECT vTicketFk,
+ vMateFk,
+ CEIL(vQuantity / vRoundQuantity) * vRoundQuantity,
+ CONCAT('+ ',i.longName)
+ FROM item i
+ WHERE id = vMateFk;
+
+ SELECT LAST_INSERT_ID() INTO vSaleFk;
+
+ CALL sale_calculateComponent(vSaleFk, NULL);
+
+ INSERT INTO itemProposal(itemFk, mateFk, counter)
+ VALUES(vItemFk, vMateFk, 1)
+ ON DUPLICATE KEY UPDATE counter = counter + 1;
+
+ COMMIT;
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/itemProposal_beta.sql b/db/routines/vn/procedures/itemProposal_beta.sql
new file mode 100644
index 000000000..4a6f761a9
--- /dev/null
+++ b/db/routines/vn/procedures/itemProposal_beta.sql
@@ -0,0 +1,76 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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;
+
+END$$
+DELIMITER ;
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..c860d239e
--- /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 item_id itemFk,
+ amount,
+ IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours,
+ IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes
+ FROM vn2008.item_out io
+ JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id
+ JOIN vn.ticket t on t.id= io.ticketFk
+ JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk
+ JOIN vn.state s ON s.id = ts.stateFk
+ LEFT JOIN vn.zone z ON z.id = t.zoneFk
+ LEFT JOIN (SELECT DISTINCT saleFk
+ FROM vn.saleTracking st
+ WHERE st.created > 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 stPrevious.saleFk IS NULL
+ AND io.dat >= util.VN_CURDATE()
+ AND io.dat < 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..02762fa0b
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_add.sql
@@ -0,0 +1,63 @@
+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;
+
+ 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..a232139d3
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_filterBuyer.sql
@@ -0,0 +1,86 @@
+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
+ 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')
+ 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
+ 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')
+ 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..ce2934426
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_inventory.sql
@@ -0,0 +1,62 @@
+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/routines/vn/procedures/itemShelving_selfConsumption.sql b/db/routines/vn/procedures/itemShelving_selfConsumption.sql
new file mode 100644
index 000000000..aa6c34199
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelving_selfConsumption.sql
@@ -0,0 +1,86 @@
+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;
+
+ SELECT c.id,
+ pc.clientSelfConsumptionFk,
+ s.warehouseFk
+ INTO vCompanyFk,
+ vClientFk,
+ vWarehouseFk
+ 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 ON TRUE
+ 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(),
+ NULL,
+ 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..5fe57f2a4
--- /dev/null
+++ b/db/routines/vn/procedures/item_getBalance.sql
@@ -0,0 +1,224 @@
+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`,
+ ct.`code`,
+ 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 clientType ct ON ct.id = c.clientTypeFk
+ 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..b2e3e425c
--- /dev/null
+++ b/db/routines/vn/procedures/item_getLack.sql
@@ -0,0 +1,55 @@
+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
+ 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
+ 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..7cc9ad63e
--- /dev/null
+++ b/db/routines/vn/procedures/item_getSimilar.sql
@@ -0,0 +1,84 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getSimilar`(vItemFk INT, vWarehouseFk INT, vDate DATE, vIsShowedByType 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
+ */
+
+ DECLARE vCalcFk INT;
+ DECLARE vTypeFk INT;
+
+ 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';
+
+ 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
+ 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;
+
+
+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/changes/234601/00-addressShortage.sql b/db/routines/vn/procedures/item_setVisibleDiscard.sql
similarity index 65%
rename from db/changes/234601/00-addressShortage.sql
rename to db/routines/vn/procedures/item_setVisibleDiscard.sql
index 57c07d480..1cc2a8871 100644
--- a/db/changes/234601/00-addressShortage.sql
+++ b/db/routines/vn/procedures/item_setVisibleDiscard.sql
@@ -1,24 +1,4 @@
-
--- Place your SQL code here
-
-ALTER TABLE `vn`.`productionConfig` ADD shortageAddressFk int(11) COMMENT 'Consignatario por defecto para añadir un item de alta';
-ALTER TABLE `vn`.`productionConfig` ADD CONSTRAINT productionConfig_FK FOREIGN KEY (shortageAddressFk) REFERENCES vn.address(id) ON DELETE RESTRICT ON UPDATE CASCADE;
-
-ALTER TABLE `vn`.`sale` MODIFY COLUMN originalQuantity double(9,1) DEFAULT NULL NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity';
-
-INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) VALUES( 'AddressShortage', '*', 'READ', 'ALLOW', 'ROLE', 'production');
-
--- vn.addressShortage definition
-
-CREATE TABLE `vn`.`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;
-
-
DELIMITER $$
-
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDiscard`(
vItemFk INT,
vWarehouseFk INT,
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/.archive/232601/00-packingSiteAdvanced.sql b/db/routines/vn/procedures/packingSite_startCollection.sql
similarity index 60%
rename from db/.archive/232601/00-packingSiteAdvanced.sql
rename to db/routines/vn/procedures/packingSite_startCollection.sql
index 0e33744cd..53edd89f1 100644
--- a/db/.archive/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/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..5e0ce93f0
--- /dev/null
+++ b/db/routines/vn/procedures/productionError_add.sql
@@ -0,0 +1,158 @@
+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
+ 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 ;
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/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_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_checkNoComponents.sql b/db/routines/vn/procedures/sale_checkNoComponents.sql
new file mode 100644
index 000000000..79abbbf92
--- /dev/null
+++ b/db/routines/vn/procedures/sale_checkNoComponents.sql
@@ -0,0 +1,70 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_checkNoComponents`(vCreatedFrom DATETIME, vCreatedTo DATETIME)
+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;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET v_done = TRUE;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.coste;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.coste;
+ CREATE TEMPORARY TABLE tmp.coste
+ (PRIMARY KEY (id)) ENGINE = MEMORY
+ SELECT s.id
+ FROM 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;
+
+ OPEN vCur;
+
+ 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, 'renewPrices');
+ END LOOP;
+
+ CLOSE vCur;
+ DROP TEMPORARY TABLE tmp.coste;
+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..0f2b2bc71
--- /dev/null
+++ b/db/routines/vn/procedures/sale_getBoxPickingList.sql
@@ -0,0 +1,110 @@
+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);
+
+ -- Products with vn.item.isBoxPickingMode = TRUE, pay atention to vn.itemShelving.packing
+ 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 / ish.packing) stickers,
+ ish.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
+ 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 s.quantity BETWEEN ish.packing AND (ish.visible - IFNULL(tISS.reserve,0))
+ AND i.isBoxPickingMode
+ 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;
+
+ -- Remaining products, vn.item.packingOut
+ INSERT IGNORE INTO tmp.sale
+ SELECT
+ s.ticketFk,
+ s.id saleFk,
+ s.itemFk,
+ s.concept,
+ s.quantity,
+ MAKETIME(pb.HH,pb.mm,0) etd,
+ pb.routeFk,
+ s.quantity / i.packingOut stickers,
+ i.packingOut,
+ pc.defaultBigPackageFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemShelving ish ON ish.itemFk = s.itemFk
+ 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 packagingConfig pc
+ LEFT JOIN routesMonitor rm ON rm.routeFk = pb.routeFk
+ LEFT JOIN itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = p.sectorFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk
+ WHERE s.quantity >= i.packingOut
+ AND NOT pb.problem
+ AND s.quantity > 0
+ AND sgd.saleFk IS NULL
+ AND p.sectorFk = vSectorFk
+ AND ts.isPreviousPreparable
+ AND iss.visible >= s.quantity
+ AND ((rm.bufferFk AND rm.isPickingAllowed)
+ OR am.code = 'REC_ALG')
+ AND pb.shipped = vDated
+ GROUP BY s.id
+ ORDER BY etd;
+
+ SELECT * FROM tmp.sale;
+
+ 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..e0cff202f
--- /dev/null
+++ b/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql
@@ -0,0 +1,114 @@
+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
+ 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..aff34d5e9
--- /dev/null
+++ b/db/routines/vn/procedures/sale_replaceItem.sql
@@ -0,0 +1,130 @@
+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.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 ;
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..9e21defc5
--- /dev/null
+++ b/db/routines/vn/procedures/sectorCollectionSaleGroup_add.sql
@@ -0,0 +1,38 @@
+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
+ */
+ 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_get.sql b/db/routines/vn/procedures/sector_get.sql
new file mode 100644
index 000000000..fe978203a
--- /dev/null
+++ b/db/routines/vn/procedures/sector_get.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sector_get`()
+BEGIN
+
+/**
+ * Obtiene los sectores
+*/
+
+ SELECT s.id,s.description,s.warehouseFk
+ FROM vn.sector s;
+
+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..eccbfb9a4
--- /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 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
+ ) 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
+ AND isVirtualStock = FALSE
+ GROUP BY item_id
+ ) 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
+ ) 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/solunionRiskRequest.sql b/db/routines/vn/procedures/solunionRiskRequest.sql
new file mode 100644
index 000000000..b735bea33
--- /dev/null
+++ b/db/routines/vn/procedures/solunionRiskRequest.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`solunionRiskRequest`()
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
+ CREATE TEMPORARY TABLE tmp.client_list
+ (PRIMARY KEY (Id_Cliente))
+ ENGINE = MEMORY
+ SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc
+ JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification
+ WHERE dateEnd IS NULL
+ ORDER BY ci.creationDate DESC
+ LIMIT 10000000000000000000) t1 GROUP BY Id_Cliente;
+
+ CALL vn2008.risk_vs_client_list(util.VN_CURDATE());
+
+ SELECT
+ c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo,
+ cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo,
+ f.Consumo consumo_anual, c.Vencimiento, ci.grade
+ FROM
+ vn2008.Clientes c
+ JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente
+ JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente
+ JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente
+ GROUP BY Id_cliente;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.risk;
+ DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
+END$$
+DELIMITER ;
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..5248b4cec
--- /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,
+ - (NZ(lc.debit) - NZ(lc.credit))
+ 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/test.sql b/db/routines/vn/procedures/test.sql
new file mode 100644
index 000000000..69340291d
--- /dev/null
+++ b/db/routines/vn/procedures/test.sql
@@ -0,0 +1,6 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`test`()
+BEGIN
+select 'procedimiento ejecutado con éxito';
+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..106e0aecc
--- /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);
+ 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..81328bc11
--- /dev/null
+++ b/db/routines/vn/procedures/ticketClon.sql
@@ -0,0 +1,55 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketClon`(vTicketFk INT, vNewShipped DATE)
+BEGIN
+
+ DECLARE done INT DEFAULT FALSE;
+ 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
+ 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 ;
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/changes/234801/00-ticket_canAdvance_update.sql b/db/routines/vn/procedures/ticket_canAdvance.sql
similarity index 99%
rename from db/changes/234801/00-ticket_canAdvance_update.sql
rename to db/routines/vn/procedures/ticket_canAdvance.sql
index afe0a4dc6..8852a3010 100644
--- a/db/changes/234801/00-ticket_canAdvance_update.sql
+++ b/db/routines/vn/procedures/ticket_canAdvance.sql
@@ -1,5 +1,4 @@
DELIMITER $$
-$$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT)
BEGIN
/**
diff --git a/db/.archive/232201/00-procedurecanbePostponed.sql b/db/routines/vn/procedures/ticket_canMerge.sql
similarity index 55%
rename from db/.archive/232201/00-procedurecanbePostponed.sql
rename to db/routines/vn/procedures/ticket_canMerge.sql
index 39aa35cd5..c3f211027 100644
--- a/db/.archive/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/.archive/232202/00-procedurecanbePostponed.sql b/db/routines/vn/procedures/ticket_canbePostponed.sql
similarity index 94%
rename from db/.archive/232202/00-procedurecanbePostponed.sql
rename to db/routines/vn/procedures/ticket_canbePostponed.sql
index 9d42dcc4b..442059b99 100644
--- a/db/.archive/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_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/.archive/224702/00-ticket_closeByTicket.sql b/db/routines/vn/procedures/ticket_closeByTicket.sql
similarity index 58%
rename from db/.archive/224702/00-ticket_closeByTicket.sql
rename to db/routines/vn/procedures/ticket_closeByTicket.sql
index f378b1146..93772225b 100644
--- a/db/.archive/224702/00-ticket_closeByTicket.sql
+++ b/db/routines/vn/procedures/ticket_closeByTicket.sql
@@ -1,35 +1,27 @@
-drop procedure `vn`.`ticket_closeByTicket`;
-
DELIMITER $$
-$$
-create
- definer = `root`@`localhost` procedure `vn`.`ticket_closeByTicket`(IN vTicketFk int)
+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
+ SELECT
t.id AS ticketFk
FROM ticket t
- JOIN agencyMode am ON am.id = t.agencyModeFk
+ 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
+ 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.id = vTicketFk
AND t.refFk IS NULL
GROUP BY t.id);
-
+
CALL ticket_close();
- DROP TEMPORARY TABLE tmp.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..b69fa220a
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_getMovable.sql
@@ -0,0 +1,44 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_getMovable`(vTicketFk INT, vDatedNew 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
+ * asume que siempre es posible
+ *
+ * @param vTicketFk -> Ticket
+ * @param vDatedNew -> Nueva fecha
+ * @return Sales con Movible
+*/
+ DECLARE vDatedOld DATETIME;
+ SET vDatedNew = DATE_ADD(vDatedNew, INTERVAL 1 DAY);
+
+ SELECT t.shipped INTO vDatedOld
+ 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);
+
+ 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;
+ DROP TEMPORARY TABLE IF EXISTS 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..7269a1caf
--- /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.
+ */
+ 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
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
+ CREATE 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 <> 0) t3
+ ORDER BY priority;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketServiceTax;
+ CREATE 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 <> 0;
+
+ 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
+ (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;
+ DROP TEMPORARY TABLE tmp.addressTaxArea;
+END$$
+DELIMITER ;
diff --git a/db/.archive/231201/00-ticket_getWarnings.sql b/db/routines/vn/procedures/ticket_getWarnings.sql
similarity index 58%
rename from db/.archive/231201/00-ticket_getWarnings.sql
rename to db/routines/vn/procedures/ticket_getWarnings.sql
index 5253b58ab..0bda30446 100644
--- a/db/.archive/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/changes/234601/00-ticketSetStateRefactor.sql b/db/routines/vn/procedures/ticket_setState.sql
similarity index 90%
rename from db/changes/234601/00-ticketSetStateRefactor.sql
rename to db/routines/vn/procedures/ticket_setState.sql
index 9078ffb0e..bde8e0692 100644
--- a/db/changes/234601/00-ticketSetStateRefactor.sql
+++ b/db/routines/vn/procedures/ticket_setState.sql
@@ -31,8 +31,8 @@ BEGIN
CALL util.throw('ASSIGN_ZONE_FIRST');
END IF;
- SET vCanChangeState = (
- vStateCode <> 'ON_CHECKING' OR
+ SET vCanChangeState = ((
+ vStateCode <> 'ON_CHECKING' AND vStateCode <> 'CHECKED') OR
vticketAlertLevel < vPackedAlertLevel
)AND NOT (
vTicketStateCode IN ('CHECKED', 'CHECKING')
@@ -40,7 +40,7 @@ BEGIN
);
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;
@@ -51,5 +51,6 @@ BEGIN
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/changes/234004/01-timeControl_calculate.sql b/db/routines/vn/procedures/timeControl_calculate.sql
similarity index 82%
rename from db/changes/234004/01-timeControl_calculate.sql
rename to db/routines/vn/procedures/timeControl_calculate.sql
index 93d88c047..258960265 100644
--- a/db/changes/234004/01-timeControl_calculate.sql
+++ b/db/routines/vn/procedures/timeControl_calculate.sql
@@ -20,17 +20,17 @@ BEGIN
*/
DECLARE vHourSeconds INTEGER;
DECLARE vDatedFromYesterday DATETIME;
- DECLARE vDatedToTomorrow 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
+ FROM workerTimeControlConfig
LIMIT 1;
CALL timeControl_getError(vDatedFromYesterday, vDatedToTomorrow);
@@ -38,13 +38,13 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.workerTimeControl
(INDEX(userFk, timed), INDEX(timed), INDEX(direction))
ENGINE = MEMORY
- SELECT wtc.userFk,
- wtc.timed,
+ 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
+ JOIN tmp.`user` u ON u.userFk = wtc.userFk
LEFT JOIN (
SELECT wtc.userFk, MIN(wtc.timed) firstIn
FROM workerTimeControl wtc
@@ -69,67 +69,67 @@ BEGIN
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))
+ (INDEX(timed))
ENGINE = MEMORY
WITH wtc AS(
SELECT timed,
userFk,
dated,
direction,
- LEAD(dated) OVER
+ LEAD(dated) OVER
(PARTITION BY userFk, dated ORDER BY timed) nextDay,
- LEAD(userFk) OVER
+ 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,
+ ), wtcToinsert AS(
+ SELECT userFk,
dated,
- IF(userFk = nextUserFk
- AND nextDay IS NULL
- AND isOdd
+ 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
+ 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
+ )SELECT userFk, util.dayEnd(dated) timed, 'out' direction
FROM wtcToinsert
WHERE outNextDay
- UNION ALL
+ UNION ALL
SELECT userFk, dated + INTERVAL 1 DAY, 'in'
FROM wtcToinsert
WHERE outNextDay
- UNION ALL
- SELECT userFk, util.dayEnd(dated) - INTERVAL 1 SECOND, 'middle'
+ 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
+ WHERE outNextDayWhitBreak
+ UNION ALL
SELECT userFk, dated + INTERVAL 1 DAY, 'in'
FROM wtcToinsert
WHERE outNextDayWhitBreak
- UNION ALL
+ 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
+ SET @oldrealDay = NULL;
+ CREATE OR REPLACE TEMPORARY TABLE tmp.timeControlCalculate
WITH workerTimed AS (
SELECT
userFk,
@@ -138,32 +138,32 @@ BEGIN
(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)
+ TIMESTAMPDIFF(SECOND, LAG(timed)
OVER (PARTITION BY userFk, dated ORDER BY timed), timed) gapTime,
- ROW_NUMBER()
+ 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))
+ SELECT SUM(IF(isOdd, 0, gapTime))
OVER (PARTITION BY userFk,dated ORDER BY userFk,timed) accumulatedWorkTime,
- SUM(IF(NOT isOdd OR breakPoint, 0, IFNULL(gapTime, 0)))
- OVER (PARTITION BY realDay ORDER BY realDay,timed) accumulatedBreakTime,
- IF(realDay <> @oldrealDay OR (isOdd AND gapTime >= vMaxTimeToBreak),
+ 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 +
+ @accumulatedForBreakTime := @accumulatedForBreakTime +
IF(isOdd, 0, gapTime )) accumulatedForBreakTime,
@oldrealDay := realDay,
userFk,
dated,
realDay
FROM workerTimed
- ), totalWorked AS (
+ ), totalWorked AS (
SELECT userFk,
dated,
- MAX(accumulatedWorkTime) +
- IF(MAX(accumulatedForBreakTime) >= vTimeToBreakTime,
- LEAST(vBreakTime, MAX(accumulatedBreakTime)),
+ MAX(accumulatedWorkTime) +
+ IF(MAX(accumulatedForBreakTime) + LEAST(vBreakTime, MAX(accumulatedBreakTime)) >= vTimeToBreakTime,
+ LEAST(vBreakTime, MAX(accumulatedBreakTime)),
0) timeWorkSeconds
FROM accumulated
GROUP BY userFk, dated
@@ -177,7 +177,7 @@ BEGIN
JOIN (
SELECT userFk,
dated,
- GROUP_CONCAT(DATE_FORMAT(timed, "%H:%i") ORDER BY timed ASC
+ GROUP_CONCAT(DATE_FORMAT(timed, "%H:%i") ORDER BY timed ASC
SEPARATOR ' - ')tableTimed
FROM tmp.workerTimeControl
WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
@@ -186,9 +186,9 @@ BEGIN
)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 ;
\ No newline at end of file
+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..840152c44
--- /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 fecha 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 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
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ 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;
+
+ COMMIT;
+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_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/changes/234004/02-workerTimeControl_clockIn.sql b/db/routines/vn/procedures/workerTimeControl_clockIn.sql
similarity index 89%
rename from db/changes/234004/02-workerTimeControl_clockIn.sql
rename to db/routines/vn/procedures/workerTimeControl_clockIn.sql
index 69091e51c..23739a515 100644
--- a/db/changes/234004/02-workerTimeControl_clockIn.sql
+++ b/db/routines/vn/procedures/workerTimeControl_clockIn.sql
@@ -2,21 +2,23 @@ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_clockIn`(
vWorkerFk INT,
vTimed DATETIME,
- vDirection VARCHAR(10)
+ vDirection VARCHAR(10),
+ vDevice VARCHAR(255)
)
BEGIN
/**
- * Verifica si el empleado puede fichar
- * @param vWorkerFk 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 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;
@@ -269,18 +271,18 @@ BEGIN
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(vWorkerFk, vTimed, vDirection, vIsManual);
+
+ -- Se permite fichar
+ INSERT INTO workerTimeControl(userFk, timed, direction, device, `manual`)
+ VALUES(vWorkerFk, vTimed, vDirection, vDevice, vIsManual);
SELECT LAST_INSERT_ID() id;
END$$
-DELIMITER ;
\ No newline at end of file
+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
+ ')
+ FROM tmp.reportHours rh
+ JOIN account.emailUser eu ON rh.id = eu.userFk
+ GROUP BY rh.id;
+
+ DROP TEMPORARY TABLE tmp.timeControlCalculate;
+ DROP TEMPORARY TABLE tmp.timeBusinessCalculate;
+ DROP TEMPORARY TABLE tmp.reportHours;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_sendMailByDepartmentLauncher.sql b/db/routines/vn/procedures/workerTimeControl_sendMailByDepartmentLauncher.sql
new file mode 100644
index 000000000..406bb8d8d
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_sendMailByDepartmentLauncher.sql
@@ -0,0 +1,12 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_sendMailByDepartmentLauncher`()
+BEGIN
+ DECLARE vDatedFrom, vDatedTo DATETIME;
+
+ IF (DAYNAME(util.VN_CURDATE()) = 'miércoles') THEN
+ SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL 9 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(), INTERVAL 3 DAY), ' 23:59:59') INTO vDatedFrom, vDatedTo;
+
+ CALL vn.workerTimeControl_sendMailByDepartment(vDatedFrom, vDatedTo, NULL);
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_weekCheckBreak.sql b/db/routines/vn/procedures/workerTimeControl_weekCheckBreak.sql
new file mode 100644
index 000000000..70ef3da07
--- /dev/null
+++ b/db/routines/vn/procedures/workerTimeControl_weekCheckBreak.sql
@@ -0,0 +1,36 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_weekCheckBreak`(vStarted DATE, vEnded DATE)
+BEGIN
+/**
+ * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas
+ * El sistema verificará el descanso corto en la siguiente semana
+ * o el largo en las 2 siguientes semanas a partir de las fechas dadas
+ * @param vStarted día inicio para verificar
+ * @param vEnded día final para verificar
+ * @return tmp.workerWithoutWeekBreak (workerFk)
+ */
+ DECLARE vDone INT DEFAULT FALSE;
+
+ IF(vStarted > vEnded) then
+ CALL util.throw ('Date end can not be greater then start');
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreakInWeek;
+ CREATE TEMPORARY TABLE tmp.workerWithoutWeekBreakInWeek
+ (workerFk INT,
+ PRIMARY KEY(workerFk))
+ ENGINE = MEMORY;
+
+
+ WHILE vStarted <= vEnded DO
+
+ CALL workerTimeControl_checkBreak(vStarted);
+ INSERT IGNORE INTO tmp.workerWithoutWeekBreakInWeek
+ SELECT workerFk
+ FROM tmp.workerWithoutWeekBreak;
+ DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreak;
+ SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY);
+
+ END WHILE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workerWeekControl.sql b/db/routines/vn/procedures/workerWeekControl.sql
new file mode 100644
index 000000000..8001d8d3a
--- /dev/null
+++ b/db/routines/vn/procedures/workerWeekControl.sql
@@ -0,0 +1,133 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerWeekControl`(vUserFk INT, vDated DATE, vTabletFk VARCHAR(100))
+BEGIN
+/*
+* Devuelve la cantidad de descansos de 12h y de 36 horas que ha disfrutado el trabajador
+* en la semana inmediatamente anterior a la fecha que pasa como parámetro.
+* UPDATED PAK 2019/09/02
+* PENDING REVIEW
+*/
+ DECLARE vDescansos12h INT;
+ DECLARE vDescansos36h INT;
+ DECLARE vJornadas INT;
+ DECLARE vImpares INT;
+ DECLARE vHasSignedToday BOOLEAN;
+ DECLARE v12hoursInMinutes INT DEFAULT 719;
+ DECLARE v36hoursInMinutes INT DEFAULT 2159;
+ DECLARE vCantWork VARCHAR(50) DEFAULT '';
+ DECLARE vDepartmentFk INT;
+ DECLARE isEnabled BOOLEAN DEFAULT TRUE;
+
+ SELECT COUNT(*) INTO vHasSignedToday
+ FROM workerTimeControl WHERE timed >= vDated AND userFk = vUserFk;
+
+ SET @day := 0;
+ SET @lastTimed := util.VN_NOW();
+
+ SELECT SUM(IF(interval_in_minutes >= v12hoursInMinutes,1,0)), SUM(FLOOR(interval_in_minutes/ v36hoursInMinutes)) , SUM(jornadas)
+ INTO vDescansos12h, vDescansos36h, vJornadas
+ FROM
+ (
+ SELECT fichada_anterior, fichada_actual, interval_in_minutes, jornadas
+ FROM
+ (
+ SELECT @lastTimed fichada_anterior,
+ timed,
+ CAST(time_to_sec(timediff(timed,@lastTimed )) / 60 AS UNSIGNED) as interval_in_minutes,
+ IF(day(timed) != @day, 1, 0) as jornadas,
+ @day := day(timed) dia_del_mes,
+ @lastTimed := timed fichada_actual
+ FROM
+ (
+ SELECT day(timed) as dayNumber, dayname(timed) as dayName, timed
+ FROM
+ (SELECT TIMESTAMPADD(DAY, -11, util.VN_NOW()) as timed, vUserFk as userFk -- Fichada virtual para los en los que no se ha trabajado la semana anterior
+ UNION ALL
+ SELECT timed, userFk
+ FROM vn.workerTimeControl wtc
+ WHERE userFk = vUserFk
+ AND timed >= TIMESTAMPADD(DAY, -10,vDated)
+ UNION ALL
+ SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk
+ ) sub4
+ ORDER BY timed
+ ) sub
+
+ ) sub2
+ WHERE fichada_actual >= TIMESTAMPADD(WEEK, -1, vDated)
+ ) sub3 ;
+
+ SELECT IFNULL(SUM(impar),0) into vImpares
+ FROM (
+ SELECT day(timed) as dayNumber,
+ count(*) mod 2 as impar
+ FROM vn.workerTimeControl wtc
+ WHERE userFk = vUserFk
+ AND timed >= TIMESTAMPADD(WEEK, -1,vDated) AND timed < vDated
+ GROUP BY dayNumber
+ ) sub;
+
+ -- Vacaciones
+ SELECT at2.name INTO vCantWork
+ FROM calendar c
+ JOIN business b ON b.id = c.businessFk
+ JOIN absenceType at2 ON at2.id = c.dayOffTypeFk
+ WHERE c.dated = util.VN_CURDATE()
+ AND at2.isAllowedToWork = FALSE
+ AND b.workerFk = vUserFk
+ LIMIT 1;
+
+ -- Contrato en vigor
+ SELECT IF(COUNT(*),vCantWork,'Sin contrato') INTO vCantWork
+ FROM business b
+ WHERE b.workerFk = vUserFk
+ AND b.started <= vDated
+ AND IFNULL(b.ended, vDated) >= vDated;
+
+ -- Departamento si vTabletFk es 0 no hacemos comprobacion (Madrid y Vilassar)
+ IF vTabletFk <> '0' THEN
+ -- 1 Obtener el departamento del usuario
+ SELECT wtcu.departmentFk INTO vDepartmentFk
+ FROM workerTimeControlUserInfo wtcu
+ WHERE wtcu.userFk = vUserFk;
+ -- 2 Comprobar si la tablet pertenece al departamento
+ SELECT COUNT(td.tabletFk) INTO isEnabled
+ FROM tabletDepartment td
+ WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk;
+
+ END IF;
+
+ IF vJornadas IS NOT NULL THEN
+
+ SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis
+ UNION ALL
+ SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, IF(vDescansos12h >= vJornadas, 'Correcto','Error: 1 por jornada') as Análisis
+ UNION ALL
+ SELECT 'Descansos 36 h' as Item, vDescansos36h as Cantidad, IF(vDescansos36h / 2 >= FLOOR(vJornadas/10), 'Correcto','Error: mínimo 2 cada 14 dias') as Análisis
+ UNION ALL
+ SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, IF(vImpares = 0, 'Correcto','Error') as Análisis
+ UNION ALL
+ SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item,
+ '' as Cantidad,
+ IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis
+ UNION ALL
+ SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis;
+
+ ELSE
+
+ SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis
+ UNION ALL
+ SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, 'Correcto' as Análisis
+ UNION ALL
+ SELECT 'Descansos 36 h' as Item, vDescansos36h as Cantidad, 'Correcto' as Análisis
+ UNION ALL
+ SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, 'Correcto' as Análisis
+ UNION ALL
+ SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item,
+ '' as Cantidad, IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis
+ UNION ALL
+ SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis;
+
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/worker_getFromHasMistake.sql b/db/routines/vn/procedures/worker_getFromHasMistake.sql
new file mode 100644
index 000000000..052097e79
--- /dev/null
+++ b/db/routines/vn/procedures/worker_getFromHasMistake.sql
@@ -0,0 +1,19 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_getFromHasMistake`(vDepartmentFk INT)
+BEGIN
+
+/**
+ * Obtiene los trabajadores de los departamentos que se les puede poner error
+ * @param vDepartmentFk id del departamento
+ *
+ */
+
+ SELECT w.id,w.firstName, w.lastName,d.name
+ FROM worker w
+ JOIN workerDepartment wd ON wd.workerFk = w.id
+ JOIN department d ON d.id = wd.departmentFk
+ WHERE d.id = vDepartmentFk
+ ORDER BY firstName;
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/worker_getHierarchy.sql b/db/routines/vn/procedures/worker_getHierarchy.sql
new file mode 100644
index 000000000..de6956898
--- /dev/null
+++ b/db/routines/vn/procedures/worker_getHierarchy.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_getHierarchy`(vUserFk INT)
+BEGIN
+/**
+ * Retorna una tabla temporal con los trabajadores que tiene
+ * el usuario por debajo en la jerarquía de la empresa.
+ *
+ * @param vUserFk Id de usuario.
+ * @return tmp.workerHierarchyList
+ */
+ CREATE OR REPLACE TEMPORARY TABLE tmp.workerHierarchyList
+ (PRIMARY KEY (workerFk))
+ ENGINE = MEMORY
+ WITH RECURSIVE workerHierarchy AS (
+ SELECT id workerFk, bossFk, 0 depth
+ FROM vn.worker
+ WHERE id = vUserFk
+ UNION ALL
+ SELECT w.id, w.bossFk, wh.depth + 1
+ FROM vn.worker w
+ JOIN workerHierarchy wh ON w.bossFk = wh.workerFk
+ )
+ SELECT *
+ FROM workerHierarchy
+ ORDER BY depth, workerFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/worker_getSector.sql b/db/routines/vn/procedures/worker_getSector.sql
new file mode 100644
index 000000000..759bb839b
--- /dev/null
+++ b/db/routines/vn/procedures/worker_getSector.sql
@@ -0,0 +1,15 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_getSector`()
+BEGIN
+
+/**
+ * Obtiene el sector del usuario conectado
+*/
+
+ SELECT s.id,s.description,s.warehouseFk
+ FROM sector s
+ JOIN operator o ON o.sectorFk = s.id
+ WHERE o.workerFk = account.myUser_getId();
+
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/worker_updateBalance.sql b/db/routines/vn/procedures/worker_updateBalance.sql
new file mode 100644
index 000000000..c1fd0adf7
--- /dev/null
+++ b/db/routines/vn/procedures/worker_updateBalance.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_updateBalance`(vSelfFk INT(11), vCredit DECIMAL(10,2), vDebit DECIMAL(10,2))
+BEGIN
+/**
+ * Actualiza la columna balance de worker.
+ *
+ * @param selfFk, credit, debit
+ */
+ UPDATE worker
+ SET balance = IFNULL(balance, 0) + IFNULL(vCredit, 0) - IFNULL(vDebit, 0)
+ WHERE id = vSelfFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/worker_updateBusiness.sql b/db/routines/vn/procedures/worker_updateBusiness.sql
new file mode 100644
index 000000000..274bc3ec0
--- /dev/null
+++ b/db/routines/vn/procedures/worker_updateBusiness.sql
@@ -0,0 +1,28 @@
+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())
+ LIMIT 1;
+
+ UPDATE worker
+ SET businessFk = vNewBusinessFk
+ WHERE id = vSelf;
+
+ IF vOldBusinessFk IS NULL THEN
+ CALL account.account_enable(vSelf);
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/worker_updateChangedBusiness.sql b/db/routines/vn/procedures/worker_updateChangedBusiness.sql
new file mode 100644
index 000000000..05e68b099
--- /dev/null
+++ b/db/routines/vn/procedures/worker_updateChangedBusiness.sql
@@ -0,0 +1,40 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_updateChangedBusiness`()
+BEGIN
+/**
+ * Actualiza el contrato actual de todos los trabajadores cuyo contracto ha
+ * empezado/vencido.
+ */
+ DECLARE vBusinessUpdated DATE;
+ DECLARE vCurdate DATE DEFAULT util.VN_CURDATE();
+ DECLARE vWorkerFk INT;
+ DECLARE vDone BOOL;
+
+ DECLARE vCursor CURSOR FOR
+ SELECT DISTINCT b.workerFk
+ FROM business b
+ WHERE b.started > vBusinessUpdated AND b.started <= vCurdate
+ OR b.ended >= vBusinessUpdated AND b.ended < vCurdate;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SELECT businessUpdated INTO vBusinessUpdated
+ FROM workerConfig;
+
+ OPEN vCursor;
+
+ l: LOOP
+ SET vDone = FALSE;
+
+ FETCH vCursor INTO vWorkerFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL worker_updateBusiness(vWorkerFk);
+ END LOOP;
+
+ UPDATE workerConfig SET businessUpdated = vCurdate;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workingHours.sql b/db/routines/vn/procedures/workingHours.sql
new file mode 100644
index 000000000..c08226db7
--- /dev/null
+++ b/db/routines/vn/procedures/workingHours.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workingHours`(username varchar(255), logon boolean)
+BEGIN
+ DECLARE userid int(11);
+
+ SELECT vn.getUserId(username) INTO userid;
+ SELECT username, userid;
+ IF userid IS NOT NULL THEN
+ IF (logon) THEN
+ CALL vn.workingHoursTimeIn(userid);
+ ELSE
+ CALL vn.workingHoursTimeOut(userid);
+ END IF;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workingHoursTimeIn.sql b/db/routines/vn/procedures/workingHoursTimeIn.sql
new file mode 100644
index 000000000..8a4268c54
--- /dev/null
+++ b/db/routines/vn/procedures/workingHoursTimeIn.sql
@@ -0,0 +1,7 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workingHoursTimeIn`(vUserId INT(11))
+BEGIN
+ INSERT INTO vn.workingHours (timeIn, userId)
+ VALUES (util.VN_NOW(),vUserId);
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/workingHoursTimeOut.sql b/db/routines/vn/procedures/workingHoursTimeOut.sql
new file mode 100644
index 000000000..f6ce2886c
--- /dev/null
+++ b/db/routines/vn/procedures/workingHoursTimeOut.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workingHoursTimeOut`(vUserId INT(11))
+BEGIN
+ UPDATE vn.workingHours
+ SET timeOut = util.VN_NOW()
+ WHERE userId = vUserId
+ AND DATE(timeIn) = util.VN_CURDATE();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/wrongEqualizatedClient.sql b/db/routines/vn/procedures/wrongEqualizatedClient.sql
new file mode 100644
index 000000000..47a6a608d
--- /dev/null
+++ b/db/routines/vn/procedures/wrongEqualizatedClient.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`wrongEqualizatedClient`()
+BEGIN
+ SELECT clientFk, c.name, c.isActive, c.isTaxDataChecked, count(ie) as num
+ FROM vn.client c
+ JOIN
+ (
+ SELECT DISTINCT
+ `a`.`clientFk` ,
+ a.isEqualizated = 0 as ie
+
+ FROM
+ `vn`.`address` `a`
+ ) sub ON sub.clientFk = c.id
+ WHERE c.hasToInvoiceByAddress = FALSE
+
+ GROUP BY clientFk
+ HAVING num > 1
+ UNION ALL
+ SELECT DISTINCT c.id, c.name, c.isActive, c.isTaxDataChecked,1
+ FROM
+ `vn`.`address` `a`
+ JOIN `vn`.`client` `c` ON `c`.`id` = `a`.`clientFk`
+ WHERE ABS(a.isEqualizated) <> ABS(c.isEqualizated)
+ AND c.hasToInvoiceByAddress = FALSE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zoneClosure_recalc.sql b/db/routines/vn/procedures/zoneClosure_recalc.sql
new file mode 100644
index 000000000..9e51c007d
--- /dev/null
+++ b/db/routines/vn/procedures/zoneClosure_recalc.sql
@@ -0,0 +1,47 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneClosure_recalc`()
+proc: BEGIN
+/**
+ * Recalculates the delivery time (hour) for every zone in days + scope in future
+ */
+ DECLARE vScope INT;
+ DECLARE vCounter INT DEFAULT 0;
+ DECLARE vShipped DATE DEFAULT util.VN_CURDATE();
+
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ DO RELEASE_LOCK('vn.zoneClosure_recalc');
+ RESIGNAL;
+ END;
+
+ IF NOT GET_LOCK('vn.zoneClosure_recalc', 0) THEN
+ LEAVE proc;
+ END IF;
+
+ SELECT scope INTO vScope
+ FROM zoneConfig;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.zone;
+ CREATE TEMPORARY TABLE tmp.zone
+ (INDEX (id))
+ ENGINE = MEMORY
+ SELECT id FROM zone;
+
+ TRUNCATE TABLE zoneClosure;
+
+ WHILE vCounter <= vScope DO
+
+ CALL zone_getOptionsForShipment(vShipped, TRUE);
+
+ REPLACE zoneClosure(zoneFk, dated, `hour`)
+ SELECT zoneFk, vShipped, `hour`
+ FROM tmp.zoneOption;
+
+ SET vCounter = vCounter + 1;
+ SET vShipped = TIMESTAMPADD(DAY, 1, vShipped);
+ END WHILE;
+
+ -- DROP TEMPORARY TABLE tmp.zone;
+ DO RELEASE_LOCK('vn.zoneClosure_recalc');
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zoneGeo_calcTree.sql b/db/routines/vn/procedures/zoneGeo_calcTree.sql
new file mode 100644
index 000000000..34e1d8241
--- /dev/null
+++ b/db/routines/vn/procedures/zoneGeo_calcTree.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneGeo_calcTree`()
+BEGIN
+/**
+ * Calculates the #path, #lft, #rgt, #sons and #depth columns of
+ * the #zoneGeo table. To build the tree, it uses the #parentFk
+ * column.
+ */
+ DECLARE vIndex INT DEFAULT 0;
+ DECLARE vSons INT;
+
+ DROP TEMPORARY TABLE IF EXISTS tNestedTree;
+ CREATE TEMPORARY TABLE tNestedTree
+ SELECT id, path, lft, rgt, depth, sons
+ FROM zoneGeo LIMIT 0;
+
+ SET max_sp_recursion_depth = 5;
+ CALL zoneGeo_calcTreeRec(NULL, '/', 0, vIndex, vSons);
+ SET max_sp_recursion_depth = 0;
+
+ UPDATE zoneGeo z
+ JOIN tNestedTree t ON t.id = z.id
+ SET z.path = t.path,
+ z.lft = t.lft,
+ z.rgt = t.rgt,
+ z.depth = t.depth,
+ z.sons = t.sons;
+
+ DROP TEMPORARY TABLE tNestedTree;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zoneGeo_calcTreeRec.sql b/db/routines/vn/procedures/zoneGeo_calcTreeRec.sql
new file mode 100644
index 000000000..da499ede3
--- /dev/null
+++ b/db/routines/vn/procedures/zoneGeo_calcTreeRec.sql
@@ -0,0 +1,69 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneGeo_calcTreeRec`(
+ vSelf INT,
+ vPath VARCHAR(255),
+ vDepth INT,
+ INOUT vIndex INT,
+ OUT vSons INT
+)
+BEGIN
+/**
+ * Calculates and sets the #path, #lft, #rgt, #sons and #depth
+ * columns for all children of the passed node. Once calculated
+ * the last node rgt index and the number of sons are returned.
+ * To update it's children, this procedure calls itself recursively
+ * for each one.
+ *
+ * @vSelf The node identifier
+ * @vPath The initial path
+ * @vDepth The initial depth
+ * @vIndex The initial lft index
+ * @vSons The number of direct sons
+ */
+ DECLARE vChildFk INT;
+ DECLARE vLft INT;
+ DECLARE vMySons INT;
+ DECLARE vDone BOOL;
+ DECLARE vChildren CURSOR FOR
+ SELECT id FROM zoneGeo
+ WHERE (vSelf IS NULL AND parentFk IS NULL)
+ OR (vSelf IS NOT NULL AND parentFk = vSelf);
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SET vSons = 0;
+
+ OPEN vChildren;
+ myLoop: LOOP
+ SET vDone = FALSE;
+ FETCH vChildren INTO vChildFk;
+
+ IF vDone THEN
+ LEAVE myLoop;
+ END IF;
+
+ SET vIndex = vIndex + 1;
+ SET vLft = vIndex;
+ SET vSons = vSons + 1;
+
+ CALL zoneGeo_calcTreeRec(
+ vChildFk,
+ CONCAT(vPath, vChildFk, '/'),
+ vDepth + 1,
+ vIndex,
+ vMySons
+ );
+
+ SET vIndex = vIndex + 1;
+
+ INSERT INTO tNestedTree
+ SET id = vChildFk,
+ path = vPath,
+ lft = vLft,
+ rgt = vIndex,
+ depth = vDepth,
+ sons = vMySons;
+ END LOOP;
+ CLOSE vChildren;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zoneGeo_checkName.sql b/db/routines/vn/procedures/zoneGeo_checkName.sql
new file mode 100644
index 000000000..5933f4be2
--- /dev/null
+++ b/db/routines/vn/procedures/zoneGeo_checkName.sql
@@ -0,0 +1,9 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneGeo_checkName`(vName VARCHAR(255))
+BEGIN
+ IF vName = '' THEN
+ SIGNAL SQLSTATE '45000'
+ SET MESSAGE_TEXT = 'Column `name` cannot be empty';
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zoneGeo_delete.sql b/db/routines/vn/procedures/zoneGeo_delete.sql
new file mode 100644
index 000000000..5bf0c5120
--- /dev/null
+++ b/db/routines/vn/procedures/zoneGeo_delete.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneGeo_delete`(vSelf INT)
+BEGIN
+/**
+ * Deletes a node from the #zoneGeo table. Also sets a mark
+ * to force the tree recalculation.
+ *
+ * @vSelf The node identifier
+ */
+ DELETE FROM zoneGeo WHERE id = vSelf;
+ UPDATE zoneGeoRecalc SET isChanged = TRUE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zoneGeo_doCalc.sql b/db/routines/vn/procedures/zoneGeo_doCalc.sql
new file mode 100644
index 000000000..ce32357ec
--- /dev/null
+++ b/db/routines/vn/procedures/zoneGeo_doCalc.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneGeo_doCalc`()
+proc: BEGIN
+/**
+ * Recalculates the zones tree.
+ */
+ DECLARE vIsChanged BOOL;
+
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ DO RELEASE_LOCK('vn.zoneGeo_doCalc');
+ RESIGNAL;
+ END;
+
+ IF !GET_LOCK('vn.zoneGeo_doCalc', 0) THEN
+ LEAVE proc;
+ END IF;
+
+ SELECT isChanged INTO vIsChanged
+ FROM zoneGeoRecalc;
+
+ IF vIsChanged THEN
+ UPDATE zoneGeoRecalc SET isChanged = FALSE;
+ CALL vn.zoneGeo_calcTree;
+ END IF;
+
+ DO RELEASE_LOCK('vn.zoneGeo_doCalc');
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zoneGeo_setParent.sql b/db/routines/vn/procedures/zoneGeo_setParent.sql
new file mode 100644
index 000000000..3f8f051a2
--- /dev/null
+++ b/db/routines/vn/procedures/zoneGeo_setParent.sql
@@ -0,0 +1,16 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneGeo_setParent`(vSelf INT, vParentFk INT)
+BEGIN
+/**
+ * Updates the parent of a node. Also sets a mark
+ * to force the tree recalculation.
+ *
+ * @vSelf The node identifier
+ * @vParentFk The new parent identifier
+ */
+ UPDATE zoneGeo SET parentFk = vParentFk
+ WHERE id = vSelf;
+
+ UPDATE zoneGeoRecalc SET isChanged = TRUE;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zoneGeo_throwNotEditable.sql b/db/routines/vn/procedures/zoneGeo_throwNotEditable.sql
new file mode 100644
index 000000000..0b5c8aecf
--- /dev/null
+++ b/db/routines/vn/procedures/zoneGeo_throwNotEditable.sql
@@ -0,0 +1,7 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneGeo_throwNotEditable`()
+BEGIN
+ SIGNAL SQLSTATE '45000'
+ SET MESSAGE_TEXT = 'Column `geoFk` cannot be modified';
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zone_excludeFromGeo.sql b/db/routines/vn/procedures/zone_excludeFromGeo.sql
new file mode 100644
index 000000000..6f0556bd7
--- /dev/null
+++ b/db/routines/vn/procedures/zone_excludeFromGeo.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_excludeFromGeo`(vZoneGeo INT)
+BEGIN
+/**
+ * Excluye zonas a partir un geoFk.
+ *
+ * @table tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, landed, shipped) The computed options
+ * @param vZoneGeo The zone geo
+ * @return tmp.zoneOption The computed options
+ */
+ DELETE t
+ FROM tmp.zoneOption t
+ JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed
+ LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id
+ JOIN zoneGeo zg1 ON zg1.id = eg.geoFk
+ JOIN zoneGeo zg2 ON zg2.id = vZoneGeo
+ WHERE zg2.`path` LIKE CONCAT(zg1.`path`, zg1.id,'/%')
+ OR zg2.id = zg1.id;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zone_getAddresses.sql b/db/routines/vn/procedures/zone_getAddresses.sql
new file mode 100644
index 000000000..1412c7ab3
--- /dev/null
+++ b/db/routines/vn/procedures/zone_getAddresses.sql
@@ -0,0 +1,55 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`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 ;
diff --git a/db/routines/vn/procedures/zone_getAgency.sql b/db/routines/vn/procedures/zone_getAgency.sql
new file mode 100644
index 000000000..8b66b110b
--- /dev/null
+++ b/db/routines/vn/procedures/zone_getAgency.sql
@@ -0,0 +1,36 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getAgency`(vAddress INT, vLanded DATE)
+BEGIN
+/**
+ * Devuelve el listado de agencias disponibles para la fecha
+ * y dirección pasadas.
+ *
+ * @param vAddress Id de dirección de envío, %NULL si es recogida
+ * @param vLanded Fecha de recogida
+ * @return tmp.zoneGetAgency Listado de agencias disponibles
+ */
+ CALL zone_getFromGeo(address_getGeo(vAddress));
+ CALL zone_getOptionsForLanding(vLanded, FALSE);
+ CALL vn.zone_excludeFromGeo(address_getGeo(vAddress));
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency;
+ CREATE TEMPORARY TABLE tmp.zoneGetAgency
+ (INDEX (agencyModeFk)) ENGINE = MEMORY
+ SELECT am.name agencyMode,
+ am.description,
+ z.agencyModeFk,
+ am.deliveryMethodFk,
+ TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped,
+ TRUE isIncluded,
+ zo.zoneFk,
+ am.web AS isVisible
+ FROM tmp.zoneOption zo
+ JOIN zone z ON z.id = zo.zoneFk
+ JOIN agencyMode am ON am.id = z.agencyModeFk
+ GROUP BY agencyModeFk;
+
+ DROP TEMPORARY TABLE
+ tmp.zone,
+ tmp.zoneOption;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zone_getAvailable.sql b/db/routines/vn/procedures/zone_getAvailable.sql
new file mode 100644
index 000000000..4fd3d1b34
--- /dev/null
+++ b/db/routines/vn/procedures/zone_getAvailable.sql
@@ -0,0 +1,13 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getAvailable`(vAddress INT, vLanded DATE)
+BEGIN
+ CALL zone_getFromGeo(address_getGeo(vAddress));
+ CALL zone_getOptionsForLanding(vLanded, FALSE);
+
+ SELECT * FROM tmp.zoneOption;
+
+ DROP TEMPORARY TABLE
+ tmp.zone,
+ tmp.zoneOption;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zone_getClosed.sql b/db/routines/vn/procedures/zone_getClosed.sql
new file mode 100644
index 000000000..f48e6ff44
--- /dev/null
+++ b/db/routines/vn/procedures/zone_getClosed.sql
@@ -0,0 +1,34 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getClosed`()
+proc:BEGIN
+/**
+ * Devuelve una tabla con las zonas cerradas para hoy
+ *
+ * @table tmp.closedZones(zoneFk, warehouseFk);
+ */
+ DROP TEMPORARY TABLE IF EXISTS tmp.closedZones;
+
+ CREATE TEMPORARY TABLE tmp.closedZones (
+ `zoneFk` int(11) NOT NULL,
+ `warehouseFk` smallint(6) unsigned NOT NULL,
+ PRIMARY KEY `zoneFk` (`zoneFk`,`warehouseFk`),
+ KEY `warehouseFk` (`warehouseFk`))
+ ENGINE=MEMORY DEFAULT CHARSET=utf8;
+
+ INSERT INTO tmp.closedZones(zoneFk, warehouseFk)
+ SELECT zoneFk, warehouseFk
+ FROM (
+ SELECT t.zoneFk, t.warehouseFk, count(DISTINCT t.id) numTickets, pc.minTicketsToCloseZone
+ FROM vn.ticket t
+ JOIN vn.expedition e ON e.ticketFk = t.id
+ JOIN vn.`zone`z on z.id = t.zoneFk
+ JOIN vn.agencyMode am ON am.id = z.agencyModeFk
+ JOIN vn.agency a ON a.id = am.agencyFk
+ JOIN vn.productionConfig pc
+ WHERE a.isOwn
+ AND pc.isZoneClosedByExpeditionActivated
+ AND e.created >= util.VN_CURDATE()
+ GROUP BY t.zoneFk, t.warehouseFk
+ HAVING numTickets >= minTicketsToCloseZone) sub;
+ END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/zone_getCollisions.sql b/db/routines/vn/procedures/zone_getCollisions.sql
new file mode 100644
index 000000000..f6779e1b7
--- /dev/null
+++ b/db/routines/vn/procedures/zone_getCollisions.sql
@@ -0,0 +1,125 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getCollisions`()
+BEGIN
+/**
+ * Calcula si para un mismo codigo postal y dia
+ * hay mas de una zona configurada y manda correo
+ *
+ */
+ DECLARE vGeoFk INT DEFAULT NULL;
+ DECLARE vZoneFk INT;
+ DECLARE vIsDone INT DEFAULT FALSE;
+ DECLARE vTableCollisions TEXT;
+ DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.zone;
+ CREATE TEMPORARY TABLE tmp.zone
+ SELECT z.id
+ FROM zone z
+ JOIN agencyMode am ON am.id = z.agencyModeFk
+ JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ WHERE dm.code IN ('AGENCY','DELIVERY');
+
+ CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE);
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes;
+ CREATE TEMPORARY TABLE tmp.zoneNodes (
+ geoFk INT,
+ name VARCHAR(100),
+ parentFk INT,
+ sons INT,
+ isChecked BOOL DEFAULT 0,
+ zoneFk INT,
+ PRIMARY KEY zoneFkk (zoneFk, geoFk),
+ INDEX(geoFk))
+ ENGINE = MyISAM;
+
+ OPEN cur1;
+ cur1Loop: LOOP
+ SET vIsDone = FALSE;
+ FETCH cur1 INTO vZoneFk;
+ IF vIsDone THEN
+ LEAVE cur1Loop;
+ END IF;
+
+ CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE);
+
+ myLoop: LOOP
+ SET vGeoFk = NULL;
+ SELECT geoFk INTO vGeoFk
+ FROM tmp.zoneNodes zn
+ WHERE NOT isChecked
+ LIMIT 1;
+
+ IF vGeoFk IS NULL THEN
+ LEAVE myLoop;
+ END IF;
+
+ CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE);
+ UPDATE tmp.zoneNodes
+ SET isChecked = TRUE
+ WHERE geoFk = vGeoFk;
+ END LOOP;
+
+ END LOOP;
+ CLOSE cur1;
+ DELETE FROM tmp.zoneNodes
+ WHERE sons > 0;
+
+ DROP TEMPORARY TABLE IF EXISTS geoCollision;
+ CREATE TEMPORARY TABLE geoCollision
+ SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk
+ FROM tmp.zoneNodes zn
+ JOIN zone z ON z.id = zn.zoneFk
+ JOIN zoneWarehouse zw ON z.id = zw.zoneFk
+ GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk
+ HAVING count(*) > 1;
+
+ SELECT '
+
+
C.Postal
+
Número de zona
+
Precio
+
Zona
+
Almacén
+
Salix
+
' INTO vTableCollisions;
+
+ 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 ''),
+ '
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/invoice-incoterms/invoice-incoterms.js b/print/templates/reports/invoice-incoterms/invoice-incoterms.js
index 2c183b6cc..9cc2600af 100755
--- a/print/templates/reports/invoice-incoterms/invoice-incoterms.js
+++ b/print/templates/reports/invoice-incoterms/invoice-incoterms.js
@@ -7,7 +7,7 @@ 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]);
},
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 0c4af803d..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,
- c.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
- JOIN vn.invoiceOutSerial ios ON ios.code = io.serial AND ios.taxAreaFk = 'WORLD'
+ 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/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/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/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,