Select Git revision
employees.js
employees.js 20.30 KiB
/*
Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
This file is part of simcaq-node.
simcaq-node is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
simcaq-node is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with simcaq-node. If not, see <https://www.gnu.org/licenses/>.
*/
const express = require('express');
const employeesApp = express.Router();
const libs = `${process.cwd()}/libs`;
const log = require(`${libs}/log`)(module);
const squel = require('squel');
const query = require(`${libs}/middlewares/query`).query;
const response = require(`${libs}/middlewares/response`);
const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);
const id2str = require(`${libs}/middlewares/id2str`);
const config = require(`${libs}/config`);
const addMissing = require(`${libs}/middlewares/addMissing`);
const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
let rqfTeacher = new ReqQueryFields();
let rqfSchool = new ReqQueryFields();
employeesApp.use(cache('15 day'));
// Returns a tuple of start and ending years of the complete enrollments dataset.
employeesApp.get('/year_range', (req, res, next) => {
req.sql.from('docente')
.field('MIN(docente.ano_censo)', 'start_year')
.field('MAX(docente.ano_censo)', 'end_year');
next();
}, query, response('range'));
employeesApp.get('/years', (req, res, next) => {
req.sql.from('docente').
field('DISTINCT docente.ano_censo', 'year');
next();
}, query, response('years'));
employeesApp.get('/source', (req, res, next) => {
req.sql.from('fonte')
.field('fonte', 'source')
.where('tabela = \'docente\'');
next();
}, query, response('source'));
employeesApp.get('/adm_dependency_detailed', (req, res, next) => {
req.result = [];
for(let i = 1; i <= 6; ++i) {
req.result.push({
id: i,
name: id2str.admDependencyPriv(i)
});
};
next();
}, response('adm_dependency_detailed'));
employeesApp.get('/adm_dependency', (req, res, next) => {
req.result = [];
for(let i = 1; i <= 4; ++i) {
req.result.push({
id: i,
name: id2str.admDependency(i)
});
};
next();
}, response('adm_dependency'));
employeesApp.get('/location', (req, res, next) => {
req.result = [];
for(let i = 1; i <= 2; ++i) {
req.result.push({
id: i,
name: id2str.location(i)
});
};
next();
}, response('location'));
employeesApp.get('/rural_location', (req, res, next) => {
req.result = [
{id: 1, name: "Urbana"},
{id: 2, name: "Rural"},
{id: 3, name: "Rural - Área de assentamento"},
{id: 4, name: "Rural - Terra indígena"},
{id: 5, name: "Rural - Área remanescente de quilombos"},
{id: 6, name: "Rural - Unidade de uso sustentável"}
];
next();
}, response('rural_location'));
employeesApp.get('/function', (req, res, next) => {
req.result = [
{id: 0, name: "Administrativos"},
{id: 1, name: "Serviços Gerais"},
{id: 2, name: "Bibliotecário"},
{id: 3, name: "Saúde"},
{id: 4, name: "Coordenador"},
{id: 5, name: "Fonoaudiólogo"},
{id: 6, name: "Nutricionista"},
{id: 7, name: "Psicólogo"},
{id: 8, name: "Alimentação"},
{id: 9, name: "Pedagogia"},
{id: 10, name: "Secretário"},
{id: 11, name: "Segurança"},
{id: 12, name: "Monitores"},
{id: 99, name: "Não Classificado"}
];
next();
}, response('function'));
rqfSchool.addField({
name: 'filter',
field: false,
where: true
}).addField({
name: 'dims',
field: true,
where: false
}).addValue({
name: 'adm_dependency',
table: '@',
tableField: 'dependencia_adm_id',
resultField: 'adm_dependency_id',
where: {
relation: '=',
type: 'integer',
field: 'dependencia_adm_id'
}
}).addValue({
name: 'adm_dependency_detailed',
table: '@',
tableField: 'dependencia_adm_priv',
resultField: 'adm_dependency_detailed_id',
where: {
relation: '=',
type: 'integer',
field: 'dependencia_adm_priv'
}
}).addValue({
name: 'region',
table: 'regiao',
tableField: ['nome', 'id'],
resultField: ['region_name', 'region_id'],
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: 'id',
foreign: 'regiao_id',
foreignTable: '@'
}
}).addValue({
name: 'state',
table: 'estado',
tableField: ['nome', 'id'],
resultField: ['state_name', 'state_id'],
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: 'id',
foreign: 'estado_id',
foreignTable: '@'
}
}).addValueToField({
name: 'city',
table: 'municipio',
tableField: ['nome', 'id'],
resultField: ['city_name', 'city_id'],
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: 'id',
foreign: 'municipio_id',
foreignTable: '@'
}
}, 'dims').addValueToField({
name: 'city',
table: 'municipio',
tableField: 'nome',
resultField: 'city_name',
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: 'id',
foreign: 'municipio_id',
foreignTable: '@'
}
}, 'filter').addValueToField({
name: 'school',
table: '@',
tableField: ['nome_escola', 'id'],
resultField: ['school_name', 'school_id'],
where: {
relation: '=',
type: 'integer',
field: 'id'
},
}, 'dims').addValueToField({
name: 'school',
table: '@',
tableField: 'escola_nome',
resultField: 'school_name',
where: {
relation: '=',
type: 'integer',
field: 'id'
},
}, 'filter').addValue({
name: 'location',
table: '@',
tableField: 'localizacao_id',
resultField: 'location_id',
where: {
relation: '=',
type: 'integer',
field: 'localizacao_id'
}
}).addValue({
name: 'diff_location',
table: '@',
tableField: 'localizacao_diferenciada_par',
resultField: 'diff_location_id_par',
where: {
relation: '=',
type: 'integer',
field: 'localizacao_diferenciada_par'
}
}).addValue({
name: 'rural_location',
table: '@',
tableField: 'localidade_area_rural',
resultField: 'rural_location_id',
where: {
relation: '=',
type: 'integer',
field: 'localidade_area_rural'
}
}).addValue({
name: 'function',
table: '@',
tableField: 'a',
resultField: 'function_id',
where: {
relation: '=',
type: 'integer',
field: 'a'
}
}).addValue({
name: 'min_year',
table: '@',
tableField: 'ano_censo',
resultField: 'year',
where: {
relation: '>=',
type: 'integer',
field: 'ano_censo'
}
}).addValue({
name: 'max_year',
table: '@',
tableField: 'ano_censo',
resultField: 'year',
where: {
relation: '<=',
type: 'integer',
field: 'ano_censo'
}
});
rqfTeacher.addField({
name: 'filter',
field: false,
where: true
}).addField({
name: 'dims',
field: true,
where: false
}).addValue({
name: 'adm_dependency',
table: '@',
tableField: 'dependencia_adm_id',
resultField: 'adm_dependency_id',
where: {
relation: '=',
type: 'integer',
field: 'dependencia_adm_id'
}
}).addValue({
name: 'adm_dependency_detailed',
table: '@',
tableField: 'dependencia_adm_priv',
resultField: 'adm_dependency_detailed_id',
where: {
relation: '=',
type: 'integer',
field: 'dependencia_adm_priv'
}
}).addValue({
name: 'region',
table: 'regiao',
tableField: ['nome', 'id'],
resultField: ['region_name', 'region_id'],
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: 'id',
foreign: 'regiao_id',
foreignTable: '@'
}
}).addValue({
name: 'state',
table: 'estado',
tableField: ['nome', 'id'],
resultField: ['state_name', 'state_id'],
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: 'id',
foreign: 'estado_id',
foreignTable: '@'
}
}).addValueToField({
name: 'city',
table: 'municipio',
tableField: ['nome', 'id'],
resultField: ['city_name', 'city_id'],
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: 'id',
foreign: 'municipio_id',
foreignTable: '@'
}
}, 'dims').addValueToField({
name: 'city',
table: 'municipio',
tableField: 'nome',
resultField: 'city_name',
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: 'id',
foreign: 'municipio_id',
foreignTable: '@'
}
}, 'filter').addValueToField({
name: 'school',
table: 'escola',
tableField: ['nome_escola', 'id'],
resultField: ['school_name', 'school_id'],
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: ['id','ano_censo'],
foreign: ['escola_id','ano_censo'],
foreignTable: '@'
}
}, 'dims').addValueToField({
name: 'school',
table: 'escola',
tableField: 'nome_escola',
resultField: 'school_name',
where: {
relation: '=',
type: 'integer',
field: 'id'
},
join: {
primary: ['id','ano_censo'],
foreign: ['escola_id','ano_censo'],
foreignTable: '@'
}
}, 'filter').addValue({
name: 'location',
table: '@',
tableField: 'localizacao_id',
resultField: 'location_id',
where: {
relation: '=',
type: 'integer',
field: 'localizacao_id'
}
}).addValue({
name: 'rural_location',
table: '@',
tableField: 'localidade_area_rural',
resultField: 'rural_location_id',
where: {
relation: '=',
type: 'integer',
field: 'localidade_area_rural'
}
}).addValue({
name: 'min_year',
table: '@',
tableField: 'ano_censo',
resultField: 'year',
where: {
relation: '>=',
type: 'integer',
field: 'ano_censo'
}
}).addValue({
name: 'max_year',
table: '@',
tableField: 'ano_censo',
resultField: 'year',
where: {
relation: '<=',
type: 'integer',
field: 'ano_censo'
}
});
function formatFunction(queryOriginal,reqDims) {
delete reqDims.size;
delete reqDims.function;
let dims = Object.keys(reqDims); //se for = 0, apenas lidamos com a dimensao function. Se for = 1, lidamos com function mais a dimensao q esta nesse array.
let name = {
qtde_admin: "Administrativos",
qtde_servicos_gerais: "Serviços Gerais",
qtde_bibliotecario: "Bibliotecário",
qtde_saude: "Saúde",
qtde_coordenador: "Coordenador",
qtde_fono: "Fonoaudiólogo",
qtde_nutricionista: "Nutricionista",
qtde_psicologo: "Psicólogo",
qtde_alimentacao: "Alimentação",
qtde_pedagogia: "Pedagogia",
qtde_secretario: "Secretário",
qtde_seguranca: "Segurança",
qtde_monitores: "Monitores",
qtde_null: "Não Classificado"
}
let resultObj = []
//Nesse caso apenas precisamos acertar as dimensoes que o banco retorna, ou seja, criando um objeto para cada funcao de funcionario
if (dims.length == 0) {
queryOriginal.forEach((result) => {
Object.keys(result).forEach(function(key,index) {
if (key.includes("qtde")) {
let newObj = {
year: result["year"],
function_id: index,
function_name: name[key],
total: result[key]
}
resultObj.push(newObj);
}
})
})
}
//Nesse caso precisamos copiar o id e name da variavel que está na dimensão junto com funcionarios por função
else {
queryOriginal.forEach((result) => {
Object.keys(result).forEach(function(key,index) {
if (key.includes("qtde")) {
let newObj = {
year: result["year"],
function_id: index,
function_name: name[key],
total: result[key]
}
newObj[dims[0] + "_id"] = result[dims[0] + "_id"];
newObj[dims[0] + "_name"] = result[dims[0] + "_name"];
resultObj.push(newObj);
}
})
})
}
return resultObj;
}
function matchQueries(queryTotal, queryPartial) {
let match = [];
queryTotal.forEach((result) => {
let newObj = {};
let keys = Object.keys(result);
keys.forEach((key) => {
newObj[key] = result[key];
});
let index = keys.indexOf('total');
if(index > -1) keys.splice(index, 1);
let objMatch = null;
for(let i = 0; i < queryPartial.length; ++i) {
let partial = queryPartial[i];
let foundMatch = true;
for(let j = 0; j < keys.length; ++j) {
let key = keys[j];
if(partial[key] !== result[key]) {
foundMatch = false;
break;
}
}
if(foundMatch) {
objMatch = partial;
break;
}
}
if(objMatch) {
newObj.total = result.total - objMatch.total;
if (newObj.total > 0) {
newObj.total_employees = result.total;
newObj.total_teachers = objMatch.total
match.push(newObj);
}
}
});
return match;
}
employeesApp.get('/', rqfSchool.parse(), (req, res, next) => {
req.allTeacher = {}
req.schoolTable = {}
if ("function" in req.dims) {
delete req.dims.function;
req.sql.field('SUM(funcionarios_por_escola.total)', 'qtde_null')
.field('funcionarios_por_escola.ano_censo', 'year')
.from('funcionarios_por_escola')
.group('funcionarios_por_escola.ano_censo')
.order('funcionarios_por_escola.ano_censo')
.where('funcionarios_por_escola.ano_censo <> 2009 or funcionarios_por_escola.estado_id <> 42')
} else {
delete req.dims.function;
req.sql.field('SUM(funcionarios_por_escola.total)', 'total')
.field('funcionarios_por_escola.ano_censo', 'year')
.from('funcionarios_por_escola')
.group('funcionarios_por_escola.ano_censo')
.order('funcionarios_por_escola.ano_censo')
.where('funcionarios_por_escola.ano_censo <> 2009 or funcionarios_por_escola.estado_id <> 42')
}
next();
}, rqfSchool.build(), query, rqfSchool.parse(), id2str.transform(), (req, res, next) => {
req.allTeacher = req.result;
req.resetSql();
if ("function" in req.dims) {
req.sql.field('SUM(CASE WHEN escola.qt_prof_admin = 88888 THEN 0 ELSE escola.qt_prof_admin END)', 'qtde_admin')
.field('SUM(CASE WHEN escola.qtde_prof_servicos_gerais = 88888 THEN 0 ELSE escola.qtde_prof_servicos_gerais END) AS qtde_servicos_gerais')
.field('SUM(CASE WHEN escola.qtde_prof_bibliotecario = 88888 THEN 0 ELSE escola.qtde_prof_bibliotecario END)', 'qtde_bibliotecario')
.field('SUM(CASE WHEN escola.qtde_prof_saude = 88888 THEN 0 ELSE escola.qtde_prof_saude END)','qtde_saude')
.field('SUM(CASE WHEN escola.qtde_prof_coordenador = 88888 THEN 0 ELSE escola.qtde_prof_coordenador END)','qtde_coordenador')
.field('SUM(CASE WHEN escola.qtde_prof_fono = 88888 THEN 0 ELSE escola.qtde_prof_fono END)','qtde_fono')
.field('SUM(CASE WHEN escola.qtde_prof_nutricionista = 88888 THEN 0 ELSE escola.qtde_prof_nutricionista END)', 'qtde_nutricionista')
.field('SUM(CASE WHEN escola.qtde_prof_psicologo = 88888 THEN 0 ELSE escola.qtde_prof_psicologo END)', 'qtde_psicologo')
.field('SUM(CASE WHEN escola.qtde_prof_alimentacao = 88888 THEN 0 ELSE escola.qtde_prof_alimentacao END)','qtde_alimentacao')
.field('SUM(CASE WHEN escola.qtde_prof_pedagogia = 88888 THEN 0 ELSE escola.qtde_prof_pedagogia END)', 'qtde_pedagogia')
.field('SUM(CASE WHEN escola.qtde_prof_secretario = 88888 THEN 0 ELSE escola.qtde_prof_secretario END)','qtde_secretario')
.field('SUM(CASE WHEN escola.qtde_prof_seguranca = 88888 THEN 0 ELSE escola.qtde_prof_seguranca END)','qtde_seguranca')
.field('SUM(CASE WHEN escola.qtde_prof_monitores = 88888 THEN 0 ELSE escola.qtde_prof_monitores END)', 'qtde_monitores')
.field("'Brasil'", 'name')
.field('escola.ano_censo', 'year')
.from('escola')
.group('escola.ano_censo')
.order('escola.ano_censo')
.where('(escola.situacao_funcionamento_pareada = 1) AND (escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1) AND (escola.dependencia_adm_id = 2 OR escola.dependencia_adm_id = 3 OR escola.dependencia_adm_id = 4) and ano_censo >= 2019');
delete req.dims.function;
} else {
req.sql.field('SUM(CASE WHEN escola.qt_prof_admin = 88888 THEN 0 ELSE escola.qt_prof_admin END) + SUM(CASE WHEN escola.qtde_prof_servicos_gerais = 88888 THEN 0 ELSE escola.qtde_prof_servicos_gerais END) + SUM(CASE WHEN escola.qtde_prof_bibliotecario = 88888 THEN 0 ELSE escola.qtde_prof_bibliotecario END) + SUM(CASE WHEN escola.qtde_prof_saude = 88888 THEN 0 ELSE escola.qtde_prof_saude END) + SUM(CASE WHEN escola.qtde_prof_coordenador = 88888 THEN 0 ELSE escola.qtde_prof_coordenador END) + SUM(CASE WHEN escola.qtde_prof_fono = 88888 THEN 0 ELSE escola.qtde_prof_fono END) + SUM(CASE WHEN escola.qtde_prof_nutricionista = 88888 THEN 0 ELSE escola.qtde_prof_nutricionista END) + SUM(CASE WHEN escola.qtde_prof_psicologo = 88888 THEN 0 ELSE escola.qtde_prof_psicologo END) + SUM(CASE WHEN escola.qtde_prof_alimentacao = 88888 THEN 0 ELSE escola.qtde_prof_alimentacao END) + SUM(CASE WHEN escola.qtde_prof_pedagogia = 88888 THEN 0 ELSE escola.qtde_prof_pedagogia END) + SUM(CASE WHEN escola.qtde_prof_secretario = 88888 THEN 0 ELSE escola.qtde_prof_secretario END) + SUM(CASE WHEN escola.qtde_prof_seguranca = 88888 THEN 0 ELSE escola.qtde_prof_seguranca END) + SUM(CASE WHEN escola.qtde_prof_monitores = 88888 THEN 0 ELSE escola.qtde_prof_monitores END)', 'total')
.field("'Brasil'", 'name')
.field('escola.ano_censo', 'year')
.from('escola')
.group('escola.ano_censo')
.order('escola.ano_censo')
.where('(escola.situacao_funcionamento_pareada = 1) AND (escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1) AND (escola.dependencia_adm_id = 2 OR escola.dependencia_adm_id = 3 OR escola.dependencia_adm_id = 4) and ano_censo >= 2019');
}
next();
}, rqfSchool.build(), query, rqfSchool.parse(), id2str.transform(), (req, res, next) => {
if ("function" in req.dims) {
let aux_employes = formatFunction(req.result, req.dims);
req.allTeacher = formatFunction(req.allTeacher, req.dims);
req.schoolTable = aux_employes;
} else {
req.schoolTable = req.result
}
if (req.filter.min_year <= 2018 && req.filter.max_year <= 2018) {
let aux_employees = req.allTeacher;
req.result = aux_employees;
} else if (req.filter.min_year >= 2019 && req.filter.max_year >= 2019) {
req.result = req.schoolTable;
} else if (req.filter.min_year <= 2018 && req.filter.max_year >= 2019) {
let aux_employees = req.allTeacher;
req.result = aux_employees.concat(req.schoolTable);
}
next();
}, response('employees'));
module.exports = employeesApp;