2017-10-18 10:51:33 +00:00
|
|
|
module.exports = (Vehicle) => {
|
|
|
|
Vehicle.remoteMethod('activeDrivers', {
|
2017-10-17 10:22:19 +00:00
|
|
|
description: 'returns actives employees with driver role',
|
|
|
|
accessType: 'READ',
|
|
|
|
accepts: [{
|
|
|
|
arg: 'filter',
|
|
|
|
type: 'Object',
|
|
|
|
required: false,
|
|
|
|
description: 'Filter defining where and paginated data',
|
|
|
|
http: {source: 'query'}
|
|
|
|
}],
|
|
|
|
returns: {
|
|
|
|
arg: 'data',
|
|
|
|
type: 'Employee',
|
|
|
|
root: true
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/activeDrivers`,
|
|
|
|
verb: 'get'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2017-10-18 10:51:33 +00:00
|
|
|
Vehicle.activeDrivers = (filter, callback) => {
|
2017-10-17 10:22:19 +00:00
|
|
|
let skip = filter.skip || 0;
|
|
|
|
let limit = filter.limit || 10;
|
|
|
|
let where = getCondition(filter.where);
|
|
|
|
// TODO: change salesPerson role to Driver role when it will be created
|
|
|
|
let query = `SELECT em.id, em.name, em.surname
|
|
|
|
FROM Employee em
|
|
|
|
JOIN Account ac ON em.userFk = ac.id
|
|
|
|
JOIN Role ON Role.id = ac.roleFK
|
|
|
|
WHERE ac.active AND Role.\`name\`='salesPerson' ${where}
|
|
|
|
ORDER BY em.name ASC
|
|
|
|
LIMIT ${limit} OFFSET ${skip}`;
|
|
|
|
|
2017-10-18 10:51:33 +00:00
|
|
|
Vehicle.rawSql(query, [], callback)
|
2017-10-17 10:22:19 +00:00
|
|
|
.then(response => {
|
|
|
|
callback(null, formatDriver(response));
|
|
|
|
})
|
|
|
|
.catch(reject => {
|
|
|
|
callback(reject, null);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
function getCondition(where) {
|
|
|
|
let out = [];
|
|
|
|
if(typeof where === 'object') {
|
|
|
|
Object.keys(where).forEach((k) => {
|
|
|
|
let value = where[k];
|
|
|
|
if (typeof value === 'number') {
|
|
|
|
out.push(`em.${k}=${value}`);
|
|
|
|
} else if (typeof value === 'string') {
|
|
|
|
out.push(`em.${k}='${value}'`);
|
|
|
|
} else if (typeof value === 'boolean' || value === null) {
|
|
|
|
out.push(`em.${k} IS ${String(value).toUpperCase()}`);
|
|
|
|
} else if (Object.keys(value).length) {
|
|
|
|
let firstProperty = Object.keys(value)[0];
|
|
|
|
out.push(`em.${k} ${firstProperty} '${value[firstProperty]}'`);
|
|
|
|
} else {
|
|
|
|
throw new Error ('Error: unexpected type');
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return out.length ? `AND (${out.join(' AND ')})` : '';
|
|
|
|
}
|
|
|
|
|
|
|
|
function formatDriver (response) {
|
|
|
|
let results = [];
|
|
|
|
|
|
|
|
response.forEach( person => {
|
|
|
|
results.push({
|
|
|
|
id: person.id,
|
|
|
|
name: `${person.name} ${person.surname}`
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
return results;
|
|
|
|
}
|
|
|
|
};
|