refs #6915 test into dev #2093

Merged
juan merged 23 commits from test into dev 2024-02-23 18:05:46 +00:00
313 changed files with 21733 additions and 34781 deletions
Showing only changes of commit 18da27179d - Show all commits

View File

@ -1,4 +1,6 @@
node_modules node_modules
print/node_modules print/node_modules
front/node_modules front
services db
e2e
storage

View File

@ -5,299 +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/), 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). 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 ## [2406.01] - 2024-02-08
### Added ### Added
### Changed
### Fixed
### Changed
### Fixed
## [2404.01] - 2024-01-25 ## [2404.01] - 2024-01-25
### Added ### Added
### Changed
### Fixed
### Changed
### Fixed
## [2402.01] - 2024-01-11 ## [2402.01] - 2024-01-11
### Added ### Added
### Changed ### Changed
### Fixed ### Fixed
## [2400.01] - 2024-01-04 ## [2400.01] - 2024-01-04
### Added ### Added
### Changed ### Changed
### Fixed ### Fixed
## [2350.01] - 2023-12-14 ## [2350.01] - 2023-12-14
### Características Añadidas 🆕 ### Características Añadidas 🆕
- **Tickets → Expediciones:** Añadido soporte para Viaexpress
- **Tickets → Expediciones:** Añadido soporte para Viaexpress
## [2348.01] - 2023-11-30 ## [2348.01] - 2023-11-30
### Características Añadidas 🆕 ### Características Añadidas 🆕
- **Tickets → Adelantar:** Permite mover lineas sin generar negativos
- **Tickets → Adelantar:** Permite modificar la fecha de los tickets - **Tickets → Adelantar:** Permite mover lineas sin generar negativos
- **Trabajadores → Notificaciones:** Nueva sección (lilium) - **Tickets → Adelantar:** Permite modificar la fecha de los tickets
- **Trabajadores → Notificaciones:** Nueva sección (lilium)
### Correcciones 🛠️ ### Correcciones 🛠️
- **Tickets → RocketChat:** Arreglada detección de cambios
- **Tickets → RocketChat:** Arreglada detección de cambios
## [2346.01] - 2023-11-16 ## [2346.01] - 2023-11-16
### Added ### Added
### Changed
### Fixed
### Changed
### Fixed
## [2342.01] - 2023-11-02 ## [2342.01] - 2023-11-02
### Added ### 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 ## [2340.01] - 2023-10-05
## [2338.01] - 2023-09-21 ## [2338.01] - 2023-09-21
### Added ### Added
- (Ticket -> Servicios) Se pueden abonar servicios
- (Facturas -> Datos básicos) Muestra valores por defecto - (Ticket -> Servicios) Se pueden abonar servicios
- (Facturas -> Borrado) Notificación al borrar un asiento ya enlazado en Sage - (Facturas -> Datos básicos) Muestra valores por defecto
- (Facturas -> Borrado) Notificación al borrar un asiento ya enlazado en Sage
### Changed ### 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 ## [2336.01] - 2023-09-07
## [2334.01] - 2023-08-24 ## [2334.01] - 2023-08-24
### Added ### 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 ## [2332.01] - 2023-08-10
### Added ### Added
- (Trabajadores -> Gestión documental) Soporte para Docuware
- (General -> Agencia) Soporte para Viaexpress - (Trabajadores -> Gestión documental) Soporte para Docuware
- (Tickets -> SMS) Nueva sección en Lilium - (General -> Agencia) Soporte para Viaexpress
- (Tickets -> SMS) Nueva sección en Lilium
### Changed ### Changed
- (General -> Tickets) Devuelve el motivo por el cual no es editable
- (Desplegables -> Trabajadores) Mejorados - (General -> Tickets) Devuelve el motivo por el cual no es editable
- (General -> Clientes) Razón social y dirección en mayúsculas - (Desplegables -> Trabajadores) Mejorados
- (General -> Clientes) Razón social y dirección en mayúsculas
### Fixed ### 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 ## [2330.01] - 2023-07-27
### Added ### Added
- (Artículos -> Vista Previa) Añadido campo "Plástico reciclado"
- (Rutas -> Troncales) Nueva sección - (Artículos -> Vista Previa) Añadido campo "Plástico reciclado"
- (Tickets -> Opciones) Opción establecer peso - (Rutas -> Troncales) Nueva sección
- (Clientes -> SMS) Nueva sección - (Tickets -> Opciones) Opción establecer peso
- (Clientes -> SMS) Nueva sección
### Changed ### 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 ## [2328.01] - 2023-07-13
### Added ### Added
- (Clientes -> Morosos) Añadida columna "es trabajador"
- (Trabajadores -> Departamentos) Nueva sección - (Clientes -> Morosos) Añadida columna "es trabajador"
- (Trabajadores -> Departamentos) Añadido listado de Trabajadores por departamento - (Trabajadores -> Departamentos) Nueva sección
- (Trabajadores -> Departamentos) Añadido características de departamento e información - (Trabajadores -> Departamentos) Añadido listado de Trabajadores por departamento
- (Trabajadores -> Departamentos) Añadido características de departamento e información
### Changed ### Changed
### Fixed ### Fixed
- (Trabajadores -> Departamentos) Arreglado búscador
- (Trabajadores -> Departamentos) Arreglado búscador
## [2326.01] - 2023-06-29 ## [2326.01] - 2023-06-29
### Added ### 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 - (Entradas -> Correo) Al cambiar el tipo de cambio enviará un correo a las personas designadas
- (General -> Históricos) Al filtar por registro se muestra todo el histórial desde que fue creado - (General -> Históricos) Botón para ver el estado del registro en cada punto
- (Tickets -> Índice) Permite enviar varios albaranes a Docuware - (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 ### 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 ### 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 ## [2324.01] - 2023-06-15
### Added ### 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 - (Tickets -> Abono) Al abonar permite crear el ticket abono con almacén o sin almmacén
- (General -> Históricos) Ahora, ademas de los ids, se muestra la descripión de los atributos - (General -> Desplegables) Mejorada eficiencia de carga de datos
- (General -> Históricos) Botón para hacer más ágil mostrar sólo los cambios en un registro - (General -> Históricos) Ahora, ademas de los ids, se muestra la descripión de los atributos
- (General -> Históricos) Filtro por cambios - (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 ### 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 ### Fixed
- -
## [2322.01] - 2023-06-01 ## [2322.01] - 2023-06-01
### Added ### 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 - (Tickets -> Crear Factura) Al facturar se envia automáticamente el pdf al cliente
- (Trabajadores -> Nuevo trabajador) Permite elegir el método de pago - (Artículos -> Histórico) Filtro para mostrar lo anterior al inventario
- (Trabajadores -> Nuevo trabajador) Permite elegir el método de pago
### Changed ### 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 ### 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 ## [2320.01] - 2023-05-25
### Added ### 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 ### 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 ### Fixed
- -
## [2318.01] - 2023-05-08 ## [2318.01] - 2023-05-08
### Added ### Added
- (Usuarios -> Histórico) Nueva sección
- (Roles -> Histórico) Nueva sección - (Usuarios -> Histórico) Nueva sección
- (Trabajadores -> Dar de alta) Permite elegir el método de pago - (Roles -> Histórico) Nueva sección
- (Trabajadores -> Dar de alta) Permite elegir el método de pago
### Changed ### 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 ### 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 ## [2314.01] - 2023-04-20
### Added ### 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 - (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.
- (Facturas recibidas -> Bases negativas) Nueva sección - (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 ### 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 ## [2312.01] - 2023-04-06
### Added ### 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 ### 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. - (Monitor tickets) Cuando se filtra por 'Pendiente' ya no muestra los estados de 'Previa'
- (Envíos -> Índice) Cambiado el buscador superior por uno lateral - (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 ## [2310.01] - 2023-03-23
### Added ### 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 ### 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 ## [2308.01] - 2023-03-09
### Added ### Added
- (Proveedores -> Datos fiscales) Añadido checkbox 'Vies'
- (Client -> Descriptor) Nuevo icono $ con barrotes para los clientes con impago - (Proveedores -> Datos fiscales) Añadido checkbox 'Vies'
- (Trabajador -> Datos Básicos) Añadido nuevo campo Taquilla - (Client -> Descriptor) Nuevo icono $ con barrotes para los clientes con impago
- (Trabajador -> PDA) Nueva sección - (Trabajador -> Datos Básicos) Añadido nuevo campo Taquilla
- (Trabajador -> PDA) Nueva sección
### Changed ### 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 ## [2306.01] - 2023-02-23
### Added ### 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 ### 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 ### 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 - (Monitor de tickets) Cuando ordenas por columna, ya no se queda deshabilitado el botón de 'Actualizar'
- (Artículos) El disponible en la vista previa se muestra correctamente - (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 ## [2304.01] - 2023-02-09
### Added ### Added
- (Rutas) Al descargar varias facturas se comprime en un zip
- (Trabajadores -> Nuevo trabajador) Nueva sección - (Rutas) Al descargar varias facturas se comprime en un zip
- (Tickets -> Adelantar tickets) Añadidos campos "líneas" y "litros" al ticket origen - (Trabajadores -> Nuevo trabajador) Nueva sección
- (Tickets -> Adelantar tickets) Nuevo icono muestra cuando las agencias de los tickets origen/destino son distintas - (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 ### 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" - (Entradas -> Compras) Cambiados los campos "Precio Grouping/Packing" por "PVP" y "Precio" por "Coste"
- (Rutas -> Sumario/Tickets) Actualizados campos de los tickets - (Artículos -> Últimas entradas) Cambiados los campos "P.P.U." y "P.P.P." por "PVP"
- (Proveedores -> Crear/Editar) Permite añadir Proveedores con la misma razón social pero con países distintos - (Rutas -> Sumario/Tickets) Actualizados campos de los tickets
- (Tickets -> Adelantar tickets) Cambiados selectores de estado por checks "Pendiente origen/destino" - (Proveedores -> Crear/Editar) Permite añadir Proveedores con la misma razón social pero con países distintos
- (Tickets -> Adelantar tickets) Cambiado stock de destino a origen. - (Tickets -> Adelantar tickets) Cambiados selectores de estado por checks "Pendiente origen/destino"
- (Tickets -> Adelantar tickets) Cambiado stock de destino a origen.
### Fixed ### 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 - (Artículos -> Etiquetas) Permite intercambiar la relevancia entre dos etiquetas.
- (Tickets -> Datos básicos) Permite guardar la hora de envío - (Cliente -> Datos Fiscales) No se permite seleccionar 'Notificar vía e-mail' a los clientes sin e-mail
- (Tickets -> Añadir pago) Eliminado "null" en las referencias - (Tickets -> Datos básicos) Permite guardar la hora de envío
- (Tickets -> Adelantar tickets) Permite ordenar por importe - (Tickets -> Añadir pago) Eliminado "null" en las referencias
- (Tickets -> Adelantar tickets) El filtrado por encajado muestra también los tickets sin tipo de encajado - (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 ## [2302.01] - 2023-01-26
### Added ### Added
- (General -> Inicio) Permite recuperar la contraseña
- (Tickets -> Opciones) Subir albarán a Docuware - (General -> Inicio) Permite recuperar la contraseña
- (Tickets -> Opciones) Enviar correo con PDF de Docuware - (Tickets -> Opciones) Subir albarán a Docuware
- (Artículos -> Datos Básicos) Añadido campo Unidades/Caja - (Tickets -> Opciones) Enviar correo con PDF de Docuware
- (Artículos -> Datos Básicos) Añadido campo Unidades/Caja
### Changed ### 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 ### Fixed
- (General) Al utilizar el traductor de Google se descuadraban los iconos
- (General) Al utilizar el traductor de Google se descuadraban los iconos
### Removed ### Removed
- (Tickets -> Control clientes) Eliminada sección
- (Tickets -> Control clientes) Eliminada sección

243
Jenkinsfile vendored
View File

@ -3,125 +3,191 @@
def PROTECTED_BRANCH def PROTECTED_BRANCH
def FROM_GIT def FROM_GIT
def RUN_TESTS 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 { pipeline {
agent any agent any
options { options {
disableConcurrentBuilds() disableConcurrentBuilds()
} }
tools {
nodejs 'node-v20'
}
environment { environment {
PROJECT_NAME = 'salix' PROJECT_NAME = 'salix'
STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}" STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}"
} }
tools {
nodejs 'node-v20'
}
stages { stages {
stage('Checkout') {
steps {
script {
// Uncomment to enable debugging
// env.DEBUG = 'strong-remoting:shared-method,puppeteer-cluster:*'
switch (env.BRANCH_NAME) {
case 'dev':
env.NODE_ENV = 'dev'
env.BACK_REPLICAS = 1
break
case 'test':
env.NODE_ENV = 'test'
env.BACK_REPLICAS = 2
break
case 'master':
env.NODE_ENV = 'production'
env.BACK_REPLICAS = 4
break
}
def packageJson = readJSON file: 'package.json'
env.VERSION = packageJson.version
env.GIT_COMMIT_MSG = sh(
script: 'git log -1 --pretty=%B ${GIT_COMMIT}',
returnStdout: true
).trim()
PROTECTED_BRANCH = [
'dev',
'test',
'master'
].contains(env.BRANCH_NAME)
FROM_GIT = JOB_NAME.startsWith('gitea/')
RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT
}
setEnv()
}
}
stage('Install') { stage('Install') {
environment { environment {
NODE_ENV = "" NODE_ENV = ''
} }
parallel { parallel {
stage('Backend') { stage('Back') {
steps { steps {
sh 'npm install --no-audit --prefer-offline' sh 'pnpm install --prefer-offline'
}
}
stage('Frontend') {
when {
expression { return FROM_GIT }
}
steps {
sh 'npm install --no-audit --prefer-offline --prefix=front'
} }
} }
stage('Print') { stage('Print') {
when { when {
expression { return FROM_GIT } expression { FROM_GIT }
} }
steps { steps {
sh 'npm install --no-audit --prefer-offline --prefix=print' sh 'pnpm install --prefer-offline --prefix=print'
}
}
stage('Front') {
when {
expression { FROM_GIT }
}
steps {
sh 'pnpm install --prefer-offline --prefix=front'
} }
} }
} }
} }
stage('Test') { stage('Stack') {
when {
expression { return RUN_TESTS }
}
environment {
NODE_ENV = ""
TZ = 'Europe/Madrid'
}
parallel { parallel {
stage('Backend') { stage('Back') {
steps { stages {
sh 'npm run test:back:ci' stage('Test') {
when {
expression { RUN_TESTS }
}
environment {
NODE_ENV = ''
}
steps {
sh 'node back/tests.js --ci --junit --network jenkins'
}
post {
always {
junit(
testResults: 'junitresults.xml',
allowEmptyResults: true
)
}
}
}
stage('Build') {
when {
expression { RUN_BUILD }
}
steps {
script {
def packageJson = readJSON file: 'package.json'
env.VERSION = packageJson.version
}
sh 'docker-compose build back'
}
}
} }
} }
stage('Frontend') { stage('Front') {
steps { when {
sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=6' 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') { stage('Push') {
when { when {
expression { return PROTECTED_BRANCH && FROM_GIT } expression { RUN_BUILD }
} }
environment { environment {
CREDENTIALS = credentials('docker-registry') CREDENTIALS = credentials('docker-registry')
} }
steps { steps {
sh 'gulp build' script {
dockerBuild() def packageJson = readJSON file: 'package.json'
env.VERSION = packageJson.version
}
sh 'docker login --username $CREDENTIALS_USR --password $CREDENTIALS_PSW $REGISTRY'
sh 'docker-compose push'
} }
} }
stage('Deploy') { stage('Deploy') {
when { when {
expression { return PROTECTED_BRANCH } expression { PROTECTED_BRANCH }
} }
parallel { parallel {
stage('Database') { stage('Database') {
@ -139,12 +205,16 @@ pipeline {
} }
stage('Docker') { stage('Docker') {
when { when {
expression { return FROM_GIT } expression { FROM_GIT }
} }
environment { environment {
DOCKER_HOST = "${env.SWARM_HOST}" DOCKER_HOST = "${env.SWARM_HOST}"
} }
steps { 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}" sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}"
} }
} }
@ -152,26 +222,20 @@ pipeline {
} }
} }
post { post {
always {
script {
if (RUN_TESTS) {
try {
junit 'junitresults.xml'
junit 'junit.xml'
} catch (e) {
echo e.toString()
}
}
}
}
success { success {
script { script {
if (env.BRANCH_NAME == 'master' && FROM_GIT) { if (env.BRANCH_NAME == 'master' && FROM_GIT) {
env.GIT_COMMIT_MSG = sh(
script: 'git log -1 --pretty=%B ${GIT_COMMIT}',
returnStdout: true
).trim()
String message = env.GIT_COMMIT_MSG String message = env.GIT_COMMIT_MSG
int index = message.indexOf('\n') int index = message.indexOf('\n')
if (index != -1) if (index != -1)
message = message.substring(0, index) message = message.substring(0, index)
setEnv()
rocketSend( rocketSend(
channel: 'vn-database', channel: 'vn-database',
message: "*DB version uploaded:* ${message}" message: "*DB version uploaded:* ${message}"
@ -183,6 +247,7 @@ pipeline {
} }
} }
unsuccessful { unsuccessful {
setEnv()
sendEmail() sendEmail()
} }
} }

View File

@ -13,7 +13,7 @@ RUN apt-get update \
graphicsmagick \ graphicsmagick \
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \ && curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \ && apt-get install -y --no-install-recommends nodejs \
&& npm install -g npm@9.6.6 && corepack enable pnpm
# Puppeteer # Puppeteer
@ -39,12 +39,12 @@ RUN apt-get update \
WORKDIR /salix WORKDIR /salix
COPY print/package.json print/package-lock.json print/ COPY print/package.json print/pnpm-lock.yaml print/
RUN npm ci --no-audit --prefer-offline --omit=dev --prefix=print RUN pnpm install --prod --prefix=print
COPY package.json package-lock.json ./ COPY package.json pnpm-lock.yaml ./
COPY loopback/package.json loopback/ COPY loopback/package.json loopback/
RUN npm ci --no-audit --prefer-offline --omit=dev RUN pnpm install --prod
COPY loopback loopback COPY loopback loopback
COPY back back COPY back back

View File

@ -49,7 +49,6 @@ module.exports = Self => {
Self.uploadFile = async(ctx, options) => { Self.uploadFile = async(ctx, options) => {
const models = Self.app.models; const models = Self.app.models;
const TempContainer = models.TempContainer; const TempContainer = models.TempContainer;
const DmsContainer = models.DmsContainer;
const fileOptions = {}; const fileOptions = {};
const args = ctx.args; const args = ctx.args;
@ -79,19 +78,21 @@ module.exports = Self => {
const addedDms = []; const addedDms = [];
for (const uploadedFile of files) { for (const uploadedFile of files) {
const newDms = await createDms(ctx, uploadedFile, myOptions);
const pathHash = DmsContainer.getHash(newDms.id);
const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name); const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name);
srcFile = path.join(file.client.root, file.container, file.name); srcFile = path.join(file.client.root, file.container, file.name);
const dmsContainer = await DmsContainer.container(pathHash); const data = {
const dstFile = path.join(dmsContainer.client.root, pathHash, newDms.file); workerFk: ctx.req.accessToken.userId,
dmsTypeFk: args.dmsTypeId,
await fs.move(srcFile, dstFile, { companyFk: args.companyId,
overwrite: true warehouseFk: args.warehouseId,
}); reference: args.reference,
description: args.description,
contentType: uploadedFile.type,
hasFile: args.hasFile
};
const extension = await models.DmsContainer.getFileExtension(uploadedFile.name);
const newDms = await Self.createFromFile(data, extension, srcFile, myOptions);
addedDms.push(newDms); addedDms.push(newDms);
} }
@ -107,27 +108,4 @@ module.exports = Self => {
throw e; throw e;
} }
}; };
async function createDms(ctx, file, myOptions) {
const models = Self.app.models;
const myUserId = ctx.req.accessToken.userId;
const args = ctx.args;
const newDms = await Self.create({
workerFk: myUserId,
dmsTypeFk: args.dmsTypeId,
companyFk: args.companyId,
warehouseFk: args.warehouseId,
reference: args.reference,
description: args.description,
contentType: file.type,
hasFile: args.hasFile
}, myOptions);
let fileName = file.name;
const extension = models.DmsContainer.getFileExtension(fileName);
fileName = `${newDms.id}.${extension}`;
return newDms.updateAttribute('file', fileName, myOptions);
}
}; };

View File

@ -87,6 +87,6 @@ module.exports = Self => {
await fs.access(file.path); await fs.access(file.path);
const stream = fs.createReadStream(file.path); const stream = fs.createReadStream(file.path);
return [stream, file.contentType, `filename="${file.name}"`]; return [stream, file.contentType, `filename="${fileName}"`];
}; };
}; };

View File

@ -8,6 +8,26 @@ module.exports = Self => {
}); });
Self.validatesUniquenessOf('bic', { 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();
}
}; };

View File

@ -1,4 +1,6 @@
const UserError = require('vn-loopback/util/user-error'); const UserError = require('vn-loopback/util/user-error');
const fs = require('fs-extra');
const path = require('path');
module.exports = Self => { module.exports = Self => {
require('../methods/dms/downloadFile')(Self); require('../methods/dms/downloadFile')(Self);
@ -35,4 +37,32 @@ module.exports = Self => {
return [stream, dms.contentType, `filename="${dms.file}"`]; return [stream, dms.contentType, `filename="${dms.file}"`];
}; };
Self.getPath = async function(dms) {
const models = Self.app.models;
const pathHash = await models.DmsContainer.getHash(dms.id);
const dmsContainer = await models.DmsContainer.container(pathHash);
const dstFile = path.join(dmsContainer.client.root, pathHash, dms.file);
return dstFile;
};
Self.createWithExtension = async function(data, extension, options) {
const newDms = await Self.create(data, options);
return newDms.updateAttribute('file', `${newDms.id}.${extension}`, options);
};
Self.createFromFile = async function(data, extension, srcFile, options) {
const dms = await Self.createWithExtension(data, extension, options);
const dstFile = await Self.getPath(dms);
await fs.move(srcFile, dstFile, {overwrite: true});
return dms;
};
Self.createFromStream = async function(data, extension, stream, options) {
const dms = await Self.createWithExtension(data, extension, options);
const dstFile = await Self.getPath(dms);
const writeStream = await fs.createWriteStream(dstFile);
await stream.pipe(writeStream);
return dms;
};
}; };

34
back/tests-helper.js Normal file
View File

@ -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();

View File

@ -1,104 +1,123 @@
/* eslint-disable no-console */ /* eslint-disable no-console */
const path = require('path'); const path = require('path');
const getopts = require('getopts');
const Myt = require('@verdnatura/myt/myt'); const Myt = require('@verdnatura/myt/myt');
const Run = require('@verdnatura/myt/myt-run'); const Run = require('@verdnatura/myt/myt-run');
let dataSources = require('../loopback/server/datasources.json'); const helper = require('./tests-helper');
let server; const opts = getopts(process.argv.slice(2), {
string: [
process.on('warning', warning => { 'network'
console.log(warning.name); ],
console.log(warning.message); boolean: [
console.log(warning.stack); 'ci',
'junit'
]
}); });
process.on('SIGUSR2', rmServer); let server;
process.on('exit', rmServer); const PARALLEL = false;
const SETUP_TIMEOUT = 15 * 60 * 1000;
const SPEC_TIMEOUT = 30 * 1000;
async function rmServer() { process.on('exit', teardown);
if (!server) return; process.on('uncaughtException', onError);
await server.rm(); process.on('unhandledRejection', onError);
server = null;
}
async function test() { 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.'); console.log('Building and running DB container.');
const isCI = process.argv[2] === 'ci';
const myt = new Myt(); const myt = new Myt();
await myt.init({ await myt.init({
workspace: path.join(__dirname, '..'), workspace: path.join(__dirname, '..'),
random: true, random: true,
ci: isCI, ci: opts.ci,
tmpfs: process.platform == 'linux', tmpfs: process.platform == 'linux',
network: isCI ? 'jenkins' : null network: opts.network || null
}); });
server = await myt.run(Run); server = await myt.run(Run);
await myt.deinit(); await myt.deinit();
const {dbConfig} = server; const {dbConfig} = server;
process.env.DB_HOST = dbConfig.host;
process.env.DB_PORT = dbConfig.port;
console.log('Initializing backend.'); if (!PARALLEL)
await helper.init();
}
dataSources = JSON.parse(JSON.stringify(dataSources)); async function teardown() {
Object.assign(dataSources.vn, { if (!server) return;
host: dbConfig.host, const oldServer = server;
port: dbConfig.port server = null;
});
const bootOptions = {dataSources}; if (!PARALLEL)
const app = require('vn-loopback/server/server'); await helper.deinit();
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();
console.log('Running tests.'); console.log('Stopping and removing DB container.');
await oldServer.rm();
}
const Jasmine = require('jasmine'); async function onError(err) {
const jasmine = new Jasmine(); console.error(err);
process.exit(1);
}
const SpecReporter = require('jasmine-spec-reporter').SpecReporter; async function test() {
jasmine.addReporter(new SpecReporter({ let runner;
spec: { const config = {
displaySuccessful: isCI, globalSetup: setup,
displayPending: isCI globalSetupTimeout: SETUP_TIMEOUT,
}, globalTeardown: teardown,
summary: { globalTeardownTimeout: SETUP_TIMEOUT,
displayPending: false, spec_dir: '.',
} spec_files: [
})); 'back/**/*[sS]pec.js',
'loopback/**/*[sS]pec.js',
'modules/*/back/**/*.[sS]pec.js'
],
helpers: []
};
if (isCI) { if (PARALLEL) {
const JunitReporter = require('jasmine-reporters'); const ParallelRunner = require('jasmine/parallel');
jasmine.addReporter(new JunitReporter.JUnitXmlReporter()); runner = new ParallelRunner({numWorkers: 1});
config.helpers.push(`back/tests-helper.js`);
} else {
const Jasmine = require('jasmine');
runner = new Jasmine();
jasmine.exitOnCompletion = true; const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 900000; runner.addReporter(new SpecReporter({
spec: {
displaySuccessful: opts.ci,
displayPending: opts.ci
},
summary: {
displayPending: false,
}
}));
} }
const backSpecs = [ if (opts.junit) {
'./back/**/*[sS]pec.js', const JunitReporter = require('jasmine-reporters');
'./loopback/**/*[sS]pec.js', runner.addReporter(new JunitReporter.JUnitXmlReporter());
'./modules/*/back/**/*.[sS]pec.js' }
]; if (opts.ci)
runner.jasmine.DEFAULT_TIMEOUT_INTERVAL = SPEC_TIMEOUT;
jasmine.loadConfig({ // runner.loadConfigFile('back/jasmine.json');
spec_dir: '.', runner.loadConfig(config);
spec_files: backSpecs, process.env.SPEC_IS_RUNNING = true;
helpers: [], await runner.execute();
});
await jasmine.execute();
console.log('Stopping.');
if (app) await app.disconnect();
await rmServer();
console.log('Tests ended.\n');
} }
test(); test();

View File

@ -13,4 +13,4 @@
} }
} }
} }
} }

View File

@ -30,7 +30,7 @@ INSERT INTO vn.buy (id,entryFk,itemFk,quantity,dispatched,buyingValue,freightVal
(18,10,15,500,0,55.0,1.0,0,1,1,1,0,0.0,1.0,'5',0.0,78.3,75.6,0.0,0,0,1,0,'2022-06-20 00:00:00',0,2.5), (18,10,15,500,0,55.0,1.0,0,1,1,1,0,0.0,1.0,'5',0.0,78.3,75.6,0.0,0,0,1,0,'2022-06-20 00:00:00',0,2.5),
(19,10,11,5000,0,50.0,1.0,0,1,1,1,1,0.0,1.0,'4',0.0,99.6,99.4,0.0,0,0,1,0,'2022-06-20 00:00:00',0,2.5); (19,10,11,5000,0,50.0,1.0,0,1,1,1,1,0.0,1.0,'4',0.0,99.6,99.4,0.0,0,0,1,0,'2022-06-20 00:00:00',0,2.5);
*/ */
INSERT INTO vn2008.Splits (Id_Split,Id_Ticket,Id_Entrada,Fecha,Notas) INSERT INTO vn.split (id,ticketFk,entryFk,dated,note)
VALUES VALUES
(1,7,2,'00-00-0000 00:00:00.000','nota1'), (1,7,2,'00-00-0000 00:00:00.000','nota1'),
(2,10,6,'00-00-0000 00:00:00.000','nota2'), (2,10,6,'00-00-0000 00:00:00.000','nota2'),
@ -66,16 +66,14 @@ UPDATE vn.supplier
SET isTrucker = 1 SET isTrucker = 1
WHERE id = 2; WHERE id = 2;
INSERT INTO vn.cmr (id, truckPlate, observations, senderInstruccions, paymentInstruccions, specialAgreements, created, companyFk, addressToFk, addressFromFk, supplierFk, packagesList, merchandiseDetail, state, landed, ead)
VALUES (2, NULL, NULL, NULL, 'Carriage paid', NULL, '2022-06-27 13:31:11.000', 442, 3, 2, 2, NULL, NULL, NULL, NULL, NULL);
-- XXX: tpv -- XXX: tpv
UPDATE `vn`.`claimRatio` SET `claimAmount` = '10' WHERE (`clientFk` = '1101'); UPDATE `vn`.`claimRatio` SET `claimAmount` = '10' WHERE (`clientFk` = '1101');
INSERT INTO `vn`.`agency` (`name`, `warehouseFk`, `warehouseAliasFk`, `isOwn`, `isAnyVolumeAllowed`) VALUES INSERT INTO `vn`.`agency` (`name`, `warehouseFk`, `isOwn`, `isAnyVolumeAllowed`)
('Agencia', '1', '1', '1', '1'), VALUES
('Otra agencia ', '1', '2', '0', '0'); ('Agencia', '1', '1', '1'),
('Otra agencia ', '1', '0', '0');
INSERT INTO `vn`.`expedition` (`agencyModeFk`, `ticketFk`, `isBox`, `counter`, `workerFk`, `externalId`, `packagingFk`, `hostFk`, `itemPackingTypeFk`, `hasNewRoute`) VALUES INSERT INTO `vn`.`expedition` (`agencyModeFk`, `ticketFk`, `isBox`, `counter`, `workerFk`, `externalId`, `packagingFk`, `hostFk`, `itemPackingTypeFk`, `hasNewRoute`) VALUES
('1', '1', 1, '1', '1', '1', '1', 'pc00', 'F', 0), ('1', '1', 1, '1', '1', '1', '1', 'pc00', 'F', 0),

View File

@ -174,23 +174,18 @@ INSERT INTO `vn`.`country`(`id`, `country`, `isUeeMember`, `code`, `currencyFk`,
(19,'Francia', 1, 'FR', 1, 27, 4, 0, 1), (19,'Francia', 1, 'FR', 1, 27, 4, 0, 1),
(30,'Canarias', 1, 'IC', 1, 24, 4, 1, 2); (30,'Canarias', 1, 'IC', 1, 24, 4, 1, 2);
INSERT INTO `vn`.`warehouseAlias`(`id`, `name`) INSERT INTO `vn`.`warehouse`(`id`, `name`, `code`, `isComparative`, `isInventory`, `hasAvailable`, `isManaged`, `hasDms`, `hasComission`, `countryFk`, `hasProduction`, `isOrigin`, `isDestiny`)
VALUES VALUES
(1, 'Main Warehouse'), (1, 'Warehouse One', 'ALG', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
(2, 'Gotham'); (2, 'Warehouse Two', NULL, 1, 1, 1, 1, 0, 1, 13, 1, 1, 0),
(3, 'Warehouse Three', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0),
(4, 'Warehouse Four', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1),
(5, 'Warehouse Five', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0),
(13, 'Inventory', 'inv', 1, 1, 1, 0, 0, 0, 1, 0, 0, 0),
(60, 'Algemesi', NULL, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0);
INSERT INTO `vn`.`warehouse`(`id`, `name`, `code`, `isComparative`, `isInventory`, `hasAvailable`, `isManaged`, `hasDms`, `hasComission`, `aliasFk`, `countryFk`, `hasProduction`) INSERT INTO `vn`.`sectorType` (`id`, `code`)
VALUES VALUES (1,'normal');
(1, 'Warehouse One', 'ALG', 1, 1, 1, 1, 1, 1, 2, 1, 1),
(2, 'Warehouse Two', NULL, 1, 1, 1, 1, 0, 1, 2, 13, 1),
(3, 'Warehouse Three', NULL, 1, 1, 1, 1, 0, 0, 2, 1, 1),
(4, 'Warehouse Four', NULL, 1, 1, 1, 1, 0, 0, 2, 1, 1),
(5, 'Warehouse Five', NULL, 1, 1, 1, 1, 0, 0, 2, 1, 1),
(13, 'Inventory', 'inv', 1, 1, 1, 0, 0, 0, 2, 1, 0),
(60, 'Algemesi', NULL, 1, 1, 1, 0, 0, 0, 2, 1, 0);
INSERT INTO `vn`.`sectorType` (id,description)
VALUES (1,'First type');
INSERT INTO `vn`.`sector`(`id`, `description`, `warehouseFk`, `code`, `typeFk`) INSERT INTO `vn`.`sector`(`id`, `description`, `warehouseFk`, `code`, `typeFk`)
VALUES VALUES
@ -271,18 +266,18 @@ INSERT INTO `vn`.`deliveryMethod`(`id`, `code`, `description`)
(3, 'PICKUP', 'Recogida'), (3, 'PICKUP', 'Recogida'),
(4, 'OTHER', 'Otros'); (4, 'OTHER', 'Otros');
INSERT INTO `vn`.`agency`(`id`, `name`, `warehouseFk`, `warehouseAliasFk`) INSERT INTO `vn`.`agency`(`id`, `name`, `warehouseFk`)
VALUES VALUES
(1, 'inhouse pickup' , 1, 1), (1, 'inhouse pickup' , 1),
(2, 'Super-Man delivery' , 1, 1), (2, 'Super-Man delivery' , 1),
(3, 'Teleportation device' , 1, 1), (3, 'Teleportation device' , 1),
(4, 'Entanglement' , 1, 1), (4, 'Entanglement' , 1),
(5, 'Quantum break device' , 1, 1), (5, 'Quantum break device' , 1),
(6, 'Walking' , 1, 1), (6, 'Walking' , 1),
(7, 'Gotham247' , 1, 1), (7, 'Gotham247' , 1),
(8, 'Gotham247Expensive' , 1, 1), (8, 'Gotham247Expensive' , 1),
(9, 'Refund' , 1, 1), (9, 'Refund' , 1),
(10, 'Other agency' , 1, 1); (10, 'Other agency' , 1);
UPDATE `vn`.`agencyMode` SET `id` = 1 WHERE `name` = 'inhouse pickup'; UPDATE `vn`.`agencyMode` SET `id` = 1 WHERE `name` = 'inhouse pickup';
UPDATE `vn`.`agencyMode` SET `id` = 2 WHERE `name` = 'Super-Man delivery'; UPDATE `vn`.`agencyMode` SET `id` = 2 WHERE `name` = 'Super-Man delivery';
@ -569,13 +564,13 @@ INSERT INTO `vn`.`supplierActivity`(`code`, `name`)
INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif`, `commission`, `created`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`, `payDay`, `taxTypeSageFk`, `withholdingSageFk`, `transactionTypeSageFk`, `workerFk`, `supplierActivityFk`, `isPayMethodChecked`, `healthRegister`) INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif`, `commission`, `created`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`, `payDay`, `taxTypeSageFk`, `withholdingSageFk`, `transactionTypeSageFk`, `workerFk`, `supplierActivityFk`, `isPayMethodChecked`, `healthRegister`)
VALUES VALUES
(1, 'Plants SL', 'Plants nick', 4100000001, 1, '06089160W', 0, util.VN_CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), (1, 'PLANTS SL', 'Plants nick', 4100000001, 1, '06089160W', 0, util.VN_CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'),
(2, 'Farmer King', 'The farmer', 4000020002, 1, '87945234L', 0, util.VN_CURDATE(), 1, 'supplier address 2', 'GOTHAM', 2, 43022, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'), (2, 'FARMER KING', 'The farmer', 4000020002, 1, '87945234L', 0, util.VN_CURDATE(), 1, 'supplier address 2', 'GOTHAM', 2, 43022, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'),
(69, 'Packaging', 'Packaging nick', 4100000069, 1, '94935005K', 0, util.VN_CURDATE(), 1, 'supplier address 5', 'ASGARD', 3, 46600, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), (69, 'PACKAGING', 'Packaging nick', 4100000069, 1, '94935005K', 0, util.VN_CURDATE(), 1, 'supplier address 5', 'ASGARD', 3, 46600, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'),
(442, 'Verdnatura Levante SL', 'Verdnatura', 5115000442, 1, '06815934E', 0, util.VN_CURDATE(), 1, 'supplier address 3', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), (442, 'VERDNATURA LEVANTE SL', 'Verdnatura', 5115000442, 1, '06815934E', 0, util.VN_CURDATE(), 1, 'supplier address 3', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'),
(567, 'Holland', 'Holland nick', 4000020567, 1, '14364089Z', 0, util.VN_CURDATE(), 1, 'supplier address 6', 'ASGARD', 3, 46600, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'), (567, 'HOLLAND', 'Holland nick', 4000020567, 1, '14364089Z', 0, util.VN_CURDATE(), 1, 'supplier address 6', 'ASGARD', 3, 46600, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'),
(791, 'Bros SL', 'Bros nick', 5115000791, 1, '37718083S', 0, util.VN_CURDATE(), 1, 'supplier address 7', 'ASGARD', 3, 46600, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), (791, 'BROS SL', 'Bros nick', 5115000791, 1, '37718083S', 0, util.VN_CURDATE(), 1, 'supplier address 7', 'ASGARD', 3, 46600, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'),
(1381, 'Ornamentales', 'Ornamentales', 7185001381, 1, '07972486L', 0, util.VN_CURDATE(), 1, 'supplier address 4', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'); (1381, 'ORNAMENTALES', 'Ornamentales', 7185001381, 1, '07972486L', 0, util.VN_CURDATE(), 1, 'supplier address 4', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V');
INSERT INTO `vn`.`supplierAddress`(`id`, `supplierFk`, `nickname`, `street`, `provinceFk`, `postalCode`, `city`, `phone`, `mobile`) INSERT INTO `vn`.`supplierAddress`(`id`, `supplierFk`, `nickname`, `street`, `provinceFk`, `postalCode`, `city`, `phone`, `mobile`)
VALUES VALUES
@ -730,40 +725,40 @@ INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agen
(6, NULL, 57, util.VN_CURDATE(), 5, 7, 'sixth route', 1.7, 60, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 3), (6, NULL, 57, util.VN_CURDATE(), 5, 7, 'sixth route', 1.7, 60, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 3),
(7, NULL, 57, util.VN_CURDATE(), 6, 8, 'seventh route', 0, 70, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 5); (7, NULL, 57, util.VN_CURDATE(), 6, 8, 'seventh route', 0, 70, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 5);
INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`, `weight`) INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`, `weight`, `cmrFk`)
VALUES VALUES
(1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1), (1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1),
(2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 1, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2), (2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 1, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 2),
(3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), NULL), (3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), NULL, 3),
(4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), NULL), (4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), NULL, NULL),
(5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), NULL), (5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), NULL, NULL),
(6 , 1, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), NULL), (6 , 1, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), NULL, NULL),
(7 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), (7 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL),
(8 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Bat cave', 121, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), (8 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Bat cave', 121, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL),
(9 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), (9 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL),
(10, 1, 1, 5, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'Ingram Street', 2, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), (10, 1, 1, 5, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'Ingram Street', 2, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(11, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), (11, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL),
(12, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), (12, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(13, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), (13, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL),
(14, 1, 2, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1104, 'Malibu Point', 4, NULL, 0, 9, 5, 1, util.VN_CURDATE(), NULL), (14, 1, 2, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1104, 'Malibu Point', 4, NULL, 0, 9, 5, 1, util.VN_CURDATE(), NULL, NULL),
(15, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1105, 'An incredibly long alias for testing purposes', 125, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), (15, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1105, 'An incredibly long alias for testing purposes', 125, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL),
(16, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), (16, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL),
(17, 1, 7, 2, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), (17, 1, 7, 2, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL),
(18, 1, 4, 4, 4, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1108, 'Cerebro', 128, NULL, 0, 12, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +12 HOUR), NULL), (18, 1, 4, 4, 4, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1108, 'Cerebro', 128, NULL, 0, 12, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +12 HOUR), NULL, NULL),
(19, 1, 5, 5, NULL, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 1, NULL, 5, 1, util.VN_CURDATE(), NULL), (19, 1, 5, 5, NULL, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 1, NULL, 5, 1, util.VN_CURDATE(), NULL, NULL),
(20, 1, 5, 5, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL), (20, 1, 5, 5, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL),
(21, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Holland', 102, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL), (21, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Holland', 102, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL),
(22, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Japan', 103, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL), (22, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Japan', 103, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL),
(23, NULL, 8, 1, 7, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'address 21', 121, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL), (23, NULL, 8, 1, 7, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'address 21', 121, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL, NULL),
(24 ,NULL, 8, 1, 7, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL), (24 ,NULL, 8, 1, 7, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL, NULL),
(25 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), (25 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(26 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'An incredibly long alias for testing purposes', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), (26 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'An incredibly long alias for testing purposes', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(27 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Wolverine', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), (27 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Wolverine', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(28, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), (28, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(29, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), (29, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), (30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), (31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL),
(32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL); (32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL);
INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`)
VALUES VALUES
@ -2410,7 +2405,7 @@ INSERT INTO `vn`.`dmsType`(`id`, `name`, `readRoleFk`, `writeRoleFk`, `code`)
(14, 'Ticket', 1, 1, 'ticket'), (14, 'Ticket', 1, 1, 'ticket'),
(15, 'Presupuestos', NULL, NULL, 'budgets'), (15, 'Presupuestos', NULL, NULL, 'budgets'),
(16, 'Logistica', NULL, NULL, 'logistics'), (16, 'Logistica', NULL, NULL, 'logistics'),
(17, 'cmr', NULL, NULL, 'cmr'), (17, 'cmr', 1, 1, 'cmr'),
(18, 'dua', NULL, NULL, 'dua'), (18, 'dua', NULL, NULL, 'dua'),
(19, 'inmovilizado', NULL, NULL, 'fixedAssets'), (19, 'inmovilizado', NULL, NULL, 'fixedAssets'),
(20, 'Reclamación', 1, 1, 'claim'); (20, 'Reclamación', 1, 1, 'claim');
@ -3067,3 +3062,8 @@ INSERT INTO `vn`.`clientSms` (`id`, `clientFk`, `smsFk`, `ticketFk`)
(4, 1103, 4, 32), (4, 1103, 4, 32),
(13, 1101, 1, NULL), (13, 1101, 1, NULL),
(14, 1101, 4, 27); (14, 1101, 4, 27);
INSERT INTO `vn`.`cmr` (id,truckPlate,observations,senderInstruccions,paymentInstruccions,specialAgreements,companyFk,addressToFk,addressFromFk,supplierFk,packagesList,merchandiseDetail,state)
VALUES (1,'123456A','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',442,1,2,1,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'),
(2,'123456N','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',69,3,4,2,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'),
(3,'123456B','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',567,5,6,69,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet');

View File

@ -1,16 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `bi`.`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 ;

View File

@ -42,9 +42,9 @@ BEGIN
CREATE TEMPORARY TABLE maxInvoice CREATE TEMPORARY TABLE maxInvoice
(PRIMARY KEY (Id_Cliente)) (PRIMARY KEY (Id_Cliente))
ENGINE = MEMORY ENGINE = MEMORY
SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha SELECT DISTINCT clientFk Id_Cliente, max(issued) as maxFecha
FROM vn2008.Facturas FROM vn.invoiceOut
GROUP BY Id_Cliente GROUP BY clientFk
HAVING maxFecha < timestampadd(month,-2,datFEC); HAVING maxFecha < timestampadd(month,-2,datFEC);
WHILE datFEC < util.VN_CURDATE() DO WHILE datFEC < util.VN_CURDATE() DO
@ -53,10 +53,10 @@ BEGIN
SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0
FROM ( FROM (
SELECT Id_Cliente, sum(Importe) as Greuge SELECT clientFk Id_Cliente, sum(amount) as Greuge
FROM vn2008.Greuges FROM vn.greuge
where Fecha <= datFEC where shipped <= datFEC
group by Id_Cliente group by clientFk
) sub ) sub
RIGHT JOIN RIGHT JOIN

View File

@ -47,7 +47,7 @@ BEGIN
LEFT JOIN vn.deliveryMethod dm ON dm.id = a.Vista LEFT JOIN vn.deliveryMethod dm ON dm.id = a.Vista
LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna
LEFT JOIN vn2008.province p ON p.province_id = cs.province_id LEFT JOIN vn2008.province p ON p.province_id = cs.province_id
LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id LEFT JOIN vn.warehouse w ON w.id = t.warehouse_id
WHERE bt.fecha >= vLastMonth AND r.mercancia; WHERE bt.fecha >= vLastMonth AND r.mercancia;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -11,8 +11,8 @@ BEGIN
-- Reclamaciones demasiado sensibles -- Reclamaciones demasiado sensibles
INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, INSERT INTO vn.greuge(shipped, clientFk, description,
Importe, Greuges_type_id,Id_Ticket) amount, greugeTypeFk, ticketFk)
SELECT cm.Fecha SELECT cm.Fecha
, cm.Id_Cliente , cm.Id_Cliente
, concat('Claim ',cm.id,' : ', m.Concepte) , concat('Claim ',cm.id,' : ', m.Concepte)
@ -29,8 +29,8 @@ BEGIN
-- Reclamaciones que pasan a Maná -- Reclamaciones que pasan a Maná
INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, INSERT INTO vn.greuge(shipped, clientFk, description,
Importe , Greuges_type_id,Id_Ticket) amount, greugeTypeFk, ticketFk)
SELECT cm.Fecha SELECT cm.Fecha
, cm.Id_Cliente , cm.Id_Cliente
, concat('Claim_mana ',cm.id,' : ', m.Concepte) , concat('Claim_mana ',cm.id,' : ', m.Concepte)
@ -73,12 +73,12 @@ BEGIN
AND s.alert_level >= 3; AND s.alert_level >= 3;
DELETE g.* DELETE g.*
FROM vn2008.Greuges g FROM vn.greuge g
JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket
WHERE Greuges_type_id = 2; WHERE g.greugeTypeFk = 2;
INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, INSERT INTO vn.greuge(clientFk, description, amount,shipped,
Greuges_type_id, Id_Ticket) greugeTypeFk, ticketFk)
SELECT Id_Cliente SELECT Id_Cliente
,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2)
AS dif AS dif
@ -130,13 +130,13 @@ BEGIN
-- Calculamos el porcentaje del recobro para añadirlo al precio de venta -- Calculamos el porcentaje del recobro para añadirlo al precio de venta
UPDATE bi.claims_ratio cr UPDATE bi.claims_ratio cr
JOIN ( JOIN (
SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge SELECT clientFk Id_Cliente, IFNULL(SUM(amount), 0) AS Greuge
FROM vn2008.Greuges FROM vn.greuge
WHERE Fecha <= util.VN_CURDATE() WHERE shipped <= util.VN_CURDATE()
GROUP BY Id_Cliente GROUP BY clientFk
) g ON g.Id_Cliente = cr.Id_Cliente ) g ON g.Id_Cliente = cr.Id_Cliente
SET recobro = GREATEST(0,round(nz(Greuge) / SET recobro = GREATEST(0,round(IFNULL(Greuge, 0) /
(nz(Consumo) * vMonthToRefund / 12 ) ,3)); (IFNULL(Consumo, 0) * vMonthToRefund / 12 ) ,3));
-- Protección neonatos -- Protección neonatos
UPDATE bi.claims_ratio cr UPDATE bi.claims_ratio cr

