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

View File

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

View File

@ -196,8 +196,48 @@ module.exports = function(Self) {
/*
* Shortcut to VnMySQL.executeP()
*/
rawSql(query, params, options, cb) {
return this.dataSource.connector.executeP(query, params, options, cb);
async rawSql(query, params, options) {
const userId = options?.userId;
const connector = this.dataSource.connector;
let conn;
let res;
const opts = Object.assign({}, options);
try {
if (userId) {
conn = await new Promise((resolve, reject) => {
connector.client.getConnection(function(err, conn) {
if (err)
reject(err);
else
resolve(conn);
});
});
const opts = Object.assign({}, options);
if (!opts.transaction) {
opts.transaction = {
connection: conn,
connector
};
}
await connector.executeP(
'CALL account.myUser_loginWithName((SELECT name FROM account.user WHERE id = ?))',
[userId], opts
);
}
res = await connector.executeP(query, params, opts);
if (userId) {
await connector.executeP('CALL account.myUser_logout()', null, opts);
}
} finally {
if (conn) conn.release();
}
return res;
},
/*

View File

@ -1,6 +1,6 @@
module.exports = Self => {
Self.remoteMethod('changePassword', {
Self.remoteMethodCtx('changePassword', {
description: 'Changes the user password',
accessType: 'WRITE',
accepts: [
@ -27,9 +27,9 @@ module.exports = Self => {
}
});
Self.changePassword = async function(id, oldPassword, newPassword) {
Self.changePassword = async function(ctx, id, oldPassword, newPassword) {
await Self.rawSql(`CALL account.user_changePassword(?, ?, ?)`,
[id, oldPassword, newPassword]);
[id, oldPassword, newPassword], {userId: ctx.req.accessToken.userId});
await Self.app.models.Account.syncById(id, newPassword);
};
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context');
describe('item getBalance()', () => {
const ctx = {req: {accessToken: {userId: 9}}};
it('should return the balance lines of a client type loses in which one has highlighted true', async() => {
const tx = await models.Item.beginTransaction({});
const options = {transaction: tx};
@ -25,7 +26,7 @@ describe('item getBalance()', () => {
date: null
}
};
const results = await models.Item.getBalance(filter, options);
const results = await models.Item.getBalance(ctx, filter, options);
const result = results.find(element => element.clientType == 'loses');
@ -59,8 +60,8 @@ describe('item getBalance()', () => {
}
};
const firstItemBalance = await models.Item.getBalance(firstFilter, options);
const secondItemBalance = await models.Item.getBalance(secondFilter, options);
const firstItemBalance = await models.Item.getBalance(ctx, firstFilter, options);
const secondItemBalance = await models.Item.getBalance(ctx, secondFilter, options);
expect(firstItemBalance[9].claimFk).toEqual(null);
expect(secondItemBalance[5].claimFk).toEqual(2);

View File

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

View File

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

View File

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

View File

@ -23,7 +23,7 @@ module.exports = Self => {
const userId = ctx.req.accessToken.userId;
const query = `CALL hedera.order_confirmWithUser(?, ?)`;
const response = await Self.rawSql(query, [orderFk, userId]);
const response = await Self.rawSql(query, [orderFk, userId], {userId});
return response;
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -52,7 +52,7 @@ describe('sale reserve()', () => {
try {
const options = {transaction: tx};
originalTicketSales = await models.Ticket.getSales(11, options);
originalTicketSales = await models.Ticket.getSales(ctx, 11, options);
expect(originalTicketSales[0].reserved).toEqual(false);
expect(originalTicketSales[1].reserved).toEqual(false);
@ -63,7 +63,7 @@ describe('sale reserve()', () => {
await models.Sale.reserve(ctx, ticketId, sales, reserved, options);
const reservedTicketSales = await models.Ticket.getSales(ticketId, options);
const reservedTicketSales = await models.Ticket.getSales(ctx, ticketId, options);
expect(reservedTicketSales[0].reserved).toEqual(true);
expect(reservedTicketSales[1].reserved).toEqual(true);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
module.exports = Self => {
Self.remoteMethod('refund', {
Self.remoteMethodCtx('refund', {
description: 'Create refund tickets with all their sales and services',
accessType: 'WRITE',
accepts: [
@ -24,7 +24,7 @@ module.exports = Self => {
}
});
Self.refund = async(ticketsIds, withWarehouse, options) => {
Self.refund = async(ctx, ticketsIds, withWarehouse, options) => {
const models = Self.app.models;
const myOptions = {};
let tx;
@ -46,7 +46,7 @@ module.exports = Self => {
const services = await models.TicketService.find(filter, myOptions);
const servicesIds = services.map(service => service.id);
const refundedTickets = await models.Sale.refund(salesIds, servicesIds, withWarehouse, myOptions);
const refundedTickets = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, myOptions);
if (tx) await tx.commit();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
module.exports = Self => {
Self.remoteMethod('summary', {
Self.remoteMethodCtx('summary', {
description: 'Returns a ticket summary',
accessType: 'READ',
accepts: [{
@ -19,7 +19,7 @@ module.exports = Self => {
}
});
Self.summary = async(ticketFk, options) => {
Self.summary = async(ctx, ticketFk, options) => {
const models = Self.app.models;
const myOptions = {};
@ -28,7 +28,7 @@ module.exports = Self => {
const summaryObj = await getTicketData(Self, ticketFk, myOptions);
summaryObj.sales = await models.Ticket.getSales(ticketFk, myOptions);
summaryObj.sales = await models.Ticket.getSales(ctx, ticketFk, myOptions);
summaryObj.packagings = await models.TicketPackaging.find({
where: {ticketFk: ticketFk},

View File

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

View File

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

View File

@ -1,5 +1,5 @@
module.exports = Self => {
Self.remoteMethod('createThermograph', {
Self.remoteMethodCtx('createThermograph', {
description: 'Creates a new thermograph',
accessType: 'WRITE',
accepts: [{
@ -36,10 +36,10 @@ module.exports = Self => {
}
});
Self.createThermograph = async(thermographId, model, temperatureFk, warehouseId, options) => {
Self.createThermograph = async(ctx, thermographId, model, temperatureFk, warehouseId, options) => {
const models = Self.app.models;
let tx;
const myOptions = {};
const myOptions = {userId: ctx.req.accessToken.userId};
const date = Date.vnNew();
if (typeof options == 'object')

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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