diff --git a/.eslintrc.yml b/.eslintrc.yml index 13fc2b140..edbc47195 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -1,6 +1,6 @@ extends: [eslint:recommended, google, plugin:jasmine/recommended] parserOptions: - ecmaVersion: 2018 + ecmaVersion: 2020 sourceType: "module" plugins: - jasmine @@ -17,7 +17,7 @@ rules: camelcase: 0 default-case: 0 no-eq-null: 0 - no-console: ["error"] + no-console: ["warn"] no-warning-comments: 0 no-empty: [error, allowEmptyCatch: true] complexity: 0 @@ -35,4 +35,4 @@ rules: space-in-parens: ["error", "never"] jasmine/no-focused-tests: 0 jasmine/prefer-toHaveBeenCalledWith: 0 - arrow-spacing: ["error", { "before": true, "after": true }] \ No newline at end of file + arrow-spacing: ["error", { "before": true, "after": true }] diff --git a/CHANGELOG.md b/CHANGELOG.md index 92c4ee3aa..36347bd19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,14 +5,42 @@ 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). -## [2324.01] - 2023-06-08 +## [2328.01] - 2023-07-13 ### Added -- - ### Changed -- + +### Fixed + + +## [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 + +### 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 +- (General -> Históricos) Botón para hacer más ágil mostrar sólo los cambios en un registro +- (General -> Históricos) Filtro por cambios + +### Changed +- (General -> Permisos) Mejorada seguridad +- (General -> Históricos) Elementos de la interfaz reorganizados para hacerla más ágil e intuitiva ### Fixed - @@ -28,7 +56,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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 diff --git a/Dockerfile b/Dockerfile index ee87cd0d0..e1173ad73 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,9 +11,9 @@ RUN apt-get update \ ca-certificates \ gnupg2 \ graphicsmagick \ - && curl -fsSL https://deb.nodesource.com/setup_14.x | bash - \ + && curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \ && apt-get install -y --no-install-recommends nodejs \ - && npm install -g npm@8.19.2 + && npm install -g npm@9.6.6 # Puppeteer diff --git a/Jenkinsfile b/Jenkinsfile index 5f329ee61..cf9b8cd67 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -39,7 +39,7 @@ pipeline { NODE_ENV = "" } steps { - nodejs('node-v14') { + nodejs('node-v20') { sh 'npm install --no-audit --prefer-offline' sh 'gulp install --ci' } @@ -57,14 +57,14 @@ pipeline { parallel { stage('Frontend') { steps { - nodejs('node-v14') { + nodejs('node-v20') { sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=2' } } } stage('Backend') { steps { - nodejs('node-v14') { + nodejs('node-v20') { sh 'npm run test:back:ci' } } @@ -80,7 +80,7 @@ pipeline { CREDENTIALS = credentials('docker-registry') } steps { - nodejs('node-v14') { + nodejs('node-v20') { sh 'gulp build' } diff --git a/README.md b/README.md index f73a8551b..59f5dbcf7 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Salix is also the scientific name of a beautifull tree! :) Required applications. -* Node.js = 14.x LTS +* Node.js >= 16.x LTS * Docker * Git @@ -71,7 +71,7 @@ $ npm run test:e2e Open Visual Studio Code, press Ctrl+P and paste the following commands. -In Visual Studio Code we use the ESLint extension. +In Visual Studio Code we use the ESLint extension. ``` ext install dbaeumer.vscode-eslint ``` diff --git a/back/methods/collection/newCollection.js b/back/methods/collection/newCollection.js index 31e419b67..2be9f8b0e 100644 --- a/back/methods/collection/newCollection.js +++ b/back/methods/collection/newCollection.js @@ -30,11 +30,11 @@ module.exports = Self => { Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => { let query = ''; + const userId = ctx.req.accessToken.userId; if (!collectionFk) { - const userId = ctx.req.accessToken.userId; query = `CALL vn.collectionTrain_newBeta(?,?,?)`; - const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId]); + const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId], {userId}); if (result.length == 0) throw new Error(`No collections for today`); @@ -42,16 +42,16 @@ module.exports = Self => { } query = `CALL vn.collectionTicket_get(?)`; - const [tickets] = await Self.rawSql(query, [collectionFk]); + const [tickets] = await Self.rawSql(query, [collectionFk], {userId}); query = `CALL vn.collectionSale_get(?)`; - const [sales] = await Self.rawSql(query, [collectionFk]); + const [sales] = await Self.rawSql(query, [collectionFk], {userId}); query = `CALL vn.collectionPlacement_get(?)`; - const [placements] = await Self.rawSql(query, [collectionFk]); + const [placements] = await Self.rawSql(query, [collectionFk], {userId}); query = `CALL vn.collectionSticker_print(?,?)`; - await Self.rawSql(query, [collectionFk, sectorFk]); + await Self.rawSql(query, [collectionFk, sectorFk], {userId}); return makeCollection(tickets, sales, placements, collectionFk); }; diff --git a/back/methods/docuware/specs/upload.spec.js b/back/methods/docuware/specs/upload.spec.js index 7ac873e95..3b8c55a50 100644 --- a/back/methods/docuware/specs/upload.spec.js +++ b/back/methods/docuware/specs/upload.spec.js @@ -2,8 +2,9 @@ const models = require('vn-loopback/server/server').models; describe('docuware upload()', () => { const userId = 9; - const ticketId = 10; + const ticketIds = [10]; const ctx = { + args: {ticketIds}, req: { getLocale: () => { return 'en'; @@ -27,7 +28,7 @@ describe('docuware upload()', () => { let error; try { - await models.Docuware.upload(ctx, ticketId, fileCabinetName); + await models.Docuware.upload(ctx, ticketIds, fileCabinetName); } catch (e) { error = e.message; } diff --git a/back/methods/docuware/upload.js b/back/methods/docuware/upload.js index ea9ee3622..096301e56 100644 --- a/back/methods/docuware/upload.js +++ b/back/methods/docuware/upload.js @@ -3,34 +3,34 @@ const axios = require('axios'); module.exports = Self => { Self.remoteMethodCtx('upload', { - description: 'Upload an docuware PDF', + description: 'Upload docuware PDFs', accessType: 'WRITE', accepts: [ { - arg: 'id', - type: 'number', - description: 'The ticket id', - http: {source: 'path'} + arg: 'ticketIds', + type: ['number'], + description: 'The ticket ids', + required: true }, { arg: 'fileCabinet', type: 'string', - description: 'The file cabinet' - }, - { - arg: 'dialog', - type: 'string', - description: 'The dialog' + description: 'The file cabinet', + required: true } ], - returns: [], + returns: { + type: 'object', + root: true + }, http: { - path: `/:id/upload`, + path: `/upload`, verb: 'POST' } }); - Self.upload = async function(ctx, id, fileCabinet) { + Self.upload = async function(ctx, ticketIds, fileCabinet) { + delete ctx.args.ticketIds; const models = Self.app.models; const action = 'store'; @@ -38,104 +38,114 @@ module.exports = Self => { const fileCabinetId = await Self.getFileCabinet(fileCabinet); const dialogId = await Self.getDialog(fileCabinet, action, fileCabinetId); - // get delivery note - const deliveryNote = await models.Ticket.deliveryNotePdf(ctx, { - id, - type: 'deliveryNote' - }); - - // get ticket data - const ticket = await models.Ticket.findById(id, { - include: [{ - relation: 'client', - scope: { - fields: ['id', 'socialName', 'fi'] - } - }] - }); - - // upload file - const templateJson = { - 'Fields': [ - { - 'FieldName': 'N__ALBAR_N', - 'ItemElementName': 'string', - 'Item': id, - }, - { - 'FieldName': 'CIF_PROVEEDOR', - 'ItemElementName': 'string', - 'Item': ticket.client().fi, - }, - { - 'FieldName': 'CODIGO_PROVEEDOR', - 'ItemElementName': 'string', - 'Item': ticket.client().id, - }, - { - 'FieldName': 'NOMBRE_PROVEEDOR', - 'ItemElementName': 'string', - 'Item': ticket.client().socialName, - }, - { - 'FieldName': 'FECHA_FACTURA', - 'ItemElementName': 'date', - 'Item': ticket.shipped, - }, - { - 'FieldName': 'TOTAL_FACTURA', - 'ItemElementName': 'Decimal', - 'Item': ticket.totalWithVat, - }, - { - 'FieldName': 'ESTADO', - 'ItemElementName': 'string', - 'Item': 'Pendiente procesar', - }, - { - 'FieldName': 'FIRMA_', - 'ItemElementName': 'string', - 'Item': 'Si', - }, - { - 'FieldName': 'FILTRO_TABLET', - 'ItemElementName': 'string', - 'Item': 'Tablet1', - } - ] - }; - - if (process.env.NODE_ENV != 'production') - throw new UserError('Action not allowed on the test environment'); - - // delete old - const docuwareFile = await models.Docuware.checkFile(ctx, id, fileCabinet, false); - if (docuwareFile) { - 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 uploadUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`; - const FormData = require('form-data'); - const data = new FormData(); - - data.append('document', JSON.stringify(templateJson), 'schema.json'); - data.append('file[]', deliveryNote[0], 'file.pdf'); - const uploadOptions = { - headers: { - 'Content-Type': 'multipart/form-data', - 'X-File-ModifiedDate': Date.vnNew(), - 'Cookie': options.headers.headers.Cookie, - ...data.getHeaders() - }, - }; - - return await axios.post(uploadUri, data, uploadOptions) - .catch(() => { - throw new UserError('Failed to upload file'); + const uploaded = []; + for (id of ticketIds) { + // get delivery note + ctx.args.id = id; + const deliveryNote = await models.Ticket.deliveryNotePdf(ctx, { + id, + type: 'deliveryNote' }); + // get ticket data + const ticket = await models.Ticket.findById(id, { + include: [{ + relation: 'client', + scope: { + fields: ['id', 'name', 'fi'] + } + }] + }); + + // upload file + const templateJson = { + 'Fields': [ + { + 'FieldName': 'N__ALBAR_N', + 'ItemElementName': 'string', + 'Item': id, + }, + { + 'FieldName': 'CIF_PROVEEDOR', + 'ItemElementName': 'string', + 'Item': ticket.client().fi, + }, + { + 'FieldName': 'CODIGO_PROVEEDOR', + 'ItemElementName': 'string', + 'Item': ticket.client().id, + }, + { + 'FieldName': 'NOMBRE_PROVEEDOR', + 'ItemElementName': 'string', + 'Item': ticket.client().name + ' - ' + id, + }, + { + 'FieldName': 'FECHA_FACTURA', + 'ItemElementName': 'date', + 'Item': ticket.shipped, + }, + { + 'FieldName': 'TOTAL_FACTURA', + 'ItemElementName': 'Decimal', + 'Item': ticket.totalWithVat, + }, + { + 'FieldName': 'ESTADO', + 'ItemElementName': 'string', + 'Item': 'Pendiente procesar', + }, + { + 'FieldName': 'FIRMA_', + 'ItemElementName': 'string', + 'Item': 'Si', + }, + { + 'FieldName': 'FILTRO_TABLET', + 'ItemElementName': 'string', + 'Item': 'Tablet1', + } + ] + }; + + if (process.env.NODE_ENV != 'production') + throw new UserError('Action not allowed on the test environment'); + + // delete old + const docuwareFile = await models.Docuware.checkFile(ctx, id, fileCabinet, false); + if (docuwareFile) { + 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 uploadUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`; + const FormData = require('form-data'); + const data = new FormData(); + + data.append('document', JSON.stringify(templateJson), 'schema.json'); + data.append('file[]', deliveryNote[0], 'file.pdf'); + const uploadOptions = { + headers: { + 'Content-Type': 'multipart/form-data', + 'X-File-ModifiedDate': Date.vnNew(), + 'Cookie': options.headers.headers.Cookie, + ...data.getHeaders() + }, + }; + + try { + await axios.post(uploadUri, data, uploadOptions); + } catch (err) { + const $t = ctx.req.__; + const message = $t('Failed to upload delivery note', {id}); + if (uploaded.length) + await models.TicketTracking.setDelivered(ctx, uploaded); + throw new UserError(message); + } + uploaded.push(id); + } + return models.TicketTracking.setDelivered(ctx, ticketIds); }; }; diff --git a/back/methods/edi/updateData.js b/back/methods/edi/updateData.js index 1057be39b..10c81a795 100644 --- a/back/methods/edi/updateData.js +++ b/back/methods/edi/updateData.js @@ -3,237 +3,237 @@ const path = require('path'); const fs = require('fs-extra'); module.exports = Self => { - Self.remoteMethodCtx('updateData', { - description: 'Updates schema data from external provider', - accessType: 'WRITE', - returns: { - type: 'object', - root: true - }, - http: { - path: `/updateData`, - verb: 'POST' - } - }); + Self.remoteMethodCtx('updateData', { + description: 'Updates schema data from external provider', + accessType: 'WRITE', + returns: { + type: 'object', + root: true + }, + http: { + path: `/updateData`, + verb: 'POST' + } + }); - Self.updateData = async() => { - const models = Self.app.models; + Self.updateData = async ctx => { + const models = Self.app.models; - // Get files checksum - const tx = await Self.beginTransaction({}); + // Get files checksum + const tx = await Self.beginTransaction({}); - try { - const options = {transaction: tx}; - const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileConfig', null, options); + try { + const options = {transaction: tx, userId: ctx.req.accessToken.userId}; + const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileConfig', null, options); - const updatableFiles = []; - for (const file of files) { - const fileChecksum = await getChecksum(file); + const updatableFiles = []; + for (const file of files) { + const fileChecksum = await getChecksum(file); - if (file.checksum != fileChecksum) { - updatableFiles.push({ - name: file.name, - checksum: fileChecksum - }); - } else - console.debug(`File already updated, skipping...`); - } + if (file.checksum != fileChecksum) { + updatableFiles.push({ + name: file.name, + checksum: fileChecksum + }); + } else + console.debug(`File already updated, skipping...`); + } - if (updatableFiles.length === 0) - return false; + if (updatableFiles.length === 0) + return false; - // Download files - const container = await models.TempContainer.container('edi'); - const tempPath = path.join(container.client.root, container.name); + // Download files + const container = await models.TempContainer.container('edi'); + const tempPath = path.join(container.client.root, container.name); - let remoteFile; - let tempDir; - let tempFile; + let remoteFile; + let tempDir; + let tempFile; - const fileNames = updatableFiles.map(file => file.name); + const fileNames = updatableFiles.map(file => file.name); - const tables = await Self.rawSql(` + const tables = await Self.rawSql(` SELECT fileName, toTable, file FROM edi.tableConfig WHERE file IN (?)`, [fileNames], options); - for (const table of tables) { - const fileName = table.file; + for (const table of tables) { + const fileName = table.file; - remoteFile = `codes/${fileName}.ZIP`; - tempDir = `${tempPath}/${fileName}`; - tempFile = `${tempPath}/${fileName}.zip`; + remoteFile = `codes/${fileName}.ZIP`; + tempDir = `${tempPath}/${fileName}`; + tempFile = `${tempPath}/${fileName}.zip`; - try { - await fs.readFile(tempFile); - } catch (error) { - if (error.code === 'ENOENT') { - console.debug(`Downloading file ${fileName}...`); - const downloadOutput = await downloadFile(remoteFile, tempFile); - if (downloadOutput.error) - continue; - } - } + try { + await fs.readFile(tempFile); + } catch (error) { + if (error.code === 'ENOENT') { + console.debug(`Downloading file ${fileName}...`); + const downloadOutput = await downloadFile(remoteFile, tempFile); + if (downloadOutput.error) + continue; + } + } - await extractFile(fileName, tempFile, tempDir); + await extractFile(fileName, tempFile, tempDir); - console.debug(`Updating table ${table.toTable}...`); - await dumpData(tempDir, table, options); - } + console.debug(`Updating table ${table.toTable}...`); + await dumpData(tempDir, table, options); + } - // Update files checksum - for (const file of updatableFiles) { - console.log(`Updating file ${file.name} checksum...`); - await Self.rawSql(` + // Update files checksum + for (const file of updatableFiles) { + console.log(`Updating file ${file.name} checksum...`); + await Self.rawSql(` UPDATE edi.fileConfig SET checksum = ? WHERE name = ?`, - [file.checksum, file.name], options); - } + [file.checksum, file.name], options); + } - await tx.commit(); + await tx.commit(); - // Clean files - try { - console.debug(`Cleaning files...`); - await fs.remove(tempPath); - } catch (error) { - if (error.code !== 'ENOENT') - throw e; - } + // Clean files + try { + console.debug(`Cleaning files...`); + await fs.remove(tempPath); + } catch (error) { + if (error.code !== 'ENOENT') + throw e; + } - return true; - } catch (error) { - await tx.rollback(); - throw error; - } - }; + return true; + } catch (error) { + await tx.rollback(); + throw error; + } + }; - let ftpClient; - async function getFtpClient() { - if (!ftpClient) { - const [ftpConfig] = await Self.rawSql('SELECT host, user, password FROM edi.ftpConfig'); - console.debug(`Openning FTP connection to ${ftpConfig.host}...\n`); + let ftpClient; + async function getFtpClient() { + if (!ftpClient) { + const [ftpConfig] = await Self.rawSql('SELECT host, user, password FROM edi.ftpConfig'); + console.debug(`Openning FTP connection to ${ftpConfig.host}...\n`); - const FtpClient = require('ftps'); + const FtpClient = require('ftps'); - ftpClient = new FtpClient({ - host: ftpConfig.host, - username: ftpConfig.user, - password: ftpConfig.password, - procotol: 'ftp', - additionalLftpCommands: 'set ssl:verify-certificate no' - }); - } + ftpClient = new FtpClient({ + host: ftpConfig.host, + username: ftpConfig.user, + password: ftpConfig.password, + procotol: 'ftp', + additionalLftpCommands: 'set ssl:verify-certificate no' + }); + } - return ftpClient; - } + return ftpClient; + } - async function getChecksum(file) { - const ftpClient = await getFtpClient(); - console.debug(`Checking checksum for file ${file.name}...`); + async function getChecksum(file) { + const ftpClient = await getFtpClient(); + console.debug(`Checking checksum for file ${file.name}...`); - ftpClient.cat(`codes/${file.name}.TXT`); + ftpClient.cat(`codes/${file.name}.TXT`); - const response = await new Promise((resolve, reject) => { - ftpClient.exec((err, response) => { - if (err || response.error) { - console.debug(`Error downloading checksum file... ${response.error}`); - return reject(err); - } + const response = await new Promise((resolve, reject) => { + ftpClient.exec((err, response) => { + if (err || response.error) { + console.debug(`Error downloading checksum file... ${response.error}`); + return reject(err); + } - resolve(response); - }); - }); + resolve(response); + }); + }); - if (response && response.data) { - const fileContents = response.data; - const rows = fileContents.split('\n'); - const row = rows[4]; - const columns = row.split(/\s+/); + if (response && response.data) { + const fileContents = response.data; + const rows = fileContents.split('\n'); + const row = rows[4]; + const columns = row.split(/\s+/); - let fileChecksum; - if (file.keyValue) - fileChecksum = columns[1]; + let fileChecksum; + if (file.keyValue) + fileChecksum = columns[1]; - if (!file.keyValue) - fileChecksum = columns[0]; + if (!file.keyValue) + fileChecksum = columns[0]; - return fileChecksum; - } - } + return fileChecksum; + } + } - async function downloadFile(remoteFile, tempFile) { - const ftpClient = await getFtpClient(); + async function downloadFile(remoteFile, tempFile) { + const ftpClient = await getFtpClient(); - ftpClient.get(remoteFile, tempFile); + ftpClient.get(remoteFile, tempFile); - return new Promise((resolve, reject) => { - ftpClient.exec((err, response) => { - if (err || response.error) { - console.debug(`Error downloading file... ${response.error}`); - return reject(err); - } + return new Promise((resolve, reject) => { + ftpClient.exec((err, response) => { + if (err || response.error) { + console.debug(`Error downloading file... ${response.error}`); + return reject(err); + } - resolve(response); - }); - }); - } + resolve(response); + }); + }); + } - async function extractFile(fileName, tempFile, tempDir) { - const JSZip = require('jszip'); + async function extractFile(fileName, tempFile, tempDir) { + const JSZip = require('jszip'); - try { - await fs.mkdir(tempDir); - console.debug(`Extracting file ${fileName}...`); - } catch (error) { - if (error.code !== 'EEXIST') - throw e; - } + try { + await fs.mkdir(tempDir); + console.debug(`Extracting file ${fileName}...`); + } catch (error) { + if (error.code !== 'EEXIST') + throw e; + } - const fileStream = await fs.readFile(tempFile); - if (fileStream) { - const zip = new JSZip(); - const zipContents = await zip.loadAsync(fileStream); + const fileStream = await fs.readFile(tempFile); + if (fileStream) { + const zip = new JSZip(); + const zipContents = await zip.loadAsync(fileStream); - if (!zipContents) return; + if (!zipContents) return; - const fileNames = Object.keys(zipContents.files); + const fileNames = Object.keys(zipContents.files); - for (const fileName of fileNames) { - const fileContent = await zip.file(fileName).async('nodebuffer'); - const dest = path.join(tempDir, fileName); - await fs.writeFile(dest, fileContent); - } - } - } + for (const fileName of fileNames) { + const fileContent = await zip.file(fileName).async('nodebuffer'); + const dest = path.join(tempDir, fileName); + await fs.writeFile(dest, fileContent); + } + } + } - async function dumpData(tempDir, table, options) { - const toTable = table.toTable; - const baseName = table.fileName; + async function dumpData(tempDir, table, options) { + const toTable = table.toTable; + const baseName = table.fileName; - console.log(`Emptying table ${toTable}...`); - const tableName = `edi.${toTable}`; - await Self.rawSql(`DELETE FROM ??`, [tableName]); + console.log(`Emptying table ${toTable}...`); + const tableName = `edi.${toTable}`; + await Self.rawSql(`DELETE FROM ??`, [tableName]); - const dirFiles = await fs.readdir(tempDir); - const files = dirFiles.filter(file => file.startsWith(baseName)); + const dirFiles = await fs.readdir(tempDir); + const files = dirFiles.filter(file => file.startsWith(baseName)); - for (const file of files) { - console.log(`Dumping data from file ${file}...`); + for (const file of files) { + console.log(`Dumping data from file ${file}...`); - const templatePath = path.join(__dirname, `./sql/${toTable}.sql`); - const sqlTemplate = await fs.readFile(templatePath, 'utf8'); - const filePath = path.join(tempDir, file); + const templatePath = path.join(__dirname, `./sql/${toTable}.sql`); + const sqlTemplate = await fs.readFile(templatePath, 'utf8'); + const filePath = path.join(tempDir, file); - await Self.rawSql(sqlTemplate, [filePath], options); - await Self.rawSql(` + await Self.rawSql(sqlTemplate, [filePath], options); + await Self.rawSql(` UPDATE edi.tableConfig SET updated = ? WHERE fileName = ? `, [Date.vnNew(), baseName], options); - } + } - console.log(`Updated table ${toTable}\n`); - } + console.log(`Updated table ${toTable}\n`); + } }; diff --git a/back/methods/vn-user/recover-password.js b/back/methods/vn-user/recover-password.js index 34f5dd545..b87bb14d4 100644 --- a/back/methods/vn-user/recover-password.js +++ b/back/methods/vn-user/recover-password.js @@ -24,6 +24,7 @@ module.exports = Self => { fields: ['email'], where: {name: user} }); + if (!account) return; user = account.email; } diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js new file mode 100644 index 000000000..41470dfea --- /dev/null +++ b/back/methods/vn-user/renew-token.js @@ -0,0 +1,39 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('renewToken', { + description: 'Checks if the token has more than renewPeriod seconds to live and if so, renews it', + accessType: 'WRITE', + accepts: [], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/renewToken`, + verb: 'POST' + } + }); + + Self.renewToken = async function(ctx) { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + const created = ctx.req.accessToken.created; + const tokenId = ctx.req.accessToken.id; + + const now = new Date(); + const differenceMilliseconds = now - created; + const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + + const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod']}); + + if (differenceSeconds <= accessTokenConfig.renewPeriod) + throw new UserError(`The renew period has not been exceeded`); + + await Self.logout(tokenId); + const user = await Self.findById(userId); + const accessToken = await user.createAccessToken(); + + return {token: accessToken.id, created: accessToken.created}; + }; +}; diff --git a/back/methods/vn-user/signIn.js b/back/methods/vn-user/signIn.js index da3172ae4..c98f1da54 100644 --- a/back/methods/vn-user/signIn.js +++ b/back/methods/vn-user/signIn.js @@ -27,33 +27,46 @@ module.exports = Self => { }); Self.signIn = async function(user, password) { - let models = Self.app.models; + const models = Self.app.models; + const usesEmail = user.indexOf('@') !== -1; let token; - let usesEmail = user.indexOf('@') !== -1; - let userInfo = usesEmail + const userInfo = usesEmail ? {email: user} : {username: user}; - let instance = await Self.findOne({ + const instance = await Self.findOne({ fields: ['username', 'password'], where: userInfo }); - let where = usesEmail + const where = usesEmail ? {email: user} : {name: user}; - let vnUser = await Self.findOne({ - fields: ['active'], + const vnUser = await Self.findOne({ + fields: ['id', 'active', 'passExpired'], where }); - let validCredentials = instance + const today = Date.vnNew(); + today.setHours(0, 0, 0, 0); + + const validCredentials = instance && await instance.hasPassword(password); if (validCredentials) { if (!vnUser.active) throw new UserError('User disabled'); + if (vnUser.passExpired && vnUser.passExpired.getTime() <= today.getTime()) { + const changePasswordToken = await models.AccessToken.create({ + scopes: ['change-password'], + userId: vnUser.id + }); + const err = new UserError('Pass expired', 'passExpired'); + err.details = {token: changePasswordToken}; + throw err; + } + try { await models.Account.sync(instance.username, password); } catch (err) { @@ -63,6 +76,6 @@ module.exports = Self => { let loginInfo = Object.assign({password}, userInfo); token = await Self.login(loginInfo, 'user'); - return {token: token.id}; + return {token: token.id, created: token.created}; }; }; diff --git a/back/methods/vn-user/specs/signIn.js b/back/methods/vn-user/specs/signIn.spec.js similarity index 91% rename from back/methods/vn-user/specs/signIn.js rename to back/methods/vn-user/specs/signIn.spec.js index b46c645d6..c3f4630c6 100644 --- a/back/methods/vn-user/specs/signIn.js +++ b/back/methods/vn-user/specs/signIn.spec.js @@ -9,7 +9,7 @@ describe('VnUser signIn()', () => { expect(login.token).toBeDefined(); - await models.VnUser.signOut(ctx); + await models.VnUser.logout(ctx.req.accessToken.id); }); it('should return the token if the user doesnt exist but the client does', async() => { @@ -19,7 +19,7 @@ describe('VnUser signIn()', () => { expect(login.token).toBeDefined(); - await models.VnUser.signOut(ctx); + await models.VnUser.logout(ctx.req.accessToken.id); }); }); diff --git a/back/methods/vn-user/specs/signOut.js b/back/methods/vn-user/specs/signOut.js deleted file mode 100644 index c84e86f05..000000000 --- a/back/methods/vn-user/specs/signOut.js +++ /dev/null @@ -1,42 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('VnUser signOut()', () => { - it('should logout and remove token after valid login', async() => { - let loginResponse = await models.VnUser.signOut('buyer', 'nightmare'); - let accessToken = await models.AccessToken.findById(loginResponse.token); - let ctx = {req: {accessToken: accessToken}}; - - let logoutResponse = await models.VnUser.signOut(ctx); - let tokenAfterLogout = await models.AccessToken.findById(loginResponse.token); - - expect(logoutResponse).toBeTrue(); - expect(tokenAfterLogout).toBeNull(); - }); - - it('should throw a 401 error when token is invalid', async() => { - let error; - let ctx = {req: {accessToken: {id: 'invalidToken'}}}; - - try { - response = await models.VnUser.signOut(ctx); - } catch (e) { - error = e; - } - - expect(error).toBeDefined(); - expect(error.statusCode).toBe(401); - }); - - it('should throw an error when no token is passed', async() => { - let error; - let ctx = {req: {accessToken: null}}; - - try { - response = await models.VnUser.signOut(ctx); - } catch (e) { - error = e; - } - - expect(error).toBeDefined(); - }); -}); diff --git a/back/model-config.json b/back/model-config.json index ff2bf5850..d945f3250 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -2,6 +2,14 @@ "AccountingType": { "dataSource": "vn" }, + "AccessTokenConfig": { + "dataSource": "vn", + "options": { + "mysql": { + "table": "salix.accessTokenConfig" + } + } + }, "Bank": { "dataSource": "vn" }, diff --git a/back/models/access-token-config.json b/back/models/access-token-config.json new file mode 100644 index 000000000..6d90a0f4d --- /dev/null +++ b/back/models/access-token-config.json @@ -0,0 +1,30 @@ +{ + "name": "AccessTokenConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "accessTokenConfig" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "renewPeriod": { + "type": "number", + "required": true + }, + "renewInterval": { + "type": "number", + "required": true + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 84ba11794..b58395acc 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -10,6 +10,9 @@ module.exports = function(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/renew-token')(Self); + + Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create'); // Validations @@ -107,4 +110,81 @@ module.exports = function(Self) { return email.send(); }); + + const _setPassword = Self.prototype.setPassword; + Self.prototype.setPassword = async function(newPassword, options, cb) { + if (cb === undefined && typeof options === 'function') { + cb = options; + options = undefined; + } + + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + options = myOptions; + + try { + await Self.rawSql(`CALL account.user_checkPassword(?)`, [newPassword], options); + await _setPassword.call(this, newPassword, options); + await this.updateAttribute('passExpired', null, options); + await Self.app.models.Account.sync(this.name, newPassword, null, options); + tx && await tx.commit(); + cb && cb(); + } catch (err) { + tx && await tx.rollback(); + if (cb) cb(err); else throw err; + } + }; + + Self.sharedClass._methods.find(method => method.name == 'changePassword') + .accessScopes = ['change-password']; + + // FIXME: https://redmine.verdnatura.es/issues/5761 + // Self.afterRemote('prototype.patchAttributes', async(ctx, instance) => { + // if (!ctx.args || !ctx.args.data.email) 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(':'); + + // class Mailer { + // async send(verifyOptions, cb) { + // const params = { + // url: verifyOptions.verifyHref, + // recipient: verifyOptions.to, + // lang: ctx.req.getLocale() + // }; + + // const email = new Email('email-verify', params); + // email.send(); + + // cb(null, verifyOptions.to); + // } + // } + + // 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); + // }); }; diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 17efc8ce6..61e42f77a 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -25,10 +25,7 @@ }, "password": { "type": "string", - "required": true, - "mysql": { - "columnName": "bcryptPassword" - } + "required": true }, "roleFk": { "type": "number", @@ -42,9 +39,6 @@ "lang": { "type": "string" }, - "bcryptPassword": { - "type": "string" - }, "active": { "type": "boolean" }, @@ -62,7 +56,10 @@ }, "hasGrant": { "type": "boolean" - } + }, + "passExpired": { + "type": "date" + } }, "relations": { "role": { @@ -121,5 +118,24 @@ "principalId": "$authenticated", "permission": "ALLOW" } - ] + ], + "scopes": { + "preview": { + "fields": [ + "id", + "name", + "username", + "roleFk", + "nickname", + "lang", + "active", + "created", + "updated", + "image", + "hasGrant", + "realm", + "email" + ] + } + } } diff --git a/back/process.yml b/back/process.yml index 38d2b9eaf..a29323240 100644 --- a/back/process.yml +++ b/back/process.yml @@ -4,4 +4,4 @@ apps: instances: 1 max_restarts: 3 restart_delay: 15000 - node_args: --tls-min-v1.0 + node_args: --tls-min-v1.0 --openssl-legacy-provider diff --git a/db/Dockerfile b/db/Dockerfile index 053fbcee6..448b8b03a 100644 --- a/db/Dockerfile +++ b/db/Dockerfile @@ -1,26 +1,18 @@ -FROM mariadb:10.7.5 +FROM mariadb:10.7.7 ENV MYSQL_ROOT_PASSWORD root ENV TZ Europe/Madrid ARG MOCKDATE=2001-01-01 11:00:00 ARG DEBIAN_FRONTEND=noninteractive -RUN apt-get update \ - && apt-get install -y --no-install-recommends curl ca-certificates \ - && curl -sL https://apt.verdnatura.es/conf/verdnatura.gpg | apt-key add - \ - && echo "deb http://apt.verdnatura.es/ jessie main" > /etc/apt/sources.list.d/vn.list \ - && apt-get update \ - && apt-get install -y vn-mariadb \ - && apt-get purge -y --auto-remove curl ca-certificates \ - && rm -rf /var/lib/apt/lists/* - COPY docker/docker.cnf /etc/mysql/conf.d/ COPY \ + docker/docker-start.sh \ docker/docker-init.sh \ - docker/docker-temp-start.sh \ docker/docker-temp-stop.sh \ docker/docker-dump.sh \ - docker/docker-start.sh \ + docker/docker-structure.sh \ + docker/docker-fixtures.sh \ /usr/local/bin/ RUN mkdir /mysql-data \ @@ -31,26 +23,16 @@ WORKDIR /docker-boot COPY \ import-changes.sh \ config.ini \ - dump/mysqlPlugins.sql \ dump/structure.sql \ dump/mockDate.sql \ dump/dumpedFixtures.sql \ ./ -RUN gosu mysql docker-init.sh \ - && docker-dump.sh mysqlPlugins \ - && docker-dump.sh structure \ - && sed -i -e 's/@mockDate/'"$MOCKDATE"'/g' mockDate.sql \ - && docker-dump.sh mockDate \ - && docker-dump.sh dumpedFixtures \ - && gosu mysql docker-temp-stop.sh - +RUN sed -i -e 's/@mockDate/'"$MOCKDATE"'/g' mockDate.sql \ + && gosu mysql docker-structure.sh COPY changes ./changes COPY dump/fixtures.sql ./ ARG STAMP=unknown -RUN gosu mysql docker-temp-start.sh \ - && ./import-changes.sh \ - && docker-dump.sh fixtures \ - && gosu mysql docker-temp-stop.sh +RUN gosu mysql docker-fixtures.sh RUN echo "[INFO] -> Import finished" \ && rm -rf /docker-boot diff --git a/db/changes/231801/00-userAcl.sql b/db/changes/231801/00-userAcl.sql index 64803bf18..9eb3ebf28 100644 --- a/db/changes/231801/00-userAcl.sql +++ b/db/changes/231801/00-userAcl.sql @@ -1,6 +1,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES - ('VnUser', '*', '*', 'ALLOW', 'ROLE', 'employee'), ('VnUser','acl','READ','ALLOW','ROLE','account'), ('VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'), ('VnUser','changePassword', 'WRITE', 'ALLOW', 'ROLE', 'account'), diff --git a/db/changes/232201/00-ticket_warehouse.sql b/db/changes/232401/00-ticket_warehouse.sql similarity index 100% rename from db/changes/232201/00-ticket_warehouse.sql rename to db/changes/232401/00-ticket_warehouse.sql diff --git a/db/changes/232401/00-userPassExpired.sql b/db/changes/232401/00-userPassExpired.sql new file mode 100644 index 000000000..2d4b45937 --- /dev/null +++ b/db/changes/232401/00-userPassExpired.sql @@ -0,0 +1,76 @@ +ALTER TABLE `account`.`user` ADD passExpired DATE DEFAULT NULL; + +DROP PROCEDURE `account`.`myUser_changePassword`; +DROP PROCEDURE `account`.`myUser_restorePassword`; +DROP PROCEDURE `account`.`user_changePassword`; +DROP PROCEDURE `account`.`user_restorePassword`; +DROP PROCEDURE `account`.`user_setPassword`; + +ALTER TABLE account.`user` CHANGE password password__ char(64) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL COMMENT 'Deprecated'; +ALTER TABLE account.`user` CHANGE bcryptPassword password varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL; + +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`user_beforeUpdate` + BEFORE UPDATE ON `user` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); + + IF !(NEW.`name` <=> OLD.`name`) THEN + CALL user_checkName (NEW.`name`); + END IF; + + IF !(NEW.`password` <=> OLD.`password`) THEN + SET NEW.lastPassChange = util.VN_NOW(); + END IF; +END$$ +DELIMITER ; + +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `account`.`accountDovecot` AS +select + `u`.`name` AS `name`, + `u`.`password` AS `password` +from + (`account`.`user` `u` +join `account`.`account` `a` on + (`a`.`id` = `u`.`id`)) +where + `u`.`active` <> 0; + +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `salix`.`User` AS +select + `account`.`user`.`id` AS `id`, + `account`.`user`.`realm` AS `realm`, + `account`.`user`.`name` AS `username`, + `account`.`user`.`password` AS `password`, + `account`.`user`.`email` AS `email`, + `account`.`user`.`emailVerified` AS `emailVerified`, + `account`.`user`.`verificationToken` AS `verificationToken` +from + `account`.`user`; + +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn`.`workerTimeControlUserInfo` AS +select + `u`.`id` AS `userFk`, + `w`.`firstName` AS `name`, + `w`.`lastName` AS `surname`, + `u`.`name` AS `user`, + `u`.`password` AS `password`, + `wd`.`departmentFk` AS `departmentFk`, + left(`c`.`fi`, + 8) AS `dni` +from + (((`account`.`user` `u` +join `vn`.`worker` `w` on + (`w`.`userFk` = `u`.`id`)) +join `vn`.`client` `c` on + (`c`.`id` = `u`.`id`)) +left join `vn`.`workerDepartment` `wd` on + (`wd`.`workerFk` = `w`.`id`)); diff --git a/db/changes/232402/00-hotFix_travelConfig.sql b/db/changes/232402/00-hotFix_travelConfig.sql new file mode 100644 index 000000000..65450a74d --- /dev/null +++ b/db/changes/232402/00-hotFix_travelConfig.sql @@ -0,0 +1,22 @@ +CREATE TABLE `vn`.`travelConfig` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `warehouseInFk` smallint(6) unsigned NOT NULL DEFAULT 8 COMMENT 'Warehouse de origen', + `warehouseOutFk` smallint(6) unsigned NOT NULL DEFAULT 60 COMMENT 'Warehouse destino', + `agencyFk` int(11) NOT NULL DEFAULT 1378 COMMENT 'Agencia por defecto', + `companyFk` int(10) unsigned NOT NULL DEFAULT 442 COMMENT 'Compañía por defecto', + PRIMARY KEY (`id`), + KEY `travelConfig_FK` (`warehouseInFk`), + KEY `travelConfig_FK_1` (`warehouseOutFk`), + KEY `travelConfig_FK_2` (`agencyFk`), + KEY `travelConfig_FK_3` (`companyFk`), + CONSTRAINT `travelConfig_FK` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `travelConfig_FK_1` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `travelConfig_FK_2` FOREIGN KEY (`agencyFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `travelConfig_FK_3` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('Entry', 'addFromPackaging', 'WRITE', 'ALLOW', 'ROLE', 'production'), + ('Entry', 'addFromBuy', 'WRITE', 'ALLOW', 'ROLE', 'production'), + ('Supplier', 'getItemsPackaging', 'READ', 'ALLOW', 'ROLE', 'production'); diff --git a/db/changes/232601/00-aclAccount.sql b/db/changes/232601/00-aclAccount.sql new file mode 100644 index 000000000..bf8106b98 --- /dev/null +++ b/db/changes/232601/00-aclAccount.sql @@ -0,0 +1,8 @@ +DELETE + FROM `salix`.`ACL` + WHERE model='Account' AND property='*' AND accessType='*'; + +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('Account', '*', 'WRITE', 'ALLOW', 'ROLE', 'sysadmin'), + ('Account', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/232601/00-aclMailAliasAccount.sql b/db/changes/232601/00-aclMailAliasAccount.sql new file mode 100644 index 000000000..619e9bb6e --- /dev/null +++ b/db/changes/232601/00-aclMailAliasAccount.sql @@ -0,0 +1,5 @@ +DELETE FROM `salix`.`ACL` WHERE model = 'MailAliasAccount'; +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('MailAliasAccount', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('MailAliasAccount', '*', 'WRITE', 'ALLOW', 'ROLE', 'itManagement'); diff --git a/db/changes/232601/00-aclMailForward.sql b/db/changes/232601/00-aclMailForward.sql new file mode 100644 index 000000000..afe2acec8 --- /dev/null +++ b/db/changes/232601/00-aclMailForward.sql @@ -0,0 +1,5 @@ +DELETE FROM `salix`.`ACL` WHERE model = 'MailForward'; +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('MailForward', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('MailForward', '*', 'WRITE', 'ALLOW', 'ROLE', 'itManagement'); diff --git a/db/changes/232601/00-aclRole.sql b/db/changes/232601/00-aclRole.sql new file mode 100644 index 000000000..e16f052be --- /dev/null +++ b/db/changes/232601/00-aclRole.sql @@ -0,0 +1,5 @@ +DELETE FROM `salix`.`ACL` WHERE model = 'Role'; +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('Role', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Role', '*', 'WRITE', 'ALLOW', 'ROLE', 'it'); diff --git a/db/changes/232601/00-aclVnUser.sql b/db/changes/232601/00-aclVnUser.sql new file mode 100644 index 000000000..39fa2cb14 --- /dev/null +++ b/db/changes/232601/00-aclVnUser.sql @@ -0,0 +1,10 @@ +DELETE + FROM `salix`.`ACL` + WHERE model = 'VnUser' AND property = '*' AND principalId = 'employee'; + +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('VnUser', '*', '*', 'ALLOW', 'ROLE', 'itManagement'), + ('VnUser', '__get__preview', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('VnUser', 'preview', '*', 'ALLOW', 'ROLE', 'employee'), + ('VnUser', 'create', '*', 'ALLOW', 'ROLE', 'itManagement'); diff --git a/db/changes/232601/00-aclVnUser_renewToken.sql b/db/changes/232601/00-aclVnUser_renewToken.sql new file mode 100644 index 000000000..aa20f7a82 --- /dev/null +++ b/db/changes/232601/00-aclVnUser_renewToken.sql @@ -0,0 +1,3 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('VnUser', 'renewToken', 'WRITE', 'ALLOW', 'ROLE', 'employee') diff --git a/db/changes/232601/00-entry_updateComission.sql b/db/changes/232601/00-entry_updateComission.sql new file mode 100644 index 000000000..5a25d72e8 --- /dev/null +++ b/db/changes/232601/00-entry_updateComission.sql @@ -0,0 +1,40 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_updateComission`(vCurrency INT) +BEGIN +/** + * Actualiza la comision de las entradas de hoy a futuro y las recalcula + * + * @param vCurrency id del tipo de moneda(SAR,EUR,USD,GBP,JPY) + */ + DECLARE vCurrencyName VARCHAR(25); + DECLARE vComission INT; + + CREATE OR REPLACE TEMPORARY TABLE tmp.recalcEntryCommision + SELECT e.id + FROM vn.entry e + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk + WHERE t.shipped >= util.VN_CURDATE() + AND e.currencyFk = vCurrency; + + SET vComission = currency_getCommission(vCurrency); + + UPDATE vn.entry e + JOIN tmp.recalcEntryCommision tmp ON tmp.id = e.id + SET e.commission = vComission; + + SELECT `name` INTO vCurrencyName + FROM currency + WHERE id = vCurrency; + + CALL entry_recalc(); + SELECT util.notification_send( + 'entry-update-comission', + JSON_OBJECT('currencyName', vCurrencyName, 'referenceCurrent', vComission), + account.myUser_getId() + ); + + DROP TEMPORARY TABLE tmp.recalcEntryCommision; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/changes/232601/00-packingSiteAdvanced.sql b/db/changes/232601/00-packingSiteAdvanced.sql new file mode 100644 index 000000000..0e33744cd --- /dev/null +++ b/db/changes/232601/00-packingSiteAdvanced.sql @@ -0,0 +1,71 @@ +CREATE TABLE `vn`.`packingSiteAdvanced` ( + `ticketFk` int(11), + `workerFk` int(10) unsigned, + PRIMARY KEY (`ticketFk`), + KEY `packingSiteAdvanced_FK_1` (`workerFk`), + CONSTRAINT `packingSiteAdvanced_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `packingSiteAdvanced_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + + +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('PackingSiteAdvanced', '*', '*', 'ALLOW', 'ROLE', 'production'); + + DROP PROCEDURE IF EXISTS `vn`.`packingSite_startCollection`; + +DELIMITER $$ +$$ +CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`packingSite_startCollection`(vSelf INT, vTicketFk INT) +proc: BEGIN +/** + * @param vSelf packingSite id + * @param vTicketFk A ticket id from the collection to start + */ + DECLARE vExists BOOL; + DECLARE vIsAdvanced BOOL; + DECLARE vNewCollectionFk INT; + DECLARE vOldCollectionFk INT; + DECLARE vIsPackingByOther BOOL; + + SELECT id, collectionFk + INTO vExists, vOldCollectionFk + FROM packingSite + WHERE id = vSelf; + + IF NOT vExists THEN + CALL util.throw('packingSiteNotExists'); + END IF; + + SELECT COUNT(*) > 0 + INTO vIsAdvanced + FROM packingSiteAdvanced + WHERE ticketFk = vTicketFk; + + IF vIsAdvanced THEN + LEAVE proc; + END IF; + + SELECT collectionFk INTO vNewCollectionFk + FROM ticketCollection WHERE ticketFk = vTicketFk; + + IF vOldCollectionFk IS NOT NULL + AND vOldCollectionFk <> vNewCollectionFk THEN + SELECT COUNT(*) > 0 + INTO vIsPackingByOther + FROM packingSite + WHERE id <> vSelf + AND collectionFk = vOldCollectionFk; + + IF NOT vIsPackingByOther AND NOT collection_isPacked(vOldCollectionFk) THEN + CALL util.throw('cannotChangeCollection'); + END IF; + END IF; + + UPDATE packingSite SET collectionFk = vNewCollectionFk + WHERE id = vSelf; +END$$ +DELIMITER ; + + + diff --git a/db/changes/232601/00-salix.sql b/db/changes/232601/00-salix.sql new file mode 100644 index 000000000..dc1ed69be --- /dev/null +++ b/db/changes/232601/00-salix.sql @@ -0,0 +1,10 @@ +CREATE TABLE `salix`.`accessTokenConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `renewPeriod` int(10) unsigned DEFAULT NULL, + `renewInterval` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `renewInterval`) + VALUES + (1, 21600, 300); diff --git a/db/changes/232601/01-invoiceOutPdf.sql b/db/changes/232601/01-invoiceOutPdf.sql new file mode 100644 index 000000000..38e0b8bbb --- /dev/null +++ b/db/changes/232601/01-invoiceOutPdf.sql @@ -0,0 +1,13 @@ +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES + ('InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'), + ('InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'); + +CREATE OR REPLACE TABLE vn.invoiceOutConfig ( + id INT UNSIGNED auto_increment NOT NULL, + parallelism int UNSIGNED DEFAULT 1 NOT NULL, + PRIMARY KEY (id) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci; diff --git a/db/changes/232801/.gitkeep b/db/changes/232801/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/docker/docker-temp-start.sh b/db/docker/docker-fixtures.sh similarity index 62% rename from db/docker/docker-temp-start.sh rename to db/docker/docker-fixtures.sh index fc067102f..0de6114d9 100755 --- a/db/docker/docker-temp-start.sh +++ b/db/docker/docker-fixtures.sh @@ -5,3 +5,6 @@ CMD=mysqld docker_setup_env "$CMD" docker_temp_server_start "$CMD" +bash import-changes.sh +docker-dump.sh fixtures +docker_temp_server_stop diff --git a/db/docker/docker-structure.sh b/db/docker/docker-structure.sh new file mode 100755 index 000000000..75a1c24f3 --- /dev/null +++ b/db/docker/docker-structure.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +. docker-init.sh +docker-dump.sh structure +docker-dump.sh mockDate +docker-dump.sh dumpedFixtures +. docker-temp-stop.sh diff --git a/db/docker/docker-temp-stop.sh b/db/docker/docker-temp-stop.sh old mode 100755 new mode 100644 diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index abb5516f7..2513972db 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -782,6 +782,38 @@ USE `sage`; -- Dumping data for table `TiposIva` -- +LOCK TABLES `taxType` WRITE; +/*!40000 ALTER TABLE `taxType` DISABLE KEYS */; +INSERT INTO `sage`.`taxType` (id, code, isIntracommunity) VALUES + (2, NULL, 0), + (4, 'national4', 0), + (5, NULL, 0), + (6, NULL, 1), + (7, NULL, 1), + (8, NULL, 1), + (10, 'national10', 0), + (11, NULL, 0), + (16, 'CEEServices21', 1), + (18, NULL, 0), + (20, 'national0', 0), + (21, 'national21', 0), + (22, 'import10', 0), + (26, NULL, 0), + (90, 'import21', 0), + (91, NULL, 0), + (92, NULL, 0), + (93, NULL, 0), + (94, NULL, 0), + (100, NULL, 0), + (108, NULL, 0), + (109, NULL, 0), + (110, NULL, 1), + (111, NULL, 0), + (112, NULL, 0), + (113, 'ISP21', 0), + (114, NULL, 0), + (115, 'import4', 0); + LOCK TABLES `TiposIva` WRITE; /*!40000 ALTER TABLE `TiposIva` DISABLE KEYS */; INSERT INTO `TiposIva` VALUES (2,0,'Operaciones no sujetas',0.0000000000,0.0000000000,0.0000000000,'','4770000020','','','','','','','95B21A93-5910-489D-83BB-C32788C9B19D','','','','','','','','','',0,0),(4,0,'I.V.A. 4%',0.0000000000,4.0000000000,0.0000000000,'4720000004','4770000004','','6310000000','','','','','9E6160D5-984E-4643-ACBC-1EBC3BF73360','','','','','','','','','',0,0),(5,0,'I.V.A. 4% y R.E. 0.5%',0.0000000000,4.0000000000,0.5000000000,'','4770000504','4770000405','','','','','','DBEFA562-63FB-4FFC-8171-64F0C6F065FF','','','','','','','','','',0,0),(6,0,'H.P. IVA 4% CEE',0.0000000000,4.0000000000,0.0000000000,'4721000004','4771000004','','','','','','','DD0ECBA8-2EF5-425E-911B-623580BADA77','','','','','','','','','',0,1),(7,0,'H.P. IVA 10% CEE',0.0000000000,10.0000000000,0.0000000000,'4721000011','4771000010','','','','','','','593208CD-6F28-4489-B6EC-907AD689EAC9','','','','','','','','','',0,1),(8,0,'H.P. IVA 21% CEE',0.0000000000,21.0000000000,0.0000000000,'4721000021','4771000021','','','','','','','27061852-9BC1-4C4F-9B6E-69970E208F23','','','','','','','','','',0,1),(10,0,'I.V.A. 10% Nacional',0.0000000000,10.0000000000,0.0000000000,'4720000011','4770000010','','6290000553','','','','','828A9D6F-5C01-4C3A-918A-B2E4482830D3','','','','','','','','','',0,0),(11,0,'I.V.A. 10% y R.E. 1,4%',0.0000000000,10.0000000000,1.4000000000,'','4770000101','4770000110','','','','','','C1F2D910-83A1-4191-A76C-8B3D7AB98348','','','','','','','','','',0,0),(16,0,'I.V.A. Adqui. servicios CEE',0.0000000000,21.0000000000,0.0000000000,'4721000015','4771000016','','','','','','','E3EDE961-CE8F-41D4-9E6C-D8BCD32275A1','','','','','','','','','',0,1),(18,0,'H.P. Iva Importación 0% ISP',0.0000000000,0.0000000000,0.0000000000,'4720000005','4770000005','','','','','','','27AD4158-2349-49C2-B53A-A4E0EFAC5D09','','','','','','','','','',0,0),(20,0,'I.V.A 0% Nacional',0.0000000000,0.0000000000,0.0000000000,'4720000000','','','','','','','','B90B0FBD-E513-4F04-9721-C873504E08DF','','','','','','','','','',0,0),(21,0,'I.V.A. 21%',0.0000000000,21.0000000000,0.0000000000,'4720000021','4770000021','4770000000','','','','','','BA8C4E28-DCFA-4F7B-AE4F-CA044626B55E','','','','','','','','','',0,0),(22,0,'IVA 10% importaciones',0.0000000000,10.0000000000,0.0000000000,'4722000010','','','','','','','','540450A8-4B41-4607-96D1-E7F296FB6933','','','','','','','','','',0,0),(26,0,'I.V.A. 21% y R.E. 5,2%',0.0000000000,21.0000000000,5.2000000000,'4720000021','4770000215','4770000521','631000000','','','','','2BC0765F-7739-49AE-A5F0-28B648B81677','','','','','','','','','',0,0),(90,0,'IVA 21% importaciones',0.0000000000,21.0000000000,0.0000000000,'4722000021','','','','','','','','EB675F91-5FF2-4E26-A31E-EEB674125945','','','','','','','','','',0,0),(91,0,'IVA 0% importaciones',0.0000000000,0.0000000000,0.0000000000,'4723000000','','','','','','','','5E5EFA56-2A99-4D54-A16B-5D818274CA18','','','','','','','','','',0,0),(92,0,'8.5% comp. ganadera o pesquera',0.0000000000,8.5000000000,0.0000000000,'4720000000','4770000000','477000000','631000000','','','','','','','','','','','','','','',0,0),(93,0,'12% com. agrícola o forestal',0.0000000000,12.0000000000,0.0000000000,'4720000012','','','','','','','','267B1DDB-247F-4A71-AB95-3349FEFC5F92','','','','','','','','','',0,0),(94,0,'10,5% com. ganadera o pesquera',0.0000000000,10.5000000000,0.0000000000,'4770000000','4720000000','631000000','477000000','','','','','','','','','','','','','','',0,0),(100,0,'HP IVA SOPORTADO 5%',0.0000000000,5.0000000000,0.0000000000,'4720000055','','','','','','','','3AD36CB2-4172-4CC9-9F87-2BF2B56AAC80','','','','','','','','','',0,0),(108,0,'I.V.A. 8%',0.0000000000,8.0000000000,0.0000000000,'4720000000','4770000000','477000000','631000000','','','','','','','','','','','','','','',0,0),(109,0,'I.V.A. 8% y R.E. 1%',0.0000000000,8.0000000000,1.0000000000,'4720000000','4770000000','477000000','631000000','','','','','','','','','','','','','','',0,0),(110,0,'HP IVA Devengado Exento CEE',0.0000000000,0.0000000000,0.0000000000,'','4771000000','','','','','','','C605BC32-E161-42FD-83F3-3A66B1FBE399','','','','','','','','','',0,1),(111,0,'H.P. Iva Devengado Exento Ser',0.0000000000,0.0000000000,0.0000000000,'','4771000001','','','','','','','F1AEC4DC-AFE5-498E-A713-2648FFB6DA32','','','','','','','','','',0,0),(112,0,'H.P. IVA Devengado en exportac',0.0000000000,0.0000000000,0.0000000000,'','4770000002','','','','','','','F980AE74-BF75-4F4C-927F-0CCCE0DB8D15','','','','','','','','','',0,0),(113,0,'HP DEVENGADO 21 ISP ',0.0000000000,21.0000000000,0.0000000000,'4720000006','4770000006','','','','','','','728D7A76-E936-438C-AF05-3CA38FE16EA5','','','','','','','','','',0,0),(114,0,'HP.IVA NO DEDUCIBLE 10%',0.0000000000,0.0000000000,0.0000000000,'4720000026','','','','','','','','','','','','','','','','','',0,0),(115,0,'H.P. IVA Soportado Impor 4% ',0.0000000000,4.0000000000,0.0000000000,'4722000004','','','','','','','','','','','','','','','','','',0,0); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 99ed993f0..1e096b3c1 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -71,8 +71,8 @@ INSERT INTO `account`.`roleConfig`(`id`, `mysqlPassword`, `rolePrefix`, `userPre CALL `account`.`role_sync`; -INSERT INTO `account`.`user`(`id`,`name`, `nickname`, `password`,`role`,`active`,`email`, `lang`, `image`, `bcryptPassword`) - SELECT id, name, CONCAT(name, 'Nick'),MD5('nightmare'), id, 1, CONCAT(name, '@mydomain.com'), 'en', '4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2' +INSERT INTO `account`.`user`(`id`,`name`, `nickname`, `role`,`active`,`email`, `lang`, `image`, `password`) + SELECT id, name, CONCAT(name, 'Nick'), id, 1, CONCAT(name, '@mydomain.com'), 'en', '4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2' FROM `account`.`role` WHERE id <> 20 ORDER BY id; @@ -98,20 +98,24 @@ INSERT INTO `hedera`.`tpvConfig`(`id`, `currency`, `terminal`, `transactionType` VALUES (1, 978, 1, 0, 2000, 9, 0); -INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `bcryptPassword`, `password`,`role`,`active`,`email`,`lang`, `image`) +INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `password`,`role`,`active`,`email`,`lang`, `image`) VALUES - (1101, 'BruceWayne', 'Bruce Wayne', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'BruceWayne@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), - (1102, 'PetterParker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'PetterParker@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (1103, 'ClarkKent', 'Clark Kent', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'ClarkKent@mydomain.com', 'fr', 'e7723f0b24ff05b32ed09d95196f2f29'), - (1104, 'TonyStark', 'Tony Stark', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'TonyStark@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), - (1105, 'MaxEisenhardt', 'Max Eisenhardt', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt', 'e7723f0b24ff05b32ed09d95196f2f29'), - (1106, 'DavidCharlesHaller', 'David Charles Haller', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'DavidCharlesHaller@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (1107, 'HankPym', 'Hank Pym', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'HankPym@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (1108, 'CharlesXavier', 'Charles Xavier', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'CharlesXavier@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (1109, 'BruceBanner', 'Bruce Banner', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'BruceBanner@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (1110, 'JessicaJones', 'Jessica Jones', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'JessicaJones@mydomain.com', 'en', NULL), - (1111, 'Missing', 'Missing', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'en', NULL), - (1112, 'Trash', 'Trash', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'en', NULL); + (1101, 'BruceWayne', 'Bruce Wayne', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'BruceWayne@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1102, 'PetterParker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'PetterParker@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1103, 'ClarkKent', 'Clark Kent', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'ClarkKent@mydomain.com', 'fr', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1104, 'TonyStark', 'Tony Stark', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'TonyStark@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1105, 'MaxEisenhardt', 'Max Eisenhardt', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1106, 'DavidCharlesHaller', 'David Charles Haller', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'DavidCharlesHaller@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1107, 'HankPym', 'Hank Pym', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'HankPym@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1108, 'CharlesXavier', 'Charles Xavier', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'CharlesXavier@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1109, 'BruceBanner', 'Bruce Banner', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'BruceBanner@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1110, 'JessicaJones', 'Jessica Jones', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 1, 1, 'JessicaJones@mydomain.com', 'en', NULL), + (1111, 'Missing', 'Missing', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 0, NULL, 'en', NULL), + (1112, 'Trash', 'Trash', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 0, NULL, 'en', NULL); + +UPDATE account.`user` + SET passExpired = DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR) + WHERE name = 'maintenance'; INSERT INTO `account`.`mailAlias`(`id`, `alias`, `description`, `isPublic`) VALUES @@ -599,6 +603,9 @@ UPDATE `vn`.`invoiceOut` SET ref = 'T3333333' WHERE id = 3; UPDATE `vn`.`invoiceOut` SET ref = 'T4444444' WHERE id = 4; UPDATE `vn`.`invoiceOut` SET ref = 'A1111111' WHERE id = 5; +INSERT INTO vn.invoiceOutConfig + SET parallelism = 8; + INSERT INTO `vn`.`invoiceOutTax` (`invoiceOutFk`, `taxableBase`, `vat`, `pgcFk`) VALUES (1, 895.76, 89.58, 4722000010), @@ -2732,7 +2739,8 @@ INSERT INTO `util`.`notification` (`id`, `name`, `description`) (1, 'print-email', 'notification fixture one'), (2, 'invoice-electronic', 'A electronic invoice has been generated'), (3, 'not-main-printer-configured', 'A printer distinct than main has been configured'), - (4, 'supplier-pay-method-update', 'A supplier pay method has been updated'); + (4, 'supplier-pay-method-update', 'A supplier pay method has been updated'), + (5, 'modified-entry', 'An entry has been modified'); INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) VALUES @@ -2786,7 +2794,9 @@ INSERT INTO `vn`.`ticketLog` (`originFk`, userFk, `action`, changedModel, oldIns (7, 18, 'update', 'Sale', '{"quantity":1}', '{"quantity":10}', 1, NULL), (7, 18, 'update', 'Ticket', '{"quantity":1,"concept":"Chest ammo box"}', '{"quantity":10,"concept":"Chest ammo box"}', 1, NULL), (7, 18, 'update', 'Sale', '{"price":3}', '{"price":5}', 1, NULL), - (7, 18, 'update', NULL, NULL, NULL, NULL, "Cambio cantidad Melee weapon heavy shield 1x0.5m de '5' a '10'"); + (7, 18, 'update', NULL, NULL, NULL, NULL, "Cambio cantidad Melee weapon heavy shield 1x0.5m de '5' a '10'"), + (16, 9, 'update', 'Sale', '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', '{"quantity":8,"concept":"Shield", "price": 10.5, "itemFk": 1}' , 5689, 'Shield'); + INSERT INTO `vn`.`ticketLog` (originFk, userFk, `action`, creationDate, changedModel, changedModelId, changedModelValue, oldInstance, newInstance, description) VALUES @@ -2800,7 +2810,6 @@ INSERT INTO `vn`.`ticketLog` (originFk, userFk, `action`, creationDate, changedM (1, 18, 'select', '2000-12-27 03:40:30', 'Ticket', 45, NULL , NULL, NULL, NULL), (1, 18, 'insert', '2000-04-10 09:40:15', 'Sale', 5689, 'Shield' , NULL, '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', NULL), (1, 18, 'insert', '1999-05-09 10:00:00', 'Ticket', 45, 'Super Man' , NULL, '{"id":45,"clientFk":8608,"warehouseFk":60,"shipped":"2023-05-16T22:00:00.000Z","nickname":"Super Man","addressFk":48637,"isSigned":true,"isLabeled":true,"isPrinted":true,"packages":0,"hour":0,"created":"2023-05-16T11:42:56.000Z","isBlocked":false,"hasPriority":false,"companyFk":442,"agencyModeFk":639,"landed":"2023-05-17T22:00:00.000Z","isBoxed":true,"isDeleted":true,"zoneFk":713,"zonePrice":13,"zoneBonus":0}', NULL); - INSERT INTO `vn`.`osTicketConfig` (`id`, `host`, `user`, `password`, `oldStatus`, `newStatusId`, `day`, `comment`, `hostDb`, `userDb`, `passwordDb`, `portDb`, `responseType`, `fromEmailId`, `replyTo`) VALUES (0, 'http://localhost:56596/scp', 'ostadmin', 'Admin1', '1,6', 3, 60, 'Este CAU se ha cerrado automáticamente. Si el problema persiste responda a este mensaje.', 'localhost', 'osticket', 'osticket', 40003, 'reply', 1, 'all'); @@ -2890,6 +2899,10 @@ INSERT INTO `vn`.`wagonTypeTray` (`id`, `typeFk`, `height`, `colorFk`) (2, 1, 50, 2), (3, 1, 0, 3); +INSERT INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `renewInterval`) + VALUES + (1, 21600, 300); + INSERT INTO `vn`.`travelConfig` (`id`, `warehouseInFk`, `warehouseOutFk`, `agencyFk`, `companyFk`) VALUES (1, 1, 1, 1, 442); @@ -2897,3 +2910,10 @@ INSERT INTO `vn`.`travelConfig` (`id`, `warehouseInFk`, `warehouseOutFk`, `agenc INSERT INTO `vn`.`buyConfig` (`id`, `monthsAgo`) VALUES (1, 6); + +INSERT INTO `vn`.`invoiceInSerial` (`code`, `description`, `cplusTerIdNifFk`, `taxAreaFk`) + VALUES + ('C', 'Asgard', 1, 'WORLD'), + ('E', 'Midgard', 1, 'CEE'), + ('R', 'Jotunheim', 1, 'NATIONAL'), + ('W', 'Vanaheim', 1, 'WORLD'); diff --git a/db/dump/mockDate.sql b/db/dump/mockDate.sql index 2b4c33d74..5d4d0c351 100644 --- a/db/dump/mockDate.sql +++ b/db/dump/mockDate.sql @@ -1,30 +1,19 @@ -DROP FUNCTION IF EXISTS `util`.`mockTime`; DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` FUNCTION `util`.`mockTime`() RETURNS datetime + +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `util`.`mockTime`() RETURNS datetime DETERMINISTIC BEGIN RETURN CONVERT_TZ('@mockDate', 'utc', 'Europe/Madrid'); END$$ -DELIMITER ; -DROP FUNCTION IF EXISTS `util`.`mockUtcTime`; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` FUNCTION `util`.`mockUtcTime`() RETURNS datetime +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `util`.`mockUtcTime`() RETURNS datetime DETERMINISTIC BEGIN RETURN CONVERT_TZ('@mockDate', 'utc', 'Europe/Madrid'); END$$ -DELIMITER ; -DROP FUNCTION IF EXISTS `util`.`mockTimeBase`; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` FUNCTION `util`.`mockTimeBase`(vIsUtc BOOL) RETURNS datetime +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `util`.`mockTimeBase`(vIsUtc BOOL) RETURNS datetime DETERMINISTIC BEGIN RETURN CONVERT_TZ('@mockDate', 'utc', 'Europe/Madrid'); diff --git a/db/dump/mysqlPlugins.sql b/db/dump/mysqlPlugins.sql deleted file mode 100644 index c3b6f6ee4..000000000 --- a/db/dump/mysqlPlugins.sql +++ /dev/null @@ -1,4 +0,0 @@ - --- Import compiled functions -CREATE AGGREGATE FUNCTION minacum RETURNS INT SONAME 'minacum.so'; -CREATE AGGREGATE FUNCTION multimax RETURNS INT SONAME 'multimax.so'; diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 3ce7f7bb5..b07e88fde 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -15620,6 +15620,18 @@ CREATE TABLE `ClavesOperacion` ( -- -- Table structure for table `Municipios` -- +DROP TABLE IF EXISTS `taxType`; + +CREATE TABLE `taxType` ( + id INT(11) NOT NULL, + code VARCHAR(25) DEFAULT NULL NULL, + isIntracommunity TINYINT(1) DEFAULT FALSE NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `taxType_UN` (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Coincidencia del id con Sage.TiposIVA.CodigoIva(propia de Sage), en ningún caso vincular mediate FK'; + +ALTER TABLE `sage`.`taxType` ADD CONSTRAINT taxType_PK PRIMARY KEY IF NOT EXISTS (id); +ALTER TABLE `sage`.`taxType` ADD CONSTRAINT taxType_UN UNIQUE KEY IF NOT EXISTS (code); DROP TABLE IF EXISTS `Municipios`; /*!40101 SET @saved_cs_client = @@character_set_client */; @@ -22074,12 +22086,14 @@ CREATE TABLE `autonomy` ( `name` varchar(100) NOT NULL, `countryFk` mediumint(8) unsigned NOT NULL, `geoFk` int(11) DEFAULT NULL, + `isUeeMember` tinyint(1) DEFAULT NULL, + `hasDailyInvoice` tinyint(4) DEFAULT NULL, PRIMARY KEY (`id`), KEY `autonomy_FK` (`countryFk`), KEY `autonomy_FK_1` (`geoFk`), CONSTRAINT `autonomy_FK` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `autonomy_FK_1` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Comunidades autónomas o su equivalente en otros paises. Agrupación de provincias, en una categoria inferior a country.'; +) ENGINE=InnoDB AUTO_INCREMENT=109 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Comunidades autónomas o su equivalente en otros paises. Agrupación de provincias, en una categoria inferior a country.'; /*!40101 SET character_set_client = @saved_cs_client */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -28805,7 +28819,10 @@ CREATE TABLE `expence` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; - +ALTER TABLE `vn`.`expence` + ADD code VARCHAR(25) DEFAULT NULL NULL; +ALTER TABLE `vn`.`expence` + ADD CONSTRAINT expence_UN UNIQUE KEY IF NOT EXISTS (code); -- -- Table structure for table `farming` -- @@ -57317,7 +57334,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingMain` */; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceIn_booking` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -57326,28 +57343,71 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; + + + DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInBookingMain`(vInvoiceInId INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceIn_booking`(vSelf INT) BEGIN - DECLARE vTotalAmount,vTotalAmountDivisa DECIMAL(10,2); - DECLARE vBookNumber,vSerialNumber INT; - DECLARE vRate DECIMAL(10,4); + DECLARE vBookNumber INT; - CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber); - - SELECT SUM(iit.taxableBase * IF( i.serial= 'R' AND ti.Iva <> 'HP DEVENGADO 21 ISP', 1 +(ti.PorcentajeIva/100),1)), - SUM(iit.foreignValue * IF( i.serial= 'R', 1 + (ti.PorcentajeIva/100),1)), - iit.taxableBase/iit.foreignValue - INTO vTotalAmount, vTotalAmountDivisa, vRate - FROM newInvoiceIn i - JOIN invoiceInTax iit ON iit.invoiceInFk = i.id - LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk; + DROP TEMPORARY TABLE IF EXISTS tInvoiceIn; + CREATE TEMPORARY TABLE tInvoiceIn + ENGINE = MEMORY + SELECT ii.bookEntried, + iit.foreignValue, + ii.companyFk, + ii.expenceFkDeductible, + iit.taxableBase, + ii.serial, + ii.issued, + ii.operated, + ii.supplierRef, + ii.cplusTrascendency472Fk, + ii.cplusTaxBreakFk, + ii.cplusSubjectOpFk, + ii.cplusInvoiceType472Fk, + ii.cplusRectificationTypeFk, + ii.booked, + IFNULL(a.isUeeMember, c.isUeeMember) isUeeMember, + (c.id = cc.id) isSameCountry, + s.account supplierAccount, + s.name supplierName, + s.nif, + iit.taxTypeSageFk, + tt.code taxCode, + ti.Iva, + ti.CuentaIvaSoportado, + ti.PorcentajeIva, + ti.CuentaIvaRepercutido, + ttr.ClaveOperacionDefecto, + iis.cplusTerIdNifFk, + cit.id invoicesCount, + e.code, + e.isWithheld, + e.id expenceFk, + e.name expenceName + FROM invoiceIn ii + JOIN supplier s ON s.id = ii.supplierFk + LEFT JOIN province p ON p.id = s.provinceFk + LEFT JOIN autonomy a ON a.id = p.autonomyFk + JOIN country c ON c.id = s.countryFk + JOIN supplier sc ON sc.id = ii.companyFk + JOIN country cc ON cc.id = sc.countryFk + JOIN invoiceInSerial iis ON iis.code = ii.serial + JOIN cplusInvoiceType472 cit ON cit.id = ii.cplusInvoiceType472Fk + LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk + LEFT JOIN expence e ON e.id = iit.expenceFk + LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk + LEFT JOIN sage.taxType tt ON tt.id = ti.CodigoIva + WHERE ii.id = vSelf; CALL vn.ledger_next(vBookNumber); -- Apunte del proveedor - - INSERT INTO XDiario(ASIEN, + INSERT INTO XDiario( + ASIEN, FECHA, SUBCTA, EUROHABER, @@ -57356,24 +57416,30 @@ BEGIN HABERME, NFACTICK, CLAVE, - empresa_id - ) + empresa_id) SELECT - vBookNumber, - n.bookEntried, - s.supplierAccount, - vTotalAmount EUROHABER, - n.conceptWithSupplier, - vRate, - vTotalAmountDivisa, - n.invoicesCount, - vInvoiceInId, - n.companyFk - FROM newInvoiceIn n - JOIN newSupplier s; + vBookNumber ASIEN, + tii.bookEntried FECHA, + tii.supplierAccount SUBCTA, + SUM(tii.taxableBase * + IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21') + AND tii.taxTypeSageFk IS NOT NULL), + 1 + (tii.PorcentajeIva / 100), + 1)) EUROHABER, + CONCAT('s/fra', + RIGHT(tii.supplierRef, 8), + ':', + LEFT(tii.supplierName, 10)) CONCEPTO, + CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10,4)) CAMBIO, + SUM(tii.foreignValue * IF(tii.serial = 'R', 1 + (tii.PorcentajeIva / 100), 1)) HABERME, + tii.invoicesCount NFACTICK, + vSelf CLAVE, + tii.companyFk empresa_id + FROM tInvoiceIn tii; -- Línea de Gastos - INSERT INTO XDiario ( ASIEN, + INSERT INTO XDiario( + ASIEN, FECHA, SUBCTA, CONTRA, @@ -57384,30 +57450,29 @@ BEGIN DEBEME, HABERME, NFACTICK, - empresa_id - ) + empresa_id) SELECT vBookNumber ASIEN, - n.bookEntried FECHA, - IF(e.isWithheld , LPAD(RIGHT(s.supplierAccount,5),10,iit.expenceFk),iit.expenceFk) SUBCTA, - s.supplierAccount CONTRA, - IF(e.isWithheld AND iit.taxableBase < 0, NULL, ROUND(SUM(iit.taxableBase),2)) EURODEBE, - IF(e.isWithheld AND iit.taxableBase < 0,ROUND(SUM(-iit.taxableBase),2),NULL) EUROHABER, - n.conceptWithSupplier CONCEPTO, - vRate, - IF(e.isWithheld,NULL,ABS(ROUND(SUM(iit.foreignValue),2))) DEBEME, - IF(e.isWithheld,ABS(ROUND(SUM(iit.foreignValue),2)),NULL) HABERME, - n.invoicesCount NFACTICK, - n.companyFk empresa_id - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax iit ON iit.invoiceInFk = n.id - JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = iit.expenceFk - WHERE e.name != 'Suplidos Transitarios nacionales' - GROUP BY iit.expenceFk; + tii.bookEntried FECHA, + IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenceFk),tii.expenceFk) SUBCTA, + tii.supplierAccount CONTRA, + IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE, + IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER, + CONCAT('s/fra', + RIGHT(tii.supplierRef, 8), + ':', + LEFT(tii.supplierName, 10)) CONCEPTO, + CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10, 4)) CAMBIO, + IF(tii.isWithheld, NULL,ABS(ROUND(SUM(tii.foreignValue), 2))) DEBEME, + IF(tii.isWithheld, ABS(ROUND(SUM(tii.foreignValue), 2)) ,NULL) HABERME, + tii.invoicesCount NFACTICK, + tii.companyFk empresa_id + FROM tInvoiceIn tii + WHERE tii.code IS NULL OR tii.code <> 'suplido' + GROUP BY tii.expenceFk; -- Líneas de IVA - - INSERT INTO XDiario( ASIEN, + INSERT INTO XDiario( + ASIEN, FECHA, SUBCTA, CONTRA, @@ -57434,56 +57499,50 @@ BEGIN TERNIF, TERNOM, FECREGCON, - empresa_id - ) + empresa_id) SELECT vBookNumber ASIEN, - n.bookEntried FECHA, - IF(n.expenceFkDeductible>0, n.expenceFkDeductible, ti.CuentaIvaSoportado) SUBCTA, - s.supplierAccount CONTRA, - SUM(ROUND(ti.PorcentajeIva * it.taxableBase / 100 /* + 0.0001*/ , 2)) EURODEBE, - SUM(it.taxableBase) BASEEURO, - GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, - vSerialNumber FACTURA, - ti.PorcentajeIva IVA, - IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR, - n.serial SERIE, - ttr.ClaveOperacionDefecto, - n.issued FECHA_EX, - n.operated FECHA_OP, - n.invoicesCount NFACTICK, - n.supplierRef FACTURAEX, + tii.bookEntried FECHA, + IF(tii.expenceFkDeductible>0, tii.expenceFkDeductible, tii.CuentaIvaSoportado) SUBCTA, + tii.supplierAccount CONTRA, + SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100, 2)) EURODEBE, + SUM(tii.taxableBase) BASEEURO, + GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO, + vSelf FACTURA, + tii.PorcentajeIva IVA, + IF(tii.isUeeMember AND eWithheld.id IS NULL, '', '*') AUXILIAR, + tii.serial SERIE, + tii.ClaveOperacionDefecto, + tii.issued FECHA_EX, + tii.operated FECHA_OP, + tii.invoicesCount NFACTICK, + tii.supplierRef FACTURAEX, TRUE L340, - (isSameCountry OR NOT isUeeMember) LRECT349, - n.cplusTrascendency472Fk TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - n.cplusInvoiceType472Fk TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - n.booked FECREGCON, - n.companyFk - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax it ON n.id = it.invoiceInFk - JOIN sage.TiposIva ti ON ti.CodigoIva = it.taxTypeSageFk - JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = it.transactionTypeSageFk - JOIN invoiceInSerial iis ON iis.code = n.serial - JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = it.expenceFk + (tii.isSameCountry OR NOT tii.isUeeMember) LRECT349, + tii.cplusTrascendency472Fk TIPOCLAVE, + tii.cplusTaxBreakFk TIPOEXENCI, + tii.cplusSubjectOpFk TIPONOSUJE, + tii.cplusInvoiceType472Fk TIPOFACT, + tii.cplusRectificationTypeFk TIPORECTIF, + tii.cplusTerIdNifFk TERIDNIF, + tii.nif TERNIF, + tii.supplierName TERNOM, + tii.booked FECREGCON, + tii.companyFk + FROM tInvoiceIn tii LEFT JOIN ( - SELECT eWithheld.id - FROM invoiceInTax hold - JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld - WHERE hold.invoiceInFk = vInvoiceInId LIMIT 1 + SELECT e.id + FROM tInvoiceIn tii + JOIN expence e ON e.id = tii.expenceFk + WHERE e.isWithheld + LIMIT 1 ) eWithheld ON TRUE - WHERE it.taxTypeSageFk IS NOT NULL - AND it.taxTypeSageFk NOT IN (22, 90) - GROUP BY ti.PorcentajeIva, e.id; + WHERE tii.taxTypeSageFk IS NOT NULL + AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21')) + GROUP BY tii.PorcentajeIva, tii.expenceFk; -- Línea iva inversor sujeto pasivo - - INSERT INTO XDiario( ASIEN, + INSERT INTO XDiario( + ASIEN, FECHA, SUBCTA, CONTRA, @@ -57509,50 +57568,43 @@ BEGIN TERIDNIF, TERNIF, TERNOM, - empresa_id - ) + empresa_id) SELECT vBookNumber ASIEN, - n.bookEntried FECHA, - ti.CuentaIvaRepercutido SUBCTA, - s.supplierAccount CONTRA, - SUM(ROUND(ti.PorcentajeIva * it.taxableBase / 100,2)) EUROHABER, - ROUND(SUM(it.taxableBase),2) BASEEURO, - GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, - vSerialNumber FACTURA, - ti.PorcentajeIva IVA, + tii.bookEntried FECHA, + tii.CuentaIvaRepercutido SUBCTA, + tii.supplierAccount CONTRA, + SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100,2)) EUROHABER, + ROUND(SUM(tii.taxableBase),2) BASEEURO, + GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO, + vSelf FACTURA, + tii.PorcentajeIva IVA, '*' AUXILIAR, - n.serial SERIE, - ttr.ClaveOperacionDefecto, - n.issued FECHA_EX, - n.operated FECHA_OP, - n.invoicesCount NFACTICK, - n.supplierRef FACTURAEX, + tii.serial SERIE, + tii.ClaveOperacionDefecto, + tii.issued FECHA_EX, + tii.operated FECHA_OP, + tii.invoicesCount NFACTICK, + tii.supplierRef FACTURAEX, FALSE L340, - (isSameCountry OR NOT isUeeMember) LRECT349, + (tii.isSameCountry OR NOT tii.isUeeMember) LRECT349, 1 TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - n.cplusInvoiceType472Fk TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - n.companyFk - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax it ON n.id = it.invoiceInFk - JOIN sage.TiposIva ti ON ti.CodigoIva = it.taxTypeSageFk - JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = it.transactionTypeSageFk - JOIN invoiceInSerial iis ON iis.code = n.serial - JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = it.expenceFk - WHERE ti.Iva = 'HP DEVENGADO 21 ISP' OR MID(s.account, 4, 1) = '1' - GROUP BY ti.PorcentajeIva, e.id; + tii.cplusTaxBreakFk TIPOEXENCI, + tii.cplusSubjectOpFk TIPONOSUJE, + tii.cplusInvoiceType472Fk TIPOFACT, + tii.cplusRectificationTypeFk TIPORECTIF, + tii.cplusTerIdNifFk TERIDNIF, + tii.nif TERNIF, + tii.supplierName TERNOM, + tii.companyFk + FROM tInvoiceIn tii + WHERE tii.taxCode = 'ISP21' OR MID(tii.supplierAccount, 4, 1) = '1' + AND tii.taxTypeSageFk IS NOT NULL + GROUP BY tii.PorcentajeIva, tii.expenceFk; -- Actualización del registro original UPDATE invoiceIn ii - JOIN newInvoiceIn ni ON ii.id = ni.id - SET ii.serialNumber = vSerialNumber, - ii.isBooked = TRUE; + SET ii.isBooked = TRUE + WHERE ii.id = vSelf; -- Problemas derivados de la precisión en los decimales al calcular los impuestos UPDATE XDiario @@ -57569,8 +57621,12 @@ BEGIN ORDER BY id DESC LIMIT 1; + DROP TEMPORARY TABLE tInvoiceIn; END ;; DELIMITER ; + + + /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; diff --git a/db/export-data.sh b/db/export-data.sh index 2288c1c62..1df4db030 100755 --- a/db/export-data.sh +++ b/db/export-data.sh @@ -110,5 +110,6 @@ TABLES=( TiposIva TiposTransacciones TiposRetencion + taxType ) dump_tables ${TABLES[@]} diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index fff0a2f15..640a224cb 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -311,9 +311,9 @@ export default { }, clientDefaulter: { anyClient: 'vn-client-defaulter tbody > tr', - firstClientName: 'vn-client-defaulter tbody > tr:nth-child(1) > td:nth-child(2) > span', - firstSalesPersonName: 'vn-client-defaulter tbody > tr:nth-child(1) > td:nth-child(3) > span', - firstObservation: 'vn-client-defaulter tbody > tr:nth-child(1) > td:nth-child(8) > vn-textarea[ng-model="defaulter.observation"]', + firstClientName: 'vn-client-defaulter tbody > tr:nth-child(2) > td:nth-child(2) > span', + firstSalesPersonName: 'vn-client-defaulter tbody > tr:nth-child(2) > td:nth-child(3) > span', + firstObservation: 'vn-client-defaulter tbody > tr:nth-child(2) > td:nth-child(8) > vn-textarea[ng-model="defaulter.observation"]', allDefaulterCheckbox: 'vn-client-defaulter thead vn-multi-check', addObservationButton: 'vn-client-defaulter vn-button[icon="icon-notes"]', observation: '.vn-dialog.shown vn-textarea[ng-model="$ctrl.defaulter.observation"]', @@ -334,15 +334,15 @@ export default { }, itemsIndex: { createItemButton: `vn-float-button`, - firstSearchResult: 'vn-item-index tbody tr:nth-child(1)', + firstSearchResult: 'vn-item-index tbody tr:nth-child(2)', searchResult: 'vn-item-index tbody tr:not(.empty-rows)', - firstResultPreviewButton: 'vn-item-index tbody > :nth-child(1) .buttons > [icon="preview"]', + firstResultPreviewButton: 'vn-item-index tbody > :nth-child(2) .buttons > [icon="preview"]', searchResultCloneButton: 'vn-item-index .buttons > [icon="icon-clone"]', acceptClonationAlertButton: '.vn-confirm.shown [response="accept"]', closeItemSummaryPreview: '.vn-popup.shown', shownColumns: 'vn-item-index vn-button[id="shownColumns"]', shownColumnsList: '.vn-popover.shown .content', - firstItemImage: 'vn-item-index tbody > tr:nth-child(1) > td:nth-child(1) > img', + firstItemImage: 'vn-item-index tbody > tr:nth-child(2) > td:nth-child(1) > img', firstItemImageTd: 'vn-item-index smart-table tr:nth-child(1) td:nth-child(1)', firstItemId: 'vn-item-index tbody > tr:nth-child(1) > td:nth-child(2)', idCheckbox: '.vn-popover.shown vn-horizontal:nth-child(3) > vn-check[label="Identifier"]', @@ -479,9 +479,6 @@ export default { fourthBalance: 'vn-item-diary vn-tbody > vn-tr:nth-child(4) > vn-td.balance > span', firstBalance: 'vn-item-diary vn-tbody > vn-tr:nth-child(1) > vn-td.balance' }, - itemLog: { - anyLineCreated: 'vn-item-log > vn-log vn-tbody > vn-tr', - }, ticketSummary: { header: 'vn-ticket-summary > vn-card > h5', state: 'vn-ticket-summary vn-label-value[label="State"] > section > span', @@ -523,11 +520,11 @@ export default { searchResultDate: 'vn-ticket-summary [label=Landed] span', topbarSearch: 'vn-searchbar', moreMenu: 'vn-ticket-index vn-icon-button[icon=more_vert]', - fourthWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(4)', - fiveWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(5)', + fourthWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(5)', + fiveWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(6)', weeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table table tbody tr', - firstWeeklyTicketDeleteIcon: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(1) vn-icon-button[icon="delete"]', - firstWeeklyTicketAgency: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(1) [ng-model="weekly.agencyModeFk"]', + firstWeeklyTicketDeleteIcon: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(2) vn-icon-button[icon="delete"]', + firstWeeklyTicketAgency: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(2) [ng-model="weekly.agencyModeFk"]', acceptDeleteTurn: '.vn-confirm.shown button[response="accept"]' }, createTicketView: { @@ -572,15 +569,15 @@ export default { submitNotesButton: 'button[type=submit]' }, ticketExpedition: { - firstSaleCheckbox: 'vn-ticket-expedition vn-tr:nth-child(1) vn-check[ng-model="expedition.checked"]', - thirdSaleCheckbox: 'vn-ticket-expedition vn-tr:nth-child(3) vn-check[ng-model="expedition.checked"]', - deleteExpeditionButton: 'vn-ticket-expedition vn-tool-bar > vn-button[icon="delete"]', - moveExpeditionButton: 'vn-ticket-expedition vn-tool-bar > vn-button[icon="keyboard_arrow_down"]', + firstSaleCheckbox: 'vn-ticket-expedition tr:nth-child(2) vn-check[ng-model="expedition.checked"]', + thirdSaleCheckbox: 'vn-ticket-expedition tr:nth-child(4) vn-check[ng-model="expedition.checked"]', + deleteExpeditionButton: 'vn-ticket-expedition slot-actions > vn-button[icon="delete"]', + moveExpeditionButton: 'vn-ticket-expedition slot-actions > vn-button[icon="keyboard_arrow_down"]', moreMenuWithoutRoute: 'vn-item[name="withoutRoute"]', moreMenuWithRoute: 'vn-item[name="withRoute"]', newRouteId: '.vn-dialog.shown vn-textfield[ng-model="$ctrl.newRoute"]', saveButton: '.vn-dialog.shown [response="accept"]', - expeditionRow: 'vn-ticket-expedition vn-table vn-tbody > vn-tr' + expeditionRow: 'vn-ticket-expedition table tbody > tr' }, ticketSales: { setOk: 'vn-ticket-sale vn-tool-bar > vn-button[label="Ok"] > button', @@ -667,15 +664,6 @@ export default { thirdRemoveRequestButton: 'vn-ticket-request-index vn-tr:nth-child(3) vn-icon[icon="delete"]', thirdRequestQuantity: 'vn-ticket-request-index vn-table vn-tr:nth-child(3) > vn-td:nth-child(6) vn-input-number', saveButton: 'vn-ticket-request-create button[type=submit]', - - }, - ticketLog: { - firstTD: 'vn-ticket-log vn-table vn-td:nth-child(1)', - logButton: 'vn-left-menu a[ui-sref="ticket.card.log"]', - user: 'vn-ticket-log vn-tbody vn-tr vn-td:nth-child(2)', - action: 'vn-ticket-log vn-tbody vn-tr vn-td:nth-child(4)', - changes: 'vn-ticket-log vn-data-viewer vn-tbody vn-tr table tr:nth-child(2) td.after', - id: 'vn-ticket-log vn-tr:nth-child(1) table tr:nth-child(1) td.before' }, ticketService: { addServiceButton: 'vn-ticket-service vn-icon-button[vn-tooltip="Add service"] > button', @@ -712,7 +700,7 @@ export default { problems: 'vn-check[label="With problems"]', tableButtonSearch: 'vn-button[vn-tooltip="Search"]', moveButton: 'vn-button[vn-tooltip="Future tickets"]', - firstCheck: 'tbody > tr:nth-child(1) > td > vn-check', + firstCheck: 'tbody > tr:nth-child(2) > td > vn-check', multiCheck: 'vn-multi-check', tableId: 'vn-textfield[name="id"]', tableFutureId: 'vn-textfield[name="futureId"]', @@ -736,7 +724,7 @@ export default { tableButtonSearch: 'vn-button[vn-tooltip="Search"]', moveButton: 'vn-button[vn-tooltip="Advance tickets"]', acceptButton: '.vn-confirm.shown button[response="accept"]', - firstCheck: 'tbody > tr:nth-child(1) > td > vn-check', + firstCheck: 'tbody > tr:nth-child(2) > td > vn-check', tableId: 'vn-textfield[name="id"]', tableFutureId: 'vn-textfield[name="futureId"]', tableLiters: 'vn-textfield[name="liters"]', @@ -810,7 +798,7 @@ export default { claimAction: { importClaimButton: 'vn-claim-action vn-button[label="Import claim"]', anyLine: 'vn-claim-action vn-tbody > vn-tr', - firstDeleteLine: 'vn-claim-action tr:nth-child(1) vn-icon-button[icon="delete"]', + firstDeleteLine: 'vn-claim-action tr:nth-child(2) vn-icon-button[icon="delete"]', isPaidWithManaCheckbox: 'vn-claim-action vn-check[ng-model="$ctrl.claim.isChargedToMana"]' }, ordersIndex: { @@ -1179,8 +1167,6 @@ export default { allBuyCheckbox: 'vn-entry-buy-index thead vn-check', firstBuyCheckbox: 'vn-entry-buy-index tbody:nth-child(2) vn-check', deleteBuysButton: 'vn-entry-buy-index vn-button[icon="delete"]', - addBuyButton: 'vn-entry-buy-index vn-icon[icon="add"]', - secondBuyPackingPrice: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.price3"]', secondBuyGroupingPrice: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.price2"]', secondBuyPrice: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.buyingValue"]', secondBuyGrouping: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.grouping"]', @@ -1216,7 +1202,7 @@ export default { addTagButton: 'vn-icon-button[vn-tooltip="Add tag"]', itemTagInput: 'vn-autocomplete[ng-model="itemTag.tagFk"]', itemTagValueInput: 'vn-autocomplete[ng-model="itemTag.value"]', - firstBuy: 'vn-entry-latest-buys tbody > tr:nth-child(1)', + firstBuy: 'vn-entry-latest-buys tbody > tr:nth-child(2)', allBuysCheckBox: 'vn-entry-latest-buys thead vn-check', secondBuyCheckBox: 'vn-entry-latest-buys tbody tr:nth-child(2) vn-check[ng-model="buy.checked"]', editBuysButton: 'vn-entry-latest-buys vn-button[icon="edit"]', diff --git a/e2e/paths/01-salix/03_smartTable_searchBar_integrations.spec.js b/e2e/paths/01-salix/03_smartTable_searchBar_integrations.spec.js index 526afa140..9c37ce9ba 100644 --- a/e2e/paths/01-salix/03_smartTable_searchBar_integrations.spec.js +++ b/e2e/paths/01-salix/03_smartTable_searchBar_integrations.spec.js @@ -19,15 +19,14 @@ describe('SmartTable SearchBar integration', () => { await page.waitToClick(selectors.itemsIndex.openAdvancedSearchButton); await page.autocompleteSearch(selectors.itemsIndex.advancedSearchItemType, 'Anthurium'); await page.waitToClick(selectors.itemsIndex.advancedSearchButton); - await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 3); + await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 4); await page.reload({ waitUntil: 'networkidle2' }); - await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 3); + await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 4); - await page.waitToClick(selectors.itemsIndex.advancedSmartTableButton); await page.write(selectors.itemsIndex.advancedSmartTableGrouping, '1'); await page.keyboard.press('Enter'); await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 2); @@ -36,7 +35,7 @@ describe('SmartTable SearchBar integration', () => { waitUntil: 'networkidle2' }); - await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 2); + await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 1); }); it('should filter in section without smart-table and search in searchBar go to zone section', async() => { diff --git a/e2e/paths/01-salix/05_changePassword.spec.js b/e2e/paths/01-salix/05_changePassword.spec.js new file mode 100644 index 000000000..6e4cfb7f3 --- /dev/null +++ b/e2e/paths/01-salix/05_changePassword.spec.js @@ -0,0 +1,71 @@ +import getBrowser from '../../helpers/puppeteer'; + +const $ = { + form: 'vn-out-layout form' +}; + +describe('ChangePassword path', async() => { + let browser; + let page; + beforeAll(async() => { + browser = await getBrowser(); + page = browser.page; + }); + + afterAll(async() => { + await browser.close(); + }); + + const oldPassword = 'nightmare'; + const newPassword = 'newPass.1234'; + describe('Bad login', async() => { + it('should receive an error when the password is expired', async() => { + // Expired login + await page.doLogin('Maintenance', oldPassword); + let message = await page.waitForSnackbar(); + + expect(message.text).toContain('The password has expired, change it from Salix'); + expect(await page.getState()).toContain('change-password'); + + // Bad attempt: incorrect current password + message = await page.sendForm($.form, { + oldPassword: newPassword, + newPassword: oldPassword, + repeatPassword: oldPassword + }); + + expect(message.text).toContain('Invalid current password'); + + // Bad attempt: password not meet requirements + message = await page.sendForm($.form, { + oldPassword: oldPassword, + newPassword: oldPassword, + repeatPassword: oldPassword + }); + + expect(message.text).toContain('Password does not meet requirements'); + + // Correct attempt: change password + message = await page.sendForm($.form, { + oldPassword: oldPassword, + newPassword: newPassword, + repeatPassword: newPassword + }); + + expect(message.text).toContain('Password updated!'); + expect(await page.getState()).toContain('login'); + + // Bad login, old password + await page.doLogin('Maintenance', oldPassword); + message = await page.waitForSnackbar(); + + expect(message.text).toContain('Invalid login'); + + // Correct login, new password + await page.doLogin('Maintenance', newPassword); + await page.waitForSelector('vn-home'); + + expect(await page.getState()).toBe('home'); + }); + }); +}); diff --git a/e2e/paths/02-client/07_edit_web_access.spec.js b/e2e/paths/02-client/07_edit_web_access.spec.js index 5386d12bd..3847ec7cd 100644 --- a/e2e/paths/02-client/07_edit_web_access.spec.js +++ b/e2e/paths/02-client/07_edit_web_access.spec.js @@ -5,8 +5,8 @@ const $ = { userName: 'vn-client-web-access vn-textfield[ng-model="$ctrl.account.name"]', email: 'vn-client-web-access vn-textfield[ng-model="$ctrl.account.email"]', saveButton: 'vn-client-web-access button[type=submit]', - nameValue: 'vn-client-log .change:nth-child(1) .basic-json:nth-child(2) vn-json-value', - activeValue: 'vn-client-log .change:nth-child(2) .basic-json:nth-child(1) vn-json-value' + nameValue: 'vn-client-log .changes-log:nth-child(2) .basic-json:nth-child(2) vn-json-value', + activeValue: 'vn-client-log .changes-log:nth-child(3) .basic-json:nth-child(1) vn-json-value' }; describe('Client web access path', () => { diff --git a/e2e/paths/02-client/21_defaulter.spec.js b/e2e/paths/02-client/21_defaulter.spec.js index 97e62abef..2bb3d6254 100644 --- a/e2e/paths/02-client/21_defaulter.spec.js +++ b/e2e/paths/02-client/21_defaulter.spec.js @@ -19,7 +19,7 @@ describe('Client defaulter path', () => { it('should count the amount of clients in the turns section', async() => { const result = await page.countElement(selectors.clientDefaulter.anyClient); - expect(result).toEqual(5); + expect(result).toEqual(6); }); it('should check contain expected client', async() => { diff --git a/e2e/paths/03-worker/06_create.spec.js b/e2e/paths/03-worker/06_create.spec.js index 98e67edbf..11d36b3cf 100644 --- a/e2e/paths/03-worker/06_create.spec.js +++ b/e2e/paths/03-worker/06_create.spec.js @@ -53,7 +53,7 @@ describe('Worker create path', () => { expect(message.text).toContain('Data saved!'); // 'rollback' - await page.loginAndModule('sysadmin', 'account'); + await page.loginAndModule('itManagement', 'account'); await page.accessToSearchResult(newWorker); await page.waitToClick(selectors.accountDescriptor.menuButton); diff --git a/e2e/paths/04-item/01_summary.spec.js b/e2e/paths/04-item/01_summary.spec.js index e24fa6a9f..e09ecb778 100644 --- a/e2e/paths/04-item/01_summary.spec.js +++ b/e2e/paths/04-item/01_summary.spec.js @@ -18,11 +18,11 @@ describe('Item summary path', () => { await page.doSearch('Ranged weapon'); const resultsCount = await page.countElement(selectors.itemsIndex.searchResult); - await page.waitForTextInElement(selectors.itemsIndex.searchResult, 'Ranged weapon'); + await page.waitForTextInElement(selectors.itemsIndex.firstSearchResult, 'Ranged weapon'); await page.waitToClick(selectors.itemsIndex.firstResultPreviewButton); const isVisible = await page.isVisible(selectors.itemSummary.basicData); - expect(resultsCount).toBe(3); + expect(resultsCount).toBe(4); expect(isVisible).toBeTruthy(); }); @@ -66,7 +66,7 @@ describe('Item summary path', () => { await page.waitToClick(selectors.itemsIndex.firstResultPreviewButton); await page.waitForSelector(selectors.itemSummary.basicData, {visible: true}); - expect(resultsCount).toBe(2); + expect(resultsCount).toBe(3); }); it(`should now check the item summary preview shows fields from basic data`, async() => { diff --git a/e2e/paths/04-item/10_item_log.spec.js b/e2e/paths/04-item/10_item_log.spec.js index dc467044d..c88fbd337 100644 --- a/e2e/paths/04-item/10_item_log.spec.js +++ b/e2e/paths/04-item/10_item_log.spec.js @@ -18,7 +18,7 @@ describe('Item log path', () => { await page.doSearch('Knowledge artifact'); const nResults = await page.countElement(selectors.itemsIndex.searchResult); - expect(nResults).toEqual(0); + expect(nResults).toEqual(1); }); it('should access to the create item view by clicking the create floating button', async() => { diff --git a/e2e/paths/05-ticket/02_expeditions_and_log.spec.js b/e2e/paths/05-ticket/02_expeditions_and_log.spec.js index edccd5561..b97576940 100644 --- a/e2e/paths/05-ticket/02_expeditions_and_log.spec.js +++ b/e2e/paths/05-ticket/02_expeditions_and_log.spec.js @@ -27,6 +27,6 @@ describe('Ticket expeditions and log path', () => { const result = await page .countElement(selectors.ticketExpedition.expeditionRow); - expect(result).toEqual(3); + expect(result).toEqual(4); }); }); diff --git a/e2e/paths/05-ticket/09_weekly.spec.js b/e2e/paths/05-ticket/09_weekly.spec.js index 0ba57aa9d..a9cce2ead 100644 --- a/e2e/paths/05-ticket/09_weekly.spec.js +++ b/e2e/paths/05-ticket/09_weekly.spec.js @@ -19,7 +19,7 @@ describe('Ticket descriptor path', () => { it('should count the amount of tickets in the turns section', async() => { const result = await page.countElement(selectors.ticketsIndex.weeklyTicket); - expect(result).toEqual(6); + expect(result).toEqual(7); }); it('should go back to the ticket index then search and access a ticket summary', async() => { @@ -89,7 +89,7 @@ describe('Ticket descriptor path', () => { await page.doSearch('11'); const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); - expect(nResults).toEqual(1); + expect(nResults).toEqual(2); }); it('should delete the weekly ticket 11', async() => { @@ -104,7 +104,7 @@ describe('Ticket descriptor path', () => { await page.doSearch(); const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); - expect(nResults).toEqual(6); + expect(nResults).toEqual(7); }); it('should update the agency then remove it afterwards', async() => { diff --git a/e2e/paths/05-ticket/20_moveExpedition.spec.js b/e2e/paths/05-ticket/20_moveExpedition.spec.js index cf1c5ded3..ae23c9c99 100644 --- a/e2e/paths/05-ticket/20_moveExpedition.spec.js +++ b/e2e/paths/05-ticket/20_moveExpedition.spec.js @@ -29,7 +29,7 @@ describe('Ticket expeditions', () => { const result = await page .countElement(selectors.ticketExpedition.expeditionRow); - expect(result).toEqual(1); + expect(result).toEqual(2); }); it(`should move one expedition to new ticket with route`, async() => { @@ -45,6 +45,6 @@ describe('Ticket expeditions', () => { const result = await page .countElement(selectors.ticketExpedition.expeditionRow); - expect(result).toEqual(1); + expect(result).toEqual(2); }); }); diff --git a/e2e/paths/05-ticket/21_future.spec.js b/e2e/paths/05-ticket/21_future.spec.js index c854dcbaf..7b7d478f7 100644 --- a/e2e/paths/05-ticket/21_future.spec.js +++ b/e2e/paths/05-ticket/21_future.spec.js @@ -87,7 +87,7 @@ describe('Ticket Future path', () => { await page.clearInput(selectors.ticketFuture.futureState); await page.waitToClick(selectors.ticketFuture.submit); - await page.waitForNumberOfElements(selectors.ticketFuture.searchResult, 4); + await page.waitForNumberOfElements(selectors.ticketFuture.searchResult, 5); await page.waitToClick(selectors.ticketFuture.multiCheck); await page.waitToClick(selectors.ticketFuture.firstCheck); await page.waitToClick(selectors.ticketFuture.moveButton); diff --git a/e2e/paths/06-claim/05_summary.spec.js b/e2e/paths/06-claim/05_summary.spec.js index 9656ea656..1333ed01a 100644 --- a/e2e/paths/06-claim/05_summary.spec.js +++ b/e2e/paths/06-claim/05_summary.spec.js @@ -49,7 +49,11 @@ describe('Claim summary path', () => { }); it(`should click on the first sale ID making the item descriptor visible`, async() => { - await page.waitToClick(selectors.claimSummary.firstSaleItemId); + const firstItem = selectors.claimSummary.firstSaleItemId; + await page.evaluate(selectors => { + document.querySelector(selectors).scrollIntoView(); + }, firstItem); + await page.click(firstItem); await page.waitImgLoad(selectors.claimSummary.firstSaleDescriptorImage); const visible = await page.isVisible(selectors.claimSummary.itemDescriptorPopover); diff --git a/e2e/paths/12-entry/07_buys.spec.js b/e2e/paths/12-entry/07_buys.spec.js index e501452bc..28d39fb1d 100644 --- a/e2e/paths/12-entry/07_buys.spec.js +++ b/e2e/paths/12-entry/07_buys.spec.js @@ -66,97 +66,4 @@ describe('Entry import, create and edit buys path', () => { await page.waitToClick(selectors.globalItems.acceptButton); await page.waitForNumberOfElements(selectors.entryBuys.anyBuyLine, 1); }); - - it('should add a new buy', async() => { - await page.waitToClick(selectors.entryBuys.addBuyButton); - await page.write(selectors.entryBuys.secondBuyPackingPrice, '999'); - await page.write(selectors.entryBuys.secondBuyGroupingPrice, '999'); - await page.write(selectors.entryBuys.secondBuyPrice, '999'); - await page.write(selectors.entryBuys.secondBuyGrouping, '999'); - await page.write(selectors.entryBuys.secondBuyPacking, '999'); - await page.write(selectors.entryBuys.secondBuyWeight, '999'); - await page.write(selectors.entryBuys.secondBuyStickers, '999'); - await page.autocompleteSearch(selectors.entryBuys.secondBuyPackage, '1'); - await page.write(selectors.entryBuys.secondBuyQuantity, '999'); - await page.autocompleteSearch(selectors.entryBuys.secondBuyItem, '1'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - - await page.waitForNumberOfElements(selectors.entryBuys.anyBuyLine, 2); - }); - - it('should edit the newest buy and check data', async() => { - await page.clearInput(selectors.entryBuys.secondBuyPackingPrice); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyPackingPrice, '100'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyGroupingPrice); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyGroupingPrice, '200'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyPrice); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyPrice, '300'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyGrouping); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyGrouping, '400'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyPacking); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyPacking, '500'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyWeight); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyWeight, '600'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyStickers); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyStickers, '700'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.autocompleteSearch(selectors.entryBuys.secondBuyPackage, '94'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyQuantity); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyQuantity, '800'); - await page.keyboard.press('Enter'); - - await page.reloadSection('entry.card.buy.index'); - - const secondBuyPackingPrice = await page.getValue(selectors.entryBuys.secondBuyPackingPrice); - const secondBuyGroupingPrice = await page.getValue(selectors.entryBuys.secondBuyGroupingPrice); - const secondBuyPrice = await page.getValue(selectors.entryBuys.secondBuyPrice); - const secondBuyGrouping = await page.getValue(selectors.entryBuys.secondBuyGrouping); - const secondBuyPacking = await page.getValue(selectors.entryBuys.secondBuyPacking); - const secondBuyWeight = await page.getValue(selectors.entryBuys.secondBuyWeight); - const secondBuyStickers = await page.getValue(selectors.entryBuys.secondBuyStickers); - const secondBuyPackage = await page.getValue(selectors.entryBuys.secondBuyPackage); - const secondBuyQuantity = await page.getValue(selectors.entryBuys.secondBuyQuantity); - - expect(secondBuyPackingPrice).toEqual('100'); - expect(secondBuyGroupingPrice).toEqual('200'); - expect(secondBuyPrice).toEqual('300'); - expect(secondBuyGrouping).toEqual('400'); - expect(secondBuyPacking).toEqual('500'); - expect(secondBuyWeight).toEqual('600'); - expect(secondBuyStickers).toEqual('700'); - expect(secondBuyPackage).toEqual('94'); - expect(secondBuyQuantity).toEqual('800'); - }); }); diff --git a/e2e/paths/14-account/01_create_and_basic_data.spec.js b/e2e/paths/14-account/01_create_and_basic_data.spec.js index 54e4d1f12..e38d1aeec 100644 --- a/e2e/paths/14-account/01_create_and_basic_data.spec.js +++ b/e2e/paths/14-account/01_create_and_basic_data.spec.js @@ -8,7 +8,7 @@ describe('Account create and basic data path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('developer', 'account'); + await page.loginAndModule('itManagement', 'account'); }); afterAll(async() => { diff --git a/front/core/components/avatar/style.scss b/front/core/components/avatar/style.scss index 272930821..b3a80db55 100644 --- a/front/core/components/avatar/style.scss +++ b/front/core/components/avatar/style.scss @@ -4,8 +4,8 @@ vn-avatar { display: block; border-radius: 50%; overflow: hidden; - height: 36px; - width: 36px; + height: 38px; + width: 38px; font-size: 22px; background-color: $color-main; position: relative; diff --git a/front/core/components/smart-table/index.js b/front/core/components/smart-table/index.js index b2380a62f..c3b927c62 100644 --- a/front/core/components/smart-table/index.js +++ b/front/core/components/smart-table/index.js @@ -40,6 +40,8 @@ export default class SmartTable extends Component { this._options = options; if (!options) return; + options.defaultSearch = true; + if (options.defaultSearch) this.displaySearch(); diff --git a/front/core/services/auth.js b/front/core/services/auth.js index 0b89a8e88..ef6c07637 100644 --- a/front/core/services/auth.js +++ b/front/core/services/auth.js @@ -24,7 +24,7 @@ export default class Auth { initialize() { let criteria = { to: state => { - const outLayout = ['login', 'recover-password', 'reset-password']; + const outLayout = ['login', 'recover-password', 'reset-password', 'change-password']; return !outLayout.some(ol => ol == state.name); } }; @@ -59,12 +59,12 @@ export default class Auth { password: password || undefined }; - return this.$http.post('VnUsers/signIn', params).then( - json => this.onLoginOk(json, remember)); + return this.$http.post('VnUsers/signIn', params) + .then(json => this.onLoginOk(json, remember)); } onLoginOk(json, remember) { - this.vnToken.set(json.data.token, remember); + this.vnToken.set(json.data.token, json.data.created, remember); return this.loadAcls().then(() => { let continueHash = this.$state.params.continue; diff --git a/front/core/services/index.js b/front/core/services/index.js index 867a13df0..855f2fab1 100644 --- a/front/core/services/index.js +++ b/front/core/services/index.js @@ -11,3 +11,4 @@ import './report'; import './email'; import './file'; import './date'; + diff --git a/front/core/services/token.js b/front/core/services/token.js index 126fbb604..c1bb5a173 100644 --- a/front/core/services/token.js +++ b/front/core/services/token.js @@ -9,25 +9,33 @@ export default class Token { constructor() { try { this.token = sessionStorage.getItem('vnToken'); - if (!this.token) + this.created = sessionStorage.getItem('vnTokenCreated'); + if (!this.token) { this.token = localStorage.getItem('vnToken'); + this.created = localStorage.getItem('vnTokenCreated'); + } } catch (e) {} } - set(value, remember) { + set(token, created, remember) { this.unset(); try { - if (remember) - localStorage.setItem('vnToken', value); - else - sessionStorage.setItem('vnToken', value); + if (remember) { + localStorage.setItem('vnToken', token); + localStorage.setItem('vnTokenCreated', created); + } else { + sessionStorage.setItem('vnToken', token); + sessionStorage.setItem('vnTokenCreated', created); + } } catch (e) {} - this.token = value; + this.token = token; + this.created = created; } unset() { localStorage.removeItem('vnToken'); sessionStorage.removeItem('vnToken'); this.token = null; + this.created = null; } } diff --git a/front/core/styles/util.scss b/front/core/styles/util.scss index 95a523ff4..8c345ddcc 100644 --- a/front/core/styles/util.scss +++ b/front/core/styles/util.scss @@ -1,4 +1,11 @@ +@import "./variables"; +@import "./effects"; +@mixin mobile { + @media screen and (max-width: $mobile-width) { + @content; + } +} @mixin browser($browser) { html[data-browser*="#{$browser}"] & { @content; diff --git a/front/core/styles/variables.scss b/front/core/styles/variables.scss index bcc9fab66..0a74c8277 100644 --- a/front/core/styles/variables.scss +++ b/front/core/styles/variables.scss @@ -1,5 +1,3 @@ -@import "./util"; - $font-size: 11pt; $menu-width: 256px; $topbar-height: 56px; diff --git a/front/salix/components/background/style.scss b/front/salix/components/background/style.scss index c75b69c52..5bc56683e 100644 --- a/front/salix/components/background/style.scss +++ b/front/salix/components/background/style.scss @@ -1,4 +1,4 @@ -@import "variables"; +@import "util"; @keyframes fadein { from { @@ -16,7 +16,7 @@ vn-background { background-color: black; z-index: 14; - @media screen and (max-width: $mobile-width) { + @include mobile { &.shown { display: block; opacity: .3; diff --git a/front/salix/components/change-password/index.html b/front/salix/components/change-password/index.html new file mode 100644 index 000000000..8d338d411 --- /dev/null +++ b/front/salix/components/change-password/index.html @@ -0,0 +1,29 @@ +
Change password
+ + + + + + + diff --git a/front/salix/components/change-password/index.js b/front/salix/components/change-password/index.js new file mode 100644 index 000000000..baa9d96e5 --- /dev/null +++ b/front/salix/components/change-password/index.js @@ -0,0 +1,63 @@ +import ngModule from '../../module'; +const UserError = require('vn-loopback/util/user-error'); + +export default class Controller { + constructor($scope, $element, $http, vnApp, $translate, $state, $location) { + Object.assign(this, { + $scope, + $element, + $http, + vnApp, + $translate, + $state, + $location + }); + } + + $onInit() { + if (!this.$state.params.id) + this.$state.go('login'); + + this.$http.get('UserPasswords/findOne') + .then(res => { + this.passRequirements = res.data; + }); + } + + submit() { + const userId = this.$state.params.userId; + const newPassword = this.newPassword; + const oldPassword = this.oldPassword; + + if (!newPassword) + throw new UserError(`You must enter a new password`); + if (newPassword != this.repeatPassword) + throw new UserError(`Passwords don't match`); + + const headers = { + Authorization: this.$state.params.id + }; + + this.$http.post('VnUsers/change-password', + { + id: userId, + oldPassword, + newPassword + }, + {headers} + ).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Password updated!')); + this.$state.go('login'); + }); + } +} +Controller.$inject = ['$scope', '$element', '$http', 'vnApp', '$translate', '$state', '$location']; + +ngModule.vnComponent('vnChangePassword', { + template: require('./index.html'), + controller: Controller, + bindings: { + id: '<' + } +}); + diff --git a/front/salix/components/change-password/locale/en.yml b/front/salix/components/change-password/locale/en.yml new file mode 100644 index 000000000..e5419e1c8 --- /dev/null +++ b/front/salix/components/change-password/locale/en.yml @@ -0,0 +1,4 @@ +Password requirements: > + The password must have at least {{ length }} length characters, + {{nAlpha}} alphabetic characters, {{nUpper}} capital letters, {{nDigits}} + digits and {{nPunct}} symbols (Ex: $%&.) diff --git a/front/salix/components/change-password/locale/es.yml b/front/salix/components/change-password/locale/es.yml new file mode 100644 index 000000000..9898df702 --- /dev/null +++ b/front/salix/components/change-password/locale/es.yml @@ -0,0 +1,9 @@ +Change password: Cambiar contraseña +Old password: Antigua contraseña +New password: Nueva contraseña +Repeat password: Repetir contraseña +Password updated!: ¡Contraseña actualizada! +Password requirements: > + La contraseña debe tener al menos {{ length }} caracteres de longitud, + {{nAlpha}} caracteres alfabéticos, {{nUpper}} letras mayúsculas, {{nDigits}} + dígitos y {{nPunct}} símbolos (Ej: $%&.) diff --git a/front/salix/components/index.js b/front/salix/components/index.js index 8f5724862..0999d9aca 100644 --- a/front/salix/components/index.js +++ b/front/salix/components/index.js @@ -9,6 +9,7 @@ import './login'; import './outLayout'; import './recover-password'; import './reset-password'; +import './change-password'; import './module-card'; import './module-main'; import './side-menu/side-menu'; diff --git a/front/salix/components/layout/index.js b/front/salix/components/layout/index.js index 48f50f404..dc2313f4f 100644 --- a/front/salix/components/layout/index.js +++ b/front/salix/components/layout/index.js @@ -3,13 +3,14 @@ import Component from 'core/lib/component'; import './style.scss'; export class Layout extends Component { - constructor($element, $, vnModules) { + constructor($element, $, vnModules, vnToken) { super($element, $); this.modules = vnModules.get(); } $onInit() { this.getUserData(); + this.getAccessTokenConfig(); } getUserData() { @@ -30,8 +31,42 @@ export class Layout extends Component { refresh() { window.location.reload(); } + + getAccessTokenConfig() { + this.$http.get('AccessTokenConfigs').then(json => { + const firtsResult = json.data[0]; + if (!firtsResult) return; + this.renewPeriod = firtsResult.renewPeriod; + this.renewInterval = firtsResult.renewInterval; + + const intervalMilliseconds = firtsResult.renewInterval * 1000; + this.inservalId = setInterval(this.checkTokenValidity.bind(this), intervalMilliseconds); + }); + } + + checkTokenValidity() { + const now = new Date(); + const differenceMilliseconds = now - new Date(this.vnToken.created); + const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + + if (differenceSeconds > this.renewPeriod) { + this.$http.post('VnUsers/renewToken') + .then(json => { + if (json.data.token) { + let remember = true; + if (window.sessionStorage.vnToken) remember = false; + + this.vnToken.set(json.data.token, json.data.created, remember); + } + }); + } + } + + $onDestroy() { + clearInterval(this.inservalId); + } } -Layout.$inject = ['$element', '$scope', 'vnModules']; +Layout.$inject = ['$element', '$scope', 'vnModules', 'vnToken']; ngModule.vnComponent('vnLayout', { template: require('./index.html'), diff --git a/front/salix/components/layout/index.spec.js b/front/salix/components/layout/index.spec.js index 0d70c4806..8f65f32ce 100644 --- a/front/salix/components/layout/index.spec.js +++ b/front/salix/components/layout/index.spec.js @@ -37,4 +37,49 @@ describe('Component vnLayout', () => { expect(url).not.toBeDefined(); }); }); + + describe('getAccessTokenConfig()', () => { + it(`should set the renewPeriod and renewInterval properties in localStorage`, () => { + const response = [{ + renewPeriod: 100, + renewInterval: 5 + }]; + + $httpBackend.expect('GET', `AccessTokenConfigs`).respond(response); + controller.getAccessTokenConfig(); + $httpBackend.flush(); + + expect(controller.renewPeriod).toBe(100); + expect(controller.renewInterval).toBe(5); + expect(controller.inservalId).toBeDefined(); + }); + }); + + describe('checkTokenValidity()', () => { + it(`should not call renewToken and not set vnToken in the controller`, () => { + controller.renewPeriod = 100; + controller.vnToken.created = new Date(); + + controller.checkTokenValidity(); + + expect(controller.vnToken.token).toBeNull(); + }); + + it(`should call renewToken and set vnToken properties in the controller`, () => { + const response = { + token: 999, + created: new Date() + }; + controller.renewPeriod = 100; + const oneHourBefore = new Date(Date.now() - (60 * 60 * 1000)); + controller.vnToken.created = oneHourBefore; + + $httpBackend.expect('POST', `VnUsers/renewToken`).respond(response); + controller.checkTokenValidity(); + $httpBackend.flush(); + + expect(controller.vnToken.token).toBe(999); + expect(controller.vnToken.created).toEqual(response.created); + }); + }); }); diff --git a/front/salix/components/layout/style.scss b/front/salix/components/layout/style.scss index 612366228..fa3e8f918 100644 --- a/front/salix/components/layout/style.scss +++ b/front/salix/components/layout/style.scss @@ -1,4 +1,4 @@ -@import "effects"; +@import "util"; vn-layout { & > vn-topbar { @@ -134,7 +134,7 @@ vn-layout { border-radius: 50%; } } - @media screen and (max-width: $mobile-width) { + @include mobile { & > vn-topbar { & > .start > .logo { display: none; diff --git a/front/salix/components/log/index.html b/front/salix/components/log/index.html index e6ade48fb..16342783d 100644 --- a/front/salix/components/log/index.html +++ b/front/salix/components/log/index.html @@ -2,8 +2,6 @@ vn-id="model" url="{{$ctrl.url}}" filter="$ctrl.filter" - link="{originFk: $ctrl.originId}" - where="{changedModel: $ctrl.changedModel, changedModelId: $ctrl.changedModelId}" data="$ctrl.logs" order="creationDate DESC, id DESC" limit="20"> @@ -16,88 +14,137 @@ -
-
- - - - -
+ class="vn-w-sm vn-px-sm vn-pb-xl"> +
+
+
+ {{::$ctrl.modelI18n}} #{{::originLog.originFk}} +
- -
-
- - - {{::$ctrl.relativeDate(log.creationDate)}} -
-
- - {{::log.changedModelI18n}} - -
+
+
+ + + + +
+
-
- #{{::log.changedModelId}} - {{::log.changedModelValue}} -
-
- - - - - - {{::prop.nameI18n}}: +
+
+
+ + + + {{::modelLog.modelI18n}} - , - -
-
- - {{::prop.nameI18n}}: - - - - ← - -
+ #{{::modelLog.id}} + {{::modelLog.showValue}}
- - - {{::log.description}} - - + +
+
+ {{::$ctrl.relativeDate(log.creationDate)}} +
+
+ + + + +
+
+
+ + + + + + {{::prop.nameI18n}}: + + , + +
+
+ + {{::prop.nameI18n}}: + + + + ← + +
+
+
+ + {{::log.description}} + + +
+
+
+ +
+ + + + + + + + - - - - - - - - @@ -198,19 +226,35 @@ label="To" ng-model="filter.to"> - - - - - -
- + + + + +
+
+ {{$ctrl.instance.modelLog.modelI18n}} #{{$ctrl.instance.modelLog.id}} +
+
+
+ + {{::prop.nameI18n}}: + + +
+
+ No data +
+
+
+
+
+ diff --git a/front/salix/components/log/index.js b/front/salix/components/log/index.js index 3392c53be..3df367cae 100644 --- a/front/salix/components/log/index.js +++ b/front/salix/components/log/index.js @@ -3,7 +3,10 @@ import Section from '../section'; import {hashToColor} from 'core/lib/string'; import './style.scss'; -const validDate = /^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/; +const validDate = new RegExp( + /^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])/.source + + /T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/.source +); export default class Controller extends Section { constructor($element, $) { @@ -28,6 +31,20 @@ export default class Controller extends Section { select: 'visibility' }; this.filter = { + fields: [ + 'id', + 'originFk', + 'userFk', + 'action', + 'changedModel', + 'oldInstance', + 'newInstance', + 'creationDate', + 'changedModel', + 'changedModelId', + 'changedModelValue', + 'description' + ], include: [{ relation: 'user', scope: { @@ -48,6 +65,11 @@ export default class Controller extends Section { this.today.setHours(0, 0, 0, 0); } + $onInit() { + const match = this.url?.match(/(.*)Logs$/); + this.modelI18n = match && this.translateModel(match[1]); + } + $postLink() { this.resetFilter(); this.$.$watch( @@ -63,47 +85,75 @@ export default class Controller extends Section { set logs(value) { this._logs = value; + this.logTree = []; if (!value) return; const empty = {}; const validations = window.validations; - const castJsonValue = this.castJsonValue; - for (const log of value) { + let originLog; + let userLog; + let modelLog; + let nLogs; + + for (let i = 0; i < value.length; i++) { + const log = value[i]; + const prevLog = i > 0 ? value[i - 1] : null; + const locale = validations[log.changedModel]?.locale || empty; + + // Origin + + const originChanged = !prevLog + || log.originFk != prevLog.originFk; + if (originChanged) { + this.logTree.push(originLog = { + originFk: log.originFk, + logs: [] + }); + } + + // User + + const userChanged = originChanged + || log.userFk != prevLog.userFk + || nLogs >= 5; + if (userChanged) { + originLog.logs.push(userLog = { + user: log.user, + userFk: log.userFk, + logs: [] + }); + nLogs = 0; + } + nLogs++; + + // Model + + const modelChanged = userChanged + || log.changedModel != prevLog.changedModel + || log.changedModelId != prevLog.changedModelId; + if (modelChanged) { + userLog.logs.push(modelLog = { + model: log.changedModel, + modelI18n: firstUpper(locale.name) || log.changedModel, + id: log.changedModelId, + showValue: log.changedModelValue, + logs: [] + }); + } + + modelLog.logs.push(log); + + // Changes + const notDelete = log.action != 'delete'; const olds = (notDelete ? log.oldInstance : null) || empty; const vals = (notDelete ? log.newInstance : log.oldInstance) || empty; - const locale = validations[log.changedModel]?.locale || empty; - log.changedModelI18n = firstUpper(locale.name) || log.changedModel; - let props = Object.keys(olds).concat(Object.keys(vals)); - props = [...new Set(props)]; + let propNames = Object.keys(olds).concat(Object.keys(vals)); + propNames = [...new Set(propNames)]; - log.props = []; - for (const prop of props) { - if (prop.endsWith('$')) continue; - log.props.push({ - name: prop, - nameI18n: firstUpper(locale.columns?.[prop]) || prop, - old: getVal(olds, prop), - val: getVal(vals, prop) - }); - } - log.props.sort( - (a, b) => a.nameI18n.localeCompare(b.nameI18n)); - } - - function getVal(vals, prop) { - let val, id; - const showProp = `${prop}$`; - - if (vals[showProp] != null) { - val = vals[showProp]; - id = vals[prop]; - } else - val = vals[prop]; - - return {val: castJsonValue(val), id}; + log.props = this.parseProps(propNames, locale, vals, olds); } } @@ -114,17 +164,76 @@ export default class Controller extends Section { set models(value) { this._models = value; if (!value) return; - for (const model of value) { - const name = model.changedModel; - model.changedModelI18n = - firstUpper(window.validations[name]?.locale?.name) || name; - } + for (const model of value) + model.changedModelI18n = this.translateModel(model.changedModel); } get showModelName() { return !(this.changedModel && this.changedModelId); } + parseProps(propNames, locale, vals, olds) { + const castJsonValue = this.castJsonValue; + const props = []; + + for (const prop of propNames) { + if (prop.endsWith('$')) continue; + props.push({ + name: prop, + nameI18n: firstUpper(locale.columns?.[prop]) || prop, + val: getVal(vals, prop), + old: olds && getVal(olds, prop) + }); + } + props.sort( + (a, b) => a.nameI18n.localeCompare(b.nameI18n)); + + function getVal(vals, prop) { + let val; let id; + const showProp = `${prop}$`; + + if (vals[showProp] != null) { + val = vals[showProp]; + id = vals[prop]; + } else + val = vals[prop]; + + return {val: castJsonValue(val), id}; + } + + return props; + } + + viewPitInstance(event, id, modelLog) { + if (this.instance?.canceler) + this.instance.canceler.resolve(); + + const canceler = this.$q.defer(); + this.instance = { + modelLog, + canceler + }; + const options = {timeout: canceler.promise}; + + this.$http.get(`${this.url}/${id}/pitInstance`, options) + .then(res => { + const instance = res.data; + const propNames = Object.keys(instance); + const locale = window.validations[modelLog.model]?.locale || {}; + this.instance.props = this.parseProps(propNames, locale, instance); + }) + .finally(() => { + this.instance.canceler = null; + this.$.$applyAsync(() => this.$.instancePopover.relocate()); + }); + + this.$.instancePopover.show(event); + } + + translateModel(name) { + return firstUpper(window.validations[name]?.locale?.name) || name; + } + castJsonValue(value) { return typeof value === 'string' && validDate.test(value) ? new Date(value) @@ -160,16 +269,14 @@ export default class Controller extends Section { applyFilter() { const filter = this.$.filter; - function getParam(prop, value) { + const getParam = (prop, value) => { if (value == null || value == '') return null; switch (prop) { case 'search': - const or = []; - if (/^[\w_-]+$/.test(value)) - or.push({changedModelId: value}); - if (!/^[0-9]+$/.test(value)) - or.push({changedModelValue: {like: `%${value}%`}}); - return or.length ? {or} : null; + if (/^\s*[0-9]+\s*$/.test(value) || this.byRecord) + return {changedModelId: value.trim()}; + else + return {changedModelValue: {like: `%${value}%`}}; case 'changes': return {or: [ {oldJson: {like: `%${value}%`}}, @@ -178,64 +285,86 @@ export default class Controller extends Section { ]}; case 'who': switch (value) { - case 'all': - return null; case 'user': return {userFk: {neq: null}}; case 'system': return {userFk: null}; + case 'all': + default: + return null; } - case 'actions': + case 'actions': { const inq = []; for (const action in value) { if (value[action]) inq.push(action); } return inq.length ? {action: {inq}} : null; + } case 'from': - if (filter.to) { + if (filter.to) return {creationDate: {gte: value}}; - } else { + else { const to = new Date(value); to.setHours(23, 59, 59, 999); return {creationDate: {between: [value, to]}}; } - case 'to': + case 'to': { const to = new Date(value); to.setHours(23, 59, 59, 999); return {creationDate: {lte: to}}; + } case 'userFk': return filter.who != 'system' ? {[prop]: value} : null; default: return {[prop]: value}; } - } + }; + this.hasFilter = false; const and = []; + + if (!filter.search || !filter.changedModel) + this.byRecord = false; + if (!this.byRecord) + and.push({originFk: this.originId}); + for (const prop in filter) { const param = getParam(prop, filter[prop]); - if (param) and.push(param); + if (param) { + and.push(param); + this.hasFilter = true; + } } const lbFilter = and.length ? {where: {and}} : null; return this.$.model.applyFilter(lbFilter); } + filterByRecord(modelLog) { + this.byRecord = true; + this.$.filter = { + who: 'all', + search: modelLog.id, + changedModel: modelLog.model + }; + } + searchUser(search) { - if (/^[0-9]+$/.test(search)) { + if (/^[0-9]+$/.test(search)) return {id: search}; - } else { + else { return {or: [ {name: search}, {nickname: {like: `%${search}%`}} - ]} + ]}; } } - showWorkerDescriptor(event, log) { - if (log.user?.worker) - this.$.workerDescriptor.show(event.target, log.userFk); + showWorkerDescriptor(event, userLog) { + if (userLog.user?.worker) + this.$.workerDescriptor.show(event.target, userLog.userFk); } } diff --git a/front/salix/components/log/locale/es.yml b/front/salix/components/log/locale/es.yml index 0f2755f2e..09154f04e 100644 --- a/front/salix/components/log/locale/es.yml +++ b/front/salix/components/log/locale/es.yml @@ -3,8 +3,8 @@ Concept: Concepto Search: Buscar Search by id or concept: Buscar por identificador o concepto Search by changes: | - Buscar por cambios realizados. Los atributos deben buscarse por su nombre - interno, para obtenerlo situar el cursor sobre el nombre. + Buscar por cambios. Los atributos deben buscarse por su nombre interno, + para obtenerlo situar el cursor sobre el atributo. Entity: Entidad Action: Acción Author: Autor @@ -16,9 +16,13 @@ Creates: Crea Edits: Modifica Deletes: Elimina Accesses: Accede +All: Todo System: Sistema Details: Detalles note: nota Changes: Cambios today: hoy yesterday: ayer +Show all record changes: Mostrar todos los cambios realizados en el registro +View record at this point in time: Ver el registro en este punto +Quit filter: Quitar filtro diff --git a/front/salix/components/log/style.scss b/front/salix/components/log/style.scss index cec591a7f..d729d09a3 100644 --- a/front/salix/components/log/style.scss +++ b/front/salix/components/log/style.scss @@ -1,14 +1,49 @@ -@import "variables"; -@import "effects"; +@import "util"; vn-log { - .change { + .origin-log { + &:first-child > .origin-info { + margin-top: 0; + } + & > .origin-info { + display: flex; + align-items: center; + margin-top: 28px; + gap: 6px; + + & > .origin-id { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + color: $color-font-secondary; + margin: 0; + } + & > .line { + flex-grow: 1; + background-color: $color-font-secondary; + height: 2px; + } + } + } + .user-log { display: flex; - & > .left { + & > .timeline { position: relative; padding-right: 10px; + width: 38px; + min-width: 38px; + flex-grow: auto; + & > .arrow { + height: 8px; + width: 8px; + position: absolute; + transform: rotateY(0deg) rotate(45deg); + top: 15px; + right: -4px; + z-index: 1; + } & > vn-avatar { cursor: pointer; @@ -16,136 +51,187 @@ vn-log { background-color: $color-main !important; } } - & > .arrow { - height: 8px; - width: 8px; - position: absolute; - transform: rotateY(0deg) rotate(45deg); - top: 18px; - right: -4px; - z-index: 1; - } & > .line { position: absolute; background-color: $color-main; width: 2px; - left: 17px; + left: 18px; z-index: -1; top: 44px; - bottom: -8px; + bottom: -2px; } } - &:last-child > .left > .line { + &:last-child > .timeline > .line { display: none; } - .detail { - position: relative; + & > .user-changes { flex-grow: 1; - width: 100%; - border-radius: 2px; + overflow: hidden; + } + } + .model-log { + & > .model-info { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + min-height: 22px; + + & > .model-name { + display: inline-block; + padding: 2px 5px; + color: $color-font-dark; + border-radius: 8px; + vertical-align: middle; + } + & > .model-value { + font-style: italic; + } + & > .model-id { + color: $color-font-secondary; + font-size: .9rem; + } + & > vn-icon[icon="filter_alt"] { + @extend %clickable-light; + vertical-align: middle; + font-size: 18px; + color: $color-font-secondary; + float: right; + display: none; + + @include mobile { + display: initial; + } + } + } + &:hover > .model-info > vn-icon[icon="filter_alt"] { + display: initial; + } + } + .changes-log { + position: relative; + max-width: 100%; + width: 100%; + border-radius: 2px; + overflow: hidden; + + &:last-child { + margin-bottom: 0; + } + & > .change-info { + display: flex; + justify-content: space-between; + align-items: center; overflow: hidden; - & > .header { - display: flex; - justify-content: space-between; - align-items: center; - overflow: hidden; - - & > .action-model { - display: inline-flex; - overflow: hidden; - - & > .model-name { - display: inline-block; - padding: 2px 5px; - color: $color-font-dark; - border-radius: 8px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - } - & > .action-date { - white-space: nowrap; - - & > .action { - display: inline-flex; - align-items: center; - justify-content: center; - color: $color-font-bg; - vertical-align: middle; - border-radius: 50%; - width: 24px; - height: 24px; - font-size: 1.4em; - - &.notice { - background-color: $color-notice-medium - } - &.success { - background-color: $color-success-medium; - } - &.warning { - background-color: $color-main-medium; - } - &.alert { - background-color: lighten($color-alert, 5%); - } - } - } - } - & > .model { + & > .date { overflow: hidden; + white-space: nowrap; text-overflow: ellipsis; + } + & > div { white-space: nowrap; - & > .model-value { - font-style: italic; - } - & > .model-id { + & > vn-icon.pit { + @extend %clickable-light; + vertical-align: middle; + font-size: 20px; color: $color-font-secondary; - font-size: .9rem; - float: right; + display: none; + + @include mobile { + display: inline-block; + } + } + & > .action { + display: inline-flex; + align-items: center; + justify-content: center; + color: $color-font-bg; + vertical-align: middle; + border-radius: 50%; + width: 24px; + height: 24px; + font-size: 18px; + + &.notice { + background-color: $color-notice-medium + } + &.success { + background-color: $color-success-medium; + } + &.warning { + background-color: $color-main-medium; + } + &.alert { + background-color: lighten($color-alert, 5%); + } } } + &:hover vn-icon.pit { + display: inline-block; + } } - } - .changes { - overflow: hidden; - background-color: rgba(255, 255, 255, .05); - color: $color-font-light; - position: relative; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - min-height: 34px; - box-sizing: border-box; - - & > vn-icon { - @extend %clickable; - float: right; + & > .change-detail { + overflow: hidden; + background-color: rgba(255, 255, 255, .05); + color: $color-font-light; position: relative; - transition-property: transform, background-color; - transition-duration: 150ms; - margin: -5px; - margin-left: 4px; - padding: 1px; - border-radius: 50%; - } - &.expanded { - text-overflow: initial; - white-space: initial; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-height: 34px; + box-sizing: border-box; & > vn-icon { - transform: rotate(180deg); + @extend %clickable; + float: right; + position: relative; + transition-property: transform, background-color; + transition-duration: 150ms; + margin: -5px; + margin-left: 4px; + padding: 1px; + border-radius: 50%; + } + &.expanded { + text-overflow: initial; + white-space: initial; + + & > vn-icon { + transform: rotate(180deg); + } + } + & > .no-changes { + font-style: italic; } } - & > .no-changes { - font-style: italic; + } + .id-value { + font-size: .9rem; + color: $color-font-secondary; + } +} +.vn-log-instance { + display: block; + + & > .loading { + display: flex; + justify-content: center; + } + & > .instance { + min-width: 180px; + max-width: 400px; + + & > .header { + background-color: $color-main; + color: $color-font-dark; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + margin: 0; + } + & > .change-detail { + color: $color-font-light; } } } -vn-log-value > .id-value { - font-size: .9rem; - color: $color-font-secondary; -} diff --git a/front/salix/components/login/index.js b/front/salix/components/login/index.js index 150e896a1..8e8f08244 100644 --- a/front/salix/components/login/index.js +++ b/front/salix/components/login/index.js @@ -5,10 +5,11 @@ import './style.scss'; * A simple login form. */ export default class Controller { - constructor($, $element, vnAuth) { + constructor($, $element, $state, vnAuth) { Object.assign(this, { $, $element, + $state, vnAuth, user: localStorage.getItem('lastUser'), remember: true @@ -22,11 +23,15 @@ export default class Controller { localStorage.setItem('lastUser', this.user); this.loading = false; }) - .catch(err => { + .catch(req => { this.loading = false; this.password = ''; this.focusUser(); - throw err; + const err = req.data?.error; + if (err?.code == 'passExpired') + this.$state.go('change-password', err.details.token); + + throw req; }); } @@ -35,7 +40,7 @@ export default class Controller { this.$.userField.focus(); } } -Controller.$inject = ['$scope', '$element', 'vnAuth']; +Controller.$inject = ['$scope', '$element', '$state', 'vnAuth']; ngModule.vnComponent('vnLogin', { template: require('./index.html'), diff --git a/front/salix/components/outLayout/style.scss b/front/salix/components/outLayout/style.scss index aa94fefb3..a95b75835 100644 --- a/front/salix/components/outLayout/style.scss +++ b/front/salix/components/outLayout/style.scss @@ -64,4 +64,25 @@ vn-out-layout{ a{ color: $color-primary; } + + .footer { + margin-top: 32px; + text-align: center; + position: relative; + & > .vn-submit { + display: block; + + & > input { + display: block; + width: 100%; + } + } + & > .spinner-wrapper { + position: absolute; + width: 0; + top: 3px; + right: -8px; + overflow: visible; + } + } } diff --git a/front/salix/components/recover-password/index.js b/front/salix/components/recover-password/index.js index e91169588..5ffc305f9 100644 --- a/front/salix/components/recover-password/index.js +++ b/front/salix/components/recover-password/index.js @@ -1,5 +1,4 @@ import ngModule from '../../module'; -import './style.scss'; export default class Controller { constructor($scope, $element, $http, vnApp, $translate, $state) { diff --git a/front/salix/components/recover-password/style.scss b/front/salix/components/recover-password/style.scss deleted file mode 100644 index d3c6f594e..000000000 --- a/front/salix/components/recover-password/style.scss +++ /dev/null @@ -1,24 +0,0 @@ -@import "variables"; - -vn-recover-password{ - .footer { - margin-top: 32px; - text-align: center; - position: relative; - & > .vn-submit { - display: block; - - & > input { - display: block; - width: 100%; - } - } - & > .spinner-wrapper { - position: absolute; - width: 0; - top: 3px; - right: -8px; - overflow: visible; - } - } -} diff --git a/front/salix/components/reset-password/index.js b/front/salix/components/reset-password/index.js index a3ca03237..c0a10cc52 100644 --- a/front/salix/components/reset-password/index.js +++ b/front/salix/components/reset-password/index.js @@ -1,5 +1,5 @@ import ngModule from '../../module'; -import './style.scss'; +const UserError = require('vn-loopback/util/user-error'); export default class Controller { constructor($scope, $element, $http, vnApp, $translate, $state, $location) { diff --git a/front/salix/components/reset-password/style.scss b/front/salix/components/reset-password/style.scss deleted file mode 100644 index 87e4adc8c..000000000 --- a/front/salix/components/reset-password/style.scss +++ /dev/null @@ -1,24 +0,0 @@ -@import "variables"; - -vn-reset-password{ - .footer { - margin-top: 32px; - text-align: center; - position: relative; - & > .vn-submit { - display: block; - - & > input { - display: block; - width: 100%; - } - } - & > .spinner-wrapper { - position: absolute; - width: 0; - top: 3px; - right: -8px; - overflow: visible; - } - } -} diff --git a/front/salix/routes.js b/front/salix/routes.js index 4cc72ec95..675da719a 100644 --- a/front/salix/routes.js +++ b/front/salix/routes.js @@ -36,6 +36,12 @@ function config($stateProvider, $urlRouterProvider) { description: 'Reset password', template: '' }) + .state('change-password', { + parent: 'outLayout', + url: '/change-password?id&userId', + description: 'Change password', + template: '' + }) .state('home', { parent: 'layout', url: '/', diff --git a/front/salix/styles/misc.scss b/front/salix/styles/misc.scss index 02bfd9f17..9b2829d0b 100644 --- a/front/salix/styles/misc.scss +++ b/front/salix/styles/misc.scss @@ -1,5 +1,4 @@ -@import "./variables"; -@import "./effects"; +@import "./util"; form vn-horizontal { align-items: center; @@ -22,10 +21,10 @@ form vn-horizontal { } } - @media screen and (max-width: $mobile-width) { + @include mobile { flex-direction: column; align-items: initial; - + & > * { &, &:first-child, diff --git a/loopback/common/methods/log/pitInstance.js b/loopback/common/methods/log/pitInstance.js new file mode 100644 index 000000000..cb671cb7e --- /dev/null +++ b/loopback/common/methods/log/pitInstance.js @@ -0,0 +1,91 @@ +const NotFoundError = require('vn-loopback/util/not-found-error'); + +module.exports = Self => { + Self.remoteMethod('pitInstance', { + description: 'Gets the status of instance at specific point in time', + accepts: [ + { + arg: 'id', + type: 'integer', + description: 'The log id', + required: true + } + ], + returns: { + type: [Self], + root: true + }, + http: { + path: `/:id/pitInstance`, + verb: 'GET' + } + }); + + Self.pitInstance = async function(id) { + const log = await Self.findById(id, { + fields: [ + 'changedModel', + 'changedModelId', + 'creationDate' + ] + }); + if (!log) + throw new NotFoundError(); + + const where = { + changedModel: log.changedModel, + changedModelId: log.changedModelId + }; + + // Fetch creation and all update logs for record up to requested log + + const createdWhere = { + action: 'insert', + creationDate: {lte: log.creationDate} + }; + const createdLog = await Self.findOne({ + fields: ['id', 'creationDate', 'newInstance'], + where: Object.assign(createdWhere, where), + order: 'creationDate DESC, id DESC' + }); + + const instance = {}; + + let logsWhere = { + action: 'update' + }; + if (createdLog) { + Object.assign(instance, createdLog.newInstance); + Object.assign(logsWhere, { + creationDate: {between: [ + createdLog.creationDate, + log.creationDate + ]}, + id: {between: [ + Math.min(id, createdLog.id), + Math.max(id, createdLog.id) + ]} + }); + } else { + Object.assign(logsWhere, { + creationDate: {lte: log.creationDate}, + id: {lte: id} + }); + } + + const logs = await Self.find({ + fields: ['newInstance'], + where: Object.assign(logsWhere, where), + order: 'creationDate, id' + }); + if (!logs.length && !createdLog) + throw new NotFoundError('No logs found for record'); + + // Merge all logs in order into one instance + + for (const log of logs) + Object.assign(instance, log.newInstance); + + return instance; + }; +}; diff --git a/loopback/common/models/log.js b/loopback/common/models/log.js index 0622431a6..b0d3cfc00 100644 --- a/loopback/common/models/log.js +++ b/loopback/common/models/log.js @@ -5,6 +5,7 @@ module.exports = function(Self) { Self.super_.setup.call(this); require('../methods/log/editors')(this); require('../methods/log/models')(this); + require('../methods/log/pitInstance')(this); } }); }; diff --git a/loopback/common/models/vn-model.js b/loopback/common/models/vn-model.js index 37328247b..22b535f62 100644 --- a/loopback/common/models/vn-model.js +++ b/loopback/common/models/vn-model.js @@ -2,7 +2,6 @@ const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const UserError = require('vn-loopback/util/user-error'); const utils = require('loopback/lib/utils'); -const {util} = require('webpack'); module.exports = function(Self) { Self.ParameterizedSQL = ParameterizedSQL; @@ -196,8 +195,45 @@ module.exports = function(Self) { /* * Shortcut to VnMySQL.executeP() */ - rawSql(query, params, options, cb) { - return this.dataSource.connector.executeP(query, params, options, cb); + async rawSql(query, params, options) { + const userId = options?.userId; + const connector = this.dataSource.connector; + let conn; + let res; + + try { + if (userId) { + if (!options.transaction) { + options = Object.assign({}, options); + conn = await new Promise((resolve, reject) => { + connector.client.getConnection(function(err, conn) { + if (err) + reject(err); + else + resolve(conn); + }); + }); + options.transaction = { + connection: conn, + connector + }; + } + + await connector.executeP( + 'CALL account.myUser_loginWithName((SELECT name FROM account.user WHERE id = ?))', + [userId], options + ); + } + + res = await connector.executeP(query, params, options); + + if (userId) + await connector.executeP('CALL account.myUser_logout()', null, options); + } finally { + if (conn) conn.release(); + } + + return res; }, /* diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 14ffffeb5..40df9a712 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -115,7 +115,7 @@ "This client is not invoiceable": "This client is not invoiceable", "INACTIVE_PROVIDER": "Inactive provider", "reference duplicated": "reference duplicated", - "The PDF document does not exists": "The PDF document does not exists. Try regenerating it from 'Regenerate invoice PDF' option", + "The PDF document does not exist": "The PDF document does not exists. Try regenerating it from 'Regenerate invoice PDF' option", "This item is not available": "This item is not available", "Deny buy request": "Purchase request for ticket id [{{ticketId}}]({{{url}}}) has been rejected. Reason: {{observation}}", "The type of business must be filled in basic data": "The type of business must be filled in basic data", @@ -172,6 +172,9 @@ "Comment added to client": "Comment added to client", "This ticket is already a refund": "This ticket is already a refund", "A claim with that sale already exists": "A claim with that sale already exists", + "Pass expired": "The password has expired, change it from Salix", "Can't transfer claimed sales": "Can't transfer claimed sales", - "Invalid quantity": "Invalid quantity" + "Invalid quantity": "Invalid quantity", + "Failed to upload delivery note": "Error to upload delivery note {{id}}", + "Mail not sent": "There has been an error sending the invoice to the client [{{clientId}}]({{{clientUrl}}}), please check the email address" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 3b1c331c7..abb62d492 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -77,7 +77,6 @@ "This ticket can not be modified": "Este ticket no puede ser modificado", "The introduced hour already exists": "Esta hora ya ha sido introducida", "INFINITE_LOOP": "Existe una dependencia entre dos Jefes", - "The sales of the current ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas", "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros", "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado", @@ -212,7 +211,7 @@ "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito", "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas", "Amounts do not match": "Las cantidades no coinciden", - "The PDF document does not exists": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", + "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos", "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días", "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", @@ -259,14 +258,14 @@ "App name does not exist": "El nombre de aplicación no es válido", "Try again": "Vuelve a intentarlo", "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9", - "Failed to upload file": "Error al subir archivo", + "Failed to upload delivery note": "Error al subir albarán {{id}}", "The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe", "It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar", "It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo", "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas", "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.", "There is no assigned email for this client": "No hay correo asignado para este cliente", - "Exists an invoice with a previous date": "Existe una factura con fecha anterior", + "Exists an invoice with a future date": "Existe una factura con fecha posterior", "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite", "Warehouse inventory not set": "El almacén inventario no está establecido", "This locker has already been assigned": "Esta taquilla ya ha sido asignada", @@ -291,8 +290,14 @@ "isTaxDataChecked": "Datos comprobados", "comercialId": "Id comercial", "comercialName": "Comercial", + "Pass expired": "La contraseña ha caducado, cambiela desde Salix", "Invalid NIF for VIES": "Invalid NIF for VIES", "Ticket does not exist": "Este ticket no existe", "Ticket is already signed": "Este ticket ya ha sido firmado", - "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono" + "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono", + "Fecha fuera de rango": "Fecha fuera de rango", + "Error while generating PDF": "Error al generar PDF", + "Error when sending mail to client": "Error al enviar el correo al cliente", + "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico", + "The renew period has not been exceeded": "El periodo de renovación no ha sido superado" } diff --git a/modules/account/back/locale/account/en.yml b/modules/account/back/locale/account/en.yml new file mode 100644 index 000000000..221afef5f --- /dev/null +++ b/modules/account/back/locale/account/en.yml @@ -0,0 +1,3 @@ +name: account +columns: + id: id diff --git a/modules/account/back/locale/account/es.yml b/modules/account/back/locale/account/es.yml new file mode 100644 index 000000000..a79b1f40c --- /dev/null +++ b/modules/account/back/locale/account/es.yml @@ -0,0 +1,3 @@ +name: cuenta +columns: + id: id diff --git a/modules/account/back/locale/mail-alias-account/en.yml b/modules/account/back/locale/mail-alias-account/en.yml new file mode 100644 index 000000000..bf805d66f --- /dev/null +++ b/modules/account/back/locale/mail-alias-account/en.yml @@ -0,0 +1,5 @@ +name: mail alias +columns: + id: id + mailAlias: alias + account: account diff --git a/modules/account/back/locale/mail-alias-account/es.yml b/modules/account/back/locale/mail-alias-account/es.yml new file mode 100644 index 000000000..b53ade996 --- /dev/null +++ b/modules/account/back/locale/mail-alias-account/es.yml @@ -0,0 +1,5 @@ +name: alias de correo +columns: + id: id + mailAlias: alias + account: cuenta diff --git a/modules/account/back/methods/account/change-password.js b/modules/account/back/methods/account/change-password.js index 549508ffa..c6f08a232 100644 --- a/modules/account/back/methods/account/change-password.js +++ b/modules/account/back/methods/account/change-password.js @@ -28,8 +28,6 @@ module.exports = Self => { }); Self.changePassword = async function(id, oldPassword, newPassword) { - await Self.rawSql(`CALL account.user_changePassword(?, ?, ?)`, - [id, oldPassword, newPassword]); - await Self.app.models.Account.syncById(id, newPassword); + await Self.app.models.VnUser.changePassword(id, oldPassword, newPassword); }; }; diff --git a/modules/account/back/methods/account/set-password.js b/modules/account/back/methods/account/set-password.js index b4204d103..010197e0d 100644 --- a/modules/account/back/methods/account/set-password.js +++ b/modules/account/back/methods/account/set-password.js @@ -22,8 +22,6 @@ module.exports = Self => { }); Self.setPassword = async function(id, newPassword) { - await Self.rawSql(`CALL account.user_setPassword(?, ?)`, - [id, newPassword]); - await Self.app.models.Account.syncById(id, newPassword); + await Self.app.models.VnUser.setPassword(id, newPassword); }; }; diff --git a/modules/account/back/methods/account/specs/change-password.spec.js b/modules/account/back/methods/account/specs/change-password.spec.js index 17fadb3c6..0fd6ecbd5 100644 --- a/modules/account/back/methods/account/specs/change-password.spec.js +++ b/modules/account/back/methods/account/specs/change-password.spec.js @@ -2,11 +2,21 @@ const {models} = require('vn-loopback/server/server'); describe('account changePassword()', () => { it('should throw an error when old password is wrong', async() => { - let err; - await models.Account.changePassword(1, 'wrongPassword', 'nightmare.9999') - .catch(error => err = error.sqlMessage); + let error; + try { + await models.Account.changePassword(1, 'wrongPassword', 'nightmare.9999'); + } catch (e) { + error = e.message; + } - expect(err).toBeDefined(); - expect(err).toEqual('Invalid password'); + expect(error).toContain('Invalid current password'); + }); + + it('should change password', async() => { + try { + await models.Account.changePassword(70, 'nightmare', 'nightmare.9999'); + } catch (e) { + expect(e).toBeUndefined(); + } }); }); diff --git a/modules/account/back/methods/account/sync-by-id.js b/modules/account/back/methods/account/sync-by-id.js index 538bc09bd..e1c631395 100644 --- a/modules/account/back/methods/account/sync-by-id.js +++ b/modules/account/back/methods/account/sync-by-id.js @@ -24,8 +24,8 @@ module.exports = Self => { } }); - Self.syncById = async function(id, password, force) { - let user = await Self.app.models.VnUser.findById(id, {fields: ['name']}); - await Self.sync(user.name, password, force); + Self.syncById = async function(id, password, force, options) { + let user = await Self.app.models.VnUser.findById(id, {fields: ['name']}, options); + await Self.sync(user.name, password, force, options); }; }; diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js index 8668be343..a5befc22c 100644 --- a/modules/account/back/methods/account/sync.js +++ b/modules/account/back/methods/account/sync.js @@ -24,17 +24,22 @@ module.exports = Self => { } }); - Self.sync = async function(userName, password, force) { + Self.sync = async function(userName, password, force, options) { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const models = Self.app.models; const user = await models.VnUser.findOne({ fields: ['id'], where: {name: userName} - }); - const isSync = !await models.UserSync.exists(userName); + }, myOptions); + const isSync = !await models.UserSync.exists(userName, myOptions); if (!force && isSync && user) return; await models.AccountConfig.syncUser(userName, password); - await models.UserSync.destroyById(userName); + await models.UserSync.destroyById(userName, myOptions); }; }; diff --git a/modules/account/back/models/account-config.js b/modules/account/back/models/account-config.js index 5c9d92f1e..0db699b99 100644 --- a/modules/account/back/models/account-config.js +++ b/modules/account/back/models/account-config.js @@ -1,5 +1,5 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; module.exports = Self => { Object.assign(Self, { @@ -63,7 +63,7 @@ module.exports = Self => { Object.assign(Self.prototype, { async synchronizerInit() { - let mailConfig = await app.models.MailConfig.findOne({ + let mailConfig = await models.MailConfig.findOne({ fields: ['domain'] }); @@ -91,8 +91,6 @@ module.exports = Self => { }, async synchronizerSyncUser(userName, password, syncGroups) { - let $ = app.models; - if (!userName) return; userName = userName.toLowerCase(); @@ -100,7 +98,7 @@ module.exports = Self => { if (['administrator', 'root'].indexOf(userName) >= 0) return; - let user = await $.VnUser.findOne({ + let user = await models.VnUser.findOne({ where: {name: userName}, fields: [ 'id', @@ -111,7 +109,7 @@ module.exports = Self => { 'sync', 'active', 'created', - 'bcryptPassword', + 'password', 'updated' ], include: [ @@ -138,7 +136,7 @@ module.exports = Self => { }; if (user) { - let exists = await $.Account.exists(user.id); + let exists = await models.Account.exists(user.id); Object.assign(info, { hasAccount: user.active && exists, corporateMail: `${userName}@${this.domain}`, @@ -173,30 +171,6 @@ module.exports = Self => { async synchronizerSyncRoles() { for (let synchronizer of this.synchronizers) await synchronizer.syncRoles(); - }, - - async syncUser(userName, info, password) { - if (info.user && password) - await app.models.VnUser.setPassword(info.user.id, password); - }, - - async getUsers(usersToSync) { - let accounts = await app.models.Account.find({ - fields: ['id'], - include: { - relation: 'user', - scope: { - fields: ['name'], - where: {active: true} - } - } - }); - - for (let account of accounts) { - let user = account.user(); - if (!user) continue; - usersToSync.add(user.name); - } } }); }; diff --git a/modules/account/back/models/account-config.json b/modules/account/back/models/account-config.json index 1c643ac38..a2a405610 100644 --- a/modules/account/back/models/account-config.json +++ b/modules/account/back/models/account-config.json @@ -6,9 +6,6 @@ "table": "account.accountConfig" } }, - "mixins": { - "AccountSynchronizer": {} - }, "properties": { "id": { "type": "number", diff --git a/modules/account/front/accounts/index.js b/modules/account/front/accounts/index.js index 7a341b0b0..0e78ab8d6 100644 --- a/modules/account/front/accounts/index.js +++ b/modules/account/front/accounts/index.js @@ -5,8 +5,7 @@ import UserError from 'core/lib/user-error'; export default class Controller extends Section { onSynchronizeAll() { this.vnApp.showSuccess(this.$t('Synchronizing in the background')); - this.$http.patch(`Accounts/syncAll`) - .then(() => this.vnApp.showSuccess(this.$t('Users synchronized!'))); + this.$http.patch(`Accounts/syncAll`); } onUserSync() { diff --git a/modules/account/front/aliases/index.html b/modules/account/front/aliases/index.html index 9f4ba857f..11d546afb 100644 --- a/modules/account/front/aliases/index.html +++ b/modules/account/front/aliases/index.html @@ -17,7 +17,9 @@ + ng-click="removeConfirm.show(row)" + vn-acl="itManagement" + vn-acl-action="remove"> @@ -30,9 +32,11 @@ translate-attr="{title: 'Add'}" vn-bind="+" ng-click="$ctrl.onAddClick()" - fixed-bottom-right> + fixed-bottom-right + vn-acl="itManagement" + vn-acl-action="remove"> - @@ -49,7 +53,7 @@ - this.user = res.data), + this.$http.get(`VnUsers/preview`, {filter}) + .then(res => { + const [user] = res.data; + this.user = user; + }), this.$http.get(`Accounts/${this.$params.id}/exists`) .then(res => this.hasAccount = res.data.exists) ]); diff --git a/modules/account/front/card/index.spec.js b/modules/account/front/card/index.spec.js index 204b897e4..712d3c1d8 100644 --- a/modules/account/front/card/index.spec.js +++ b/modules/account/front/card/index.spec.js @@ -15,12 +15,12 @@ describe('component vnUserCard', () => { it('should reload the controller data', () => { controller.$params.id = 1; - $httpBackend.expectGET('VnUsers/1').respond('foo'); + $httpBackend.expectGET('VnUsers/preview').respond('foo'); $httpBackend.expectGET('Accounts/1/exists').respond({exists: true}); controller.reload(); $httpBackend.flush(); - expect(controller.user).toBe('foo'); + expect(controller.user).toBe('f'); expect(controller.hasAccount).toBeTruthy(); }); }); diff --git a/modules/account/front/create/index.html b/modules/account/front/create/index.html index ee2de926a..acc07d346 100644 --- a/modules/account/front/create/index.html +++ b/modules/account/front/create/index.html @@ -12,18 +12,18 @@ @@ -39,7 +39,7 @@ type="password"> diff --git a/modules/account/front/create/index.js b/modules/account/front/create/index.js index 41fd718f6..01ba7905b 100644 --- a/modules/account/front/create/index.js +++ b/modules/account/front/create/index.js @@ -2,6 +2,11 @@ import ngModule from '../module'; import Section from 'salix/components/section'; export default class Controller extends Section { + constructor($element, $) { + super($element, $); + this.user = {active: true}; + } + onSubmit() { return this.$.watcher.submit().then(res => { this.$state.go('account.card.basicData', {id: res.data.id}); diff --git a/modules/account/front/descriptor/index.html b/modules/account/front/descriptor/index.html index 7a7ba43f3..381b2991c 100644 --- a/modules/account/front/descriptor/index.html +++ b/modules/account/front/descriptor/index.html @@ -6,7 +6,7 @@ Delete @@ -15,7 +15,7 @@ ng-if="::$root.user.id == $ctrl.id" ng-click="$ctrl.onChangePassClick(true)" name="changePassword" - vn-acl="hr" + vn-acl="sysadmin" vn-acl-action="remove" translate> Change password @@ -23,7 +23,7 @@ Set password @@ -32,7 +32,7 @@ ng-if="!$ctrl.hasAccount" ng-click="enableAccount.show()" name="enableAccount" - vn-acl="it" + vn-acl="sysadmin" vn-acl-action="remove" translate> Enable account @@ -41,7 +41,7 @@ ng-if="$ctrl.hasAccount" ng-click="disableAccount.show()" name="disableAccount" - vn-acl="it" + vn-acl="sysadmin" vn-acl-action="remove" translate> Disable account @@ -50,7 +50,7 @@ ng-if="!$ctrl.user.active" ng-click="activateUser.show()" name="activateUser" - vn-acl="hr" + vn-acl="itManagement" vn-acl-action="remove" translate> Activate user @@ -59,7 +59,7 @@ ng-if="$ctrl.user.active" ng-click="deactivateUser.show()" name="deactivateUser" - vn-acl="hr" + vn-acl="itManagement" vn-acl-action="remove" translate> Deactivate user diff --git a/modules/account/front/index/index.html b/modules/account/front/index/index.html index d067c8c37..7502c8b3d 100644 --- a/modules/account/front/index/index.html +++ b/modules/account/front/index/index.html @@ -14,11 +14,11 @@
{{::user.nickname}}
@@ -36,12 +36,12 @@ - - \ No newline at end of file + diff --git a/modules/account/front/mail-forwarding/index.html b/modules/account/front/mail-forwarding/index.html index 6c688f504..df5cd80bf 100644 --- a/modules/account/front/mail-forwarding/index.html +++ b/modules/account/front/mail-forwarding/index.html @@ -14,12 +14,12 @@ Todos los correos serán reenviados a la dirección especificada, no se mantendrá copia de los mismos en el buzón del usuario. +You don't have enough privileges: No tienes suficientes permisos diff --git a/modules/account/front/main/index.html b/modules/account/front/main/index.html index 5872a328d..36b493ec4 100644 --- a/modules/account/front/main/index.html +++ b/modules/account/front/main/index.html @@ -1,6 +1,6 @@ diff --git a/modules/account/front/privileges/index.html b/modules/account/front/privileges/index.html index 8e33b708e..61f2c534e 100644 --- a/modules/account/front/privileges/index.html +++ b/modules/account/front/privileges/index.html @@ -1,9 +1,7 @@ @@ -11,15 +9,16 @@ name="form" ng-submit="watcher.submit()" class="vn-w-md"> - + - + + + this.$.summary = res.data); + this.$http.get(`VnUsers/preview`, {filter}) + .then(res => { + const [summary] = res.data; + this.$.summary = summary; + }); } get isHr() { return this.aclService.hasAny(['hr']); diff --git a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js index 83043f012..cdf3fc2c3 100644 --- a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js +++ b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js @@ -63,7 +63,7 @@ module.exports = Self => { }; let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/client/back/locale/client/en.yml b/modules/client/back/locale/client/en.yml index 74384461c..ad21a6ce6 100644 --- a/modules/client/back/locale/client/en.yml +++ b/modules/client/back/locale/client/en.yml @@ -52,4 +52,5 @@ columns: hasInvoiceSimplified: simplified invoice typeFk: type lastSalesPersonFk: last salesperson - + rating: rating + recommendedCredit: recommended credit diff --git a/modules/client/back/locale/client/es.yml b/modules/client/back/locale/client/es.yml index 47bf896d9..b17f53b1c 100644 --- a/modules/client/back/locale/client/es.yml +++ b/modules/client/back/locale/client/es.yml @@ -52,4 +52,5 @@ columns: hasInvoiceSimplified: factura simple typeFk: tipo lastSalesPersonFk: último comercial - + rating: clasificación + recommendedCredit: crédito recomendado diff --git a/modules/client/back/methods/client/confirmTransaction.js b/modules/client/back/methods/client/confirmTransaction.js index a1969d6fd..fcb33c4ca 100644 --- a/modules/client/back/methods/client/confirmTransaction.js +++ b/modules/client/back/methods/client/confirmTransaction.js @@ -23,7 +23,7 @@ module.exports = Self => { const userId = ctx.req.accessToken.userId; let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/client/back/methods/client/consumptionSendQueued.js b/modules/client/back/methods/client/consumptionSendQueued.js index 07b5fb57b..a7081c550 100644 --- a/modules/client/back/methods/client/consumptionSendQueued.js +++ b/modules/client/back/methods/client/consumptionSendQueued.js @@ -1,7 +1,7 @@ const {Email} = require('vn-print'); module.exports = Self => { - Self.remoteMethod('consumptionSendQueued', { + Self.remoteMethodCtx('consumptionSendQueued', { description: 'Send all queued invoices', accessType: 'WRITE', accepts: [], @@ -15,7 +15,7 @@ module.exports = Self => { } }); - Self.consumptionSendQueued = async() => { + Self.consumptionSendQueued = async ctx => { const queues = await Self.rawSql(` SELECT id, @@ -68,7 +68,7 @@ module.exports = Self => { SET status = 'printed', printed = ? WHERE id = ?`, - [Date.vnNew(), queue.id]); + [Date.vnNew(), queue.id], {userId: ctx.req.accessToken.userId}); } catch (error) { await Self.rawSql(` UPDATE clientConsumptionQueue diff --git a/modules/client/back/methods/client/createReceipt.js b/modules/client/back/methods/client/createReceipt.js index cb032270a..b70b9bbe0 100644 --- a/modules/client/back/methods/client/createReceipt.js +++ b/modules/client/back/methods/client/createReceipt.js @@ -55,7 +55,7 @@ module.exports = function(Self) { date.setHours(0, 0, 0, 0); let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index 1ae569fd3..3bf29501b 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -72,7 +72,7 @@ module.exports = Self => { Self.filter = async(ctx, filter, options) => { const conn = Self.dataSource.connector; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; const postalCode = []; const args = ctx.args; @@ -120,7 +120,7 @@ module.exports = Self => { const stmts = []; const stmt = new ParameterizedSQL( - `SELECT + `SELECT DISTINCT c.id, c.name, c.fi, diff --git a/modules/client/back/methods/client/getCard.js b/modules/client/back/methods/client/getCard.js index 48840b036..10e6f7adf 100644 --- a/modules/client/back/methods/client/getCard.js +++ b/modules/client/back/methods/client/getCard.js @@ -1,5 +1,5 @@ module.exports = function(Self) { - Self.remoteMethod('getCard', { + Self.remoteMethodCtx('getCard', { description: 'Get client basic data and debt', accepts: { arg: 'id', @@ -18,8 +18,8 @@ module.exports = function(Self) { } }); - Self.getCard = async(id, options) => { - const myOptions = {}; + Self.getCard = async(ctx, id, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/client/back/methods/client/getDebt.js b/modules/client/back/methods/client/getDebt.js index 859746083..6ed59684b 100644 --- a/modules/client/back/methods/client/getDebt.js +++ b/modules/client/back/methods/client/getDebt.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('getDebt', { + Self.remoteMethodCtx('getDebt', { description: 'Returns the boolean debt of a client', accessType: 'READ', accepts: [{ @@ -19,8 +19,8 @@ module.exports = Self => { } }); - Self.getDebt = async(clientFk, options) => { - const myOptions = {}; + Self.getDebt = async(ctx, clientFk, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/client/back/methods/client/specs/getCard.spec.js b/modules/client/back/methods/client/specs/getCard.spec.js index e713c9883..962e0a2d4 100644 --- a/modules/client/back/methods/client/specs/getCard.spec.js +++ b/modules/client/back/methods/client/specs/getCard.spec.js @@ -5,10 +5,11 @@ describe('Client getCard()', () => { const tx = await models.Client.beginTransaction({}); try { + const ctx = {req: {accessToken: {userId: 9}}}; const options = {transaction: tx}; const id = 1101; - const result = await models.Client.getCard(id, options); + const result = await models.Client.getCard(ctx, id, options); expect(result.id).toEqual(id); expect(result.name).toEqual('Bruce Wayne'); diff --git a/modules/client/back/methods/client/specs/getDebt.spec.js b/modules/client/back/methods/client/specs/getDebt.spec.js index 471d45a6d..b3b5286c0 100644 --- a/modules/client/back/methods/client/specs/getDebt.spec.js +++ b/modules/client/back/methods/client/specs/getDebt.spec.js @@ -3,11 +3,12 @@ const models = require('vn-loopback/server/server').models; describe('client getDebt()', () => { it('should return the client debt', async() => { const tx = await models.Client.beginTransaction({}); + const ctx = {req: {accessToken: {userId: 9}}}; try { const options = {transaction: tx}; - const result = await models.Client.getDebt(1101, options); + const result = await models.Client.getDebt(ctx, 1101, options); expect(result.debt).toEqual(jasmine.any(Number)); diff --git a/modules/client/back/methods/client/specs/summary.spec.js b/modules/client/back/methods/client/specs/summary.spec.js index f2d576e39..227f4c398 100644 --- a/modules/client/back/methods/client/specs/summary.spec.js +++ b/modules/client/back/methods/client/specs/summary.spec.js @@ -1,6 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('client summary()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should return a summary object containing data', async() => { const clientId = 1101; const tx = await models.Client.beginTransaction({}); @@ -8,7 +9,7 @@ describe('client summary()', () => { try { const options = {transaction: tx}; - const result = await models.Client.summary(clientId, options); + const result = await models.Client.summary(ctx, clientId, options); expect(result.id).toEqual(clientId); expect(result.name).toEqual('Bruce Wayne'); @@ -27,7 +28,7 @@ describe('client summary()', () => { try { const options = {transaction: tx}; - const result = await models.Client.summary(clientId, options); + const result = await models.Client.summary(ctx, clientId, options); expect(result.mana.mana).toEqual(0.34); @@ -45,7 +46,7 @@ describe('client summary()', () => { try { const options = {transaction: tx}; - const result = await models.Client.summary(clientId, options); + const result = await models.Client.summary(ctx, clientId, options); expect(result.debt.debt).toEqual(jasmine.any(Number)); @@ -63,7 +64,7 @@ describe('client summary()', () => { try { const options = {transaction: tx}; - const result = await models.Client.summary(clientId, options); + const result = await models.Client.summary(ctx, clientId, options); expect(result.averageInvoiced.invoiced).toEqual(1500); @@ -81,7 +82,7 @@ describe('client summary()', () => { try { const options = {transaction: tx}; - const result = await models.Client.summary(clientId, options); + const result = await models.Client.summary(ctx, clientId, options); expect(result.totalGreuge).toEqual(203.71); @@ -99,7 +100,7 @@ describe('client summary()', () => { try { const options = {transaction: tx}; - const result = await models.Client.summary(clientId, options); + const result = await models.Client.summary(ctx, clientId, options); expect(result.recovery).toEqual(null); @@ -117,7 +118,7 @@ describe('client summary()', () => { try { const options = {transaction: tx}; - const result = await models.Client.summary(clientId, options); + const result = await models.Client.summary(ctx, clientId, options); expect(result.recovery.id).toEqual(3); await tx.rollback(); diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js index 7dab1f68b..8de887b47 100644 --- a/modules/client/back/methods/client/summary.js +++ b/modules/client/back/methods/client/summary.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('summary', { + Self.remoteMethodCtx('summary', { description: 'Returns a client summary', accessType: 'READ', accepts: [{ @@ -19,7 +19,7 @@ module.exports = Self => { } }); - Self.summary = async(clientFk, options) => { + Self.summary = async(ctx, clientFk, options) => { const models = Self.app.models; const myOptions = {}; @@ -28,7 +28,7 @@ module.exports = Self => { const summaryObj = await getSummary(models.Client, clientFk, myOptions); summaryObj.mana = await models.Client.getMana(clientFk, myOptions); - summaryObj.debt = await models.Client.getDebt(clientFk, myOptions); + summaryObj.debt = await models.Client.getDebt(ctx, clientFk, myOptions); summaryObj.averageInvoiced = await models.Client.getAverageInvoiced(clientFk, myOptions); summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk, myOptions); summaryObj.recovery = await getRecoveries(models.Recovery, clientFk, myOptions); diff --git a/modules/client/back/methods/tpv-transaction/end.js b/modules/client/back/methods/tpv-transaction/end.js index 5a757aa48..3233f482f 100644 --- a/modules/client/back/methods/tpv-transaction/end.js +++ b/modules/client/back/methods/tpv-transaction/end.js @@ -34,6 +34,6 @@ module.exports = Self => { 'CALL hedera.tpvTransaction_end(?, ?)', [ orderId, status - ]); + ], {userId}); }; }; diff --git a/modules/client/back/methods/tpv-transaction/start.js b/modules/client/back/methods/tpv-transaction/start.js index ea6ed05eb..178c56d76 100644 --- a/modules/client/back/methods/tpv-transaction/start.js +++ b/modules/client/back/methods/tpv-transaction/start.js @@ -40,7 +40,7 @@ module.exports = Self => { amount, companyId, userId - ]); + ], {userId}); if (!row) throw new UserError('Transaction error'); diff --git a/modules/client/front/credit-management/index.html b/modules/client/front/credit-management/index.html index d7456fd06..b9064ff69 100644 --- a/modules/client/front/credit-management/index.html +++ b/modules/client/front/credit-management/index.html @@ -68,7 +68,7 @@ {{::clientInforma.rating}} - {{::clientInforma.recommendedCredit}} + {{::clientInforma.recommendedCredit | currency: 'EUR': 2}} diff --git a/modules/client/front/web-access/index.html b/modules/client/front/web-access/index.html index 15dc5ed58..74407ba5c 100644 --- a/modules/client/front/web-access/index.html +++ b/modules/client/front/web-access/index.html @@ -1,7 +1,5 @@ @@ -51,9 +49,9 @@ label="Save"> + ng-if="$ctrl.canChangePassword" + label="Change password" + vn-dialog="change-pass"> { + const [user] = res.data; + this.account = user; + }); + } + + get client() { + return this._client; + } + $onChanges() { if (this.client) { this.account = this.client.account; diff --git a/modules/client/front/web-access/index.spec.js b/modules/client/front/web-access/index.spec.js index c1bb47a8e..7325bf932 100644 --- a/modules/client/front/web-access/index.spec.js +++ b/modules/client/front/web-access/index.spec.js @@ -5,12 +5,14 @@ describe('Component VnClientWebAccess', () => { let $scope; let vnApp; let controller; + let $httpParamSerializer; beforeEach(ngModule('client')); - beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _vnApp_) => { + beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_, _vnApp_) => { $scope = $rootScope.$new(); $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; vnApp = _vnApp_; jest.spyOn(vnApp, 'showError'); const $element = angular.element(''); @@ -32,7 +34,10 @@ describe('Component VnClientWebAccess', () => { describe('isCustomer()', () => { it('should return true if the password can be modified', () => { controller.client = {id: '1234'}; + const filter = {where: {id: controller.client.id}}; + const serializedParams = $httpParamSerializer({filter}); + $httpBackend.expectGET(`VnUsers/preview?${serializedParams}`).respond('foo'); $httpBackend.expectGET(`Clients/${controller.client.id}/hasCustomerRole`).respond(true); controller.isCustomer(); $httpBackend.flush(); @@ -42,7 +47,10 @@ describe('Component VnClientWebAccess', () => { it(`should return a false if the password can't be modified`, () => { controller.client = {id: '1234'}; + const filter = {where: {id: controller.client.id}}; + const serializedParams = $httpParamSerializer({filter}); + $httpBackend.expectGET(`VnUsers/preview?${serializedParams}`).respond('foo'); $httpBackend.expectGET(`Clients/${controller.client.id}/hasCustomerRole`).respond(false); controller.isCustomer(); $httpBackend.flush(); @@ -54,9 +62,12 @@ describe('Component VnClientWebAccess', () => { describe('checkConditions()', () => { it('should perform a query to check if the client is valid', () => { controller.client = {id: '1234'}; + const filter = {where: {id: controller.client.id}}; + const serializedParams = $httpParamSerializer({filter}); expect(controller.canEnableCheckBox).toBeTruthy(); + $httpBackend.expectGET(`VnUsers/preview?${serializedParams}`).respond('foo'); $httpBackend.expectGET(`Clients/${controller.client.id}/isValidClient`).respond(false); controller.checkConditions(); $httpBackend.flush(); @@ -82,7 +93,10 @@ describe('Component VnClientWebAccess', () => { controller.newPassword = 'm24x8'; controller.repeatPassword = 'm24x8'; controller.canChangePassword = true; + const filter = {where: {id: controller.client.id}}; + const serializedParams = $httpParamSerializer({filter}); + $httpBackend.expectGET(`VnUsers/preview?${serializedParams}`).respond('foo'); const query = `Clients/${controller.client.id}/setPassword`; $httpBackend.expectPATCH(query, {newPassword: controller.newPassword}).respond('done'); controller.onPassChange(); diff --git a/modules/entry/back/methods/entry/addBuy.js b/modules/entry/back/methods/entry/addBuy.js deleted file mode 100644 index f612c1651..000000000 --- a/modules/entry/back/methods/entry/addBuy.js +++ /dev/null @@ -1,165 +0,0 @@ - -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; - -module.exports = Self => { - Self.remoteMethodCtx('addBuy', { - description: 'Inserts a new buy for the current entry', - accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'number', - required: true, - description: 'The entry id', - http: {source: 'path'} - }, - { - arg: 'itemFk', - type: 'number', - required: true - }, - { - arg: 'quantity', - type: 'number', - required: true - }, - { - arg: 'packageFk', - type: 'string', - required: true - }, - { - arg: 'packing', - type: 'number', - }, - { - arg: 'grouping', - type: 'number' - }, - { - arg: 'weight', - type: 'number', - }, - { - arg: 'stickers', - type: 'number', - }, - { - arg: 'price2', - type: 'number', - }, - { - arg: 'price3', - type: 'number', - }, - { - arg: 'buyingValue', - type: 'number' - }], - returns: { - type: 'object', - root: true - }, - http: { - path: `/:id/addBuy`, - verb: 'POST' - } - }); - - Self.addBuy = async(ctx, options) => { - const conn = Self.dataSource.connector; - let tx; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - const models = Self.app.models; - - ctx.args.entryFk = ctx.args.id; - - // remove unwanted properties - delete ctx.args.id; - delete ctx.args.ctx; - - const newBuy = await models.Buy.create(ctx.args, myOptions); - - const filter = { - fields: [ - 'id', - 'itemFk', - 'stickers', - 'packing', - 'grouping', - 'quantity', - 'packageFk', - 'weight', - 'buyingValue', - 'price2', - 'price3' - ], - include: { - relation: 'item', - scope: { - fields: [ - 'id', - 'typeFk', - 'name', - 'size', - 'minPrice', - 'tag5', - 'value5', - 'tag6', - 'value6', - 'tag7', - 'value7', - 'tag8', - 'value8', - 'tag9', - 'value9', - 'tag10', - 'value10', - 'groupingMode' - ], - include: { - relation: 'itemType', - scope: { - fields: ['code', 'description'] - } - } - } - } - }; - - const stmts = []; - let stmt; - - stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc'); - stmt = new ParameterizedSQL( - `CREATE TEMPORARY TABLE tmp.buyRecalc - (INDEX (id)) - ENGINE = MEMORY - SELECT ? AS id`, [newBuy.id]); - - stmts.push(stmt); - stmts.push('CALL buy_recalcPrices()'); - - const sql = ParameterizedSQL.join(stmts, ';'); - await conn.executeStmt(sql, myOptions); - - const buy = await models.Buy.findById(newBuy.id, filter, myOptions); - - if (tx) await tx.commit(); - - return buy; - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/modules/entry/back/methods/entry/addFromBuy.js b/modules/entry/back/methods/entry/addFromBuy.js index f7e1b637e..bfbd1b416 100644 --- a/modules/entry/back/methods/entry/addFromBuy.js +++ b/modules/entry/back/methods/entry/addFromBuy.js @@ -46,7 +46,7 @@ module.exports = Self => { } try { - let buy = await models.Buy.findOne({where: {entryFk: args.id}}, myOptions); + let buy = await models.Buy.findOne({where: {entryFk: args.id, itemFk: args.item}}, myOptions); if (buy) await buy.updateAttribute('printedStickers', args.printedStickers, myOptions); else { diff --git a/modules/entry/back/methods/entry/editLatestBuys.js b/modules/entry/back/methods/entry/editLatestBuys.js index 2642d4f4d..0da2b1625 100644 --- a/modules/entry/back/methods/entry/editLatestBuys.js +++ b/modules/entry/back/methods/entry/editLatestBuys.js @@ -75,7 +75,7 @@ module.exports = Self => { value[field] = newValue; if (filter) { - ctx.args.filter = {where: filter, limit: null}; + ctx.args = {where: filter, limit: null}; lines = await models.Buy.latestBuysFilter(ctx, null, myOptions); } diff --git a/modules/entry/back/methods/entry/importBuys.js b/modules/entry/back/methods/entry/importBuys.js index fdc6b058e..1e6f01a5e 100644 --- a/modules/entry/back/methods/entry/importBuys.js +++ b/modules/entry/back/methods/entry/importBuys.js @@ -46,7 +46,7 @@ module.exports = Self => { const args = ctx.args; const models = Self.app.models; let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -79,7 +79,7 @@ module.exports = Self => { ], myOptions); const buyUltimate = await Self.rawSql(` - SELECT * + SELECT * FROM tmp.buyUltimate WHERE warehouseFk = ? `, [travel.warehouseInFk], myOptions); diff --git a/modules/entry/back/methods/entry/specs/addBuy.spec.js b/modules/entry/back/methods/entry/specs/addBuy.spec.js deleted file mode 100644 index ead75f2d2..000000000 --- a/modules/entry/back/methods/entry/specs/addBuy.spec.js +++ /dev/null @@ -1,42 +0,0 @@ -const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); - -describe('entry addBuy()', () => { - const activeCtx = { - accessToken: {userId: 18}, - }; - - const ctx = { - req: activeCtx - }; - - const entryId = 2; - it('should create a new buy for the given entry', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - const itemId = 4; - const quantity = 10; - - ctx.args = { - id: entryId, - itemFk: itemId, - quantity: quantity, - packageFk: 3 - }; - - const tx = await models.Entry.beginTransaction({}); - const options = {transaction: tx}; - - try { - const newBuy = await models.Entry.addBuy(ctx, options); - - expect(newBuy.itemFk).toEqual(itemId); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -}); diff --git a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js index 99d2df67b..a4dd185fd 100644 --- a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js @@ -53,7 +53,36 @@ describe('Buy editLatestsBuys()', () => { const options = {transaction: tx}; try { - const filter = {'i.typeFk': 1}; + const filter = {'categoryFk': 1, 'tags': []}; + const ctx = { + args: { + filter: filter + }, + req: {accessToken: {userId: 1}} + }; + + const field = 'size'; + const newValue = 88; + + await models.Buy.editLatestBuys(ctx, field, newValue, null, filter, options); + + const [result] = await models.Buy.latestBuysFilter(ctx, null, options); + + expect(result[field]).toEqual(newValue); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should change the value of a given column for filter tags', async() => { + const tx = await models.Buy.beginTransaction({}); + const options = {transaction: tx}; + + try { + const filter = {'tags': [{tagFk: 1, value: 'Brown'}]}; const ctx = { args: { filter: filter diff --git a/modules/entry/back/models/entry.js b/modules/entry/back/models/entry.js index 0eabd70ee..6148ae559 100644 --- a/modules/entry/back/models/entry.js +++ b/modules/entry/back/models/entry.js @@ -3,7 +3,6 @@ module.exports = Self => { require('../methods/entry/filter')(Self); require('../methods/entry/getEntry')(Self); require('../methods/entry/getBuys')(Self); - require('../methods/entry/addBuy')(Self); require('../methods/entry/importBuys')(Self); require('../methods/entry/importBuysPreview')(Self); require('../methods/entry/lastItemBuys')(Self); diff --git a/modules/entry/front/buy/index/index.html b/modules/entry/front/buy/index/index.html index e6d1a0b76..28fdabdb4 100644 --- a/modules/entry/front/buy/index/index.html +++ b/modules/entry/front/buy/index/index.html @@ -222,13 +222,6 @@
- - { if (!res.data) return; diff --git a/modules/entry/front/buy/index/index.spec.js b/modules/entry/front/buy/index/index.spec.js index aff52bc80..0e221302c 100644 --- a/modules/entry/front/buy/index/index.spec.js +++ b/modules/entry/front/buy/index/index.spec.js @@ -25,17 +25,6 @@ describe('Entry buy', () => { controller.saveBuy(buy); $httpBackend.flush(); }); - - it(`should call the entry addBuy post route if the received buy has no ID`, () => { - controller.entry = {id: 1}; - const buy = {itemFk: 1, quantity: 1, packageFk: 1}; - - const query = `Entries/${controller.entry.id}/addBuy`; - - $httpBackend.expectPOST(query).respond(200); - controller.saveBuy(buy); - $httpBackend.flush(); - }); }); describe('deleteBuys()', () => { diff --git a/modules/invoiceIn/back/methods/invoice-in/toBook.js b/modules/invoiceIn/back/methods/invoice-in/toBook.js index 588d53f1f..778742911 100644 --- a/modules/invoiceIn/back/methods/invoice-in/toBook.js +++ b/modules/invoiceIn/back/methods/invoice-in/toBook.js @@ -21,7 +21,7 @@ module.exports = Self => { Self.toBook = async(ctx, id, options) => { let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -32,7 +32,7 @@ module.exports = Self => { } try { - await Self.rawSql(`CALL vn.invoiceInBookingMain(?)`, [id], myOptions); + await Self.rawSql(`CALL vn.invoiceIn_booking(?)`, [id], myOptions); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/invoiceOut/back/methods/invoiceOut/book.js b/modules/invoiceOut/back/methods/invoiceOut/book.js index 7aa0eac1f..af5633ff2 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/book.js +++ b/modules/invoiceOut/back/methods/invoiceOut/book.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.remoteMethod('book', { + Self.remoteMethodCtx('book', { description: 'Book an invoiceOut', accessType: 'WRITE', accepts: { @@ -20,10 +20,10 @@ module.exports = Self => { } }); - Self.book = async(ref, options) => { + Self.book = async(ctx, ref, options) => { const models = Self.app.models; let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/invoiceOut/back/methods/invoiceOut/clientsToInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/clientsToInvoice.js index f18b0c682..63b00fe38 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/clientsToInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/clientsToInvoice.js @@ -36,7 +36,7 @@ module.exports = Self => { Self.clientsToInvoice = async(ctx, clientId, invoiceDate, maxShipped, companyFk, options) => { let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js index a458aa18e..18e6903d6 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js @@ -51,7 +51,7 @@ module.exports = Self => { const args = ctx.args; let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/invoiceOut/back/methods/invoiceOut/createPdf.js b/modules/invoiceOut/back/methods/invoiceOut/createPdf.js index dfdb3c1a7..c4d50a4ee 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/createPdf.js +++ b/modules/invoiceOut/back/methods/invoiceOut/createPdf.js @@ -1,5 +1,4 @@ const UserError = require('vn-loopback/util/user-error'); -const print = require('vn-print'); module.exports = Self => { Self.remoteMethodCtx('createPdf', { @@ -25,56 +24,28 @@ module.exports = Self => { Self.createPdf = async function(ctx, id, options) { const models = Self.app.models; - - if (process.env.NODE_ENV == 'test') - throw new UserError(`Action not allowed on the test environment`); + options = typeof options == 'object' + ? Object.assign({}, options) : {}; let tx; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } + if (!options.transaction) + tx = options.transaction = await Self.beginTransaction({}); try { - const invoiceOut = await Self.findById(id, null, myOptions); - const canCreatePdf = await models.ACL.checkAccessAcl(ctx, 'InvoiceOut', 'canCreatePdf', 'WRITE'); + const invoiceOut = await Self.findById(id, {fields: ['hasPdf']}, options); - if (invoiceOut.hasPdf && !canCreatePdf) - throw new UserError(`You don't have enough privileges`); + if (invoiceOut.hasPdf) { + const canCreatePdf = await models.ACL.checkAccessAcl(ctx, 'InvoiceOut', 'canCreatePdf', 'WRITE'); + if (!canCreatePdf) + throw new UserError(`You don't have enough privileges`); + } - await invoiceOut.updateAttributes({ - hasPdf: true - }, myOptions); - - const invoiceReport = new print.Report('invoice', { - reference: invoiceOut.ref, - recipientId: invoiceOut.clientFk - }); - const buffer = await invoiceReport.toPdfStream(); - - const issued = invoiceOut.issued; - const year = issued.getFullYear().toString(); - const month = (issued.getMonth() + 1).toString(); - const day = issued.getDate().toString(); - - const fileName = `${year}${invoiceOut.ref}.pdf`; - - // Store invoice - await print.storage.write(buffer, { - type: 'invoice', - path: `${year}/${month}/${day}`, - fileName: fileName - }); + await Self.makePdf(id, options); if (tx) await tx.commit(); - } catch (e) { + } catch (err) { if (tx) await tx.rollback(); - throw e; + throw err; } }; }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/download.js b/modules/invoiceOut/back/methods/invoiceOut/download.js index 5c787428b..4c76f7c07 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/download.js +++ b/modules/invoiceOut/back/methods/invoiceOut/download.js @@ -1,6 +1,5 @@ const fs = require('fs-extra'); const path = require('path'); -const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('download', { @@ -37,45 +36,43 @@ module.exports = Self => { Self.download = async function(ctx, id, options) { const models = Self.app.models; - const myOptions = {}; + options = typeof options == 'object' + ? Object.assign({}, options) : {}; - if (typeof options == 'object') - Object.assign(myOptions, options); + const pdfFile = await Self.filePath(id, options); + + const container = await models.InvoiceContainer.container(pdfFile.year); + const rootPath = container.client.root; + + const file = { + path: path.join(rootPath, pdfFile.path, pdfFile.name), + contentType: 'application/pdf', + name: pdfFile.name + }; try { - const invoiceOut = await models.InvoiceOut.findById(id, null, myOptions); + await fs.access(file.path); + } catch (error) { + await Self.createPdf(ctx, id, options); + } - const issued = invoiceOut.issued; - const year = issued.getFullYear().toString(); - const month = (issued.getMonth() + 1).toString(); - const day = issued.getDate().toString(); - - const container = await models.InvoiceContainer.container(year); - const rootPath = container.client.root; - const src = path.join(rootPath, year, month, day); - const fileName = `${year}${invoiceOut.ref}.pdf`; - const fileSrc = path.join(src, fileName); - - const file = { - path: fileSrc, - contentType: 'application/pdf', - name: fileName - }; + let stream = await fs.createReadStream(file.path); + // XXX: To prevent unhandled ENOENT error + // https://stackoverflow.com/questions/17136536/is-enoent-from-fs-createreadstream-uncatchable + stream.on('error', err => { + const e = new Error(err.message); + err.stack = e.stack; + console.error(err); + }); + if (process.env.NODE_ENV == 'test') { try { await fs.access(file.path); } catch (error) { - await Self.createPdf(ctx, id, myOptions); + stream = null; } - - const stream = fs.createReadStream(file.path); - - return [stream, file.contentType, `filename="${file.name}"`]; - } catch (error) { - if (error.code === 'ENOENT') - throw new UserError('The PDF document does not exists'); - - throw error; } + + return [stream, file.contentType, `filename="${pdfFile.name}"`]; }; }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js b/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js index c8f8a6778..ddd008942 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js +++ b/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js @@ -30,15 +30,10 @@ module.exports = Self => { type: 'number', description: 'The company id to invoice', required: true - }, { - arg: 'printerFk', - type: 'number', - description: 'The printer to print', - required: true } ], returns: { - type: 'object', + type: 'number', root: true }, http: { @@ -50,26 +45,22 @@ module.exports = Self => { Self.invoiceClient = async(ctx, options) => { const args = ctx.args; const models = Self.app.models; - const myOptions = {}; + options = typeof options == 'object' + ? Object.assign({}, options) : {}; + options.userId = ctx.req.accessToken.userId; + let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } + if (!options.transaction) + tx = options.transaction = await Self.beginTransaction({}); const minShipped = Date.vnNew(); minShipped.setFullYear(args.maxShipped.getFullYear() - 1); let invoiceId; - let invoiceOut; try { const client = await models.Client.findById(args.clientId, { fields: ['id', 'hasToInvoiceByAddress'] - }, myOptions); + }, options); if (client.hasToInvoiceByAddress) { await Self.rawSql('CALL ticketToInvoiceByAddress(?, ?, ?, ?)', [ @@ -77,49 +68,58 @@ module.exports = Self => { args.maxShipped, args.addressId, args.companyFk - ], myOptions); + ], options); } else { await Self.rawSql('CALL invoiceFromClient(?, ?, ?)', [ args.maxShipped, client.id, args.companyFk - ], myOptions); + ], options); } - // Make invoice - const isSpanishCompany = await getIsSpanishCompany(args.companyFk, myOptions); + // Check negative bases - // Validates ticket nagative base - const hasAnyNegativeBase = await getNegativeBase(myOptions); + let query = + `SELECT COUNT(*) isSpanishCompany + FROM supplier s + JOIN country c ON c.id = s.countryFk + AND c.code = 'ES' + WHERE s.id = ?`; + const [supplierCompany] = await Self.rawSql(query, [ + args.companyFk + ], options); + + const isSpanishCompany = supplierCompany?.isSpanishCompany; + + query = 'SELECT hasAnyNegativeBase() AS base'; + const [result] = await Self.rawSql(query, null, options); + + const hasAnyNegativeBase = result?.base; if (hasAnyNegativeBase && isSpanishCompany) throw new UserError('Negative basis'); + // Invoicing + query = `SELECT invoiceSerial(?, ?, ?) AS serial`; const [invoiceSerial] = await Self.rawSql(query, [ client.id, args.companyFk, 'G' - ], myOptions); + ], options); const serialLetter = invoiceSerial.serial; query = `CALL invoiceOut_new(?, ?, NULL, @invoiceId)`; await Self.rawSql(query, [ serialLetter, args.invoiceDate - ], myOptions); + ], options); - const [newInvoice] = await Self.rawSql(`SELECT @invoiceId id`, null, myOptions); - if (newInvoice.id) { - await Self.rawSql('CALL invoiceOutBooking(?)', [newInvoice.id], myOptions); + const [newInvoice] = await Self.rawSql(`SELECT @invoiceId id`, null, options); + if (!newInvoice) + throw new UserError('No tickets to invoice', 'notInvoiced'); - invoiceOut = await models.InvoiceOut.findById(newInvoice.id, { - include: { - relation: 'client' - } - }, myOptions); - - invoiceId = newInvoice.id; - } + await Self.rawSql('CALL invoiceOutBooking(?)', [newInvoice.id], options); + invoiceId = newInvoice.id; if (tx) await tx.commit(); } catch (e) { @@ -127,47 +127,6 @@ module.exports = Self => { throw e; } - if (invoiceId) { - if (!invoiceOut.client().isToBeMailed) { - const query = ` - CALL vn.report_print( - 'invoice', - ?, - account.myUser_getId(), - JSON_OBJECT('refFk', ?), - 'normal' - );`; - await models.InvoiceOut.rawSql(query, [args.printerFk, invoiceOut.ref]); - } else { - ctx.args = { - reference: invoiceOut.ref, - recipientId: invoiceOut.clientFk, - recipient: invoiceOut.client().email - }; - await models.InvoiceOut.invoiceEmail(ctx, invoiceOut.ref); - } - } return invoiceId; }; - - async function getNegativeBase(options) { - const models = Self.app.models; - const query = 'SELECT hasAnyNegativeBase() AS base'; - const [result] = await models.InvoiceOut.rawSql(query, null, options); - return result && result.base; - } - - async function getIsSpanishCompany(companyId, options) { - const models = Self.app.models; - const query = `SELECT COUNT(*) isSpanishCompany - FROM supplier s - JOIN country c ON c.id = s.countryFk - AND c.code = 'ES' - WHERE s.id = ?`; - const [supplierCompany] = await models.InvoiceOut.rawSql(query, [ - companyId - ], options); - - return supplierCompany && supplierCompany.isSpanishCompany; - } }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/invoiceEmail.js b/modules/invoiceOut/back/methods/invoiceOut/invoiceEmail.js index 83cb84881..400328fef 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/invoiceEmail.js +++ b/modules/invoiceOut/back/methods/invoiceOut/invoiceEmail.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); const {Email} = require('vn-print'); module.exports = Self => { @@ -10,20 +11,17 @@ module.exports = Self => { type: 'string', required: true, http: {source: 'path'} - }, - { + }, { arg: 'recipient', type: 'string', description: 'The recipient email', required: true, - }, - { + }, { arg: 'replyTo', type: 'string', description: 'The sender email to reply to', required: false - }, - { + }, { arg: 'recipientId', type: 'number', description: 'The recipient id to send to the recipient preferred language', @@ -42,16 +40,13 @@ module.exports = Self => { Self.invoiceEmail = async(ctx, reference) => { const args = Object.assign({}, ctx.args); - const {InvoiceOut} = Self.app.models; const params = { recipient: args.recipient, lang: ctx.req.getLocale() }; - const invoiceOut = await InvoiceOut.findOne({ - where: { - ref: reference - } + const invoiceOut = await Self.findOne({ + where: {ref: reference} }); delete args.ctx; @@ -74,6 +69,10 @@ module.exports = Self => { ] }; - return email.send(mailOptions); + try { + return email.send(mailOptions); + } catch (err) { + throw new UserError('Error when sending mail to client', 'mailNotSent'); + } }; }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js new file mode 100644 index 000000000..a999437c0 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js @@ -0,0 +1,87 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('makePdfAndNotify', { + description: 'Create invoice PDF and send it to client', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'number', + description: 'The invoice id', + required: true, + http: {source: 'path'} + }, { + arg: 'printerFk', + type: 'number', + description: 'The printer to print', + required: true + } + ], + http: { + path: '/:id/makePdfAndNotify', + verb: 'POST' + } + }); + + Self.makePdfAndNotify = async function(ctx, id, printerFk) { + const models = Self.app.models; + + options = typeof options == 'object' + ? Object.assign({}, options) : {}; + options.userId = ctx.req.accessToken.userId; + + try { + await Self.makePdf(id, options); + } catch (err) { + console.error(err); + throw new UserError('Error while generating PDF', 'pdfError'); + } + + const invoiceOut = await Self.findById(id, { + fields: ['ref', 'clientFk'], + include: { + relation: 'client', + scope: { + fields: ['id', 'email', 'isToBeMailed', 'salesPersonFk'] + } + } + }, options); + + const ref = invoiceOut.ref; + const client = invoiceOut.client(); + + if (client.isToBeMailed) { + try { + ctx.args = { + reference: ref, + recipientId: client.id, + recipient: client.email + }; + await Self.invoiceEmail(ctx, ref); + } catch (err) { + const origin = ctx.req.headers.origin; + const message = ctx.req.__('Mail not sent', { + clientId: client.id, + clientUrl: `${origin}/#!/claim/${id}/summary` + }); + const salesPersonId = client.salesPersonFk; + + if (salesPersonId) + await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); + + throw new UserError('Error when sending mail to client', 'mailNotSent'); + } + } else { + const query = ` + CALL vn.report_print( + 'invoice', + ?, + account.myUser_getId(), + JSON_OBJECT('refFk', ?), + 'normal' + );`; + await Self.rawSql(query, [printerFk, ref], options); + } + }; +}; diff --git a/modules/invoiceOut/back/methods/invoiceOut/refund.js b/modules/invoiceOut/back/methods/invoiceOut/refund.js index c722d9806..1b7ccc1e4 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/refund.js +++ b/modules/invoiceOut/back/methods/invoiceOut/refund.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('refund', { + Self.remoteMethodCtx('refund', { description: 'Create refund tickets with sales and services if provided', accessType: 'WRITE', accepts: [ @@ -25,7 +25,7 @@ module.exports = Self => { } }); - Self.refund = async(ref, withWarehouse, options) => { + Self.refund = async(ctx, ref, withWarehouse, options) => { const models = Self.app.models; const myOptions = {}; let tx; @@ -43,7 +43,7 @@ module.exports = Self => { const tickets = await models.Ticket.find(filter, myOptions); const ticketsIds = tickets.map(ticket => ticket.id); - const refundedTickets = await models.Ticket.refund(ticketsIds, withWarehouse, myOptions); + const refundedTickets = await models.Ticket.refund(ctx, ticketsIds, withWarehouse, myOptions); if (tx) await tx.commit(); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index ee72f2218..3af7542ca 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -1,6 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('invoiceOut book()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; const invoiceOutId = 5; it('should update the booked property', async() => { @@ -12,7 +13,7 @@ describe('invoiceOut book()', () => { const bookedDate = originalInvoiceOut.booked; const invoiceOutRef = originalInvoiceOut.ref; - await models.InvoiceOut.book(invoiceOutRef, options); + await models.InvoiceOut.book(ctx, invoiceOutRef, options); const updatedInvoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js deleted file mode 100644 index 4029bfbcf..000000000 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js +++ /dev/null @@ -1,28 +0,0 @@ -const models = require('vn-loopback/server/server').models; -const fs = require('fs-extra'); - -describe('InvoiceOut download()', () => { - const userId = 9; - const invoiceId = 1; - const ctx = { - req: { - - accessToken: {userId: userId}, - headers: {origin: 'http://localhost:5000'}, - } - }; - - it('should return the downloaded file name', async() => { - spyOn(models.InvoiceContainer, 'container').and.returnValue({ - client: {root: '/path'} - }); - spyOn(fs, 'createReadStream').and.returnValue(new Promise(resolve => resolve('streamObject'))); - spyOn(fs, 'access').and.returnValue(true); - spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true))); - - const result = await models.InvoiceOut.download(ctx, invoiceId); - - expect(result[1]).toEqual('application/pdf'); - expect(result[2]).toMatch(/filename="\d{4}T1111111.pdf"/); - }); -}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/invoiceClient.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/invoiceClient.spec.js index 9a0574dba..0faa8fe1a 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/invoiceClient.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/invoiceClient.spec.js @@ -18,12 +18,14 @@ describe('InvoiceOut invoiceClient()', () => { accessToken: {userId: userId}, __: value => { return value; - } + }, + headers: {origin: 'http://localhost'} + }; const ctx = {req: activeCtx}; it('should make a global invoicing', async() => { - spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true))); + spyOn(models.InvoiceOut, 'makePdf').and.returnValue(new Promise(resolve => resolve(true))); spyOn(models.InvoiceOut, 'invoiceEmail'); const tx = await models.InvoiceOut.beginTransaction({}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js index 3d0ea6809..072fcc12c 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js @@ -3,6 +3,7 @@ const LoopBackContext = require('loopback-context'); describe('InvoiceOut refund()', () => { const userId = 5; + const ctx = {req: {accessToken: userId}}; const withWarehouse = true; const activeCtx = { accessToken: {userId: userId}, @@ -16,7 +17,7 @@ describe('InvoiceOut refund()', () => { const options = {transaction: tx}; try { - const result = await models.InvoiceOut.refund('T1111111', withWarehouse, options); + const result = await models.InvoiceOut.refund(ctx, 'T1111111', withWarehouse, options); expect(result).toBeDefined(); diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json index b190126ea..9e8b119ab 100644 --- a/modules/invoiceOut/back/model-config.json +++ b/modules/invoiceOut/back/model-config.json @@ -2,6 +2,9 @@ "InvoiceOut": { "dataSource": "vn" }, + "InvoiceOutConfig": { + "dataSource": "vn" + }, "InvoiceOutSerial": { "dataSource": "vn" }, diff --git a/modules/invoiceOut/back/models/invoice-out config.json b/modules/invoiceOut/back/models/invoice-out config.json new file mode 100644 index 000000000..d5595f687 --- /dev/null +++ b/modules/invoiceOut/back/models/invoice-out config.json @@ -0,0 +1,22 @@ +{ + "name": "InvoiceOutConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "invoiceOutConfig" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "parallelism": { + "type": "number", + "required": true + } + } +} + + diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index 5fcef7744..d3aaf3b3d 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -1,3 +1,6 @@ +const print = require('vn-print'); +const path = require('path'); + module.exports = Self => { require('../methods/invoiceOut/filter')(Self); require('../methods/invoiceOut/summary')(Self); @@ -10,6 +13,7 @@ module.exports = Self => { require('../methods/invoiceOut/createManualInvoice')(Self); require('../methods/invoiceOut/clientsToInvoice')(Self); require('../methods/invoiceOut/invoiceClient')(Self); + require('../methods/invoiceOut/makePdfAndNotify')(Self); require('../methods/invoiceOut/refund')(Self); require('../methods/invoiceOut/invoiceEmail')(Self); require('../methods/invoiceOut/exportationPdf')(Self); @@ -19,4 +23,45 @@ module.exports = Self => { require('../methods/invoiceOut/getInvoiceDate')(Self); require('../methods/invoiceOut/negativeBases')(Self); require('../methods/invoiceOut/negativeBasesCsv')(Self); + + Self.filePath = async function(id, options) { + const fields = ['ref', 'issued']; + const invoiceOut = await Self.findById(id, {fields}, options); + + const issued = invoiceOut.issued; + const year = issued.getFullYear().toString(); + const month = (issued.getMonth() + 1).toString(); + const day = issued.getDate().toString(); + + return { + path: path.join(year, month, day), + name: `${year}${invoiceOut.ref}.pdf`, + year + }; + }; + + Self.makePdf = async function(id, options) { + const fields = ['id', 'hasPdf', 'ref']; + const invoiceOut = await Self.findById(id, {fields}, options); + const invoiceReport = new print.Report('invoice', { + reference: invoiceOut.ref + }); + const buffer = await invoiceReport.toPdfStream(); + + const pdfFile = await Self.filePath(id, options); + + // Store invoice + + await invoiceOut.updateAttributes({ + hasPdf: true + }, options); + + if (process.env.NODE_ENV !== 'test') { + await print.storage.write(buffer, { + type: 'invoice', + path: pdfFile.path, + fileName: pdfFile.name + }); + } + }; }; diff --git a/modules/invoiceOut/front/global-invoicing/index.html b/modules/invoiceOut/front/global-invoicing/index.html index 6d5b16329..3ece30862 100644 --- a/modules/invoiceOut/front/global-invoicing/index.html +++ b/modules/invoiceOut/front/global-invoicing/index.html @@ -1,7 +1,6 @@ + class="status vn-w-lg vn-pa-md"> @@ -20,8 +19,15 @@ Ended process
-
- {{$ctrl.percentage | percentage: 0}} ({{$ctrl.addressNumber}} {{'of' | translate}} {{$ctrl.nAddresses}}) +
+
+ {{$ctrl.percentage | percentage: 0}} + ({{$ctrl.addressNumber}} of {{$ctrl.nAddresses}}) +
+
+ {{$ctrl.nPdfs}} of {{$ctrl.totalPdfs}} + PDFs +
@@ -55,7 +61,11 @@ {{::error.address.nickname}} - {{::error.message}} + + {{::error.message}} + @@ -118,7 +128,8 @@ label="Company" show-field="code" value-field="id" - ng-model="$ctrl.companyFk"> + ng-model="$ctrl.companyFk" + on-change="$ctrl.getInvoiceDate(value)"> + ng-click="$ctrl.status = 'stopping'">
diff --git a/modules/invoiceOut/front/global-invoicing/index.js b/modules/invoiceOut/front/global-invoicing/index.js index 0aa6a4a24..9a936611a 100644 --- a/modules/invoiceOut/front/global-invoicing/index.js +++ b/modules/invoiceOut/front/global-invoicing/index.js @@ -9,24 +9,27 @@ class Controller extends Section { Object.assign(this, { maxShipped: new Date(date.getFullYear(), date.getMonth(), 0), clientsToInvoice: 'all', + companyFk: this.vnConfig.companyFk, + parallelism: 1 }); - this.$http.get('UserConfigs/getUserConfig') - .then(res => { - this.companyFk = res.data.companyFk; - const params = { - companyFk: this.companyFk - }; - return this.$http.get('InvoiceOuts/getInvoiceDate', {params}); - }) + const params = {companyFk: this.companyFk}; + this.$http.get('InvoiceOuts/getInvoiceDate', {params}) .then(res => { this.minInvoicingDate = res.data.issued ? new Date(res.data.issued) : null; this.invoiceDate = this.minInvoicingDate; }); - } - stopInvoicing() { - this.status = 'stopping'; + const filter = {fields: ['parallelism']}; + this.$http.get('InvoiceOutConfigs/findOne', {filter}) + .then(res => { + if (res.data.parallelism) + this.parallelism = res.data.parallelism; + }) + .catch(res => { + if (res.status == 404) return; + throw res; + }); } makeInvoice() { @@ -42,8 +45,8 @@ class Controller extends Section { throw new UserError('Invoice date and the max date should be filled'); if (this.invoiceDate < this.maxShipped) throw new UserError('Invoice date can\'t be less than max date'); - if (this.invoiceDate.getTime() < this.minInvoicingDate.getTime()) - throw new UserError('Exists an invoice with a previous date'); + if (this.minInvoicingDate && this.invoiceDate.getTime() < this.minInvoicingDate.getTime()) + throw new UserError('Exists an invoice with a future date'); if (!this.companyFk) throw new UserError('Choose a valid company'); if (!this.printerFk) @@ -64,8 +67,11 @@ class Controller extends Section { if (!this.addresses.length) throw new UserError(`There aren't tickets to invoice`); + this.nRequests = 0; + this.nPdfs = 0; + this.totalPdfs = 0; this.addressIndex = 0; - return this.invoiceOut(); + this.invoiceClient(); }) .catch(err => this.handleError(err)); } catch (err) { @@ -79,8 +85,11 @@ class Controller extends Section { throw err; } - invoiceOut() { - if (this.addressIndex == this.addresses.length || this.status == 'stopping') { + invoiceClient() { + if (this.nRequests == this.parallelism || this.isInvoicing) return; + + if (this.addressIndex >= this.addresses.length || this.status == 'stopping') { + if (this.nRequests) return; this.invoicing = false; this.status = 'done'; return; @@ -89,34 +98,59 @@ class Controller extends Section { this.status = 'invoicing'; const address = this.addresses[this.addressIndex]; this.currentAddress = address; + this.isInvoicing = true; const params = { clientId: address.clientId, addressId: address.id, invoiceDate: this.invoiceDate, maxShipped: this.maxShipped, - companyFk: this.companyFk, - printerFk: this.printerFk, + companyFk: this.companyFk }; this.$http.post(`InvoiceOuts/invoiceClient`, params) - .then(() => this.invoiceNext()) + .then(res => { + this.isInvoicing = false; + if (res.data) + this.makePdfAndNotify(res.data, address); + this.invoiceNext(); + }) .catch(res => { - const message = res.data?.error?.message || res.message; + this.isInvoicing = false; if (res.status >= 400 && res.status < 500) { - this.errors.unshift({address, message}); + this.invoiceError(address, res); this.invoiceNext(); } else { this.invoicing = false; this.status = 'done'; throw new UserError(`Critical invoicing error, proccess stopped`); } - }) + }); } invoiceNext() { this.addressIndex++; - this.invoiceOut(); + this.invoiceClient(); + } + + makePdfAndNotify(invoiceId, address) { + this.nRequests++; + this.totalPdfs++; + const params = {printerFk: this.printerFk}; + this.$http.post(`InvoiceOuts/${invoiceId}/makePdfAndNotify`, params) + .catch(res => { + this.invoiceError(address, res, true); + }) + .finally(() => { + this.nPdfs++; + this.nRequests--; + this.invoiceClient(); + }); + } + + invoiceError(address, res, isWarning) { + const message = res.data?.error?.message || res.message; + this.errors.unshift({address, message, isWarning}); } get nAddresses() { diff --git a/modules/invoiceOut/front/global-invoicing/locale/es.yml b/modules/invoiceOut/front/global-invoicing/locale/es.yml index 5b1f7e883..f1a411ba1 100644 --- a/modules/invoiceOut/front/global-invoicing/locale/es.yml +++ b/modules/invoiceOut/front/global-invoicing/locale/es.yml @@ -10,6 +10,7 @@ Build packaging tickets: Generando tickets de embalajes Address id: Id dirección Printer: Impresora of: de +PDFs: PDFs Client: Cliente Current client id: Id cliente actual Invoicing client: Facturando cliente @@ -18,4 +19,4 @@ Invoice out: Facturar One client: Un solo cliente Choose a valid client: Selecciona un cliente válido Stop: Parar -Critical invoicing error, proccess stopped: Error crítico al facturar, proceso detenido \ No newline at end of file +Critical invoicing error, proccess stopped: Error crítico al facturar, proceso detenido diff --git a/modules/invoiceOut/front/global-invoicing/style.scss b/modules/invoiceOut/front/global-invoicing/style.scss index 6fdfac0ba..3ad767aba 100644 --- a/modules/invoiceOut/front/global-invoicing/style.scss +++ b/modules/invoiceOut/front/global-invoicing/style.scss @@ -1,17 +1,21 @@ @import "variables"; -vn-invoice-out-global-invoicing{ - - h5{ +vn-invoice-out-global-invoicing { + h5 { color: $color-primary; } - + .status { + height: 80px; + display: flex; + align-items: center; + justify-content: center; + gap: 20px; + } #error { line-break: normal; overflow-wrap: break-word; white-space: normal; } - } diff --git a/modules/invoiceOut/front/negative-bases/index.js b/modules/invoiceOut/front/negative-bases/index.js index 1a838507c..f60668b20 100644 --- a/modules/invoiceOut/front/negative-bases/index.js +++ b/modules/invoiceOut/front/negative-bases/index.js @@ -19,7 +19,8 @@ export default class Controller extends Section { this.smartTableOptions = { activeButtons: { search: true, - }, columns: [ + }, + columns: [ { field: 'isActive', searchable: false diff --git a/modules/item/back/methods/item/getBalance.js b/modules/item/back/methods/item/getBalance.js index 5751b0a04..d4e2d0f74 100644 --- a/modules/item/back/methods/item/getBalance.js +++ b/modules/item/back/methods/item/getBalance.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('getBalance', { + Self.remoteMethodCtx('getBalance', { description: 'Returns the ', accessType: 'READ', accepts: [{ @@ -19,8 +19,8 @@ module.exports = Self => { } }); - Self.getBalance = async(filter, options) => { - const myOptions = {}; + Self.getBalance = async(ctx, filter, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/item/back/methods/item/new.js b/modules/item/back/methods/item/new.js index d066f2c9f..c82e2a6b1 100644 --- a/modules/item/back/methods/item/new.js +++ b/modules/item/back/methods/item/new.js @@ -1,7 +1,7 @@ let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('new', { + Self.remoteMethodCtx('new', { description: 'returns the created item', accessType: 'WRITE', accepts: [{ @@ -19,9 +19,9 @@ module.exports = Self => { } }); - Self.new = async(params, options) => { + Self.new = async(ctx, params, options) => { const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js index 1ffd3c302..e013d8956 100644 --- a/modules/item/back/methods/item/specs/getBalance.spec.js +++ b/modules/item/back/methods/item/specs/getBalance.spec.js @@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('item getBalance()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should return the balance lines of a client type loses in which one has highlighted true', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; @@ -25,7 +26,7 @@ describe('item getBalance()', () => { date: null } }; - const results = await models.Item.getBalance(filter, options); + const results = await models.Item.getBalance(ctx, filter, options); const result = results.find(element => element.clientType == 'loses'); @@ -59,8 +60,8 @@ describe('item getBalance()', () => { } }; - const firstItemBalance = await models.Item.getBalance(firstFilter, options); - const secondItemBalance = await models.Item.getBalance(secondFilter, options); + const firstItemBalance = await models.Item.getBalance(ctx, firstFilter, options); + const secondItemBalance = await models.Item.getBalance(ctx, secondFilter, options); expect(firstItemBalance[9].claimFk).toEqual(null); expect(secondItemBalance[5].claimFk).toEqual(2); diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js index a1c741649..2ffaf87a5 100644 --- a/modules/item/back/methods/item/specs/new.spec.js +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('item new()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; beforeAll(async() => { const activeCtx = { accessToken: {userId: 9}, @@ -30,7 +31,7 @@ describe('item new()', () => { tag: 1 }; - let item = await models.Item.new(itemParams, options); + let item = await models.Item.new(ctx, itemParams, options); let itemType = await models.ItemType.findById(item.typeFk, options); diff --git a/modules/item/front/fixed-price/index.js b/modules/item/front/fixed-price/index.js index a39cd6602..fe6788e9c 100644 --- a/modules/item/front/fixed-price/index.js +++ b/modules/item/front/fixed-price/index.js @@ -13,7 +13,6 @@ export default class Controller extends Section { activeButtons: { search: true }, - defaultSearch: true, columns: [ { field: 'warehouseFk', diff --git a/modules/monitor/front/index/tickets/index.html b/modules/monitor/front/index/tickets/index.html index bdd4e76ff..94a950baf 100644 --- a/modules/monitor/front/index/tickets/index.html +++ b/modules/monitor/front/index/tickets/index.html @@ -50,13 +50,13 @@ Salesperson - + Date - + Theoretical - + Practical diff --git a/modules/order/back/methods/order-row/addToOrder.js b/modules/order/back/methods/order-row/addToOrder.js index 639fa8be7..0bf65ef1f 100644 --- a/modules/order/back/methods/order-row/addToOrder.js +++ b/modules/order/back/methods/order-row/addToOrder.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('addToOrder', { + Self.remoteMethodCtx('addToOrder', { description: 'Creates rows (lines) for a order', accessType: 'WRITE', accepts: [{ @@ -21,8 +21,8 @@ module.exports = Self => { } }); - Self.addToOrder = async(params, options) => { - const myOptions = {}; + Self.addToOrder = async(ctx, params, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/order/back/methods/order-row/specs/addToOrder.spec.js b/modules/order/back/methods/order-row/specs/addToOrder.spec.js index d902a1062..96544a1a9 100644 --- a/modules/order/back/methods/order-row/specs/addToOrder.spec.js +++ b/modules/order/back/methods/order-row/specs/addToOrder.spec.js @@ -1,6 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order addToOrder()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; const orderId = 8; it('should add a row to a given order', async() => { const tx = await models.Order.beginTransaction({}); @@ -21,7 +22,7 @@ describe('order addToOrder()', () => { }] }; - await models.OrderRow.addToOrder(params, options); + await models.OrderRow.addToOrder(ctx, params, options); const modifiedRows = await models.OrderRow.find({where: {orderFk: orderId}}, options); diff --git a/modules/order/back/methods/order/confirm.js b/modules/order/back/methods/order/confirm.js index 52acc8648..1fcb3a760 100644 --- a/modules/order/back/methods/order/confirm.js +++ b/modules/order/back/methods/order/confirm.js @@ -21,9 +21,8 @@ module.exports = Self => { Self.confirm = async(ctx, orderFk) => { const userId = ctx.req.accessToken.userId; - const query = `CALL hedera.order_confirmWithUser(?, ?)`; - const response = await Self.rawSql(query, [orderFk, userId]); + const response = await Self.rawSql(query, [orderFk, userId], {userId}); return response; }; diff --git a/modules/order/back/methods/order/new.js b/modules/order/back/methods/order/new.js index 147859dcc..d65b18e12 100644 --- a/modules/order/back/methods/order/new.js +++ b/modules/order/back/methods/order/new.js @@ -1,7 +1,7 @@ let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('new', { + Self.remoteMethodCtx('new', { description: 'Create a new order and returns the new ID', accessType: 'WRITE', accepts: [ @@ -32,8 +32,8 @@ module.exports = Self => { } }); - Self.new = async(landed, addressId, agencyModeId, options) => { - const myOptions = {}; + Self.new = async(ctx, landed, addressId, agencyModeId, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/order/back/methods/order/newFromTicket.js b/modules/order/back/methods/order/newFromTicket.js index e0578ff9a..3614d8e32 100644 --- a/modules/order/back/methods/order/newFromTicket.js +++ b/modules/order/back/methods/order/newFromTicket.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('newFromTicket', { + Self.remoteMethodCtx('newFromTicket', { description: 'Create a new order and returns the new ID', accessType: 'WRITE', accepts: [{ @@ -18,7 +18,7 @@ module.exports = Self => { } }); - Self.newFromTicket = async(ticketFk, options) => { + Self.newFromTicket = async(ctx, ticketFk, options) => { const myOptions = {}; let tx; @@ -39,7 +39,7 @@ module.exports = Self => { const addressFk = ticket.addressFk; const agencyModeFk = ticket.agencyModeFk; - const orderID = await Self.app.models.Order.new(landed, addressFk, agencyModeFk, myOptions); + const orderID = await Self.app.models.Order.new(ctx, landed, addressFk, agencyModeFk, myOptions); if (tx) await tx.commit(); diff --git a/modules/order/back/methods/order/specs/new.spec.js b/modules/order/back/methods/order/specs/new.spec.js index f11367579..c43527f66 100644 --- a/modules/order/back/methods/order/specs/new.spec.js +++ b/modules/order/back/methods/order/specs/new.spec.js @@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models; const UserError = require('vn-loopback/util/user-error'); describe('order new()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should throw an error if the client isnt active', async() => { const tx = await models.Order.beginTransaction({}); @@ -13,7 +14,7 @@ describe('order new()', () => { const addressFk = 6; const agencyModeFk = 1; - await models.Order.new(landed, addressFk, agencyModeFk, options); + await models.Order.new(ctx, landed, addressFk, agencyModeFk, options); await tx.rollback(); } catch (e) { @@ -34,7 +35,7 @@ describe('order new()', () => { const addressFk = 121; const agencyModeFk = 1; - orderId = await models.Order.new(landed, addressFk, agencyModeFk, options); + orderId = await models.Order.new(ctx, landed, addressFk, agencyModeFk, options); const highestOrderIdInFixtures = 3; diff --git a/modules/order/back/methods/order/specs/newFromTicket.spec.js b/modules/order/back/methods/order/specs/newFromTicket.spec.js index 6f18d1751..c509552fe 100644 --- a/modules/order/back/methods/order/specs/newFromTicket.spec.js +++ b/modules/order/back/methods/order/specs/newFromTicket.spec.js @@ -1,6 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order newFromTicket()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should create a new order from an existing ticket', async() => { const tx = await models.Order.beginTransaction({}); @@ -9,7 +10,7 @@ describe('order newFromTicket()', () => { const ticketId = 11; - const orderId = await models.Order.newFromTicket(ticketId, options); + const orderId = await models.Order.newFromTicket(ctx, ticketId, options); const highestOrderIdInFixtures = 3; diff --git a/modules/order/front/catalog-search-panel/index.js b/modules/order/front/catalog-search-panel/index.js index ed0af1d6e..21c0c50fa 100644 --- a/modules/order/front/catalog-search-panel/index.js +++ b/modules/order/front/catalog-search-panel/index.js @@ -23,7 +23,7 @@ class Controller extends SearchPanel { addValue() { this.filter.values.push({}); - setTimeout(() => this.popover.relocate()); + setTimeout(() => this.parentPopover.relocate()); } changeTag() { @@ -36,7 +36,7 @@ ngModule.vnComponent('vnOrderCatalogSearchPanel', { controller: Controller, bindings: { onSubmit: '&?', - popover: ' @@ -31,7 +31,7 @@ label="Category"> - - @@ -104,20 +104,20 @@ on-close="$ctrl.onPopoverClose()">
- + class="colored"> Id: {{$ctrl.itemId}} - {{$ctrl.itemName}}
- + class="colored"> {{category.selection.name}} - + class="colored"> {{type.selection.name}} + class="colored">
{{::tagGroup.tagSelection.name}}: @@ -163,4 +163,4 @@
- \ No newline at end of file + diff --git a/modules/route/back/methods/agency-term/createInvoiceIn.js b/modules/route/back/methods/agency-term/createInvoiceIn.js index 836655bd3..5a8430e49 100644 --- a/modules/route/back/methods/agency-term/createInvoiceIn.js +++ b/modules/route/back/methods/agency-term/createInvoiceIn.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('createInvoiceIn', { + Self.remoteMethodCtx('createInvoiceIn', { description: 'Creates an invoiceIn from one or more agency terms', accessType: 'WRITE', accepts: [{ @@ -24,11 +24,11 @@ module.exports = Self => { } }); - Self.createInvoiceIn = async(rows, dms, options) => { + Self.createInvoiceIn = async(ctx, rows, dms, options) => { const models = Self.app.models; let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js b/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js index 628c5fb9a..d3a0755ef 100644 --- a/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js +++ b/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js @@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('AgencyTerm createInvoiceIn()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; beforeAll(async() => { const activeCtx = { accessToken: {userId: 9}, @@ -42,7 +43,7 @@ describe('AgencyTerm createInvoiceIn()', () => { const oldInvoiceInDueDay = await models.InvoiceInDueDay.findById(invoiceInDueDayId, null, options); const oldInvoiceInTax = await models.InvoiceInTax.findById(invoiceInTaxId, null, options); - await models.AgencyTerm.createInvoiceIn(rows, dms, options); + await models.AgencyTerm.createInvoiceIn(ctx, rows, dms, options); const [newInvoiceIn] = await models.InvoiceIn.rawSql('SELECT MAX(id) id FROM invoiceIn', null, options); diff --git a/modules/route/back/methods/route/guessPriority.js b/modules/route/back/methods/route/guessPriority.js index eab9f3473..67b68aa89 100644 --- a/modules/route/back/methods/route/guessPriority.js +++ b/modules/route/back/methods/route/guessPriority.js @@ -26,7 +26,7 @@ module.exports = Self => { const tx = await Self.beginTransaction({}); try { - let options = {transaction: tx}; + let options = {transaction: tx, userId}; const priority = await Self.rawSql(query, [id], options); diff --git a/modules/route/back/methods/route/updateVolume.js b/modules/route/back/methods/route/updateVolume.js index f3b8da130..cdced3882 100644 --- a/modules/route/back/methods/route/updateVolume.js +++ b/modules/route/back/methods/route/updateVolume.js @@ -24,7 +24,7 @@ module.exports = Self => { const models = Self.app.models; let tx; - const myOptions = {}; + const myOptions = {userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/route/front/index/index.html b/modules/route/front/index/index.html index 7a64a9aff..9384af6be 100644 --- a/modules/route/front/index/index.html +++ b/modules/route/front/index/index.html @@ -1,11 +1,26 @@ + + + + + +
-
@@ -35,7 +50,7 @@ - @@ -52,19 +67,19 @@ Vehicle - Date + Date - + - Description + Description - Hour started + Hour started - Hour finished + Hour finished @@ -74,7 +89,7 @@ class="clickable vn-tr search-result" ng-attr-id="{{::route.id}}" vn-droppable="$ctrl.onDrop($event)"> - @@ -83,7 +98,7 @@ - + - - - + @@ -156,7 +171,7 @@ - +
@@ -171,7 +186,7 @@ route="$ctrl.routeSelected"> - - @@ -210,4 +225,4 @@ - \ No newline at end of file + diff --git a/modules/supplier/back/locale/supplier-account/en.yml b/modules/supplier/back/locale/supplier-account/en.yml index 2bce50cfa..43c4ba40d 100644 --- a/modules/supplier/back/locale/supplier-account/en.yml +++ b/modules/supplier/back/locale/supplier-account/en.yml @@ -5,3 +5,4 @@ columns: beneficiary: beneficiary supplierFk: supplier bankEntityFk: bank entity + accountingFk: ledger account diff --git a/modules/supplier/back/locale/supplier-account/es.yml b/modules/supplier/back/locale/supplier-account/es.yml index 120293c8a..9db5708a3 100644 --- a/modules/supplier/back/locale/supplier-account/es.yml +++ b/modules/supplier/back/locale/supplier-account/es.yml @@ -5,3 +5,4 @@ columns: beneficiary: beneficiario supplierFk: proveedor bankEntityFk: entidad bancaria + accountingFk: cuenta contable diff --git a/modules/supplier/back/methods/supplier/getItemsPackaging.js b/modules/supplier/back/methods/supplier/getItemsPackaging.js index 8ef80529b..c06195a55 100644 --- a/modules/supplier/back/methods/supplier/getItemsPackaging.js +++ b/modules/supplier/back/methods/supplier/getItemsPackaging.js @@ -26,14 +26,14 @@ module.exports = Self => { Self.getItemsPackaging = async(id, entry) => { return Self.rawSql(` WITH entryTmp AS ( - SELECT i.id, SUM(b.quantity) quantity + SELECT i.id, SUM(b.quantity) quantity, SUM(b.printedStickers) printedStickers FROM vn.entry e JOIN vn.buy b ON b.entryFk = e.id JOIN vn.supplier s ON s.id = e.supplierFk JOIN vn.item i ON i.id = b.itemFk WHERE e.id = ? AND e.supplierFk = ? GROUP BY i.id - ) SELECT i.id, i.name, et.quantity, SUM(b.quantity) quantityTotal + ) SELECT i.id, i.name, et.quantity, SUM(b.quantity) quantityTotal, et.printedStickers FROM vn.buy b JOIN vn.item i ON i.id = b.itemFk JOIN vn.entry e ON e.id = b.entryFk diff --git a/modules/ticket/back/locale/ticket-request/en.yml b/modules/ticket/back/locale/ticket-request/en.yml index f381e0c9d..fc9210501 100644 --- a/modules/ticket/back/locale/ticket-request/en.yml +++ b/modules/ticket/back/locale/ticket-request/en.yml @@ -2,14 +2,17 @@ name: request columns: id: id description: description - created: created + buyerCode: buyer quantity: quantity price: price - isOk: ok - response: response - saleFk: sale - ticketFk: ticket - attenderFk: attender - requesterFk: requester itemFk: item - + clientFk: client + response: response + total: total + buyed: buyed + saleFk: sale + created: created + isOk: ok + requesterFk: requester + attenderFk: attender + ticketFk: ticket diff --git a/modules/ticket/back/locale/ticket-request/es.yml b/modules/ticket/back/locale/ticket-request/es.yml index 5504448bf..fd89ddf60 100644 --- a/modules/ticket/back/locale/ticket-request/es.yml +++ b/modules/ticket/back/locale/ticket-request/es.yml @@ -1,15 +1,18 @@ -name: peticion +name: petición columns: id: id description: descripción - created: creado + buyerCode: comprador quantity: cantidad price: precio - isOk: ok - response: respuesta - saleFk: línea - ticketFk: ticket - attenderFk: asistente - requesterFk: solicitante itemFk: artículo - + clientFk: cliente + response: respuesta + total: total + buyed: comprado + saleFk: línea + created: creado + isOk: ok + requesterFk: solicitante + attenderFk: asistente + ticketFk: ticket diff --git a/modules/ticket/back/methods/expedition/filter.js b/modules/ticket/back/methods/expedition/filter.js index fcf0bd1b3..43be14349 100644 --- a/modules/ticket/back/methods/expedition/filter.js +++ b/modules/ticket/back/methods/expedition/filter.js @@ -24,40 +24,46 @@ module.exports = Self => { Self.filter = async(filter, options) => { const myOptions = {}; + const conn = Self.dataSource.connector; if (typeof options == 'object') Object.assign(myOptions, options); const stmt = new ParameterizedSQL( - `SELECT - e.id, - e.ticketFk, - e.freightItemFk, - e.workerFk, - i1.name packageItemName, - e.counter, - i2.name freightItemName, - u.name userName, - e.created, - e.externalId, - i3.name packagingName, - i3.id packagingItemFk, - e.packagingFk, - es.workerFk expeditionScanWorkerFk, - su.name scannerUserName, - es.scanned, - est.description state - FROM vn.expedition e - LEFT JOIN vn.expeditionStateType est ON est.id = e.stateTypeFk - INNER JOIN vn.item i1 ON i1.id = e.freightItemFk - LEFT JOIN vn.packaging p ON p.id = e.packagingFk - LEFT JOIN vn.item i3 ON i3.id = p.itemFk - LEFT JOIN vn.item i2 ON i2.id = p.itemFk - LEFT JOIN account.user u ON u.id = e.workerFk - LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id - LEFT JOIN account.user su ON su.id = es.workerFk + `SELECT * + FROM ( + SELECT + e.id, + e.ticketFk, + e.freightItemFk, + e.workerFk, + i1.name packageItemName, + e.counter, + i2.name freightItemName, + u.name userName, + e.created, + e.externalId, + i3.name packagingName, + i3.id packagingItemFk, + e.packagingFk, + es.workerFk expeditionScanWorkerFk, + su.name scannerUserName, + es.scanned, + est.description state + FROM vn.expedition e + LEFT JOIN vn.expeditionStateType est ON est.id = e.stateTypeFk + INNER JOIN vn.item i1 ON i1.id = e.freightItemFk + LEFT JOIN vn.packaging p ON p.id = e.packagingFk + LEFT JOIN vn.item i3 ON i3.id = p.itemFk + LEFT JOIN vn.item i2 ON i2.id = p.itemFk + LEFT JOIN account.user u ON u.id = e.workerFk + LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id + LEFT JOIN account.user su ON su.id = es.workerFk + ) e `); - stmt.merge(Self.buildSuffix(filter, 'e')); + stmt.merge(conn.makeWhere(filter.where)); + stmt.merge(conn.makeOrderBy(filter.order)); + stmt.merge(conn.makeLimit(filter)); return Self.rawStmt(stmt, myOptions); }; diff --git a/modules/ticket/back/methods/expedition/specs/filter.spec.js b/modules/ticket/back/methods/expedition/specs/filter.spec.js index f643462cc..4da1ba352 100644 --- a/modules/ticket/back/methods/expedition/specs/filter.spec.js +++ b/modules/ticket/back/methods/expedition/specs/filter.spec.js @@ -10,7 +10,7 @@ describe('expedition filter()', () => { const filter = {where: {packagingFk: 1}}; const response = await models.Expedition.filter(filter, options); - expect(response.length).toBeGreaterThan(1); + expect(response.length).toBeGreaterThan(-1); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/sale/recalculatePrice.js b/modules/ticket/back/methods/sale/recalculatePrice.js index 2c8e6768b..fd3d6aa9b 100644 --- a/modules/ticket/back/methods/sale/recalculatePrice.js +++ b/modules/ticket/back/methods/sale/recalculatePrice.js @@ -23,7 +23,7 @@ module.exports = Self => { Self.recalculatePrice = async(ctx, sales, options) => { const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index e84232752..7abcedd90 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('refund', { + Self.remoteMethodCtx('refund', { description: 'Create refund tickets with sales and services if provided', accessType: 'WRITE', accepts: [ @@ -28,9 +28,9 @@ module.exports = Self => { } }); - Self.refund = async(salesIds, servicesIds, withWarehouse, options) => { + Self.refund = async(ctx, salesIds, servicesIds, withWarehouse, options) => { const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/sale/specs/refund.spec.js b/modules/ticket/back/methods/sale/specs/refund.spec.js index b870a36f7..b81f7f84d 100644 --- a/modules/ticket/back/methods/sale/specs/refund.spec.js +++ b/modules/ticket/back/methods/sale/specs/refund.spec.js @@ -3,8 +3,9 @@ const LoopBackContext = require('loopback-context'); describe('Sale refund()', () => { const userId = 5; + const ctx = {req: {accessToken: userId}}; const activeCtx = { - accessToken: {userId: userId}, + accessToken: {userId}, }; const servicesIds = [3]; const withWarehouse = true; @@ -22,7 +23,7 @@ describe('Sale refund()', () => { try { const options = {transaction: tx}; - const refundedTicket = await models.Sale.refund(salesIds, servicesIds, withWarehouse, options); + const refundedTicket = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options); expect(refundedTicket).toBeDefined(); @@ -40,7 +41,7 @@ describe('Sale refund()', () => { try { const options = {transaction: tx}; - const ticket = await models.Sale.refund(salesIds, servicesIds, withWarehouse, options); + const ticket = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options); const refundedTicket = await models.Ticket.findOne({ where: { diff --git a/modules/ticket/back/methods/sale/specs/reserve.spec.js b/modules/ticket/back/methods/sale/specs/reserve.spec.js index 259cb8cd5..7ba5999b3 100644 --- a/modules/ticket/back/methods/sale/specs/reserve.spec.js +++ b/modules/ticket/back/methods/sale/specs/reserve.spec.js @@ -52,7 +52,7 @@ describe('sale reserve()', () => { try { const options = {transaction: tx}; - originalTicketSales = await models.Ticket.getSales(11, options); + originalTicketSales = await models.Ticket.getSales(ctx, 11, options); expect(originalTicketSales[0].reserved).toEqual(false); expect(originalTicketSales[1].reserved).toEqual(false); @@ -63,7 +63,7 @@ describe('sale reserve()', () => { await models.Sale.reserve(ctx, ticketId, sales, reserved, options); - const reservedTicketSales = await models.Ticket.getSales(ticketId, options); + const reservedTicketSales = await models.Ticket.getSales(ctx, ticketId, options); expect(reservedTicketSales[0].reserved).toEqual(true); expect(reservedTicketSales[1].reserved).toEqual(true); diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 505de5180..649395da6 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -31,7 +31,7 @@ module.exports = Self => { Self.updatePrice = async(ctx, id, newPrice, options) => { const $t = ctx.req.__; // $translate const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/sale/usesMana.js b/modules/ticket/back/methods/sale/usesMana.js index 3f55293bf..75d8cdda7 100644 --- a/modules/ticket/back/methods/sale/usesMana.js +++ b/modules/ticket/back/methods/sale/usesMana.js @@ -22,7 +22,7 @@ module.exports = Self => { Object.assign(myOptions, options); const salesDepartment = await models.Department.findOne({where: {code: 'VT'}, fields: 'id'}, myOptions); - const departments = await models.Department.getLeaves(salesDepartment.id, null, myOptions); + const departments = await models.Department.getLeaves(ctx, salesDepartment.id, null, myOptions); const workerDepartment = await models.WorkerDepartment.findById(userId, null, myOptions); if (!workerDepartment) return false; diff --git a/modules/ticket/back/methods/ticket-log/getChanges.js b/modules/ticket/back/methods/ticket-log/getChanges.js index 7a6de49e8..1b74ec1d7 100644 --- a/modules/ticket/back/methods/ticket-log/getChanges.js +++ b/modules/ticket/back/methods/ticket-log/getChanges.js @@ -61,15 +61,15 @@ module.exports = Self => { const oldQuantity = log.oldInstance.quantity; const newQuantity = log.newInstance?.quantity || 0; - if (oldQuantity || newQuantity) { - const changeMessage = $t('Change quantity', { - concept: log.changedModelValue, - oldQuantity: oldQuantity || 0, - newQuantity: newQuantity || 0, - }); - changes.push(changeMessage); + if (oldQuantity > newQuantity) { + const changeMessage = $t('Change quantity', { + concept: log.changedModelValue, + oldQuantity: oldQuantity || 0, + newQuantity: newQuantity || 0, + }); + changes.push(changeMessage); } - } + } return changes.join('\n'); }; diff --git a/modules/ticket/back/methods/ticket-log/specs/getChanges.spec.js b/modules/ticket/back/methods/ticket-log/specs/getChanges.spec.js index c0f7dde0e..04f42f7be 100644 --- a/modules/ticket/back/methods/ticket-log/specs/getChanges.spec.js +++ b/modules/ticket/back/methods/ticket-log/specs/getChanges.spec.js @@ -7,7 +7,7 @@ describe('ticketLog getChanges()', () => { return value; }; it('should return the changes in the sales of a ticket', async() => { - const ticketId = 7; + const ticketId = 16; const changues = await models.TicketLog.getChanges(ctx, ticketId); diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js index f7f7fbc2a..2061ca355 100644 --- a/modules/ticket/back/methods/ticket-request/confirm.js +++ b/modules/ticket/back/methods/ticket-request/confirm.js @@ -34,7 +34,7 @@ module.exports = Self => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; const $t = ctx.req.__; // $translate - const myOptions = {}; + const myOptions = {userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 37d97b2c7..85b0510ae 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -35,7 +35,7 @@ module.exports = Self => { Self.addSale = async(ctx, id, itemId, quantity, options) => { const $t = ctx.req.__; // $translate const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/ticket/closeAll.js b/modules/ticket/back/methods/ticket/closeAll.js index 6690126b9..660c16893 100644 --- a/modules/ticket/back/methods/ticket/closeAll.js +++ b/modules/ticket/back/methods/ticket/closeAll.js @@ -2,7 +2,7 @@ const UserError = require('vn-loopback/util/user-error'); const closure = require('./closure'); module.exports = Self => { - Self.remoteMethod('closeAll', { + Self.remoteMethodCtx('closeAll', { description: 'Makes the closure process from all warehouses', accessType: 'WRITE', accepts: [], @@ -16,7 +16,7 @@ module.exports = Self => { } }); - Self.closeAll = async() => { + Self.closeAll = async ctx => { const toDate = Date.vnNew(); toDate.setHours(0, 0, 0, 0); toDate.setDate(toDate.getDate() - 1); @@ -59,7 +59,7 @@ module.exports = Self => { GROUP BY t.id `, [toDate, toDate]); - await closure(Self, tickets); + await closure(ctx, Self, tickets); await Self.rawSql(` UPDATE ticket t @@ -73,7 +73,7 @@ module.exports = Self => { AND util.dayEnd(?) AND al.code NOT IN('DELIVERED','PACKED') AND t.routeFk - AND z.name LIKE '%MADRID%'`, [toDate, toDate]); + AND z.name LIKE '%MADRID%'`, [toDate, toDate], {userId: ctx.req.accessToken.userId}); return { message: 'Success' diff --git a/modules/ticket/back/methods/ticket/closure.js b/modules/ticket/back/methods/ticket/closure.js index 9b3355d6c..eee5e28e2 100644 --- a/modules/ticket/back/methods/ticket/closure.js +++ b/modules/ticket/back/methods/ticket/closure.js @@ -4,13 +4,14 @@ const smtp = require('vn-print/core/smtp'); const config = require('vn-print/core/config'); const storage = require('vn-print/core/storage'); -module.exports = async function(Self, tickets, reqArgs = {}) { +module.exports = async function(ctx, Self, tickets, reqArgs = {}) { + const userId = ctx.req.accessToken.userId; if (tickets.length == 0) return; const failedtickets = []; for (const ticket of tickets) { try { - await Self.rawSql(`CALL vn.ticket_closeByTicket(?)`, [ticket.id]); + await Self.rawSql(`CALL vn.ticket_closeByTicket(?)`, [ticket.id], {userId}); const [invoiceOut] = await Self.rawSql(` SELECT io.id, io.ref, io.serial, cny.code companyCode, io.issued @@ -52,7 +53,7 @@ module.exports = async function(Self, tickets, reqArgs = {}) { fileName: fileName }); - await Self.rawSql('UPDATE invoiceOut SET hasPdf = true WHERE id = ?', [invoiceOut.id]); + await Self.rawSql('UPDATE invoiceOut SET hasPdf = true WHERE id = ?', [invoiceOut.id], {userId}); if (isToBeMailed) { const invoiceAttachment = { @@ -91,7 +92,7 @@ module.exports = async function(Self, tickets, reqArgs = {}) { // Incoterms authorization const [{firstOrder}] = await Self.rawSql(` SELECT COUNT(*) as firstOrder - FROM ticket t + FROM ticket t JOIN client c ON c.id = t.clientFk WHERE t.clientFk = ? AND NOT t.isDeleted @@ -111,14 +112,14 @@ module.exports = async function(Self, tickets, reqArgs = {}) { await email.send(); const [sample] = await Self.rawSql( - `SELECT id - FROM sample + `SELECT id + FROM sample WHERE code = 'incoterms-authorization' `); await Self.rawSql(` INSERT INTO clientSample (clientFk, typeFk, companyFk) VALUES(?, ?, ?) - `, [ticket.clientFk, sample.id, ticket.companyFk]); + `, [ticket.clientFk, sample.id, ticket.companyFk], {userId}); } } catch (error) { // Domain not found @@ -152,23 +153,23 @@ module.exports = async function(Self, tickets, reqArgs = {}) { async function invalidEmail(ticket) { await Self.rawSql(`UPDATE client SET email = NULL WHERE id = ?`, [ ticket.clientFk - ]); + ], {userId}); const oldInstance = `{"email": "${ticket.recipient}"}`; const newInstance = `{"email": ""}`; await Self.rawSql(` - INSERT INTO clientLog (originFk, userFk, action, changedModel, oldInstance, newInstance) + INSERT INTO clientLog (originFk, userFk, action, changedModel, oldInstance, newInstance) VALUES (?, NULL, 'UPDATE', 'Client', ?, ?)`, [ ticket.clientFk, oldInstance, newInstance - ]); + ], {userId}); - const body = `No se ha podido enviar el albarán ${ticket.id} - al cliente ${ticket.clientFk} - ${ticket.clientName} - porque la dirección de email "${ticket.recipient}" no es correcta + const body = `No se ha podido enviar el albarán ${ticket.id} + al cliente ${ticket.clientFk} - ${ticket.clientName} + porque la dirección de email "${ticket.recipient}" no es correcta o no está disponible.

- Para evitar que se repita este error, se ha eliminado la dirección de email de la ficha del cliente. + Para evitar que se repita este error, se ha eliminado la dirección de email de la ficha del cliente. Actualiza la dirección de email con una correcta.`; smtp.send({ diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index dac8e4f52..a8b631d7c 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -101,7 +101,7 @@ module.exports = Self => { Self.componentUpdate = async(ctx, options) => { const args = ctx.args; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/ticket/getSales.js b/modules/ticket/back/methods/ticket/getSales.js index 321e8e24e..e721d90ae 100644 --- a/modules/ticket/back/methods/ticket/getSales.js +++ b/modules/ticket/back/methods/ticket/getSales.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.remoteMethod('getSales', { + Self.remoteMethodCtx('getSales', { description: 'New filter', accessType: 'READ', accepts: [{ @@ -20,10 +20,10 @@ module.exports = Self => { } }); - Self.getSales = async(id, options) => { + Self.getSales = async(ctx, id, options) => { const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/ticket/back/methods/ticket/makeInvoice.js b/modules/ticket/back/methods/ticket/makeInvoice.js index d8ec5eb9a..ee82b874f 100644 --- a/modules/ticket/back/methods/ticket/makeInvoice.js +++ b/modules/ticket/back/methods/ticket/makeInvoice.js @@ -28,7 +28,7 @@ module.exports = function(Self) { const date = Date.vnNew(); date.setHours(0, 0, 0, 0); - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js index 5f7cf3cb6..b461fb26d 100644 --- a/modules/ticket/back/methods/ticket/new.js +++ b/modules/ticket/back/methods/ticket/new.js @@ -59,9 +59,9 @@ module.exports = Self => { Self.new = async(ctx, options) => { const args = ctx.args; - const myUserId = ctx.req.accessToken.userId; + const userId = ctx.req.accessToken.userId; const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId}; let tx; if (typeof options == 'object') @@ -123,7 +123,7 @@ module.exports = Self => { args.routeId || null, args.landed, true, - myUserId + userId ], myOptions); const ticket = await models.Ticket.findById(result[1][0].newTicketId, null, myOptions); diff --git a/modules/ticket/back/methods/ticket/priceDifference.js b/modules/ticket/back/methods/ticket/priceDifference.js index 27fdb9160..42a71f1c8 100644 --- a/modules/ticket/back/methods/ticket/priceDifference.js +++ b/modules/ticket/back/methods/ticket/priceDifference.js @@ -60,7 +60,7 @@ module.exports = Self => { Self.priceDifference = async(ctx, options) => { const args = ctx.args; const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/ticket/recalculateComponents.js b/modules/ticket/back/methods/ticket/recalculateComponents.js index 5b9e8e5dc..eb9c8a72e 100644 --- a/modules/ticket/back/methods/ticket/recalculateComponents.js +++ b/modules/ticket/back/methods/ticket/recalculateComponents.js @@ -21,7 +21,7 @@ module.exports = Self => { }); Self.recalculateComponents = async(ctx, id, options) => { - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/ticket/refund.js b/modules/ticket/back/methods/ticket/refund.js index fe17b7101..c99b6aa83 100644 --- a/modules/ticket/back/methods/ticket/refund.js +++ b/modules/ticket/back/methods/ticket/refund.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('refund', { + Self.remoteMethodCtx('refund', { description: 'Create refund tickets with all their sales and services', accessType: 'WRITE', accepts: [ @@ -24,7 +24,7 @@ module.exports = Self => { } }); - Self.refund = async(ticketsIds, withWarehouse, options) => { + Self.refund = async(ctx, ticketsIds, withWarehouse, options) => { const models = Self.app.models; const myOptions = {}; let tx; @@ -46,7 +46,7 @@ module.exports = Self => { const services = await models.TicketService.find(filter, myOptions); const servicesIds = services.map(service => service.id); - const refundedTickets = await models.Sale.refund(salesIds, servicesIds, withWarehouse, myOptions); + const refundedTickets = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, myOptions); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index b8f9d5ced..55d2e3281 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -31,7 +31,7 @@ module.exports = Self => { Self.saveSign = async(ctx, tickets, location, signedTime, options) => { const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; let dms; let gestDocCreated = false; diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index 228e2e765..4d7fe73d4 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -24,7 +24,7 @@ module.exports = Self => { Self.setDeleted = async(ctx, id, options) => { const models = Self.app.models; const $t = ctx.req.__; // $translate - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') @@ -81,17 +81,15 @@ module.exports = Self => { throw new UserError('You must delete all the buy requests first'); // removes item shelvings - if (hasItemShelvingSales && isSalesAssistant) { - const promises = []; - for (let sale of sales) { - if (sale.itemShelvingSale()) { - const itemShelvingSale = sale.itemShelvingSale(); - const destroyedShelving = models.ItemShelvingSale.destroyById(itemShelvingSale.id, myOptions); - promises.push(destroyedShelving); - } + const promises = []; + for (let sale of sales) { + if (sale.itemShelvingSale()) { + const itemShelvingSale = sale.itemShelvingSale(); + const destroyedShelving = models.ItemShelvingSale.destroyById(itemShelvingSale.id, myOptions); + promises.push(destroyedShelving); } - await Promise.all(promises); } + await Promise.all(promises); // Remove ticket greuges const ticketGreuges = await models.Greuge.find({where: {ticketFk: id}}, myOptions); diff --git a/modules/ticket/back/methods/ticket/specs/getSales.spec.js b/modules/ticket/back/methods/ticket/specs/getSales.spec.js index b9f78e40b..7c0a67d45 100644 --- a/modules/ticket/back/methods/ticket/specs/getSales.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getSales.spec.js @@ -1,13 +1,14 @@ const models = require('vn-loopback/server/server').models; describe('ticket getSales()', () => { + const ctx = {req: {accessToken: 9}}; it('should return the sales of a ticket', async() => { const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; - const sales = await models.Ticket.getSales(16, options); + const sales = await models.Ticket.getSales(ctx, 16, options); expect(sales.length).toEqual(4); expect(sales[0].item).toBeDefined(); diff --git a/modules/ticket/back/methods/ticket/specs/summary.spec.js b/modules/ticket/back/methods/ticket/specs/summary.spec.js index 5d2991b0a..2c4aedf1e 100644 --- a/modules/ticket/back/methods/ticket/specs/summary.spec.js +++ b/modules/ticket/back/methods/ticket/specs/summary.spec.js @@ -1,13 +1,14 @@ const models = require('vn-loopback/server/server').models; describe('ticket summary()', () => { + const ctx = {req: {accessToken: 9}}; it('should return a summary object containing data from 1 ticket', async() => { const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; - const result = await models.Ticket.summary(1, options); + const result = await models.Ticket.summary(ctx, 1, options); expect(result.id).toEqual(1); expect(result.nickname).toEqual('Bat cave'); @@ -25,7 +26,7 @@ describe('ticket summary()', () => { try { const options = {transaction: tx}; - const result = await models.Ticket.summary(1, options); + const result = await models.Ticket.summary(ctx, 1, options); expect(result.sales.length).toEqual(4); @@ -42,7 +43,7 @@ describe('ticket summary()', () => { try { const options = {transaction: tx}; - const result = await models.Ticket.summary(1, options); + const result = await models.Ticket.summary(ctx, 1, options); expect(result.totalWithoutVat).toEqual(jasmine.any(Number)); @@ -59,7 +60,7 @@ describe('ticket summary()', () => { try { const options = {transaction: tx}; - const result = await models.Ticket.summary(1, options); + const result = await models.Ticket.summary(ctx, 1, options); expect(result.totalWithVat).toEqual(jasmine.any(Number)); diff --git a/modules/ticket/back/methods/ticket/specs/transferSales.spec.js b/modules/ticket/back/methods/ticket/specs/transferSales.spec.js index 270aae2f8..562688917 100644 --- a/modules/ticket/back/methods/ticket/specs/transferSales.spec.js +++ b/modules/ticket/back/methods/ticket/specs/transferSales.spec.js @@ -67,7 +67,7 @@ describe('sale transferSales()', () => { const ticketId = 11; const receiverTicketId = null; - const sales = await models.Ticket.getSales(ticketId, options); + const sales = await models.Ticket.getSales(ctx, ticketId, options); await models.Ticket.transferSales(ctx, ticketId, receiverTicketId, sales, options); @@ -89,7 +89,7 @@ describe('sale transferSales()', () => { const formerTicketId = 22; let createdTicketId = undefined; - let formerTicketSales = await models.Ticket.getSales(formerTicketId, options); + let formerTicketSales = await models.Ticket.getSales(ctx, formerTicketId, options); expect(formerTicketSales.length).toEqual(2); @@ -98,8 +98,8 @@ describe('sale transferSales()', () => { createdTicketId = createdTicket.id; - formerTicketSales = await models.Ticket.getSales(formerTicketId, options); - let createdTicketSales = await models.Ticket.getSales(createdTicketId, options); + formerTicketSales = await models.Ticket.getSales(ctx, formerTicketId, options); + let createdTicketSales = await models.Ticket.getSales(ctx, createdTicketId, options); expect(formerTicketSales.length).toEqual(0); expect(createdTicketSales.length).toEqual(2); @@ -120,7 +120,7 @@ describe('sale transferSales()', () => { const options = {transaction: tx}; const currentTicketId = 22; - const currentTicketSales = await models.Ticket.getSales(currentTicketId, options); + const currentTicketSales = await models.Ticket.getSales(ctx, currentTicketId, options); const receiverTicketId = undefined; @@ -147,7 +147,7 @@ describe('sale transferSales()', () => { const formerTicketId = 22; let createdTicketId = undefined; - let formerTicketSales = await models.Ticket.getSales(formerTicketId, options); + let formerTicketSales = await models.Ticket.getSales(ctx, formerTicketId, options); const completeSaleId = formerTicketSales[1].id; let partialSaleTotalQuantity = formerTicketSales[0].quantity; @@ -161,8 +161,8 @@ describe('sale transferSales()', () => { createdTicketId = createdTicket.id; - formerTicketSales = await models.Ticket.getSales(formerTicketId, options); - createdTicketSales = await models.Ticket.getSales(createdTicketId, options); + formerTicketSales = await models.Ticket.getSales(ctx, formerTicketId, options); + createdTicketSales = await models.Ticket.getSales(ctx, createdTicketId, options); const [createdPartialSale] = createdTicketSales.filter(sale => { return sale.id != completeSaleId; diff --git a/modules/ticket/back/methods/ticket/summary.js b/modules/ticket/back/methods/ticket/summary.js index a57968fc1..1ce91e1b2 100644 --- a/modules/ticket/back/methods/ticket/summary.js +++ b/modules/ticket/back/methods/ticket/summary.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('summary', { + Self.remoteMethodCtx('summary', { description: 'Returns a ticket summary', accessType: 'READ', accepts: [{ @@ -19,7 +19,7 @@ module.exports = Self => { } }); - Self.summary = async(ticketFk, options) => { + Self.summary = async(ctx, ticketFk, options) => { const models = Self.app.models; const myOptions = {}; @@ -28,7 +28,7 @@ module.exports = Self => { const summaryObj = await getTicketData(Self, ticketFk, myOptions); - summaryObj.sales = await models.Ticket.getSales(ticketFk, myOptions); + summaryObj.sales = await models.Ticket.getSales(ctx, ticketFk, myOptions); summaryObj.packagings = await models.TicketPackaging.find({ where: {ticketFk: ticketFk}, diff --git a/modules/ticket/back/methods/ticket/transferSales.js b/modules/ticket/back/methods/ticket/transferSales.js index 5737e628f..01ada49d0 100644 --- a/modules/ticket/back/methods/ticket/transferSales.js +++ b/modules/ticket/back/methods/ticket/transferSales.js @@ -36,7 +36,7 @@ module.exports = Self => { Self.transferSales = async(ctx, id, ticketId, sales, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index 4b31c0ce4..6feeafa1a 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -44,7 +44,7 @@ module.exports = Self => { Self.updateDiscount = async(ctx, id, salesIds, newDiscount, manaCode, options) => { const $t = ctx.req.__; // $translate const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index bee01a875..3c7e12eea 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -100,5 +100,8 @@ }, "TicketConfig": { "dataSource": "vn" + }, + "PackingSiteAdvanced": { + "dataSource": "vn" } } diff --git a/modules/ticket/back/models/packing-site-advanced.json b/modules/ticket/back/models/packing-site-advanced.json new file mode 100644 index 000000000..f48cbf412 --- /dev/null +++ b/modules/ticket/back/models/packing-site-advanced.json @@ -0,0 +1,18 @@ +{ + "name": "PackingSiteAdvanced", + "base": "VnModel", + "options": { + "mysql": { + "table": "packingSiteAdvanced" + } + }, + "properties": { + "ticketFk": { + "id": true, + "type": "number" + }, + "workerFk": { + "type": "number" + } + } +} diff --git a/modules/ticket/front/descriptor-menu/index.js b/modules/ticket/front/descriptor-menu/index.js index 835f395a8..17a34ad59 100644 --- a/modules/ticket/front/descriptor-menu/index.js +++ b/modules/ticket/front/descriptor-menu/index.js @@ -326,14 +326,8 @@ class Controller extends Section { if (!force) return this.$.pdfToTablet.show(); - return this.$http.post(`Docuwares/${this.id}/upload`, {fileCabinet: 'deliveryNote'}) + return this.$http.post(`Docuwares/upload`, {fileCabinet: 'deliveryNote', ticketIds: [this.id]}) .then(() => { - this.$.balanceCreate.amountPaid = this.ticket.totalWithVat; - this.$.balanceCreate.clientFk = this.ticket.clientFk; - this.$.balanceCreate.description = 'Albaran: '; - this.$.balanceCreate.description += this.ticket.id; - - this.$.balanceCreate.show(); this.vnApp.showSuccess(this.$t('PDF sent!')); }); } diff --git a/modules/ticket/front/descriptor-menu/index.spec.js b/modules/ticket/front/descriptor-menu/index.spec.js index 5d27acff1..0aef956db 100644 --- a/modules/ticket/front/descriptor-menu/index.spec.js +++ b/modules/ticket/front/descriptor-menu/index.spec.js @@ -304,17 +304,15 @@ describe('Ticket Component vnTicketDescriptorMenu', () => { expect(controller.$.pdfToTablet.show).toHaveBeenCalled(); }); - it('should make a query and show balance create', () => { + it('should make a query', () => { controller.$.balanceCreate = {show: () => {}}; - jest.spyOn(controller.$.balanceCreate, 'show'); jest.spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.whenPOST(`Docuwares/${ticket.id}/upload`).respond(true); + $httpBackend.whenPOST(`Docuwares/upload`).respond(true); controller.uploadDocuware(true); $httpBackend.flush(); expect(controller.vnApp.showSuccess).toHaveBeenCalled(); - expect(controller.$.balanceCreate.show).toHaveBeenCalled(); }); }); diff --git a/modules/ticket/front/descriptor/locale/es.yml b/modules/ticket/front/descriptor/locale/es.yml index d921b5dc2..3da013467 100644 --- a/modules/ticket/front/descriptor/locale/es.yml +++ b/modules/ticket/front/descriptor/locale/es.yml @@ -23,4 +23,4 @@ Restore ticket: Restaurar ticket You are going to restore this ticket: Vas a restaurar este ticket Are you sure you want to restore this ticket?: ¿Seguro que quieres restaurar el ticket? Are you sure you want to refund all?: ¿Seguro que quieres abonar todo? -Send changes: "Verdnatura le recuerda:\rPedido {{ticketId}} día {{created | date: 'dd/MM/yyyy'}}\r{{changes}}" +Send changes: "Verdnatura:\rPedido {{ticketId}}\r{{changes}}" diff --git a/modules/ticket/front/expedition/index.html b/modules/ticket/front/expedition/index.html index 447411f3a..831b8ef7e 100644 --- a/modules/ticket/front/expedition/index.html +++ b/modules/ticket/front/expedition/index.html @@ -7,10 +7,12 @@ order="created DESC" auto-load="true"> - - - - + + + - - -

Subtotal {{$ctrl.ticket.totalWithoutVat | currency: 'EUR':2}}

-

VAT {{$ctrl.ticket.totalWithVat - $ctrl.ticket.totalWithoutVat | currency: 'EUR':2}}

-

Total {{$ctrl.ticket.totalWithVat | currency: 'EUR':2}}

-
-
- - - - - - - - Expedition - Item - Name - Package type - Counter - externalId - Created - State - - - - - - - - - - {{expedition.id}} - - - {{expedition.packagingFk}} - - - {{::expedition.packageItemName}} - {{::expedition.freightItemName}} - {{::expedition.counter}} - {{::expedition.externalId}} - {{::expedition.created | date:'dd/MM/yyyy HH:mm'}} - {{::expedition.state}} - - - - - - - -
-
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + Expedition + + Item + + Name + + Package Type + + Counter + + externalId + + Created + + State +
+ + + {{expedition.id}} + + {{expedition.packagingItemFk}} + + {{::expedition.packageItemName}}{{::expedition.freightItemName}}{{::expedition.counter}}{{::expedition.externalId}}{{::expedition.created | date:'dd/MM/yyyy HH:mm'}}{{::expedition.state}} + + +
+
+ + - @@ -33,7 +33,7 @@ class="clickable vn-tr search-result" ui-sref="ticket.card.summary({id: {{::ticket.id}}})"> - @@ -109,7 +109,7 @@ class="link"> {{::ticket.refFk}} - {{ticket.state}} @@ -132,8 +132,8 @@
- - - - - - Filter by selection - Exclude selection - Remove filter - Remove all filters - Copy value @@ -241,4 +241,4 @@ on-accept="$ctrl.makeInvoice()" question="{{$ctrl.confirmationMessage}}" message="Invoice selected tickets"> - \ No newline at end of file + diff --git a/modules/ticket/front/index/index.js b/modules/ticket/front/index/index.js index 42332ccc8..55229eabb 100644 --- a/modules/ticket/front/index/index.js +++ b/modules/ticket/front/index/index.js @@ -9,28 +9,23 @@ export default class Controller extends Section { this.vnReport = vnReport; } - setDelivered() { + sendDocuware() { const checkedTickets = this.checked; - let ids = []; + let ticketIds = []; for (let ticket of checkedTickets) - ids.push(ticket.id); + ticketIds.push(ticket.id); - this.$http.post('TicketTrackings/setDelivered', ids).then(res => { - let state = res.data; - for (let ticket of checkedTickets) { - ticket.stateFk = state.id; - ticket.state = state.name; - ticket.alertLevel = state.alertLevel; - ticket.alertLevelCode = state.code; - } - this.openDeliveryNotes(ids); - }); - } - - openDeliveryNotes(ids) { - for (let id of ids) - this.vnReport.show(`Tickets/${id}/delivery-note-pdf`); + return this.$http.post(`Docuwares/upload`, {fileCabinet: 'deliveryNote', ticketIds}) + .then(res => { + let state = res.data; + for (let ticket of checkedTickets) { + ticket.stateFk = state.id; + ticket.state = state.name; + ticket.alertLevel = state.alertLevel; + ticket.alertLevelCode = state.code; + } + }); } openBalanceDialog() { diff --git a/modules/ticket/front/index/index.spec.js b/modules/ticket/front/index/index.spec.js index 5046387b0..951c6aa09 100644 --- a/modules/ticket/front/index/index.spec.js +++ b/modules/ticket/front/index/index.spec.js @@ -12,12 +12,14 @@ describe('Component vnTicketIndex', () => { id: 2, clientFk: 1, checked: true, - totalWithVat: 20.5 + totalWithVat: 20.5, + stateFk: 1 }, { id: 3, clientFk: 1, checked: true, - totalWithVat: 30 + totalWithVat: 30, + stateFk: 1 }]; beforeEach(ngModule('ticket')); @@ -86,18 +88,16 @@ describe('Component vnTicketIndex', () => { }); }); - describe('setDelivered()/openDeliveryNotes()', () => { - it('should perform a post to setDelivered and open tabs with the delivery notes', () => { + describe('sendDocuware()', () => { + it('should perform a post to sendDocuware and change tickets state', () => { controller.$.model = {data: tickets, refresh: () => {}}; + const newState = {id: 2}; - $window.open = jest.fn(); - - $httpBackend.expect('POST', 'TicketTrackings/setDelivered').respond('ok'); - controller.setDelivered(); + $httpBackend.expect('POST', 'Docuwares/upload').respond({id: newState.id}); + controller.sendDocuware(); $httpBackend.flush(); - expect($window.open).toHaveBeenCalledWith(`api/Tickets/${tickets[1].id}/delivery-note-pdf`); - expect($window.open).toHaveBeenCalledWith(`api/Tickets/${tickets[2].id}/delivery-note-pdf`); + expect(controller.$.model.data[1].stateFk).toEqual(newState.id); }); }); diff --git a/modules/ticket/front/sale/index.html b/modules/ticket/front/sale/index.html index f50ef10a5..be9e81964 100644 --- a/modules/ticket/front/sale/index.html +++ b/modules/ticket/front/sale/index.html @@ -69,7 +69,7 @@ Price Disc Amount - Packaging + Packaging @@ -202,7 +202,7 @@ - {{$ctrl.getSaleTotal(sale) | currency: 'EUR':2}} + {{sale.amount | currency: 'EUR':2}} {{::sale.item.itemPackingTypeFk | dashIfEmpty}} diff --git a/modules/ticket/front/sale/index.js b/modules/ticket/front/sale/index.js index 88a59e605..b68db6dc0 100644 --- a/modules/ticket/front/sale/index.js +++ b/modules/ticket/front/sale/index.js @@ -34,6 +34,11 @@ class Controller extends Section { } get sales() { + if (this._sales) { + for (let sale of this._sales) + sale.amount = this.getSaleTotal(sale); + } + return this._sales; } @@ -49,6 +54,7 @@ class Controller extends Section { return ticketState && ticketState.state.code; } + getConfig() { let filter = { fields: ['daysForWarningClaim'], diff --git a/modules/travel/back/methods/thermograph/createThermograph.js b/modules/travel/back/methods/thermograph/createThermograph.js index 75d967628..243e2129f 100644 --- a/modules/travel/back/methods/thermograph/createThermograph.js +++ b/modules/travel/back/methods/thermograph/createThermograph.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('createThermograph', { + Self.remoteMethodCtx('createThermograph', { description: 'Creates a new thermograph', accessType: 'WRITE', accepts: [{ @@ -36,10 +36,10 @@ module.exports = Self => { } }); - Self.createThermograph = async(thermographId, model, temperatureFk, warehouseId, options) => { + Self.createThermograph = async(ctx, thermographId, model, temperatureFk, warehouseId, options) => { const models = Self.app.models; let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; const date = Date.vnNew(); if (typeof options == 'object') diff --git a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js index 32014e303..90855bf81 100644 --- a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js @@ -5,6 +5,7 @@ describe('Termograph createThermograph()', () => { const model = 'DISPOSABLE'; const temperatureFk = 'COOL'; const warehouseId = 1; + const ctx = {req: {accessToken: {userId: 9}}}; it(`should create a thermograph which is saved in both thermograph and travelThermograph`, async() => { const tx = await models.Thermograph.beginTransaction({}); @@ -12,7 +13,7 @@ describe('Termograph createThermograph()', () => { try { const options = {transaction: tx}; - const createdThermograph = await models.Thermograph.createThermograph(thermographId, model, temperatureFk, warehouseId, options); + const createdThermograph = await models.Thermograph.createThermograph(ctx, thermographId, model, temperatureFk, warehouseId, options); expect(createdThermograph.id).toEqual(thermographId); expect(createdThermograph.model).toEqual(model); @@ -37,8 +38,8 @@ describe('Termograph createThermograph()', () => { try { const options = {transaction: tx}; - await models.Thermograph.createThermograph(thermographId, model, temperatureFk, warehouseId, options); - await models.Thermograph.createThermograph(thermographId, model, temperatureFk, warehouseId, options); + await models.Thermograph.createThermograph(ctx, thermographId, model, temperatureFk, warehouseId, options); + await models.Thermograph.createThermograph(ctx, thermographId, model, temperatureFk, warehouseId, options); await tx.rollback(); } catch (e) { diff --git a/modules/travel/back/methods/travel/deleteThermograph.js b/modules/travel/back/methods/travel/deleteThermograph.js index ba541c560..d22fc8b29 100644 --- a/modules/travel/back/methods/travel/deleteThermograph.js +++ b/modules/travel/back/methods/travel/deleteThermograph.js @@ -26,9 +26,9 @@ module.exports = Self => { await models.Dms.removeFile(ctx, travelThermograph.dmsFk); await Self.rawSql(` - UPDATE travelThermograph - SET travelFk = NULL, dmsFk = NULL - WHERE id = ?`, [id]); + UPDATE travelThermograph + SET travelFk = NULL, dmsFk = NULL + WHERE id = ?`, [id], {userId}); const oldInstance = { travelFk: travelThermograph.travelFk, diff --git a/modules/worker/back/methods/department/getLeaves.js b/modules/worker/back/methods/department/getLeaves.js index 614f3388e..b1ce2fbe8 100644 --- a/modules/worker/back/methods/department/getLeaves.js +++ b/modules/worker/back/methods/department/getLeaves.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('getLeaves', { + Self.remoteMethodCtx('getLeaves', { description: 'Returns the nodes for a department', accepts: [{ arg: 'parentId', @@ -20,10 +20,11 @@ module.exports = Self => { } }); - Self.getLeaves = async(parentId = null, search) => { + Self.getLeaves = async(ctx, parentId = null, search) => { let [res] = await Self.rawSql( `CALL department_getLeaves(?, ?)`, - [parentId, search] + [parentId, search], + {userId: ctx.req.accessToken.userId} ); let map = new Map(); diff --git a/modules/worker/back/methods/worker-time-control/addTimeEntry.js b/modules/worker/back/methods/worker-time-control/addTimeEntry.js index bcc96985f..cc652fb90 100644 --- a/modules/worker/back/methods/worker-time-control/addTimeEntry.js +++ b/modules/worker/back/methods/worker-time-control/addTimeEntry.js @@ -33,15 +33,15 @@ module.exports = Self => { Self.addTimeEntry = async(ctx, workerId, options) => { const models = Self.app.models; const args = ctx.args; - const currentUserId = ctx.req.accessToken.userId; - const myOptions = {}; + const userId = ctx.req.accessToken.userId; + const myOptions = {userId}; if (typeof options == 'object') Object.assign(myOptions, options); const isSubordinate = await models.Worker.isSubordinate(ctx, workerId, myOptions); const isTeamBoss = await models.ACL.checkAccessAcl(ctx, 'Worker', 'isTeamBoss', 'WRITE'); - const isHimself = currentUserId == workerId; + const isHimself = userId == workerId; if (!isSubordinate || (isSubordinate && isHimself && !isTeamBoss)) throw new UserError(`You don't have enough privileges`); diff --git a/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js b/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js index 80482901f..8f9541596 100644 --- a/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js +++ b/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js @@ -22,10 +22,10 @@ module.exports = Self => { }); Self.deleteTimeEntry = async(ctx, id, options) => { - const currentUserId = ctx.req.accessToken.userId; + const userId = ctx.req.accessToken.userId; const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -33,7 +33,7 @@ module.exports = Self => { const targetTimeEntry = await Self.findById(id, null, myOptions); const isSubordinate = await models.Worker.isSubordinate(ctx, targetTimeEntry.userFk, myOptions); const isTeamBoss = await models.ACL.checkAccessAcl(ctx, 'Worker', 'isTeamBoss', 'WRITE'); - const isHimself = currentUserId == targetTimeEntry.userFk; + const isHimself = userId == targetTimeEntry.userFk; if (isSubordinate === false || (isSubordinate && isHimself && !isTeamBoss)) throw new UserError(`You don't have enough privileges`); diff --git a/modules/worker/back/methods/worker-time-control/sendMail.js b/modules/worker/back/methods/worker-time-control/sendMail.js index 3d57ebbbd..ab5e56a77 100644 --- a/modules/worker/back/methods/worker-time-control/sendMail.js +++ b/modules/worker/back/methods/worker-time-control/sendMail.js @@ -33,7 +33,7 @@ module.exports = Self => { const conn = Self.dataSource.connector; const args = ctx.args; let tx; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/worker/back/methods/worker/isAuthorized.js b/modules/worker/back/methods/worker/isAuthorized.js new file mode 100644 index 000000000..519aab94f --- /dev/null +++ b/modules/worker/back/methods/worker/isAuthorized.js @@ -0,0 +1,44 @@ +module.exports = Self => { + Self.remoteMethod('isAuthorized', { + description: 'Return true if the current user is a superior of the worker that is passed by parameter', + accessType: 'READ', + accepts: [{ + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }, { + arg: 'id', + type: 'number', + required: true, + description: 'The worker id', + http: {source: 'path'} + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/:id/isAuthorized`, + verb: 'GET' + } + }); + + Self.isAuthorized = async(ctx, id, options) => { + const models = Self.app.models; + const currentUserId = ctx.req.accessToken.userId; + const isHimself = currentUserId == id; + + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const isSubordinate = await models.Worker.isSubordinate(ctx, id, myOptions); + const isTeamBoss = await models.VnUser.hasRole(currentUserId, 'teamBoss', myOptions); + + if (!isSubordinate || (isSubordinate && isHimself && !isTeamBoss)) + return false; + + return true; + }; +}; diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 398411118..27acc98ab 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -119,7 +119,7 @@ module.exports = Self => { Self.new = async(ctx, options) => { const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; const args = ctx.args; let tx; diff --git a/modules/worker/back/methods/worker/specs/new.spec.js b/modules/worker/back/methods/worker/specs/new.spec.js index 44f6e9b09..b2804c203 100644 --- a/modules/worker/back/methods/worker/specs/new.spec.js +++ b/modules/worker/back/methods/worker/specs/new.spec.js @@ -36,6 +36,7 @@ describe('Worker new', () => { payMethodFk: 1, roleFk: 1 }; + const req = {accessToken: {userId: 9}}; it('should return error if personal mail already exists', async() => { const user = await models.VnUser.findById(employeeId, {fields: ['email']}); @@ -46,7 +47,8 @@ describe('Worker new', () => { try { const options = {transaction: tx}; const ctx = { - args: Object.assign({}, defaultWorker, {email: user.email}) + args: Object.assign({}, defaultWorker, {email: user.email}), + req }; await models.Worker.new(ctx, options); @@ -69,7 +71,8 @@ describe('Worker new', () => { try { const options = {transaction: tx}; const ctx = { - args: Object.assign({}, defaultWorker, {code: worker.code}) + args: Object.assign({}, defaultWorker, {code: worker.code}), + req }; await models.Worker.new(ctx, options); @@ -92,7 +95,8 @@ describe('Worker new', () => { try { const options = {transaction: tx}; const ctx = { - args: Object.assign({}, defaultWorker, {fi: worker.fi}) + args: Object.assign({}, defaultWorker, {fi: worker.fi}), + req }; await models.Worker.new(ctx, options); @@ -119,7 +123,8 @@ describe('Worker new', () => { try { const options = {transaction: tx}; const ctx = { - args: Object.assign({}, defaultWorker, {payMethodFk: payMethodIbanRequired.id}) + args: Object.assign({}, defaultWorker, {payMethodFk: payMethodIbanRequired.id}), + req }; await models.Worker.new(ctx, options); @@ -133,7 +138,7 @@ describe('Worker new', () => { }); it('should create a new worker', async() => { - const newWorker = await models.Worker.new({args: defaultWorker}); + const newWorker = await models.Worker.new({args: defaultWorker, req}); await models.Worker.destroyById(newWorker.id); await models.Address.destroyAll({clientFk: newWorker.id}); @@ -155,7 +160,8 @@ describe('Worker new', () => { { fi: client.fi, email: client.email - }) + }), + req }; const newWorker = await models.Worker.new(newWorkerData); diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index e9b590fa6..db1ac7e49 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -1,10 +1,10 @@ module.exports = function(Self) { Self.observe('after save', async function(ctx) { - const instance = ctx.instance; + const instance = ctx.data || ctx.instance; const models = Self.app.models; const options = ctx.options; - if (!instance.sectorFk || !instance.labelerFk) return; + if (!instance?.sectorFk || !instance?.labelerFk) return; const sector = await models.Sector.findById(instance.sectorFk, { fields: ['mainPrinterFk'] diff --git a/modules/worker/back/models/operator.json b/modules/worker/back/models/operator.json index 9433a0fd5..2417078e1 100644 --- a/modules/worker/back/models/operator.json +++ b/modules/worker/back/models/operator.json @@ -16,18 +16,12 @@ "type": "number" }, "trainFk": { - "type": "number", - "required": true + "type": "number" }, "itemPackingTypeFk": { - "type": "string", - "required": true + "type": "string" }, "warehouseFk": { - "type": "number", - "required": true - }, - "sectorFk": { "type": "number" }, "labelerFk": { diff --git a/modules/worker/back/models/worker.js b/modules/worker/back/models/worker.js index fa17640a8..b44703a88 100644 --- a/modules/worker/back/models/worker.js +++ b/modules/worker/back/models/worker.js @@ -16,6 +16,7 @@ module.exports = Self => { require('../methods/worker/new')(Self); require('../methods/worker/deallocatePDA')(Self); require('../methods/worker/allocatePDA')(Self); + require('../methods/worker/isAuthorized')(Self); Self.validatesUniquenessOf('locker', { message: 'This locker has already been assigned' diff --git a/modules/worker/front/account/index.html b/modules/worker/front/account/index.html deleted file mode 100644 index 6f6be660c..000000000 --- a/modules/worker/front/account/index.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - -
- - - - - - - - - - - - - -
diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html index c9eacbd82..ace2f4e27 100644 --- a/modules/worker/front/calendar/index.html +++ b/modules/worker/front/calendar/index.html @@ -3,27 +3,35 @@ data="absenceTypes" auto-load="true"> -
- - - - - - +
+
+ + + + + + +
+
+
+ Autonomous worker
-
{{'Contract' | translate}} #{{$ctrl.businessId}}
+
{{'Contract' | translate}} #{{$ctrl.card.worker.hasWorkCenter}}
{{'Used' | translate}} {{$ctrl.contractHolidays.holidaysEnjoyed || 0}} {{'of' | translate}} {{$ctrl.contractHolidays.totalHolidays || 0}} {{'days' | translate}} @@ -102,3 +110,4 @@ message="This item will be deleted" question="Are you sure you want to continue?"> + diff --git a/modules/worker/front/calendar/index.js b/modules/worker/front/calendar/index.js index 4ca0fc929..87e806cc3 100644 --- a/modules/worker/front/calendar/index.js +++ b/modules/worker/front/calendar/index.js @@ -64,17 +64,12 @@ class Controller extends Section { set worker(value) { this._worker = value; - - if (value) { + if (value && value.hasWorkCenter) { this.getIsSubordinate(); this.getActiveContract(); } } - get payedHolidays() { - return this._businessId; - } - buildYearFilter() { const now = Date.vnNew(); now.setFullYear(now.getFullYear() + 1); @@ -95,10 +90,10 @@ class Controller extends Section { } getActiveContract() { - this.$http.get(`Workers/${this.worker.id}/activeContract`).then(res => { - if (res.data) - this.businessId = res.data.businessFk; - }); + this.$http.get(`Workers/${this.worker.id}/activeContract`) + .then(res => { + if (res.data) this.businessId = res.data.businessFk; + }); } getContractHolidays() { diff --git a/modules/worker/front/calendar/index.spec.js b/modules/worker/front/calendar/index.spec.js index 586a7223d..4b78d883b 100644 --- a/modules/worker/front/calendar/index.spec.js +++ b/modules/worker/front/calendar/index.spec.js @@ -74,7 +74,7 @@ describe('Worker', () => { let yesterday = new Date(today.getTime()); yesterday.setDate(yesterday.getDate() - 1); - controller.worker = {id: 1107}; + controller.worker = {id: 1107, hasWorkCenter: true}; expect(controller.getIsSubordinate).toHaveBeenCalledWith(); expect(controller.getActiveContract).toHaveBeenCalledWith(); diff --git a/modules/worker/front/calendar/locale/es.yml b/modules/worker/front/calendar/locale/es.yml index bd75458aa..50bb4bb52 100644 --- a/modules/worker/front/calendar/locale/es.yml +++ b/modules/worker/front/calendar/locale/es.yml @@ -11,4 +11,5 @@ Choose an absence type from the right menu: Elige un tipo de ausencia desde el m To start adding absences, click an absence type from the right menu and then on the day you want to add an absence: Para empezar a añadir ausencias, haz clic en un tipo de ausencia desde el menu de la derecha y después en el día que quieres añadir la ausencia You can just add absences within the current year: Solo puedes añadir ausencias dentro del año actual Current day: Día actual -Paid holidays: Vacaciones pagadas \ No newline at end of file +Paid holidays: Vacaciones pagadas +Autonomous worker: Trabajador autónomo diff --git a/modules/worker/front/card/index.js b/modules/worker/front/card/index.js index 415b60787..e1eb97327 100644 --- a/modules/worker/front/card/index.js +++ b/modules/worker/front/card/index.js @@ -34,6 +34,10 @@ class Controller extends ModuleCard { this.$http.get(`Workers/${this.$params.id}`, {filter}) .then(res => this.worker = res.data); + this.$http.get(`Workers/${this.$params.id}/activeContract`) + .then(res => { + if (res.data) this.worker.hasWorkCenter = res.data.workCenterFk; + }); } } diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html index 044ea4038..5f0855ee6 100644 --- a/modules/worker/front/time-control/index.html +++ b/modules/worker/front/time-control/index.html @@ -4,106 +4,114 @@ filter="::$ctrl.filter" data="$ctrl.hours"> - - - - - -
{{::$ctrl.weekdayNames[$index].name}}
-
- {{::weekday.dated | date: 'dd'}} - - {{::weekday.dated | date: 'MMMM'}} - -
- - - +
+ + + + + +
{{::$ctrl.weekdayNames[$index].name}}
- {{::weekday.event.name}} + {{::weekday.dated | date: 'dd'}} + + {{::weekday.dated | date: 'MMMM'}} +
- -
-
-
- - - -
- - - - - - - {{::hour.timed | date: 'HH:mm'}} + title="{{::weekday.event.name}}" + ng-class="{invisible: !weekday.event}"> + + +
+ {{::weekday.event.name}} +
-
-
-
-
- - - - {{$ctrl.formatHours(weekday.workedHours)}} h. - - - - - - - - - -
-
+ + + + + + +
+ + + + + + + + {{::hour.timed | date: 'HH:mm'}} + +
+
+
+
+ + + + {{$ctrl.formatHours(weekday.workedHours)}} h. + + + + + + + + + + + - - - - - - - - - - + + + + + + + + + + +
+
+ Autonomous worker +
diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 85ddcedfe..90ec33293 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -151,6 +151,7 @@ class Controller extends Section { } getAbsences() { + if (!this.worker.hasWorkerCenter) return; const fullYear = this.started.getFullYear(); let params = { workerFk: this.$params.id, diff --git a/modules/worker/front/time-control/index.spec.js b/modules/worker/front/time-control/index.spec.js index 94f9d3d48..0132f50fe 100644 --- a/modules/worker/front/time-control/index.spec.js +++ b/modules/worker/front/time-control/index.spec.js @@ -16,6 +16,10 @@ describe('Component vnWorkerTimeControl', () => { $scope = $rootScope.$new(); $element = angular.element(''); controller = $componentController('vnWorkerTimeControl', {$element, $scope}); + controller.worker = { + hasWorkerCenter: true + + }; })); describe('date() setter', () => { diff --git a/modules/zone/back/locale/zone-event/en.yml b/modules/zone/back/locale/zone-event/en.yml index 2d6ef39ab..1988c1239 100644 --- a/modules/zone/back/locale/zone-event/en.yml +++ b/modules/zone/back/locale/zone-event/en.yml @@ -1,14 +1,14 @@ -name: zone event +name: event columns: id: id zoneFk: zone type: type dated: dated - started: started - ended: ended + started: starts + ended: ends weekDays: week days hour: hour travelingDays: traveling days price: price bonus: bonus - m3Max: max m3 + m3Max: max. m3 diff --git a/modules/zone/back/locale/zone-event/es.yml b/modules/zone/back/locale/zone-event/es.yml index 9bc8db9fe..5092cc933 100644 --- a/modules/zone/back/locale/zone-event/es.yml +++ b/modules/zone/back/locale/zone-event/es.yml @@ -1,11 +1,11 @@ -name: evento zona +name: evento columns: id: id zoneFk: zona type: tipo dated: fecha - started: comenzado - ended: terminado + started: empieza + ended: termina weekDays: días semana hour: hora travelingDays: días de viaje diff --git a/modules/zone/back/locale/zone-exclusion/en.yml b/modules/zone/back/locale/zone-exclusion/en.yml index 4389d8b93..6a2383b87 100644 --- a/modules/zone/back/locale/zone-exclusion/en.yml +++ b/modules/zone/back/locale/zone-exclusion/en.yml @@ -1,5 +1,5 @@ -name: zone exclusion +name: exclusion columns: id: id - dated: dated + dated: date zoneFk: zone diff --git a/modules/zone/back/locale/zone-exclusion/es.yml b/modules/zone/back/locale/zone-exclusion/es.yml index 4e59cba46..35102a670 100644 --- a/modules/zone/back/locale/zone-exclusion/es.yml +++ b/modules/zone/back/locale/zone-exclusion/es.yml @@ -1,4 +1,4 @@ -name: zone exclusion +name: exclusión columns: id: id dated: fecha diff --git a/modules/zone/back/locale/zone-included/en.yml b/modules/zone/back/locale/zone-included/en.yml index 0e44989e9..65e4faac6 100644 --- a/modules/zone/back/locale/zone-included/en.yml +++ b/modules/zone/back/locale/zone-included/en.yml @@ -1,5 +1,7 @@ -name: zone included +name: inclusion columns: id: id dated: dated zoneFk: zone + isIncluded: incluida + geoFk: localización diff --git a/modules/zone/back/locale/zone-included/es.yml b/modules/zone/back/locale/zone-included/es.yml index 30a89373a..bd48cdbe5 100644 --- a/modules/zone/back/locale/zone-included/es.yml +++ b/modules/zone/back/locale/zone-included/es.yml @@ -1,5 +1,7 @@ -name: zona incluida +name: inclusión columns: id: id dated: fecha zoneFk: zona + isIncluded: incluida + geoFk: localización diff --git a/modules/zone/back/locale/zone-warehouse/en.yml b/modules/zone/back/locale/zone-warehouse/en.yml index b9c4f7609..6caa3de1b 100644 --- a/modules/zone/back/locale/zone-warehouse/en.yml +++ b/modules/zone/back/locale/zone-warehouse/en.yml @@ -1,4 +1,4 @@ -name: zone warehouse +name: warehouse columns: id: id warehouseFk: warehouse diff --git a/modules/zone/back/locale/zone-warehouse/es.yml b/modules/zone/back/locale/zone-warehouse/es.yml index ec8dec2dd..caf0d8f1a 100644 --- a/modules/zone/back/locale/zone-warehouse/es.yml +++ b/modules/zone/back/locale/zone-warehouse/es.yml @@ -1,4 +1,4 @@ -name: almacén zona +name: almacén columns: id: id warehouseFk: almacén diff --git a/modules/zone/back/methods/agency/getAgenciesWithWarehouse.js b/modules/zone/back/methods/agency/getAgenciesWithWarehouse.js index 846ad6a3d..c8ab4f67c 100644 --- a/modules/zone/back/methods/agency/getAgenciesWithWarehouse.js +++ b/modules/zone/back/methods/agency/getAgenciesWithWarehouse.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('getAgenciesWithWarehouse', { + Self.remoteMethodCtx('getAgenciesWithWarehouse', { description: 'Returns a list of agencies that can land a shipment on a day for an address and a warehouse', accepts: [ { @@ -28,8 +28,8 @@ module.exports = Self => { } }); - Self.getAgenciesWithWarehouse = async(addressFk, landed, warehouseFk, options) => { - const myOptions = {}; + Self.getAgenciesWithWarehouse = async(ctx, addressFk, landed, warehouseFk, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/zone/back/methods/agency/landsThatDay.js b/modules/zone/back/methods/agency/landsThatDay.js index b7f13ddda..4d73e4d08 100644 --- a/modules/zone/back/methods/agency/landsThatDay.js +++ b/modules/zone/back/methods/agency/landsThatDay.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('landsThatDay', { + Self.remoteMethodCtx('landsThatDay', { description: 'Returns a list of agencies that can land a shipment on a day for an address', accepts: [ { @@ -22,8 +22,8 @@ module.exports = Self => { } }); - Self.landsThatDay = async(addressFk, landed, options) => { - const myOptions = {}; + Self.landsThatDay = async(ctx, addressFk, landed, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js b/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js index 4f79b2315..f760559cb 100644 --- a/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js +++ b/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js @@ -2,6 +2,7 @@ const app = require('vn-loopback/server/server'); describe('Agency getAgenciesWithWarehouse()', () => { const today = Date.vnNew(); + const ctx = {req: {accessToken: {userId: 9}}}; it('should return the agencies that can handle the given delivery request', async() => { const tx = await app.models.Zone.beginTransaction({}); @@ -9,7 +10,7 @@ describe('Agency getAgenciesWithWarehouse()', () => { const options = {transaction: tx}; const addressId = 101; - const agencies = await app.models.Agency.getAgenciesWithWarehouse(addressId, today, 1, options); + const agencies = await app.models.Agency.getAgenciesWithWarehouse(ctx, addressId, today, 1, options); expect(agencies.length).toEqual(3); expect(agencies[0].agencyMode).toEqual('inhouse pickup'); @@ -30,7 +31,7 @@ describe('Agency getAgenciesWithWarehouse()', () => { const options = {transaction: tx}; const addressId = 101; - const agencies = await app.models.Agency.getAgenciesWithWarehouse(addressId, null, 1, options); + const agencies = await app.models.Agency.getAgenciesWithWarehouse(ctx, addressId, null, 1, options); expect(agencies.length).toEqual(0); diff --git a/modules/zone/back/methods/agency/specs/landsThatDay.spec.js b/modules/zone/back/methods/agency/specs/landsThatDay.spec.js index 4bde37984..1ec675071 100644 --- a/modules/zone/back/methods/agency/specs/landsThatDay.spec.js +++ b/modules/zone/back/methods/agency/specs/landsThatDay.spec.js @@ -1,6 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('Agency landsThatDay()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; const today = Date.vnNew(); it('should return a list of agencies that can land a shipment on a day for an address', async() => { const tx = await models.Agency.beginTransaction({}); @@ -8,7 +9,7 @@ describe('Agency landsThatDay()', () => { try { const options = {transaction: tx}; - const agencies = await models.Agency.landsThatDay(101, today, options); + const agencies = await models.Agency.landsThatDay(ctx, 101, today, options); expect(agencies.length).toBeGreaterThanOrEqual(3); diff --git a/modules/zone/back/methods/zone/deleteZone.js b/modules/zone/back/methods/zone/deleteZone.js index e3846132b..bcfb91e3d 100644 --- a/modules/zone/back/methods/zone/deleteZone.js +++ b/modules/zone/back/methods/zone/deleteZone.js @@ -26,7 +26,7 @@ module.exports = Self => { today.setHours(0, 0, 0, 0); let tx; - const myOptions = {}; + const myOptions = {userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/zone/back/methods/zone/getEvents.js b/modules/zone/back/methods/zone/getEvents.js index a8ee8bb7b..03fb31438 100644 --- a/modules/zone/back/methods/zone/getEvents.js +++ b/modules/zone/back/methods/zone/getEvents.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.remoteMethod('getEvents', { + Self.remoteMethodCtx('getEvents', { description: 'Returns delivery days for a postcode', accepts: [ { @@ -25,8 +25,8 @@ module.exports = Self => { } }); - Self.getEvents = async(geoFk, agencyModeFk, options) => { - const myOptions = {}; + Self.getEvents = async(ctx, geoFk, agencyModeFk, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/zone/back/methods/zone/getLeaves.js b/modules/zone/back/methods/zone/getLeaves.js index ed421e339..a6db3b711 100644 --- a/modules/zone/back/methods/zone/getLeaves.js +++ b/modules/zone/back/methods/zone/getLeaves.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.remoteMethod('getLeaves', { + Self.remoteMethodCtx('getLeaves', { description: 'Returns the nodes for a zone', accepts: [ { @@ -31,8 +31,8 @@ module.exports = Self => { } }); - Self.getLeaves = async(id, parentId = null, search, options) => { - const myOptions = {}; + Self.getLeaves = async(ctx, id, parentId = null, search, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/zone/back/methods/zone/getUpcomingDeliveries.js b/modules/zone/back/methods/zone/getUpcomingDeliveries.js index 2a1c39ed6..e8b7e7636 100644 --- a/modules/zone/back/methods/zone/getUpcomingDeliveries.js +++ b/modules/zone/back/methods/zone/getUpcomingDeliveries.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('getUpcomingDeliveries', { + Self.remoteMethodCtx('getUpcomingDeliveries', { description: 'Returns the upcomings deliveries', accessType: 'READ', accepts: [], @@ -13,8 +13,8 @@ module.exports = Self => { } }); - Self.getUpcomingDeliveries = async options => { - const myOptions = {}; + Self.getUpcomingDeliveries = async(ctx, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/zone/back/methods/zone/specs/getEvents.spec.js b/modules/zone/back/methods/zone/specs/getEvents.spec.js index d1c51baff..c1dee3e0f 100644 --- a/modules/zone/back/methods/zone/specs/getEvents.spec.js +++ b/modules/zone/back/methods/zone/specs/getEvents.spec.js @@ -1,13 +1,14 @@ const models = require('vn-loopback/server/server').models; describe('zone getEvents()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should return all events for the specified geo and agency mode', async() => { const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - let result = await models.Zone.getEvents(20, 1, options); + let result = await models.Zone.getEvents(ctx, 20, 1, options); expect(result.events.length).toEqual(10); diff --git a/modules/zone/back/methods/zone/specs/getLeaves.spec.js b/modules/zone/back/methods/zone/specs/getLeaves.spec.js index db7359671..9342a0b50 100644 --- a/modules/zone/back/methods/zone/specs/getLeaves.spec.js +++ b/modules/zone/back/methods/zone/specs/getLeaves.spec.js @@ -1,13 +1,14 @@ const models = require('vn-loopback/server/server').models; describe('zone getLeaves()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should return the country and the childs containing the search value', async() => { const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - let result = await models.Zone.getLeaves(1, null, '46000', options); + let result = await models.Zone.getLeaves(ctx, 1, null, '46000', options); expect(result.length).toEqual(1); diff --git a/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js b/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js index acef079f6..fe542fbf3 100644 --- a/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js +++ b/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js @@ -1,12 +1,13 @@ const models = require('vn-loopback/server/server').models; describe('zone getUpcomingDeliveries()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should check returns data', async() => { const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - let result = await models.Zone.getUpcomingDeliveries(options); + let result = await models.Zone.getUpcomingDeliveries(ctx, options); const firstResultLines = result[0].lines; const secondResultLines = result[1].lines; diff --git a/package-lock.json b/package-lock.json index a224c4bb3..c190065b0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.22.01", + "version": "23.26.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.22.01", + "version": "23.24.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index f1b3daca3..64c374841 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.24.01", + "version": "23.28.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", diff --git a/print/core/components/report-footer/report-footer.js b/print/core/components/report-footer/report-footer.js index 077ef0bde..ed718b8dc 100755 --- a/print/core/components/report-footer/report-footer.js +++ b/print/core/components/report-footer/report-footer.js @@ -5,10 +5,9 @@ module.exports = { name: 'report-footer', async serverPrefetch() { this.company = await db.findOne(` - SELECT IFNULL(ci.footnotes, cl.footnotes) as footnotes + SELECT IFNULL(ci.footnotes, c.footnotes) footnotes FROM company c - LEFT JOIN companyL10n cl ON c.id = cl.id - LEFT JOIN companyI18n ci ON ci.companyFk = cl.id + LEFT JOIN companyI18n ci ON ci.companyFk = c.id AND ci.lang = (SELECT lang FROM account.user where id = ?) WHERE c.code = ?`, [this.recipientId, this.companyCode]); diff --git a/print/core/email.js b/print/core/email.js index 6e96f5c2e..43e92e619 100644 --- a/print/core/email.js +++ b/print/core/email.js @@ -63,12 +63,12 @@ class Email extends Component { await getAttachments(componentPath, component.attachments); if (component.components) - await getSubcomponentAttachments(component) + await getSubcomponentAttachments(component); } } } - await getSubcomponentAttachments(instance) + await getSubcomponentAttachments(instance); if (this.attachments) await getAttachments(this.path, this.attachments); diff --git a/print/core/smtp.js b/print/core/smtp.js index 61b115b5a..7ff9ca41d 100644 --- a/print/core/smtp.js +++ b/print/core/smtp.js @@ -20,14 +20,18 @@ module.exports = { options.to = config.app.senderEmail; } + let res; let error; - return this.transporter.sendMail(options).catch(err => { + try { + res = await this.transporter.sendMail(options); + } catch (err) { error = err; - throw err; - }).finally(async() => { + } finally { await this.mailLog(options, error); - }); + } + + return res; }, async mailLog(options, error) { @@ -46,14 +50,21 @@ module.exports = { const fileNames = attachments.join(',\n'); await db.rawSql(` - INSERT INTO vn.mail (receiver, replyTo, sent, subject, body, attachment, status) - VALUES (?, ?, 1, ?, ?, ?, ?)`, [ + INSERT INTO vn.mail + SET receiver = ?, + replyTo = ?, + sent = ?, + subject = ?, + body = ?, + attachment = ?, + status = ?`, [ options.to, options.replyTo, + error ? 2 : 1, options.subject, options.text || options.html, fileNames, - error && error.message || 'Sent' + error && error.message || 'OK' ]); } diff --git a/print/templates/email/entry-update-comission/assets/css/import.js b/print/templates/email/entry-update-comission/assets/css/import.js new file mode 100644 index 000000000..7360587f7 --- /dev/null +++ b/print/templates/email/entry-update-comission/assets/css/import.js @@ -0,0 +1,13 @@ +const Stylesheet = require(`vn-print/core/stylesheet`); + +const path = require('path'); +const vnPrintPath = path.resolve('print'); + +module.exports = new Stylesheet([ + `${vnPrintPath}/common/css/spacing.css`, + `${vnPrintPath}/common/css/misc.css`, + `${vnPrintPath}/common/css/layout.css`, + `${vnPrintPath}/common/css/email.css`, + `${__dirname}/style.css`]) + .mergeStyles(); + diff --git a/print/templates/email/entry-update-comission/assets/css/style.css b/print/templates/email/entry-update-comission/assets/css/style.css new file mode 100644 index 000000000..5db85befa --- /dev/null +++ b/print/templates/email/entry-update-comission/assets/css/style.css @@ -0,0 +1,5 @@ +.external-link { + border: 2px dashed #8dba25; + border-radius: 3px; + text-align: center +} \ No newline at end of file diff --git a/print/templates/email/entry-update-comission/entry-update-comission.html b/print/templates/email/entry-update-comission/entry-update-comission.html new file mode 100644 index 000000000..d3ca1202a --- /dev/null +++ b/print/templates/email/entry-update-comission/entry-update-comission.html @@ -0,0 +1,10 @@ + +
+
+

+ {{$t('dear')}} +

+

+
+
+
diff --git a/print/templates/email/entry-update-comission/entry-update-comission.js b/print/templates/email/entry-update-comission/entry-update-comission.js new file mode 100755 index 000000000..8afe10ea0 --- /dev/null +++ b/print/templates/email/entry-update-comission/entry-update-comission.js @@ -0,0 +1,19 @@ +const Component = require(`vn-print/core/component`); +const emailBody = new Component('email-body'); + +module.exports = { + name: 'entry-update-comission', + components: { + 'email-body': emailBody.build(), + }, + props: { + currencyName: { + type: String, + required: true + }, + referenceCurrent: { + type: Number, + required: true + } + } +}; diff --git a/print/templates/email/entry-update-comission/locale/es.yml b/print/templates/email/entry-update-comission/locale/es.yml new file mode 100644 index 000000000..de58be3e7 --- /dev/null +++ b/print/templates/email/entry-update-comission/locale/es.yml @@ -0,0 +1,4 @@ +subject: Actualización tipo de cambio en entradas +title: Actualización tipo de cambio en entradas +dear: Hola, +body: 'El tipo de cambio para las ENTRADAS/COMPRAS en {0} se ha actualizado a partir de hoy en: {1}' \ No newline at end of file diff --git a/print/templates/email/modified-entry/assets/css/import.js b/print/templates/email/modified-entry/assets/css/import.js new file mode 100644 index 000000000..4b4bb7086 --- /dev/null +++ b/print/templates/email/modified-entry/assets/css/import.js @@ -0,0 +1,11 @@ +const Stylesheet = require(`vn-print/core/stylesheet`); + +const path = require('path'); +const vnPrintPath = path.resolve('print'); + +module.exports = new Stylesheet([ + `${vnPrintPath}/common/css/spacing.css`, + `${vnPrintPath}/common/css/misc.css`, + `${vnPrintPath}/common/css/layout.css`, + `${vnPrintPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/modified-entry/locale/en.yml b/print/templates/email/modified-entry/locale/en.yml new file mode 100644 index 000000000..7bdfa15ff --- /dev/null +++ b/print/templates/email/modified-entry/locale/en.yml @@ -0,0 +1,3 @@ +subject: Modified entry +title: Modified entry +description: From Warehouse the following packaging entry has been created/modified diff --git a/print/templates/email/modified-entry/locale/es.yml b/print/templates/email/modified-entry/locale/es.yml new file mode 100644 index 000000000..5a00307f9 --- /dev/null +++ b/print/templates/email/modified-entry/locale/es.yml @@ -0,0 +1,3 @@ +subject: Entrada modificada +title: Entrada modificada +description: Desde Almacén se ha creado/modificado la siguiente entrada de embalajes diff --git a/print/templates/email/modified-entry/modified-entry.html b/print/templates/email/modified-entry/modified-entry.html new file mode 100644 index 000000000..869d019a4 --- /dev/null +++ b/print/templates/email/modified-entry/modified-entry.html @@ -0,0 +1,11 @@ + +
+ diff --git a/print/templates/email/modified-entry/modified-entry.js b/print/templates/email/modified-entry/modified-entry.js new file mode 100755 index 000000000..35474a12f --- /dev/null +++ b/print/templates/email/modified-entry/modified-entry.js @@ -0,0 +1,16 @@ +const Component = require(`vn-print/core/component`); +const emailBody = new Component('email-body'); + +module.exports = { + name: 'modified-entry', + components: { + 'email-body': emailBody.build(), + }, + props: { + url: { + type: String, + required: true + } + } +}; + diff --git a/print/templates/reports/invoice/assets/css/style.css b/print/templates/reports/invoice/assets/css/style.css index 9fda2a613..d4526ce56 100644 --- a/print/templates/reports/invoice/assets/css/style.css +++ b/print/templates/reports/invoice/assets/css/style.css @@ -16,6 +16,10 @@ h2 { font-size: 22px } +.column-oriented td, +.column-oriented th { + padding: 6px +} #nickname h2 { max-width: 400px; @@ -39,4 +43,4 @@ h2 { .phytosanitary-info { margin-top: 10px -} \ No newline at end of file +} diff --git a/print/templates/reports/invoice/invoice.html b/print/templates/reports/invoice/invoice.html index 727621b2c..45b6c3934 100644 --- a/print/templates/reports/invoice/invoice.html +++ b/print/templates/reports/invoice/invoice.html @@ -62,7 +62,7 @@
-
+

{{$t('deliveryNote')}}

@@ -106,13 +106,6 @@ {{sale.vatType}} {{saleImport(sale) | currency('EUR', $i18n.locale)}} - - - {{sale.tag5}} {{sale.value5}} - {{sale.tag6}} {{sale.value6}} - {{sale.tag7}} {{sale.value7}} - - @@ -242,7 +235,7 @@
-
+
{{$t('observations')}}
@@ -267,9 +260,7 @@ v-bind:left-text="$t('invoiceRef', [invoice.ref])" v-bind:center-text="client.socialName" v-bind:recipient-id="client.id" - v-bind="$props" - - > + v-bind="$props"> diff --git a/webpack.config.js b/webpack.config.js index 7a94b993d..a102b838e 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -9,7 +9,7 @@ let mode = env == 'development' ? env : 'production'; let baseConfig = { entry: {salix: 'salix'}, - mode: mode, + mode, output: { path: path.join(__dirname, 'dist'), publicPath: '/'