client module changes for transactions
gitea/salix/pipeline/head This commit looks good Details

This commit is contained in:
Carlos Jimenez Ruiz 2021-07-08 15:53:30 +02:00
parent 10c7aa70d6
commit 3b2b4e3819
55 changed files with 1715 additions and 1178 deletions

View File

@ -21,8 +21,9 @@ module.exports = Self => {
});
Self.removeFile = async(ctx, id, options) => {
const models = Self.app.models;
let tx;
let myOptions = {};
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
@ -33,7 +34,6 @@ module.exports = Self => {
}
try {
const models = Self.app.models;
const dms = await models.Dms.findById(id, null, myOptions);
const trashDmsType = await models.DmsType.findOne({
where: {code: 'trash'}

View File

@ -25,8 +25,9 @@ module.exports = Self => {
});
Self.createFromSales = async(ctx, ticketId, sales, options) => {
const models = Self.app.models;
let tx;
let myOptions = {};
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
@ -35,7 +36,6 @@ module.exports = Self => {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
try {

View File

@ -4,12 +4,12 @@ module.exports = Self => {
accessType: 'WRITE',
accepts: {
arg: 'id',
type: 'Number',
type: 'number',
description: 'The document id',
http: {source: 'path'}
},
returns: {
type: 'Object',
type: 'object',
root: true
},
http: {
@ -18,13 +18,33 @@ module.exports = Self => {
}
});
Self.removeFile = async(ctx, id) => {
Self.removeFile = async(ctx, id, options) => {
const models = Self.app.models;
const clientDms = await Self.findById(id);
let tx;
const myOptions = {};
await models.Dms.removeFile(ctx, clientDms.dmsFk);
if (typeof options == 'object')
Object.assign(myOptions, options);
return clientDms.destroy();
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const clientDms = await Self.findById(id, null, myOptions);
await models.Dms.removeFile(ctx, clientDms.dmsFk, myOptions);
const destroyedClient = await clientDms.destroy(myOptions);
if (tx) await tx.commit();
return destroyedClient;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};

View File

@ -1,17 +1,24 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('ClientDms removeFile()', () => {
const clientDmsFk = 3;
it(`should return an error for a user without enough privileges`, async() => {
let clientId = 1101;
let ctx = {req: {accessToken: {userId: clientId}}};
const tx = await models.Client.beginTransaction({});
let error;
await app.models.ClientDms.removeFile(ctx, clientDmsFk).catch(e => {
try {
const options = {transaction: tx};
const clientDmsFk = 3;
const clientId = 1101;
const ctx = {req: {accessToken: {userId: clientId}}};
await models.ClientDms.removeFile(ctx, clientDmsFk, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}).finally(() => {
expect(error.message).toEqual(`You don't have enough privileges`);
});
}
expect(error).toBeDefined();
});

View File

@ -12,7 +12,7 @@ module.exports = function(Self) {
},
{
arg: 'data',
type: 'Object',
type: 'object',
required: true,
description: 'data with new value',
http: {source: 'body'}
@ -29,12 +29,21 @@ module.exports = function(Self) {
}
});
Self.addressesPropagateRe = async(id, data) => {
if (data.hasOwnProperty('isEqualizated')) {
let client = await Self.app.models.Client.findById(id);
Self.addressesPropagateRe = async(id, data, options) => {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const isEqualizated = Object.prototype.hasOwnProperty.call(data, 'isEqualizated');
if (isEqualizated) {
const client = await models.Client.findById(id, null, myOptions);
if (client) {
await Self.app.models.Address.updateAll({clientFk: id}, data);
await client.updateAttributes({hasToInvoiceByAddress: false});
await models.Address.updateAll({clientFk: id}, data, myOptions);
await client.updateAttributes({hasToInvoiceByAddress: false}, myOptions);
return true;
}
}

View File

@ -20,8 +20,15 @@ module.exports = Self => {
}
});
Self.canCreateTicket = async id => {
const client = await Self.app.models.Client.findById(id);
Self.canCreateTicket = async(id, options) => {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const client = await models.Client.findById(id, null, myOptions);
const canCreateTicket = client && client.isActive;
if (!canCreateTicket)
return false;

View File

@ -9,7 +9,7 @@ module.exports = Self => {
description: 'Transaction id'
}],
returns: {
type: 'Object',
type: 'object',
root: true
},
http: {
@ -18,23 +18,32 @@ module.exports = Self => {
}
});
Self.confirmTransaction = async(ctx, id) => {
let userId = ctx.req.accessToken.userId;
let tx = await Self.beginTransaction({});
Self.confirmTransaction = async(ctx, id, options) => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
let options = {transaction: tx};
const oldTpvTransaction = await models.TpvTransaction.findById(id, null, myOptions);
let oldTpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options);
const confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], myOptions);
let confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], options);
const tpvTransaction = await models.TpvTransaction.findById(id, null, myOptions);
let tpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options);
const oldInstance = {status: oldTpvTransaction.status};
const newInstance = {status: tpvTransaction.status};
let oldInstance = {status: oldTpvTransaction.status};
let newInstance = {status: tpvTransaction.status};
let logRecord = {
const logRecord = {
originFk: tpvTransaction.clientFk,
userFk: userId,
action: 'update',
@ -44,12 +53,13 @@ module.exports = Self => {
newInstance: newInstance
};
await Self.app.models.ClientLog.create(logRecord, options);
await models.ClientLog.create(logRecord, myOptions);
if (tx) await tx.commit();
await tx.commit();
return confirm;
} catch (e) {
await tx.rollback();
if (tx) await tx.rollback();
throw e;
}
};

View File

@ -10,44 +10,52 @@ module.exports = Self => {
accepts: [
{
arg: 'filter',
type: 'Object',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string'
}, {
},
{
arg: 'search',
type: 'String',
type: 'string',
description: `If it's and integer searchs by id, otherwise it searchs by name`
}, {
},
{
arg: 'itemId',
type: 'Number',
type: 'number',
description: 'Item id'
}, {
},
{
arg: 'categoryId',
type: 'Number',
type: 'number',
description: 'Category id'
}, {
},
{
arg: 'typeId',
type: 'Number',
type: 'number',
description: 'Item type id',
}, {
},
{
arg: 'buyerId',
type: 'Number',
type: 'number',
description: 'Buyer id'
}, {
},
{
arg: 'from',
type: 'Date',
type: 'date',
description: `The from date filter`
}, {
},
{
arg: 'to',
type: 'Date',
type: 'date',
description: `The to date filter`
}, {
},
{
arg: 'grouped',
type: 'Boolean',
type: 'boolean',
description: 'Group by item'
}
],
returns: {
type: ['Object'],
type: ['object'],
root: true
},
http: {
@ -56,7 +64,12 @@ module.exports = Self => {
}
});
Self.consumption = async(ctx, filter) => {
Self.consumption = async(ctx, filter, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const conn = Self.dataSource.connector;
const args = ctx.args;
const where = buildFilter(ctx.args, (param, value) => {
@ -83,7 +96,7 @@ module.exports = Self => {
});
filter = mergeFilters(filter, {where});
let stmt = new ParameterizedSQL('SELECT');
const stmt = new ParameterizedSQL('SELECT');
if (args.grouped)
stmt.merge(`SUM(s.quantity) AS quantity,`);
else
@ -121,6 +134,6 @@ module.exports = Self => {
stmt.merge(conn.makePagination(filter));
return conn.executeStmt(stmt);
return conn.executeStmt(stmt, myOptions);
};
};

View File

@ -62,7 +62,7 @@ module.exports = function(Self) {
}],
returns: {
root: true,
type: 'Object'
type: 'object'
},
http: {
verb: 'post',
@ -70,18 +70,26 @@ module.exports = function(Self) {
}
});
Self.createAddress = async(ctx, clientFk) => {
Self.createAddress = async(ctx, clientFk, options) => {
const models = Self.app.models;
const args = ctx.args;
const tx = await models.Address.beginTransaction({});
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const options = {transaction: tx};
const province = await models.Province.findById(args.provinceFk, {
include: {
relation: 'country'
}
}, options);
}, myOptions);
const isUeeMember = province.country().isUeeMember;
if (!isUeeMember && !args.incotermsFk)
@ -91,19 +99,20 @@ module.exports = function(Self) {
throw new UserError(`Customs agent is required for a non UEE member`);
delete args.ctx; // Remove unwanted properties
const newAddress = await models.Address.create(args, options);
const client = await Self.findById(clientFk, null, options);
const newAddress = await models.Address.create(args, myOptions);
const client = await Self.findById(clientFk, null, myOptions);
if (args.isDefaultAddress) {
await client.updateAttributes({
defaultAddressFk: newAddress.id
}, options);
}, myOptions);
}
await tx.commit();
if (tx) await tx.commit();
return newAddress;
} catch (e) {
await tx.rollback();
if (tx) await tx.rollback();
throw e;
}
};

View File

@ -48,19 +48,26 @@ module.exports = function(Self) {
}
});
Self.createReceipt = async ctx => {
Self.createReceipt = async(ctx, options) => {
const models = Self.app.models;
const args = ctx.args;
const tx = await models.Address.beginTransaction({});
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const options = {transaction: tx};
delete args.ctx; // Remove unwanted properties
const newReceipt = await models.Receipt.create(args, options);
const clientOriginal = await models.Client.findById(args.clientFk);
const bank = await models.Bank.findById(args.bankFk);
const accountingType = await models.AccountingType.findById(bank.accountingTypeFk);
const newReceipt = await models.Receipt.create(args, myOptions);
const originalClient = await models.Client.findById(args.clientFk, myOptions);
const bank = await models.Bank.findById(args.bankFk, null, myOptions);
const accountingType = await models.AccountingType.findById(bank.accountingTypeFk, null, myOptions);
if (accountingType.code == 'compensation') {
if (!args.compensationAccount)
@ -70,14 +77,16 @@ module.exports = function(Self) {
where: {
account: args.compensationAccount
}
});
}, myOptions);
let clientCompensation = {};
if (!supplierCompensation) {
clientCompensation = await models.Client.findOne({
where: {
accountingAccount: args.compensationAccount
}
});
}, myOptions);
}
if (!supplierCompensation && !clientCompensation)
throw new UserError('Invalid account');
@ -87,20 +96,21 @@ module.exports = function(Self) {
[
args.compensationAccount,
args.bankFk,
accountingType.receiptDescription + clientOriginal.accountingAccount,
accountingType.receiptDescription + originalClient.accountingAccount,
args.amountPaid,
args.companyFk,
clientOriginal.accountingAccount
originalClient.accountingAccount
],
options);
myOptions
);
} else if (accountingType.isAutoConciliated == true) {
const description = `${clientOriginal.id} : ${clientOriginal.socialName} - ${accountingType.receiptDescription}`;
const description = `${originalClient.id} : ${originalClient.socialName} - ${accountingType.receiptDescription}`;
const [xdiarioNew] = await Self.rawSql(
`SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ledger;`,
[
null,
bank.account,
clientOriginal.accountingAccount,
originalClient.accountingAccount,
description,
args.amountPaid,
0,
@ -112,13 +122,14 @@ module.exports = function(Self) {
false,
args.companyFk
],
options);
myOptions
);
await Self.rawSql(
`SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`,
[
xdiarioNew.ledger,
clientOriginal.accountingAccount,
originalClient.accountingAccount,
bank.account,
description,
0,
@ -131,13 +142,15 @@ module.exports = function(Self) {
false,
args.companyFk
],
options);
myOptions
);
}
await tx.commit();
if (tx) await tx.commit();
return newReceipt;
} catch (e) {
await tx.rollback();
if (tx) await tx.rollback();
throw e;
}
};

View File

@ -16,22 +16,29 @@ module.exports = function(Self) {
}
});
Self.createWithUser = async data => {
let firstEmail = data.email ? data.email.split(',')[0] : null;
let user = {
Self.createWithUser = async(data, options) => {
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const firstEmail = data.email ? data.email.split(',')[0] : null;
const user = {
name: data.userName,
email: firstEmail,
password: parseInt(Math.random() * 100000000000000)
};
const Account = Self.app.models.Account;
const Address = Self.app.models.Address;
const tx = await Account.beginTransaction({});
try {
let options = {transaction: tx};
let account = await Account.create(user, options);
let client = await Self.create({
const account = await models.Account.create(user, myOptions);
const client = await Self.create({
id: account.id,
name: data.name,
fi: data.fi,
@ -44,9 +51,9 @@ module.exports = function(Self) {
provinceFk: data.provinceFk,
countryFk: data.countryFk,
isEqualizated: data.isEqualizated
}, options);
}, myOptions);
let address = await Address.create({
const address = await models.Address.create({
clientFk: client.id,
nickname: client.name,
city: client.city,
@ -55,16 +62,17 @@ module.exports = function(Self) {
provinceFk: client.provinceFk,
isEqualizated: client.isEqualizated,
isActive: true
}, options);
}, myOptions);
await client.updateAttributes({
defaultAddressFk: address.id
}, options);
}, myOptions);
if (tx) await tx.commit();
await tx.commit();
return client;
} catch (e) {
await tx.rollback();
if (tx) await tx.rollback();
throw e;
}
};

View File

@ -19,9 +19,14 @@ module.exports = Self => {
}
});
Self.getAverageInvoiced = async clientFk => {
let query = `SELECT invoiced FROM vn.annualAverageInvoiced WHERE clientFk = ?`;
let [invoiced] = await Self.rawSql(query, [clientFk]);
Self.getAverageInvoiced = async(clientFk, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `SELECT invoiced FROM vn.annualAverageInvoiced WHERE clientFk = ?`;
const [invoiced] = await Self.rawSql(query, [clientFk], myOptions);
return invoiced;
};

View File

@ -9,7 +9,7 @@ module.exports = function(Self) {
http: {source: 'path'}
},
returns: {
type: 'Object',
type: 'object',
root: true
},
http: {
@ -18,8 +18,13 @@ module.exports = function(Self) {
}
});
Self.getCard = async function(id) {
let client = await Self.findOne({
Self.getCard = async(id, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const client = await Self.findOne({
where: {
id: id
},
@ -29,38 +34,44 @@ module.exports = function(Self) {
scope: {
fields: ['id', 'name']
}
}, {
},
{
relation: 'province',
scope: {
fields: ['id', 'name']
}
}, {
}, {
},
{
relation: 'salesPersonUser',
scope: {
fields: ['id', 'name']
}
}, {
},
{
relation: 'country',
scope: {
fields: ['id', 'country']
}
}, {
},
{
relation: 'payMethod',
scope: {
fields: ['id', 'name']
}
}, {
},
{
relation: 'account',
scope: {
fields: ['id', 'name', 'active']
}
}
]
});
}, myOptions);
let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`;
client.debt = (await Self.rawSql(query, [id]))[0].debt;
const query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`;
const data = await Self.rawSql(query, [id], myOptions);
client.debt = data[0].debt;
return client;
};

View File

@ -19,9 +19,14 @@ module.exports = Self => {
}
});
Self.getDebt = async clientFk => {
let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`;
let [debt] = await Self.rawSql(query, [clientFk]);
Self.getDebt = async(clientFk, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`;
const [debt] = await Self.rawSql(query, [clientFk], myOptions);
return debt;
};

View File

@ -19,9 +19,14 @@ module.exports = Self => {
}
});
Self.getMana = async clientFk => {
let query = `SELECT vn.clientGetMana(?) AS mana`;
let [mana] = await Self.rawSql(query, [clientFk]);
Self.getMana = async(clientFk, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `SELECT vn.clientGetMana(?) AS mana`;
const [mana] = await Self.rawSql(query, [clientFk], myOptions);
return mana;
};

View File

@ -7,12 +7,12 @@ module.exports = Self => {
accessType: 'READ',
accepts: [{
arg: 'filter',
type: 'Object',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string',
http: {source: 'query'}
}],
returns: {
type: ['Object'],
type: ['object'],
root: true
},
http: {
@ -21,9 +21,14 @@ module.exports = Self => {
}
});
Self.getTransactions = async filter => {
let conn = Self.dataSource.connector;
let stmt = new ParameterizedSQL(`
Self.getTransactions = async(filter, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const conn = Self.dataSource.connector;
const stmt = new ParameterizedSQL(`
SELECT
t.id,
t.clientFk,
@ -39,6 +44,6 @@ module.exports = Self => {
stmt.merge(conn.makeSuffix(filter, 't'));
return await Self.rawStmt(stmt);
return Self.rawStmt(stmt, myOptions);
};
};

View File

@ -2,23 +2,13 @@ module.exports = Self => {
Self.remoteMethod('hasCustomerRole', {
description: 'Comprueba si un usuario tiene el rol de cliente',
accessType: 'READ',
accepts: [
{
accepts: [{
arg: 'id',
type: 'string',
required: true,
description: 'The user id',
http: {source: 'path'}
}, {
arg: 'context',
type: 'object',
required: true,
description: 'Filter defining where',
http: function(context) {
return context.req.query;
}
}
],
}],
returns: {
type: 'boolean',
root: true
@ -29,17 +19,19 @@ module.exports = Self => {
}
});
Self.hasCustomerRole = (id, context, callback) => {
let query = `
Self.hasCustomerRole = (id, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `
SELECT COUNT(*) > 0 isCustomer
FROM salix.Account A
JOIN salix.Role r ON r.id = A.roleFK
WHERE r.name = 'customer'
AND A.id IN (?)`;
Self.rawSql(query, [id]).then(
instances => callback(null, instances[0]),
err => callback(err)
);
return Self.rawSql(query, [id], myOptions);
};
};

View File

@ -9,14 +9,6 @@ module.exports = Self => {
required: true,
description: 'The user id',
http: {source: 'path'}
}, {
arg: 'context',
type: 'object',
required: true,
description: 'Filter defining where',
http: function(context) {
return context.req.query;
}
}
],
returns: {
@ -29,8 +21,13 @@ module.exports = Self => {
}
});
Self.isValidClient = async id => {
let query = `
Self.isValidClient = async(id, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `
SELECT r.name
FROM salix.Account a
JOIN vn.client c ON a.id = c.id
@ -38,9 +35,9 @@ module.exports = Self => {
JOIN salix.Role r ON r.id = rm.roleId
WHERE a.id = ? AND c.isActive AND c.isTaxDataChecked`;
let roleNames = await Self.rawSql(query, [id]);
const roleNames = await Self.rawSql(query, [id], myOptions);
let isEmployee = roleNames.findIndex(role => {
const isEmployee = roleNames.findIndex(role => {
return role.name === 'employee';
});

View File

@ -2,19 +2,22 @@ module.exports = Self => {
Self.remoteMethod('lastActiveTickets', {
description: 'Returns the last three active tickets of a client',
accessType: 'READ',
accepts: [{
accepts: [
{
arg: 'id',
type: 'Number',
type: 'number',
required: true,
description: 'Client id',
http: {source: 'path'}
}, {
},
{
arg: 'ticketId',
type: 'Number',
type: 'number',
required: true
}],
}
],
returns: {
type: ['Object'],
type: ['object'],
root: true
},
http: {
@ -23,8 +26,13 @@ module.exports = Self => {
}
});
Self.lastActiveTickets = async(id, ticketId) => {
const ticket = await Self.app.models.Ticket.findById(ticketId);
Self.lastActiveTickets = async(id, ticketId, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const ticket = await Self.app.models.Ticket.findById(ticketId, null, myOptions);
const query = `
SELECT
t.id,
@ -47,7 +55,7 @@ module.exports = Self => {
ORDER BY t.shipped
LIMIT 10`;
return Self.rawSql(query, [id, ticketId, ticket.warehouseFk]);
return Self.rawSql(query, [id, ticketId, ticket.warehouseFk], myOptions);
};
};

View File

@ -5,23 +5,23 @@ module.exports = Self => {
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'Number',
type: 'number',
required: true,
description: 'The ticket id',
http: {source: 'path'}
},
{
arg: 'destination',
type: 'String',
type: 'string',
required: true,
},
{
arg: 'message',
type: 'String',
type: 'string',
required: true,
}],
returns: {
type: 'Object',
type: 'object',
root: true
},
http: {
@ -30,11 +30,17 @@ module.exports = Self => {
}
});
Self.sendSms = async(ctx, id, destination, message) => {
Self.sendSms = async(ctx, id, destination, message, options) => {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const userId = ctx.req.accessToken.userId;
let sms = await Self.app.models.Sms.send(ctx, id, destination, message);
let logRecord = {
const sms = await models.Sms.send(ctx, id, destination, message);
const logRecord = {
originFk: id,
userFk: userId,
action: 'insert',
@ -48,7 +54,7 @@ module.exports = Self => {
}
};
const clientLog = await Self.app.models.ClientLog.create(logRecord);
const clientLog = await models.ClientLog.create(logRecord, myOptions);
sms.logId = clientLog.id;

View File

@ -1,40 +1,30 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client addressesPropagateRe', () => {
let client;
beforeEach(async() => {
client = await app.models.Client.findById(1101);
await app.models.Address.update({clientFk: 1101}, {isEqualizated: false});
await client.updateAttributes({hasToInvoiceByAddress: true});
});
afterAll(async done => {
await app.models.Address.update({clientFk: 1101}, {isEqualizated: false});
await client.updateAttributes({hasToInvoiceByAddress: true});
done();
});
it('should propagate the isEqualizated on both addresses of Mr Wayne and set hasToInvoiceByAddress to false', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
let id = 1101;
let data = {
isEqualizated: true
};
let resultAddress = await app.models.Address.find({where: {clientFk: id}});
let resultClient = await app.models.Client.find({where: {id: id}});
await models.Client.addressesPropagateRe(id, data, options);
expect(resultAddress[0].isEqualizated).toBeFalsy();
expect(resultAddress[1].isEqualizated).toBeFalsy();
expect(resultClient[0].hasToInvoiceByAddress).toBeTruthy();
const addresses = await models.Address.find({where: {clientFk: id}}, options);
const client = await models.Client.findById(id, null, options);
await app.models.Client.addressesPropagateRe(id, data);
expect(addresses[0].isEqualizated).toBeTruthy();
expect(addresses[1].isEqualizated).toBeTruthy();
expect(client.hasToInvoiceByAddress).toBeFalsy();
resultAddress = await app.models.Address.find({where: {clientFk: id}});
resultClient = await app.models.Client.find({where: {id: id}});
expect(resultAddress[0].isEqualizated).toBeTruthy();
expect(resultAddress[1].isEqualizated).toBeTruthy();
expect(resultClient[0].hasToInvoiceByAddress).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,4 +1,4 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context');
describe('client canBeInvoiced()', () => {
@ -7,7 +7,6 @@ describe('client canBeInvoiced()', () => {
const activeCtx = {
accessToken: {userId: userId}
};
const models = app.models;
beforeAll(async done => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
@ -18,7 +17,7 @@ describe('client canBeInvoiced()', () => {
});
it('should return falsy for a client without the data checked', async() => {
const tx = await models.Ticket.beginTransaction({});
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
@ -37,7 +36,7 @@ describe('client canBeInvoiced()', () => {
});
it('should return falsy for a client with invoicing disabled', async() => {
const tx = await models.Ticket.beginTransaction({});
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
@ -56,8 +55,18 @@ describe('client canBeInvoiced()', () => {
});
it('should return truthy for an invoiceable client', async() => {
const canBeInvoiced = await models.Client.canBeInvoiced(clientId);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const canBeInvoiced = await models.Client.canBeInvoiced(clientId, options);
expect(canBeInvoiced).toEqual(true);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,17 +1,37 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client canCreateTicket', () => {
it('should receive true if the client is active', async() => {
let id = 1105;
let canCreateTicket = await app.models.Client.canCreateTicket(id);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = 1105;
const canCreateTicket = await models.Client.canCreateTicket(id, null, options);
expect(canCreateTicket).toBeTruthy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it(`should receive false if the client isn't active`, async() => {
let id = 1106;
let canCreateTicket = await app.models.Client.canCreateTicket(id);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = 1106;
const canCreateTicket = await models.Client.canCreateTicket(id, null, options);
expect(canCreateTicket).toBe(false);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,24 +1,26 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client confirmTransaction', () => {
it('should call confirmTransaction() method to mark transaction as confirmed', async() => {
const tx = await models.Client.beginTransaction({});
const transactionId = 2;
afterAll(async done => {
await app.models.Client.rawSql(`
CALL hedera.tpvTransaction_undo(?)`, [transactionId]);
try {
const options = {transaction: tx};
done();
});
it('should call confirmTransaction() method to mark transaction as confirmed', async() => {
let ctx = {req: {accessToken: {userId: 1}}};
await app.models.Client.confirmTransaction(ctx, transactionId);
await models.Client.confirmTransaction(ctx, transactionId, options);
let [receipt] = await app.models.Client.rawSql(
let [receipt] = await models.Client.rawSql(
`SELECT receiptFk
FROM hedera.tpvTransaction
WHERE id = ?`, [transactionId]);
WHERE id = ?`, [transactionId], options);
expect(receipt.receiptFk).toBeGreaterThan(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,7 +1,12 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('client consumption() filter', () => {
it('should return a list of buyed items by ticket', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: 9}}, args: {}};
const filter = {
where: {
@ -9,12 +14,22 @@ describe('client consumption() filter', () => {
},
order: 'itemTypeFk, itemName, itemSize'
};
const result = await app.models.Client.consumption(ctx, filter);
const result = await app.models.Client.consumption(ctx, filter, options);
expect(result.length).toEqual(10);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should return a list of tickets grouped by item', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: 9}},
args: {
grouped: true
@ -26,7 +41,7 @@ describe('client consumption() filter', () => {
},
order: 'itemFk'
};
const result = await app.models.Client.consumption(ctx, filter);
const result = await app.models.Client.consumption(ctx, filter, options);
const firstRow = result[0];
const secondRow = result[1];
@ -36,9 +51,19 @@ describe('client consumption() filter', () => {
expect(firstRow.quantity).toEqual(10);
expect(secondRow.quantity).toEqual(15);
expect(thirdRow.quantity).toEqual(20);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should return a list of tickets from the item id 4', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: 9}},
args: {
itemId: 4
@ -50,11 +75,16 @@ describe('client consumption() filter', () => {
},
order: 'itemTypeFk, itemName, itemSize'
};
const result = await app.models.Client.consumption(ctx, filter);
const result = await app.models.Client.consumption(ctx, filter, options);
const expectedItemId = 4;
const firstRow = result[0];
expect(firstRow.itemFk).toEqual(expectedItemId);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,4 +1,4 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Address createAddress', () => {
const clientFk = 1101;
@ -7,6 +7,13 @@ describe('Address createAddress', () => {
const customAgentOneId = 1;
it('should throw a non uee member error if no incoterms is defined', async() => {
const tx = await models.Client.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const expectedResult = 'My edited address';
const ctx = {
args: {
@ -18,17 +25,26 @@ describe('Address createAddress', () => {
}
};
try {
await app.models.Client.createAddress(ctx, clientFk);
await models.Client.createAddress(ctx, clientFk, options);
await tx.rollback();
} catch (e) {
err = e;
await tx.rollback();
error = e;
}
expect(err).toBeDefined();
expect(err.message).toEqual('Incoterms is required for a non UEE member');
expect(error).toBeDefined();
expect(error.message).toEqual('Incoterms is required for a non UEE member');
});
it('should throw a non uee member error if no customsAgent is defined', async() => {
const tx = await models.Client.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const expectedResult = 'My edited address';
const ctx = {
args: {
@ -40,23 +56,24 @@ describe('Address createAddress', () => {
}
};
try {
await app.models.Client.createAddress(ctx, clientFk);
await models.Client.createAddress(ctx, clientFk, options);
await tx.rollback();
} catch (e) {
err = e;
await tx.rollback();
error = e;
}
expect(err).toBeDefined();
expect(err.message).toEqual('Customs agent is required for a non UEE member');
});
it('should verify that client defaultAddressFk is untainted', async() => {
const client = await app.models.Client.findById(clientFk);
expect(client.defaultAddressFk).toEqual(1);
expect(error).toBeDefined();
expect(error.message).toEqual('Customs agent is required for a non UEE member');
});
it('should create a new address and set as a client default address', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const ctx = {
args: {
clientFk: 1101,
@ -74,17 +91,23 @@ describe('Address createAddress', () => {
}
};
const address = await app.models.Client.createAddress(ctx, clientFk);
const client = await app.models.Client.findById(clientFk);
const address = await models.Client.createAddress(ctx, clientFk, options);
const client = await models.Client.findById(clientFk, null, options);
expect(client.defaultAddressFk).toEqual(address.id);
// restores
await client.updateAttributes({defaultAddressFk: 1});
await address.destroy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should create a new address and set all properties', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const ctx = {
args: {
clientFk: 1101,
@ -102,12 +125,13 @@ describe('Address createAddress', () => {
}
};
address = await app.models.Client.createAddress(ctx, clientFk);
address = await models.Client.createAddress(ctx, clientFk, options);
expect(address).toEqual(jasmine.objectContaining(ctx.args));
// restores
const client = await app.models.Client.findById(clientFk);
await client.updateAttributes({defaultAddressFk: 1});
await address.destroy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,4 +1,4 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context');
describe('Client createReceipt', () => {
@ -27,6 +27,11 @@ describe('Client createReceipt', () => {
});
it('should create a new receipt', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const bankFk = 1;
ctx.args = {
clientFk: clientFk,
@ -37,27 +42,26 @@ describe('Client createReceipt', () => {
description: description
};
const receipt = await app.models.Client.createReceipt(ctx);
const receipt = await models.Client.createReceipt(ctx, options);
delete ctx.args.payed;
const till = await app.models.Till.findOne({
where: {
bankFk: bankFk,
in: amountPaid,
number: clientFk
}
});
expect(receipt).toEqual(jasmine.objectContaining(ctx.args));
// restores
await receipt.destroy();
await till.destroy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should throw Compensation account is empty', async() => {
const bankFk = 3;
const tx = await models.Client.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const bankFk = 3;
ctx.args = {
clientFk: clientFk,
payed: payed,
@ -67,9 +71,11 @@ describe('Client createReceipt', () => {
description: description
};
try {
await app.models.Client.createReceipt(ctx);
await models.Client.createReceipt(ctx, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
@ -78,7 +84,13 @@ describe('Client createReceipt', () => {
});
it('should throw Invalid account if compensationAccount does not belongs to a client nor a supplier', async() => {
const tx = await models.Client.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const bankFk = 3;
ctx.args = {
clientFk: clientFk,
@ -90,9 +102,11 @@ describe('Client createReceipt', () => {
compensationAccount: 'non existing account'
};
try {
await app.models.Client.createReceipt(ctx);
await models.Client.createReceipt(ctx, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
@ -101,6 +115,11 @@ describe('Client createReceipt', () => {
});
it('should create a new receipt with a compensation for a client', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const bankFk = 3;
ctx.args = {
@ -112,34 +131,31 @@ describe('Client createReceipt', () => {
description: description,
compensationAccount: '4300000001'
};
const receipt = await app.models.Client.createReceipt(ctx);
const receiptCompensated = await app.models.Receipt.findOne({
const receipt = await models.Client.createReceipt(ctx, options);
const receiptCompensated = await models.Receipt.findOne({
where: {
clientFk: 1,
bankFk: ctx.args.bankFk
}
});
const till = await app.models.Till.findOne({
where: {
bankFk: bankFk,
in: amountPaid,
number: clientFk
}
});
}, options);
delete ctx.args.payed;
expect(receipt).toEqual(jasmine.objectContaining(ctx.args));
expect(receipt.amountPaid).toEqual(-receiptCompensated.amountPaid);
// restores
await receipt.destroy();
await receiptCompensated.destroy();
await till.destroy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should create a new receipt with a compensation for a supplier', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const bankFk = 3;
ctx.args = {
@ -151,24 +167,16 @@ describe('Client createReceipt', () => {
description: description,
compensationAccount: '4100000001'
};
const receipt = await app.models.Client.createReceipt(ctx);
const receipt = await models.Client.createReceipt(ctx, options);
const paymentCompensated = await app.models.Payment.findOne({
const paymentCompensated = await models.Payment.findOne({
where: {
clientFk: ctx.args.sale,
payed: ctx.args.payed,
amountPaid: ctx.args.amountPaid,
bankFk: ctx.args.bankFk
}
});
const till = await app.models.Till.findOne({
where: {
bankFk: ctx.args.bankFk,
in: amountPaid,
number: clientFk
}
});
}, options);
delete ctx.args.payed;
@ -176,9 +184,9 @@ describe('Client createReceipt', () => {
expect(paymentCompensated.amountPaid).toEqual(paymentCompensated.amountPaid);
// restores
await receipt.destroy();
await paymentCompensated.destroy();
await till.destroy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,28 +1,7 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client Create', () => {
const clientName = 'Wade';
const AccountName = 'Deadpool';
afterEach(async done => {
let address = await app.models.Address.findOne({where: {nickname: clientName}});
let client = await app.models.Client.findOne({where: {name: clientName}});
let account = await app.models.Account.findOne({where: {name: AccountName}});
if (address && client && account) {
try {
await app.models.Address.destroyById(address.id);
await app.models.Client.destroyById(client.id);
await app.models.Account.destroyById(account.id);
} catch (error) {
console.error(error);
}
}
done();
});
let newAccount = {
const newAccount = {
userName: 'Deadpool',
email: 'Deadpool@marvel.com',
fi: '16195279J',
@ -33,34 +12,66 @@ describe('Client Create', () => {
};
it(`should not find Deadpool as he's not created yet`, async() => {
let account = await app.models.Account.findOne({where: {name: newAccount.userName}});
let client = await app.models.Client.findOne({where: {name: newAccount.name}});
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const account = await models.Account.findOne({where: {name: newAccount.userName}}, options);
const client = await models.Client.findOne({where: {name: newAccount.name}}, options);
expect(account).toEqual(null);
expect(client).toEqual(null);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should create a new account', async() => {
let client = await app.models.Client.createWithUser(newAccount);
let account = await app.models.Account.findOne({where: {name: newAccount.userName}});
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const client = await models.Client.createWithUser(newAccount, options);
const account = await models.Account.findOne({where: {name: newAccount.userName}}, options);
expect(account.name).toEqual(newAccount.userName);
expect(client.id).toEqual(account.id);
expect(client.name).toEqual(newAccount.name);
expect(client.email).toEqual(newAccount.email);
expect(client.fi).toEqual(newAccount.fi);
expect(client.socialName).toEqual(newAccount.socialName);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should not be able to create a user if exists', async() => {
await app.models.Client.createWithUser(newAccount);
const tx = await models.Client.beginTransaction({});
let error;
try {
let client = await app.models.Client.createWithUser(newAccount);
const options = {transaction: tx};
await models.Client.createWithUser(newAccount, options);
const client = await models.Client.createWithUser(newAccount, options);
expect(client).toBeNull();
} catch (err) {
expect(err.details.codes.name[0]).toEqual('uniqueness');
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
const errorName = error.details.codes.name[0];
expect(errorName).toEqual('uniqueness');
});
});

View File

@ -1,9 +1,19 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('client getAverageInvoiced()', () => {
it('should call the getAverageInvoiced method', async() => {
const {invoiced} = await app.models.Client.getAverageInvoiced(1101);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const {invoiced} = await models.Client.getAverageInvoiced(1101, options);
expect(invoiced).toEqual(1500);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,12 +1,22 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client getCard()', () => {
it('should receive a formated card of Bruce Wayne', async() => {
let id = 1101;
let result = await app.models.Client.getCard(id);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = 1101;
const result = await models.Client.getCard(id, options);
expect(result.id).toEqual(id);
expect(result.name).toEqual('Bruce Wayne');
expect(result.debt).toEqual(jasmine.any(Number));
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,10 +1,20 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('client getDebt()', () => {
it('should return the client debt', async() => {
let result = await app.models.Client.getDebt(1101);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const result = await models.Client.getDebt(1101, options);
expect(result.debt).toEqual(jasmine.any(Number));
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,9 +1,19 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('client getMana()', () => {
it('should call the getMana method', async() => {
let result = await app.models.Client.getMana(1105);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const result = await models.Client.getMana(1105, options);
expect(result.mana).toEqual(0.34);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,10 +1,20 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client getTransations', () => {
it('should call getTransations() method to receive a list of Web Payments from Bruce Wayne', async() => {
let filter = {where: {clientFk: 1101}};
let result = await app.models.Client.getTransactions(filter);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const filter = {where: {clientFk: 1101}};
const result = await models.Client.getTransactions(filter, options);
expect(result[1].id).toBeTruthy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,59 +1,74 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client hasCustomerRole', () => {
it('should call the hasCustomerRole() method with a customer id', done => {
let id = 1101;
let params = {};
it('should call the hasCustomerRole() method with a customer id', async() => {
const tx = await models.Client.beginTransaction({});
let callback = (error, result) => {
if (error) return done.fail(error);
try {
const options = {transaction: tx};
const id = 1101;
const [result] = await models.Client.hasCustomerRole(id, options);
expect(result).toEqual(jasmine.objectContaining({isCustomer: 1}));
done();
};
app.models.Client.hasCustomerRole(id, params, callback);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should call the hasCustomerRole() method with a non customer id', done => {
let id = 8;
let params = {};
it('should call the hasCustomerRole() method with a non customer id', async() => {
const tx = await models.Client.beginTransaction({});
let callback = (error, result) => {
if (error) return done.fail(error);
try {
const options = {transaction: tx};
const id = 8;
const [result] = await models.Client.hasCustomerRole(id, options);
expect(result).toEqual(jasmine.objectContaining({isCustomer: 0}));
done();
};
app.models.Client.hasCustomerRole(id, params, callback);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should call the hasCustomerRole() method with an unreal id', done => {
let id = 999;
let params = {};
it('should call the hasCustomerRole() method with an unreal id', async() => {
const tx = await models.Client.beginTransaction({});
let callback = (error, result) => {
if (error) return done.fail(error);
try {
const options = {transaction: tx};
const id = 999;
const [result] = await models.Client.hasCustomerRole(id, options);
expect(result).toEqual(jasmine.objectContaining({isCustomer: 0}));
done();
};
app.models.Client.hasCustomerRole(id, params, callback);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should call the hasCustomerRole() method with an invalid id', done => {
let id = 'WRONG!';
let params = {};
it('should call the hasCustomerRole() method with an invalid id', async() => {
const tx = await models.Client.beginTransaction({});
let callback = (error, result) => {
if (error) return done.fail(error);
try {
const options = {transaction: tx};
const id = 'WRONG!';
const [result] = await models.Client.hasCustomerRole(id, options);
expect(result).toEqual(jasmine.objectContaining({isCustomer: 0}));
done();
};
app.models.Client.hasCustomerRole(id, params, callback);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,45 +1,105 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client isValidClient', () => {
it('should call the isValidClient() method with a client id and receive true', async() => {
let id = 1101;
let result = await app.models.Client.isValidClient(id);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = 1101;
const result = await models.Client.isValidClient(id, options);
expect(result).toBeTruthy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should call the isValidClient() method with an employee id to receive false', async() => {
let id = 1;
let result = await app.models.Client.isValidClient(id);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = 1;
const result = await models.Client.isValidClient(id, options);
expect(result).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should call the isValidClient() method with an unexistant id and receive false', async() => {
let id = 999;
let result = await app.models.Client.isValidClient(id);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = 999;
const result = await models.Client.isValidClient(id, options);
expect(result).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should call the isValidClient() method with an invalid id and receive false', async() => {
let id = 'Pepinillos';
let result = await app.models.Client.isValidClient(id);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = 'Pepinillos';
const result = await models.Client.isValidClient(id, options);
expect(result).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should call the isValidClient() method with a customer id which isnt active and return false', async() => {
let id = '1106';
let result = await app.models.Client.isValidClient(id);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = '1106';
const result = await models.Client.isValidClient(id, options);
expect(result).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should call the isValidClient() method with a customer id which his data isnt verified and return false', async() => {
let id = '110';
let result = await app.models.Client.isValidClient(id);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = '110';
const result = await models.Client.isValidClient(id, options);
expect(result).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,11 +1,15 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client last active tickets', () => {
it('should receive an array of last active tickets of Bruce Wayne', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const ticketId = 22;
const clientId = 1109;
const warehouseId = 5;
const result = await app.models.Client.lastActiveTickets(clientId, ticketId, warehouseId);
const result = await models.Client.lastActiveTickets(clientId, ticketId, options);
const length = result.length;
const anyResult = result[Math.floor(Math.random() * Math.floor(length))];
@ -14,5 +18,10 @@ describe('Client last active tickets', () => {
expect(properties.length).toEqual(9);
expect(result.length).toEqual(3);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,29 +1,28 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
const soap = require('soap');
describe('client sendSms()', () => {
let createdLog;
afterAll(async done => {
await app.models.ClientLog.destroyById(createdLog.id);
done();
});
it('should now send a message and log it', async() => {
spyOn(soap, 'createClientAsync').and.returnValue('a so fake client');
let ctx = {req: {accessToken: {userId: 9}}};
let id = 1101;
let destination = 222222222;
let message = 'this is the message created in a test';
const tx = await models.Client.beginTransaction({});
let sms = await app.models.Client.sendSms(ctx, id, destination, message);
try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: 9}}};
const id = 1101;
const destination = 222222222;
const message = 'this is the message created in a test';
logId = sms.logId;
const sms = await models.Client.sendSms(ctx, id, destination, message, options);
createdLog = await app.models.ClientLog.findById(logId);
let json = JSON.parse(JSON.stringify(createdLog.newInstance));
const createdLog = await models.ClientLog.findById(sms.logId);
const json = JSON.parse(JSON.stringify(createdLog.newInstance));
expect(json.message).toEqual(message);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,46 +1,123 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('client summary()', () => {
it('should return a summary object containing data', async() => {
let result = await app.models.Client.summary(1101);
const clientId = 1101;
const tx = await models.Client.beginTransaction({});
expect(result.id).toEqual(1101);
try {
const options = {transaction: tx};
const result = await models.Client.summary(clientId, options);
expect(result.id).toEqual(clientId);
expect(result.name).toEqual('Bruce Wayne');
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should return a summary object containing mana', async() => {
let result = await app.models.Client.summary(1105);
const clientId = 1105;
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const result = await models.Client.summary(clientId, options);
expect(result.mana.mana).toEqual(0.34);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should return a summary object containing debt', async() => {
let result = await app.models.Client.summary(1101);
const clientId = 1101;
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const result = await models.Client.summary(clientId, options);
expect(result.debt.debt).toEqual(jasmine.any(Number));
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should return a summary object containing averageInvoiced', async() => {
let result = await app.models.Client.summary(1101);
const clientId = 1101;
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const result = await models.Client.summary(clientId, options);
expect(result.averageInvoiced.invoiced).toEqual(1500);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should return a summary object containing totalGreuge', async() => {
let result = await app.models.Client.summary(1101);
const clientId = 1101;
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const result = await models.Client.summary(clientId, options);
expect(result.totalGreuge).toEqual(203.71);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should return a summary object without containing active recoveries', async() => {
let result = await app.models.Client.summary(1101);
const clientId = 1101;
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const result = await models.Client.summary(clientId, options);
expect(result.recovery).toEqual(null);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should return a summary object containing active recoveries', async() => {
let result = await app.models.Client.summary(1102);
const clientId = 1102;
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const result = await models.Client.summary(clientId, options);
expect(result.recovery.id).toEqual(3);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,12 +0,0 @@
const app = require('vn-loopback/server/server');
describe('client lastActiveTickets()', () => {
it('should return the last three active tickets', async() => {
const clientId = 1109;
const ticketId = 19;
let result = await app.models.Client.lastActiveTickets(clientId, ticketId);
expect(result.length).toEqual(3);
});
});

View File

@ -1,4 +1,4 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Address updateAddress', () => {
const clientId = 1101;
@ -8,7 +8,12 @@ describe('Address updateAddress', () => {
const customAgentOneId = 1;
it('should throw the non uee member error if no incoterms is defined', async() => {
let err;
const tx = await models.Client.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const ctx = {
args: {
provinceFk: provinceId,
@ -16,18 +21,25 @@ describe('Address updateAddress', () => {
}
};
try {
await app.models.Client.updateAddress(ctx, clientId, addressId);
await models.Client.updateAddress(ctx, clientId, addressId, options);
await tx.rollback();
} catch (e) {
err = e;
await tx.rollback();
error = e;
}
expect(err).toBeDefined();
expect(err.message).toEqual('Incoterms is required for a non UEE member');
expect(error).toBeDefined();
expect(error.message).toEqual('Incoterms is required for a non UEE member');
});
it('should throw a non uee member error if no customsAgent is defined', async() => {
let err;
const tx = await models.Client.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const ctx = {
args: {
provinceFk: provinceId,
@ -35,18 +47,23 @@ describe('Address updateAddress', () => {
}
};
try {
await app.models.Client.updateAddress(ctx, clientId, addressId);
await models.Client.updateAddress(ctx, clientId, addressId, options);
await tx.rollback();
} catch (e) {
err = e;
await tx.rollback();
error = e;
}
expect(err).toBeDefined();
expect(err.message).toEqual('Customs agent is required for a non UEE member');
expect(error).toBeDefined();
expect(error.message).toEqual('Customs agent is required for a non UEE member');
});
it('should update the adress from a non uee member with no error thrown', async() => {
const expectedResult = 'My edited address';
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const ctx = {
args: {
provinceFk: provinceId,
@ -55,46 +72,41 @@ describe('Address updateAddress', () => {
customsAgentFk: customAgentOneId
}
};
const expectedResult = 'My edited address';
let oldAddress = await app.models.Address.findById(addressId);
await models.Client.updateAddress(ctx, clientId, addressId, options);
await app.models.Client.updateAddress(ctx, clientId, addressId);
let address = await app.models.Address.findById(addressId);
const address = await models.Address.findById(addressId, null, options);
expect(address.nickname).toEqual(expectedResult);
// restores
await address.updateAttributes({
nickname: oldAddress.nickname,
provinceFk: oldAddress.provinceFk,
customsAgentFk: null,
incotermsFk: null
});
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should update the address', async() => {
const expectedResult = 'My second time edited address';
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const ctx = {
args: {
nickname: expectedResult
}
};
const expectedResult = 'My second time edited address';
oldAddress = await app.models.Address.findById(addressId);
await models.Client.updateAddress(ctx, clientId, addressId, options);
await app.models.Client.updateAddress(ctx, clientId, addressId);
address = await app.models.Address.findById(addressId);
const address = await models.Address.findById(addressId, null, options);
expect(address.nickname).toEqual(expectedResult);
// restores
await address.updateAttributes({
nickname: oldAddress.nickname,
provinceFk: oldAddress.provinceFk,
customsAgentFk: null,
incotermsFk: null
});
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,61 +1,76 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client updateFiscalData', () => {
const clientId = 1101;
const employeeId = 1;
const salesAssistantId = 21;
const administrativeId = 5;
afterAll(async done => {
const ctx = {req: {accessToken: {userId: administrativeId}}};
ctx.args = {postcode: 46460};
await app.models.Client.updateFiscalData(ctx, clientId);
done();
});
it('should return an error if the user is not salesAssistant and the isTaxDataChecked value is true', async() => {
const tx = await models.Client.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: employeeId}}};
ctx.args = {};
let error;
await app.models.Client.updateFiscalData(ctx, clientId)
.catch(e => {
await models.Client.updateFiscalData(ctx, clientId, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
});
}
expect(error.message).toEqual(`You can't make changes on a client with verified data`);
});
it('should return an error if the salesAssistant did not fill the sage data before checking verified data', async() => {
const client = await app.models.Client.findById(clientId);
await client.updateAttribute('isTaxDataChecked', false);
const tx = await models.Client.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const client = await models.Client.findById(clientId, options);
await client.updateAttribute('isTaxDataChecked', false, options);
const ctx = {req: {accessToken: {userId: salesAssistantId}}};
ctx.args = {isTaxDataChecked: true};
let error;
await app.models.Client.updateFiscalData(ctx, clientId)
.catch(e => {
await models.Client.updateFiscalData(ctx, clientId, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
});
}
expect(error.message).toEqual('You need to fill sage information before you check verified data');
// Restores
await client.updateAttribute('isTaxDataChecked', true);
});
it('should update the client fiscal data and return the count if changes made', async() => {
it('should update the client fiscal data', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: administrativeId}}};
ctx.args = {postcode: 46680};
const client = await app.models.Client.findById(clientId);
const client = await models.Client.findById(clientId, null, options);
expect(client.postcode).toEqual('46460');
const result = await app.models.Client.updateFiscalData(ctx, clientId);
const result = await models.Client.updateFiscalData(ctx, clientId, options);
expect(result.postcode).toEqual('46680');
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,19 +1,26 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('Client uploadFile()', () => {
it(`should return an error for a user without enough privileges`, async() => {
let clientId = 1101;
let currentUserId = 1102;
let paymentLawTypeId = 12;
let ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: paymentLawTypeId}};
const tx = await models.Client.beginTransaction({});
let error;
await app.models.Client.uploadFile(ctx, clientId).catch(e => {
try {
const options = {transaction: tx};
const clientId = 1101;
const currentUserId = 1102;
const paymentLawTypeId = 12;
const ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: paymentLawTypeId}};
await models.Client.uploadFile(ctx, clientId, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}).finally(() => {
}
expect(error.message).toEqual(`You don't have enough privileges`);
});
expect(error).toBeDefined();
});
});

View File

@ -19,21 +19,26 @@ module.exports = Self => {
}
});
Self.summary = async clientFk => {
let models = Self.app.models;
let summaryObj = await getSummary(models.Client, clientFk);
Self.summary = async(clientFk, options) => {
const models = Self.app.models;
const myOptions = {};
summaryObj.mana = await models.Client.getMana(clientFk);
summaryObj.debt = await models.Client.getDebt(clientFk);
summaryObj.averageInvoiced = await models.Client.getAverageInvoiced(clientFk);
summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk);
summaryObj.recovery = await getRecoveries(models.Recovery, clientFk);
if (typeof options == 'object')
Object.assign(myOptions, options);
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.averageInvoiced = await models.Client.getAverageInvoiced(clientFk, myOptions);
summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk, myOptions);
summaryObj.recovery = await getRecoveries(models.Recovery, clientFk, myOptions);
return summaryObj;
};
async function getSummary(client, clientId) {
let filter = {
async function getSummary(clientModel, clientId, options) {
const filter = {
include: [
{
relation: 'account',
@ -115,17 +120,17 @@ module.exports = Self => {
where: {id: clientId}
};
return await client.findOne(filter);
return clientModel.findOne(filter, options);
}
async function getRecoveries(recovery, clientId) {
let filter = {
async function getRecoveries(recoveryModel, clientId, options) {
const filter = {
where: {
and: [{clientFk: clientId}, {or: [{finished: null}, {finished: {gt: Date.now()}}]}]
},
limit: 1
};
return await recovery.findOne(filter);
return recoveryModel.findOne(filter, options);
}
};

View File

@ -3,7 +3,8 @@ const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
Self.remoteMethod('updateAddress', {
description: 'Updates a client address updating default address',
accepts: [{
accepts: [
{
arg: 'ctx',
type: 'object',
http: {source: 'context'}
@ -67,7 +68,8 @@ module.exports = function(Self) {
{
arg: 'isEqualizated',
type: 'boolean'
}],
}
],
returns: {
root: true,
type: 'object'
@ -78,26 +80,37 @@ module.exports = function(Self) {
}
});
Self.updateAddress = async(ctx, clientId, addressId) => {
Self.updateAddress = async(ctx, clientId, addressId, options) => {
const models = Self.app.models;
const args = ctx.args;
const tx = await models.Address.beginTransaction({});
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const options = {transaction: tx};
const address = await models.Address.findOne({
where: {
id: addressId,
clientFk: clientId
}
});
}, myOptions);
const provinceId = args.provinceFk || address.provinceFk;
const province = await models.Province.findById(provinceId, {
include: {
relation: 'country'
}
}, options);
}, myOptions);
const isUeeMember = province.country().isUeeMember;
const incotermsId = args.incotermsFk || address.incotermsFk;
if (!isUeeMember && !incotermsId)
throw new UserError(`Incoterms is required for a non UEE member`);
@ -107,12 +120,14 @@ module.exports = function(Self) {
throw new UserError(`Customs agent is required for a non UEE member`);
delete args.ctx; // Remove unwanted properties
const updatedAddress = await address.updateAttributes(ctx.args, options);
await tx.commit();
const updatedAddress = await address.updateAttributes(ctx.args, myOptions);
if (tx) await tx.commit();
return updatedAddress;
} catch (e) {
await tx.rollback();
if (tx) await tx.rollback();
throw e;
}
};

View File

@ -4,14 +4,15 @@ module.exports = Self => {
Self.remoteMethod('updateFiscalData', {
description: 'Updates fiscal data of a client',
accessType: 'WRITE',
accepts: [{
accepts: [
{
arg: 'ctx',
type: 'Object',
type: 'object',
http: {source: 'context'}
},
{
arg: 'id',
type: 'Number',
type: 'number',
description: 'The client id',
http: {source: 'path'}
},
@ -94,7 +95,8 @@ module.exports = Self => {
{
arg: 'despiteOfClient',
type: 'number'
}],
}
],
returns: {
arg: 'res',
type: 'string',
@ -106,14 +108,25 @@ module.exports = Self => {
}
});
Self.updateFiscalData = async(ctx, clientId) => {
Self.updateFiscalData = async(ctx, clientId, options) => {
let tx;
const myOptions = {};
const models = Self.app.models;
const args = ctx.args;
const userId = ctx.req.accessToken.userId;
const isSalesAssistant = await models.Account.hasRole(userId, 'salesAssistant');
const $t = ctx.req.__;
const client = await models.Client.findById(clientId);
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const isSalesAssistant = await models.Account.hasRole(userId, 'salesAssistant', myOptions);
const client = await models.Client.findById(clientId, null, myOptions);
if (!isSalesAssistant && client.isTaxDataChecked)
throw new UserError(`You can't make changes on a client with verified data`);
@ -139,13 +152,21 @@ module.exports = Self => {
})
};
await models.ClientLog.create(logRecord);
await models.ClientLog.create(logRecord, myOptions);
}
// Remove unwanted properties
delete args.ctx;
delete args.id;
return client.updateAttributes(args);
const updatedClient = await client.updateAttributes(args, myOptions);
if (tx) await tx.commit();
return updatedClient;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};

View File

@ -2,42 +2,50 @@ module.exports = Self => {
Self.remoteMethodCtx('uploadFile', {
description: 'Upload and attach a file to a client',
accessType: 'WRITE',
accepts: [{
accepts: [
{
arg: 'id',
type: 'Number',
type: 'number',
description: 'The client id',
http: {source: 'path'}
}, {
},
{
arg: 'warehouseId',
type: 'Number',
type: 'number',
description: 'The warehouse id',
required: true
}, {
},
{
arg: 'companyId',
type: 'Number',
type: 'number',
description: 'The company id',
required: true
}, {
},
{
arg: 'dmsTypeId',
type: 'Number',
type: 'number',
description: 'The dms type id',
required: true
}, {
},
{
arg: 'reference',
type: 'String',
type: 'string',
required: true
}, {
},
{
arg: 'description',
type: 'String',
type: 'string',
required: true
}, {
},
{
arg: 'hasFile',
type: 'Boolean',
type: 'boolean',
description: 'True if has an attached file',
required: true
}],
}
],
returns: {
type: 'Object',
type: 'object',
root: true
},
http: {
@ -46,31 +54,39 @@ module.exports = Self => {
}
});
Self.uploadFile = async(ctx, id) => {
Self.uploadFile = async(ctx, id, options) => {
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const promises = [];
const tx = await Self.beginTransaction({});
try {
const options = {transaction: tx};
const uploadedFiles = await models.Dms.uploadFile(ctx, options);
const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions);
uploadedFiles.forEach(dms => {
const newClientDms = models.ClientDms.create({
clientFk: id,
dmsFk: dms.id
}, options);
}, myOptions);
promises.push(newClientDms);
});
const resolvedPromises = await Promise.all(promises);
const resolvedPromises = await Promise.all(promises, myOptions);
await tx.commit();
if (tx) await tx.commit();
return resolvedPromises;
} catch (err) {
await tx.rollback();
throw err;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};

View File

@ -1,17 +1,13 @@
module.exports = Self => {
Self.remoteMethod('createWithInsurance', {
description: 'Creates both classification and one insurance',
accepts: [{
accepts: [
{
arg: 'data',
type: 'object',
http: {source: 'body'}
}, {
arg: 'context',
type: 'object',
http: function(ctx) {
return ctx;
}
}],
],
returns: {
root: true,
type: 'boolean'
@ -22,29 +18,36 @@ module.exports = Self => {
}
});
Self.createWithInsurance = async(data, ctx) => {
const tx = await Self.beginTransaction({});
Self.createWithInsurance = async(data, options) => {
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
let options = {transaction: tx};
const newClassification = await Self.create({
client: data.clientFk,
started: data.started
}, options);
}, myOptions);
await models.CreditInsurance.create({
creditClassification: newClassification.id,
credit: data.credit,
grade: data.grade
}, options);
}, myOptions);
await tx.commit();
if (tx) await tx.commit();
return newClassification;
} catch (e) {
await tx.rollback();
if (tx) await tx.rollback();
throw e;
}
};

View File

@ -1,64 +1,26 @@
const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
const models = require('vn-loopback/server/server').models;
describe('Client createWithInsurance', () => {
const activeCtx = {
accessToken: {userId: 1101},
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
const ctx = {req: activeCtx};
activeCtx.http.req.__ = value => {
return value;
};
it('should verify the classifications and insurances are untainted', async() => {
let classifications = await app.models.CreditClassification.find();
let insurances = await app.models.CreditInsurance.find();
expect(classifications.length).toEqual(5);
expect(insurances.length).toEqual(3);
});
it('should not create the insurance if couldnt create the classification', async() => {
let error;
let data = {clientFk: null, started: Date.now(), credit: 999, grade: 255};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
await app.models.CreditClassification.createWithInsurance(data, ctx)
.catch(e => {
error = e;
});
expect(error.toString()).toBe('Error: ER_BAD_NULL_ERROR: Column \'client\' cannot be null');
let classifications = await app.models.CreditClassification.find();
let insurances = await app.models.CreditInsurance.find();
expect(classifications.length).toEqual(5);
expect(insurances.length).toEqual(3);
});
it('should create a new client credit classification with insurance', async() => {
let data = {clientFk: 1101, started: Date.now(), credit: 999, grade: 255};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
let result = await app.models.CreditClassification.createWithInsurance(data, ctx);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const data = {clientFk: 1101, started: Date.now(), credit: 999, grade: 255};
const result = await models.CreditClassification.createWithInsurance(data, options);
expect(result.client).toEqual(1101);
let classifications = await app.models.CreditClassification.find();
let insurances = await app.models.CreditInsurance.find();
const classifications = await models.CreditClassification.find();
const insurances = await models.CreditInsurance.find();
expect(classifications.length).toEqual(6);
expect(insurances.length).toEqual(4);
// restore
await app.models.CreditClassification.destroyById(result.id);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -1,14 +1,21 @@
const totalGreuge = require('../sumAmount');
const models = require('vn-loopback/server/server').models;
describe('Greuge totalGreuge()', () => {
it('should call the sumAmount method', async() => {
let clientFk = 1;
let self = jasmine.createSpyObj('self', ['remoteMethod', 'rawSql']);
self.rawSql.and.returnValue(Promise.resolve([{sumAmount: 6000}]));
totalGreuge(self);
const tx = await models.Client.beginTransaction({});
let result = await self.sumAmount(clientFk);
try {
const options = {transaction: tx};
const clientId = 1;
const result = await models.Client.sumAmount(clientId, options);
expect(result).toBe(6000);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -18,10 +18,15 @@ module.exports = Self => {
}
});
Self.sumAmount = async clientFk => {
let query = `SELECT SUM(amount) AS sumAmount FROM vn.greuge WHERE clientFk = ?`;
Self.sumAmount = async(clientFk, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `SELECT SUM(amount) AS sumAmount FROM vn.greuge WHERE clientFk = ?`;
try {
let [response] = await Self.rawSql(query, [clientFk]);
const [response] = await Self.rawSql(query, [clientFk], myOptions);
return response ? response.sumAmount : 0;
} catch (e) {

View File

@ -7,23 +7,25 @@ module.exports = Self => {
accepts: [
{
arg: 'filter',
type: 'Object',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string',
http: {source: 'query'}
}, {
},
{
arg: 'clientId',
type: 'Number',
type: 'number',
description: 'The client id',
required: true,
}, {
},
{
arg: 'companyId',
type: 'Number',
type: 'number',
description: 'The company id',
required: true,
}
],
returns: {
type: ['Object'],
type: ['object'],
root: true
},
http: {
@ -32,8 +34,13 @@ module.exports = Self => {
}
});
Self.filter = async(filter, clientId, companyId) => {
let stmt = new ParameterizedSQL(
Self.filter = async(filter, clientId, companyId, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const stmt = new ParameterizedSQL(
`SELECT * FROM (
SELECT
r.id,
@ -75,8 +82,8 @@ module.exports = Self => {
JOIN vn.company c ON c.id = i.companyFk
WHERE i.clientFk = ? AND i.companyFk = ?
ORDER BY payed DESC, created DESC
) t
ORDER BY payed DESC, created DESC`, [
) t ORDER BY payed DESC, created DESC`,
[
clientId,
companyId,
clientId,
@ -85,6 +92,7 @@ module.exports = Self => {
);
stmt.merge(Self.makeLimit(filter));
return await Self.rawStmt(stmt);
return Self.rawStmt(stmt, myOptions);
};
};

View File

@ -1,12 +1,22 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('receipt filter()', () => {
it('should return the receipts', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const filter = {limit: 20};
const clientId = 1101;
const companyId = 442;
let result = await app.models.Receipt.filter(filter, clientId, companyId);
const result = await models.Receipt.filter(filter, clientId, companyId, options);
expect(result.length).toBeGreaterThan(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -21,14 +21,20 @@ module.exports = Self => {
}
});
Self.hasActiveRecovery = async id => {
let result = await Self.rawSql(
`SELECT count(*) AS hasActiveRecovery
Self.hasActiveRecovery = async(id, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `
SELECT count(*) AS hasActiveRecovery
FROM vn.recovery
WHERE clientFk = ?
AND IFNULL(finished,CURDATE()) >= CURDATE();`,
[id]
);
return result[0].hasActiveRecovery != 0;
AND IFNULL(finished,CURDATE()) >= CURDATE();
`;
const [result] = await Self.rawSql(query, [id], myOptions);
return result.hasActiveRecovery != 0;
};
};

View File

@ -1,15 +1,35 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('client hasActiveRecovery', () => {
it(`should return false if the client doesn't owes`, async() => {
let hasActiveRecovery = await app.models.Recovery.hasActiveRecovery(1101);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const hasActiveRecovery = await models.Recovery.hasActiveRecovery(1101, options);
expect(hasActiveRecovery).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
it('should return true if the client owes', async() => {
let hasActiveRecovery = await app.models.Recovery.hasActiveRecovery(1102);
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const hasActiveRecovery = await models.Recovery.hasActiveRecovery(1102, options);
expect(hasActiveRecovery).toBeTruthy();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});

View File

@ -6,22 +6,24 @@ module.exports = Self => {
Self.remoteMethod('send', {
description: 'Sends SMS to a destination phone',
accessType: 'WRITE',
accepts: [{
accepts: [
{
arg: 'destinationFk',
type: 'Integer'
type: 'integer'
},
{
arg: 'destination',
type: 'String',
type: 'string',
required: true,
},
{
arg: 'message',
type: 'String',
type: 'string',
required: true,
}],
}
],
returns: {
type: 'Object',
type: 'object',
root: true
},
http: {
@ -82,6 +84,7 @@ module.exports = Self => {
};
const sms = await Self.create(newSms);
if (statusCode != 200)
throw new UserError(`We weren't able to send this SMS`);