View File

@ -14,8 +14,8 @@ BEGIN
WHERE hasChanged AND date = vDate; WHERE hasChanged AND date = vDate;
DECLARE invoices CURSOR FOR DECLARE invoices CURSOR FOR
SELECT Vencimiento, importe FROM vn2008.Facturas f SELECT dued Vencimiento, amount importe FROM vn.invoiceOut
WHERE f.Fecha >= '2016-01-01' AND f.Id_Cliente = vClient ORDER BY f.Fecha DESC; WHERE issued >= '2016-01-01' AND clientFk = vClient ORDER BY issued DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

View File

@ -19,8 +19,8 @@ BEGIN
FROM FROM
vn.ticket t vn.ticket t
JOIN vn2008.Clientes cli ON cli.Id_cliente = t.clientFk JOIN vn2008.Clientes cli ON cli.Id_cliente = t.clientFk
LEFT JOIN vn2008.expeditions e ON e.ticket_id = t.id LEFT JOIN vn.expedition e ON e.ticketFk = t.id
JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.EsBulto JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
JOIN vn.zone z ON t.zoneFk = z.id JOIN vn.zone z ON t.zoneFk = z.id
WHERE WHERE
t.shipped between datSTART AND datEND t.shipped between datSTART AND datEND
@ -64,17 +64,17 @@ BEGIN
CREATE TEMPORARY TABLE tmp.dp_aux CREATE TEMPORARY TABLE tmp.dp_aux
(PRIMARY KEY (ticketFk)) (PRIMARY KEY (ticketFk))
ENGINE = MEMORY ENGINE = MEMORY
SELECT dp.ticketFk, sum(Importe) Importe SELECT dp.ticketFk, sum(g.amount) Importe
FROM tmp.dp FROM tmp.dp
JOIN vn2008.Greuges g ON g.Id_Ticket = dp.ticketFk JOIN vn.greuge g ON g.ticketFk = dp.ticketFk
WHERE Greuges_type_id = 1 -- dif_porte WHERE g.greugeTypeFk = 1 -- dif_porte
GROUP BY dp.ticketFk; GROUP BY dp.ticketFk;
UPDATE tmp.dp UPDATE tmp.dp
JOIN tmp.dp_aux USING(ticketFk) JOIN tmp.dp_aux USING(ticketFk)
SET greuge = IFNULL(Importe,0); SET greuge = IFNULL(Importe,0);
INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, Greuges_type_id, Id_Ticket) INSERT INTO vn.greuge (clientFk,description,amount,shipped,greugeTypeFk,ticketFk)
SELECT dp.clientFk SELECT dp.clientFk
, concat('dif_porte ', dp.ticketFk) , concat('dif_porte ', dp.ticketFk)
, round(IFNULL(dp.teorico,0) - IFNULL(dp.practico,0) - IFNULL(dp.greuge,0),2) as Importe , round(IFNULL(dp.teorico,0) - IFNULL(dp.practico,0) - IFNULL(dp.greuge,0),2) as Importe

