Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix into 6130-commitLint
This commit is contained in:
commit
9786c10e98
|
@ -1,4 +1,6 @@
|
|||
node_modules
|
||||
print/node_modules
|
||||
front/node_modules
|
||||
services
|
||||
front
|
||||
db
|
||||
e2e
|
||||
storage
|
||||
|
|
|
@ -10,3 +10,4 @@ print.*.json
|
|||
db.json
|
||||
junit.xml
|
||||
.DS_Store
|
||||
storage
|
|
@ -3,12 +3,20 @@
|
|||
// Carácter predeterminado de final de línea.
|
||||
"files.eol": "\n",
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": true
|
||||
"source.fixAll.eslint": "explicit"
|
||||
},
|
||||
"search.useIgnoreFiles": false,
|
||||
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
|
||||
"eslint.format.enable": true,
|
||||
"[javascript]": {
|
||||
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
|
||||
}
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "vscode.json-language-features"
|
||||
},
|
||||
"cSpell.words": [
|
||||
"salix",
|
||||
"fdescribe",
|
||||
"Loggable"
|
||||
]
|
||||
}
|
||||
|
|
134
CHANGELOG.md
134
CHANGELOG.md
|
@ -5,79 +5,138 @@ All notable changes to this project will be documented in this file.
|
|||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [2342.01] - 2023-10-19
|
||||
## [24.16.01] - 2024-04-18
|
||||
|
||||
## [2414.01] - 2024-04-04
|
||||
|
||||
## [2408.01] - 2024-02-22
|
||||
|
||||
## [2406.01] - 2024-02-08
|
||||
|
||||
### Added
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
## [2340.01] - 2023-10-05
|
||||
## [2404.01] - 2024-01-25
|
||||
|
||||
### Added
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
## [2402.01] - 2024-01-11
|
||||
|
||||
### Added
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
## [2400.01] - 2024-01-04
|
||||
|
||||
### Added
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
## [2350.01] - 2023-12-14
|
||||
|
||||
### Características Añadidas 🆕
|
||||
|
||||
- **Tickets → Expediciones:** Añadido soporte para Viaexpress
|
||||
|
||||
## [2348.01] - 2023-11-30
|
||||
|
||||
### Características Añadidas 🆕
|
||||
|
||||
- **Tickets → Adelantar:** Permite mover lineas sin generar negativos
|
||||
- **Tickets → Adelantar:** Permite modificar la fecha de los tickets
|
||||
- **Trabajadores → Notificaciones:** Nueva sección (lilium)
|
||||
|
||||
### Correcciones 🛠️
|
||||
|
||||
- **Tickets → RocketChat:** Arreglada detección de cambios
|
||||
|
||||
## [2346.01] - 2023-11-16
|
||||
|
||||
### Added
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
## [2342.01] - 2023-11-02
|
||||
|
||||
### Added
|
||||
|
||||
- (Usuarios -> Foto) Se muestra la foto del trabajador
|
||||
|
||||
### Changed
|
||||
### Fixed
|
||||
|
||||
- (Usuarios -> Historial) Abre el descriptor del usuario correctamente
|
||||
|
||||
## [2340.01] - 2023-10-05
|
||||
|
||||
## [2338.01] - 2023-09-21
|
||||
|
||||
### Added
|
||||
|
||||
- (Ticket -> Servicios) Se pueden abonar servicios
|
||||
- (Facturas -> Datos básicos) Muestra valores por defecto
|
||||
- (Facturas -> Borrado) Notificación al borrar un asiento ya enlazado en Sage
|
||||
|
||||
### Changed
|
||||
|
||||
- (Trabajadores -> Calendario) Icono de check arreglado cuando pulsas un tipo de dia
|
||||
|
||||
### Fixed
|
||||
|
||||
## [2336.01] - 2023-09-07
|
||||
|
||||
### Added
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
|
||||
## [2334.01] - 2023-08-24
|
||||
|
||||
### Added
|
||||
- (General -> Errores) Botón para enviar cau con los datos del error
|
||||
|
||||
- (General -> Errores) Botón para enviar cau con los datos del error
|
||||
|
||||
## [2332.01] - 2023-08-10
|
||||
|
||||
### Added
|
||||
|
||||
- (Trabajadores -> Gestión documental) Soporte para Docuware
|
||||
- (General -> Agencia) Soporte para Viaexpress
|
||||
- (Tickets -> SMS) Nueva sección en Lilium
|
||||
|
||||
### Changed
|
||||
|
||||
- (General -> Tickets) Devuelve el motivo por el cual no es editable
|
||||
- (Desplegables -> Trabajadores) Mejorados
|
||||
- (General -> Clientes) Razón social y dirección en mayúsculas
|
||||
|
||||
### Fixed
|
||||
- (Clientes -> SMS) Al pasar el ratón por encima muestra el mensaje completo
|
||||
|
||||
- (Clientes -> SMS) Al pasar el ratón por encima muestra el mensaje completo
|
||||
|
||||
## [2330.01] - 2023-07-27
|
||||
|
||||
### Added
|
||||
|
||||
- (Artículos -> Vista Previa) Añadido campo "Plástico reciclado"
|
||||
- (Rutas -> Troncales) Nueva sección
|
||||
- (Tickets -> Opciones) Opción establecer peso
|
||||
- (Clientes -> SMS) Nueva sección
|
||||
|
||||
### 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
|
||||
|
||||
|
||||
## [2328.01] - 2023-07-13
|
||||
|
||||
### Added
|
||||
|
||||
- (Clientes -> Morosos) Añadida columna "es trabajador"
|
||||
- (Trabajadores -> Departamentos) Nueva sección
|
||||
- (Trabajadores -> Departamentos) Añadido listado de Trabajadores por departamento
|
||||
|
@ -86,28 +145,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
### Changed
|
||||
|
||||
### Fixed
|
||||
- (Trabajadores -> Departamentos) Arreglado búscador
|
||||
|
||||
- (Trabajadores -> Departamentos) Arreglado búscador
|
||||
|
||||
## [2326.01] - 2023-06-29
|
||||
|
||||
### Added
|
||||
|
||||
- (Entradas -> Correo) Al cambiar el tipo de cambio enviará un correo a las personas designadas
|
||||
- (General -> Históricos) Botón para ver el estado del registro en cada punto
|
||||
- (General -> Históricos) Al filtar por registro se muestra todo el histórial desde que fue creado
|
||||
- (Tickets -> Índice) Permite enviar varios albaranes a Docuware
|
||||
|
||||
### 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
|
||||
|
||||
### Fixed
|
||||
|
||||
- (General -> Históricos) Duplicidades eliminadas
|
||||
- (Facturas -> Facturación global) Solucionados fallos que paran el proceso
|
||||
|
||||
## [2324.01] - 2023-06-15
|
||||
|
||||
### Added
|
||||
|
||||
- (Tickets -> Abono) Al abonar permite crear el ticket abono con almacén o sin almmacén
|
||||
- (General -> Desplegables) Mejorada eficiencia de carga de datos
|
||||
- (General -> Históricos) Ahora, ademas de los ids, se muestra la descripión de los atributos
|
||||
|
@ -115,77 +178,84 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
- (General -> Históricos) Filtro por cambios
|
||||
|
||||
### Changed
|
||||
|
||||
- (General -> Permisos) Mejorada seguridad
|
||||
- (General -> Históricos) Elementos de la interfaz reorganizados para hacerla más ágil e intuitiva
|
||||
|
||||
### Fixed
|
||||
|
||||
-
|
||||
|
||||
|
||||
|
||||
## [2322.01] - 2023-06-01
|
||||
|
||||
### Added
|
||||
|
||||
- (Tickets -> Crear Factura) Al facturar se envia automáticamente el pdf al cliente
|
||||
- (Artículos -> Histórico) Filtro para mostrar lo anterior al inventario
|
||||
- (Trabajadores -> Nuevo trabajador) Permite elegir el método de pago
|
||||
|
||||
### 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
|
||||
|
||||
### 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
|
||||
|
||||
|
||||
|
||||
## [2320.01] - 2023-05-25
|
||||
|
||||
### Added
|
||||
|
||||
- (Tickets -> Crear Factura) Al facturar se envia automáticamente el pdf al cliente
|
||||
|
||||
|
||||
### Changed
|
||||
|
||||
- (Trabajadores -> Nuevo trabajador) Los clientes se crean sin 'TR' pero se añade tipo de negocio 'Trabajador'
|
||||
|
||||
### Fixed
|
||||
|
||||
-
|
||||
|
||||
|
||||
|
||||
## [2318.01] - 2023-05-08
|
||||
|
||||
### Added
|
||||
|
||||
- (Usuarios -> Histórico) Nueva sección
|
||||
- (Roles -> Histórico) Nueva sección
|
||||
- (Trabajadores -> Dar de alta) Permite elegir el método de pago
|
||||
|
||||
### Changed
|
||||
|
||||
- (Artículo -> Precio fijado) Modificado el buscador superior por uno lateral
|
||||
- (Trabajadores -> Dar de alta) Quitada obligatoriedad del iban
|
||||
|
||||
### Fixed
|
||||
|
||||
- (Ticket -> Boxing) Arreglado selección de horas
|
||||
- (Cesta -> Índice) Optimizada búsqueda
|
||||
|
||||
|
||||
|
||||
## [2314.01] - 2023-04-20
|
||||
|
||||
### Added
|
||||
|
||||
- (Clientes -> Morosos) Ahora se puede filtrar por las columnas "Desde" y "Fecha Ú. O.". También se envia un email al comercial cuando se añade una nota.
|
||||
- (Monitor tickets) Muestra un icono al lado de la zona, si el ticket es frágil y se envía por agencia
|
||||
- (Facturas recibidas -> Bases negativas) Nueva sección
|
||||
|
||||
### Fixed
|
||||
|
||||
- (Clientes -> Morosos) Ahora se mantienen los elementos seleccionados al hacer sroll.
|
||||
|
||||
## [2312.01] - 2023-04-06
|
||||
|
||||
### Added
|
||||
|
||||
- (Monitor tickets) Muestra un icono al lado de la zona, si el ticket es frágil y se envía por agencia
|
||||
|
||||
### Changed
|
||||
|
||||
- (Monitor tickets) Cuando se filtra por 'Pendiente' ya no muestra los estados de 'Previa'
|
||||
- (Envíos -> Extra comunitarios) Se agrupan las entradas del mismo travel. Añadidos campos Referencia y Importe.
|
||||
- (Envíos -> Índice) Cambiado el buscador superior por uno lateral
|
||||
|
@ -193,33 +263,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
## [2310.01] - 2023-03-23
|
||||
|
||||
### Added
|
||||
|
||||
- (Trabajadores -> Control de horario) Ahora se puede confirmar/no confirmar el registro horario de cada semana desde esta sección
|
||||
|
||||
### 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
|
||||
|
||||
## [2308.01] - 2023-03-09
|
||||
|
||||
### Added
|
||||
|
||||
- (Proveedores -> Datos fiscales) Añadido checkbox 'Vies'
|
||||
- (Client -> Descriptor) Nuevo icono $ con barrotes para los clientes con impago
|
||||
- (Trabajador -> Datos Básicos) Añadido nuevo campo Taquilla
|
||||
- (Trabajador -> PDA) Nueva sección
|
||||
|
||||
### Changed
|
||||
|
||||
- (Ticket -> Borrar ticket) Restringido el borrado de tickets con abono
|
||||
|
||||
## [2306.01] - 2023-02-23
|
||||
|
||||
### Added
|
||||
|
||||
- (Tickets -> Datos Básicos) Mensaje de confirmación al intentar generar tickets con negativos
|
||||
- (Artículos) El visible y disponible se calcula a partir de un almacén diferente dependiendo de la sección en la que te encuentres. Se ha añadido un icono que informa sobre a partir de que almacén se esta calculando.
|
||||
|
||||
### Changed
|
||||
|
||||
- (General -> Inicio) Ahora permite recuperar la contraseña tanto con el correo de recuperación como el usuario
|
||||
|
||||
### Fixed
|
||||
|
||||
- (Monitor de tickets) Cuando ordenas por columna, ya no se queda deshabilitado el botón de 'Actualizar'
|
||||
- (Zone -> Días de entrega) Al hacer click en un día, muestra correctamente las zonas
|
||||
- (Artículos) El disponible en la vista previa se muestra correctamente
|
||||
|
@ -227,12 +304,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
## [2304.01] - 2023-02-09
|
||||
|
||||
### Added
|
||||
|
||||
- (Rutas) Al descargar varias facturas se comprime en un zip
|
||||
- (Trabajadores -> Nuevo trabajador) Nueva sección
|
||||
- (Tickets -> Adelantar tickets) Añadidos campos "líneas" y "litros" al ticket origen
|
||||
- (Tickets -> Adelantar tickets) Nuevo icono muestra cuando las agencias de los tickets origen/destino son distintas
|
||||
|
||||
### Changed
|
||||
|
||||
- (Entradas -> Compras) Cambiados los campos "Precio Grouping/Packing" por "PVP" y "Precio" por "Coste"
|
||||
- (Artículos -> Últimas entradas) Cambiados los campos "P.P.U." y "P.P.P." por "PVP"
|
||||
- (Rutas -> Sumario/Tickets) Actualizados campos de los tickets
|
||||
|
@ -241,6 +320,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
- (Tickets -> Adelantar tickets) Cambiado stock de destino a origen.
|
||||
|
||||
### Fixed
|
||||
|
||||
- (Artículos -> Etiquetas) Permite intercambiar la relevancia entre dos etiquetas.
|
||||
- (Cliente -> Datos Fiscales) No se permite seleccionar 'Notificar vía e-mail' a los clientes sin e-mail
|
||||
- (Tickets -> Datos básicos) Permite guardar la hora de envío
|
||||
|
@ -251,17 +331,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
## [2302.01] - 2023-01-26
|
||||
|
||||
### Added
|
||||
|
||||
- (General -> Inicio) Permite recuperar la contraseña
|
||||
- (Tickets -> Opciones) Subir albarán a Docuware
|
||||
- (Tickets -> Opciones) Enviar correo con PDF de Docuware
|
||||
- (Artículos -> Datos Básicos) Añadido campo Unidades/Caja
|
||||
|
||||
### Changed
|
||||
|
||||
- (Reclamaciones -> Descriptor) Cambiado el campo Agencia por Zona
|
||||
- (Tickets -> Líneas preparadas) Actualizada sección para que sea más visual
|
||||
|
||||
### Fixed
|
||||
|
||||
- (General) Al utilizar el traductor de Google se descuadraban los iconos
|
||||
|
||||
### Removed
|
||||
|
||||
- (Tickets -> Control clientes) Eliminada sección
|
||||
|
|
|
@ -1,144 +1,254 @@
|
|||
#!/usr/bin/env groovy
|
||||
|
||||
def PROTECTED_BRANCH
|
||||
def FROM_GIT
|
||||
def RUN_TESTS
|
||||
def RUN_BUILD
|
||||
|
||||
def BRANCH_ENV = [
|
||||
test: 'test',
|
||||
master: 'production'
|
||||
]
|
||||
|
||||
node {
|
||||
stage('Setup') {
|
||||
env.BACK_REPLICAS = 1
|
||||
env.NODE_ENV = BRANCH_ENV[env.BRANCH_NAME] ?: 'dev'
|
||||
|
||||
PROTECTED_BRANCH = [
|
||||
'dev',
|
||||
'test',
|
||||
'master'
|
||||
].contains(env.BRANCH_NAME)
|
||||
|
||||
FROM_GIT = env.JOB_NAME.startsWith('gitea/')
|
||||
RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT
|
||||
RUN_BUILD = PROTECTED_BRANCH && FROM_GIT
|
||||
|
||||
// https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables
|
||||
echo "NODE_NAME: ${env.NODE_NAME}"
|
||||
echo "WORKSPACE: ${env.WORKSPACE}"
|
||||
|
||||
configFileProvider([
|
||||
configFile(fileId: 'salix.properties',
|
||||
variable: 'PROPS_FILE')
|
||||
]) {
|
||||
def props = readProperties file: PROPS_FILE
|
||||
props.each {key, value -> env."${key}" = value }
|
||||
props.each {key, value -> echo "${key}: ${value}" }
|
||||
}
|
||||
|
||||
if (PROTECTED_BRANCH) {
|
||||
configFileProvider([
|
||||
configFile(fileId: "salix.branch.${env.BRANCH_NAME}",
|
||||
variable: 'BRANCH_PROPS_FILE')
|
||||
]) {
|
||||
def props = readProperties file: BRANCH_PROPS_FILE
|
||||
props.each {key, value -> env."${key}" = value }
|
||||
props.each {key, value -> echo "${key}: ${value}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pipeline {
|
||||
agent any
|
||||
options {
|
||||
disableConcurrentBuilds()
|
||||
}
|
||||
tools {
|
||||
nodejs 'node-v20'
|
||||
}
|
||||
environment {
|
||||
PROJECT_NAME = 'salix'
|
||||
STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}"
|
||||
}
|
||||
stages {
|
||||
stage('Checkout') {
|
||||
steps {
|
||||
script {
|
||||
switch (env.BRANCH_NAME) {
|
||||
case 'master':
|
||||
env.NODE_ENV = 'production'
|
||||
env.BACK_REPLICAS = 4
|
||||
break
|
||||
case 'test':
|
||||
env.NODE_ENV = 'test'
|
||||
env.BACK_REPLICAS = 2
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
configFileProvider([
|
||||
configFile(fileId: "salix.groovy",
|
||||
variable: 'GROOVY_FILE')
|
||||
]) {
|
||||
load env.GROOVY_FILE
|
||||
}
|
||||
|
||||
setEnv()
|
||||
}
|
||||
}
|
||||
stage('Install') {
|
||||
environment {
|
||||
NODE_ENV = ""
|
||||
}
|
||||
steps {
|
||||
nodejs('node-v20') {
|
||||
sh 'npm install --no-audit --prefer-offline'
|
||||
sh 'gulp install --ci'
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Test') {
|
||||
when { not { anyOf {
|
||||
branch 'test'
|
||||
branch 'master'
|
||||
}}}
|
||||
environment {
|
||||
NODE_ENV = ""
|
||||
TZ = 'Europe/Madrid'
|
||||
NODE_ENV = ''
|
||||
}
|
||||
parallel {
|
||||
stage('Frontend') {
|
||||
stage('Back') {
|
||||
steps {
|
||||
nodejs('node-v20') {
|
||||
sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=2'
|
||||
sh 'pnpm install --prefer-offline'
|
||||
}
|
||||
}
|
||||
stage('Print') {
|
||||
when {
|
||||
expression { FROM_GIT }
|
||||
}
|
||||
stage('Backend') {
|
||||
steps {
|
||||
nodejs('node-v20') {
|
||||
sh 'npm run test:back:ci'
|
||||
sh 'pnpm install --prefer-offline --prefix=print'
|
||||
}
|
||||
}
|
||||
stage('Front') {
|
||||
when {
|
||||
expression { FROM_GIT }
|
||||
}
|
||||
steps {
|
||||
sh 'pnpm install --prefer-offline --prefix=front'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Stack') {
|
||||
parallel {
|
||||
stage('Back') {
|
||||
stages {
|
||||
stage('Test') {
|
||||
when {
|
||||
expression { RUN_TESTS }
|
||||
}
|
||||
environment {
|
||||
NODE_ENV = ''
|
||||
}
|
||||
steps {
|
||||
sh 'node back/tests.js --ci --junit --network jenkins'
|
||||
}
|
||||
post {
|
||||
always {
|
||||
junit(
|
||||
testResults: 'junitresults.xml',
|
||||
allowEmptyResults: true
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Build') {
|
||||
when { anyOf {
|
||||
branch 'test'
|
||||
branch 'master'
|
||||
}}
|
||||
when {
|
||||
expression { RUN_BUILD }
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
def packageJson = readJSON file: 'package.json'
|
||||
env.VERSION = packageJson.version
|
||||
}
|
||||
sh 'docker-compose build back'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Front') {
|
||||
when {
|
||||
expression { FROM_GIT }
|
||||
}
|
||||
stages {
|
||||
stage('Test') {
|
||||
when {
|
||||
expression { RUN_TESTS }
|
||||
}
|
||||
environment {
|
||||
NODE_ENV = ''
|
||||
}
|
||||
steps {
|
||||
sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=10'
|
||||
}
|
||||
post {
|
||||
always {
|
||||
junit(
|
||||
testResults: 'junit.xml',
|
||||
allowEmptyResults: true
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Build') {
|
||||
when {
|
||||
expression { RUN_BUILD }
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
def packageJson = readJSON file: 'package.json'
|
||||
env.VERSION = packageJson.version
|
||||
}
|
||||
sh 'gulp build'
|
||||
sh 'docker-compose build front'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Push') {
|
||||
when {
|
||||
expression { RUN_BUILD }
|
||||
}
|
||||
environment {
|
||||
CREDENTIALS = credentials('docker-registry')
|
||||
}
|
||||
steps {
|
||||
nodejs('node-v20') {
|
||||
sh 'gulp build'
|
||||
script {
|
||||
def packageJson = readJSON file: 'package.json'
|
||||
env.VERSION = packageJson.version
|
||||
}
|
||||
|
||||
dockerBuild()
|
||||
sh 'docker login --username $CREDENTIALS_USR --password $CREDENTIALS_PSW $REGISTRY'
|
||||
sh 'docker-compose push'
|
||||
}
|
||||
}
|
||||
stage('Deploy') {
|
||||
when { anyOf {
|
||||
branch 'test'
|
||||
branch 'master'
|
||||
}}
|
||||
environment {
|
||||
DOCKER_HOST = "${env.SWARM_HOST}"
|
||||
}
|
||||
steps {
|
||||
sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}"
|
||||
}
|
||||
when {
|
||||
expression { PROTECTED_BRANCH }
|
||||
}
|
||||
parallel {
|
||||
stage('Database') {
|
||||
when { anyOf {
|
||||
branch 'test'
|
||||
branch 'master'
|
||||
}}
|
||||
steps {
|
||||
configFileProvider([
|
||||
configFile(fileId: "config.${env.NODE_ENV}.ini",
|
||||
variable: 'MYSQL_CONFIG')
|
||||
]) {
|
||||
sh 'cp "$MYSQL_CONFIG" db/config.$NODE_ENV.ini'
|
||||
sh 'mkdir -p db/remotes'
|
||||
sh 'cp "$MYSQL_CONFIG" db/remotes/$NODE_ENV.ini'
|
||||
}
|
||||
|
||||
sh 'db/import-changes.sh -f $NODE_ENV'
|
||||
sh 'npx myt push $NODE_ENV --force --commit'
|
||||
}
|
||||
}
|
||||
stage('Docker') {
|
||||
when {
|
||||
expression { FROM_GIT }
|
||||
}
|
||||
environment {
|
||||
DOCKER_HOST = "${env.SWARM_HOST}"
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
def packageJson = readJSON file: 'package.json'
|
||||
env.VERSION = packageJson.version
|
||||
}
|
||||
sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
post {
|
||||
always {
|
||||
success {
|
||||
script {
|
||||
if (!['master', 'test'].contains(env.BRANCH_NAME)) {
|
||||
try {
|
||||
junit 'junitresults.xml'
|
||||
junit 'junit.xml'
|
||||
} catch (e) {
|
||||
echo e.toString()
|
||||
}
|
||||
}
|
||||
if (env.BRANCH_NAME == 'master' && FROM_GIT) {
|
||||
env.GIT_COMMIT_MSG = sh(
|
||||
script: 'git log -1 --pretty=%B ${GIT_COMMIT}',
|
||||
returnStdout: true
|
||||
).trim()
|
||||
|
||||
if (!env.COMMITTER_EMAIL || currentBuild.currentResult == 'SUCCESS') return;
|
||||
try {
|
||||
mail(
|
||||
to: env.COMMITTER_EMAIL,
|
||||
subject: "Pipeline: ${env.JOB_NAME} (${env.BUILD_NUMBER}): ${currentBuild.currentResult}",
|
||||
body: "Check status at ${env.BUILD_URL}"
|
||||
String message = env.GIT_COMMIT_MSG
|
||||
int index = message.indexOf('\n')
|
||||
if (index != -1)
|
||||
message = message.substring(0, index)
|
||||
|
||||
setEnv()
|
||||
rocketSend(
|
||||
channel: 'vn-database',
|
||||
message: "*DB version uploaded:* ${message}"
|
||||
+"\n$COMMITTER_EMAIL ($BRANCH_NAME)"
|
||||
+"\n$RUN_DISPLAY_URL",
|
||||
rawMessage: true
|
||||
)
|
||||
} catch (e) {
|
||||
echo e.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
unsuccessful {
|
||||
setEnv()
|
||||
sendEmail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
40
README.md
40
README.md
|
@ -8,7 +8,7 @@ Salix is also the scientific name of a beautifull tree! :)
|
|||
|
||||
Required applications.
|
||||
|
||||
* Node.js >= 16.x LTS
|
||||
* Node.js
|
||||
* Docker
|
||||
* Git
|
||||
|
||||
|
@ -17,20 +17,7 @@ You will need to install globally the following items.
|
|||
$ sudo npm install -g jest gulp-cli
|
||||
```
|
||||
|
||||
For the usage of jest --watch on macOs.
|
||||
```
|
||||
$ brew install watchman
|
||||
```
|
||||
* [watchman](https://facebook.github.io/watchman/)
|
||||
|
||||
## Linux Only Prerequisites
|
||||
|
||||
Your user must be on the docker group to use it so you will need to run this command:
|
||||
```
|
||||
$ sudo usermod -a -G docker yourusername
|
||||
```
|
||||
|
||||
## Getting Started // Installing
|
||||
## Installing dependencies and launching
|
||||
|
||||
Pull from repository.
|
||||
|
||||
|
@ -76,29 +63,6 @@ In Visual Studio Code we use the ESLint extension.
|
|||
ext install dbaeumer.vscode-eslint
|
||||
```
|
||||
|
||||
Gitlens for visualization of code authorship
|
||||
```
|
||||
ext install eamodio.gitlens
|
||||
```
|
||||
|
||||
Spanish language pack
|
||||
```
|
||||
ext install ms-ceintl.vscode-language-pack-es
|
||||
```
|
||||
|
||||
### Recommended extensions
|
||||
|
||||
Material icon Theme
|
||||
```
|
||||
ext install pkief.material-icon-theme
|
||||
```
|
||||
|
||||
Material UI Themes
|
||||
```
|
||||
ext install equinusocio.vsc-material-theme
|
||||
```
|
||||
|
||||
|
||||
## Built With
|
||||
|
||||
* [angularjs](https://angularjs.org/)
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
FROM debian:bullseye-slim
|
||||
FROM debian:bookworm-slim
|
||||
ENV TZ Europe/Madrid
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
|
@ -13,7 +13,7 @@ RUN apt-get update \
|
|||
graphicsmagick \
|
||||
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
|
||||
&& apt-get install -y --no-install-recommends nodejs \
|
||||
&& npm install -g npm@9.6.6
|
||||
&& corepack enable pnpm
|
||||
|
||||
# Puppeteer
|
||||
|
||||
|
@ -25,7 +25,13 @@ RUN apt-get update \
|
|||
libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 \
|
||||
libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 \
|
||||
libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 \
|
||||
fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget \
|
||||
fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget
|
||||
|
||||
# Extra dependencies
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
samba-common-bin samba-dsdb-modules\
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& npm -g install pm2
|
||||
|
||||
|
@ -33,12 +39,12 @@ RUN apt-get update \
|
|||
|
||||
WORKDIR /salix
|
||||
|
||||
COPY print/package.json print/package-lock.json print/
|
||||
RUN npm --prefix ./print install --omit=dev ./print
|
||||
COPY print/package.json print/pnpm-lock.yaml print/
|
||||
RUN pnpm install --prod --prefix=print
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
COPY loopback/package.json loopback/
|
||||
RUN npm install --omit=dev
|
||||
RUN pnpm install --prod
|
||||
|
||||
COPY loopback loopback
|
||||
COPY back back
|
|
@ -26,15 +26,14 @@ module.exports = Self => {
|
|||
|
||||
Self.sendCheckingPresence = async(ctx, recipientId, message) => {
|
||||
if (!recipientId) return false;
|
||||
|
||||
const models = Self.app.models;
|
||||
|
||||
const userId = ctx.req.accessToken.userId;
|
||||
const sender = await models.VnUser.findById(userId, {fields: ['id']});
|
||||
const recipient = await models.VnUser.findById(recipientId, null);
|
||||
|
||||
// Prevent sending messages to yourself
|
||||
if (recipientId == userId) return false;
|
||||
|
||||
if (!recipient)
|
||||
throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`);
|
||||
|
||||
|
|
|
@ -0,0 +1,32 @@
|
|||
const UserError = require('vn-loopback/util/user-error');
|
||||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('assign', {
|
||||
description: 'Assign a collection',
|
||||
accessType: 'WRITE',
|
||||
http: {
|
||||
path: `/assign`,
|
||||
verb: 'POST'
|
||||
},
|
||||
returns: {
|
||||
type: ['object'],
|
||||
root: true
|
||||
},
|
||||
});
|
||||
|
||||
Self.assign = async(ctx, options) => {
|
||||
const userId = ctx.req.accessToken.userId;
|
||||
const myOptions = {userId};
|
||||
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
||||
const [, , [{collectionFk}]] =
|
||||
await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk); SELECT @vCollectionFk collectionFk',
|
||||
[userId], myOptions);
|
||||
|
||||
if (!collectionFk) throw new UserError('There are not picking tickets');
|
||||
await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions);
|
||||
|
||||
return collectionFk;
|
||||
};
|
||||
};
|
|
@ -0,0 +1,157 @@
|
|||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('getSales', {
|
||||
description: 'Get sales from ticket or collection',
|
||||
accessType: 'READ',
|
||||
accepts: [
|
||||
{
|
||||
arg: 'collectionOrTicketFk',
|
||||
type: 'number',
|
||||
required: true
|
||||
}, {
|
||||
arg: 'print',
|
||||
type: 'boolean',
|
||||
required: true
|
||||
}, {
|
||||
arg: 'source',
|
||||
type: 'string',
|
||||
required: true
|
||||
},
|
||||
|
||||
],
|
||||
returns: {
|
||||
type: 'Object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/getSales`,
|
||||
verb: 'GET'
|
||||
},
|
||||
});
|
||||
|
||||
Self.getSales = async(ctx, collectionOrTicketFk, print, source, options) => {
|
||||
const userId = ctx.req.accessToken.userId;
|
||||
const myOptions = {userId};
|
||||
const $t = ctx.req.__;
|
||||
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
||||
const [{id}] = await Self.rawSql('SELECT vn.ticket_get(?) as id',
|
||||
[collectionOrTicketFk],
|
||||
myOptions);
|
||||
|
||||
const [tickets] = await Self.rawSql('CALL vn.collection_getTickets(?)', [id], myOptions);
|
||||
|
||||
if (source) {
|
||||
await Self.rawSql(
|
||||
'CALL vn.ticketStateToday_setState(?,?)', [id, source], myOptions
|
||||
);
|
||||
}
|
||||
|
||||
const [sales] = await Self.rawSql('CALL vn.sale_getFromTicketOrCollection(?)',
|
||||
[id], myOptions);
|
||||
|
||||
const isPicker = source != 'CHECKER';
|
||||
const [placements] = await Self.rawSql('CALL vn.collectionPlacement_get(?, ?)',
|
||||
[id, isPicker], myOptions
|
||||
);
|
||||
|
||||
if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions);
|
||||
|
||||
for (let ticket of tickets) {
|
||||
let observations = ticket.observaciones.split(' ');
|
||||
|
||||
for (let observation of observations) {
|
||||
const salesPerson = ticket.salesPersonFk;
|
||||
if (observation.startsWith('#') || observation.startsWith('@')) {
|
||||
await models.Chat.send(ctx,
|
||||
observation,
|
||||
$t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return getCollection(id, tickets, sales, placements, myOptions);
|
||||
};
|
||||
|
||||
async function getCollection(id, tickets, sales, placements, options) {
|
||||
const collection = {
|
||||
collectionFk: id,
|
||||
tickets: [],
|
||||
};
|
||||
for (let ticket of tickets) {
|
||||
const {ticketFk} = ticket;
|
||||
ticket.sales = [];
|
||||
|
||||
const barcodes = await getBarcodes(ticketFk, options);
|
||||
await Self.rawSql(
|
||||
'CALL util.log_add(?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
['vn', 'ticket', 'Ticket', ticketFk, ticketFk, 'select', null, null],
|
||||
options
|
||||
);
|
||||
|
||||
for (let sale of sales) {
|
||||
if (sale.ticketFk == ticketFk) {
|
||||
sale.placements = [];
|
||||
for (const salePlacement of placements) {
|
||||
if (salePlacement.saleFk == sale.saleFk && salePlacement.order) {
|
||||
const placement = {
|
||||
saleFk: salePlacement.saleFk,
|
||||
itemFk: salePlacement.itemFk,
|
||||
placement: salePlacement.placement,
|
||||
shelving: salePlacement.shelving,
|
||||
created: salePlacement.created,
|
||||
visible: salePlacement.visible,
|
||||
order: salePlacement.order,
|
||||
grouping: salePlacement.grouping,
|
||||
priority: salePlacement.priority,
|
||||
saleOrder: salePlacement.saleOrder,
|
||||
isPreviousPrepared: salePlacement.isPreviousPrepared,
|
||||
itemShelvingSaleFk: salePlacement.itemShelvingSaleFk,
|
||||
ticketFk: salePlacement.ticketFk,
|
||||
id: salePlacement.id
|
||||
};
|
||||
sale.placements.push(placement);
|
||||
}
|
||||
}
|
||||
|
||||
sale.barcodes = [];
|
||||
for (const barcode of barcodes) {
|
||||
if (barcode.movementId == sale.saleFk) {
|
||||
if (barcode.code) {
|
||||
sale.barcodes.push(barcode.code);
|
||||
sale.barcodes.push(`0 ${barcode.code}`);
|
||||
}
|
||||
|
||||
if (barcode.id) {
|
||||
sale.barcodes.push(barcode.id);
|
||||
sale.barcodes.push(`0 ${barcode.id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ticket.sales.push(sale);
|
||||
}
|
||||
}
|
||||
collection.tickets.push(ticket);
|
||||
}
|
||||
|
||||
return collection;
|
||||
}
|
||||
|
||||
async function getBarcodes(ticketId, options) {
|
||||
const query =
|
||||
`SELECT s.id movementId,
|
||||
b.code,
|
||||
c.id
|
||||
FROM vn.sale s
|
||||
LEFT JOIN vn.itemBarcode b ON b.itemFk = s.itemFk
|
||||
LEFT JOIN vn.buy c ON c.itemFk = s.itemFk
|
||||
LEFT JOIN vn.entry e ON e.id = c.entryFk
|
||||
LEFT JOIN vn.travel tr ON tr.id = e.travelFk
|
||||
WHERE s.ticketFk = ?
|
||||
AND tr.landed >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)`;
|
||||
return Self.rawSql(query, [ticketId], options);
|
||||
}
|
||||
};
|
|
@ -1,20 +0,0 @@
|
|||
module.exports = Self => {
|
||||
Self.remoteMethod('getSectors', {
|
||||
description: 'Get all sectors',
|
||||
accessType: 'READ',
|
||||
returns: {
|
||||
type: 'Object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/getSectors`,
|
||||
verb: 'GET'
|
||||
}
|
||||
});
|
||||
|
||||
Self.getSectors = async() => {
|
||||
const query = `CALL vn.sector_get()`;
|
||||
const [result] = await Self.rawSql(query);
|
||||
return result;
|
||||
};
|
||||
};
|
|
@ -26,7 +26,7 @@ module.exports = Self => {
|
|||
|
||||
Self.getTickets = async(ctx, id, print, options) => {
|
||||
const userId = ctx.req.accessToken.userId;
|
||||
const origin = ctx.req.headers.origin;
|
||||
const url = await Self.app.models.Url.getUrl();
|
||||
const $t = ctx.req.__;
|
||||
const myOptions = {};
|
||||
|
||||
|
@ -36,7 +36,6 @@ module.exports = Self => {
|
|||
myOptions.userId = userId;
|
||||
|
||||
const promises = [];
|
||||
|
||||
const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions);
|
||||
const sales = await Self.rawSql(`
|
||||
SELECT s.ticketFk,
|
||||
|
@ -76,7 +75,7 @@ module.exports = Self => {
|
|||
LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
|
||||
LEFT JOIN origin o ON o.id = i.originFk
|
||||
WHERE tc.collectionFk = ?
|
||||
GROUP BY ish.id, p.code, p2.code
|
||||
GROUP BY s.id, ish.id, p.code, p2.code
|
||||
ORDER BY pickingOrder;`, [id], myOptions);
|
||||
|
||||
if (print)
|
||||
|
@ -86,24 +85,19 @@ module.exports = Self => {
|
|||
if (tickets && tickets.length) {
|
||||
for (const ticket of tickets) {
|
||||
const ticketId = ticket.ticketFk;
|
||||
|
||||
// SEND ROCKET
|
||||
if (ticket.observaciones != '') {
|
||||
for (observation of ticket.observaciones.split(' ')) {
|
||||
if (['#', '@'].includes(observation.charAt(0))) {
|
||||
promises.push(Self.app.models.Chat.send(ctx, observation,
|
||||
$t('The ticket is in preparation', {
|
||||
ticketId: ticketId,
|
||||
ticketUrl: `${origin}/#!/ticket/${ticketId}/summary`,
|
||||
ticketUrl: `${url}ticket/${ticketId}/summary`,
|
||||
salesPersonId: ticket.salesPersonFk
|
||||
})));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SET COLLECTION
|
||||
if (sales && sales.length) {
|
||||
// GET BARCODES
|
||||
const barcodes = await Self.rawSql(`
|
||||
SELECT s.id saleFk, b.code, c.id
|
||||
FROM vn.sale s
|
||||
|
@ -114,13 +108,10 @@ module.exports = Self => {
|
|||
WHERE s.ticketFk = ?
|
||||
AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`,
|
||||
[ticketId], myOptions);
|
||||
|
||||
// BINDINGS
|
||||
ticket.sales = [];
|
||||
for (const sale of sales) {
|
||||
if (sale.ticketFk === ticketId) {
|
||||
sale.Barcodes = [];
|
||||
|
||||
if (barcodes && barcodes.length) {
|
||||
for (const barcode of barcodes) {
|
||||
if (barcode.saleFk === sale.saleFk) {
|
||||
|
@ -131,7 +122,6 @@ module.exports = Self => {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
ticket.sales.push(sale);
|
||||
}
|
||||
}
|
||||
|
@ -140,7 +130,6 @@ module.exports = Self => {
|
|||
}
|
||||
}
|
||||
await Promise.all(promises);
|
||||
|
||||
return collection;
|
||||
};
|
||||
};
|
||||
|
|
|
@ -1,133 +0,0 @@
|
|||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('newCollection', {
|
||||
description: 'Make a new collection of tickets',
|
||||
accessType: 'WRITE',
|
||||
accepts: [{
|
||||
arg: 'collectionFk',
|
||||
type: 'Number',
|
||||
required: false,
|
||||
description: 'The collection id'
|
||||
}, {
|
||||
arg: 'sectorFk',
|
||||
type: 'Number',
|
||||
required: true,
|
||||
description: 'The sector of worker'
|
||||
}, {
|
||||
arg: 'vWagons',
|
||||
type: 'Number',
|
||||
required: true,
|
||||
description: 'The number of wagons'
|
||||
}],
|
||||
returns: {
|
||||
type: 'Object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/newCollection`,
|
||||
verb: 'POST'
|
||||
}
|
||||
});
|
||||
|
||||
Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => {
|
||||
let query = '';
|
||||
const userId = ctx.req.accessToken.userId;
|
||||
|
||||
if (!collectionFk) {
|
||||
query = `CALL vn.collectionTrain_newBeta(?,?,?)`;
|
||||
const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId], {userId});
|
||||
if (result.length == 0)
|
||||
throw new Error(`No collections for today`);
|
||||
|
||||
collectionFk = result[0].vCollectionFk;
|
||||
}
|
||||
|
||||
query = `CALL vn.collectionTicket_get(?)`;
|
||||
const [tickets] = await Self.rawSql(query, [collectionFk], {userId});
|
||||
|
||||
query = `CALL vn.collectionSale_get(?)`;
|
||||
const [sales] = await Self.rawSql(query, [collectionFk], {userId});
|
||||
|
||||
query = `CALL vn.collectionPlacement_get(?)`;
|
||||
const [placements] = await Self.rawSql(query, [collectionFk], {userId});
|
||||
|
||||
query = `CALL vn.collectionSticker_print(?,?)`;
|
||||
await Self.rawSql(query, [collectionFk, sectorFk], {userId});
|
||||
|
||||
return makeCollection(tickets, sales, placements, collectionFk);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a collection json
|
||||
* @param {*} tickets - Request tickets
|
||||
* @param {*} sales - Request sales
|
||||
* @param {*} placements - Request placements
|
||||
* @param {*} collectionFk - Request placements
|
||||
* @return {Object} Collection JSON
|
||||
*/
|
||||
async function makeCollection(tickets, sales, placements, collectionFk) {
|
||||
let collection = [];
|
||||
|
||||
for (let i = 0; i < tickets.length; i++) {
|
||||
let ticket = {};
|
||||
ticket['ticketFk'] = tickets[i]['ticketFk'];
|
||||
ticket['level'] = tickets[i]['level'];
|
||||
ticket['agencyName'] = tickets[i]['agencyName'];
|
||||
ticket['warehouseFk'] = tickets[i]['warehouseFk'];
|
||||
ticket['salesPersonFk'] = tickets[i]['salesPersonFk'];
|
||||
|
||||
let ticketSales = [];
|
||||
|
||||
for (let x = 0; x < sales.length; x++) {
|
||||
if (sales[x]['ticketFk'] == ticket['ticketFk']) {
|
||||
let sale = {};
|
||||
sale['collectionFk'] = collectionFk;
|
||||
sale['ticketFk'] = sales[x]['ticketFk'];
|
||||
sale['saleFk'] = sales[x]['saleFk'];
|
||||
sale['itemFk'] = sales[x]['itemFk'];
|
||||
sale['quantity'] = sales[x]['quantity'];
|
||||
if (sales[x]['quantityPicked'] != null)
|
||||
sale['quantityPicked'] = sales[x]['quantityPicked'];
|
||||
else
|
||||
sale['quantityPicked'] = 0;
|
||||
sale['longName'] = sales[x]['longName'];
|
||||
sale['size'] = sales[x]['size'];
|
||||
sale['color'] = sales[x]['color'];
|
||||
sale['discount'] = sales[x]['discount'];
|
||||
sale['price'] = sales[x]['price'];
|
||||
sale['stems'] = sales[x]['stems'];
|
||||
sale['category'] = sales[x]['category'];
|
||||
sale['origin'] = sales[x]['origin'];
|
||||
sale['clientFk'] = sales[x]['clientFk'];
|
||||
sale['productor'] = sales[x]['productor'];
|
||||
sale['reserved'] = sales[x]['reserved'];
|
||||
sale['isPreviousPrepared'] = sales[x]['isPreviousPrepared'];
|
||||
sale['isPrepared'] = sales[x]['isPrepared'];
|
||||
sale['isControlled'] = sales[x]['isControlled'];
|
||||
|
||||
let salePlacements = [];
|
||||
|
||||
for (let z = 0; z < placements.length; z++) {
|
||||
if (placements[z]['saleFk'] == sale['saleFk']) {
|
||||
let placement = {};
|
||||
placement['saleFk'] = placements[z]['saleFk'];
|
||||
placement['itemFk'] = placements[z]['itemFk'];
|
||||
placement['placement'] = placements[z]['placement'];
|
||||
placement['shelving'] = placements[z]['shelving'];
|
||||
placement['created'] = placements[z]['created'];
|
||||
placement['visible'] = placements[z]['visible'];
|
||||
placement['order'] = placements[z]['order'];
|
||||
placement['grouping'] = placements[z]['grouping'];
|
||||
salePlacements.push(placement);
|
||||
}
|
||||
}
|
||||
sale['placements'] = salePlacements;
|
||||
ticketSales.push(sale);
|
||||
}
|
||||
}
|
||||
ticket['sales'] = ticketSales;
|
||||
collection.push(ticket);
|
||||
}
|
||||
|
||||
return collection;
|
||||
}
|
||||
};
|
|
@ -0,0 +1,38 @@
|
|||
const models = require('vn-loopback/server/server').models;
|
||||
const LoopBackContext = require('loopback-context');
|
||||
|
||||
describe('ticket assign()', () => {
|
||||
let ctx;
|
||||
let options;
|
||||
let tx;
|
||||
beforeEach(async() => {
|
||||
ctx = {
|
||||
req: {
|
||||
accessToken: {userId: 1106},
|
||||
headers: {origin: 'http://localhost'},
|
||||
__: value => value
|
||||
},
|
||||
args: {}
|
||||
};
|
||||
|
||||
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
|
||||
active: ctx.req
|
||||
});
|
||||
|
||||
options = {transaction: tx};
|
||||
tx = await models.Sale.beginTransaction({});
|
||||
options.transaction = tx;
|
||||
});
|
||||
|
||||
afterEach(async() => {
|
||||
await tx.rollback();
|
||||
});
|
||||
|
||||
it('should throw an error when there is not picking tickets', async() => {
|
||||
try {
|
||||
await models.Collection.assign(ctx, options);
|
||||
} catch (e) {
|
||||
expect(e.message).toEqual('There are not picking tickets');
|
||||
}
|
||||
});
|
||||
});
|
|
@ -0,0 +1,62 @@
|
|||
const {models} = require('vn-loopback/server/server');
|
||||
|
||||
describe('collection getSales()', () => {
|
||||
const collectionOrTicketFk = 999999;
|
||||
const print = true;
|
||||
const source = 'CHECKER';
|
||||
|
||||
beforeAll(() => {
|
||||
ctx = {
|
||||
req: {
|
||||
accessToken: {userId: 9},
|
||||
headers: {origin: 'http://localhost'},
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
it('should return a collection with tickets, placements and barcodes settled correctly', async() => {
|
||||
const tx = await models.Collection.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
try {
|
||||
const collection = await models.Collection.getSales(ctx,
|
||||
collectionOrTicketFk, print, source, options);
|
||||
|
||||
const [firstTicket] = collection.tickets;
|
||||
const [firstSale] = firstTicket.sales;
|
||||
const [firstPlacement] = firstSale.placements;
|
||||
|
||||
expect(collection.tickets.length).toBeTruthy();
|
||||
expect(collection.collectionFk).toEqual(firstTicket.ticketFk);
|
||||
|
||||
expect(firstSale.ticketFk).toEqual(firstTicket.ticketFk);
|
||||
expect(firstSale.placements.length).toBeTruthy();
|
||||
expect(firstSale.barcodes.length).toBeTruthy();
|
||||
|
||||
expect(firstSale.saleFk).toEqual(firstPlacement.saleFk);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
it('should print a sticker', async() => {
|
||||
const tx = await models.Collection.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
const query = 'SELECT * FROM printQueue pq JOIN printQueueArgs pqa ON pqa.printQueueFk = pq.id';
|
||||
try {
|
||||
const printQueueBefore = await models.Collection.rawSql(
|
||||
query, [], options);
|
||||
await models.Collection.getSales(ctx,
|
||||
collectionOrTicketFk, true, source, options);
|
||||
const printQueueAfter = await models.Collection.rawSql(
|
||||
query, [], options);
|
||||
|
||||
expect(printQueueAfter.length).toEqual(printQueueBefore.length + 1);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
});
|
|
@ -1,11 +0,0 @@
|
|||
const {models} = require('vn-loopback/server/server');
|
||||
|
||||
describe('getSectors()', () => {
|
||||
it('return list of sectors', async() => {
|
||||
let response = await models.Collection.getSectors();
|
||||
|
||||
expect(response.length).toBeGreaterThan(0);
|
||||
expect(response[0].id).toEqual(1);
|
||||
expect(response[0].description).toEqual('First sector');
|
||||
});
|
||||
});
|
|
@ -1,12 +0,0 @@
|
|||
const {models} = require('vn-loopback/server/server');
|
||||
|
||||
describe('newCollection()', () => {
|
||||
it('should return a new collection', async() => {
|
||||
pending('#3400 analizar que hacer con rutas de back collection');
|
||||
let ctx = {req: {accessToken: {userId: 1106}}};
|
||||
let response = await models.Collection.newCollection(ctx, 1, 1, 1);
|
||||
|
||||
expect(response.length).toBeGreaterThan(0);
|
||||
expect(response[0].ticketFk).toEqual(2);
|
||||
});
|
||||
});
|
|
@ -18,6 +18,14 @@ describe('setSaleQuantity()', () => {
|
|||
|
||||
it('should change quantity sale', async() => {
|
||||
const tx = await models.Ticket.beginTransaction({});
|
||||
spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => {
|
||||
if (sqlStatement.includes('catalog_calcFromItem')) {
|
||||
sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY
|
||||
SELECT 100 as available;`;
|
||||
params = null;
|
||||
}
|
||||
return models.Ticket.rawSql(sqlStatement, params, options);
|
||||
});
|
||||
|
||||
try {
|
||||
const options = {transaction: tx};
|
||||
|
|
|
@ -29,7 +29,8 @@ module.exports = Self => {
|
|||
http: {
|
||||
path: `/:id/downloadFile`,
|
||||
verb: 'GET'
|
||||
}
|
||||
},
|
||||
// accessScopes: ['read:multimedia']
|
||||
});
|
||||
|
||||
Self.downloadFile = async function(ctx, id) {
|
||||
|
|
|
@ -22,8 +22,8 @@ module.exports = Self => {
|
|||
|
||||
Self.removeFile = async(ctx, id, options) => {
|
||||
const models = Self.app.models;
|
||||
let tx;
|
||||
const myOptions = {};
|
||||
let tx;
|
||||
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
|
|
@ -49,7 +49,6 @@ module.exports = Self => {
|
|||
Self.uploadFile = async(ctx, options) => {
|
||||
const models = Self.app.models;
|
||||
const TempContainer = models.TempContainer;
|
||||
const DmsContainer = models.DmsContainer;
|
||||
const fileOptions = {};
|
||||
const args = ctx.args;
|
||||
|
||||
|
@ -79,19 +78,21 @@ module.exports = Self => {
|
|||
|
||||
const addedDms = [];
|
||||
for (const uploadedFile of files) {
|
||||
const newDms = await createDms(ctx, uploadedFile, myOptions);
|
||||
const pathHash = DmsContainer.getHash(newDms.id);
|
||||
|
||||
const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name);
|
||||
srcFile = path.join(file.client.root, file.container, file.name);
|
||||
|
||||
const dmsContainer = await DmsContainer.container(pathHash);
|
||||
const dstFile = path.join(dmsContainer.client.root, pathHash, newDms.file);
|
||||
|
||||
await fs.move(srcFile, dstFile, {
|
||||
overwrite: true
|
||||
});
|
||||
|
||||
const data = {
|
||||
workerFk: ctx.req.accessToken.userId,
|
||||
dmsTypeFk: args.dmsTypeId,
|
||||
companyFk: args.companyId,
|
||||
warehouseFk: args.warehouseId,
|
||||
reference: args.reference,
|
||||
description: args.description,
|
||||
contentType: uploadedFile.type,
|
||||
hasFile: args.hasFile
|
||||
};
|
||||
const extension = await models.DmsContainer.getFileExtension(uploadedFile.name);
|
||||
const newDms = await Self.createFromFile(data, extension, srcFile, myOptions);
|
||||
addedDms.push(newDms);
|
||||
}
|
||||
|
||||
|
@ -107,27 +108,4 @@ module.exports = Self => {
|
|||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
async function createDms(ctx, file, myOptions) {
|
||||
const models = Self.app.models;
|
||||
const myUserId = ctx.req.accessToken.userId;
|
||||
const args = ctx.args;
|
||||
|
||||
const newDms = await Self.create({
|
||||
workerFk: myUserId,
|
||||
dmsTypeFk: args.dmsTypeId,
|
||||
companyFk: args.companyId,
|
||||
warehouseFk: args.warehouseId,
|
||||
reference: args.reference,
|
||||
description: args.description,
|
||||
contentType: file.type,
|
||||
hasFile: args.hasFile
|
||||
}, myOptions);
|
||||
|
||||
let fileName = file.name;
|
||||
const extension = models.DmsContainer.getFileExtension(fileName);
|
||||
fileName = `${newDms.id}.${extension}`;
|
||||
|
||||
return newDms.updateAttribute('file', fileName, myOptions);
|
||||
}
|
||||
};
|
||||
|
|
|
@ -42,7 +42,8 @@ module.exports = Self => {
|
|||
http: {
|
||||
path: `/:id/download`,
|
||||
verb: 'GET'
|
||||
}
|
||||
},
|
||||
// accessScopes: ['read:multimedia']
|
||||
});
|
||||
|
||||
Self.download = async function(id, fileCabinet, filter) {
|
||||
|
|
|
@ -24,15 +24,40 @@ describe('docuware upload()', () => {
|
|||
});
|
||||
|
||||
it('should try upload file', async() => {
|
||||
const tx = await models.Docuware.beginTransaction({});
|
||||
spyOn(ticketModel, 'deliveryNotePdf').and.returnValue(new Promise(resolve => resolve({})));
|
||||
|
||||
let error;
|
||||
try {
|
||||
await models.Docuware.upload(ctx, ticketIds, fileCabinetName);
|
||||
const options = {transaction: tx};
|
||||
const user = await models.UserConfig.findById(userId, null, options);
|
||||
await user.updateAttribute('tabletFk', 'Tablet1', options);
|
||||
await models.Docuware.upload(ctx, ticketIds, fileCabinetName, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
error = e.message;
|
||||
error = e;
|
||||
await tx.rollback();
|
||||
}
|
||||
|
||||
expect(error).toEqual('Action not allowed on the test environment');
|
||||
expect(error.message).toEqual('Action not allowed on the test environment');
|
||||
});
|
||||
|
||||
it('should throw error when not have tablet assigned', async() => {
|
||||
const tx = await models.Docuware.beginTransaction({});
|
||||
spyOn(ticketModel, 'deliveryNotePdf').and.returnValue(new Promise(resolve => resolve({})));
|
||||
|
||||
let error;
|
||||
try {
|
||||
const options = {transaction: tx};
|
||||
await models.Docuware.upload(ctx, ticketIds, fileCabinetName, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
error = e;
|
||||
await tx.rollback();
|
||||
}
|
||||
|
||||
expect(error.message).toEqual('This user does not have an assigned tablet');
|
||||
});
|
||||
});
|
||||
|
|
|
@ -29,12 +29,24 @@ module.exports = Self => {
|
|||
}
|
||||
});
|
||||
|
||||
Self.upload = async function(ctx, ticketIds, fileCabinet) {
|
||||
Self.upload = async function(ctx, ticketIds, fileCabinet, options) {
|
||||
delete ctx.args.ticketIds;
|
||||
const models = Self.app.models;
|
||||
const action = 'store';
|
||||
|
||||
const options = await Self.getOptions();
|
||||
const myOptions = {};
|
||||
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
||||
const userConfig = await models.UserConfig.findById(ctx.req.accessToken.userId, {
|
||||
fields: ['tabletFk']
|
||||
}, myOptions);
|
||||
|
||||
if (!userConfig?.tabletFk)
|
||||
throw new UserError('This user does not have an assigned tablet');
|
||||
|
||||
const docuwareOptions = await Self.getOptions();
|
||||
const fileCabinetId = await Self.getFileCabinet(fileCabinet);
|
||||
const dialogId = await Self.getDialog(fileCabinet, action, fileCabinetId);
|
||||
|
||||
|
@ -45,7 +57,7 @@ module.exports = Self => {
|
|||
const deliveryNote = await models.Ticket.deliveryNotePdf(ctx, {
|
||||
id,
|
||||
type: 'deliveryNote'
|
||||
});
|
||||
}, myOptions);
|
||||
// get ticket data
|
||||
const ticket = await models.Ticket.findById(id, {
|
||||
include: [{
|
||||
|
@ -54,7 +66,7 @@ module.exports = Self => {
|
|||
fields: ['id', 'name', 'fi']
|
||||
}
|
||||
}]
|
||||
});
|
||||
}, myOptions);
|
||||
|
||||
// upload file
|
||||
const templateJson = {
|
||||
|
@ -102,7 +114,7 @@ module.exports = Self => {
|
|||
{
|
||||
'FieldName': 'FILTRO_TABLET',
|
||||
'ItemElementName': 'string',
|
||||
'Item': 'Tablet1',
|
||||
'Item': userConfig.tabletFk,
|
||||
}
|
||||
]
|
||||
};
|
||||
|
@ -116,11 +128,11 @@ module.exports = Self => {
|
|||
const deleteJson = {
|
||||
'Field': [{'FieldName': 'ESTADO', 'Item': 'Pendiente eliminar', 'ItemElementName': 'String'}]
|
||||
};
|
||||
const deleteUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents/${docuwareFile.id}/Fields`;
|
||||
await axios.put(deleteUri, deleteJson, options.headers);
|
||||
const deleteUri = `${docuwareOptions.url}/FileCabinets/${fileCabinetId}/Documents/${docuwareFile.id}/Fields`;
|
||||
await axios.put(deleteUri, deleteJson, docuwareOptions.headers);
|
||||
}
|
||||
|
||||
const uploadUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`;
|
||||
const uploadUri = `${docuwareOptions.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`;
|
||||
const FormData = require('form-data');
|
||||
const data = new FormData();
|
||||
|
||||
|
@ -130,7 +142,7 @@ module.exports = Self => {
|
|||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'X-File-ModifiedDate': Date.vnNew(),
|
||||
'Cookie': options.headers.headers.Cookie,
|
||||
'Cookie': docuwareOptions.headers.headers.Cookie,
|
||||
...data.getHeaders()
|
||||
},
|
||||
};
|
||||
|
@ -141,11 +153,11 @@ module.exports = Self => {
|
|||
const $t = ctx.req.__;
|
||||
const message = $t('Failed to upload delivery note', {id});
|
||||
if (uploaded.length)
|
||||
await models.TicketTracking.setDelivered(ctx, uploaded);
|
||||
await models.TicketTracking.setDelivered(ctx, uploaded, myOptions);
|
||||
throw new UserError(message);
|
||||
}
|
||||
uploaded.push(id);
|
||||
}
|
||||
return models.TicketTracking.setDelivered(ctx, ticketIds);
|
||||
return models.TicketTracking.setDelivered(ctx, ticketIds, myOptions);
|
||||
};
|
||||
};
|
||||
|
|
|
@ -47,7 +47,8 @@ module.exports = Self => {
|
|||
http: {
|
||||
path: `/:collection/:size/:id/download`,
|
||||
verb: 'GET'
|
||||
}
|
||||
},
|
||||
// accessScopes: ['read:multimedia']
|
||||
});
|
||||
|
||||
Self.download = async function(ctx, collection, size, id) {
|
||||
|
@ -87,6 +88,6 @@ module.exports = Self => {
|
|||
|
||||
await fs.access(file.path);
|
||||
const stream = fs.createReadStream(file.path);
|
||||
return [stream, file.contentType, `filename="${file.name}"`];
|
||||
return [stream, file.contentType, `filename="${fileName}"`];
|
||||
};
|
||||
};
|
||||
|
|
|
@ -4,20 +4,21 @@ describe('image download()', () => {
|
|||
const collection = 'user';
|
||||
const size = '160x160';
|
||||
const employeeId = 1;
|
||||
const developerId = 9;
|
||||
const jessicaJonesId = 1110;
|
||||
const ctx = {req: {accessToken: {userId: employeeId}}};
|
||||
|
||||
it('should return the image content-type of the user', async() => {
|
||||
const userId = 9;
|
||||
const image = await models.Image.download(ctx, collection, size, userId);
|
||||
const image = await models.Image.download(ctx, collection, size, developerId);
|
||||
const contentType = image[1];
|
||||
|
||||
expect(contentType).toEqual('image/png');
|
||||
});
|
||||
|
||||
it(`should return false if the user doesn't have image`, async() => {
|
||||
const userId = 1110;
|
||||
const image = await models.Image.download(ctx, collection, size, userId);
|
||||
it('should return the user profile picture', async() => {
|
||||
const image = await models.Image.download(ctx, collection, size, jessicaJonesId);
|
||||
const fileName = image[2];
|
||||
|
||||
expect(image).toBeFalse();
|
||||
expect(fileName).toMatch('1110.png');
|
||||
});
|
||||
});
|
||||
|
|
|
@ -95,10 +95,7 @@ describe('image upload()', () => {
|
|||
spyOn(containerModel, 'upload');
|
||||
|
||||
const ctx = {req: {accessToken: {userId: hhrrId}},
|
||||
args: {
|
||||
id: itemId,
|
||||
collection: 'user'
|
||||
}
|
||||
args: {id: itemId, collection: 'user'}
|
||||
};
|
||||
|
||||
try {
|
||||
|
@ -109,7 +106,7 @@ describe('image upload()', () => {
|
|||
});
|
||||
|
||||
it('should try to upload a file for the collection "catalog" and throw a privilege error', async() => {
|
||||
const ctx = {req: {accessToken: {userId: hhrrId}},
|
||||
const ctx = {req: {accessToken: {userId: 1}},
|
||||
args: {
|
||||
id: workerId,
|
||||
collection: 'catalog'
|
||||
|
|
|
@ -0,0 +1,132 @@
|
|||
const {models} = require('vn-loopback/server/server');
|
||||
|
||||
describe('machineWorker updateInTime()', () => {
|
||||
const itBoss = 104;
|
||||
const davidCharles = 1106;
|
||||
|
||||
beforeAll(async() => {
|
||||
ctx = {
|
||||
req: {
|
||||
accessToken: {},
|
||||
headers: {origin: 'http://localhost'},
|
||||
__: value => value
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
it('should throw an error if the plate does not exist', async() => {
|
||||
const tx = await models.MachineWorker.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
const plate = 'RE-123';
|
||||
ctx.req.accessToken.userId = 1106;
|
||||
try {
|
||||
await models.MachineWorker.updateInTime(ctx, plate, options);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
const error = e;
|
||||
|
||||
expect(error.message).toContain('the plate does not exist');
|
||||
await tx.rollback();
|
||||
}
|
||||
});
|
||||
|
||||
it('should grab a machine where is not in use', async() => {
|
||||
const tx = await models.MachineWorker.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
const plate = 'RE-003';
|
||||
ctx.req.accessToken.userId = 1107;
|
||||
try {
|
||||
const totalBefore = await models.MachineWorker.find(null, options);
|
||||
await models.MachineWorker.updateInTime(ctx, plate, options);
|
||||
const totalAfter = await models.MachineWorker.find(null, options);
|
||||
|
||||
expect(totalAfter.length).toEqual(totalBefore.length + 1);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
}
|
||||
});
|
||||
|
||||
describe('less than 12h', () => {
|
||||
const plate = 'RE-001';
|
||||
it('should trow an error if it is not himself', async() => {
|
||||
const tx = await models.MachineWorker.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
ctx.req.accessToken.userId = davidCharles;
|
||||
|
||||
try {
|
||||
await models.MachineWorker.updateInTime(ctx, plate, options);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
const error = e;
|
||||
|
||||
expect(error.message).toContain('This machine is already in use');
|
||||
await tx.rollback();
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw an error if it is himself with a different machine', async() => {
|
||||
const tx = await models.MachineWorker.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
ctx.req.accessToken.userId = itBoss;
|
||||
const plate = 'RE-003';
|
||||
try {
|
||||
await models.MachineWorker.updateInTime(ctx, plate, options);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
const error = e;
|
||||
|
||||
expect(error.message).toEqual('You are already using a machine');
|
||||
await tx.rollback();
|
||||
}
|
||||
});
|
||||
|
||||
it('should set the out time if it is himself', async() => {
|
||||
const tx = await models.MachineWorker.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
ctx.req.accessToken.userId = itBoss;
|
||||
|
||||
try {
|
||||
const isNotParked = await models.MachineWorker.findOne({
|
||||
where: {workerFk: itBoss}
|
||||
}, options);
|
||||
await models.MachineWorker.updateInTime(ctx, plate, options);
|
||||
const isParked = await models.MachineWorker.findOne({
|
||||
where: {workerFk: itBoss}
|
||||
}, options);
|
||||
|
||||
expect(isNotParked.outTime).toBeNull();
|
||||
expect(isParked.outTime).toBeDefined();
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('equal or more than 12h', () => {
|
||||
const plate = 'RE-002';
|
||||
it('should set the out time and grab the machine', async() => {
|
||||
const tx = await models.MachineWorker.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
ctx.req.accessToken.userId = davidCharles;
|
||||
const filter = {
|
||||
where: {workerFk: davidCharles, machineFk: 2}
|
||||
};
|
||||
try {
|
||||
const isNotParked = await models.MachineWorker.findOne(filter, options);
|
||||
const totalBefore = await models.MachineWorker.find(null, options);
|
||||
await models.MachineWorker.updateInTime(ctx, plate, options);
|
||||
const isParked = await models.MachineWorker.findOne(filter, options);
|
||||
const totalAfter = await models.MachineWorker.find(null, options);
|
||||
|
||||
expect(isNotParked.outTime).toBeNull();
|
||||
expect(isParked.outTime).toBeDefined();
|
||||
expect(totalAfter.length).toEqual(totalBefore.length + 1);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,77 @@
|
|||
const UserError = require('vn-loopback/util/user-error');
|
||||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('updateInTime', {
|
||||
description: 'Updates the corresponding registry if the worker has been registered in the last few hours',
|
||||
accessType: 'WRITE',
|
||||
accepts: [
|
||||
{
|
||||
arg: 'plate',
|
||||
type: 'string',
|
||||
}
|
||||
],
|
||||
http: {
|
||||
path: `/updateInTime`,
|
||||
verb: 'POST'
|
||||
}
|
||||
});
|
||||
|
||||
Self.updateInTime = async(ctx, plate, options) => {
|
||||
const models = Self.app.models;
|
||||
const userId = ctx.req.accessToken.userId;
|
||||
const $t = ctx.req.__;
|
||||
|
||||
let tx;
|
||||
const myOptions = {};
|
||||
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
||||
if (!myOptions.transaction) {
|
||||
tx = await Self.beginTransaction({});
|
||||
myOptions.transaction = tx;
|
||||
}
|
||||
|
||||
try {
|
||||
const machine = await models.Machine.findOne({
|
||||
fields: ['id', 'plate'],
|
||||
where: {plate}
|
||||
}, myOptions);
|
||||
|
||||
if (!machine)
|
||||
throw new UserError($t('the plate does not exist', {plate}));
|
||||
|
||||
const machineWorker = await Self.findOne({
|
||||
where: {
|
||||
or: [{machineFk: machine.id}, {workerFk: userId}],
|
||||
outTime: null,
|
||||
}
|
||||
}, myOptions);
|
||||
|
||||
const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions);
|
||||
const hoursDifference = (Date.vnNow() - machineWorker?.inTime?.getTime() ?? 0) / (60 * 60 * 1000);
|
||||
|
||||
if (machineWorker) {
|
||||
const isHimself = userId == machineWorker.workerFk;
|
||||
const isSameMachine = machine.id == machineWorker.machineFk;
|
||||
|
||||
if (hoursDifference < maxHours && !isHimself)
|
||||
throw new UserError($t('This machine is already in use.'));
|
||||
|
||||
if (hoursDifference < maxHours && isHimself && !isSameMachine)
|
||||
throw new UserError($t('You are already using a machine'));
|
||||
|
||||
await machineWorker.updateAttributes({
|
||||
outTime: Date.vnNew()
|
||||
}, myOptions);
|
||||
}
|
||||
|
||||
if (!machineWorker || hoursDifference >= maxHours)
|
||||
await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions);
|
||||
|
||||
if (tx) await tx.commit();
|
||||
} catch (e) {
|
||||
if (tx) await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
};
|
|
@ -0,0 +1,50 @@
|
|||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('getVersion', {
|
||||
description: 'gets app version data',
|
||||
accessType: 'READ',
|
||||
accepts: [{
|
||||
arg: 'app',
|
||||
type: 'string',
|
||||
required: true
|
||||
}],
|
||||
returns: {
|
||||
type: ['object'],
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/getVersion`,
|
||||
verb: 'GET'
|
||||
}
|
||||
});
|
||||
|
||||
Self.getVersion = async(ctx, app) => {
|
||||
const {models} = Self.app;
|
||||
const userId = ctx.req.accessToken.userId;
|
||||
|
||||
const workerFk = await models.WorkerAppTester.findOne({
|
||||
where: {
|
||||
workerFk: userId
|
||||
}
|
||||
});
|
||||
let fields = ['id', 'appName'];
|
||||
|
||||
if (workerFk)
|
||||
fields = fields.concat(['isVersionBetaCritical', 'versionBeta', 'urlBeta']);
|
||||
else
|
||||
fields = fields.concat(['isVersionCritical', 'version', 'urlProduction']);
|
||||
|
||||
const filter = {
|
||||
where: {
|
||||
appName: app
|
||||
},
|
||||
fields,
|
||||
};
|
||||
|
||||
const result = await Self.findOne(filter);
|
||||
return {
|
||||
isVersionCritical: result?.isVersionBetaCritical ?? result?.isVersionCritical,
|
||||
version: result?.versionBeta ?? result?.version,
|
||||
url: result?.urlBeta ?? result?.urlProduction
|
||||
};
|
||||
};
|
||||
};
|
|
@ -0,0 +1,29 @@
|
|||
const {models} = require('vn-loopback/server/server');
|
||||
|
||||
describe('mobileAppVersionControl getVersion()', () => {
|
||||
const appName = 'delivery';
|
||||
const appNameVersion = '9.2';
|
||||
const appNameVersionBeta = '9.7';
|
||||
beforeAll(async() => {
|
||||
ctx = {
|
||||
req: {
|
||||
accessToken: {},
|
||||
headers: {origin: 'http://localhost'},
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
it('should get the version app', async() => {
|
||||
ctx.req.accessToken.userId = 9;
|
||||
const {version} = await models.MobileAppVersionControl.getVersion(ctx, appName);
|
||||
|
||||
expect(version).toEqual(appNameVersion);
|
||||
});
|
||||
|
||||
it('should get the beta version app', async() => {
|
||||
ctx.req.accessToken.userId = 66;
|
||||
const {version} = await models.MobileAppVersionControl.getVersion(ctx, appName);
|
||||
|
||||
expect(version).toEqual(appNameVersionBeta);
|
||||
});
|
||||
});
|
|
@ -0,0 +1,20 @@
|
|||
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:mrw="http://www.mrw.es/">
|
||||
<soap:Header>
|
||||
<mrw:AuthInfo>
|
||||
<mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia>
|
||||
<mrw:CodigoAbonado><%= mrw.subscriberCode %></mrw:CodigoAbonado>
|
||||
<mrw:CodigoDepartamento/>
|
||||
<mrw:UserName><%= mrw.user %></mrw:UserName>
|
||||
<mrw:Password><%= mrw.password %></mrw:Password>
|
||||
</mrw:AuthInfo>
|
||||
</soap:Header>
|
||||
<soap:Body>
|
||||
<mrw:CancelarEnvio>
|
||||
<mrw:request>
|
||||
<mrw:CancelaEnvio>
|
||||
<mrw:NumeroEnvioOriginal><%= externalId %></mrw:NumeroEnvioOriginal>
|
||||
</mrw:CancelaEnvio>
|
||||
</mrw:request>
|
||||
</mrw:CancelarEnvio>
|
||||
</soap:Body>
|
||||
</soap:Envelope>
|
|
@ -0,0 +1,46 @@
|
|||
const axios = require('axios');
|
||||
const fs = require('fs');
|
||||
const ejs = require('ejs');
|
||||
const {DOMParser} = require('xmldom');
|
||||
|
||||
module.exports = Self => {
|
||||
Self.remoteMethod('cancelShipment', {
|
||||
description: 'Cancel a shipment by providing the expedition ID, interacting with MRW WebService',
|
||||
accessType: 'WRITE',
|
||||
accepts: [{
|
||||
arg: 'expeditionFk',
|
||||
type: 'number',
|
||||
required: true
|
||||
}],
|
||||
returns: {
|
||||
type: ['object'],
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/cancelShipment`,
|
||||
verb: 'POST'
|
||||
}
|
||||
});
|
||||
|
||||
Self.cancelShipment = async expeditionFk => {
|
||||
const models = Self.app.models;
|
||||
|
||||
const mrw = await models.MrwConfig.findOne();
|
||||
const {externalId} = await models.Expedition.findById(expeditionFk);
|
||||
|
||||
const template = fs.readFileSync(__dirname + '/cancelShipment.ejs', 'utf-8');
|
||||
const renderedXml = ejs.render(template, {mrw, externalId});
|
||||
const response = await axios.post(mrw.url, renderedXml, {
|
||||
headers: {
|
||||
'Content-Type': 'application/soap+xml; charset=utf-8'
|
||||
}
|
||||
});
|
||||
|
||||
const xmlString = response.data;
|
||||
const parser = new DOMParser();
|
||||
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
|
||||
const [resultElement] = xmlDoc.getElementsByTagName('Mensaje');
|
||||
|
||||
return resultElement.textContent;
|
||||
};
|
||||
};
|
|
@ -0,0 +1,43 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:mrw="http://www.mrw.es/">
|
||||
<soap:Header>
|
||||
<mrw:AuthInfo>
|
||||
<mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia>
|
||||
<mrw:CodigoAbonado><%= mrw.subscriberCode %></mrw:CodigoAbonado>
|
||||
<mrw:CodigoDepartamento/>
|
||||
<mrw:UserName><%= mrw.user %></mrw:UserName>
|
||||
<mrw:Password><%= mrw.password %></mrw:Password>
|
||||
</mrw:AuthInfo>
|
||||
</soap:Header>
|
||||
<soap:Body>
|
||||
<mrw:TransmEnvio>
|
||||
<mrw:request>
|
||||
<mrw:DatosEntrega>
|
||||
<mrw:Direccion>
|
||||
<mrw:CodigoTipoVia/>
|
||||
<mrw:Via><%= expeditionData.street %></mrw:Via>
|
||||
<mrw:Numero/>
|
||||
<mrw:Resto/>
|
||||
<mrw:CodigoPostal><%= expeditionData.postalCode %></mrw:CodigoPostal>
|
||||
<mrw:Poblacion><%= expeditionData.city %></mrw:Poblacion>
|
||||
<mrw:Provincia/>
|
||||
<mrw:CodigoPais/>
|
||||
</mrw:Direccion>
|
||||
<mrw:Nif><%= expeditionData.fi %></mrw:Nif>
|
||||
<mrw:Nombre><%= expeditionData.clientName %></mrw:Nombre>
|
||||
<mrw:Telefono><%= expeditionData.phone %></mrw:Telefono>
|
||||
</mrw:DatosEntrega>
|
||||
<mrw:DatosServicio>
|
||||
<mrw:Fecha><%= expeditionData.created %></mrw:Fecha>
|
||||
<mrw:Referencia><%= expeditionData.expeditionDataId %></mrw:Referencia>
|
||||
<mrw:CodigoServicio><%= expeditionData.serviceType %></mrw:CodigoServicio>
|
||||
<mrw:NumeroBultos>1</mrw:NumeroBultos>
|
||||
<mrw:EntregaSabado><%= expeditionData.weekDays %></mrw:EntregaSabado>
|
||||
<mrw:Peso><%= expeditionData.kg %></mrw:Peso>
|
||||
<mrw:Reembolso/>
|
||||
<mrw:ImporteReembolso/>
|
||||
</mrw:DatosServicio>
|
||||
</mrw:request>
|
||||
</mrw:TransmEnvio>
|
||||
</soap:Body>
|
||||
</soap:Envelope>
|
|
@ -0,0 +1,118 @@
|
|||
const axios = require('axios');
|
||||
const {DOMParser} = require('xmldom');
|
||||
const fs = require('fs');
|
||||
const ejs = require('ejs');
|
||||
const UserError = require('vn-loopback/util/user-error');
|
||||
|
||||
module.exports = Self => {
|
||||
Self.remoteMethod('createShipment', {
|
||||
description: 'Create an expedition and return a base64Binary label from de MRW WebService',
|
||||
accessType: 'WRITE',
|
||||
accepts: [{
|
||||
arg: 'expeditionFk',
|
||||
type: 'number',
|
||||
required: true
|
||||
}],
|
||||
returns: {
|
||||
type: ['object'],
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/createShipment`,
|
||||
verb: 'POST'
|
||||
}
|
||||
});
|
||||
|
||||
Self.createShipment = async(expeditionFk, options) => {
|
||||
const myOptions = {};
|
||||
let tx;
|
||||
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
||||
if (!myOptions.transaction) {
|
||||
tx = await Self.beginTransaction({});
|
||||
myOptions.transaction = tx;
|
||||
}
|
||||
|
||||
const models = Self.app.models;
|
||||
const mrw = await models.MrwConfig.findOne(null, myOptions);
|
||||
|
||||
if (!mrw)
|
||||
throw new UserError(`Some mrwConfig parameters are not set`);
|
||||
|
||||
const query =
|
||||
`SELECT CASE co.code
|
||||
WHEN 'ES' THEN a.postalCode
|
||||
WHEN 'PT' THEN LEFT(a.postalCode, 4)
|
||||
WHEN 'AD' THEN REPLACE(a.postalCode, 'AD', '00')
|
||||
END postalCode,
|
||||
a.city,
|
||||
a.street,
|
||||
co.code countryCode,
|
||||
c.fi,
|
||||
c.name clientName,
|
||||
c.phone,
|
||||
DATE_FORMAT(t.shipped, '%d/%m/%Y') created,
|
||||
t.shipped,
|
||||
e.id expeditionId,
|
||||
LPAD(IF(mw.params IS NULL, ms.serviceType, mw.serviceType), 4 ,'0') serviceType,
|
||||
IF(mw.weekdays, 'S', 'N') weekDays
|
||||
FROM expedition e
|
||||
JOIN ticket t ON e.ticketFk = t.id
|
||||
JOIN agencyMode am ON am.id = t.agencyModeFk
|
||||
JOIN mrwService ms ON ms.agencyModeCodeFk = am.code
|
||||
LEFT JOIN mrwServiceWeekday mw ON mw.weekdays = DATE_FORMAT(t.shipped, '%a')
|
||||
JOIN client c ON t.clientFk = c.id
|
||||
JOIN address a ON t.addressFk = a.id
|
||||
JOIN province p ON a.provinceFk = p.id
|
||||
JOIN country co ON co.id = p.countryFk
|
||||
WHERE e.id = ?
|
||||
LIMIT 1`;
|
||||
|
||||
const [expeditionData] = await Self.rawSql(query, [expeditionFk], myOptions);
|
||||
|
||||
if (!expeditionData)
|
||||
throw new UserError(`This expedition is not a MRW shipment`);
|
||||
|
||||
const today = Date.vnNew();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today)
|
||||
throw new UserError(`This ticket has a shipped date earlier than today`);
|
||||
|
||||
const shipmentResponse = await sendXmlDoc('createShipment', {mrw, expeditionData}, 'application/soap+xml');
|
||||
const shipmentId = getTextByTag(shipmentResponse, 'NumeroEnvio');
|
||||
|
||||
if (!shipmentId)
|
||||
throw new UserError(getTextByTag(shipmentResponse, 'Mensaje'));
|
||||
|
||||
const getLabelResponse = await sendXmlDoc('getLabel', {mrw, shipmentId}, 'text/xml');
|
||||
const file = getTextByTag(getLabelResponse, 'EtiquetaFile');
|
||||
|
||||
try {
|
||||
await models.Expedition.updateAll({id: expeditionFk}, {externalId: shipmentId}, myOptions);
|
||||
if (tx) await tx.commit();
|
||||
} catch (error) {
|
||||
if (tx) await tx.rollback();
|
||||
throw error;
|
||||
}
|
||||
return file;
|
||||
};
|
||||
|
||||
function getTextByTag(xmlDoc, tag) {
|
||||
return xmlDoc?.getElementsByTagName(tag)[0]?.textContent;
|
||||
}
|
||||
|
||||
async function sendXmlDoc(xmlDock, params, contentType) {
|
||||
const parser = new DOMParser();
|
||||
|
||||
const xmlTemplate = fs.readFileSync(__dirname + `/${xmlDock}.ejs`, 'utf-8');
|
||||
const renderedTemplate = ejs.render(xmlTemplate, params);
|
||||
const data = await axios.post(params.mrw.url, renderedTemplate, {
|
||||
headers: {
|
||||
'Content-Type': `${contentType}; charset=utf-8`
|
||||
}
|
||||
});
|
||||
return parser.parseFromString(data.data, 'text/xml');
|
||||
}
|
||||
};
|
|
@ -0,0 +1,25 @@
|
|||
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mrw="http://www.mrw.es/">
|
||||
<soapenv:Header>
|
||||
<mrw:AuthInfo>
|
||||
<mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia>
|
||||
<mrw:CodigoAbonado><%= mrw.subscriberCode %></mrw:CodigoAbonado>
|
||||
<mrw:CodigoDepartamento/>
|
||||
<mrw:UserName><%= mrw.user %></mrw:UserName>
|
||||
<mrw:Password><%= mrw.password %></mrw:Password>
|
||||
</mrw:AuthInfo>
|
||||
</soapenv:Header>
|
||||
<soapenv:Body>
|
||||
<mrw:GetEtiquetaEnvio>
|
||||
<mrw:request>
|
||||
<mrw:NumeroEnvio><%= shipmentId %></mrw:NumeroEnvio>
|
||||
<mrw:NumerosEtiqueta>1</mrw:NumerosEtiqueta>
|
||||
<mrw:SeparadorNumerosEnvio></mrw:SeparadorNumerosEnvio>
|
||||
<mrw:FechaInicioEnvio></mrw:FechaInicioEnvio>
|
||||
<mrw:FechaFinEnvio></mrw:FechaFinEnvio>
|
||||
<mrw:TipoEtiquetaEnvio>0</mrw:TipoEtiquetaEnvio>
|
||||
<mrw:ReportTopMargin>0</mrw:ReportTopMargin>
|
||||
<mrw:ReportLeftMargin>0</mrw:ReportLeftMargin>
|
||||
</mrw:request>
|
||||
</mrw:GetEtiquetaEnvio>
|
||||
</soapenv:Body>
|
||||
</soapenv:Envelope>
|
|
@ -0,0 +1,121 @@
|
|||
const models = require('vn-loopback/server/server').models;
|
||||
const axios = require('axios');
|
||||
const fs = require('fs');
|
||||
|
||||
const mockBase64Binary = 'base64BinaryString';
|
||||
const ticket1 = {
|
||||
'id': '44',
|
||||
'clientFk': 1101,
|
||||
'shipped': Date.vnNew(),
|
||||
'nickname': 'MRW',
|
||||
'addressFk': 1,
|
||||
'agencyModeFk': 999
|
||||
};
|
||||
|
||||
const expedition1 = {
|
||||
'id': 17,
|
||||
'agencyModeFk': 999,
|
||||
'ticketFk': 44,
|
||||
'freightItemFk': 71,
|
||||
'created': '2001-01-01',
|
||||
'counter': 1,
|
||||
'workerFk': 18,
|
||||
'packagingFk': '94',
|
||||
'hostFk': '',
|
||||
'stateTypeFk': 3,
|
||||
'hasNewRoute': 0,
|
||||
'isBox': 71,
|
||||
'editorFk': 100
|
||||
};
|
||||
|
||||
let tx;
|
||||
let options;
|
||||
|
||||
describe('MRWConfig createShipment()', () => {
|
||||
beforeEach(async() => {
|
||||
options = tx = undefined;
|
||||
tx = await models.MrwConfig.beginTransaction({});
|
||||
options = {transaction: tx};
|
||||
|
||||
await models.Agency.create(
|
||||
{'id': 999, 'name': 'mrw'},
|
||||
options
|
||||
);
|
||||
|
||||
await models.AgencyMode.create(
|
||||
{'id': 999, 'name': 'mrw', 'agencyFk': 999, 'code': 'mrw'},
|
||||
options
|
||||
);
|
||||
|
||||
await models.MrwConfig.create(
|
||||
{
|
||||
'id': 1,
|
||||
'url': 'https://url.com',
|
||||
'user': 'user',
|
||||
'password': 'password',
|
||||
'franchiseCode': 'franchiseCode',
|
||||
'subscriberCode': 'subscriberCode'
|
||||
}, options
|
||||
);
|
||||
|
||||
await models.Application.rawSql(
|
||||
`INSERT INTO vn.mrwService
|
||||
SET agencyModeCodeFk = 'mrw',
|
||||
clientType = 1,
|
||||
serviceType = 1,
|
||||
kg = 1`, null, options
|
||||
);
|
||||
await models.Ticket.create(ticket1, options);
|
||||
await models.Expedition.create(expedition1, options);
|
||||
});
|
||||
|
||||
afterEach(async() => {
|
||||
await tx.rollback();
|
||||
});
|
||||
|
||||
it('should create a shipment and return a base64Binary label', async() => {
|
||||
const mockPostResponses = [
|
||||
{data: fs.readFileSync(__dirname + '/mockGetLabel.xml', 'utf-8')},
|
||||
{data: fs.readFileSync(__dirname + '/mockCreateShipment.xml', 'utf-8')}
|
||||
];
|
||||
|
||||
spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop()));
|
||||
|
||||
const base64Binary = await models.MrwConfig.createShipment(expedition1.id, options);
|
||||
|
||||
expect(base64Binary).toEqual(mockBase64Binary);
|
||||
});
|
||||
|
||||
it('should fail if mrwConfig has no data', async() => {
|
||||
let error;
|
||||
await models.MrwConfig.createShipment(expedition1.id).catch(e => {
|
||||
error = e;
|
||||
}).finally(async() => {
|
||||
expect(error.message).toEqual(`Some mrwConfig parameters are not set`);
|
||||
});
|
||||
|
||||
expect(error).toBeDefined();
|
||||
});
|
||||
|
||||
it('should fail if expeditionFk is not a MrwExpedition', async() => {
|
||||
let error;
|
||||
await models.MrwConfig.createShipment(undefined, options).catch(e => {
|
||||
error = e;
|
||||
}).finally(async() => {
|
||||
expect(error.message).toEqual(`This expedition is not a MRW shipment`);
|
||||
});
|
||||
});
|
||||
|
||||
it(' should fail if the creation date of this ticket is before the current date it', async() => {
|
||||
let error;
|
||||
const yesterday = Date.vnNew();
|
||||
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
await models.Ticket.updateAll({id: ticket1.id}, {shipped: yesterday}, options);
|
||||
await models.MrwConfig.createShipment(expedition1.id, options).catch(e => {
|
||||
error = e;
|
||||
}).finally(async() => {
|
||||
expect(error.message).toEqual(`This ticket has a shipped date earlier than today`);
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,16 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
|
||||
<soap:Body>
|
||||
<TransmEnvioResponse xmlns="http://www.mrw.es/">
|
||||
<TransmEnvioResult>
|
||||
<Estado>1</Estado>
|
||||
<Mensaje />
|
||||
<NumeroSolicitud>1</NumeroSolicitud>
|
||||
<NumeroEnvio>1</NumeroEnvio>
|
||||
<Url>http://url.com</Url>
|
||||
</TransmEnvioResult>
|
||||
</TransmEnvioResponse>
|
||||
</soap:Body>
|
||||
</soap:Envelope>
|
|
@ -0,0 +1,14 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
|
||||
<soap:Body>
|
||||
<GetEtiquetaEnvioResponse xmlns="http://www.mrw.es/">
|
||||
<GetEtiquetaEnvioResult>
|
||||
<Estado>1</Estado>
|
||||
<Mensaje />
|
||||
<EtiquetaFile>base64BinaryString</EtiquetaFile>
|
||||
</GetEtiquetaEnvioResult>
|
||||
</GetEtiquetaEnvioResponse>
|
||||
</soap:Body>
|
||||
</soap:Envelope>
|
|
@ -0,0 +1,54 @@
|
|||
module.exports = Self => {
|
||||
Self.remoteMethod('getList', {
|
||||
description: 'Get list of the available and active notification subscriptions',
|
||||
accessType: 'READ',
|
||||
accepts: [
|
||||
{
|
||||
arg: 'id',
|
||||
type: 'number',
|
||||
description: 'User to modify',
|
||||
http: {source: 'path'}
|
||||
}
|
||||
],
|
||||
returns: {
|
||||
type: 'object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/:id/getList`,
|
||||
verb: 'GET'
|
||||
}
|
||||
});
|
||||
|
||||
Self.getList = async(id, options) => {
|
||||
const activeNotificationsMap = new Map();
|
||||
|
||||
const myOptions = {};
|
||||
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
||||
const availableNotificationsMap = await Self.getAvailable(id, myOptions);
|
||||
const activeNotifications = await Self.app.models.NotificationSubscription.find({
|
||||
fields: ['id', 'notificationFk'],
|
||||
include: {relation: 'notification'},
|
||||
where: {userFk: id}
|
||||
}, myOptions);
|
||||
|
||||
for (active of activeNotifications) {
|
||||
activeNotificationsMap.set(active.notificationFk, {
|
||||
id: active.id,
|
||||
notificationFk: active.notificationFk,
|
||||
name: active.notification().name,
|
||||
description: active.notification().description,
|
||||
active: true
|
||||
});
|
||||
availableNotificationsMap.delete(active.notificationFk);
|
||||
}
|
||||
|
||||
return {
|
||||
active: [...activeNotificationsMap.entries()],
|
||||
available: [...availableNotificationsMap.entries()]
|
||||
};
|
||||
};
|
||||
};
|
|
@ -0,0 +1,13 @@
|
|||
const models = require('vn-loopback/server/server').models;
|
||||
|
||||
describe('NotificationSubscription getList()', () => {
|
||||
it('should return a list of available and active notifications of a user', async() => {
|
||||
const userId = 9;
|
||||
const {active, available} = await models.NotificationSubscription.getList(userId);
|
||||
const notifications = await models.Notification.find({});
|
||||
const totalAvailable = notifications.length - active.length;
|
||||
|
||||
expect(active.length).toEqual(3);
|
||||
expect(available.length).toEqual(totalAvailable);
|
||||
});
|
||||
});
|
|
@ -35,11 +35,18 @@ module.exports = Self => {
|
|||
let html = `<strong>Motivo</strong>:<br/>${reason}<br/>`;
|
||||
html += `<strong>Usuario</strong>:<br/>${ctx.req.accessToken.userId} ${emailUser.email}<br/>`;
|
||||
|
||||
delete additionalData.backError.config.headers.Authorization;
|
||||
const httpRequest = JSON.parse(additionalData?.httpRequest);
|
||||
|
||||
if (httpRequest)
|
||||
delete httpRequest.config.headers.Authorization;
|
||||
additionalData.httpRequest = httpRequest;
|
||||
|
||||
for (const data in additionalData)
|
||||
html += `<strong>${data}</strong>:<br/>${tryParse(additionalData[data])}<br/>`;
|
||||
|
||||
const subjectReason = JSON.parse(additionalData?.httpRequest)?.data?.error;
|
||||
smtp.send({
|
||||
const subjectReason = httpRequest?.data?.error;
|
||||
await smtp.send({
|
||||
to: `${config.app.reportEmail}, ${emailUser.email}`,
|
||||
subject:
|
||||
'[Support-Salix] ' +
|
||||
|
|
|
@ -0,0 +1,80 @@
|
|||
const {ParameterizedSQL} = require('loopback-connector');
|
||||
const {buildFilter} = require('vn-loopback/util/filter');
|
||||
|
||||
module.exports = Self => {
|
||||
Self.remoteMethod('filter', {
|
||||
description:
|
||||
'Find all postcodes of the model matched by postcode, town, province or country.',
|
||||
accessType: 'READ',
|
||||
accepts: [
|
||||
{
|
||||
arg: 'filter',
|
||||
type: 'object',
|
||||
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string',
|
||||
http: {source: 'query'}
|
||||
},
|
||||
{
|
||||
arg: 'search',
|
||||
type: 'string',
|
||||
description: 'Value to filter',
|
||||
http: {source: 'query'}
|
||||
},
|
||||
],
|
||||
returns: {
|
||||
type: ['object'],
|
||||
root: true,
|
||||
},
|
||||
http: {
|
||||
path: `/filter`,
|
||||
verb: 'GET',
|
||||
},
|
||||
});
|
||||
Self.filter = async(ctx, filter, options) => {
|
||||
const myOptions = {};
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
||||
filter = ctx?.filter ?? {};
|
||||
|
||||
const conn = Self.dataSource.connector;
|
||||
const where = buildFilter(filter?.where, (param, value) => {
|
||||
switch (param) {
|
||||
case 'search':
|
||||
return {
|
||||
or: [
|
||||
{'pc.code': {like: `%${value}%`}},
|
||||
{'t.name': {like: `%${value}%`}},
|
||||
{'p.name': {like: `%${value}%`}},
|
||||
{'c.country': {like: `%${value}%`}}
|
||||
]
|
||||
};
|
||||
}
|
||||
}) ?? {};
|
||||
delete ctx.filter.where;
|
||||
|
||||
const stmts = [];
|
||||
let stmt;
|
||||
stmt = new ParameterizedSQL(`
|
||||
SELECT
|
||||
pc.townFk,
|
||||
t.provinceFk,
|
||||
p.countryFk,
|
||||
pc.code,
|
||||
t.name as town,
|
||||
p.name as province,
|
||||
c.country
|
||||
FROM
|
||||
postCode pc
|
||||
JOIN town t on t.id = pc.townFk
|
||||
JOIN province p on p.id = t.provinceFk
|
||||
JOIN country c on c.id = p.countryFk
|
||||
`);
|
||||
|
||||
stmt.merge(conn.makeSuffix({where, ...ctx}));
|
||||
const itemsIndex = stmts.push(stmt) - 1;
|
||||
|
||||
const sql = ParameterizedSQL.join(stmts, ';');
|
||||
const result = await conn.executeStmt(sql, myOptions);
|
||||
return itemsIndex === 0 ? result : result[itemsIndex];
|
||||
};
|
||||
};
|
|
@ -0,0 +1,111 @@
|
|||
const {models} = require('vn-loopback/server/server');
|
||||
|
||||
describe('Postcode filter()', () => {
|
||||
it('should retrieve with no filter', async() => {
|
||||
const tx = await models.Postcode.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
|
||||
try {
|
||||
const ctx = {
|
||||
filter: {
|
||||
},
|
||||
limit: 1
|
||||
};
|
||||
const results = await models.Postcode.filter(ctx, options);
|
||||
|
||||
expect(results.length).toEqual(1);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
it('should retrieve with filter as postcode', async() => {
|
||||
const tx = await models.Postcode.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
|
||||
try {
|
||||
const ctx = {
|
||||
filter: {
|
||||
where: {
|
||||
search: 46,
|
||||
}
|
||||
},
|
||||
};
|
||||
const results = await models.Postcode.filter(ctx, options);
|
||||
|
||||
expect(results.length).toEqual(4);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
it('should retrieve with filter as city', async() => {
|
||||
const tx = await models.Postcode.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
|
||||
try {
|
||||
const ctx = {
|
||||
filter: {
|
||||
where: {
|
||||
search: 'Alz',
|
||||
}
|
||||
},
|
||||
};
|
||||
const results = await models.Postcode.filter(ctx, options);
|
||||
|
||||
expect(results.length).toEqual(1);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
it('should retrieve with filter as province', async() => {
|
||||
const tx = await models.Postcode.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
|
||||
try {
|
||||
const ctx = {
|
||||
filter: {
|
||||
where: {
|
||||
search: 'one',
|
||||
}
|
||||
},
|
||||
};
|
||||
const results = await models.Postcode.filter(ctx, options);
|
||||
|
||||
expect(results.length).toEqual(4);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
it('should retrieve with filter as country', async() => {
|
||||
const tx = await models.Postcode.beginTransaction({});
|
||||
const options = {transaction: tx};
|
||||
|
||||
try {
|
||||
const ctx = {
|
||||
filter: {
|
||||
where: {
|
||||
search: 'Ec',
|
||||
}
|
||||
},
|
||||
};
|
||||
const results = await models.Postcode.filter(ctx, options);
|
||||
|
||||
expect(results.length).toEqual(1);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
});
|
|
@ -0,0 +1,40 @@
|
|||
module.exports = function(Self) {
|
||||
Self.remoteMethod('getByUser', {
|
||||
description: 'returns the starred modules for the current user',
|
||||
accessType: 'READ',
|
||||
accepts: [{
|
||||
arg: 'userId',
|
||||
type: 'number',
|
||||
description: 'The user id',
|
||||
required: true,
|
||||
http: {source: 'path'}
|
||||
}],
|
||||
returns: {
|
||||
type: 'object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/:userId/get-by-user`,
|
||||
verb: 'GET'
|
||||
}
|
||||
});
|
||||
|
||||
Self.getByUser = async userId => {
|
||||
const models = Self.app.models;
|
||||
const appNames = ['hedera'];
|
||||
const filter = {
|
||||
fields: ['appName', 'url'],
|
||||
where: {
|
||||
appName: {inq: appNames},
|
||||
environment: process.env.NODE_ENV ?? 'development',
|
||||
}
|
||||
};
|
||||
|
||||
const isWorker = await models.Account.findById(userId, {fields: ['id']});
|
||||
if (!isWorker)
|
||||
return models.Url.find(filter);
|
||||
|
||||
appNames.push('salix');
|
||||
return models.Url.find(filter);
|
||||
};
|
||||
};
|
|
@ -0,0 +1,30 @@
|
|||
module.exports = Self => {
|
||||
Self.remoteMethod('getUrl', {
|
||||
description: 'Returns the colling app name',
|
||||
accessType: 'READ',
|
||||
accepts: [
|
||||
{
|
||||
arg: 'app',
|
||||
type: 'string',
|
||||
required: false
|
||||
}
|
||||
],
|
||||
returns: {
|
||||
type: 'object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/getUrl`,
|
||||
verb: 'get'
|
||||
}
|
||||
});
|
||||
Self.getUrl = async(appName = 'salix') => {
|
||||
const {url} = await Self.app.models.Url.findOne({
|
||||
where: {
|
||||
appName,
|
||||
environment: process.env.NODE_ENV || 'development'
|
||||
}
|
||||
});
|
||||
return url;
|
||||
};
|
||||
};
|
|
@ -0,0 +1,19 @@
|
|||
const {models} = require('vn-loopback/server/server');
|
||||
|
||||
describe('getByUser()', () => {
|
||||
const worker = 1;
|
||||
const notWorker = 2;
|
||||
it(`should return only hedera url if not is worker`, async() => {
|
||||
const urls = await models.Url.getByUser(notWorker);
|
||||
|
||||
expect(urls.length).toEqual(1);
|
||||
expect(urls[0].appName).toEqual('hedera');
|
||||
});
|
||||
|
||||
it(`should return more than hedera url`, async() => {
|
||||
const urls = await models.Url.getByUser(worker);
|
||||
|
||||
expect(urls.length).toBeGreaterThan(1);
|
||||
expect(urls.find(url => url.appName == 'salix').appName).toEqual('salix');
|
||||
});
|
||||
});
|
|
@ -0,0 +1,11 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
|
||||
<soap12:Body>
|
||||
<DeleteEnvio xmlns="http://82.223.6.71:82">
|
||||
<IdCliente><%= viaexpressConfig.client %></IdCliente>
|
||||
<Usuario><%= viaexpressConfig.user %></Usuario>
|
||||
<Password><%= viaexpressConfig.password %></Password>
|
||||
<etiqueta><%= externalId %></etiqueta>
|
||||
</DeleteEnvio>
|
||||
</soap12:Body>
|
||||
</soap12:Envelope>
|
|
@ -0,0 +1,45 @@
|
|||
const axios = require('axios');
|
||||
const {DOMParser} = require('xmldom');
|
||||
|
||||
module.exports = Self => {
|
||||
Self.remoteMethod('deleteExpedition', {
|
||||
description: 'Delete a shipment by providing the expedition ID, interacting with Viaexpress API',
|
||||
accessType: 'WRITE',
|
||||
accepts: [{
|
||||
arg: 'expeditionFk',
|
||||
type: 'number',
|
||||
required: true
|
||||
}],
|
||||
returns: {
|
||||
type: ['object'],
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/deleteExpedition`,
|
||||
verb: 'POST'
|
||||
}
|
||||
});
|
||||
|
||||
Self.deleteExpedition = async expeditionFk => {
|
||||
const models = Self.app.models;
|
||||
|
||||
const viaexpressConfig = await models.ViaexpressConfig.findOne({
|
||||
fields: ['url']
|
||||
});
|
||||
|
||||
const renderedXml = await models.ViaexpressConfig.deleteExpeditionRenderer(expeditionFk);
|
||||
const response = await axios.post(`${viaexpressConfig.url}ServicioVxClientes.asmx`, renderedXml, {
|
||||
headers: {
|
||||
'Content-Type': 'application/soap+xml; charset=utf-8'
|
||||
}
|
||||
});
|
||||
|
||||
const xmlString = response.data;
|
||||
const parser = new DOMParser();
|
||||
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
|
||||
const resultElement = xmlDoc.getElementsByTagName('DeleteEnvioResult')[0];
|
||||
const result = resultElement.textContent;
|
||||
|
||||
return result;
|
||||
};
|
||||
};
|
|
@ -0,0 +1,44 @@
|
|||
const fs = require('fs');
|
||||
const ejs = require('ejs');
|
||||
|
||||
module.exports = Self => {
|
||||
Self.remoteMethod('deleteExpeditionRenderer', {
|
||||
description: 'Renders the data from an XML',
|
||||
accessType: 'READ',
|
||||
accepts: [{
|
||||
arg: 'expeditionFk',
|
||||
type: 'number',
|
||||
required: true
|
||||
}],
|
||||
returns: {
|
||||
type: ['object'],
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/deleteExpeditionRenderer`,
|
||||
verb: 'GET'
|
||||
}
|
||||
});
|
||||
|
||||
Self.deleteExpeditionRenderer = async expeditionFk => {
|
||||
const models = Self.app.models;
|
||||
|
||||
const viaexpressConfig = await models.ViaexpressConfig.findOne({
|
||||
fields: ['client', 'user', 'password']
|
||||
});
|
||||
|
||||
const expedition = await models.Expedition.findOne({
|
||||
fields: ['id', 'externalId'],
|
||||
where: {id: expeditionFk}
|
||||
});
|
||||
|
||||
const data = {
|
||||
viaexpressConfig,
|
||||
externalId: expedition.externalId
|
||||
};
|
||||
|
||||
const template = fs.readFileSync(__dirname + '/deleteExpedition.ejs', 'utf-8');
|
||||
const renderedXml = ejs.render(template, data);
|
||||
return renderedXml;
|
||||
};
|
||||
};
|
|
@ -20,7 +20,7 @@ module.exports = Self => {
|
|||
}
|
||||
});
|
||||
|
||||
Self.internationalExpedition = async expeditionFk => {
|
||||
Self.internationalExpedition = async (expeditionFk) => {
|
||||
const models = Self.app.models;
|
||||
|
||||
const viaexpressConfig = await models.ViaexpressConfig.findOne({
|
||||
|
|
|
@ -20,11 +20,11 @@ module.exports = Self => {
|
|||
}
|
||||
});
|
||||
|
||||
Self.renderer = async expeditionFk => {
|
||||
Self.renderer = async (expeditionFk) => {
|
||||
const models = Self.app.models;
|
||||
|
||||
const viaexpressConfig = await models.ViaexpressConfig.findOne({
|
||||
fields: ['client', 'user', 'password', 'defaultWeight', 'deliveryType']
|
||||
fields: ['client', 'user', 'password', 'defaultWeight', 'deliveryType', 'agencyModeFk']
|
||||
});
|
||||
|
||||
const expedition = await models.Expedition.findOne({
|
||||
|
@ -34,7 +34,7 @@ module.exports = Self => {
|
|||
{
|
||||
relation: 'ticket',
|
||||
scope: {
|
||||
fields: ['shipped', 'addressFk', 'clientFk', 'companyFk'],
|
||||
fields: ['shipped', 'addressFk', 'clientFk', 'companyFk', 'agencyModeFk'],
|
||||
include: [
|
||||
{
|
||||
relation: 'client',
|
||||
|
@ -102,7 +102,6 @@ module.exports = Self => {
|
|||
}
|
||||
]
|
||||
}
|
||||
|
||||
}
|
||||
]
|
||||
});
|
||||
|
@ -110,13 +109,15 @@ module.exports = Self => {
|
|||
const ticket = expedition.ticket();
|
||||
const sender = ticket.company().client();
|
||||
const shipped = ticket.shipped.toISOString();
|
||||
const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk)
|
||||
const data = {
|
||||
viaexpressConfig,
|
||||
sender,
|
||||
senderAddress: sender.defaultAddress(),
|
||||
client: ticket.client(),
|
||||
address: ticket.address(),
|
||||
shipped
|
||||
shipped,
|
||||
isInterdia
|
||||
};
|
||||
|
||||
const template = fs.readFileSync(__dirname + '/template.ejs', 'utf-8');
|
||||
|
|
|
@ -13,7 +13,7 @@
|
|||
<Asegurado>0</Asegurado>
|
||||
<Imprimir>0</Imprimir>
|
||||
<ConDevolucionAlbaran>0</ConDevolucionAlbaran>
|
||||
<Intradia>0</Intradia>
|
||||
<Intradia><%= isInterdia %></Intradia>
|
||||
<Observaciones></Observaciones>
|
||||
<AlbaranRemitente></AlbaranRemitente>
|
||||
<Modo>0</Modo>
|
||||
|
|
|
@ -68,7 +68,7 @@ module.exports = Self => {
|
|||
userToUpdate.hasGrant = hasGrant;
|
||||
|
||||
if (roleFk) {
|
||||
const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions);
|
||||
const role = await models.VnRole.findById(roleFk, {fields: ['name']}, myOptions);
|
||||
const hasRole = await Self.hasRole(userId, role.name, myOptions);
|
||||
|
||||
if (!hasRole)
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
const UserError = require('vn-loopback/util/user-error');
|
||||
const {models} = require('vn-loopback/server/server');
|
||||
|
||||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('renewToken', {
|
||||
|
@ -16,20 +16,31 @@ module.exports = Self => {
|
|||
});
|
||||
|
||||
Self.renewToken = async function(ctx) {
|
||||
const models = Self.app.models;
|
||||
const token = ctx.req.accessToken;
|
||||
const {accessToken: token} = ctx.req;
|
||||
|
||||
const now = new Date();
|
||||
// Check if current token is valid
|
||||
|
||||
const {renewPeriod, courtesyTime} = await models.AccessTokenConfig.findOne({
|
||||
fields: ['renewPeriod', 'courtesyTime']
|
||||
});
|
||||
const now = Date.now();
|
||||
const differenceMilliseconds = now - token.created;
|
||||
const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
|
||||
const isNotExceeded = differenceSeconds < renewPeriod - courtesyTime;
|
||||
if (isNotExceeded)
|
||||
return token;
|
||||
|
||||
const fields = ['renewPeriod', 'courtesyTime'];
|
||||
const accessTokenConfig = await models.AccessTokenConfig.findOne({fields});
|
||||
|
||||
if (differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime)
|
||||
throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded');
|
||||
|
||||
// Schedule to remove current token
|
||||
setTimeout(async() => {
|
||||
try {
|
||||
await Self.logout(token.id);
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(err);
|
||||
}
|
||||
}, courtesyTime * 1000);
|
||||
|
||||
// Create new accessToken
|
||||
const user = await Self.findById(token.userId);
|
||||
const accessToken = await user.createAccessToken();
|
||||
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
|
||||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('shareToken', {
|
||||
description: 'Returns token to view files or images and share it',
|
||||
accessType: 'WRITE',
|
||||
accepts: [],
|
||||
returns: {
|
||||
type: 'Object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/shareToken`,
|
||||
verb: 'GET'
|
||||
}
|
||||
});
|
||||
|
||||
Self.shareToken = async function(ctx) {
|
||||
const {accessToken: token} = ctx.req;
|
||||
|
||||
const user = await Self.findById(token.userId);
|
||||
const multimediaToken = await user.accessTokens.create({
|
||||
scopes: ['read:multimedia']
|
||||
});
|
||||
|
||||
return {multimediaToken};
|
||||
};
|
||||
};
|
|
@ -49,8 +49,7 @@ module.exports = Self => {
|
|||
if (vnUser.twoFactor)
|
||||
throw new ForbiddenError(null, 'REQUIRES_2FA');
|
||||
}
|
||||
|
||||
return Self.validateLogin(user, password);
|
||||
return Self.validateLogin(user, password, ctx);
|
||||
};
|
||||
|
||||
Self.passExpired = async vnUser => {
|
||||
|
|
|
@ -70,7 +70,7 @@ describe('VnUser privileges()', () => {
|
|||
const tx = await models.VnUser.beginTransaction({});
|
||||
|
||||
const options = {transaction: tx};
|
||||
const agency = await models.Role.findOne({
|
||||
const agency = await models.VnRole.findOne({
|
||||
where: {
|
||||
name: 'agency'
|
||||
}
|
||||
|
|
|
@ -0,0 +1,50 @@
|
|||
const {models} = require('vn-loopback/server/server');
|
||||
describe('Renew Token', () => {
|
||||
const startingTime = Date.now();
|
||||
let ctx = null;
|
||||
beforeAll(async() => {
|
||||
const unAuthCtx = {
|
||||
req: {
|
||||
headers: {},
|
||||
connection: {
|
||||
remoteAddress: '127.0.0.1'
|
||||
},
|
||||
getLocale: () => 'en'
|
||||
},
|
||||
args: {}
|
||||
};
|
||||
let login = await models.VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare');
|
||||
let accessToken = await models.AccessToken.findById(login.token);
|
||||
ctx = {req: {accessToken: accessToken}};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jasmine.clock().install();
|
||||
jasmine.clock().mockDate(new Date(startingTime));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jasmine.clock().uninstall();
|
||||
});
|
||||
|
||||
it('should renew token', async() => {
|
||||
const mockDate = new Date(startingTime + 26600000);
|
||||
jasmine.clock().mockDate(mockDate);
|
||||
const {id} = await models.VnUser.renewToken(ctx);
|
||||
|
||||
expect(id).not.toEqual(ctx.req.accessToken.id);
|
||||
});
|
||||
|
||||
it('NOT should renew', async() => {
|
||||
let error;
|
||||
let response;
|
||||
try {
|
||||
response = await models.VnUser.renewToken(ctx);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error).toBeUndefined();
|
||||
expect(response.id).toEqual(ctx.req.accessToken.id);
|
||||
});
|
||||
});
|
|
@ -0,0 +1,27 @@
|
|||
const {models} = require('vn-loopback/server/server');
|
||||
describe('Share Token', () => {
|
||||
let ctx = null;
|
||||
beforeAll(async() => {
|
||||
const unAuthCtx = {
|
||||
req: {
|
||||
headers: {},
|
||||
connection: {
|
||||
remoteAddress: '127.0.0.1'
|
||||
},
|
||||
getLocale: () => 'en'
|
||||
},
|
||||
args: {}
|
||||
};
|
||||
let login = await models.VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare');
|
||||
let accessToken = await models.AccessToken.findById(login.token);
|
||||
ctx = {req: {accessToken: accessToken}};
|
||||
});
|
||||
|
||||
it('should renew token', async() => {
|
||||
const multimediaToken = await models.VnUser.shareToken(ctx);
|
||||
|
||||
expect(Object.keys(multimediaToken).length).toEqual(1);
|
||||
expect(multimediaToken.multimediaToken.userId).toEqual(ctx.req.accessToken.userId);
|
||||
expect(multimediaToken.multimediaToken.scopes[0]).toEqual('read:multimedia');
|
||||
});
|
||||
});
|
|
@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server');
|
|||
|
||||
describe('VnUser Sign-in()', () => {
|
||||
const employeeId = 1;
|
||||
const unauthCtx = {
|
||||
const unAuthCtx = {
|
||||
req: {
|
||||
headers: {},
|
||||
connection: {
|
||||
|
@ -12,10 +12,21 @@ describe('VnUser Sign-in()', () => {
|
|||
},
|
||||
args: {}
|
||||
};
|
||||
const {VnUser, AccessToken} = models;
|
||||
const {VnUser, AccessToken, SignInLog} = models;
|
||||
describe('when credentials are correct', () => {
|
||||
it('should return the token if user uses email', async() => {
|
||||
let login = await VnUser.signIn(unAuthCtx, 'salesAssistant@mydomain.com', 'nightmare');
|
||||
let accessToken = await AccessToken.findById(login.token);
|
||||
let ctx = {req: {accessToken: accessToken}};
|
||||
let signInLog = await SignInLog.find({where: {token: accessToken.id}});
|
||||
|
||||
expect(signInLog.length).toEqual(0);
|
||||
|
||||
await VnUser.logout(ctx.req.accessToken.id);
|
||||
});
|
||||
|
||||
it('should return the token', async() => {
|
||||
let login = await VnUser.signIn(unauthCtx, 'salesAssistant', 'nightmare');
|
||||
let login = await VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare');
|
||||
let accessToken = await AccessToken.findById(login.token);
|
||||
let ctx = {req: {accessToken: accessToken}};
|
||||
|
||||
|
@ -25,7 +36,7 @@ describe('VnUser Sign-in()', () => {
|
|||
});
|
||||
|
||||
it('should return the token if the user doesnt exist but the client does', async() => {
|
||||
let login = await VnUser.signIn(unauthCtx, 'PetterParker', 'nightmare');
|
||||
let login = await VnUser.signIn(unAuthCtx, 'PetterParker', 'nightmare');
|
||||
let accessToken = await AccessToken.findById(login.token);
|
||||
let ctx = {req: {accessToken: accessToken}};
|
||||
|
||||
|
@ -40,7 +51,7 @@ describe('VnUser Sign-in()', () => {
|
|||
let error;
|
||||
|
||||
try {
|
||||
await VnUser.signIn(unauthCtx, 'IDontExist', 'TotallyWrongPassword');
|
||||
await VnUser.signIn(unAuthCtx, 'IDontExist', 'TotallyWrongPassword');
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
|
@ -61,7 +72,7 @@ describe('VnUser Sign-in()', () => {
|
|||
const options = {transaction: tx};
|
||||
await employee.updateAttribute('twoFactor', 'email', options);
|
||||
|
||||
await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options);
|
||||
await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
|
@ -86,7 +97,7 @@ describe('VnUser Sign-in()', () => {
|
|||
const options = {transaction: tx};
|
||||
await employee.updateAttribute('passExpired', yesterday, options);
|
||||
|
||||
await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options);
|
||||
await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options);
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
|
|
|
@ -0,0 +1,39 @@
|
|||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('updateUser', {
|
||||
description: 'Update user data',
|
||||
accepts: [
|
||||
{
|
||||
arg: 'id',
|
||||
type: 'integer',
|
||||
description: 'The user id',
|
||||
required: true,
|
||||
http: {source: 'path'}
|
||||
}, {
|
||||
arg: 'name',
|
||||
type: 'string',
|
||||
description: 'The user name',
|
||||
}, {
|
||||
arg: 'nickname',
|
||||
type: 'string',
|
||||
description: 'The user nickname',
|
||||
}, {
|
||||
arg: 'email',
|
||||
type: 'string',
|
||||
description: 'The user email'
|
||||
}, {
|
||||
arg: 'lang',
|
||||
type: 'string',
|
||||
description: 'The user lang'
|
||||
}
|
||||
],
|
||||
http: {
|
||||
path: `/:id/update-user`,
|
||||
verb: 'PATCH'
|
||||
}
|
||||
});
|
||||
|
||||
Self.updateUser = async(ctx, id, name, nickname, email, lang) => {
|
||||
await Self.userSecurity(ctx, id);
|
||||
await Self.upsertWithWhere({id}, {name, nickname, email, lang});
|
||||
};
|
||||
};
|
|
@ -1,17 +0,0 @@
|
|||
module.exports = Self => {
|
||||
Self.remoteMethod('validateToken', {
|
||||
description: 'Validates the current logged user token',
|
||||
returns: {
|
||||
type: 'Boolean',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/validateToken`,
|
||||
verb: 'GET'
|
||||
}
|
||||
});
|
||||
|
||||
Self.validateToken = async function() {
|
||||
return true;
|
||||
};
|
||||
};
|
|
@ -13,7 +13,7 @@
|
|||
"AuthCode": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"Bank": {
|
||||
"Accounting": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"Buyer": {
|
||||
|
@ -79,15 +79,24 @@
|
|||
"Language": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"Machine": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"MachineWorker": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"MachineWorkerConfig": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"MobileAppVersionControl": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"Module": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"MrwConfig": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"Notification": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
|
@ -139,9 +148,6 @@
|
|||
"Warehouse": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"VnUser": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"OsTicket": {
|
||||
"dataSource": "osticket"
|
||||
},
|
||||
|
@ -156,8 +162,17 @@
|
|||
},
|
||||
"ViaexpressConfig": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"VnUser": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"VnRole": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"WorkerActivity": {
|
||||
"dataSource": "vn"
|
||||
},
|
||||
"WorkerActivityType": {
|
||||
"dataSource": "vn"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
{
|
||||
"name": "Bank",
|
||||
"name": "Accounting",
|
||||
"base": "VnModel",
|
||||
"options": {
|
||||
"mysql": {
|
||||
"table": "bank"
|
||||
"table": "accounting"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
|
@ -22,10 +22,7 @@
|
|||
},
|
||||
"accountingTypeFk": {
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"mysql": {
|
||||
"columnName": "cash"
|
||||
}
|
||||
"required": true
|
||||
},
|
||||
"entityFk": {
|
||||
"type": "number",
|
|
@ -8,6 +8,26 @@ module.exports = Self => {
|
|||
});
|
||||
|
||||
Self.validatesUniquenessOf('bic', {
|
||||
message: 'This BIC already exist.'
|
||||
message: 'This BIC already exist'
|
||||
});
|
||||
|
||||
Self.validatesPresenceOf('countryFk', {
|
||||
message: 'CountryFK cannot be empty'
|
||||
});
|
||||
|
||||
Self.validateAsync('bic', checkBic, {
|
||||
message: 'Bank entity id must be specified'
|
||||
});
|
||||
async function checkBic(err, done) {
|
||||
const filter = {
|
||||
fields: ['code'],
|
||||
where: {id: this.countryFk}
|
||||
};
|
||||
const country = await Self.app.models.Country.findOne(filter);
|
||||
const code = country ? country.code.toLowerCase() : null;
|
||||
|
||||
if (code == 'es' && !this.id)
|
||||
err();
|
||||
done();
|
||||
}
|
||||
};
|
||||
|
|
|
@ -7,17 +7,14 @@ module.exports = Self => {
|
|||
|
||||
Self.observe('before save', async function(ctx) {
|
||||
if (!ctx.isNewInstance) return;
|
||||
|
||||
let {message} = ctx.instance;
|
||||
if (!message) return;
|
||||
|
||||
const parts = message.match(/(?<=\[)[a-zA-Z0-9_\-+!@#$%^&*()={};':"\\|,.<>/?\s]*(?=])/g);
|
||||
if (!parts) return;
|
||||
|
||||
const replacedParts = parts.map(part => {
|
||||
return part.replace(/[!$%^&*()={};':"\\,.<>/?]/g, '');
|
||||
});
|
||||
|
||||
for (const [index, part] of parts.entries())
|
||||
message = message.replace(part, replacedParts[index]);
|
||||
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
module.exports = Self => {
|
||||
require('../methods/collection/getCollection')(Self);
|
||||
require('../methods/collection/newCollection')(Self);
|
||||
require('../methods/collection/getSectors')(Self);
|
||||
require('../methods/collection/setSaleQuantity')(Self);
|
||||
require('../methods/collection/previousLabel')(Self);
|
||||
require('../methods/collection/getTickets')(Self);
|
||||
require('../methods/collection/assign')(Self);
|
||||
require('../methods/collection/getSales')(Self);
|
||||
};
|
||||
|
|
|
@ -17,10 +17,6 @@
|
|||
"type": "string",
|
||||
"required": true
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"required": true
|
||||
},
|
||||
"code": {
|
||||
"type": "string",
|
||||
"required": true
|
||||
|
@ -29,12 +25,12 @@
|
|||
"relations": {
|
||||
"readRole": {
|
||||
"type": "belongsTo",
|
||||
"model": "Role",
|
||||
"model": "VnRole",
|
||||
"foreignKey": "readRoleFk"
|
||||
},
|
||||
"writeRole": {
|
||||
"type": "belongsTo",
|
||||
"model": "Role",
|
||||
"model": "VnRole",
|
||||
"foreignKey": "writeRoleFk"
|
||||
}
|
||||
},
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
const UserError = require('vn-loopback/util/user-error');
|
||||
const fs = require('fs-extra');
|
||||
const path = require('path');
|
||||
|
||||
module.exports = Self => {
|
||||
require('../methods/dms/downloadFile')(Self);
|
||||
|
@ -35,4 +37,32 @@ module.exports = Self => {
|
|||
|
||||
return [stream, dms.contentType, `filename="${dms.file}"`];
|
||||
};
|
||||
|
||||
Self.getPath = async function(dms) {
|
||||
const models = Self.app.models;
|
||||
const pathHash = await models.DmsContainer.getHash(dms.id);
|
||||
const dmsContainer = await models.DmsContainer.container(pathHash);
|
||||
const dstFile = path.join(dmsContainer.client.root, pathHash, dms.file);
|
||||
return dstFile;
|
||||
};
|
||||
|
||||
Self.createWithExtension = async function(data, extension, options) {
|
||||
const newDms = await Self.create(data, options);
|
||||
return newDms.updateAttribute('file', `${newDms.id}.${extension}`, options);
|
||||
};
|
||||
|
||||
Self.createFromFile = async function(data, extension, srcFile, options) {
|
||||
const dms = await Self.createWithExtension(data, extension, options);
|
||||
const dstFile = await Self.getPath(dms);
|
||||
await fs.move(srcFile, dstFile, {overwrite: true});
|
||||
return dms;
|
||||
};
|
||||
|
||||
Self.createFromStream = async function(data, extension, stream, options) {
|
||||
const dms = await Self.createWithExtension(data, extension, options);
|
||||
const dstFile = await Self.getPath(dms);
|
||||
const writeStream = await fs.createWriteStream(dstFile);
|
||||
await stream.pipe(writeStream);
|
||||
return dms;
|
||||
};
|
||||
};
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "docuwareTablet",
|
||||
"base": "VnModel",
|
||||
"options": {
|
||||
"mysql": {
|
||||
"table": "docuwareTablet"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"tablet": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -46,12 +46,12 @@
|
|||
},
|
||||
"readRole": {
|
||||
"type": "belongsTo",
|
||||
"model": "Role",
|
||||
"model": "VnRole",
|
||||
"foreignKey": "readRoleFk"
|
||||
},
|
||||
"writeRole": {
|
||||
"type": "belongsTo",
|
||||
"model": "Role",
|
||||
"model": "VnRole",
|
||||
"foreignKey": "writeRoleFk"
|
||||
}
|
||||
},
|
||||
|
@ -64,4 +64,3 @@
|
|||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"name": "MachineWorkerConfig",
|
||||
"base": "VnModel",
|
||||
"options": {
|
||||
"mysql": {
|
||||
"table": "vn.machineWorkerConfig"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "number",
|
||||
"id": true
|
||||
},
|
||||
"maxHours": {
|
||||
"type": "number"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
module.exports = Self => {
|
||||
require('../methods/machine-worker/updateInTime')(Self);
|
||||
};
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"name": "Machine",
|
||||
"base": "VnModel",
|
||||
"options": {
|
||||
"mysql": {
|
||||
"table": "vn.machine"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "number",
|
||||
"id": true
|
||||
},
|
||||
"plate": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
module.exports = Self => {
|
||||
require('../methods/mobile-app-version-control/getVersion')(Self);
|
||||
};
|
|
@ -0,0 +1,39 @@
|
|||
{
|
||||
"name": "MobileAppVersionControl",
|
||||
"base": "VnModel",
|
||||
"options": {
|
||||
"mysql": {
|
||||
"table": "vn.mobileAppVersionControl"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "number",
|
||||
"id": true
|
||||
},
|
||||
"appName": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
"version": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
"isVersionCritical": {
|
||||
"type": "boolean"
|
||||
},
|
||||
|
||||
"urlProduction": {
|
||||
"type": "string"
|
||||
},
|
||||
"urlBeta": {
|
||||
"type": "string"
|
||||
},
|
||||
"versionBeta": {
|
||||
"type": "string"
|
||||
},
|
||||
"isVersionBetaCritical": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
module.exports = Self => {
|
||||
require('../methods/mrw-config/createShipment')(Self);
|
||||
require('../methods/mrw-config/cancelShipment')(Self);
|
||||
};
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"name": "MrwConfig",
|
||||
"base": "VnModel",
|
||||
"options": {
|
||||
"mysql": {
|
||||
"table": "mrwConfig"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "number",
|
||||
"id": true,
|
||||
"required": true
|
||||
},
|
||||
"url": {
|
||||
"type": "string",
|
||||
"required": true
|
||||
},
|
||||
"user": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
"franchiseCode": {
|
||||
"type": "string"
|
||||
},
|
||||
"subscriberCode": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -24,7 +24,7 @@
|
|||
},
|
||||
"role": {
|
||||
"type": "belongsTo",
|
||||
"model": "Role",
|
||||
"model": "VnRole",
|
||||
"foreignKey": "roleFk"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,62 +1,74 @@
|
|||
const UserError = require('vn-loopback/util/user-error');
|
||||
|
||||
module.exports = Self => {
|
||||
require('../methods/notification/getList')(Self);
|
||||
|
||||
Self.observe('before save', async function(ctx) {
|
||||
await checkModifyPermission(ctx);
|
||||
});
|
||||
|
||||
Self.observe('before delete', async function(ctx) {
|
||||
await checkModifyPermission(ctx);
|
||||
});
|
||||
|
||||
async function checkModifyPermission(ctx) {
|
||||
const models = Self.app.models;
|
||||
const instance = ctx.instance;
|
||||
const userId = ctx.options.accessToken.userId;
|
||||
const user = await ctx.instance.userFk;
|
||||
const modifiedUser = await getUserToModify(null, user, models);
|
||||
|
||||
if (userId != modifiedUser.id && userId != modifiedUser.bossFk)
|
||||
throw new UserError('You dont have permission to modify this user');
|
||||
});
|
||||
let notificationFk;
|
||||
let workerId;
|
||||
|
||||
Self.remoteMethod('deleteNotification', {
|
||||
description: 'Deletes a notification subscription',
|
||||
accepts: [
|
||||
{
|
||||
arg: 'ctx',
|
||||
type: 'object',
|
||||
http: {source: 'context'}
|
||||
},
|
||||
{
|
||||
arg: 'notificationId',
|
||||
type: 'number',
|
||||
required: true
|
||||
},
|
||||
],
|
||||
returns: {
|
||||
type: 'object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
verb: 'POST',
|
||||
path: '/deleteNotification'
|
||||
if (instance) {
|
||||
notificationFk = instance.notificationFk;
|
||||
workerId = instance.userFk;
|
||||
} else {
|
||||
const notificationSubscription = await models.NotificationSubscription.findById(ctx.where.id);
|
||||
notificationFk = notificationSubscription.notificationFk;
|
||||
workerId = notificationSubscription.userFk;
|
||||
}
|
||||
});
|
||||
|
||||
Self.deleteNotification = async function(ctx, notificationId) {
|
||||
const worker = await models.Worker.findById(workerId, {fields: ['id', 'bossFk']});
|
||||
const available = await Self.getAvailable(workerId);
|
||||
const hasAcl = available.has(notificationFk);
|
||||
|
||||
if (!hasAcl || (userId != worker.id && userId != worker.bossFk))
|
||||
throw new UserError('The notification subscription of this worker cant be modified');
|
||||
}
|
||||
|
||||
Self.getAvailable = async function(userId, options) {
|
||||
const availableNotificationsMap = new Map();
|
||||
const models = Self.app.models;
|
||||
const user = ctx.req.accessToken.userId;
|
||||
const modifiedUser = await getUserToModify(notificationId, null, models);
|
||||
|
||||
if (user != modifiedUser.id && user != modifiedUser.bossFk)
|
||||
throw new UserError('You dont have permission to modify this user');
|
||||
const myOptions = {};
|
||||
|
||||
await models.NotificationSubscription.destroyById(notificationId);
|
||||
};
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
||||
async function getUserToModify(notificationId, userFk, models) {
|
||||
let userToModify = userFk;
|
||||
if (notificationId) {
|
||||
const subscription = await models.NotificationSubscription.findById(notificationId);
|
||||
userToModify = subscription.userFk;
|
||||
}
|
||||
return await models.Worker.findOne({
|
||||
fields: ['id', 'bossFk'],
|
||||
const roles = await models.RoleMapping.find({
|
||||
fields: ['roleId'],
|
||||
where: {principalId: userId}
|
||||
}, myOptions);
|
||||
|
||||
const availableNotifications = await models.NotificationAcl.find({
|
||||
fields: ['notificationFk', 'roleFk'],
|
||||
include: {relation: 'notification'},
|
||||
where: {
|
||||
id: userToModify
|
||||
roleFk: {
|
||||
inq: roles.map(role => role.roleId),
|
||||
},
|
||||
}
|
||||
}, myOptions);
|
||||
|
||||
for (available of availableNotifications) {
|
||||
availableNotificationsMap.set(available.notificationFk, {
|
||||
id: null,
|
||||
notificationFk: available.notificationFk,
|
||||
name: available.notification().name,
|
||||
description: available.notification().description,
|
||||
active: false
|
||||
});
|
||||
}
|
||||
return availableNotificationsMap;
|
||||
};
|
||||
};
|
||||
|
|
|
@ -47,7 +47,7 @@
|
|||
},
|
||||
"bank": {
|
||||
"type": "belongsTo",
|
||||
"model": "Bank",
|
||||
"model": "Accounting",
|
||||
"foreignKey": "bankFk"
|
||||
},
|
||||
"payMethod": {
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
let UserError = require('vn-loopback/util/user-error');
|
||||
|
||||
module.exports = Self => {
|
||||
require('../methods/postcode/filter.js')(Self);
|
||||
Self.rewriteDbError(function(err) {
|
||||
if (err.code === 'ER_DUP_ENTRY')
|
||||
return new UserError(`This postcode already exists`);
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
const models = require('vn-loopback/server/server').models;
|
||||
|
||||
describe('loopback model MailAliasAccount', () => {
|
||||
it('should add a mail Alias', async() => {
|
||||
const tx = await models.MailAliasAccount.beginTransaction({});
|
||||
let error;
|
||||
|
||||
try {
|
||||
const options = {transaction: tx, accessToken: {userId: 9}};
|
||||
await models.MailAliasAccount.create({mailAlias: 2, account: 5}, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should add a mail Alias of an inherit role', async() => {
|
||||
const tx = await models.MailAliasAccount.beginTransaction({});
|
||||
let error;
|
||||
|
||||
try {
|
||||
const options = {transaction: tx, accessToken: {userId: 9}};
|
||||
await models.MailAliasAccount.create({mailAlias: 3, account: 5}, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should delete a mail Alias', async() => {
|
||||
const tx = await models.MailAliasAccount.beginTransaction({});
|
||||
let error;
|
||||
|
||||
try {
|
||||
const options = {transaction: tx, accessToken: {userId: 1}};
|
||||
const mailAclId = 2;
|
||||
await models.MailAliasAccount.destroyAll({id: mailAclId}, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,74 +1,126 @@
|
|||
const models = require('vn-loopback/server/server').models;
|
||||
|
||||
describe('loopback model NotificationSubscription', () => {
|
||||
it('Should fail to delete a notification if the user is not editing itself or a subordinate', async() => {
|
||||
it('should fail to add a notification subscription if the worker doesnt have ACLs', async() => {
|
||||
const tx = await models.NotificationSubscription.beginTransaction({});
|
||||
|
||||
try {
|
||||
const options = {transaction: tx};
|
||||
const user = 9;
|
||||
const notificationSubscriptionId = 2;
|
||||
const ctx = {req: {accessToken: {userId: user}}};
|
||||
const notification = await models.NotificationSubscription.findById(notificationSubscriptionId);
|
||||
|
||||
let error;
|
||||
|
||||
try {
|
||||
await models.NotificationSubscription.deleteNotification(ctx, notification.id, options);
|
||||
const options = {transaction: tx, accessToken: {userId: 9}};
|
||||
await models.NotificationSubscription.create({notificationFk: 1, userFk: 62}, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error.message).toContain('You dont have permission to modify this user');
|
||||
expect(error.message).toEqual('The notification subscription of this worker cant be modified');
|
||||
});
|
||||
|
||||
it('should fail to add a notification subscription if the user isnt editing itself or subordinate', async() => {
|
||||
const tx = await models.NotificationSubscription.beginTransaction({});
|
||||
let error;
|
||||
|
||||
try {
|
||||
const options = {transaction: tx, accessToken: {userId: 1}};
|
||||
await models.NotificationSubscription.create({notificationFk: 1, userFk: 9}, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error.message).toEqual('The notification subscription of this worker cant be modified');
|
||||
});
|
||||
|
||||
it('Should delete a notification if the user is editing itself', async() => {
|
||||
it('should fail to delete a notification subscription if the user isnt editing itself or subordinate', async() => {
|
||||
const tx = await models.NotificationSubscription.beginTransaction({});
|
||||
let error;
|
||||
|
||||
try {
|
||||
const options = {transaction: tx};
|
||||
const user = 9;
|
||||
const options = {transaction: tx, accessToken: {userId: 9}};
|
||||
const notificationSubscriptionId = 2;
|
||||
await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error.message).toEqual('The notification subscription of this worker cant be modified');
|
||||
});
|
||||
|
||||
it('should add a notification subscription if the user is editing itself', async() => {
|
||||
const tx = await models.NotificationSubscription.beginTransaction({});
|
||||
let error;
|
||||
|
||||
try {
|
||||
const options = {transaction: tx, accessToken: {userId: 9}};
|
||||
await models.NotificationSubscription.create({notificationFk: 2, userFk: 9}, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should delete a notification subscription if the user is editing itself', async() => {
|
||||
const tx = await models.NotificationSubscription.beginTransaction({});
|
||||
let error;
|
||||
|
||||
try {
|
||||
const options = {transaction: tx, accessToken: {userId: 9}};
|
||||
const notificationSubscriptionId = 6;
|
||||
await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should add a notification subscription if the user is editing a subordinate', async() => {
|
||||
const tx = await models.NotificationSubscription.beginTransaction({});
|
||||
let error;
|
||||
|
||||
try {
|
||||
const options = {transaction: tx, accessToken: {userId: 9}};
|
||||
await models.NotificationSubscription.create({notificationFk: 1, userFk: 5}, options);
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should delete a notification subscription if the user is editing a subordinate', async() => {
|
||||
const tx = await models.NotificationSubscription.beginTransaction({});
|
||||
let error;
|
||||
|
||||
try {
|
||||
const options = {transaction: tx, accessToken: {userId: 19}};
|
||||
const notificationSubscriptionId = 4;
|
||||
const ctx = {req: {accessToken: {userId: user}}};
|
||||
const notification = await models.NotificationSubscription.findById(notificationSubscriptionId);
|
||||
await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options);
|
||||
|
||||
await models.NotificationSubscription.deleteNotification(ctx, notification.id, options);
|
||||
|
||||
const deletedNotification = await models.NotificationSubscription.findById(notificationSubscriptionId);
|
||||
|
||||
expect(deletedNotification).toBeNull();
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
error = e;
|
||||
}
|
||||
});
|
||||
|
||||
it('Should delete a notification if the user is editing a subordinate', async() => {
|
||||
const tx = await models.NotificationSubscription.beginTransaction({});
|
||||
|
||||
try {
|
||||
const options = {transaction: tx};
|
||||
const user = 9;
|
||||
const notificationSubscriptionId = 5;
|
||||
const ctx = {req: {accessToken: {userId: user}}};
|
||||
const notification = await models.NotificationSubscription.findById(notificationSubscriptionId);
|
||||
|
||||
await models.NotificationSubscription.deleteNotification(ctx, notification.id, options);
|
||||
|
||||
const deletedNotification = await models.NotificationSubscription.findById(notificationSubscriptionId);
|
||||
|
||||
expect(deletedNotification).toBeNull();
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
const models = require('vn-loopback/server/server').models;
|
||||
const ForbiddenError = require('vn-loopback/util/forbiddenError');
|
||||
|
||||
describe('loopback model VnUser', () => {
|
||||
it('should return true if the user has the given role', async() => {
|
||||
|
@ -12,4 +13,42 @@ describe('loopback model VnUser', () => {
|
|||
|
||||
expect(result).toBeFalsy();
|
||||
});
|
||||
|
||||
describe('userSecurity', () => {
|
||||
const itManagementId = 115;
|
||||
const hrId = 37;
|
||||
const employeeId = 1;
|
||||
|
||||
it('should check if you are the same user', async() => {
|
||||
const ctx = {options: {accessToken: {userId: employeeId}}};
|
||||
await models.VnUser.userSecurity(ctx, employeeId);
|
||||
});
|
||||
|
||||
it('should check for higher privileges', async() => {
|
||||
const ctx = {options: {accessToken: {userId: itManagementId}}};
|
||||
await models.VnUser.userSecurity(ctx, employeeId);
|
||||
});
|
||||
|
||||
it('should check if you have medium privileges and the user email is not verified', async() => {
|
||||
const ctx = {options: {accessToken: {userId: hrId}}};
|
||||
await models.VnUser.userSecurity(ctx, employeeId);
|
||||
});
|
||||
|
||||
it('should throw an error if you have medium privileges and the users email is verified', async() => {
|
||||
const tx = await models.VnUser.beginTransaction({});
|
||||
const ctx = {options: {accessToken: {userId: hrId}}};
|
||||
try {
|
||||
const options = {transaction: tx};
|
||||
const userToUpdate = await models.VnUser.findById(1, null, options);
|
||||
userToUpdate.updateAttribute('emailVerified', 1, options);
|
||||
|
||||
await models.VnUser.userSecurity(ctx, employeeId, options);
|
||||
await tx.rollback();
|
||||
} catch (error) {
|
||||
await tx.rollback();
|
||||
|
||||
expect(error).toEqual(new ForbiddenError());
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -0,0 +1,4 @@
|
|||
module.exports = Self => {
|
||||
require('../methods/url/getByUser')(Self);
|
||||
require('../methods/url/getUrl')(Self);
|
||||
};
|
|
@ -26,6 +26,9 @@
|
|||
},
|
||||
"darkMode": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"tabletFk": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"relations": {
|
||||
|
@ -43,6 +46,11 @@
|
|||
"type": "belongsTo",
|
||||
"model": "VnUser",
|
||||
"foreignKey": "userFk"
|
||||
},
|
||||
"Tablet": {
|
||||
"type": "belongsTo",
|
||||
"model": "docuwareTablet",
|
||||
"foreignKey": "tabletFk"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
module.exports = Self => {
|
||||
require('../methods/viaexpress-config/internationalExpedition')(Self);
|
||||
require('../methods/viaexpress-config/renderer')(Self);
|
||||
require('../methods/viaexpress-config/deleteExpedition')(Self);
|
||||
require('../methods/viaexpress-config/deleteExpeditionRenderer')(Self);
|
||||
};
|
||||
|
|
|
@ -29,6 +29,9 @@
|
|||
},
|
||||
"deliveryType": {
|
||||
"type": "string"
|
||||
},
|
||||
"agencyModeFk": {
|
||||
"type": "number"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"name": "VnRole",
|
||||
"base": "Role",
|
||||
"validateUpsert": true,
|
||||
"options": {
|
||||
"mysql": {
|
||||
"table": "account.role"
|
||||
}
|
||||
},
|
||||
"mixins": {
|
||||
"Loggable": true
|
||||
}
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
const vnModel = require('vn-loopback/common/models/vn-model');
|
||||
const LoopBackContext = require('loopback-context');
|
||||
const {Email} = require('vn-print');
|
||||
const ForbiddenError = require('vn-loopback/util/forbiddenError');
|
||||
const LoopBackContext = require('loopback-context');
|
||||
const UserError = require('vn-loopback/util/user-error');
|
||||
|
||||
module.exports = function(Self) {
|
||||
vnModel(Self);
|
||||
|
@ -8,10 +10,11 @@ module.exports = function(Self) {
|
|||
require('../methods/vn-user/sign-in')(Self);
|
||||
require('../methods/vn-user/acl')(Self);
|
||||
require('../methods/vn-user/recover-password')(Self);
|
||||
require('../methods/vn-user/validate-token')(Self);
|
||||
require('../methods/vn-user/privileges')(Self);
|
||||
require('../methods/vn-user/validate-auth')(Self);
|
||||
require('../methods/vn-user/renew-token')(Self);
|
||||
require('../methods/vn-user/share-token')(Self);
|
||||
require('../methods/vn-user/update-user')(Self);
|
||||
|
||||
Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create');
|
||||
|
||||
|
@ -122,11 +125,43 @@ module.exports = function(Self) {
|
|||
return email.send();
|
||||
});
|
||||
|
||||
Self.validateLogin = async function(user, password) {
|
||||
let loginInfo = Object.assign({password}, Self.userUses(user));
|
||||
token = await Self.login(loginInfo, 'user');
|
||||
/**
|
||||
* Sign-in validate
|
||||
* @param {String} user The user
|
||||
* @param {Object} userToken Options
|
||||
* @param {Object} token accessToken
|
||||
* @param {Object} ctx context
|
||||
*/
|
||||
Self.signInValidate = async(user, userToken, token, ctx) => {
|
||||
const [[key, value]] = Object.entries(Self.userUses(user));
|
||||
const isOwner = Self.rawSql(`SELECT ? = ? `, [userToken[key], value]);
|
||||
if (!isOwner) {
|
||||
await Self.app.models.SignInLog.create({
|
||||
userName: user,
|
||||
token: token.id,
|
||||
userFk: userToken.id,
|
||||
ip: ctx.req.ip,
|
||||
owner: isOwner
|
||||
});
|
||||
throw new UserError('Try again');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate login params
|
||||
* @param {String} user The user
|
||||
* @param {String} password
|
||||
* @param {Object} ctx context
|
||||
*/
|
||||
Self.validateLogin = async function(user, password, ctx) {
|
||||
const loginInfo = Object.assign({password}, Self.userUses(user));
|
||||
const token = await Self.login(loginInfo, 'user');
|
||||
|
||||
const userToken = await token.user.get();
|
||||
|
||||
if (ctx)
|
||||
await Self.signInValidate(user, userToken, token, ctx);
|
||||
|
||||
try {
|
||||
await Self.app.models.Account.sync(userToken.name, password);
|
||||
} catch (err) {
|
||||
|
@ -178,45 +213,82 @@ module.exports = function(Self) {
|
|||
Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls
|
||||
.filter(acl => acl.property != 'changePassword');
|
||||
|
||||
// FIXME: https://redmine.verdnatura.es/issues/5761
|
||||
// Self.afterRemote('prototype.patchAttributes', async(ctx, instance) => {
|
||||
// if (!ctx.args || !ctx.args.data.email) return;
|
||||
Self.userSecurity = async(ctx, userId, options) => {
|
||||
const models = Self.app.models;
|
||||
const accessToken = ctx?.options?.accessToken || LoopBackContext.getCurrentContext().active.accessToken;
|
||||
const ctxToken = {req: {accessToken}};
|
||||
|
||||
// const loopBackContext = LoopBackContext.getCurrentContext();
|
||||
// const httpCtx = {req: loopBackContext.active};
|
||||
// const httpRequest = httpCtx.req.http.req;
|
||||
// const headers = httpRequest.headers;
|
||||
// const origin = headers.origin;
|
||||
// const url = origin.split(':');
|
||||
if (userId === accessToken.userId) return;
|
||||
|
||||
// class Mailer {
|
||||
// async send(verifyOptions, cb) {
|
||||
// const params = {
|
||||
// url: verifyOptions.verifyHref,
|
||||
// recipient: verifyOptions.to,
|
||||
// lang: ctx.req.getLocale()
|
||||
// };
|
||||
const myOptions = {};
|
||||
if (typeof options == 'object')
|
||||
Object.assign(myOptions, options);
|
||||
|
||||
// const email = new Email('email-verify', params);
|
||||
// email.send();
|
||||
const hasHigherPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'higherPrivileges', myOptions);
|
||||
if (hasHigherPrivileges) return;
|
||||
|
||||
// cb(null, verifyOptions.to);
|
||||
// }
|
||||
// }
|
||||
const hasMediumPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'mediumPrivileges', myOptions);
|
||||
const user = await models.VnUser.findById(userId, {fields: ['id', 'emailVerified']}, myOptions);
|
||||
if (!user.emailVerified && hasMediumPrivileges) return;
|
||||
|
||||
// const options = {
|
||||
// type: 'email',
|
||||
// to: instance.email,
|
||||
// from: {},
|
||||
// redirect: `${origin}/#!/account/${instance.id}/basic-data?emailConfirmed`,
|
||||
// template: false,
|
||||
// mailer: new Mailer,
|
||||
// host: url[1].split('/')[2],
|
||||
// port: url[2],
|
||||
// protocol: url[0],
|
||||
// user: Self
|
||||
// };
|
||||
|
||||
// await instance.verify(options);
|
||||
// });
|
||||
throw new ForbiddenError();
|
||||
};
|
||||
|
||||
Self.observe('after save', async ctx => {
|
||||
const instance = ctx?.instance;
|
||||
const newEmail = instance?.email;
|
||||
const oldEmail = ctx?.hookState?.oldInstance?.email;
|
||||
if (!ctx.isNewInstance && (!newEmail || !oldEmail || newEmail == oldEmail)) return;
|
||||
|
||||
const loopBackContext = LoopBackContext.getCurrentContext();
|
||||
const httpCtx = {req: loopBackContext.active};
|
||||
const httpRequest = httpCtx.req.http.req;
|
||||
const headers = httpRequest.headers;
|
||||
const origin = headers.origin;
|
||||
const url = origin.split(':');
|
||||
|
||||
const env = process.env.NODE_ENV;
|
||||
const liliumUrl = await Self.app.models.Url.findOne({
|
||||
where: {
|
||||
and: [
|
||||
{appName: 'lilium'},
|
||||
{environment: env}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
class Mailer {
|
||||
async send(verifyOptions, cb) {
|
||||
try {
|
||||
const url = new URL(verifyOptions.verifyHref);
|
||||
if (process.env.NODE_ENV) url.port = '';
|
||||
|
||||
const email = new Email('email-verify', {
|
||||
url: url.href,
|
||||
recipient: verifyOptions.to
|
||||
});
|
||||
await email.send();
|
||||
|
||||
cb(null, verifyOptions.to);
|
||||
} catch (err) {
|
||||
cb(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const options = {
|
||||
type: 'email',
|
||||
to: newEmail,
|
||||
from: {},
|
||||
redirect: `${liliumUrl.url}verifyEmail?userId=${instance.id}`,
|
||||
template: false,
|
||||
mailer: new Mailer,
|
||||
host: url[1].split('/')[2],
|
||||
port: url[2],
|
||||
protocol: url[0],
|
||||
user: Self
|
||||
};
|
||||
|
||||
await instance.verify(options, ctx.options);
|
||||
});
|
||||
};
|
||||
|
|
|
@ -7,6 +7,9 @@
|
|||
"table": "account.user"
|
||||
}
|
||||
},
|
||||
"mixins": {
|
||||
"Loggable": true
|
||||
},
|
||||
"resetPasswordTokenTTL": "604800",
|
||||
"properties": {
|
||||
"id": {
|
||||
|
@ -18,14 +21,7 @@
|
|||
"required": true
|
||||
},
|
||||
"username": {
|
||||
"type": "string",
|
||||
"mysql": {
|
||||
"columnName": "name"
|
||||
}
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"required": true
|
||||
"type": "string"
|
||||
},
|
||||
"roleFk": {
|
||||
"type": "number",
|
||||
|
@ -45,6 +41,9 @@
|
|||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"emailVerified": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"created": {
|
||||
"type": "date"
|
||||
},
|
||||
|
@ -67,7 +66,7 @@
|
|||
"relations": {
|
||||
"role": {
|
||||
"type": "belongsTo",
|
||||
"model": "Role",
|
||||
"model": "VnRole",
|
||||
"foreignKey": "roleFk"
|
||||
},
|
||||
"roles": {
|
||||
|
@ -106,13 +105,6 @@
|
|||
"principalType": "ROLE",
|
||||
"principalId": "$everyone",
|
||||
"permission": "ALLOW"
|
||||
},
|
||||
{
|
||||
"property": "validateToken",
|
||||
"accessType": "EXECUTE",
|
||||
"principalType": "ROLE",
|
||||
"principalId": "$authenticated",
|
||||
"permission": "ALLOW"
|
||||
},
|
||||
{
|
||||
"property": "validateAuth",
|
||||
|
@ -127,6 +119,20 @@
|
|||
"principalType": "ROLE",
|
||||
"principalId": "$authenticated",
|
||||
"permission": "ALLOW"
|
||||
},
|
||||
{
|
||||
"property": "renewToken",
|
||||
"accessType": "WRITE",
|
||||
"principalType": "ROLE",
|
||||
"principalId": "$authenticated",
|
||||
"permission": "ALLOW"
|
||||
},
|
||||
{
|
||||
"property": "shareToken",
|
||||
"accessType": "WRITE",
|
||||
"principalType": "ROLE",
|
||||
"principalId": "$authenticated",
|
||||
"permission": "ALLOW"
|
||||
}
|
||||
],
|
||||
"scopes": {
|
||||
|
@ -144,7 +150,8 @@
|
|||
"image",
|
||||
"hasGrant",
|
||||
"realm",
|
||||
"email"
|
||||
"email",
|
||||
"emailVerified"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,39 @@
|
|||
{
|
||||
"name": "WorkerActivity",
|
||||
"base": "VnModel",
|
||||
"options": {
|
||||
"mysql": {
|
||||
"table": "workerActivity"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"id": {
|
||||
"id": true,
|
||||
"type": "number"
|
||||
},
|
||||
"created": {
|
||||
"type": "date"
|
||||
},
|
||||
"model": {
|
||||
"type": "string"
|
||||
},
|
||||
"event": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"type": "string"
|
||||
},
|
||||
"relations": {
|
||||
"workerFk": {
|
||||
"type": "belongsTo",
|
||||
"model": "Worker",
|
||||
"foreignKey": "workerFk"
|
||||
},
|
||||
"workerActivityTypeFk": {
|
||||
"type": "belongsTo",
|
||||
"model": "WorkerActivityType",
|
||||
"foreignKey": "workerActivityTypeFk"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"name": "WorkerActivityType",
|
||||
"base": "VnModel",
|
||||
"options": {
|
||||
"mysql": {
|
||||
"table": "workerActivityType"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"code": {
|
||||
"id": true,
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"required": false
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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();
|
161
back/tests.js
161
back/tests.js
|
@ -1,80 +1,123 @@
|
|||
const Docker = require('../db/docker.js');
|
||||
let dataSources = require('../loopback/server/datasources.json');
|
||||
/* eslint-disable no-console */
|
||||
const path = require('path');
|
||||
const getopts = require('getopts');
|
||||
const Myt = require('@verdnatura/myt/myt');
|
||||
const Run = require('@verdnatura/myt/myt-run');
|
||||
const helper = require('./tests-helper');
|
||||
|
||||
process.on('warning', warning => {
|
||||
console.log(warning.name);
|
||||
console.log(warning.message);
|
||||
console.log(warning.stack);
|
||||
const opts = getopts(process.argv.slice(2), {
|
||||
string: [
|
||||
'network'
|
||||
],
|
||||
boolean: [
|
||||
'ci',
|
||||
'junit'
|
||||
]
|
||||
});
|
||||
|
||||
process.on('exit', async function() {
|
||||
if (container) await container.rm();
|
||||
});
|
||||
let server;
|
||||
const PARALLEL = false;
|
||||
const SETUP_TIMEOUT = 15 * 60 * 1000;
|
||||
const SPEC_TIMEOUT = 30 * 1000;
|
||||
|
||||
process.on('exit', teardown);
|
||||
process.on('uncaughtException', onError);
|
||||
process.on('unhandledRejection', onError);
|
||||
|
||||
const exitSignals = [
|
||||
'SIGINT',
|
||||
'SIGUSR1',
|
||||
'SIGUSR2'
|
||||
];
|
||||
for (const signal of exitSignals)
|
||||
process.on(signal, () => process.exit());
|
||||
|
||||
async function setup() {
|
||||
console.log('Building and running DB container.');
|
||||
|
||||
const myt = new Myt();
|
||||
await myt.init({
|
||||
workspace: path.join(__dirname, '..'),
|
||||
random: true,
|
||||
ci: opts.ci,
|
||||
tmpfs: process.platform == 'linux',
|
||||
network: opts.network || null
|
||||
});
|
||||
server = await myt.run(Run);
|
||||
await myt.deinit();
|
||||
|
||||
const {dbConfig} = server;
|
||||
process.env.DB_HOST = dbConfig.host;
|
||||
process.env.DB_PORT = dbConfig.port;
|
||||
|
||||
if (!PARALLEL)
|
||||
await helper.init();
|
||||
}
|
||||
|
||||
async function teardown() {
|
||||
if (!server) return;
|
||||
const oldServer = server;
|
||||
server = null;
|
||||
|
||||
if (!PARALLEL)
|
||||
await helper.deinit();
|
||||
|
||||
console.log('Stopping and removing DB container.');
|
||||
await oldServer.rm();
|
||||
}
|
||||
|
||||
async function onError(err) {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let container;
|
||||
async function test() {
|
||||
let isCI = false;
|
||||
|
||||
if (process.argv[2] === 'ci')
|
||||
isCI = true;
|
||||
|
||||
container = new Docker();
|
||||
|
||||
await container.run(isCI);
|
||||
dataSources = JSON.parse(JSON.stringify(dataSources));
|
||||
|
||||
Object.assign(dataSources.vn, {
|
||||
host: container.dbConf.host,
|
||||
port: container.dbConf.port
|
||||
});
|
||||
|
||||
const bootOptions = {dataSources};
|
||||
const app = require('vn-loopback/server/server');
|
||||
await new Promise((resolve, reject) => {
|
||||
app.boot(bootOptions,
|
||||
err => err ? reject(err) : resolve());
|
||||
});
|
||||
// FIXME: Workaround to wait for loopback to be ready
|
||||
await app.models.Application.status();
|
||||
let runner;
|
||||
const config = {
|
||||
globalSetup: setup,
|
||||
globalSetupTimeout: SETUP_TIMEOUT,
|
||||
globalTeardown: teardown,
|
||||
globalTeardownTimeout: SETUP_TIMEOUT,
|
||||
spec_dir: '.',
|
||||
spec_files: [
|
||||
'back/**/*[sS]pec.js',
|
||||
'loopback/**/*[sS]pec.js',
|
||||
'modules/*/back/**/*.[sS]pec.js'
|
||||
],
|
||||
helpers: []
|
||||
};
|
||||
|
||||
if (PARALLEL) {
|
||||
const ParallelRunner = require('jasmine/parallel');
|
||||
runner = new ParallelRunner({numWorkers: 1});
|
||||
config.helpers.push(`back/tests-helper.js`);
|
||||
} else {
|
||||
const Jasmine = require('jasmine');
|
||||
const jasmine = new Jasmine();
|
||||
runner = new Jasmine();
|
||||
|
||||
const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
|
||||
jasmine.addReporter(new SpecReporter({
|
||||
runner.addReporter(new SpecReporter({
|
||||
spec: {
|
||||
displaySuccessful: isCI,
|
||||
displayPending: isCI
|
||||
displaySuccessful: opts.ci,
|
||||
displayPending: opts.ci
|
||||
},
|
||||
summary: {
|
||||
displayPending: false,
|
||||
}
|
||||
}));
|
||||
|
||||
if (isCI) {
|
||||
const JunitReporter = require('jasmine-reporters');
|
||||
jasmine.addReporter(new JunitReporter.JUnitXmlReporter());
|
||||
|
||||
jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 90000;
|
||||
jasmine.exitOnCompletion = true;
|
||||
}
|
||||
|
||||
const backSpecs = [
|
||||
'./back/**/*[sS]pec.js',
|
||||
'./loopback/**/*[sS]pec.js',
|
||||
'./modules/*/back/**/*.[sS]pec.js'
|
||||
];
|
||||
if (opts.junit) {
|
||||
const JunitReporter = require('jasmine-reporters');
|
||||
runner.addReporter(new JunitReporter.JUnitXmlReporter());
|
||||
}
|
||||
if (opts.ci)
|
||||
runner.jasmine.DEFAULT_TIMEOUT_INTERVAL = SPEC_TIMEOUT;
|
||||
|
||||
jasmine.loadConfig({
|
||||
spec_dir: '.',
|
||||
spec_files: backSpecs,
|
||||
helpers: [],
|
||||
});
|
||||
|
||||
await jasmine.execute();
|
||||
if (app) await app.disconnect();
|
||||
if (container) await container.rm();
|
||||
console.log('App disconnected & container removed');
|
||||
// runner.loadConfigFile('back/jasmine.json');
|
||||
runner.loadConfig(config);
|
||||
process.env.SPEC_IS_RUNNING = true;
|
||||
await runner.execute();
|
||||
}
|
||||
|
||||
test();
|
||||
|
|
|
@ -1,49 +0,0 @@
|
|||
INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
|
||||
VALUES
|
||||
('ClientConsumptionQueue', '*', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Ticket', 'deliveryNotePdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Ticket', 'deliveryNoteEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Ticket', 'deliveryNoteCsvPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Ticket', 'deliveryNoteCsvEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'campaignMetricsPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'campaignMetricsEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'clientWelcomeHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'clientWelcomeEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'creditRequestPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'creditRequestHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'creditRequestEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'printerSetupHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'printerSetupEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'sepaCoreEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'letterDebtorPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'letterDebtorStHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'letterDebtorStEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'letterDebtorNdHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'letterDebtorNdEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'clientDebtStatementPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'clientDebtStatementHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'clientDebtStatementEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'incotermsAuthorizationPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'incotermsAuthorizationHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'incotermsAuthorizationEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Client', 'consumptionSendQueued', 'WRITE', 'ALLOW', 'ROLE', 'system'),
|
||||
('InvoiceOut', 'invoiceEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('InvoiceOut', 'exportationPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('InvoiceOut', 'sendQueued', 'WRITE', 'ALLOW', 'ROLE', 'system'),
|
||||
('Ticket', 'invoiceCsvPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Ticket', 'invoiceCsvEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Supplier', 'campaignMetricsPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Supplier', 'campaignMetricsEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Travel', 'extraCommunityPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Travel', 'extraCommunityEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Entry', 'entryOrderPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('OsTicket', 'osTicketReportEmail', 'WRITE', 'ALLOW', 'ROLE', 'system'),
|
||||
('Item', 'buyerWasteEmail', 'WRITE', 'ALLOW', 'ROLE', 'system'),
|
||||
('Claim', 'claimPickupPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
|
||||
('Claim', 'claimPickupEmail', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'),
|
||||
('Item', 'labelPdf', 'READ', 'ALLOW', 'ROLE', 'employee');
|
||||
|
||||
INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
|
||||
VALUES ('Sector','*','READ','ALLOW','ROLE','employee');
|
||||
INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
|
||||
VALUES ('Sector','*','WRITE','ALLOW','ROLE','employee');
|
|
@ -1,9 +0,0 @@
|
|||
create table `vn`.`clientConsumptionQueue`
|
||||
(
|
||||
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
params json not null,
|
||||
queued datetime default current_timestamp() not null,
|
||||
printed datetime null,
|
||||
status varchar(50) default '' null
|
||||
)
|
||||
comment 'Queue for client consumption PDF mailing';
|
|
@ -1 +0,0 @@
|
|||
rename table `vn`.`invoiceOut_queue` to `vn`.`invoiceOutQueue`;
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue