salix/services/loopback/common/methods/client/activeSalesPerson.js

74 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-11-21 10:59:43 +00:00
module.exports = Client => {
2017-09-27 05:22:40 +00:00
Client.remoteMethod('activeSalesPerson', {
description: 'Returns actives workers with salesperson role',
2017-09-27 05:22:40 +00:00
accessType: 'READ',
accepts: [{
arg: 'filter',
type: 'Object',
required: false,
description: 'Filter defining where and paginated data',
http: {source: 'query'}
}],
returns: {
arg: 'data',
type: 'Worker',
2017-09-27 05:22:40 +00:00
root: true
},
http: {
path: `/activeSalesPerson`,
verb: 'get'
}
});
Client.activeSalesPerson = (filter, callback) => {
2017-09-27 07:25:33 +00:00
let skip = filter.skip || 0;
let limit = filter.limit || 10;
2017-11-21 10:50:37 +00:00
let where = getCondition(filter.where, limit, skip);
2017-09-27 05:22:40 +00:00
let query =
`SELECT em.id, em.firstName, em.name
FROM worker em
JOIN account.user ac ON em.userFk = ac.id
JOIN account.role r ON r.id = ac.role
2018-02-15 12:11:23 +00:00
WHERE ac.active ${where.sql}
ORDER BY em.name ASC
LIMIT ? OFFSET ?`;
2017-10-18 13:06:38 +00:00
Client.rawSql(query, where.params).then(
response => callback(null, formatSalesPerson(response)),
err => callback(err)
);
2017-09-27 05:22:40 +00:00
};
2017-09-27 07:25:33 +00:00
2017-11-21 10:50:37 +00:00
function getCondition(where, limit, skip) {
let out = {
sql: '',
params: []
};
if (where && where.or) {
out.sql = `AND (em.firstName regexp ? OR em.name regexp ?)`;
2017-11-21 10:50:37 +00:00
where.or.forEach(val => {
Object.keys(val).forEach(key => {
out.params.push(val[key].regexp);
});
});
}
out.params.push(parseInt(limit, 10));
out.params.push(parseInt(skip, 10));
2017-10-18 13:06:38 +00:00
return out;
2017-09-28 07:13:42 +00:00
}
2017-10-18 13:06:38 +00:00
function formatSalesPerson(response) {
2017-09-28 07:13:42 +00:00
let results = [];
2017-10-18 13:06:38 +00:00
response.forEach(person => {
2017-09-28 07:13:42 +00:00
results.push({
id: person.id,
name: `${person.firstName} ${person.name}`
2017-09-28 07:13:42 +00:00
});
});
2017-09-27 07:25:33 +00:00
2017-09-28 07:13:42 +00:00
return results;
2017-09-27 07:25:33 +00:00
}
2017-11-21 10:59:43 +00:00
};