View File

@ -20,16 +20,16 @@ BEGIN
c.movil, c.movil,
c.POBLACION poblacion, c.POBLACION poblacion,
p.`name` provincia, p.`name` provincia,
vn2008.red(f.futur) futur, ROUND(f.futur, 2) futur,
c.Credito credito, c.Credito credito,
pm.`name` forma_pago, pm.`name` forma_pago,
vn2008.red(c365 / 12) consumo_medio365, ROUND(c365 / 12, 2) consumo_medio365,
vn2008.red(c365) consumo365, ROUND(c365, 2) consumo365,
vn2008.red(CmLy.peso) peso_mes_año_pasado, ROUND(CmLy.peso, 2) peso_mes_año_pasado,
vn2008.red(CmLy.peso * 1.19) objetivo, ROUND(CmLy.peso * 1.19, 2) objetivo,
tr.CodigoTrabajador, tr.CodigoTrabajador,
vn2008.red(mes_actual.consumo) consumoMes, ROUND(mes_actual.consumo, 2) consumoMes,
vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, ROUND(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0), 2) como_lo_llevo,
DATE(LastTicket) ultimo_ticket, DATE(LastTicket) ultimo_ticket,
dead.muerto, dead.muerto,
g.Greuge, g.Greuge,
@ -37,9 +37,9 @@ BEGIN
FROM FROM
vn2008.Clientes c vn2008.Clientes c
LEFT JOIN LEFT JOIN
(SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge (SELECT g.clientFk Id_Cliente, CAST( SUM(g.amount) as DECIMAL(12,2)) AS Greuge
FROM vn2008.Greuges g FROM vn.greuge g
JOIN vn.`client` c ON c.id = g.Id_Cliente JOIN vn.`client` c ON c.id = g.clientFk
LEFT JOIN vn.worker w ON c.salesPersonFk = w.id LEFT JOIN vn.worker w ON c.salesPersonFk = w.id
WHERE (c.salesPersonFk = vWorker OR w.bossFk = vWorker) WHERE (c.salesPersonFk = vWorker OR w.bossFk = vWorker)
GROUP BY Id_Cliente GROUP BY Id_Cliente
@ -98,9 +98,9 @@ BEGIN
GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente
LEFT JOIN LEFT JOIN
(SELECT c.Id_Cliente, (SELECT c.Id_Cliente,
IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto IF(MAX(io.issued) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto
FROM vn2008.Facturas f FROM vn.invoiceOut io
JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente JOIN vn2008.Clientes c ON c.Id_cliente = io.clientFk
LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador
WHERE (c.Id_Trabajador = vWorker OR tr.boss = vWorker) WHERE (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente

View File

@ -82,11 +82,11 @@ BEGIN
AND Fechacobro > vFromDated AND Fechacobro > vFromDated
AND Fechacobro <= vToDated AND Fechacobro <= vToDated
UNION ALL UNION ALL
SELECT g.Id_Cliente, g.Importe SELECT clientFk, amount
FROM vn2008.Greuges g FROM vn.greuge
WHERE Greuges_type_id = vManaGreugeTypeId WHERE greugeTypeFk = vManaGreugeTypeId
AND Fecha > vFromDated AND shipped > vFromDated
AND Fecha <= vToDated AND shipped <= vToDated
UNION ALL UNION ALL
SELECT clientFk, mana SELECT clientFk, mana
FROM vn.clientManaCache FROM vn.clientManaCache

View File

@ -23,9 +23,9 @@ BEGIN
ENGINE = MEMORY ENGINE = MEMORY
SELECT Id_Ticket SELECT Id_Ticket
FROM vn2008.Tickets t FROM vn2008.Tickets t
JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura JOIN vn.invoiceOut io ON io.id = t.Factura
WHERE year(f.Fecha) = vYear WHERE year(io.issued) = vYear
AND month(f.Fecha) = vMonth; AND month(io.issued) = vMonth;
INSERT INTO bs.ventas_contables(year INSERT INTO bs.ventas_contables(year
, month , month

View File

@ -13,9 +13,9 @@ BEGIN
(PRIMARY KEY (Id_Ticket)) (PRIMARY KEY (Id_Ticket))
SELECT Id_Ticket SELECT Id_Ticket
FROM vn2008.Tickets t FROM vn2008.Tickets t
JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura JOIN vn.invoiceOut io ON io.id = t.Factura
WHERE year(f.Fecha) = vYear WHERE year(io.issued) = vYear
AND month(f.Fecha) = vMonth; AND month(io.issued) = vMonth;
SELECT vYear Año, SELECT vYear Año,
vMonth Mes, vMonth Mes,

View File

@ -24,20 +24,20 @@ BEGIN
WHERE date BETWEEN @datSTART WHERE date BETWEEN @datSTART
AND @datEND ) tm AND @datEND ) tm
LEFT JOIN LEFT JOIN
(SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra (SELECT DISTINCT tm.yearMonth, io.clientFk Id_Cliente , 1 as Compra
FROM vn2008.Facturas f FROM vn.invoiceOut io
JOIN vn2008.time tm ON tm.date = f.Fecha JOIN vn2008.time tm ON tm.date = io.issued
WHERE Fecha BETWEEN @datSTART WHERE io.issued BETWEEN @datSTART
AND @datEND) f ON f.yearMonth = tm.yearMonth AND @datEND) f ON f.yearMonth = tm.yearMonth
AND f.Id_Cliente = c.Id_Cliente; AND f.Id_Cliente = c.Id_Cliente;
UPDATE tmp.VivosMuertos vm UPDATE tmp.VivosMuertos vm
JOIN JOIN
(SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente (SELECT MIN(tm.yearMonth) firstMonth, io.clientFk Id_Cliente
FROM vn2008.Facturas f FROM vn.invoiceOut io
JOIN vn2008.time tm ON tm.date = f.Fecha JOIN vn2008.time tm ON tm.date = io.issued
WHERE Fecha BETWEEN @datSTART AND @datEND WHERE io.issued BETWEEN @datSTART AND @datEND
GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth GROUP BY io.clientFk) fm ON fm.firstMonth = vm.yearMonth
AND fm.Id_Cliente = vm.Id_Cliente AND fm.Id_Cliente = vm.Id_Cliente
SET Nuevo = 1; SET Nuevo = 1;
@ -46,11 +46,11 @@ BEGIN
UPDATE tmp.VivosMuertos vm UPDATE tmp.VivosMuertos vm
JOIN ( JOIN (
SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente SELECT MAX(tm.yearMonth) firstMonth, io.clientFk Id_Cliente
FROM vn2008.Facturas f FROM vn.invoiceOut io
JOIN vn2008.time tm ON tm.date = f.Fecha JOIN vn2008.time tm ON tm.date = io.issued
WHERE Fecha BETWEEN @datSTART AND @datEND WHERE io.issued BETWEEN @datSTART AND @datEND
GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth GROUP BY io.clientFk) fm ON fm.firstMonth = vm.yearMonth
AND fm.Id_Cliente = vm.Id_Cliente AND fm.Id_Cliente = vm.Id_Cliente
SET Muerto = 1 SET Muerto = 1

View File

@ -5,7 +5,8 @@ proc: BEGIN
DECLARE vReserveDate DATETIME; DECLARE vReserveDate DATETIME;
DECLARE vParams CHAR(100); DECLARE vParams CHAR(100);
DECLARE vInventoryDate DATE; DECLARE vInventoryDate DATE;
DECLARE vIsLogifloraDay BOOLEAN; DECLARE vLifeScope DATE;
DECLARE vWarehouseFkInventory INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN BEGIN
@ -26,43 +27,42 @@ proc: BEGIN
LEAVE proc; LEAVE proc;
END IF; END IF;
-- Invoca al procedimiento que genera el stock virtual de Logiflora, si coincide con la peticion de refresco del disponible
IF vn.isLogifloraDay(vDated, vWarehouse) THEN
-- CALL edi.floramondo_offerRefresh;
SET vIsLogifloraDay = TRUE;
ELSE
SET vIsLogifloraDay = FALSE;
END IF;
-- Calcula algunos parámetros necesarios -- Calcula algunos parámetros necesarios
SET vStartDate = TIMESTAMP(vDated, '00:00:00'); SET vStartDate = TIMESTAMP(vDated, '00:00:00');
SELECT inventoried INTO vInventoryDate FROM vn.config; SELECT inventoried INTO vInventoryDate FROM vn.config;
SELECT DATE_SUB(vStartDate, INTERVAL MAX(life) DAY) INTO vLifeScope FROM vn.itemType;
SELECT SUBTIME(util.VN_NOW(), reserveTime) INTO vReserveDate SELECT SUBTIME(util.VN_NOW(), reserveTime) INTO vReserveDate
FROM hedera.orderConfig; FROM hedera.orderConfig;
SELECT w.id INTO vWarehouseFkInventory
FROM vn.warehouse w
WHERE w.code = 'inv';
-- Calcula el ultimo dia de vida para cada producto -- Calcula el ultimo dia de vida para cada producto
DROP TEMPORARY TABLE IF EXISTS itemRange; DROP TEMPORARY TABLE IF EXISTS itemRange;
CREATE TEMPORARY TABLE itemRange CREATE TEMPORARY TABLE itemRange
(PRIMARY KEY (itemFk)) (PRIMARY KEY (itemFk))
ENGINE = MEMORY ENGINE = MEMORY
SELECT c.itemFk, SELECT i.id itemFk,
IF(it.life IS NULL, util.dayEnd(DATE_ADD(c.maxLanded, INTERVAL it.life DAY)) ended, it.life
NULL, FROM vn.item i
TIMESTAMP(TIMESTAMPADD(DAY, it.life, c.landing), '23:59:59')) ended LEFT JOIN (
FROM ( SELECT b.itemFk, MAX(t.landed) maxLanded
SELECT b.itemFk, MAX(t.landed) landing FROM vn.buy b
FROM vn.buy b JOIN vn.entry e ON b.entryFk = e.id
JOIN vn.entry e ON b.entryFk = e.id JOIN vn.travel t ON t.id = e.travelFk
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 JOIN vn.item i ON i.id = b.itemFk
WHERE t.landed BETWEEN vInventoryDate AND vStartDate JOIN vn.itemType it ON it.id = i.typeFk
AND t.warehouseInFk = vWarehouse WHERE t.landed BETWEEN vLifeScope AND vStartDate
AND NOT e.isExcludedFromAvailable AND t.warehouseInFk = vWarehouse
GROUP BY b.itemFk AND t.warehouseOutFk <> vWarehouseFkInventory
) c AND it.life
JOIN vn.item i ON i.id = c.itemFk AND NOT e.isExcludedFromAvailable
GROUP BY b.itemFk
) c ON i.id = c.itemFk
JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.itemType it ON it.id = i.typeFk
HAVING ended >= vStartDate OR ended IS NULL; HAVING ended >= vStartDate OR life IS NULL;
-- Calcula el ATP -- Calcula el ATP
DELETE FROM available WHERE calc_id = vCalc; DELETE FROM available WHERE calc_id = vCalc;
@ -86,7 +86,7 @@ proc: BEGIN
WHERE i.landed >= vStartDate WHERE i.landed >= vStartDate
AND (ir.ended IS NULL OR i.landed <= ir.ended) AND (ir.ended IS NULL OR i.landed <= ir.ended)
AND i.warehouseInFk = vWarehouse AND i.warehouseInFk = vWarehouse
AND (ISNULL(wf.entryFk) OR vIsLogifloraDay) AND ISNULL(wf.entryFk)
UNION ALL UNION ALL
SELECT i.itemFk, i.shipped, i.quantity SELECT i.itemFk, i.shipped, i.quantity
FROM vn.itemEntryOut i FROM vn.itemEntryOut i

View File

@ -22,6 +22,7 @@ proc:BEGIN
DECLARE vHasItemGroup BOOL; DECLARE vHasItemGroup BOOL;
DECLARE vDescription VARCHAR(255); DECLARE vDescription VARCHAR(255);
DECLARE vSaleFk INT; DECLARE vSaleFk INT;
DECLARE vDefaultEntry INT;
-- Carga los datos necesarios del EKT -- 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),
@ -41,6 +42,9 @@ proc:BEGIN
CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription); CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription);
LEAVE proc; LEAVE proc;
END IF; END IF;
SELECT defaultEntry INTO vDefaultEntry
FROM vn.entryConfig;
-- Asigna la entrada -- Asigna la entrada
SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk; SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk;
@ -100,10 +104,9 @@ proc:BEGIN
LEFT JOIN ekt l ON l.ref = e.ref LEFT JOIN ekt l ON l.ref = e.ref
LEFT JOIN vn.buy b ON b.ektFk = l.id LEFT JOIN vn.buy b ON b.ektFk = l.id
LEFT JOIN vn.item i ON i.id = b.itemFk LEFT JOIN vn.item i ON i.id = b.itemFk
JOIN vn2008.config cfg
WHERE e.id = vSelf WHERE e.id = vSelf
AND l.id != vSelf AND l.id != vSelf
AND b.itemFk != cfg.generic_item AND b.itemFk != vDefaultEntry
AND IF(t.s1, l.s1 = e.s1, TRUE) AND IF(t.s1, l.s1 = e.s1, TRUE)
AND IF(t.s2, l.s2 = e.s2, TRUE) AND IF(t.s2, l.s2 = e.s2, TRUE)
AND IF(t.s3, l.s3 = e.s3, TRUE) AND IF(t.s3, l.s3 = e.s3, TRUE)
@ -142,7 +145,7 @@ proc:BEGIN
SELECT vEntryFk, SELECT vEntryFk,
vSelf, vSelf,
(@t := IF(i.stems, i.stems, 1)) * e.pri / IFNULL(i.stemMultiplier, 1) buyingValue, (@t := IF(i.stems, i.stems, 1)) * e.pri / IFNULL(i.stemMultiplier, 1) buyingValue,
IFNULL(vItem, cfg.generic_item) itemFk, IFNULL(vItem, vDefaultEntry) itemFk,
e.qty stickers, e.qty stickers,
@pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing, @pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing,
IFNULL(b.`grouping`, e.pac), IFNULL(b.`grouping`, e.pac),
@ -153,8 +156,7 @@ proc:BEGIN
FROM ekt e FROM ekt e
LEFT JOIN vn.buy b ON b.id = vBuy LEFT JOIN vn.buy b ON b.id = vBuy
LEFT JOIN vn.item i ON i.id = b.itemFk LEFT JOIN vn.item i ON i.id = b.itemFk
LEFT JOIN vn.supplier s ON e.pro = s.id LEFT JOIN vn.supplier s ON e.pro = s.id
JOIN vn2008.config cfg
WHERE e.id = vSelf WHERE e.id = vSelf
LIMIT 1; LIMIT 1;

View File

@ -2,7 +2,7 @@ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`ekt_scan`(vBarcode VARCHAR(512)) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`ekt_scan`(vBarcode VARCHAR(512))
BEGIN BEGIN
/** /**
* Busca transaciones a partir de un código de barras, las marca como escaneadas * Busca transaciones a partir de un codigo de barras, las marca como escaneadas
* y las devuelve. * y las devuelve.
* Ver https://wiki.verdnatura.es/index.php/Ekt#Algoritmos_de_lectura * Ver https://wiki.verdnatura.es/index.php/Ekt#Algoritmos_de_lectura
* *
@ -73,7 +73,7 @@ BEGIN
INSERT INTO tmp.ekt INSERT INTO tmp.ekt
SELECT id SELECT id
FROM ekt FROM ekt
WHERE fec = vFec WHERE fec >= vFec - INTERVAL 1 DAY
AND (( AND ((
vKlo = vDefaultKlo vKlo = vDefaultKlo
AND (klo = vKlo OR klo IS NULL OR klo = 0) AND (klo = vKlo OR klo IS NULL OR klo = 0)
@ -82,7 +82,7 @@ BEGIN
AND auction = vAuction AND auction = vAuction
AND agj = vShortAgj) AND agj = vShortAgj)
) )
ORDER BY agj DESC ORDER BY agj DESC, fec DESC
LIMIT 1; LIMIT 1;
SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; SELECT COUNT(*) FROM tmp.ekt INTO vIsFound;

View File

@ -0,0 +1,6 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `edi`.`ektK2`
AS SELECT `eek`.`id` AS `id`,
`eek`.`description` AS `description`
FROM `edi`.`ektK1` `eek`

View File

@ -0,0 +1,58 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `util`.`accountNumberToIban`(
vAccount VARCHAR(20)
)
RETURNS varchar(4) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
DETERMINISTIC
BEGIN
/**
* Calcula y genera el código IBAN correspondiente
* a un número de cuenta bancaria español.
*
* @param vAccount Número de cuenta bancaria
* @return vIban Código IBAN de 4 caracteres.
*/
DECLARE vIban VARCHAR(4);
SELECT
CONCAT('ES',
RIGHT(
CONCAT(0,
98-MOD(
CONCAT(
MOD(
CONCAT(
MOD(
CONCAT(
MOD(
SUBSTRING(vAccount, 1, 8),
97
),
SUBSTRING(vAccount,9,8)
),
97
),
SUBSTRING(
CONCAT(vAccount, 142800),
17,
8
)
),
97
),
SUBSTRING(
CONCAT(vAccount, 142800),
25,
2
)
),
97
)
),
2
)
) INTO vIban;
RETURN vIban;
END$$
DELIMITER ;

View File

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

View File

@ -16,8 +16,8 @@ BEGIN
FROM ( FROM (
SELECT DISTINCT t.Id_Ruta SELECT DISTINCT t.Id_Ruta
FROM vn2008.scan_line sl FROM vn2008.scan_line sl
JOIN vn2008.expeditions e ON e.expeditions_id = sl.code JOIN expedition e ON e.id = sl.code
JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticket_id JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticketFk
WHERE sl.scan_id = vScanId WHERE sl.scan_id = vScanId
AND t.Id_Ruta AND t.Id_Ruta
) t1; ) t1;

View File

@ -1,14 +0,0 @@
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 ;

View File

@ -0,0 +1,41 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_check`()
BEGIN
/**
* Realiza la revisión diaria de los asientos contables,
* identificando y notificando los asientos descuadrados
* y ajustando los saldos en caso necesario.
*/
INSERT INTO mail (receiver, subject, body)
SELECT 'cau@verdnatura.es',
'Asientos descuadrados',
GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n')
FROM (
SELECT ASIEN,
SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon
FROM XDiario
WHERE NOT enlazado
GROUP BY ASIEN
HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01
) sub
HAVING COUNT(*);
UPDATE XDiario xd
JOIN (
SELECT xd.id, SUBCTA, recon
FROM XDiario xd
JOIN (
SELECT ASIEN,
SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon
FROM XDiario
WHERE NOT enlazado
GROUP BY ASIEN
HAVING recon
) sub ON sub.ASIEN = xd.ASIEN
WHERE xd.SUBCTA > '5999999999'
GROUP BY xd.ASIEN
) sub ON sub.id = xd.id
SET xd.Eurohaber = IF(IFNULL(xd.Eurohaber, 0) = 0, xd.Eurohaber, xd.Eurohaber + sub.recon),
xd.Eurodebe = IF(IFNULL(xd.Eurodebe, 0) = 0, xd.Eurodebe, xd.Eurodebe - sub.recon);
END$$
DELIMITER ;

View File

@ -16,7 +16,7 @@ BEGIN
LEFT JOIN vn.supplier s LEFT JOIN vn.supplier s
ON s.id = bp.supplierFk ON s.id = bp.supplierFk
LEFT JOIN vn.bank b LEFT JOIN vn.bank b
ON b.id = bp.bankFk ON b.id = bp.accountingFk
WHERE bp.insuranceExpired = util.VN_CURDATE(); WHERE bp.insuranceExpired = util.VN_CURDATE();
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -74,6 +74,8 @@ BEGIN
WHERE b.id = vSelf; WHERE b.id = vSelf;
END IF; END IF;
CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck
SELECT vSelf id;
CALL buy_checkItem();
END$$ END$$
DELIMITER ; DELIMITER ;

View File

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

View File

@ -90,6 +90,7 @@ BEGIN
FROM vn.expeditionTruck FROM vn.expeditionTruck
WHERE eta < v3Month; WHERE eta < v3Month;
DELETE FROM XDiario WHERE FECHA < v3Month OR FECHA IS NULL;
-- borrar travels sin entradas -- borrar travels sin entradas
DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete; DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete;
CREATE TEMPORARY TABLE tmp.thermographToDelete CREATE TEMPORARY TABLE tmp.thermographToDelete

View File

@ -48,7 +48,7 @@ BEGIN
SELECT lc.companyFk, SELECT lc.companyFk,
c.id, c.id,
0, 0,
- (NZ(lc.credit) - NZ(lc.debit)) - (IFNULL(lc.credit, 0) - IFNULL(lc.debit, 0))
FROM tmp.ledgerComparative lc FROM tmp.ledgerComparative lc
JOIN client c ON c.accountingAccount = lc.account JOIN client c ON c.accountingAccount = lc.account
WHERE lc.`date` BETWEEN vDateFrom AND vDateTo WHERE lc.`date` BETWEEN vDateFrom AND vDateTo

View File

@ -70,9 +70,9 @@ BEGIN
ish.created, ish.created,
ish.visible, ish.visible,
IFNULL( IFNULL(
IF(st.description = 'previousByPacking', ish.packing, g.`grouping`), IF(st.code = 'previousByPacking', ish.packing, g.`grouping`),
1) `grouping`, 1) `grouping`,
st.description = 'previousPrepared' isPreviousPrepared, st.code = 'previousPrepared' isPreviousPrepared,
iss.id itemShelvingSaleFk, iss.id itemShelvingSaleFk,
ts.ticketFk, ts.ticketFk,
iss.id, iss.id,

View File

@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaInvoiceInBooking
BEGIN BEGIN
/** /**
* Genera el asiento de un DUA y marca las entradas como confirmadas * Genera el asiento de un DUA y marca las entradas como confirmadas
* *
* @param vDuaFk Id del dua a recalcular * @param vDuaFk Id del dua a recalcular
*/ */
DECLARE done BOOL DEFAULT FALSE; DECLARE done BOOL DEFAULT FALSE;
@ -23,7 +23,7 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN rs; OPEN rs;
UPDATE invoiceIn ii UPDATE invoiceIn ii
JOIN entry e ON e.invoiceInFk = ii.id JOIN entry e ON e.invoiceInFk = ii.id
JOIN duaEntry de ON de.entryFk = e.id JOIN duaEntry de ON de.entryFk = e.id
@ -41,34 +41,34 @@ BEGIN
WHERE id = vDuaFk; WHERE id = vDuaFk;
FETCH rs INTO vInvoiceFk; FETCH rs INTO vInvoiceFk;
WHILE NOT done DO WHILE NOT done DO
CALL invoiceIn_booking(vInvoiceFk); CALL invoiceIn_booking(vInvoiceFk);
IF vCounter > 0 OR vASIEN > 0 THEN IF vCounter > 0 OR vASIEN > 0 THEN
UPDATE vn2008.XDiario x UPDATE XDiario x
JOIN ledgerConfig lc ON lc.lastBookEntry = x.ASIEN JOIN ledgerConfig lc ON lc.lastBookEntry = x.ASIEN
SET x.ASIEN = vASIEN; SET x.ASIEN = vASIEN;
ELSE ELSE
SELECT lastBookEntry INTO vASIEN FROM ledgerConfig; SELECT lastBookEntry INTO vASIEN FROM ledgerConfig;
END IF; END IF;
SET vCounter = vCounter + 1; SET vCounter = vCounter + 1;
FETCH rs INTO vInvoiceFk; FETCH rs INTO vInvoiceFk;
END WHILE; END WHILE;
CLOSE rs; CLOSE rs;
UPDATE dua UPDATE dua
SET ASIEN = vASIEN SET ASIEN = vASIEN
WHERE id = vDuaFk; WHERE id = vDuaFk;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,211 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_getTransfer`(
vSelf INT
)
BEGIN
/**
* Retorna los artículos trasladables a partir de una entrada.
*
* @param vSelf Id de entrada
*/
DECLARE vDateShipped DATE;
DECLARE vDateLanded DATE;
DECLARE vWarehouseIn INT;
DECLARE vWarehouseOut INT;
DECLARE vCalcVisible INT;
DECLARE vInventoryDate DATE DEFAULT vn.getInventoryDate();
SELECT shipped, landed, warehouseInFk, warehouseOutFk
INTO vDateShipped, vDateLanded, vWarehouseIn, vWarehouseOut
FROM vn.travel t
JOIN vn.entry e ON e.travelFk = t.id
WHERE e.id = vSelf;
CALL vn.rate_getPrices(vDateShipped, vWarehouseIn);
-- Traslado en almacen origen
CREATE OR REPLACE TEMPORARY TABLE tBuy
(PRIMARY KEY (itemFk), INDEX(buyFk))
ENGINE = MEMORY
SELECT *
FROM (
SELECT b.itemFk, b.id buyFk
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vInventoryDate AND vDateShipped
AND NOT b.isIgnored
AND b.price2 >= 0
ORDER BY (vWarehouseOut = t.warehouseInFk) DESC, t.landed DESC
LIMIT 10000000000000000000
) sub
GROUP BY itemFk;
IF vDateShipped >= util.VN_CURDATE() THEN
CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseOut);
CREATE OR REPLACE TEMPORARY TABLE tItem (
`itemFk` int(10) unsigned NOT NULL,
`visible` int(11) NOT NULL DEFAULT 0,
`available` int(11) NOT NULL DEFAULT 0,
`visibleLanding` int(11) NOT NULL DEFAULT 0,
`availableLanding` int(11) NOT NULL DEFAULT 0,
UNIQUE INDEX i USING HASH (itemFk)
) ENGINE = MEMORY;
INSERT INTO tItem(itemFk, visible)
SELECT item_id itemFk, visible
FROM `cache`.visible
WHERE calc_id = vCalcVisible
AND visible;
CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseIn);
INSERT INTO tItem(itemFk, visibleLanding)
SELECT item_id, `visible`
FROM `cache`.`visible` v
WHERE v.calc_id = vCalcVisible
AND v.`visible`
ON DUPLICATE KEY UPDATE visibleLanding = v.`visible`;
CALL vn2008.availableTraslate(vWarehouseOut, vDateShipped, NULL);
INSERT INTO tItem(itemFk, available)
SELECT a.item_id, a.available
FROM vn2008.availableTraslate a
WHERE a.available
ON DUPLICATE KEY UPDATE available = a.available;
CALL vn2008.availableTraslate(vWarehouseIn, vDateLanded, vWarehouseOut);
INSERT INTO tItem(itemFk, availableLanding)
SELECT a.item_id, a.available
FROM vn2008.availableTraslate a
WHERE a.available
ON DUPLICATE KEY UPDATE availableLanding = a.available;
ELSE
CALL vn.item_getStock(vWarehouseOut, vDateShipped, NULL);
CREATE OR REPLACE TEMPORARY TABLE tItem
(UNIQUE INDEX i USING HASH (itemFk))
ENGINE = MEMORY
SELECT itemFk,
`visible`,
available,
0 visibleLanding,
0 availableLanding
FROM tmp.itemList;
END IF;
CALL vn.buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded);
CREATE OR REPLACE TEMPORARY TABLE tTransfer
ENGINE = MEMORY
SELECT it.code `type`,
it.categoryFk,
i.typeFk,
i.id itemFk,
i.name item,
i.`size`,
i.category,
i.inkFk,
o.code originCode,
b2.quantity,
i.stems,
CAST(ti.visible AS DECIMAL(10,0)) vis1,
CAST(ti.available AS DECIMAL(10,0)) ava1,
CAST(ti.visibleLanding AS DECIMAL(10,0)) vis2,
CAST(ti.availableLanding AS DECIMAL(10,0)) ava2,
COALESCE(b2.`grouping`, b.`grouping`) `grouping`,
COALESCE(b2.packing, b.packing) packing,
COALESCE(b3.groupingMode, b2.groupingMode, b.groupingMode) package,
IFNULL(p.name, s.nickname) productor,
TRUE tinta,
b.packagingFk,
b2.id buyFk,
b2.stickers,
b.ektFk,
it.workerFk,
pa.volume,
IFNULL(pa.width, 0) width,
IFNULL(pa.`depth`, 0) `depth`,
IFNULL(pa.height, 0) height,
IFNULL(b.buyingValue, 0) buyingValue,
IFNULL(b.comissionValue, 0) comissionValue,
IFNULL(b.freightValue, 0) freightValue,
am.m3,
e.commission,
pa.isPackageReturnable,
IFNULL(pa2.value, pa.value) `value`,
r.rate3 r3,
r.rate2 r2,
it.promo,
b.`grouping` groupingOrigin,
b.packing packingOrigin,
b.id buyFkOrigin,
pa.returnCost,
b.weight
FROM vn.item i
JOIN tItem ti ON ti.itemFk = i.id
LEFT JOIN vn.producer p ON p.id = i.producerFk
LEFT JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN vn.origin o ON o.id = i.originFk
LEFT JOIN tBuy lb ON lb.itemFk = i.id
LEFT JOIN vn.buy b ON b.id = lb.buyFk
LEFT JOIN vn.packaging pa ON pa.id = b.packagingFk
LEFT JOIN vn.entry e2 ON e2.id = b.entryFk
LEFT JOIN vn.supplier s ON s.id = e2.supplierFk
LEFT JOIN vn.entry e ON e.id = vSelf
LEFT JOIN vn.travel tr ON tr.id = e.travelFk
LEFT JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
LEFT JOIN vn.buy b2 ON b2.itemFk = i.id
AND b2.entryFk = vSelf
LEFT JOIN vn.packaging pa2 ON pa2.id = b.packagingFk
LEFT JOIN tmp.rate r ON TRUE
LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id
LEFT JOIN vn.buy b3 ON b3.id = bufi.buyFk
WHERE ic.display
AND NOT e.isRaid
AND (ti.visible OR ti.available)
ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name;
CREATE INDEX tIndex USING HASH ON tTransfer (itemFk);
SET @carriage := 0;
SET @comission := 0;
SET @packaging := 0;
SET @rate3 := 0;
SET @cost := 0;
SELECT *,
quantity - MOD(quantity , `grouping`) subQuantity,
MOD(quantity, `grouping`) soll,
ROUND((IF(volume > 0,volume, width * `depth` *
IF(height = 0, `size` + 10, height))) /
packing, 0) cm3,
buyingValue + comissionValue + freightValue cost,
@carriage := ROUND((IF(volume > 0, volume, width * `depth` *
IF(height = 0, `size` + 10, height))) *
m3 / 1000000 / Packing, 3) carriage,
@comission := ROUND((buyingValue + comissionValue + freightValue) *
commission / 100, 3) commission,
ROUND(@packaging := (returnCost + IF(isPackageReturnable, 0, value))
/ packing, 3) packaging,
@cost := IFNULL((buyingValue + comissionValue + freightValue), 0) +
IFNULL(@packaging, 0) +
IFNULL(@carriage, 0) +
IFNULL(@comission, 0) expense,
@rate3 := ROUND(@cost / ( (100 - r3 - promo) / 100), 2) rate3,
ROUND(@rate3 * (1 + ((r2 - r3)/100)), 2) rate2,
FALSE selected
FROM tTransfer;
DROP TEMPORARY TABLE IF EXISTS
tTransfer,
tItem,
tBuy,
tmp.buyUltimateFromInterval,
tmp.rate,
tmp.itemList;
END$$
DELIMITER ;

View File

@ -1,79 +0,0 @@
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 ;

View File

@ -1,36 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`fustControlDetail`(vFromDated DATE, vToDated DATE)
BEGIN
DECLARE vSijsnerClientFk INT DEFAULT 19752;
DECLARE vDateStart DATETIME;
DECLARE vDateEnd DATETIME;
SET vDateStart = vFromDated;
SET vDateEnd = util.Dayend(vToDated);
SELECT a.nickname shopName,
a.city ,
IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode,
tp.quantity,
tp.ticketFk,
CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange
FROM vn.ticketPackaging tp
JOIN vn.ticket t ON t.id = tp.ticketFk
JOIN vn.warehouse w ON w.id = t.warehouseFk
JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk
JOIN vn.packaging p ON p.id = tp.packagingFk
LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.province p2 ON p2.id = a.provinceFk
JOIN vn.country c ON c.id = p2.countryFk
WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated)
AND wa.name = 'VNH'
AND p.isPackageReturnable
AND c.country = 'FRANCIA'
AND t.clientFk != vSijsnerClientFk
AND tp.quantity > 0;
END$$
DELIMITER ;

View File

@ -3,13 +3,13 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`getDayExpeditions`(
BEGIN BEGIN
SELECT SELECT
e.expeditions_id as expeditionFk, e.id as expeditionFk,
date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate, date_format(e.created,'%Y-%m-%d') as expeditionDate,
e.ticket_id as ticketFk, e.ticketFk,
t.routeFk as routeFk t.routeFk as routeFk
FROM vn2008.expeditions e FROM expedition e
INNER JOIN vn.ticket t ON t.id = e.ticket_id INNER JOIN ticket t ON t.id = e.ticketFk
WHERE DATE(odbc_date) = util.VN_CURDATE(); WHERE DATE(e.created) = util.VN_CURDATE();
END$$ END$$
DELIMITER ; DELIMITER ;

View File

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

View File

@ -50,31 +50,30 @@ BEGIN
) alb ON alb.itemFk = i.id ) alb ON alb.itemFk = i.id
LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk
LEFT JOIN ( LEFT JOIN (
SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta
FROM vn2008.item_out FROM itemTicketOut
WHERE dat BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
AND warehouse_id = vWarehouseFk AND warehouseFk = vWarehouseFk
GROUP BY item_id GROUP BY itemFk
) sale ON sale.item_id = i.id ) sale ON sale.item_id = i.id
LEFT JOIN ( LEFT JOIN (
SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra
FROM vn2008.item_entry_in FROM itemEntryIn
WHERE dat BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) WHERE landed BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
AND warehouse_id = vWarehouseFk AND warehouseInFk = vWarehouseFk
AND isVirtualStock = FALSE AND isVirtualStock = FALSE
GROUP BY item_id GROUP BY itemFk
) buy ON buy.item_id = i.id ) buy ON buy.item_id = i.id
LEFT JOIN ( LEFT JOIN (
SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado
FROM vn2008.item_entry_out FROM itemEntryOut
WHERE dat BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
AND warehouse_id = vWarehouseFk AND warehouseOutFk = vWarehouseFk
GROUP BY item_id GROUP BY itemFk
) mov ON mov.item_id = i.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 i.itemPackingTypeFk = 'H'
AND ic.shortLife AND ic.shortLife;
;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -8,27 +8,22 @@ BEGIN
* @param vItemFk Identificador de vn.item * @param vItemFk Identificador de vn.item
* @param vSectorFk Identificador de vn.sector * @param vSectorFk Identificador de vn.sector
*/ */
DECLARE vWarehouseAliasFk INT;
SELECT w.aliasFk INTO vWarehouseAliasFk
FROM vn.sector s
JOIN vn.warehouse w ON w.id = s.warehouseFk
WHERE s.id = vSectorFk;
SELECT ish.shelvingFk shelving, SELECT ish.shelvingFk shelving,
p.code parking, p.code parking,
sum(ish.visible) as stockTotal, SUM(ish.visible) stockTotal,
ish.created, ish.created,
p.pickingOrder p.pickingOrder
FROM vn.itemShelving ish FROM vn.itemShelving ish
JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector sc ON sc.id = p.sectorFk JOIN vn.sector sc ON sc.id = p.sectorFk
JOIN vn.warehouse w ON w.id = sc.warehouseFk JOIN vn.warehouse w ON w.id = sc.warehouseFk
WHERE w.aliasFk = vWarehouseAliasFk WHERE sc.id = vSectorFk
AND ish.visible > 0 AND ish.visible > 0
AND ish.itemFk = vItemFk AND ish.itemFk = vItemFk
GROUP BY ish.id GROUP BY ish.id
ORDER BY (sc.id = vSectorFk) DESC, sh.priority DESC, ish.created, p.pickingOrder; ORDER BY sh.priority DESC,
ish.created,
p.pickingOrder;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -143,12 +143,12 @@ proc:BEGIN
CREATE TEMPORARY TABLE tmp.itemOutTime CREATE TEMPORARY TABLE tmp.itemOutTime
SELECT *,SUM(amount) quantity SELECT *,SUM(amount) quantity
FROM FROM
(SELECT item_id itemFk, (SELECT io.itemFk,
amount, io.quantity amount,
IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours,
IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes
FROM vn2008.item_out io FROM itemTicketOut io
JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.itemFk
JOIN vn.ticket t on t.id= io.ticketFk JOIN vn.ticket t on t.id= io.ticketFk
JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk
JOIN vn.state s ON s.id = ts.stateFk JOIN vn.state s ON s.id = ts.stateFk
@ -160,10 +160,10 @@ proc:BEGIN
) stPrevious ON `stPrevious`.`saleFk` = io.saleFk ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk
WHERE t.warehouseFk = vWarehouseFk WHERE t.warehouseFk = vWarehouseFk
AND s.isPicked = 0 AND s.isPicked = 0
AND NOT io.Reservado AND NOT io.reserved
AND stPrevious.saleFk IS NULL AND stPrevious.saleFk IS NULL
AND io.dat >= util.VN_CURDATE() AND io.shipped >= util.VN_CURDATE()
AND io.dat < util.VN_CURDATE() + INTERVAL 1 DAY AND io.shipped < util.VN_CURDATE() + INTERVAL 1 DAY
) sub ) sub
GROUP BY itemFk, hours, minutes; GROUP BY itemFk, hours, minutes;

