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/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/loopback/common/models/vn-model.js b/loopback/common/models/vn-model.js index 37328247b..695834849 100644 --- a/loopback/common/models/vn-model.js +++ b/loopback/common/models/vn-model.js @@ -196,8 +196,48 @@ 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; + const opts = Object.assign({}, options); + + try { + if (userId) { + conn = await new Promise((resolve, reject) => { + connector.client.getConnection(function(err, conn) { + if (err) + reject(err); + else + resolve(conn); + }); + }); + + const opts = Object.assign({}, options); + if (!opts.transaction) { + opts.transaction = { + connection: conn, + connector + }; + } + + await connector.executeP( + 'CALL account.myUser_loginWithName((SELECT name FROM account.user WHERE id = ?))', + [userId], opts + ); + } + + res = await connector.executeP(query, params, opts); + + if (userId) { + await connector.executeP('CALL account.myUser_logout()', null, opts); + } + } finally { + if (conn) conn.release(); + } + + return res; }, /* diff --git a/modules/account/back/methods/account/change-password.js b/modules/account/back/methods/account/change-password.js index 549508ffa..bace3e628 100644 --- a/modules/account/back/methods/account/change-password.js +++ b/modules/account/back/methods/account/change-password.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.remoteMethod('changePassword', { + Self.remoteMethodCtx('changePassword', { description: 'Changes the user password', accessType: 'WRITE', accepts: [ @@ -27,9 +27,9 @@ module.exports = Self => { } }); - Self.changePassword = async function(id, oldPassword, newPassword) { + Self.changePassword = async function(ctx, id, oldPassword, newPassword) { await Self.rawSql(`CALL account.user_changePassword(?, ?, ?)`, - [id, oldPassword, newPassword]); + [id, oldPassword, newPassword], {userId: ctx.req.accessToken.userId}); await Self.app.models.Account.syncById(id, newPassword); }; }; diff --git a/modules/account/back/methods/account/set-password.js b/modules/account/back/methods/account/set-password.js index b4204d103..81a310e45 100644 --- a/modules/account/back/methods/account/set-password.js +++ b/modules/account/back/methods/account/set-password.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('setPassword', { + Self.remoteMethodCtx('setPassword', { description: 'Sets the user password', accessType: 'WRITE', accepts: [ @@ -21,9 +21,9 @@ module.exports = Self => { } }); - Self.setPassword = async function(id, newPassword) { + Self.setPassword = async function(ctx, id, newPassword) { await Self.rawSql(`CALL account.user_setPassword(?, ?)`, - [id, newPassword]); + [id, newPassword], {userId: ctx.req.accessToken.userId}); await Self.app.models.Account.syncById(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..0274cbded 100644 --- a/modules/account/back/methods/account/specs/change-password.spec.js +++ b/modules/account/back/methods/account/specs/change-password.spec.js @@ -2,8 +2,9 @@ const {models} = require('vn-loopback/server/server'); describe('account changePassword()', () => { it('should throw an error when old password is wrong', async() => { + const ctx = {req: {accessToken: {userId: 9}}}; let err; - await models.Account.changePassword(1, 'wrongPassword', 'nightmare.9999') + await models.Account.changePassword(ctx, 1, 'wrongPassword', 'nightmare.9999') .catch(error => err = error.sqlMessage); expect(err).toBeDefined(); diff --git a/modules/account/back/methods/account/specs/set-password.spec.js b/modules/account/back/methods/account/specs/set-password.spec.js index 5de2a7bad..f54fba36f 100644 --- a/modules/account/back/methods/account/specs/set-password.spec.js +++ b/modules/account/back/methods/account/specs/set-password.spec.js @@ -1,14 +1,15 @@ const {models} = require('vn-loopback/server/server'); describe('Account setPassword()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should throw an error when password does not meet requirements', async() => { - let req = models.Account.setPassword(1, 'insecurePass'); + let req = models.Account.setPassword(ctx, 1, 'insecurePass'); await expectAsync(req).toBeRejected(); }); it('should update password when it passes requirements', async() => { - let req = models.Account.setPassword(1, 'Very$ecurePa22.'); + let req = models.Account.setPassword(ctx, 1, 'Very$ecurePa22.'); await expectAsync(req).toBeResolved(); }); 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/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/setPassword.js b/modules/client/back/methods/client/setPassword.js index e5b8949e7..fbed2828d 100644 --- a/modules/client/back/methods/client/setPassword.js +++ b/modules/client/back/methods/client/setPassword.js @@ -1,6 +1,6 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('setPassword', { + Self.remoteMethodCtx('setPassword', { description: 'Sets the password of a non-worker client', accepts: [ { @@ -21,14 +21,14 @@ module.exports = Self => { } }); - Self.setPassword = async function(id, newPassword) { + Self.setPassword = async function(ctx, id, newPassword) { const models = Self.app.models; const isClient = await models.Client.findById(id); const isAccount = await models.Account.findById(id); if (isClient && !isAccount) - await models.Account.setPassword(id, newPassword); + await models.Account.setPassword(ctx, id, newPassword); else throw new UserError(`Modifiable password only via recovery or by an administrator`); }; 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/setPassword.spec.js b/modules/client/back/methods/client/specs/setPassword.spec.js index 590172a02..c004b0372 100644 --- a/modules/client/back/methods/client/specs/setPassword.spec.js +++ b/modules/client/back/methods/client/specs/setPassword.spec.js @@ -1,11 +1,12 @@ const models = require('vn-loopback/server/server').models; describe('Client setPassword', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should throw an error the setPassword target is not just a client but a worker', async() => { let error; try { - await models.Client.setPassword(1, 't0pl3v3l.p455w0rd!'); + await models.Client.setPassword(ctx, 1, 't0pl3v3l.p455w0rd!'); } catch (e) { error = e; } @@ -17,7 +18,7 @@ describe('Client setPassword', () => { let error; try { - await models.Client.setPassword(1101, 't0pl3v3l.p455w0rd!'); + await models.Client.setPassword(ctx, 1101, 't0pl3v3l.p455w0rd!'); } catch (e) { error = e; } 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/confirm.js b/modules/client/back/methods/tpv-transaction/confirm.js index 41229a1fd..4faa21bb5 100644 --- a/modules/client/back/methods/tpv-transaction/confirm.js +++ b/modules/client/back/methods/tpv-transaction/confirm.js @@ -2,7 +2,7 @@ const UserError = require('vn-loopback/util/user-error'); const base64url = require('base64url'); module.exports = Self => { - Self.remoteMethod('confirm', { + Self.remoteMethodCtx('confirm', { description: 'Confirms electronic payment transaction', accessType: 'WRITE', accepts: [ @@ -30,7 +30,7 @@ module.exports = Self => { } }); - Self.confirm = async(signatureVersion, merchantParameters, signature) => { + Self.confirm = async(ctx, signatureVersion, merchantParameters, signature) => { const $ = Self.app.models; let transaction; @@ -83,7 +83,7 @@ module.exports = Self => { params['Ds_Currency'], params['Ds_Response'], params['Ds_ErrorCode'] - ]); + ], {userId: ctx.req.accessToken.userId}); return true; } catch (err) { 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/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/invoiceIn/back/methods/invoice-in/toBook.js b/modules/invoiceIn/back/methods/invoice-in/toBook.js index 588d53f1f..877552f41 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); 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/invoiceClient.js b/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js index c8f8a6778..421cbaea1 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js +++ b/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js @@ -50,7 +50,7 @@ module.exports = Self => { Self.invoiceClient = 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/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/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/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/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..5fdab29b3 100644 --- a/modules/order/back/methods/order/confirm.js +++ b/modules/order/back/methods/order/confirm.js @@ -23,7 +23,7 @@ module.exports = Self => { 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/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/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-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..7cc300547 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') 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/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..48fe78e08 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/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/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;