fixes #5595 Al modificar tablas dentro de procedimientos los logs creados no añaden el usuario loggeado #1499

Merged
alexandre merged 11 commits from 5595-modify-loggable-tables-in-procs into dev 2023-06-12 05:37:57 +00:00
92 changed files with 455 additions and 384 deletions

View File

@ -30,11 +30,11 @@ module.exports = Self => {
Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => { Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => {
let query = ''; let query = '';
const userId = ctx.req.accessToken.userId;
if (!collectionFk) { if (!collectionFk) {
const userId = ctx.req.accessToken.userId;
query = `CALL vn.collectionTrain_newBeta(?,?,?)`; 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) if (result.length == 0)
throw new Error(`No collections for today`); throw new Error(`No collections for today`);
@ -42,16 +42,16 @@ module.exports = Self => {
} }
query = `CALL vn.collectionTicket_get(?)`; 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(?)`; 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(?)`; 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(?,?)`; query = `CALL vn.collectionSticker_print(?,?)`;
await Self.rawSql(query, [collectionFk, sectorFk]); await Self.rawSql(query, [collectionFk, sectorFk], {userId});
return makeCollection(tickets, sales, placements, collectionFk); return makeCollection(tickets, sales, placements, collectionFk);
}; };

View File

@ -3,237 +3,237 @@ const path = require('path');
const fs = require('fs-extra'); const fs = require('fs-extra');
module.exports = Self => { module.exports = Self => {
Self.remoteMethodCtx('updateData', { Self.remoteMethodCtx('updateData', {
description: 'Updates schema data from external provider', description: 'Updates schema data from external provider',
accessType: 'WRITE', accessType: 'WRITE',
returns: { returns: {
type: 'object', type: 'object',
root: true root: true
}, },
http: { http: {
path: `/updateData`, path: `/updateData`,
verb: 'POST' verb: 'POST'
} }
}); });
Self.updateData = async() => { Self.updateData = async ctx => {
const models = Self.app.models; const models = Self.app.models;
// Get files checksum // Get files checksum
const tx = await Self.beginTransaction({}); const tx = await Self.beginTransaction({});
try { try {
const options = {transaction: tx}; const options = {transaction: tx, userId: ctx.req.accessToken.userId};
const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileConfig', null, options); const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileConfig', null, options);
const updatableFiles = []; const updatableFiles = [];
for (const file of files) { for (const file of files) {
const fileChecksum = await getChecksum(file); const fileChecksum = await getChecksum(file);
if (file.checksum != fileChecksum) { if (file.checksum != fileChecksum) {
updatableFiles.push({ updatableFiles.push({
name: file.name, name: file.name,
checksum: fileChecksum checksum: fileChecksum
}); });
} else } else
console.debug(`File already updated, skipping...`); console.debug(`File already updated, skipping...`);
} }
if (updatableFiles.length === 0) if (updatableFiles.length === 0)
return false; return false;
// Download files // Download files
const container = await models.TempContainer.container('edi'); const container = await models.TempContainer.container('edi');
const tempPath = path.join(container.client.root, container.name); const tempPath = path.join(container.client.root, container.name);
let remoteFile; let remoteFile;
let tempDir; let tempDir;
let tempFile; 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 SELECT fileName, toTable, file
FROM edi.tableConfig FROM edi.tableConfig
WHERE file IN (?)`, [fileNames], options); WHERE file IN (?)`, [fileNames], options);
for (const table of tables) { for (const table of tables) {
const fileName = table.file; const fileName = table.file;
remoteFile = `codes/${fileName}.ZIP`; remoteFile = `codes/${fileName}.ZIP`;
tempDir = `${tempPath}/${fileName}`; tempDir = `${tempPath}/${fileName}`;
tempFile = `${tempPath}/${fileName}.zip`; tempFile = `${tempPath}/${fileName}.zip`;
try { try {
await fs.readFile(tempFile); await fs.readFile(tempFile);
} catch (error) { } catch (error) {
if (error.code === 'ENOENT') { if (error.code === 'ENOENT') {
console.debug(`Downloading file ${fileName}...`); console.debug(`Downloading file ${fileName}...`);
const downloadOutput = await downloadFile(remoteFile, tempFile); const downloadOutput = await downloadFile(remoteFile, tempFile);
if (downloadOutput.error) if (downloadOutput.error)
continue; continue;
} }
} }
await extractFile(fileName, tempFile, tempDir); await extractFile(fileName, tempFile, tempDir);
console.debug(`Updating table ${table.toTable}...`); console.debug(`Updating table ${table.toTable}...`);
await dumpData(tempDir, table, options); await dumpData(tempDir, table, options);
} }
// Update files checksum // Update files checksum
for (const file of updatableFiles) { for (const file of updatableFiles) {
console.log(`Updating file ${file.name} checksum...`); console.log(`Updating file ${file.name} checksum...`);
await Self.rawSql(` await Self.rawSql(`
UPDATE edi.fileConfig UPDATE edi.fileConfig
SET checksum = ? SET checksum = ?
WHERE name = ?`, WHERE name = ?`,
[file.checksum, file.name], options); [file.checksum, file.name], options);
} }
await tx.commit(); await tx.commit();
// Clean files // Clean files
try { try {
console.debug(`Cleaning files...`); console.debug(`Cleaning files...`);
await fs.remove(tempPath); await fs.remove(tempPath);
} catch (error) { } catch (error) {
if (error.code !== 'ENOENT') if (error.code !== 'ENOENT')
throw e; throw e;
} }
return true; return true;
} catch (error) { } catch (error) {
await tx.rollback(); await tx.rollback();
throw error; throw error;
} }
}; };
let ftpClient; let ftpClient;
async function getFtpClient() { async function getFtpClient() {
if (!ftpClient) { if (!ftpClient) {
const [ftpConfig] = await Self.rawSql('SELECT host, user, password FROM edi.ftpConfig'); const [ftpConfig] = await Self.rawSql('SELECT host, user, password FROM edi.ftpConfig');
console.debug(`Openning FTP connection to ${ftpConfig.host}...\n`); console.debug(`Openning FTP connection to ${ftpConfig.host}...\n`);
const FtpClient = require('ftps'); const FtpClient = require('ftps');
ftpClient = new FtpClient({ ftpClient = new FtpClient({
host: ftpConfig.host, host: ftpConfig.host,
username: ftpConfig.user, username: ftpConfig.user,
password: ftpConfig.password, password: ftpConfig.password,
procotol: 'ftp', procotol: 'ftp',
additionalLftpCommands: 'set ssl:verify-certificate no' additionalLftpCommands: 'set ssl:verify-certificate no'
}); });
} }
return ftpClient; return ftpClient;
} }
async function getChecksum(file) { async function getChecksum(file) {
const ftpClient = await getFtpClient(); const ftpClient = await getFtpClient();
console.debug(`Checking checksum for file ${file.name}...`); 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) => { const response = await new Promise((resolve, reject) => {
ftpClient.exec((err, response) => { ftpClient.exec((err, response) => {
if (err || response.error) { if (err || response.error) {
console.debug(`Error downloading checksum file... ${response.error}`); console.debug(`Error downloading checksum file... ${response.error}`);
return reject(err); return reject(err);
} }
resolve(response); resolve(response);
}); });
}); });
if (response && response.data) { if (response && response.data) {
const fileContents = response.data; const fileContents = response.data;
const rows = fileContents.split('\n'); const rows = fileContents.split('\n');
const row = rows[4]; const row = rows[4];
const columns = row.split(/\s+/); const columns = row.split(/\s+/);
let fileChecksum; let fileChecksum;
if (file.keyValue) if (file.keyValue)
fileChecksum = columns[1]; fileChecksum = columns[1];
if (!file.keyValue) if (!file.keyValue)
fileChecksum = columns[0]; fileChecksum = columns[0];
return fileChecksum; return fileChecksum;
} }
} }
async function downloadFile(remoteFile, tempFile) { async function downloadFile(remoteFile, tempFile) {
const ftpClient = await getFtpClient(); const ftpClient = await getFtpClient();
ftpClient.get(remoteFile, tempFile); ftpClient.get(remoteFile, tempFile);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
ftpClient.exec((err, response) => { ftpClient.exec((err, response) => {
if (err || response.error) { if (err || response.error) {
console.debug(`Error downloading file... ${response.error}`); console.debug(`Error downloading file... ${response.error}`);
return reject(err); return reject(err);
} }
resolve(response); resolve(response);
}); });
}); });
} }
async function extractFile(fileName, tempFile, tempDir) { async function extractFile(fileName, tempFile, tempDir) {
const JSZip = require('jszip'); const JSZip = require('jszip');
try { try {
await fs.mkdir(tempDir); await fs.mkdir(tempDir);
console.debug(`Extracting file ${fileName}...`); console.debug(`Extracting file ${fileName}...`);
} catch (error) { } catch (error) {
if (error.code !== 'EEXIST') if (error.code !== 'EEXIST')
throw e; throw e;
} }
const fileStream = await fs.readFile(tempFile); const fileStream = await fs.readFile(tempFile);
if (fileStream) { if (fileStream) {
const zip = new JSZip(); const zip = new JSZip();
const zipContents = await zip.loadAsync(fileStream); 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) { for (const fileName of fileNames) {
const fileContent = await zip.file(fileName).async('nodebuffer'); const fileContent = await zip.file(fileName).async('nodebuffer');
const dest = path.join(tempDir, fileName); const dest = path.join(tempDir, fileName);
await fs.writeFile(dest, fileContent); await fs.writeFile(dest, fileContent);
} }
} }
} }
async function dumpData(tempDir, table, options) { async function dumpData(tempDir, table, options) {
const toTable = table.toTable; const toTable = table.toTable;
const baseName = table.fileName; const baseName = table.fileName;
console.log(`Emptying table ${toTable}...`); console.log(`Emptying table ${toTable}...`);
const tableName = `edi.${toTable}`; const tableName = `edi.${toTable}`;
await Self.rawSql(`DELETE FROM ??`, [tableName]); await Self.rawSql(`DELETE FROM ??`, [tableName]);
const dirFiles = await fs.readdir(tempDir); const dirFiles = await fs.readdir(tempDir);
const files = dirFiles.filter(file => file.startsWith(baseName)); const files = dirFiles.filter(file => file.startsWith(baseName));
for (const file of files) { for (const file of files) {
console.log(`Dumping data from file ${file}...`); console.log(`Dumping data from file ${file}...`);
const templatePath = path.join(__dirname, `./sql/${toTable}.sql`); const templatePath = path.join(__dirname, `./sql/${toTable}.sql`);
const sqlTemplate = await fs.readFile(templatePath, 'utf8'); const sqlTemplate = await fs.readFile(templatePath, 'utf8');
const filePath = path.join(tempDir, file); const filePath = path.join(tempDir, file);
await Self.rawSql(sqlTemplate, [filePath], options); await Self.rawSql(sqlTemplate, [filePath], options);
await Self.rawSql(` await Self.rawSql(`
UPDATE edi.tableConfig UPDATE edi.tableConfig
SET updated = ? SET updated = ?
WHERE fileName = ? WHERE fileName = ?
`, [Date.vnNew(), baseName], options); `, [Date.vnNew(), baseName], options);
} }
console.log(`Updated table ${toTable}\n`); console.log(`Updated table ${toTable}\n`);
} }
}; };

View File

@ -196,8 +196,48 @@ module.exports = function(Self) {
/* /*
* Shortcut to VnMySQL.executeP() * Shortcut to VnMySQL.executeP()
*/ */
rawSql(query, params, options, cb) { async rawSql(query, params, options) {
return this.dataSource.connector.executeP(query, params, options, cb); 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;
}, },
/* /*

View File

@ -1,6 +1,6 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('changePassword', { Self.remoteMethodCtx('changePassword', {
description: 'Changes the user password', description: 'Changes the user password',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [ 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(?, ?, ?)`, 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); await Self.app.models.Account.syncById(id, newPassword);
}; };
}; };

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('setPassword', { Self.remoteMethodCtx('setPassword', {
description: 'Sets the user password', description: 'Sets the user password',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [ 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(?, ?)`, await Self.rawSql(`CALL account.user_setPassword(?, ?)`,
[id, newPassword]); [id, newPassword], {userId: ctx.req.accessToken.userId});
await Self.app.models.Account.syncById(id, newPassword); await Self.app.models.Account.syncById(id, newPassword);
}; };
}; };

View File

@ -2,8 +2,9 @@ const {models} = require('vn-loopback/server/server');
describe('account changePassword()', () => { describe('account changePassword()', () => {
it('should throw an error when old password is wrong', async() => { it('should throw an error when old password is wrong', async() => {
const ctx = {req: {accessToken: {userId: 9}}};
let err; let err;
await models.Account.changePassword(1, 'wrongPassword', 'nightmare.9999') await models.Account.changePassword(ctx, 1, 'wrongPassword', 'nightmare.9999')
.catch(error => err = error.sqlMessage); .catch(error => err = error.sqlMessage);
expect(err).toBeDefined(); expect(err).toBeDefined();

View File

@ -1,14 +1,15 @@
const {models} = require('vn-loopback/server/server'); const {models} = require('vn-loopback/server/server');
describe('Account setPassword()', () => { describe('Account setPassword()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
it('should throw an error when password does not meet requirements', async() => { 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(); await expectAsync(req).toBeRejected();
}); });
it('should update password when it passes requirements', async() => { 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(); await expectAsync(req).toBeResolved();
}); });

View File

@ -63,7 +63,7 @@ module.exports = Self => {
}; };
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -23,7 +23,7 @@ module.exports = Self => {
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,7 +1,7 @@
const {Email} = require('vn-print'); const {Email} = require('vn-print');
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('consumptionSendQueued', { Self.remoteMethodCtx('consumptionSendQueued', {
description: 'Send all queued invoices', description: 'Send all queued invoices',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [], accepts: [],
@ -15,7 +15,7 @@ module.exports = Self => {
} }
}); });
Self.consumptionSendQueued = async() => { Self.consumptionSendQueued = async ctx => {
const queues = await Self.rawSql(` const queues = await Self.rawSql(`
SELECT SELECT
id, id,
@ -68,7 +68,7 @@ module.exports = Self => {
SET status = 'printed', SET status = 'printed',
printed = ? printed = ?
WHERE id = ?`, WHERE id = ?`,
[Date.vnNew(), queue.id]); [Date.vnNew(), queue.id], {userId: ctx.req.accessToken.userId});
} catch (error) { } catch (error) {
await Self.rawSql(` await Self.rawSql(`
UPDATE clientConsumptionQueue UPDATE clientConsumptionQueue

View File

@ -55,7 +55,7 @@ module.exports = function(Self) {
date.setHours(0, 0, 0, 0); date.setHours(0, 0, 0, 0);
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -72,7 +72,7 @@ module.exports = Self => {
Self.filter = async(ctx, filter, options) => { Self.filter = async(ctx, filter, options) => {
const conn = Self.dataSource.connector; const conn = Self.dataSource.connector;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
const postalCode = []; const postalCode = [];
const args = ctx.args; const args = ctx.args;
@ -120,7 +120,7 @@ module.exports = Self => {
const stmts = []; const stmts = [];
const stmt = new ParameterizedSQL( const stmt = new ParameterizedSQL(
`SELECT `SELECT
DISTINCT c.id, DISTINCT c.id,
c.name, c.name,
c.fi, c.fi,

View File

@ -1,5 +1,5 @@
module.exports = function(Self) { module.exports = function(Self) {
Self.remoteMethod('getCard', { Self.remoteMethodCtx('getCard', {
description: 'Get client basic data and debt', description: 'Get client basic data and debt',
accepts: { accepts: {
arg: 'id', arg: 'id',
@ -18,8 +18,8 @@ module.exports = function(Self) {
} }
}); });
Self.getCard = async(id, options) => { Self.getCard = async(ctx, id, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('getDebt', { Self.remoteMethodCtx('getDebt', {
description: 'Returns the boolean debt of a client', description: 'Returns the boolean debt of a client',
accessType: 'READ', accessType: 'READ',
accepts: [{ accepts: [{
@ -19,8 +19,8 @@ module.exports = Self => {
} }
}); });
Self.getDebt = async(clientFk, options) => { Self.getDebt = async(ctx, clientFk, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,6 +1,6 @@
const UserError = require('vn-loopback/util/user-error'); const UserError = require('vn-loopback/util/user-error');
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('setPassword', { Self.remoteMethodCtx('setPassword', {
description: 'Sets the password of a non-worker client', description: 'Sets the password of a non-worker client',
accepts: [ 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 models = Self.app.models;
const isClient = await models.Client.findById(id); const isClient = await models.Client.findById(id);
const isAccount = await models.Account.findById(id); const isAccount = await models.Account.findById(id);
if (isClient && !isAccount) if (isClient && !isAccount)
await models.Account.setPassword(id, newPassword); await models.Account.setPassword(ctx, id, newPassword);
else else
throw new UserError(`Modifiable password only via recovery or by an administrator`); throw new UserError(`Modifiable password only via recovery or by an administrator`);
}; };

View File

@ -5,10 +5,11 @@ describe('Client getCard()', () => {
const tx = await models.Client.beginTransaction({}); const tx = await models.Client.beginTransaction({});
try { try {
const ctx = {req: {accessToken: {userId: 9}}};
const options = {transaction: tx}; const options = {transaction: tx};
const id = 1101; 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.id).toEqual(id);
expect(result.name).toEqual('Bruce Wayne'); expect(result.name).toEqual('Bruce Wayne');

View File

@ -3,11 +3,12 @@ const models = require('vn-loopback/server/server').models;
describe('client getDebt()', () => { describe('client getDebt()', () => {
it('should return the client debt', async() => { it('should return the client debt', async() => {
const tx = await models.Client.beginTransaction({}); const tx = await models.Client.beginTransaction({});
const ctx = {req: {accessToken: {userId: 9}}};
try { try {
const options = {transaction: tx}; 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)); expect(result.debt).toEqual(jasmine.any(Number));

View File

@ -1,11 +1,12 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('Client setPassword', () => { 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() => { it('should throw an error the setPassword target is not just a client but a worker', async() => {
let error; let error;
try { try {
await models.Client.setPassword(1, 't0pl3v3l.p455w0rd!'); await models.Client.setPassword(ctx, 1, 't0pl3v3l.p455w0rd!');
} catch (e) { } catch (e) {
error = e; error = e;
} }
@ -17,7 +18,7 @@ describe('Client setPassword', () => {
let error; let error;
try { try {
await models.Client.setPassword(1101, 't0pl3v3l.p455w0rd!'); await models.Client.setPassword(ctx, 1101, 't0pl3v3l.p455w0rd!');
} catch (e) { } catch (e) {
error = e; error = e;
} }

View File

@ -1,6 +1,7 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('client summary()', () => { describe('client summary()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
it('should return a summary object containing data', async() => { it('should return a summary object containing data', async() => {
const clientId = 1101; const clientId = 1101;
const tx = await models.Client.beginTransaction({}); const tx = await models.Client.beginTransaction({});
@ -8,7 +9,7 @@ describe('client summary()', () => {
try { try {
const options = {transaction: tx}; 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.id).toEqual(clientId);
expect(result.name).toEqual('Bruce Wayne'); expect(result.name).toEqual('Bruce Wayne');
@ -27,7 +28,7 @@ describe('client summary()', () => {
try { try {
const options = {transaction: tx}; 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); expect(result.mana.mana).toEqual(0.34);
@ -45,7 +46,7 @@ describe('client summary()', () => {
try { try {
const options = {transaction: tx}; 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)); expect(result.debt.debt).toEqual(jasmine.any(Number));
@ -63,7 +64,7 @@ describe('client summary()', () => {
try { try {
const options = {transaction: tx}; 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); expect(result.averageInvoiced.invoiced).toEqual(1500);
@ -81,7 +82,7 @@ describe('client summary()', () => {
try { try {
const options = {transaction: tx}; 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); expect(result.totalGreuge).toEqual(203.71);
@ -99,7 +100,7 @@ describe('client summary()', () => {
try { try {
const options = {transaction: tx}; 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); expect(result.recovery).toEqual(null);
@ -117,7 +118,7 @@ describe('client summary()', () => {
try { try {
const options = {transaction: tx}; 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); expect(result.recovery.id).toEqual(3);
await tx.rollback(); await tx.rollback();

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('summary', { Self.remoteMethodCtx('summary', {
description: 'Returns a client summary', description: 'Returns a client summary',
accessType: 'READ', accessType: 'READ',
accepts: [{ 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 models = Self.app.models;
const myOptions = {}; const myOptions = {};
@ -28,7 +28,7 @@ module.exports = Self => {
const summaryObj = await getSummary(models.Client, clientFk, myOptions); const summaryObj = await getSummary(models.Client, clientFk, myOptions);
summaryObj.mana = await models.Client.getMana(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.averageInvoiced = await models.Client.getAverageInvoiced(clientFk, myOptions);
summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk, myOptions); summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk, myOptions);
summaryObj.recovery = await getRecoveries(models.Recovery, clientFk, myOptions); summaryObj.recovery = await getRecoveries(models.Recovery, clientFk, myOptions);

View File

@ -2,7 +2,7 @@ const UserError = require('vn-loopback/util/user-error');
const base64url = require('base64url'); const base64url = require('base64url');
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('confirm', { Self.remoteMethodCtx('confirm', {
description: 'Confirms electronic payment transaction', description: 'Confirms electronic payment transaction',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [ 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; const $ = Self.app.models;
let transaction; let transaction;
@ -83,7 +83,7 @@ module.exports = Self => {
params['Ds_Currency'], params['Ds_Currency'],
params['Ds_Response'], params['Ds_Response'],
params['Ds_ErrorCode'] params['Ds_ErrorCode']
]); ], {userId: ctx.req.accessToken.userId});
return true; return true;
} catch (err) { } catch (err) {

View File

@ -34,6 +34,6 @@ module.exports = Self => {
'CALL hedera.tpvTransaction_end(?, ?)', [ 'CALL hedera.tpvTransaction_end(?, ?)', [
orderId, orderId,
status status
]); ], {userId});
}; };
}; };

View File

@ -40,7 +40,7 @@ module.exports = Self => {
amount, amount,
companyId, companyId,
userId userId
]); ], {userId});
if (!row) if (!row)
throw new UserError('Transaction error'); throw new UserError('Transaction error');

View File

@ -46,7 +46,7 @@ module.exports = Self => {
const args = ctx.args; const args = ctx.args;
const models = Self.app.models; const models = Self.app.models;
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
@ -79,7 +79,7 @@ module.exports = Self => {
], myOptions); ], myOptions);
const buyUltimate = await Self.rawSql(` const buyUltimate = await Self.rawSql(`
SELECT * SELECT *
FROM tmp.buyUltimate FROM tmp.buyUltimate
WHERE warehouseFk = ? WHERE warehouseFk = ?
`, [travel.warehouseInFk], myOptions); `, [travel.warehouseInFk], myOptions);

View File

@ -21,7 +21,7 @@ module.exports = Self => {
Self.toBook = async(ctx, id, options) => { Self.toBook = async(ctx, id, options) => {
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,6 +1,6 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('book', { Self.remoteMethodCtx('book', {
description: 'Book an invoiceOut', description: 'Book an invoiceOut',
accessType: 'WRITE', accessType: 'WRITE',
accepts: { accepts: {
@ -20,10 +20,10 @@ module.exports = Self => {
} }
}); });
Self.book = async(ref, options) => { Self.book = async(ctx, ref, options) => {
const models = Self.app.models; const models = Self.app.models;
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -36,7 +36,7 @@ module.exports = Self => {
Self.clientsToInvoice = async(ctx, clientId, invoiceDate, maxShipped, companyFk, options) => { Self.clientsToInvoice = async(ctx, clientId, invoiceDate, maxShipped, companyFk, options) => {
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -51,7 +51,7 @@ module.exports = Self => {
const args = ctx.args; const args = ctx.args;
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -50,7 +50,7 @@ module.exports = Self => {
Self.invoiceClient = async(ctx, options) => { Self.invoiceClient = async(ctx, options) => {
const args = ctx.args; const args = ctx.args;
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('refund', { Self.remoteMethodCtx('refund', {
description: 'Create refund tickets with sales and services if provided', description: 'Create refund tickets with sales and services if provided',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [ 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 models = Self.app.models;
const myOptions = {}; const myOptions = {};
let tx; let tx;
@ -43,7 +43,7 @@ module.exports = Self => {
const tickets = await models.Ticket.find(filter, myOptions); const tickets = await models.Ticket.find(filter, myOptions);
const ticketsIds = tickets.map(ticket => ticket.id); 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(); if (tx) await tx.commit();

View File

@ -1,6 +1,7 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('invoiceOut book()', () => { describe('invoiceOut book()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
const invoiceOutId = 5; const invoiceOutId = 5;
it('should update the booked property', async() => { it('should update the booked property', async() => {
@ -12,7 +13,7 @@ describe('invoiceOut book()', () => {
const bookedDate = originalInvoiceOut.booked; const bookedDate = originalInvoiceOut.booked;
const invoiceOutRef = originalInvoiceOut.ref; 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); const updatedInvoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options);

View File

@ -3,6 +3,7 @@ const LoopBackContext = require('loopback-context');
describe('InvoiceOut refund()', () => { describe('InvoiceOut refund()', () => {
const userId = 5; const userId = 5;
const ctx = {req: {accessToken: userId}};
const withWarehouse = true; const withWarehouse = true;
const activeCtx = { const activeCtx = {
accessToken: {userId: userId}, accessToken: {userId: userId},
@ -16,7 +17,7 @@ describe('InvoiceOut refund()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
try { try {
const result = await models.InvoiceOut.refund('T1111111', withWarehouse, options); const result = await models.InvoiceOut.refund(ctx, 'T1111111', withWarehouse, options);
expect(result).toBeDefined(); expect(result).toBeDefined();

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('getBalance', { Self.remoteMethodCtx('getBalance', {
description: 'Returns the ', description: 'Returns the ',
accessType: 'READ', accessType: 'READ',
accepts: [{ accepts: [{
@ -19,8 +19,8 @@ module.exports = Self => {
} }
}); });
Self.getBalance = async(filter, options) => { Self.getBalance = async(ctx, filter, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,7 +1,7 @@
let UserError = require('vn-loopback/util/user-error'); let UserError = require('vn-loopback/util/user-error');
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('new', { Self.remoteMethodCtx('new', {
description: 'returns the created item', description: 'returns the created item',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [{ 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 models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context'); const LoopBackContext = require('loopback-context');
describe('item getBalance()', () => { 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() => { 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 tx = await models.Item.beginTransaction({});
const options = {transaction: tx}; const options = {transaction: tx};
@ -25,7 +26,7 @@ describe('item getBalance()', () => {
date: null 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'); const result = results.find(element => element.clientType == 'loses');
@ -59,8 +60,8 @@ describe('item getBalance()', () => {
} }
}; };
const firstItemBalance = await models.Item.getBalance(firstFilter, options); const firstItemBalance = await models.Item.getBalance(ctx, firstFilter, options);
const secondItemBalance = await models.Item.getBalance(secondFilter, options); const secondItemBalance = await models.Item.getBalance(ctx, secondFilter, options);
expect(firstItemBalance[9].claimFk).toEqual(null); expect(firstItemBalance[9].claimFk).toEqual(null);
expect(secondItemBalance[5].claimFk).toEqual(2); expect(secondItemBalance[5].claimFk).toEqual(2);

View File

@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context'); const LoopBackContext = require('loopback-context');
describe('item new()', () => { describe('item new()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
beforeAll(async() => { beforeAll(async() => {
const activeCtx = { const activeCtx = {
accessToken: {userId: 9}, accessToken: {userId: 9},
@ -30,7 +31,7 @@ describe('item new()', () => {
tag: 1 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); let itemType = await models.ItemType.findById(item.typeFk, options);

View File

@ -1,7 +1,7 @@
const UserError = require('vn-loopback/util/user-error'); const UserError = require('vn-loopback/util/user-error');
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('addToOrder', { Self.remoteMethodCtx('addToOrder', {
description: 'Creates rows (lines) for a order', description: 'Creates rows (lines) for a order',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [{ accepts: [{
@ -21,8 +21,8 @@ module.exports = Self => {
} }
}); });
Self.addToOrder = async(params, options) => { Self.addToOrder = async(ctx, params, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -1,6 +1,7 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('order addToOrder()', () => { describe('order addToOrder()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
const orderId = 8; const orderId = 8;
it('should add a row to a given order', async() => { it('should add a row to a given order', async() => {
const tx = await models.Order.beginTransaction({}); 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); const modifiedRows = await models.OrderRow.find({where: {orderFk: orderId}}, options);

View File

@ -23,7 +23,7 @@ module.exports = Self => {
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const query = `CALL hedera.order_confirmWithUser(?, ?)`; 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; return response;
}; };

View File

@ -1,7 +1,7 @@
let UserError = require('vn-loopback/util/user-error'); let UserError = require('vn-loopback/util/user-error');
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('new', { Self.remoteMethodCtx('new', {
description: 'Create a new order and returns the new ID', description: 'Create a new order and returns the new ID',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [ accepts: [
@ -32,8 +32,8 @@ module.exports = Self => {
} }
}); });
Self.new = async(landed, addressId, agencyModeId, options) => { Self.new = async(ctx, landed, addressId, agencyModeId, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('newFromTicket', { Self.remoteMethodCtx('newFromTicket', {
description: 'Create a new order and returns the new ID', description: 'Create a new order and returns the new ID',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [{ accepts: [{
@ -18,7 +18,7 @@ module.exports = Self => {
} }
}); });
Self.newFromTicket = async(ticketFk, options) => { Self.newFromTicket = async(ctx, ticketFk, options) => {
const myOptions = {}; const myOptions = {};
let tx; let tx;
@ -39,7 +39,7 @@ module.exports = Self => {
const addressFk = ticket.addressFk; const addressFk = ticket.addressFk;
const agencyModeFk = ticket.agencyModeFk; 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(); if (tx) await tx.commit();

View File

@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models;
const UserError = require('vn-loopback/util/user-error'); const UserError = require('vn-loopback/util/user-error');
describe('order new()', () => { describe('order new()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
it('should throw an error if the client isnt active', async() => { it('should throw an error if the client isnt active', async() => {
const tx = await models.Order.beginTransaction({}); const tx = await models.Order.beginTransaction({});
@ -13,7 +14,7 @@ describe('order new()', () => {
const addressFk = 6; const addressFk = 6;
const agencyModeFk = 1; const agencyModeFk = 1;
await models.Order.new(landed, addressFk, agencyModeFk, options); await models.Order.new(ctx, landed, addressFk, agencyModeFk, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -34,7 +35,7 @@ describe('order new()', () => {
const addressFk = 121; const addressFk = 121;
const agencyModeFk = 1; 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; const highestOrderIdInFixtures = 3;

View File

@ -1,6 +1,7 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('order newFromTicket()', () => { describe('order newFromTicket()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
it('should create a new order from an existing ticket', async() => { it('should create a new order from an existing ticket', async() => {
const tx = await models.Order.beginTransaction({}); const tx = await models.Order.beginTransaction({});
@ -9,7 +10,7 @@ describe('order newFromTicket()', () => {
const ticketId = 11; const ticketId = 11;
const orderId = await models.Order.newFromTicket(ticketId, options); const orderId = await models.Order.newFromTicket(ctx, ticketId, options);
const highestOrderIdInFixtures = 3; const highestOrderIdInFixtures = 3;

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('createInvoiceIn', { Self.remoteMethodCtx('createInvoiceIn', {
description: 'Creates an invoiceIn from one or more agency terms', description: 'Creates an invoiceIn from one or more agency terms',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [{ 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; const models = Self.app.models;
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context'); const LoopBackContext = require('loopback-context');
describe('AgencyTerm createInvoiceIn()', () => { describe('AgencyTerm createInvoiceIn()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
beforeAll(async() => { beforeAll(async() => {
const activeCtx = { const activeCtx = {
accessToken: {userId: 9}, accessToken: {userId: 9},
@ -42,7 +43,7 @@ describe('AgencyTerm createInvoiceIn()', () => {
const oldInvoiceInDueDay = await models.InvoiceInDueDay.findById(invoiceInDueDayId, null, options); const oldInvoiceInDueDay = await models.InvoiceInDueDay.findById(invoiceInDueDayId, null, options);
const oldInvoiceInTax = await models.InvoiceInTax.findById(invoiceInTaxId, 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); const [newInvoiceIn] = await models.InvoiceIn.rawSql('SELECT MAX(id) id FROM invoiceIn', null, options);

View File

@ -26,7 +26,7 @@ module.exports = Self => {
const tx = await Self.beginTransaction({}); const tx = await Self.beginTransaction({});
try { try {
let options = {transaction: tx}; let options = {transaction: tx, userId};
const priority = await Self.rawSql(query, [id], options); const priority = await Self.rawSql(query, [id], options);

View File

@ -24,7 +24,7 @@ module.exports = Self => {
const models = Self.app.models; const models = Self.app.models;
let tx; let tx;
const myOptions = {}; const myOptions = {userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -23,7 +23,7 @@ module.exports = Self => {
Self.recalculatePrice = async(ctx, sales, options) => { Self.recalculatePrice = async(ctx, sales, options) => {
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('refund', { Self.remoteMethodCtx('refund', {
description: 'Create refund tickets with sales and services if provided', description: 'Create refund tickets with sales and services if provided',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [ 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 models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -3,8 +3,9 @@ const LoopBackContext = require('loopback-context');
describe('Sale refund()', () => { describe('Sale refund()', () => {
const userId = 5; const userId = 5;
const ctx = {req: {accessToken: userId}};
const activeCtx = { const activeCtx = {
accessToken: {userId: userId}, accessToken: {userId},
}; };
const servicesIds = [3]; const servicesIds = [3];
const withWarehouse = true; const withWarehouse = true;
@ -22,7 +23,7 @@ describe('Sale refund()', () => {
try { try {
const options = {transaction: tx}; 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(); expect(refundedTicket).toBeDefined();
@ -40,7 +41,7 @@ describe('Sale refund()', () => {
try { try {
const options = {transaction: tx}; 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({ const refundedTicket = await models.Ticket.findOne({
where: { where: {

View File

@ -52,7 +52,7 @@ describe('sale reserve()', () => {
try { try {
const options = {transaction: tx}; 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[0].reserved).toEqual(false);
expect(originalTicketSales[1].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); 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[0].reserved).toEqual(true);
expect(reservedTicketSales[1].reserved).toEqual(true); expect(reservedTicketSales[1].reserved).toEqual(true);

View File

@ -31,7 +31,7 @@ module.exports = Self => {
Self.updatePrice = async(ctx, id, newPrice, options) => { Self.updatePrice = async(ctx, id, newPrice, options) => {
const $t = ctx.req.__; // $translate const $t = ctx.req.__; // $translate
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -22,7 +22,7 @@ module.exports = Self => {
Object.assign(myOptions, options); Object.assign(myOptions, options);
const salesDepartment = await models.Department.findOne({where: {code: 'VT'}, fields: 'id'}, myOptions); 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); const workerDepartment = await models.WorkerDepartment.findById(userId, null, myOptions);
if (!workerDepartment) return false; if (!workerDepartment) return false;

View File

@ -34,7 +34,7 @@ module.exports = Self => {
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const models = Self.app.models; const models = Self.app.models;
const $t = ctx.req.__; // $translate const $t = ctx.req.__; // $translate
const myOptions = {}; const myOptions = {userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -35,7 +35,7 @@ module.exports = Self => {
Self.addSale = async(ctx, id, itemId, quantity, options) => { Self.addSale = async(ctx, id, itemId, quantity, options) => {
const $t = ctx.req.__; // $translate const $t = ctx.req.__; // $translate
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -2,7 +2,7 @@ const UserError = require('vn-loopback/util/user-error');
const closure = require('./closure'); const closure = require('./closure');
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('closeAll', { Self.remoteMethodCtx('closeAll', {
description: 'Makes the closure process from all warehouses', description: 'Makes the closure process from all warehouses',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [], accepts: [],
@ -16,7 +16,7 @@ module.exports = Self => {
} }
}); });
Self.closeAll = async() => { Self.closeAll = async ctx => {
const toDate = Date.vnNew(); const toDate = Date.vnNew();
toDate.setHours(0, 0, 0, 0); toDate.setHours(0, 0, 0, 0);
toDate.setDate(toDate.getDate() - 1); toDate.setDate(toDate.getDate() - 1);
@ -59,7 +59,7 @@ module.exports = Self => {
GROUP BY t.id GROUP BY t.id
`, [toDate, toDate]); `, [toDate, toDate]);
await closure(Self, tickets); await closure(ctx, Self, tickets);
await Self.rawSql(` await Self.rawSql(`
UPDATE ticket t UPDATE ticket t
@ -73,7 +73,7 @@ module.exports = Self => {
AND util.dayEnd(?) AND util.dayEnd(?)
AND al.code NOT IN('DELIVERED','PACKED') AND al.code NOT IN('DELIVERED','PACKED')
AND t.routeFk AND t.routeFk
AND z.name LIKE '%MADRID%'`, [toDate, toDate]); AND z.name LIKE '%MADRID%'`, [toDate, toDate], {userId: ctx.req.accessToken.userId});
return { return {
message: 'Success' message: 'Success'

View File

@ -4,13 +4,14 @@ const smtp = require('vn-print/core/smtp');
const config = require('vn-print/core/config'); const config = require('vn-print/core/config');
const storage = require('vn-print/core/storage'); 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; if (tickets.length == 0) return;
const failedtickets = []; const failedtickets = [];
for (const ticket of tickets) { for (const ticket of tickets) {
try { 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(` const [invoiceOut] = await Self.rawSql(`
SELECT io.id, io.ref, io.serial, cny.code companyCode, io.issued 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 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) { if (isToBeMailed) {
const invoiceAttachment = { const invoiceAttachment = {
@ -91,7 +92,7 @@ module.exports = async function(Self, tickets, reqArgs = {}) {
// Incoterms authorization // Incoterms authorization
const [{firstOrder}] = await Self.rawSql(` const [{firstOrder}] = await Self.rawSql(`
SELECT COUNT(*) as firstOrder SELECT COUNT(*) as firstOrder
FROM ticket t FROM ticket t
JOIN client c ON c.id = t.clientFk JOIN client c ON c.id = t.clientFk
WHERE t.clientFk = ? WHERE t.clientFk = ?
AND NOT t.isDeleted AND NOT t.isDeleted
@ -111,14 +112,14 @@ module.exports = async function(Self, tickets, reqArgs = {}) {
await email.send(); await email.send();
const [sample] = await Self.rawSql( const [sample] = await Self.rawSql(
`SELECT id `SELECT id
FROM sample FROM sample
WHERE code = 'incoterms-authorization' WHERE code = 'incoterms-authorization'
`); `);
await Self.rawSql(` await Self.rawSql(`
INSERT INTO clientSample (clientFk, typeFk, companyFk) VALUES(?, ?, ?) INSERT INTO clientSample (clientFk, typeFk, companyFk) VALUES(?, ?, ?)
`, [ticket.clientFk, sample.id, ticket.companyFk]); `, [ticket.clientFk, sample.id, ticket.companyFk], {userId});
} }
} catch (error) { } catch (error) {
// Domain not found // Domain not found
@ -152,23 +153,23 @@ module.exports = async function(Self, tickets, reqArgs = {}) {
async function invalidEmail(ticket) { async function invalidEmail(ticket) {
await Self.rawSql(`UPDATE client SET email = NULL WHERE id = ?`, [ await Self.rawSql(`UPDATE client SET email = NULL WHERE id = ?`, [
ticket.clientFk ticket.clientFk
]); ], {userId});
const oldInstance = `{"email": "${ticket.recipient}"}`; const oldInstance = `{"email": "${ticket.recipient}"}`;
const newInstance = `{"email": ""}`; const newInstance = `{"email": ""}`;
await Self.rawSql(` 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', ?, ?)`, [ VALUES (?, NULL, 'UPDATE', 'Client', ?, ?)`, [
ticket.clientFk, ticket.clientFk,
oldInstance, oldInstance,
newInstance newInstance
]); ], {userId});
const body = `No se ha podido enviar el albarán <strong>${ticket.id}</strong> const body = `No se ha podido enviar el albarán <strong>${ticket.id}</strong>
al cliente <strong>${ticket.clientFk} - ${ticket.clientName}</strong> al cliente <strong>${ticket.clientFk} - ${ticket.clientName}</strong>
porque la dirección de email <strong>"${ticket.recipient}"</strong> no es correcta porque la dirección de email <strong>"${ticket.recipient}"</strong> no es correcta
o no está disponible.<br/><br/> o no está disponible.<br/><br/>
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.`; Actualiza la dirección de email con una correcta.`;
smtp.send({ smtp.send({

View File

@ -101,7 +101,7 @@ module.exports = Self => {
Self.componentUpdate = async(ctx, options) => { Self.componentUpdate = async(ctx, options) => {
const args = ctx.args; const args = ctx.args;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -1,6 +1,6 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('getSales', { Self.remoteMethodCtx('getSales', {
description: 'New filter', description: 'New filter',
accessType: 'READ', accessType: 'READ',
accepts: [{ 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 models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -28,7 +28,7 @@ module.exports = function(Self) {
const date = Date.vnNew(); const date = Date.vnNew();
date.setHours(0, 0, 0, 0); date.setHours(0, 0, 0, 0);
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -59,9 +59,9 @@ module.exports = Self => {
Self.new = async(ctx, options) => { Self.new = async(ctx, options) => {
const args = ctx.args; const args = ctx.args;
const myUserId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')
@ -123,7 +123,7 @@ module.exports = Self => {
args.routeId || null, args.routeId || null,
args.landed, args.landed,
true, true,
myUserId userId
], myOptions); ], myOptions);
const ticket = await models.Ticket.findById(result[1][0].newTicketId, null, myOptions); const ticket = await models.Ticket.findById(result[1][0].newTicketId, null, myOptions);

View File

@ -60,7 +60,7 @@ module.exports = Self => {
Self.priceDifference = async(ctx, options) => { Self.priceDifference = async(ctx, options) => {
const args = ctx.args; const args = ctx.args;
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -21,7 +21,7 @@ module.exports = Self => {
}); });
Self.recalculateComponents = async(ctx, id, options) => { Self.recalculateComponents = async(ctx, id, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('refund', { Self.remoteMethodCtx('refund', {
description: 'Create refund tickets with all their sales and services', description: 'Create refund tickets with all their sales and services',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [ 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 models = Self.app.models;
const myOptions = {}; const myOptions = {};
let tx; let tx;
@ -46,7 +46,7 @@ module.exports = Self => {
const services = await models.TicketService.find(filter, myOptions); const services = await models.TicketService.find(filter, myOptions);
const servicesIds = services.map(service => service.id); 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(); if (tx) await tx.commit();

View File

@ -31,7 +31,7 @@ module.exports = Self => {
Self.saveSign = async(ctx, tickets, location, signedTime, options) => { Self.saveSign = async(ctx, tickets, location, signedTime, options) => {
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
let dms; let dms;
let gestDocCreated = false; let gestDocCreated = false;

View File

@ -24,7 +24,7 @@ module.exports = Self => {
Self.setDeleted = async(ctx, id, options) => { Self.setDeleted = async(ctx, id, options) => {
const models = Self.app.models; const models = Self.app.models;
const $t = ctx.req.__; // $translate const $t = ctx.req.__; // $translate
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -1,13 +1,14 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('ticket getSales()', () => { describe('ticket getSales()', () => {
const ctx = {req: {accessToken: 9}};
it('should return the sales of a ticket', async() => { it('should return the sales of a ticket', async() => {
const tx = await models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
try { try {
const options = {transaction: tx}; 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.length).toEqual(4);
expect(sales[0].item).toBeDefined(); expect(sales[0].item).toBeDefined();

View File

@ -1,13 +1,14 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('ticket summary()', () => { describe('ticket summary()', () => {
const ctx = {req: {accessToken: 9}};
it('should return a summary object containing data from 1 ticket', async() => { it('should return a summary object containing data from 1 ticket', async() => {
const tx = await models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
try { try {
const options = {transaction: tx}; 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.id).toEqual(1);
expect(result.nickname).toEqual('Bat cave'); expect(result.nickname).toEqual('Bat cave');
@ -25,7 +26,7 @@ describe('ticket summary()', () => {
try { try {
const options = {transaction: tx}; 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); expect(result.sales.length).toEqual(4);
@ -42,7 +43,7 @@ describe('ticket summary()', () => {
try { try {
const options = {transaction: tx}; 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)); expect(result.totalWithoutVat).toEqual(jasmine.any(Number));
@ -59,7 +60,7 @@ describe('ticket summary()', () => {
try { try {
const options = {transaction: tx}; 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)); expect(result.totalWithVat).toEqual(jasmine.any(Number));

View File

@ -67,7 +67,7 @@ describe('sale transferSales()', () => {
const ticketId = 11; const ticketId = 11;
const receiverTicketId = null; 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); await models.Ticket.transferSales(ctx, ticketId, receiverTicketId, sales, options);
@ -89,7 +89,7 @@ describe('sale transferSales()', () => {
const formerTicketId = 22; const formerTicketId = 22;
let createdTicketId = undefined; 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); expect(formerTicketSales.length).toEqual(2);
@ -98,8 +98,8 @@ describe('sale transferSales()', () => {
createdTicketId = createdTicket.id; createdTicketId = createdTicket.id;
formerTicketSales = await models.Ticket.getSales(formerTicketId, options); formerTicketSales = await models.Ticket.getSales(ctx, formerTicketId, options);
let createdTicketSales = await models.Ticket.getSales(createdTicketId, options); let createdTicketSales = await models.Ticket.getSales(ctx, createdTicketId, options);
expect(formerTicketSales.length).toEqual(0); expect(formerTicketSales.length).toEqual(0);
expect(createdTicketSales.length).toEqual(2); expect(createdTicketSales.length).toEqual(2);
@ -120,7 +120,7 @@ describe('sale transferSales()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
const currentTicketId = 22; const currentTicketId = 22;
const currentTicketSales = await models.Ticket.getSales(currentTicketId, options); const currentTicketSales = await models.Ticket.getSales(ctx, currentTicketId, options);
const receiverTicketId = undefined; const receiverTicketId = undefined;
@ -147,7 +147,7 @@ describe('sale transferSales()', () => {
const formerTicketId = 22; const formerTicketId = 22;
let createdTicketId = undefined; 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; const completeSaleId = formerTicketSales[1].id;
let partialSaleTotalQuantity = formerTicketSales[0].quantity; let partialSaleTotalQuantity = formerTicketSales[0].quantity;
@ -161,8 +161,8 @@ describe('sale transferSales()', () => {
createdTicketId = createdTicket.id; createdTicketId = createdTicket.id;
formerTicketSales = await models.Ticket.getSales(formerTicketId, options); formerTicketSales = await models.Ticket.getSales(ctx, formerTicketId, options);
createdTicketSales = await models.Ticket.getSales(createdTicketId, options); createdTicketSales = await models.Ticket.getSales(ctx, createdTicketId, options);
const [createdPartialSale] = createdTicketSales.filter(sale => { const [createdPartialSale] = createdTicketSales.filter(sale => {
return sale.id != completeSaleId; return sale.id != completeSaleId;

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('summary', { Self.remoteMethodCtx('summary', {
description: 'Returns a ticket summary', description: 'Returns a ticket summary',
accessType: 'READ', accessType: 'READ',
accepts: [{ 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 models = Self.app.models;
const myOptions = {}; const myOptions = {};
@ -28,7 +28,7 @@ module.exports = Self => {
const summaryObj = await getTicketData(Self, ticketFk, myOptions); 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({ summaryObj.packagings = await models.TicketPackaging.find({
where: {ticketFk: ticketFk}, where: {ticketFk: ticketFk},

View File

@ -36,7 +36,7 @@ module.exports = Self => {
Self.transferSales = async(ctx, id, ticketId, sales, options) => { Self.transferSales = async(ctx, id, ticketId, sales, options) => {
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -44,7 +44,7 @@ module.exports = Self => {
Self.updateDiscount = async(ctx, id, salesIds, newDiscount, manaCode, options) => { Self.updateDiscount = async(ctx, id, salesIds, newDiscount, manaCode, options) => {
const $t = ctx.req.__; // $translate const $t = ctx.req.__; // $translate
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
let tx; let tx;
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('createThermograph', { Self.remoteMethodCtx('createThermograph', {
description: 'Creates a new thermograph', description: 'Creates a new thermograph',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [{ 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; const models = Self.app.models;
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
const date = Date.vnNew(); const date = Date.vnNew();
if (typeof options == 'object') if (typeof options == 'object')

View File

@ -5,6 +5,7 @@ describe('Termograph createThermograph()', () => {
const model = 'DISPOSABLE'; const model = 'DISPOSABLE';
const temperatureFk = 'COOL'; const temperatureFk = 'COOL';
const warehouseId = 1; const warehouseId = 1;
const ctx = {req: {accessToken: {userId: 9}}};
it(`should create a thermograph which is saved in both thermograph and travelThermograph`, async() => { it(`should create a thermograph which is saved in both thermograph and travelThermograph`, async() => {
const tx = await models.Thermograph.beginTransaction({}); const tx = await models.Thermograph.beginTransaction({});
@ -12,7 +13,7 @@ describe('Termograph createThermograph()', () => {
try { try {
const options = {transaction: tx}; 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.id).toEqual(thermographId);
expect(createdThermograph.model).toEqual(model); expect(createdThermograph.model).toEqual(model);
@ -37,8 +38,8 @@ describe('Termograph createThermograph()', () => {
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
await models.Thermograph.createThermograph(thermographId, model, temperatureFk, warehouseId, options); await models.Thermograph.createThermograph(ctx, 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 tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {

View File

@ -26,9 +26,9 @@ module.exports = Self => {
await models.Dms.removeFile(ctx, travelThermograph.dmsFk); await models.Dms.removeFile(ctx, travelThermograph.dmsFk);
await Self.rawSql(` await Self.rawSql(`
UPDATE travelThermograph UPDATE travelThermograph
SET travelFk = NULL, dmsFk = NULL SET travelFk = NULL, dmsFk = NULL
WHERE id = ?`, [id]); WHERE id = ?`, [id], {userId});
const oldInstance = { const oldInstance = {
travelFk: travelThermograph.travelFk, travelFk: travelThermograph.travelFk,

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('getLeaves', { Self.remoteMethodCtx, ('getLeaves', {
description: 'Returns the nodes for a department', description: 'Returns the nodes for a department',
accepts: [{ accepts: [{
arg: 'parentId', 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( let [res] = await Self.rawSql(
`CALL department_getLeaves(?, ?)`, `CALL department_getLeaves(?, ?)`,
[parentId, search] [parentId, search],
{userId: ctx.req.accessToken.userId}
); );
let map = new Map(); let map = new Map();

View File

@ -33,15 +33,15 @@ module.exports = Self => {
Self.addTimeEntry = async(ctx, workerId, options) => { Self.addTimeEntry = async(ctx, workerId, options) => {
const models = Self.app.models; const models = Self.app.models;
const args = ctx.args; const args = ctx.args;
const currentUserId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const myOptions = {}; const myOptions = {userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
const isSubordinate = await models.Worker.isSubordinate(ctx, workerId, myOptions); const isSubordinate = await models.Worker.isSubordinate(ctx, workerId, myOptions);
const isTeamBoss = await models.ACL.checkAccessAcl(ctx, 'Worker', 'isTeamBoss', 'WRITE'); const isTeamBoss = await models.ACL.checkAccessAcl(ctx, 'Worker', 'isTeamBoss', 'WRITE');
const isHimself = currentUserId == workerId; const isHimself = userId == workerId;
if (!isSubordinate || (isSubordinate && isHimself && !isTeamBoss)) if (!isSubordinate || (isSubordinate && isHimself && !isTeamBoss))
throw new UserError(`You don't have enough privileges`); throw new UserError(`You don't have enough privileges`);

View File

@ -22,10 +22,10 @@ module.exports = Self => {
}); });
Self.deleteTimeEntry = async(ctx, id, options) => { Self.deleteTimeEntry = async(ctx, id, options) => {
const currentUserId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
@ -33,7 +33,7 @@ module.exports = Self => {
const targetTimeEntry = await Self.findById(id, null, myOptions); const targetTimeEntry = await Self.findById(id, null, myOptions);
const isSubordinate = await models.Worker.isSubordinate(ctx, targetTimeEntry.userFk, myOptions); const isSubordinate = await models.Worker.isSubordinate(ctx, targetTimeEntry.userFk, myOptions);
const isTeamBoss = await models.ACL.checkAccessAcl(ctx, 'Worker', 'isTeamBoss', 'WRITE'); 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)) if (isSubordinate === false || (isSubordinate && isHimself && !isTeamBoss))
throw new UserError(`You don't have enough privileges`); throw new UserError(`You don't have enough privileges`);

View File

@ -33,7 +33,7 @@ module.exports = Self => {
const conn = Self.dataSource.connector; const conn = Self.dataSource.connector;
const args = ctx.args; const args = ctx.args;
let tx; let tx;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -119,7 +119,7 @@ module.exports = Self => {
Self.new = async(ctx, options) => { Self.new = async(ctx, options) => {
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
const args = ctx.args; const args = ctx.args;
let tx; let tx;

View File

@ -36,6 +36,7 @@ describe('Worker new', () => {
payMethodFk: 1, payMethodFk: 1,
roleFk: 1 roleFk: 1
}; };
const req = {accessToken: {userId: 9}};
it('should return error if personal mail already exists', async() => { it('should return error if personal mail already exists', async() => {
const user = await models.VnUser.findById(employeeId, {fields: ['email']}); const user = await models.VnUser.findById(employeeId, {fields: ['email']});
@ -46,7 +47,8 @@ describe('Worker new', () => {
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
const ctx = { const ctx = {
args: Object.assign({}, defaultWorker, {email: user.email}) args: Object.assign({}, defaultWorker, {email: user.email}),
req
}; };
await models.Worker.new(ctx, options); await models.Worker.new(ctx, options);
@ -69,7 +71,8 @@ describe('Worker new', () => {
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
const ctx = { const ctx = {
args: Object.assign({}, defaultWorker, {code: worker.code}) args: Object.assign({}, defaultWorker, {code: worker.code}),
req
}; };
await models.Worker.new(ctx, options); await models.Worker.new(ctx, options);
@ -92,7 +95,8 @@ describe('Worker new', () => {
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
const ctx = { const ctx = {
args: Object.assign({}, defaultWorker, {fi: worker.fi}) args: Object.assign({}, defaultWorker, {fi: worker.fi}),
req
}; };
await models.Worker.new(ctx, options); await models.Worker.new(ctx, options);
@ -119,7 +123,8 @@ describe('Worker new', () => {
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
const ctx = { const ctx = {
args: Object.assign({}, defaultWorker, {payMethodFk: payMethodIbanRequired.id}) args: Object.assign({}, defaultWorker, {payMethodFk: payMethodIbanRequired.id}),
req
}; };
await models.Worker.new(ctx, options); await models.Worker.new(ctx, options);
@ -133,7 +138,7 @@ describe('Worker new', () => {
}); });
it('should create a new worker', async() => { 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.Worker.destroyById(newWorker.id);
await models.Address.destroyAll({clientFk: newWorker.id}); await models.Address.destroyAll({clientFk: newWorker.id});
@ -155,7 +160,8 @@ describe('Worker new', () => {
{ {
fi: client.fi, fi: client.fi,
email: client.email email: client.email
}) }),
req
}; };
const newWorker = await models.Worker.new(newWorkerData); const newWorker = await models.Worker.new(newWorkerData);

View File

@ -1,5 +1,5 @@
module.exports = Self => { 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', description: 'Returns a list of agencies that can land a shipment on a day for an address and a warehouse',
accepts: [ accepts: [
{ {
@ -28,8 +28,8 @@ module.exports = Self => {
} }
}); });
Self.getAgenciesWithWarehouse = async(addressFk, landed, warehouseFk, options) => { Self.getAgenciesWithWarehouse = async(ctx, addressFk, landed, warehouseFk, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,5 +1,5 @@
module.exports = Self => { 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', description: 'Returns a list of agencies that can land a shipment on a day for an address',
accepts: [ accepts: [
{ {
@ -22,8 +22,8 @@ module.exports = Self => {
} }
}); });
Self.landsThatDay = async(addressFk, landed, options) => { Self.landsThatDay = async(ctx, addressFk, landed, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -2,6 +2,7 @@ const app = require('vn-loopback/server/server');
describe('Agency getAgenciesWithWarehouse()', () => { describe('Agency getAgenciesWithWarehouse()', () => {
const today = Date.vnNew(); const today = Date.vnNew();
const ctx = {req: {accessToken: {userId: 9}}};
it('should return the agencies that can handle the given delivery request', async() => { it('should return the agencies that can handle the given delivery request', async() => {
const tx = await app.models.Zone.beginTransaction({}); const tx = await app.models.Zone.beginTransaction({});
@ -9,7 +10,7 @@ describe('Agency getAgenciesWithWarehouse()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
const addressId = 101; 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.length).toEqual(3);
expect(agencies[0].agencyMode).toEqual('inhouse pickup'); expect(agencies[0].agencyMode).toEqual('inhouse pickup');
@ -30,7 +31,7 @@ describe('Agency getAgenciesWithWarehouse()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
const addressId = 101; 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); expect(agencies.length).toEqual(0);

View File

@ -1,6 +1,7 @@
const {models} = require('vn-loopback/server/server'); const {models} = require('vn-loopback/server/server');
describe('Agency landsThatDay()', () => { describe('Agency landsThatDay()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
const today = Date.vnNew(); const today = Date.vnNew();
it('should return a list of agencies that can land a shipment on a day for an address', async() => { 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({}); const tx = await models.Agency.beginTransaction({});
@ -8,7 +9,7 @@ describe('Agency landsThatDay()', () => {
try { try {
const options = {transaction: tx}; 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); expect(agencies.length).toBeGreaterThanOrEqual(3);

View File

@ -26,7 +26,7 @@ module.exports = Self => {
today.setHours(0, 0, 0, 0); today.setHours(0, 0, 0, 0);
let tx; let tx;
const myOptions = {}; const myOptions = {userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,6 +1,6 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('getEvents', { Self.remoteMethodCtx('getEvents', {
description: 'Returns delivery days for a postcode', description: 'Returns delivery days for a postcode',
accepts: [ accepts: [
{ {
@ -25,8 +25,8 @@ module.exports = Self => {
} }
}); });
Self.getEvents = async(geoFk, agencyModeFk, options) => { Self.getEvents = async(ctx, geoFk, agencyModeFk, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,6 +1,6 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('getLeaves', { Self.remoteMethodCtx('getLeaves', {
description: 'Returns the nodes for a zone', description: 'Returns the nodes for a zone',
accepts: [ accepts: [
{ {
@ -31,8 +31,8 @@ module.exports = Self => {
} }
}); });
Self.getLeaves = async(id, parentId = null, search, options) => { Self.getLeaves = async(ctx, id, parentId = null, search, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('getUpcomingDeliveries', { Self.remoteMethodCtx('getUpcomingDeliveries', {
description: 'Returns the upcomings deliveries', description: 'Returns the upcomings deliveries',
accessType: 'READ', accessType: 'READ',
accepts: [], accepts: [],
@ -13,8 +13,8 @@ module.exports = Self => {
} }
}); });
Self.getUpcomingDeliveries = async options => { Self.getUpcomingDeliveries = async(ctx, options) => {
const myOptions = {}; const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,13 +1,14 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('zone getEvents()', () => { describe('zone getEvents()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
it('should return all events for the specified geo and agency mode', async() => { it('should return all events for the specified geo and agency mode', async() => {
const tx = await models.Zone.beginTransaction({}); const tx = await models.Zone.beginTransaction({});
try { try {
const options = {transaction: tx}; 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); expect(result.events.length).toEqual(10);

View File

@ -1,13 +1,14 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('zone getLeaves()', () => { describe('zone getLeaves()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
it('should return the country and the childs containing the search value', async() => { it('should return the country and the childs containing the search value', async() => {
const tx = await models.Zone.beginTransaction({}); const tx = await models.Zone.beginTransaction({});
try { try {
const options = {transaction: tx}; 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); expect(result.length).toEqual(1);

View File

@ -1,12 +1,13 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
describe('zone getUpcomingDeliveries()', () => { describe('zone getUpcomingDeliveries()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
it('should check returns data', async() => { it('should check returns data', async() => {
const tx = await models.Zone.beginTransaction({}); const tx = await models.Zone.beginTransaction({});
try { try {
const options = {transaction: tx}; 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 firstResultLines = result[0].lines;
const secondResultLines = result[1].lines; const secondResultLines = result[1].lines;