View File

@ -15,11 +15,13 @@ BEGIN
p.code, p.code,
ish.id, ish.id,
s.priority, s.priority,
ish.isChecked ish.isChecked,
ic.url
FROM itemShelving ish FROM itemShelving ish
JOIN item i ON i.id = ish.itemFk JOIN item i ON i.id = ish.itemFk
JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci
LEFT JOIN parking p ON s.parkingFk = p.id LEFT JOIN parking p ON s.parkingFk = p.id
JOIN hedera.imageConfig ic
WHERE ish.shelvingFk COLLATE utf8_unicode_ci = vSelf; WHERE ish.shelvingFk COLLATE utf8_unicode_ci = vSelf;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -23,7 +23,8 @@ BEGIN
SUM(IFNULL(sub.amount,0)) lack, SUM(IFNULL(sub.amount,0)) lack,
i.inkFk, i.inkFk,
IFNULL(im.timed, util.midnight()) timed, IFNULL(im.timed, util.midnight()) timed,
IFNULL(izc.timed, util.midnight()) minTimed IFNULL(izc.timed, util.midnight()) minTimed,
o.name originFk
FROM (SELECT item_id, FROM (SELECT item_id,
warehouse_id, warehouse_id,
amount amount
@ -42,6 +43,7 @@ BEGIN
JOIN itemCategory ic ON ic.id = it.categoryFk JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id
LEFT JOIN tmp.itemZoneClosure izc ON izc.itemFk = i.id LEFT JOIN tmp.itemZoneClosure izc ON izc.itemFk = i.id
JOIN origin o ON o.id = i.originFk
WHERE w.isForTicket WHERE w.isForTicket
AND ic.display AND ic.display
AND it.code != 'GEN' AND it.code != 'GEN'

View File

@ -207,7 +207,7 @@ proc: BEGIN
ENGINE = MEMORY ENGINE = MEMORY
SELECT ish.itemFk, SELECT ish.itemFk,
p.sectorFk, p.sectorFk,
st.description = 'previousPrepared' isPreviousPrepared, st.code = 'previousPrepared' isPreviousPrepared,
sc.itemPackingTypeFk sc.itemPackingTypeFk
FROM itemShelving ish FROM itemShelving ish
JOIN shelving sh ON sh.code = ish.shelvingFk JOIN shelving sh ON sh.code = ish.shelvingFk

View File

@ -85,7 +85,7 @@ BEGIN
JOIN client c ON c.id = t.clientFk JOIN client c ON c.id = t.clientFk
JOIN tmp.productionBuffer pb ON pb.ticketFk = t.id JOIN tmp.productionBuffer pb ON pb.ticketFk = t.id
JOIN packagingConfig pc JOIN packagingConfig pc
WHERE IF(st.description = 'previousByPacking', WHERE IF(st.code = 'previousByPacking',
i.`size` > pc.previousPreparationMinimumSize i.`size` > pc.previousPreparationMinimumSize
AND (MOD(TRUNCATE(isa.quantity,0), isa.packing)= 0 ), AND (MOD(TRUNCATE(isa.quantity,0), isa.packing)= 0 ),
TRUE) TRUE)

View File

@ -21,11 +21,8 @@ BEGIN
DECLARE vAgencyModeFk INT; DECLARE vAgencyModeFk INT;
DECLARE vNewPrice DECIMAL(10,2); DECLARE vNewPrice DECIMAL(10,2);
DECLARE vOldPrice DECIMAL(10,2); DECLARE vOldPrice DECIMAL(10,2);
DECLARE vOption INT DEFAULT NULL; DECLARE vOption VARCHAR(255);
DECLARE vNewSaleFk INT; DECLARE vNewSaleFk INT;
DECLARE vChangePrice INT DEFAULT 1;
DECLARE vBuyerDiscount INT DEFAULT 4;
DECLARE vManaDiscount INT DEFAULT 3;
DECLARE vForceToGrouping INT DEFAULT 1; DECLARE vForceToGrouping INT DEFAULT 1;
DECLARE vForceToPacking INT DEFAULT 2; DECLARE vForceToPacking INT DEFAULT 2;
DECLARE vFinalPrice DECIMAL(10,2); DECLARE vFinalPrice DECIMAL(10,2);
@ -85,16 +82,13 @@ BEGIN
IF vNewPrice IS NULL THEN IF vNewPrice IS NULL THEN
CALL util.throw('price retrieval failed'); CALL util.throw('price retrieval failed');
END IF; END IF;
IF vNewPrice > vOldPrice THEN IF vNewPrice > vOldPrice THEN
SET vFinalPrice = vOldPrice; SET vFinalPrice = vOldPrice;
IF worker_isInDepartment('vt') THEN SET vOption = 'substitution';
SET vOption = vManaDiscount;
ELSE
SET vOption = vBuyerDiscount;
END IF;
ELSE ELSE
SET vFinalPrice = vNewPrice; SET vFinalPrice = vNewPrice;
SET vOption = vChangePrice; SET vOption = 'renewPrices';
END IF; END IF;
START TRANSACTION; START TRANSACTION;

View File

@ -34,26 +34,26 @@ BEGIN
) fue ON fue.itemFk = i.id ) fue ON fue.itemFk = i.id
LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk
LEFT JOIN ( LEFT JOIN (
SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta
FROM vn2008.item_out FROM itemTicketOut
WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
AND warehouse_id = vWarehouseFk AND warehouseFk = vWarehouseFk
GROUP BY item_id GROUP BY itemFk
) sale ON sale.item_id = i.id ) sale ON sale.item_id = i.id
LEFT JOIN ( LEFT JOIN (
SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra
FROM vn2008.item_entry_in FROM itemEntryIn
WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) WHERE landed BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
AND warehouse_id = vWarehouseFk AND warehouseInFk = vWarehouseFk
AND isVirtualStock = FALSE AND isVirtualStock = FALSE
GROUP BY item_id GROUP BY itemFk
) buy ON buy.item_id = i.id ) buy ON buy.item_id = i.id
LEFT JOIN ( LEFT JOIN (
SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado
FROM vn2008.item_entry_out FROM itemEntryOut
WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
AND warehouse_id = vWarehouseFk AND warehouseOutFk = vWarehouseFk
GROUP BY item_id GROUP BY itemFk
) mov ON mov.item_id = i.id ) mov ON mov.item_id = i.id
WHERE v.amount; WHERE v.amount;

