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

74 lines
2.1 KiB
JavaScript

module.exports = Client => {
Client.remoteMethod('activeSalesPerson', {
description: 'Returns actives workers with salesperson role',
accessType: 'READ',
accepts: [{
arg: 'filter',
type: 'Object',
required: false,
description: 'Filter defining where and paginated data',
http: {source: 'query'}
}],
returns: {
arg: 'data',
type: 'Worker',
root: true
},
http: {
path: `/activeSalesPerson`,
verb: 'get'
}
});
Client.activeSalesPerson = (filter, callback) => {
let skip = filter.skip || 0;
let limit = filter.limit || 10;
let where = getCondition(filter.where, limit, skip);
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
WHERE ac.active ${where.sql}
ORDER BY em.name ASC
LIMIT ? OFFSET ?`;
Client.rawSql(query, where.params).then(
response => callback(null, formatSalesPerson(response)),
err => callback(err)
);
};
function getCondition(where, limit, skip) {
let out = {
sql: '',
params: []
};
if (where && where.or) {
out.sql = `AND (em.firstName regexp ? OR em.name regexp ?)`;
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));
return out;
}
function formatSalesPerson(response) {
let results = [];
response.forEach(person => {
results.push({
id: person.id,
name: `${person.firstName} ${person.name}`
});
});
return results;
}
};