salix/modules/worker/back/methods/worker/search.js

71 lines
2.3 KiB
JavaScript

const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
module.exports = Self => {
Self.remoteMethodCtx('search', {
description: 'Returns an array of search results for a specified worker',
accepts: [{
arg: 'filter',
type: 'object',
description: 'Filter to define conditions and paginate the data.',
required: true
},
{
arg: 'departmentCodes',
type: ['string'],
description: 'Department codes to search workers',
}],
returns: {
type: ['object'],
root: true
},
http: {
path: `/search`,
verb: 'GET'
}
});
Self.search = async(ctx, filter, departmentCodes) => {
const models = Self.app.models;
const conn = Self.dataSource.connector;
if (departmentCodes) {
const departments = await models.Department.find({
fields: ['id', 'sons'],
where: {code: {inq: departmentCodes}}
});
const allLeaves = await getAllLeaves(ctx, departments);
const where = {'departmentFk': {inq: allLeaves}};
filter = mergeFilters(filter, {where});
}
const stmt = new ParameterizedSQL(`
SELECT *
FROM(
SELECT w.id, w.code, u.name, u.nickname, u.active, wd.departmentFk
FROM worker w
JOIN account.user u ON u.id = w.id
LEFT JOIN workerDepartment wd ON wd.workerFk = w.id
) w`);
stmt.merge(conn.makeSuffix(filter));
return conn.executeStmt(stmt);
};
async function getAllLeaves(ctx, departments) {
const models = Self.app.models;
const leaves = [];
for (const department of departments) {
if (department.sons > 0) {
const subLeaves = await models.Department.getLeaves(ctx, department.id, null);
const grandLeaves = await getAllLeaves(ctx, subLeaves);
leaves.push(...grandLeaves);
}
leaves.push(department.id);
}
return leaves;
}
};