View File

@ -60,7 +60,7 @@ BEGIN
SELECT lc.companyFk, SELECT lc.companyFk,
s.id, s.id,
0, 0,
- (NZ(lc.debit) - NZ(lc.credit)) - (IFNULL(lc.debit, 0) - IFNULL(lc.credit, 0))
FROM tmp.ledgerComparative lc FROM tmp.ledgerComparative lc
JOIN supplier s ON s.account = lc.account JOIN supplier s ON s.account = lc.account
WHERE lc.`date` BETWEEN vDateFrom AND vDateTo WHERE lc.`date` BETWEEN vDateFrom AND vDateTo

View File

@ -0,0 +1,139 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_statement`(
vSupplierFk INT,
vCurrencyFk INT,
vCompanyFk INT,
vOrderBy VARCHAR(15),
vIsConciliated BOOL
)
BEGIN
/**
* Crea un estado de cuenta de proveedores calculando
* los saldos en euros y en la moneda especificada.
*
* @param vSupplierFk Id del proveedor
* @param vCurrencyFk Id de la moneda
* @param vCompanyFk Id de la empresa
* @param vOrderBy Criterio de ordenación
* @param vIsConciliated Indica si está conciliado o no
* @return tmp.supplierStatement
*/
SET @euroBalance:= 0;
SET @currencyBalance:= 0;
CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement
ENGINE = MEMORY
SELECT *,
@euroBalance:= ROUND(
@euroBalance + IFNULL(paymentEuros, 0) -
IFNULL(invoiceEuros, 0), 2
) euroBalance,
@currencyBalance:= ROUND(
@currencyBalance + IFNULL(paymentCurrency, 0) -
IFNULL(invoiceCurrency, 0), 2
) currencyBalance
FROM (
SELECT * FROM
(
SELECT NULL bankFk,
ii.companyFk,
ii.serial,
ii.id,
CASE
WHEN vOrderBy = 'issued' THEN ii.issued
WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried
WHEN vOrderBy = 'booked' THEN ii.booked
WHEN vOrderBy = 'dueDate' THEN iid.dueDated
END dated,
CONCAT('S/Fra ', ii.supplierRef) sref,
IF(ii.currencyFk > 1,
ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3),
NULL
) changeValue,
CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros,
CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency,
NULL paymentEuros,
NULL paymentCurrency,
ii.currencyFk,
ii.isBooked,
c.code,
'invoiceIn' statementType
FROM invoiceIn ii
JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
JOIN currency c ON c.id = ii.currencyFk
WHERE ii.issued > '2014-12-31'
AND ii.supplierFk = vSupplierFk
AND vCurrencyFk IN (ii.currencyFk, 0)
AND vCompanyFk IN (ii.companyFk, 0)
AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated)
GROUP BY iid.id
UNION ALL
SELECT p.bankFk,
p.companyFk,
NULL,
p.id,
CASE
WHEN vOrderBy = 'issued' THEN p.received
WHEN vOrderBy = 'bookEntried' THEN p.received
WHEN vOrderBy = 'booked' THEN p.received
WHEN vOrderBy = 'dueDate' THEN p.dueDated
END,
CONCAT(IFNULL(pm.name, ''),
IF(pn.concept <> '',
CONCAT(' : ', pn.concept),
'')
),
IF(p.currencyFk > 1, p.divisa / p.amount, NULL),
NULL,
NULL,
p.amount,
p.divisa,
p.currencyFk,
p.isConciliated,
c.code,
'payment'
FROM payment p
LEFT JOIN currency c ON c.id = p.currencyFk
LEFT JOIN bank b ON b.id = p.bankFk
LEFT JOIN payMethod pm ON pm.id = p.payMethodFk
LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id
WHERE p.received > '2014-12-31'
AND p.supplierFk = vSupplierFk
AND vCurrencyFk IN (p.currencyFk, 0)
AND vCompanyFk IN (p.companyFk, 0)
AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated)
UNION ALL
SELECT NULL,
companyFk,
NULL,
se.id,
CASE
WHEN vOrderBy = 'issued' THEN se.dated
WHEN vOrderBy = 'bookEntried' THEN se.dated
WHEN vOrderBy = 'booked' THEN se.dated
WHEN vOrderBy = 'dueDate' THEN se.dueDated
END,
se.description,
1,
amount,
NULL,
NULL,
NULL,
currencyFk,
isConciliated,
c.`code`,
'expense'
FROM supplierExpense se
JOIN currency c ON c.id = se.currencyFk
WHERE se.supplierFk = vSupplierFk
AND vCurrencyFk IN (se.currencyFk,0)
AND vCompanyFk IN (se.companyFk,0)
AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated)
) sub
ORDER BY (dated IS NULL AND NOT isBooked),
dated,
IF(vOrderBy = 'dueDate', id, NULL)
LIMIT 10000000000000000000
) t;
END$$
DELIMITER ;

View File

@ -31,8 +31,8 @@ BEGIN
CALL util.throw('ASSIGN_ZONE_FIRST'); CALL util.throw('ASSIGN_ZONE_FIRST');
END IF; END IF;
SET vCanChangeState = ( SET vCanChangeState = ((
vStateCode <> 'ON_CHECKING' OR vStateCode <> 'ON_CHECKING' AND vStateCode <> 'CHECKED') OR
vticketAlertLevel < vPackedAlertLevel vticketAlertLevel < vPackedAlertLevel
)AND NOT ( )AND NOT (
vTicketStateCode IN ('CHECKED', 'CHECKING') vTicketStateCode IN ('CHECKED', 'CHECKING')
@ -51,5 +51,6 @@ BEGIN
ELSE ELSE
CALL util.throw('INCORRECT_TICKET_STATE'); CALL util.throw('INCORRECT_TICKET_STATE');
END IF; END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -0,0 +1,109 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_getDetailFromContinent`(
vContinentFk INT
)
BEGIN
/**
* Devuelve los detalles de los vuelos que tienen
* un almacén de salida de un continente.
*
* @param vContinentFk Id de continente
*/
DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK;
SELECT IFNULL(CONCAT(" ", entryFk), travelFk) travelAndEntry,
sub.*
FROM (
SELECT tr.id travelFk,
NULL entryFk,
TRUE isTravel,
am.name agency,
tr.ref,
tr.shipped,
wOut.name originBoxes,
tr.landed,
wIn.name destination,
SUM(b.stickers) stickers,
NULL evaNotes,
tr.kg,
CAST(SUM(b.weight * b.stickers) AS INT) loadedkg,
CAST(
SUM(vc.aerealVolumetricDensity *
b.stickers *
IF(p.volume,
p.volume,
p.width * p.depth * p.height
) / 1000000
) AS INT
) volumeKg,
NULL loadPriority,
NULL invoiceAmount,
s.nickname freighter,
NULL reference
FROM travel tr
LEFT JOIN supplier s ON s.id = tr.cargoSupplierFk
LEFT JOIN entry e ON e.travelFk = tr.id
LEFT JOIN buy b ON b.entryFk = e.id
LEFT JOIN packaging p ON p.id = b.packagingFk
LEFT JOIN item i ON i.id = b.itemFk
LEFT JOIN itemType it ON it.id = i.typeFk
JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
JOIN country co ON co.id = wOut.countryFk
JOIN agencyMode am ON am.id = tr.agencyModeFk
JOIN volumeConfig vc
WHERE tr.landed >= vDateFrom
AND co.continentFk = vContinentFk
GROUP BY tr.id
UNION ALL
SELECT e.travelFk,
e.id,
FALSE,
s.name,
e.invoiceNumber,
tr.shipped,
wOut.name,
tr.landed,
wIn.name,
SUM(b.stickers),
e.evaNotes,
NULL,
CAST(SUM(b.weight * b.stickers) AS INT),
CAST(
SUM(vc.aerealVolumetricDensity *
b.stickers *
IF(p.volume,
p.volume,
p.width * p.depth * p.height
) / 1000000
) AS INT
),
loadPriority,
e.invoiceAmount,
s2.nickname,
e.reference
FROM entry e
JOIN buy b ON b.entryFk = e.id
JOIN packaging p ON p.id = b.packagingFk
JOIN item i ON i.id = b.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN supplier s ON s.id = e.supplierFk
JOIN travel tr ON tr.id = e.travelFk
LEFT JOIN supplier s2 ON s2.id = tr.cargoSupplierFk
JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
JOIN country co ON co.id = wOut.countryFk
JOIN volumeConfig vc
WHERE tr.landed >= vDateFrom
AND co.continentFk = vContinentFk
GROUP BY e.id
) sub
ORDER BY landed ASC,
shipped ASC,
travelFk,
isTravel DESC,
(loadPriority > 0) DESC,
loadPriority,
agency,
evaNotes;
END$$
DELIMITER ;

