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

64 lines
2.1 KiB
JavaScript

const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const buildFilter = require('../../filter.js').buildFilter;
const mergeFilters = require('../../filter.js').mergeFilters;
module.exports = Self => {
Self.remoteMethod('activeWorkersWithRole', {
description: 'Returns actives workers with salesperson role',
accessType: 'READ',
accepts: [{
arg: 'filter',
type: 'Object',
description: 'Filter defining where and paginated data',
required: true
}],
returns: {
type: 'Worker',
root: true
},
http: {
path: `/activeWorkersWithRole`,
verb: 'get'
}
});
Self.activeWorkersWithRole = async filter => {
let conn = Self.dataSource.connector;
if (filter.where && filter.where.and && Array.isArray(filter.where.and)) {
let where = {};
filter.where.and.forEach(element => {
where[Object.keys(element)[0]] = Object.values(element)[0];
});
filter.where = where;
}
let clientFilter = Object.assign({}, filter);
clientFilter.where = buildFilter(filter.where, (param, value) => {
switch (param) {
case 'role':
return {'r.name': value};
case 'firstName':
return {or: [{'w.firstName': {like: `%${value}%`}}, {'w.name': {like: `%${value}%`}}]};
case 'id':
return {'w.id': value};
}
});
let myFilter = {
where: {'u.active': true}
};
console.log(filter.where);
myFilter = mergeFilters(myFilter, clientFilter);
let stmt = new ParameterizedSQL(
`SELECT DISTINCT w.id, w.firstName, w.name
FROM worker w
JOIN account.user u ON u.id = w.userFk
JOIN account.roleRole i ON i.role = u.role
JOIN account.role r ON r.id = i.inheritsFrom`
);
stmt.merge(conn.makeSuffix(myFilter));
return await conn.executeStmt(stmt);
};
};