View File

@ -75,7 +75,7 @@ BEGIN
SET vDated = DATE(vTimed); SET vDated = DATE(vTimed);
SELECT IF(pc.name = 'Conductor +3500kg', SELECT IF(pc.code = 'driveCE',
wc.dayBreakDriver, wc.dayBreakDriver,
wc.dayBreak), wc.dayBreak),
wc.shortWeekBreak, wc.shortWeekBreak,

View File

@ -0,0 +1,15 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`accountReconciliation_beforeInsert`
BEFORE INSERT ON `accountReconciliation`
FOR EACH ROW
SET NEW.calculatedCode = REPLACE(
REPLACE(
REPLACE(
REPLACE(
CONCAT(NEW.supplierAccountFk,NEW.operationDated,NEW.amount,NEW.concept,NEW.debitCredit)
,' ','')
,":",'')
,'-','')
,'.','')$$
DELIMITER ;

View File

@ -0,0 +1,15 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`awbInvoiceIn_afterDelete`
AFTER DELETE ON `awbInvoiceIn`
FOR EACH ROW
BEGIN
IF (NOT(SELECT COUNT(*) FROM invoiceInTax where invoiceInFk = OLD.invoiceInFk))
AND
(NOT(SELECT COUNT(*) FROM invoiceInDueDay where invoiceInFk = OLD.invoiceInFk))
AND
(NOT(SELECT isBooked FROM invoiceIn WHERE id = OLD.invoiceInFk) )
THEN
DELETE FROM invoiceIn WHERE id = OLD.invoiceInFk;
END IF;
END$$
DELIMITER ;

View File

@ -41,8 +41,8 @@ trig:BEGIN
FROM genericAllocation ga FROM genericAllocation ga
JOIN entry e ON e.id = NEW.entryFk JOIN entry e ON e.id = NEW.entryFk
JOIN travel tr on tr.id = e.travelFk JOIN travel tr on tr.id = e.travelFk
WHERE ga.itemFk = vGenericFk WHERE ga.itemFk = vGenericFk
AND tr.landed BETWEEN ga.startDated AND ga.endDated; AND tr.landed BETWEEN ga.startDated AND ga.endDated;
IF vGenericInDate THEN IF vGenericInDate THEN
SET NEW.itemOriginalFk = NEW.itemFk; SET NEW.itemOriginalFk = NEW.itemFk;
SET NEW.itemFk = vGenericFk; SET NEW.itemFk = vGenericFk;
@ -64,5 +64,12 @@ trig:BEGIN
IF NEW.quantity < 0 THEN IF NEW.quantity < 0 THEN
SET NEW.isIgnored = TRUE; SET NEW.isIgnored = TRUE;
END IF; END IF;
IF NOT (NEW.itemFk <=> OLD.itemFk) OR
NOT (OLD.entryFk <=> NEW.entryFk) THEN
CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck
SELECT NEW.id;
CALL buy_checkItem();
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -13,5 +13,15 @@ BEGIN
CALL travel_requestRecalc(OLD.travelFk); CALL travel_requestRecalc(OLD.travelFk);
CALL travel_requestRecalc(NEW.travelFk); CALL travel_requestRecalc(NEW.travelFk);
END IF; END IF;
IF NOT (NEW.travelFk <=> OLD.travelFk) THEN
CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck
SELECT b.id
FROM buy b
WHERE b.entryFk = NEW.id;
CALL buy_checkItem();
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -4,22 +4,22 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expedition_beforeInse
FOR EACH ROW FOR EACH ROW
BEGIN BEGIN
DECLARE intcounter INT; DECLARE intcounter INT;
DECLARE vShipFk INT; DECLARE vShipFk INT;
SET NEW.editorFk = account.myUser_getId(); SET NEW.editorFk = account.myUser_getId();
IF NEW.freightItemFk IS NOT NULL THEN IF NEW.freightItemFk IS NOT NULL THEN
UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; UPDATE ticket SET packages = IFNULL(packages, 0) + 1 WHERE id = NEW.ticketFk;
SELECT IFNULL(MAX(counter),0) +1 INTO intcounter SELECT IFNULL(MAX(counter),0) +1 INTO intcounter
FROM expedition e FROM expedition e
INNER JOIN ticket t1 ON e.ticketFk = t1.id INNER JOIN ticket t1 ON e.ticketFk = t1.id
LEFT JOIN ticketState ts ON ts.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticketFk = t1.id
INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped)
AND t1.warehouseFk = t2.warehouseFk AND t1.warehouseFk = t2.warehouseFk
WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk
AND t1.agencyModeFk = t2.agencyModeFk; AND t1.agencyModeFk = t2.agencyModeFk;
SET NEW.`counter` = intcounter; SET NEW.`counter` = intcounter;
END IF; END IF;

View File

@ -10,5 +10,18 @@ BEGIN
SET commission = entry_getCommission(travelFk, currencyFk,supplierFk) SET commission = entry_getCommission(travelFk, currencyFk,supplierFk)
WHERE travelFk = NEW.id; WHERE travelFk = NEW.id;
END IF; END IF;
IF NOT (NEW.agencyModeFk <=> OLD.agencyModeFk) THEN
IF (SELECT hasWeightVolumetric FROM agencyMode WHERE id = NEW.agencyModeFk) THEN
CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck
SELECT b.id
FROM entry e
JOIN buy b ON b.entryFk = e.id
JOIN item i ON i.id = b.itemFk
WHERE e.travelFk = NEW.id;
CALL buy_checkItem();
END IF;
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -4,15 +4,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`travel_beforeUpdate`
FOR EACH ROW FOR EACH ROW
BEGIN BEGIN
SET NEW.editorFk = account.myUser_getId(); 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) IF NOT (NEW.landed <=> OLD.landed)
OR NOT (NEW.shipped <=> OLD.shipped) THEN OR NOT (NEW.shipped <=> OLD.shipped) THEN
CALL travel_checkDates(NEW.shipped, NEW.landed); CALL travel_checkDates(NEW.shipped, NEW.landed);

View File

@ -1,12 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` 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 ;

View File

@ -1,7 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`agencyWarehouse`
AS SELECT `a`.`agency_id` AS `agencyFk`,
`a`.`warehouse_id` AS `warehouseFk`,
`a`.`Vista` AS `agencyType`
FROM `vn2008`.`agency_warehouse` `a`

View File

@ -1,24 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`bankPolicy`
AS SELECT `bp`.`poliza_id` AS `id`,
`bp`.`referencia` AS `ref`,
`bp`.`importe` AS `amount`,
`bp`.`com_dispuesto` AS `balanceInterestDrawn`,
`bp`.`com_no_dispuesto` AS `commissionAvailableBalances`,
`bp`.`com_anual` AS `openingCommission`,
`bp`.`apertura` AS `started`,
`bp`.`cierre` AS `ended`,
`bp`.`Id_Banco` AS `bankFk`,
`bp`.`empresa_id` AS `companyFk`,
`bp`.`supplierFk` AS `supplierFk`,
`bp`.`description` AS `description`,
`bp`.`hasGuarantee` AS `hasGuarantee`,
`bp`.`dmsFk` AS `dmsFk`,
`bp`.`notaryFk` AS `notaryFk`,
`bp`.`currencyFk` AS `currencyFk`,
`bp`.`amortizationTypeFk` AS `amortizationTypeFk`,
`bp`.`periodicityTypeFk` AS `periodicityTypeFk`,
`bp`.`insuranceExpired` AS `insuranceExpired`
FROM `vn2008`.`Bancos_poliza` `bp`
ORDER BY `bp`.`poliza_id` DESC

View File

@ -1,9 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`clientDefaultCompany`
AS SELECT `t`.`Id_Clientes_empresa` AS `id`,
`t`.`Id_Cliente` AS `clientFk`,
`t`.`empresa_id` AS `companyFk`,
`t`.`fecha_ini` AS `started`,
`t`.`fecha_fin` AS `finished`
FROM `vn2008`.`Clientes_empresa` `t`

View File

@ -1,6 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`coolerPath`
AS SELECT `c`.`cooler_path_id` AS `id`,
`c`.`description` AS `description`
FROM `vn2008`.`cooler_path` `c`

View File

@ -1,14 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`doc`
AS SELECT `g`.`id` AS `id`,
`g`.`sref` AS `sref`,
`g`.`brief` AS `brief`,
`g`.`emp_id` AS `companyFk`,
`g`.`orden` AS `order`,
`g`.`file` AS `file`,
`g`.`original` AS `original`,
`g`.`trabajador_id` AS `workerFk`,
`g`.`odbc_date` AS `created`,
`g`.`warehouse_id` AS `warehouseFk`
FROM `vn2008`.`gestdoc` `g`

View File

@ -1,7 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`grantGroup`
AS SELECT `vn2008`.`Grupos`.`id` AS `id`,
`vn2008`.`Grupos`.`Grupo` AS `description`,
`vn2008`.`Grupos`.`observation_type_id` AS `observationTypeFk`
FROM `vn2008`.`Grupos`

View File

@ -15,7 +15,7 @@ AS SELECT `ish`.`itemFk` AS `itemFk`,
`sh`.`parkingFk` AS `parkingFk`, `sh`.`parkingFk` AS `parkingFk`,
`ish`.`id` AS `itemShelvingFk`, `ish`.`id` AS `itemShelvingFk`,
`ish`.`created` AS `created`, `ish`.`created` AS `created`,
`st`.`description` = 'previousPrepared' AS `isPreviousPrepared` `st`.`code` = 'previousPrepared' AS `isPreviousPrepared`
FROM ( FROM (
( (
( (

View File

@ -1,6 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`warehouseJoined`
AS SELECT `wj`.`warehouse_id` AS `warehouseFk`,
`wj`.`warehouse_alias_id` AS `warehouseAliasFk`
FROM `vn2008`.`warehouse_joined` `wj`

View File

@ -17,19 +17,17 @@ FROM (
( (
( (
( (
( `vn`.`ticket` `t`
`vn`.`ticket` `t` JOIN `vn`.`ticketStateToday` `tst` ON(`tst`.`ticketFk` = `t`.`id`)
JOIN `vn`.`ticketStateToday` `tst` ON(`tst`.`ticketFk` = `t`.`id`)
)
JOIN `vn`.`state` `s` ON(`s`.`id` = `tst`.`state`)
) )
JOIN `vn`.`saleVolume` `sv` ON(`sv`.`ticketFk` = `t`.`id`) JOIN `vn`.`state` `s` ON(`s`.`id` = `tst`.`state`)
) )
LEFT JOIN `vn`.`lastHourProduction` `lhp` ON(`lhp`.`warehouseFk` = `t`.`warehouseFk`) JOIN `vn`.`saleVolume` `sv` ON(`sv`.`ticketFk` = `t`.`id`)
) )
JOIN `vn`.`warehouse` `w` ON(`w`.`id` = `t`.`warehouseFk`) 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`) ) STRAIGHT_JOIN `vn`.`zone` `z` ON(`z`.`id` = `t`.`zoneFk`)
) )
LEFT JOIN `vn`.`zoneClosure` `zc` ON( LEFT JOIN `vn`.`zoneClosure` `zc` ON(
@ -43,6 +41,5 @@ FROM (
) )
) )
JOIN `vn`.`alertLevel` `al` ON(`al`.`id` = `s`.`alertLevel`) JOIN `vn`.`alertLevel` `al` ON(`al`.`id` = `s`.`alertLevel`)
)
WHERE `w`.`hasProduction` <> 0 WHERE `w`.`hasProduction` <> 0
AND cast(`t`.`shipped` AS date) = `util`.`VN_CURDATE`() AND cast(`t`.`shipped` AS date) = `util`.`VN_CURDATE`()

View File

@ -1,49 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn2008`.`cc_to_iban`(cc VARCHAR(20))
RETURNS varchar(4) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
DETERMINISTIC
BEGIN
DECLARE iban VARCHAR(4);
select
CONCAT('ES',
RIGHT(
concat(0,
98-
mod(
concat(
mod(
concat(
mod(
concat(
mod(
substring(cc,1,8),
97),
substring(cc,9,8)
),
97),
substring(
concat(
cc,
142800
),
17,
8
)
),
97),
substring(
concat(
cc,
142800
),
25,
2
)
),
97)
)
,2)
)into iban;
RETURN iban;
END$$
DELIMITER ;

View File

@ -1,20 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn2008`.`intrastat_neto`(intINSTRASTAT INTEGER,intUNIDADES INTEGER)
RETURNS double
DETERMINISTIC
BEGIN
DECLARE n DOUBLE;
SELECT ROUND(intUNIDADES / (SUM(MEDIA) / COUNT(media)), 2) INTO n FROM
(SELECT *, unidades / neto MEDIA
FROM intrastat_data
WHERE intrastat_id = intINSTRASTAT AND neto
AND unidades > 0
ORDER BY odbc_date DESC
LIMIT 20) t;
-- JGF 01/06 per a evitar Kg en negatiu
RETURN n/2;
END$$
DELIMITER ;

View File

@ -1,14 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn2008`.`nz`(dblCANTIDAD DOUBLE)
RETURNS double
DETERMINISTIC
BEGIN
DECLARE dblRESULT DOUBLE;
SET dblRESULT = IFNULL(dblCANTIDAD,0);
RETURN dblRESULT;
END$$
DELIMITER ;

View File

@ -1,14 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn2008`.`red`(intCANTIDAD DOUBLE)
RETURNS double
DETERMINISTIC
BEGIN
DECLARE n DOUBLE;
SET n = SIGN(intCANTIDAD) * TRUNCATE( (ABS(intCANTIDAD) * 100) + 0.5001 ,0) /100 ;
RETURN n;
END$$
DELIMITER ;

View File

@ -47,13 +47,13 @@ BEGIN
UNION ALL UNION ALL
SELECT empresa_id, Id_Cliente, - Importe SELECT io.companyFk, io.clientFk Id_Cliente, - io.amount
FROM Facturas f FROM vn.invoiceOut io
JOIN Clientes c using(Id_Cliente) JOIN Clientes c ON c.Id_Cliente = io.clientFk
JOIN pay_met pm on pm.id = pay_met_id JOIN pay_met pm on pm.id = pay_met_id
WHERE f.Vencimiento > vFechaRemesa WHERE io.dued > vFechaRemesa
AND pay_met_id = 4 AND pm.deudaviva AND pay_met_id = 4 AND pm.deudaviva
AND Importe > 0 AND io.amount > 0
) risk ON c.Id_Cliente = risk.clientFk ) risk ON c.Id_Cliente = risk.clientFk
GROUP BY risk.companyFk, Id_Cliente GROUP BY risk.companyFk, Id_Cliente

View File

@ -13,9 +13,9 @@ SELECT Agencia,
FROM Tickets ti FROM Tickets ti
INNER JOIN Consignatarios ON ti.Id_Consigna = Consignatarios.Id_consigna INNER JOIN Consignatarios ON ti.Id_Consigna = Consignatarios.Id_consigna
INNER JOIN Agencias ON ti.Id_Agencia = Agencias.Id_Agencia INNER JOIN Agencias ON ti.Id_Agencia = Agencias.Id_Agencia
LEFT JOIN (SELECT Ticket_Id,count(*) AS ncajas FROM expeditions WHERE Id_Article=94 GROUP BY ticket_id) sub1 ON ti.Id_Ticket=sub1.Ticket_Id LEFT JOIN (SELECT ticketFk,count(*) AS ncajas FROM vn.expedition WHERE packagingFk=94 GROUP BY ticketFk) sub1 ON ti.Id_Ticket=sub1.ticketFk
LEFT JOIN (SELECT Ticket_Id,count(*) AS nbultos FROM expeditions WHERE Id_Article IS NULL GROUP BY ticket_id) sub2 ON ti.Id_Ticket=sub2.Ticket_Id LEFT JOIN (SELECT ticketFk,count(*) AS nbultos FROM vn.expedition WHERE packagingFk IS NULL GROUP BY ticketFk) sub2 ON ti.Id_Ticket=sub2.ticketFk
LEFT JOIN (SELECT Ticket_Id,count(*) AS notros FROM expeditions WHERE Id_Article >0 GROUP BY ticket_id) sub3 ON ti.Id_Ticket=sub3.Ticket_Id LEFT JOIN (SELECT ticketFk,count(*) AS notros FROM vn.expedition WHERE packagingFk >0 GROUP BY ticketFk) sub3 ON ti.Id_Ticket=sub3.ticketFk
INNER JOIN vn.ticketState ts ON ti.Id_ticket = ts.ticketFk INNER JOIN vn.ticketState ts ON ti.Id_ticket = ts.ticketFk
WHERE ti.Fecha=util.VN_CURDATE() AND WHERE ti.Fecha=util.VN_CURDATE() AND
ts.userFk=intId_Trabajador ts.userFk=intId_Trabajador

View File

@ -1,34 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`XDiario_Quadrator`()
BEGIN
INSERT INTO vn.mail (receiver, subject, body)
SELECT 'cau@verdnatura.es',
'asientos descuadrados',
group_concat(CONCAT(' Asiento: ', ASIEN, '- importe:', quadre) SEPARATOR ' \r\n ')
FROM (
SELECT ASIEN, SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0)) quadre
FROM XDiario
WHERE enlazado = FALSE
GROUP BY ASIEN
HAVING ABS(SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0))) > 0.01
) t
HAVING count(*) > 0;
UPDATE XDiario XD
INNER JOIN(
SELECT XD.id, SUBCTA, Quadre FROM XDiario XD
INNER JOIN (
SELECT ASIEN, SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0)) as Quadre
FROM XDiario
WHERE enlazado = FALSE
GROUP BY ASIEN
HAVING Quadre != 0
) sub USING(ASIEN)
WHERE SUBCTA > '5999999999'
GROUP BY ASIEN
) sub2 USING(id)
SET Eurohaber = IF(IFNULL(Eurohaber,0) = 0, Eurohaber, Eurohaber + Quadre),
Eurodebe = IF(IFNULL(Eurodebe,0) = 0, Eurodebe, Eurodebe - Quadre);
END$$
DELIMITER ;

View File

@ -67,12 +67,12 @@ proc: BEGIN
CREATE TEMPORARY TABLE tmp.itemCalc CREATE TEMPORARY TABLE tmp.itemCalc
(INDEX (itemFk,warehouseFk)) (INDEX (itemFk,warehouseFk))
ENGINE = MEMORY ENGINE = MEMORY
SELECT i.item_id itemFk, vWarehouseLanding warehouseFk, i.dat dated, i.amount quantity SELECT i.itemFk, vWarehouseLanding warehouseFk, i.shipped dated, i.quantity
FROM item_out i FROM vn.itemTicketOut i
JOIN itemRangeLive ir ON ir.itemFK = i.item_id JOIN itemRangeLive ir ON ir.itemFK = i.itemFk
WHERE i.dat >= vDatedFrom WHERE i.shipped >= vDatedFrom
AND (ir.dated IS NULL OR i.dat <= ir.dated) AND (ir.dated IS NULL OR i.shipped <= ir.dated)
AND i.warehouse_id = vWarehouseLanding AND i.warehouseFk = vWarehouseLanding
UNION ALL UNION ALL
SELECT b.itemFk, vWarehouseLanding, t.landed, b.quantity SELECT b.itemFk, vWarehouseLanding, t.landed, b.quantity
FROM vn.buy b FROM vn.buy b
@ -86,12 +86,12 @@ proc: BEGIN
AND t.landed >= vDatedFrom AND t.landed >= vDatedFrom
AND (ir.dated IS NULL OR t.landed <= ir.dated) AND (ir.dated IS NULL OR t.landed <= ir.dated)
UNION ALL UNION ALL
SELECT i.item_id, vWarehouseLanding, i.dat, i.amount SELECT i.itemFk, vWarehouseLanding, i.shipped, i.quantity
FROM item_entry_out i FROM vn.itemEntryOut i
JOIN itemRangeLive ir ON ir.itemFk = i.item_id JOIN itemRangeLive ir ON ir.itemFk = i.itemFk
WHERE i.dat >= vDatedFrom WHERE i.shipped >= vDatedFrom
AND (ir.dated IS NULL OR i.dat <= ir.dated) AND (ir.dated IS NULL OR i.shipped <= ir.dated)
AND i.warehouse_id = vWarehouseLanding AND i.warehouseOutFk = vWarehouseLanding
UNION ALL UNION ALL
SELECT r.item_id, vWarehouseLanding, r.shipment, -r.amount SELECT r.item_id, vWarehouseLanding, r.shipment, -r.amount
FROM hedera.order_row r FROM hedera.order_row r

View File

@ -122,9 +122,9 @@ BEGIN
-- Añadimos los gastos, para facilitar el formulario -- Añadimos los gastos, para facilitar el formulario
UPDATE tmp.balance b UPDATE tmp.balance b
JOIN vn2008.balance_nest_tree bnt on bnt.id = b.id JOIN vn2008.balance_nest_tree bnt on bnt.id = b.id
JOIN (SELECT Id_Gasto, Gasto JOIN (SELECT id Id_Gasto, name Gasto
FROM vn2008.Gastos FROM vn.expense
GROUP BY Id_Gasto) g ON g.Id_Gasto = bnt.Id_Gasto COLLATE utf8_general_ci GROUP BY id) g ON g.Id_Gasto = bnt.Id_Gasto COLLATE utf8_general_ci
SET b.Id_Gasto = g.Id_Gasto COLLATE utf8_general_ci SET b.Id_Gasto = g.Id_Gasto COLLATE utf8_general_ci
, b.Gasto = g.Gasto COLLATE utf8_general_ci ; , b.Gasto = g.Gasto COLLATE utf8_general_ci ;

View File

@ -21,19 +21,10 @@ proc: BEGIN
SET vRangeDeleteTicket = 60; SET vRangeDeleteTicket = 60;
DELETE FROM cdr WHERE calldate < vDate18; DELETE FROM cdr WHERE calldate < vDate18;
DELETE FROM Monitoring WHERE ODBC_TIME < vDate;
DELETE FROM Conteo WHERE Fecha < vDate;
DELETE FROM XDiario WHERE FECHA < vDate3 OR FECHA IS NULL;
DELETE FROM mail WHERE DATE_ODBC < vDate; DELETE FROM mail WHERE DATE_ODBC < vDate;
DELETE FROM expeditions_deleted WHERE odbc_date < vDate26;
DELETE FROM Movimientos_mark WHERE odbc_date < vDate; DELETE FROM Movimientos_mark WHERE odbc_date < vDate;
DELETE FROM Splits WHERE Fecha < vDate18; DELETE FROM Splits WHERE Fecha < vDate18;
DELETE ts
FROM Tickets_stack ts
JOIN Tickets t ON ts.Id_Ticket = t.Id_Ticket
WHERE t.Fecha < vDate;
DELETE tobs DELETE tobs
FROM ticket_observation tobs FROM ticket_observation tobs
JOIN Tickets t ON tobs.Id_Ticket = t.Id_Ticket JOIN Tickets t ON tobs.Id_Ticket = t.Id_Ticket
@ -65,13 +56,6 @@ proc: BEGIN
JOIN travel t ON t.id = e.travel_id JOIN travel t ON t.id = e.travel_id
WHERE t.landing <= vDate; WHERE t.landing <= vDate;
DELETE co
FROM Compres_ok co JOIN Compres c ON c.Id_Compra = co.Id_Compra
JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
JOIN travel t ON t.id = e.travel_id
WHERE t.landing <= vDate;
DELETE FROM scan WHERE odbc_date < vDate6 AND id <> 1;
IF v_full THEN IF v_full THEN
CREATE OR REPLACE TEMPORARY TABLE tTicketDelete CREATE OR REPLACE TEMPORARY TABLE tTicketDelete
SELECT DISTINCT tl.originFk ticketFk SELECT DISTINCT tl.originFk ticketFk

View File

@ -25,7 +25,7 @@ BEGIN
FROM Clientes FROM Clientes
WHERE Id_Cliente = idCLI; WHERE Id_Cliente = idCLI;
CALL vn.ledger_next(max_asien); CALL vn.ledger_next(max_asien);
INSERT INTO XDiario (ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE,EUROHABER,empresa_id) INSERT INTO vn.XDiario (ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE,EUROHABER,empresa_id)
SELECT max_asien,datFEC,SUBCTA,CONTRA,strCONCEPTO,EURODEBE,EUROHABER,idEMP SELECT max_asien,datFEC,SUBCTA,CONTRA,strCONCEPTO,EURODEBE,EUROHABER,idEMP
FROM(SELECT cuenta_banco SUBCTA, cuenta_cliente CONTRA, 0 EURODEBE, dblIMPORTE EUROHABER FROM(SELECT cuenta_banco SUBCTA, cuenta_cliente CONTRA, 0 EURODEBE, dblIMPORTE EUROHABER
UNION ALL UNION ALL

View File

@ -31,7 +31,7 @@ BEGIN
stock.available stock.available
FROM vn2008.Tickets t FROM vn2008.Tickets t
JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
JOIN vn2008.warehouse wh ON wh.id = t.warehouse_id JOIN vn.warehouse wh ON wh.id = t.warehouse_id
JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket
JOIN vn2008.Articles i ON i.Id_Article = m.Id_Article JOIN vn2008.Articles i ON i.Id_Article = m.Id_Article
JOIN vn2008.Tipos tp ON tp.tipo_id = i.tipo_id JOIN vn2008.Tipos tp ON tp.tipo_id = i.tipo_id
@ -88,8 +88,8 @@ BEGIN
FROM vn2008.Compres c FROM vn2008.Compres c
JOIN vn2008.Entradas e ON e.Id_Entrada = c.Id_Entrada JOIN vn2008.Entradas e ON e.Id_Entrada = c.Id_Entrada
JOIN vn2008.travel tr ON tr.id = e.travel_id JOIN vn2008.travel tr ON tr.id = e.travel_id
JOIN vn2008.warehouse whi ON whi.id = tr.warehouse_id JOIN vn.warehouse whi ON whi.id = tr.warehouse_id
JOIN vn2008.warehouse who ON who.id = tr.warehouse_id_out JOIN vn.warehouse who ON who.id = tr.warehouse_id_out
JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article
JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id
JOIN vn.confectionType ct ON ct.id = tp.confeccion JOIN vn.confectionType ct ON ct.id = tp.confeccion

View File

@ -18,11 +18,11 @@ SELECT * FROM
WHERE Id_Cliente = vCustomer WHERE Id_Cliente = vCustomer
AND Fechacobro >= '2017-01-01' AND Fechacobro >= '2017-01-01'
UNION ALL UNION ALL
SELECT vn.getDueDate(f.Fecha,c.Vencimiento), - Importe SELECT vn.getDueDate(io.issued,c.Vencimiento), - io.amount
FROM Facturas f FROM vn.invoiceOut io
JOIN Clientes c ON f.Id_Cliente = c.Id_Cliente JOIN Clientes c ON io.clientFk = c.Id_Cliente
WHERE f.Id_Cliente = vCustomer WHERE io.clientFk = vCustomer
AND Fecha >= '2017-01-01' AND io.issued >= '2017-01-01'
UNION ALL UNION ALL
SELECT '2016-12-31', Debt SELECT '2016-12-31', Debt
FROM bi.customerDebtInventory FROM bi.customerDebtInventory

View File

@ -1,82 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`desglose_volume`(IN vAgencyFk INT)
BEGIN
DECLARE vStarted DATETIME DEFAULT TIMESTAMP(util.VN_CURDATE());
DECLARE vEnded DATETIME DEFAULT TIMESTAMP(util.VN_CURDATE(), '23:59:59');
DECLARE vIsHolland BOOL;
SELECT (wa.name = 'Holanda') INTO vIsHolland
FROM vn.agency a
JOIN vn.warehouseAlias wa ON wa.id = a.warehouseAliasFk
WHERE a.id = vAgencyFk;
IF vIsHolland THEN
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_PackagingEstimated;
CREATE TEMPORARY TABLE tmp.ticket_PackagingEstimated
(
ticketFk INT PRIMARY KEY
,carros DECIMAL(5,1) DEFAULT 0
);
INSERT INTO tmp.ticket_PackagingEstimated(ticketFk, carros)
SELECT sv.ticketFk, ROUND(vc.dutchCompressionRate * sum(sv.volume) / vc.trolleyM3,0)
FROM vn.ticket t
JOIN vn.saleVolume sv ON sv.ticketFk = t.id
JOIN vn.agencyMode am ON am.id = t.agencyModeFk
JOIN vn.volumeConfig vc
WHERE t.shipped BETWEEN vStarted AND vEnded
AND am.agencyFk = vAgencyFk
GROUP BY t.id;
SELECT a.nickname Provincia,
count(*) expediciones,
0 Bultos,
sum(tpe.carros) Prevision
FROM vn.ticket t
JOIN vn.address a ON a.id = t.addressFk
JOIN tmp.ticket_PackagingEstimated tpe ON tpe.ticketFk = t.id
GROUP BY a.nickname;
ELSE
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_PackagingEstimated;
CREATE TEMPORARY TABLE tmp.ticket_PackagingEstimated
(
ticketFk INT PRIMARY KEY
,boxes INT DEFAULT 0
);
INSERT INTO tmp.ticket_PackagingEstimated(ticketFk, boxes)
SELECT sv.ticketFk, CEIL(1000 * sum(sv.volume) / vc.standardFlowerBox)
FROM vn.ticket t
JOIN vn.saleVolume sv ON sv.ticketFk = t.id
JOIN vn.agencyMode am ON am.id = t.agencyModeFk
JOIN vn.volumeConfig vc
WHERE t.shipped BETWEEN vStarted AND vEnded
AND IFNULL(t.packages,0) = 0
AND am.agencyFk = vAgencyFk
GROUP BY t.id;
SELECT p.name Provincia,
count(*) expediciones,
sum(t.packages) Bultos,
sum(tpe.boxes) Prevision
FROM vn.ticket t
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.province p ON a.provinceFk = p.id
JOIN vn.agencyMode am ON am.id = t.agencyModeFk
JOIN tmp.ticket_PackagingEstimated tpe ON tpe.ticketFk = t.id
WHERE t.warehouseFk = 60
AND t.shipped BETWEEN vStarted AND vEnded
AND am.agencyFk = vAgencyFk
GROUP BY p.name;
END IF;
SELECT * FROM tmp.ticket_PackagingEstimated;
DROP TEMPORARY TABLE tmp.ticket_PackagingEstimated;
END$$
DELIMITER ;

View File

@ -8,16 +8,10 @@ BEGIN
END; END;
START TRANSACTION; START TRANSACTION;
INSERT INTO vn.clientCredit(clientFk, amount)
SELECT c.id, 0
FROM vn.`client` c
JOIN vn.payMethod pm ON pm.id = c.payMethodFk
WHERE c.credit <> 0 AND pm.`code` = 'card';
UPDATE vn.`client` c UPDATE vn.`client` c
JOIN vn.payMethod pm ON pm.id = c.payMethodFk JOIN vn.payMethod pm ON pm.id = c.payMethodFk
SET credit = 0 SET credit = 0
WHERE pm.`code` = 'card'; WHERE pm.`code` = 'card';
DROP TEMPORARY TABLE IF EXISTS clientes_credit; DROP TEMPORARY TABLE IF EXISTS clientes_credit;
CREATE TEMPORARY TABLE clientes_credit CREATE TEMPORARY TABLE clientes_credit
@ -44,10 +38,6 @@ BEGIN
UPDATE Clientes UPDATE Clientes
JOIN clientes_credit USING(Id_Cliente) JOIN clientes_credit USING(Id_Cliente)
SET Clientes.Credito = newCredit; SET Clientes.Credito = newCredit;
INSERT INTO credit(Id_Cliente, amount, Id_Trabajador)
SELECT Id_Cliente, newCredit, NULL
FROM clientes_credit;
DROP TEMPORARY TABLE clientes_credit; DROP TEMPORARY TABLE clientes_credit;
COMMIT; COMMIT;

View File

@ -1,117 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`supplierStatement`(vSupplierFk INT, vCurrencyFk INT, vCompanyFk INT, vOrderBy VARCHAR(15), vOnlyConciliated BIT)
BEGIN
SET @saldo_eur:= 0;
SET @saldo_div:= 0;
select vOnlyConciliated;
DROP TEMPORARY TABLE IF EXISTS tmp.supplierStatement;
CREATE TEMPORARY TABLE tmp.supplierStatement ENGINE = MEMORY
SELECT
*,
@saldo_eur:= round(@saldo_eur + IFNULL(Pago_Euros, 0) - IFNULL(Fac_Euros, 0) ,2 ) AS saldo_eur,
@saldo_div:= round(@saldo_div + IFNULL(Pago_Divisas, 0) - IFNULL(Fac_Divisas, 0) ,2 ) AS saldo_div
FROM
(SELECT * FROM
(SELECT
NULL as banco_id,
r.empresa_id,
r.serie,
r.id,
CASE
WHEN vOrderBy = 'issued' THEN r.fecha
WHEN vOrderBy = 'bookEntried' THEN r.bookEntried
WHEN vOrderBy = 'booked' THEN r.dateBooking
WHEN vOrderBy = 'dueDate' THEN rv.fecha
END AS fecha,
CONCAT('S/Fra ', r.sref) sref,
if(r.moneda_id > 1,round(sum(divisa) / sum(cantidad),3),NULL) val_cambio,
CAST(sum(cantidad) as DECIMAL(10,2)) as Fac_Euros,
CAST(sum(divisa) as DECIMAL(10,2)) as Fac_Divisas,
NULL AS Pago_Euros,
NULL AS Pago_Divisas,
r.moneda_id,
r.contabilizada,
Moneda,
NULL as pago_sdc_id,
'invoiceIn' statementType
FROM
recibida r
JOIN recibida_vencimiento rv on rv.recibida_id = r.id
JOIN Monedas m on m.Id_Moneda = r.moneda_id
WHERE
r.fecha > '2014-12-31'
AND r.proveedor_id = vSupplierFk
AND vCurrencyFk IN (r.moneda_id, 0)
AND vCompanyFk IN (r.empresa_id,0)
AND (vOnlyConciliated = r.contabilizada OR NOT vOnlyConciliated)
GROUP BY rv.id
UNION ALL
SELECT
p.id_banco,
p.empresa_id,
NULL,
p.id,
CASE
WHEN vOrderBy = 'issued' THEN p.Fecha
WHEN vOrderBy = 'bookEntried' THEN p.Fecha
WHEN vOrderBy = 'booked' THEN p.Fecha
WHEN vOrderBy = 'dueDate' THEN p.dueDated
END AS fecha,
CONCAT(IFNULL(name, ''), IF(pre.concepto <> '', CONCAT(' : ', pre.concepto), '')),
if(p.id_moneda > 1, p.divisa / importe, NULL) tip_cambio,
NULL,
NULL,
p.importe,
p.divisa,
p.id_moneda,
p.conciliado,
Moneda,
NULL as pago_sdc_id,
'payment' statementType
FROM
pago p
LEFT JOIN Monedas ON Monedas.Id_Moneda = p.id_moneda
LEFT JOIN Bancos ON p.id_banco = Bancos.Id_banco
LEFT JOIN pay_met pm ON p.pay_met_id = pm.id
LEFT JOIN Pagares pre ON pre.pago_id = p.id
WHERE
Fecha > '2014-12-31'
AND p.Id_Proveedor = vSupplierFk
AND vCurrencyFk IN (p.id_moneda,0)
AND vCompanyFk IN (p.empresa_id,0)
AND (vOnlyConciliated = p.conciliado OR NOT vOnlyConciliated)
UNION ALL
SELECT
NULL,
companyFk,
NULL,
se.id,
CASE
WHEN vOrderBy = 'issued' THEN se.dated
WHEN vOrderBy = 'bookEntried' THEN se.dated
WHEN vOrderBy = 'booked' THEN se.dated
WHEN vOrderBy = 'dueDate' THEN se.dueDated
END AS fecha,
se.description,
1 tip_cambio,
amount,
NULL,
NULL,
NULL,
currencyFk,
isConciliated,
c.`code`,
NULL,
'expense' statementType
FROM vn.supplierExpense se
JOIN vn.currency c on c.id= se.currencyFk
WHERE se.supplierFk = vSupplierFk
AND vCurrencyFk IN (se.currencyFk,0)
AND vCompanyFk IN (se.companyFk,0)
AND (vOnlyConciliated = se.isConciliated OR NOT vOnlyConciliated)
) AS SUB
ORDER BY (fecha is null and NOT contabilizada),fecha, IF(vOrderBy = 'dueDate', id, NULL) LIMIT 10000000000000000000) t;
END$$
DELIMITER ;

View File

@ -1,182 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`traslado`(IN i_entrada INTEGER)
BEGIN
DECLARE dateShipment DATE;
DECLARE dateLanding DATE;
DECLARE warehouseShipment INTEGER;
DECLARE warehouseLanding INTEGER;
DECLARE v_calc_visible INTEGER;
DECLARE vInventoryDate DATE;
SET vInventoryDate := vn.getInventoryDate();
SELECT shipment, landing, warehouse_id_out, warehouse_id
INTO dateShipment, dateLanding, warehouseShipment, warehouseLanding
FROM travel t JOIN Entradas e ON t.id = e.travel_id
WHERE Id_Entrada = i_entrada;
CALL vn.rate_getPrices(dateShipment, warehouseLanding);
-- Traslado en almacen origen
DROP TEMPORARY TABLE IF EXISTS buy_edi_temp;
CREATE TEMPORARY TABLE buy_edi_temp
(KEY (Id_Article), INDEX(Id_Compra)) ENGINE = MEMORY
SELECT *
FROM (SELECT c.Id_Article, c.Id_Compra
FROM Compres c INNER JOIN Entradas e USING(Id_Entrada)
INNER JOIN travel t ON t.id = e.travel_id
WHERE t.landing BETWEEN vInventoryDate AND dateShipment
AND c.Novincular = FALSE
AND c.Tarifa2 >= 0
ORDER BY (warehouseShipment = t.warehouse_id) DESC, t.landing DESC
LIMIT 10000000000000000000) t
GROUP BY Id_Article;
IF dateShipment >= util.VN_CURDATE() THEN
CALL `cache`.visible_refresh(v_calc_visible, TRUE, warehouseShipment);
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item (
`itemFk` int(10) unsigned NOT NULL,
`visible` int(11) NOT NULL DEFAULT 0,
`available` int(11) NOT NULL DEFAULT 0,
`visibleLanding` int(11) NOT NULL DEFAULT 0,
`availableLanding` int(11) NOT NULL DEFAULT 0,
UNIQUE INDEX i USING HASH (itemFk)
) ENGINE = MEMORY;
INSERT INTO tmp.item(itemFk, visible)
SELECT item_id itemFk, visible
FROM `cache`.visible
WHERE calc_id = v_calc_visible
AND visible;
CALL `cache`.visible_refresh(v_calc_visible, TRUE, warehouseLanding);
INSERT INTO tmp.item(itemFk, visibleLanding)
SELECT item_id, `visible`
FROM `cache`.`visible` v
WHERE v.calc_id = v_calc_visible
AND v.`visible`
ON DUPLICATE KEY UPDATE visibleLanding = v.`visible`;
CALL availableTraslate(warehouseShipment, dateShipment, NULL);
INSERT INTO tmp.item(itemFk, available)
SELECT a.item_id, a.available
FROM availableTraslate a
WHERE a.available
ON DUPLICATE KEY UPDATE available = a.available;
CALL availableTraslate(warehouseLanding, dateLanding, warehouseShipment);
INSERT INTO tmp.item(itemFk, availableLanding)
SELECT a.item_id, a.available
FROM availableTraslate a
WHERE a.available
ON DUPLICATE KEY UPDATE availableLanding = a.available;
ELSE
CALL vn.item_getStock(warehouseShipment, dateShipment, NULL);
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item (UNIQUE INDEX i USING HASH (itemFk)) ENGINE = MEMORY
SELECT itemFk, `visible`, available , 0 visibleLanding, 0 availableLanding
FROM tmp.itemList;
DROP TEMPORARY TABLE tmp.itemList;
END IF;
CALL vn.buyUltimateFromInterval(warehouseLanding,vInventoryDate, dateLanding);
DROP TEMPORARY TABLE IF EXISTS Traslados;
CREATE TEMPORARY TABLE Traslados ENGINE = MEMORY
SELECT tp.Id_Tipo AS Tipo,
tp.reino_id,
ar.tipo_id,
ar.Id_Article AS article_id,
ar.Article,
ar.Medida,
ar.Categoria,
ar.Color,
Origen.abreviatura as Origen,
CE.Cantidad,
ar.Tallos,
CAST(AIM.visible AS DECIMAL(10,0)) as vis1,
CAST(AIM.available AS DECIMAL(10,0)) as dis1,
CAST(AIM.visibleLanding AS DECIMAL(10,0)) as vis2,
CAST(AIM.availableLanding AS DECIMAL(10,0)) as dis2,
COALESCE(CE.`grouping`, C.`grouping`) as `grouping`,
COALESCE(CE.Packing, C.Packing) as Packing,
COALESCE(cl.caja, CE.caja, C.caja) as caja,
IFNULL(p.name, P2.Alias) AS Productor,
C.Id_Cubo,
1 Tinta,
CE.Id_Compra,
CE.Etiquetas,
C.buy_edi_id,
tp.Id_Trabajador,
CB.Volumen,
IFNULL(CB.x,0) x,
IFNULL(CB.y,0) y,
IFNULL(CB.z,0) z,
IFNULL(C.Costefijo,0) Costefijo,
IFNULL(C.Comisionfija,0) Comisionfija,
IFNULL(C.Portefijo,0) Portefijo,
A.m3,
E.comision,
CB.Retornable,
IFNULL(CEB.Valor,CB.Valor) Valor,
r.rate3 t3, r.rate2 t2, tp.promo,
C.`grouping` groupingOrigin,
C.Packing PackingOrigin,
C.Id_Compra CompraOrigin,
CB.costeRetorno,
C.weight
FROM Articles ar
JOIN tmp.item AIM ON AIM.itemFk = ar.Id_Article
LEFT JOIN producer p ON p.producer_id = ar.producer_id
LEFT JOIN Tipos tp ON tp.tipo_id = ar.tipo_id
JOIN vn.itemCategory ic ON ic.id = tp.reino_id
LEFT JOIN Origen ON Origen.id = ar.id_origen
LEFT JOIN buy_edi_temp lb ON lb.Id_Article = ar.Id_Article
LEFT JOIN Compres C ON C.Id_Compra = lb.Id_Compra
LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo
LEFT JOIN Entradas E2 ON E2.Id_Entrada = C.Id_Entrada
LEFT JOIN Proveedores P2 ON P2.Id_Proveedor = E2.Id_Proveedor
LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada
LEFT JOIN travel TR ON TR.id = E.travel_id
LEFT JOIN Agencias A ON A.Id_Agencia = TR.agency_id
LEFT JOIN Compres CE ON CE.Id_Article = ar.Id_Article AND CE.Id_Entrada = i_entrada
LEFT JOIN Cubos CEB ON CEB.Id_Cubo = CE.Id_Cubo
LEFT JOIN tmp.rate r ON TRUE
LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = ar.Id_Article
LEFT JOIN Compres cl ON cl.Id_Compra = bufi.buyFk
WHERE ic.display
AND E.Redada = FALSE
AND (AIM.visible != 0 OR AIM.available != 0)
ORDER BY tipo_id, Article, article_id, Medida, Categoria, Origen;
CREATE INDEX tindex USING HASH ON Traslados (article_id);
SELECT t.*,
Cantidad - MOD(Cantidad , `grouping`) as Subcantidad,
MOD(Cantidad , `grouping`) as Soll,
ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) / Packing,0) as cm3,
Costefijo + Comisionfija + Portefijo AS Cost,
@porte := ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) * m3 / 1000000 / Packing ,3) AS Porte,
@comision := ROUND((Costefijo + Comisionfija + Portefijo) * comision / 100 ,3) AS Comision,
ROUND(@embalaje := (costeRetorno + IF(Retornable != 0, 0, Valor)) / packing ,3) AS Embalaje,
@coste := IFNULL((Costefijo + Comisionfija + Portefijo),0) + IFNULL(@embalaje,0) + IFNULL(@porte,0) + IFNULL(@comision,0) AS Coste,
@t3 := ROUND(@coste / ( (100 - t3 - t.promo)/100),2) AS Tarifa3,
ROUND(@t3 * (1 + ((t2 - t3)/100)),2) AS Tarifa2,
0 selected
FROM Traslados t;
DROP TEMPORARY TABLE Traslados;
DROP TEMPORARY TABLE tmp.item;
DROP TEMPORARY TABLE buy_edi_temp;
DROP TEMPORARY TABLE tmp.buyUltimateFromInterval;
DROP TEMPORARY TABLE tmp.rate;
END$$
DELIMITER ;

View File

@ -1,119 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`travelDetail`()
BEGIN
/**
* Returns the details of the travels that have a departure warehouse in Ecuador or Colombia.
*/
DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK;
SELECT IFNULL(CONCAT(" ",Entrada),travel) travelAndEntry,
travel,
Entrada,
IsTravel,
Agencia,
ref,
shipment,
OrigenCajas,
landing,
Destino,
Etiquetas,
Notas_Eva,
kg,
loadedKg,
volumeKg,
loadPriority,
invoiceAmount,
Carguera,
reference
FROM
(SELECT TRUE IsTravel,
tr.id travel,
NULL Entrada,
ag.Agencia,
tr.ref,
tr.shipment,
wo.name OrigenCajas,
tr.landing,
w.name Destino,
SUM(c.Etiquetas) Etiquetas,
NULL Notas_Eva,
tr.kg,
CAST(SUM(c.weight * c.Etiquetas) AS INT) loadedkg,
CAST(
SUM(vc.aerealVolumetricDensity *
c.Etiquetas *
IF(cb.Volumen,
cb.Volumen,
cb.X * cb.Y * cb.Z
) / 1000000
) AS INT
) volumeKg,
NULL loadPriority,
NULL invoiceAmount,
pc.Alias Carguera,
NULL reference
FROM travel tr
LEFT JOIN Proveedores pc ON pc.Id_Proveedor = tr.cargoSupplierFk
LEFT JOIN Entradas e ON e.travel_id = tr.id
LEFT JOIN Compres c ON c.Id_Entrada = e.Id_Entrada
LEFT JOIN Cubos cb ON cb.Id_Cubo = c.Id_Cubo
LEFT JOIN Articles a ON a.Id_Article = c.Id_Article
LEFT JOIN Tipos tp ON tp.tipo_id = a.tipo_id
JOIN warehouse w ON w.id = tr.warehouse_id
JOIN warehouse wo ON wo.id = tr.warehouse_id_out
JOIN Agencias ag ON ag.Id_Agencia = tr.agency_id
JOIN vn.volumeConfig vc
WHERE tr.landing >= vDateFrom
AND (wo.name="Colombia" OR wo.name="Ecuador")
GROUP BY tr.id
UNION ALL
SELECT 0 IsTravel,
e.travel_id travel,
e.Id_Entrada,
p.Proveedor,
e.Referencia,
tr.shipment,
wo.name OrigenCajas,
tr.landing,
w.name Destino,
SUM(Etiquetas) Etiquetas,
e.Notas_Eva,
NULL kg,
CAST(SUM(c.weight * c.Etiquetas) AS INT) loadedkg,
CAST(
SUM(vc.aerealVolumetricDensity *
c.Etiquetas *
IF(cb.Volumen,
cb.Volumen,
cb.X * cb.Y * cb.Z
) / 1000000
) AS INT
) volumeKg,
loadPriority,
e.invoiceAmount,
pc.Alias carguera,
e.reference
FROM Entradas e
JOIN Compres c ON c.Id_Entrada = e.Id_Entrada
JOIN Cubos cb ON cb.Id_Cubo = c.Id_Cubo
JOIN Articles a ON a.Id_Article = c.Id_Article
JOIN Tipos tp ON tp.tipo_id = a.tipo_id
JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor
JOIN travel tr ON tr.id = e.travel_id
LEFT JOIN Proveedores pc ON pc.Id_Proveedor = tr.cargoSupplierFk
JOIN warehouse w ON w.id = tr.warehouse_id
JOIN warehouse wo ON wo.id = tr.warehouse_id_out
JOIN vn.volumeConfig vc
WHERE tr.landing >= vDateFrom
AND (wo.name="Colombia" OR wo.name="Ecuador")
GROUP BY e.Id_Entrada
) sub
ORDER BY landing ASC,
shipment ASC,
travel,
IsTravel DESC,
(loadPriority > 0) DESC,
loadPriority,
Agencia,
Notas_Eva;
END$$
DELIMITER ;

View File

@ -1,14 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn2008`.`Conteo_afterInsert`
AFTER INSERT ON `Conteo`
FOR EACH ROW
BEGIN
DECLARE intTravel INTEGER;
SELECT t.id INTO intTravel FROM Compres c JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
JOIN travel t ON t.id = e.travel_id
WHERE landing = util.VN_CURDATE() AND c.Id_Article = NEW.Id_Article AND warehouse_id = NEW.warehouse_id AND received <> TRUE LIMIT 1;
IF (intTravel) then
UPDATE travel SET received = TRUE WHERE id = intTravel;
END IF;
END$$
DELIMITER ;

View File

@ -1,14 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn2008`.`account_conciliacion_beforeInsert`
BEFORE INSERT ON `account_conciliacion`
FOR EACH ROW
set new.id_calculated = replace(
replace(
replace(
replace(
concat(new.Id_Proveedores_account,new.Fechaoperacion,new.importe,new.Concepto,new.DebeHaber)
,' ','')
,":",'')
,'-','')
,'.','')$$
DELIMITER ;

View File

@ -1,18 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn2008`.`agency_hour_afterUpdate`
AFTER UPDATE ON `agency_hour`
FOR EACH ROW
BEGIN
DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE;
SELECT COUNT(*) INTO vAlreadyExists
FROM vn2008.agency_hour
WHERE NEW.week_day <=> week_day AND NEW.province_id <=> province_id
AND NEW.warehouse_id <=> warehouse_id AND NEW.max_hour <=> max_hour
AND NEW.agency_id <=> agency_id;
IF vAlreadyExists > 1 THEN
CALL util.throw('ALREADY_EXISTS');
END IF;
END$$
DELIMITER ;

View File

@ -1,21 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn2008`.`agency_hour_beforeInsert`
BEFORE INSERT ON `agency_hour`
FOR EACH ROW
BEGIN
DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE;
IF NEW.week_day IS NULL AND NEW.province_id IS NULL AND NEW.subtract_day = 0 AND NEW.max_hour = 0 THEN
CALL util.throw ('FILL_MORE_FIELDS');
END IF;
SELECT COUNT(*) INTO vAlreadyExists
FROM vn2008.agency_hour
WHERE NEW.week_day <=> week_day AND NEW.province_id <=> province_id
AND NEW.warehouse_id <=> warehouse_id AND NEW.max_hour <=> max_hour
AND NEW.agency_id <=> agency_id;
IF vAlreadyExists > 1 THEN
CALL util.throw('ALREADY_EXISTS');
END IF;
END$$
DELIMITER ;

View File

@ -1,13 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn2008`.`awb_recibida_afterDelete`
AFTER DELETE ON `awb_recibida`
FOR EACH ROW
IF (SELECT COUNT(*) FROM recibida_iva where recibida_id = OLD.recibida_id) = 0
AND
(SELECT COUNT(*) FROM recibida_vencimiento where recibida_id = OLD.recibida_id) = 0
AND
(SELECT contabilizada FROM recibida WHERE id = OLD.recibida_id) = 0
THEN
DELETE FROM recibida WHERE id = OLD.recibida_id;
END IF$$
DELIMITER ;

View File

@ -1,7 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn2008`.`Articles_botanical`
AS SELECT `ab`.`itemFk` AS `Id_Article`,
`ab`.`genusFk` AS `genus_id`,
`ab`.`specieFk` AS `specie_id`
FROM `vn`.`itemBotanical` `ab`

Some files were not shown because too many files have changed in this diff Show More