diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4a127f3796ffeec2fc82fe020336578e2010bef7..356b1c4bb62a490f2043bcaf264a4cd660bf03e1 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -10,23 +10,34 @@ variables: MONGO_URI: 'mongodb://mongo/app_name' NODE_ENV: 'test' -before_script: - - node -v - - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint - - npm install - - curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py - - python get-pip.py +#run_tests: +# stage: test +# before_script: +# - node -v +# - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha #gulp-eslint +# - npm install +# script: +# - ping -W1 -c1 mongo +# - sed -i -e 's/false/true/g' config.json +# - gulp build +# - gulp test +# tags: +# - node -run_tests: +regression_tests: stage: test + before_script: + - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint + - npm install + - gulp build && gulp & + - curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py + - python get-pip.py + - sleep 60 script: + - git clone https://gitlab.c3sl.ufpr.br/simcaq/lde-api-regression-test.git - - ping -W1 -c1 mongo - - sed -i -e 's/false/true/g' config.json - - gulp build - - gulp test - cd lde-api-regression-test - pip install -r requirements.txt - - python regression_test.py --compare + - python manage.py compare --verbose tags: - node diff --git a/CHANGELOG.md b/CHANGELOG.md index ce0f1edd653ca85f567c631ac1483f5c0467f870..c9ef25a349751667192b35369187f3fe57c40c8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,29 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 1.14.0 - 2020-06-17 +## Added +- Route school_location +- Route mesoregion +- Route microregion +## Changed +- City route now returns microregion_id and mesoregion_id +- Update classCount base filters +- Update classroom base query +- Update classroomCount base filters in school +- Removed addMissing from cub route +- Changed dailyChargeAmount filter pattern +- Enrollment now has mesoregion/microregion dims/filters +- Changed reqFilters in outOfSchool route +- School now has mesoregion/microregion dims/filters +- Teacher now has mesoregion/microregion dims/filters +- UnivesityEnrollment now has mesoregion/microregion dims/filters + ## 1.13.4 - 2020-06-05 - Arrangment filter in school indicator 2007-2019 +- Employees Indicator 2007-2019 ## 1.13.3 - 2020-05-21 -- Employees Indicator 2007-2019 ## 1.13.2 - 2020-05-21 ## Changed diff --git a/src/libs/convert/cineDetailed.js b/src/libs/convert/cineDetailed.js new file mode 100644 index 0000000000000000000000000000000000000000..e12117040aef3946cb7f4ca72c934daec7cbf038 --- /dev/null +++ b/src/libs/convert/cineDetailed.js @@ -0,0 +1,199 @@ +/* +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/>. +*/ +module.exports = function cineDetailed(id) { + switch (id) { + case 11: + return 'Programas básicos'; + case 111: + return 'Ciência da educação'; + case 112: + return 'Formação de professores de educação infantil'; + case 113: + return 'Formação de professores sem áreas específicas'; + case 114: + return 'Formação de professores em áreas específicas (exceto Letras)'; + case 115: + return 'Formação de professores de letras'; + case 188: + return 'Programas interdisciplinares abrangendo educação'; + case 211: + return 'Produção audiovisual, de mídia e cultural'; + case 212: + return 'Moda, design de interiores e desenho industrial'; + case 213: + return 'Belas artes'; + case 214: + return 'Artesanato'; + case 215: + return 'Música e artes cênicas'; + case 221: + return 'Religião e teologia'; + case 222: + return 'História e arqueologia'; + case 223: + return 'Filosofia e ética'; + case 231: + return 'Letras'; + case 288: + return 'Programas interdisciplinares abrangendo artes e humanidades'; + case 311: + return 'Economia'; + case 312: + return 'Ciências sociais e políticas'; + case 313: + return 'Psicologia'; + case 321: + return 'Jornalismo e reportagem'; + case 322: + return 'Biblioteconomia, informação e estudos arquivísticos'; + case 388: + return 'Programas interdisciplinares abrangendo ciências sociais, jornalismo e informação'; + case 411: + return 'Contabilidade e tributação'; + case 412: + return 'Finanças, bancos e seguros'; + case 413: + return 'Gestão e administração'; + case 414: + return 'Marketing e propaganda'; + case 415: + return 'Secretariado e trabalhos de escritório'; + case 416: + return 'Gestão comercial'; + case 421: + return 'Direito'; + case 488: + return 'Programas interdisciplinares abrangendo negócios, administração e direito'; + case 511: + return 'Biologia'; + case 512: + return 'Bioquímica e biotecnologia'; + case 521: + return 'Ciências ambientais'; + case 531: + return 'Química'; + case 532: + return 'Ciências da terra'; + case 533: + return 'Física'; + case 541: + return 'Matemática'; + case 542: + return 'Estatística'; + case 588: + return 'Programas interdisciplinares abrangendo ciências naturais, matemática e estatística'; + case 612: + return 'Infraestrutura e gestão de TIC'; + case 613: + return 'Produção de software'; + case 614: + return 'Ciência da computação'; + case 615: + return 'Gestão e desenvolvimento de sistemas de informação'; + case 616: + return 'Desenvolvimento de sistemas que integram software e hardware'; + case 688: + return 'Programas interdisciplinares abrangendo computação e Tecnologias da Informação e Comunicação (TIC)'; + case 710: + return 'Engenharia e profissões correlatas sem definição precisa'; + case 711: + return 'Engenharia química e de processos'; + case 712: + return 'Tecnologia de proteção ambiental'; + case 713: + return 'Eletricidade e energia'; + case 714: + return 'Eletrônica e automação'; + case 715: + return 'Engenharia mecânica e metalurgia'; + case 716: + return 'Veículos a motor, construção naval, aeronáutica, ferroviária e metroviária'; + case 721: + return 'Processamento de alimentos'; + case 722: + return 'Materiais'; + case 723: + return 'Têxteis (vestuário, calçados e couro)'; + case 724: + return 'Mineração e extração'; + case 725: + return 'Produção e processos de fabricação'; + case 731: + return 'Arquitetura e planejamento urbano'; + case 732: + return 'Engenharia civil e construção'; + case 788: + return 'Programas interdisciplinares abrangendo engenharia, produção e construção'; + case 811: + return 'Produção agrícola, agropecuária e zootecnia'; + case 812: + return 'Horticultura'; + case 821: + return 'Silvicultura'; + case 831: + return 'Pesca'; + case 841: + return 'Veterinária'; + case 888: + return 'Programas interdisciplinares abrangendo agricultura, silvicultura, pesca e veterinária'; + case 911: + return 'Odontologia'; + case 912: + return 'Medicina'; + case 913: + return 'Enfermagem'; + case 914: + return 'Tecnologia de diagnóstico e tratamento médico'; + case 915: + return 'Promoção, prevenção, terapia e reabilitação'; + case 916: + return 'Farmácia'; + case 917: + return 'Medicina e terapia tradicional e complementar'; + case 918: + return 'Saúde pública e saúde coletiva'; + case 921: + return 'Assistência a idosos e a deficientes'; + case 923: + return 'Serviço social'; + case 988: + return 'Programas interdisciplinares abrangendo saúde e bem-estar'; + case 1011: + return 'Serviços domésticos'; + case 1012: + return 'Serviços de beleza'; + case 1013: + return 'Serviços de alimentação'; + case 1014: + return 'Esportes e lazer'; + case 1015: + return 'Turismo e hotelaria'; + case 1022: + return 'Saúde e segurança no trabalho'; + case 1031: + return 'Setor militar e de defesa'; + case 1032: + return 'Proteção de pessoas e de propriedades'; + case 1041: + return 'Serviços de transporte'; + default: + return 'Não classificada'; + } +}; \ No newline at end of file diff --git a/src/libs/convert/cineGeral.js b/src/libs/convert/cineGeral.js new file mode 100644 index 0000000000000000000000000000000000000000..4f38e88a51ba2ea805c1359438922eb1b16505d9 --- /dev/null +++ b/src/libs/convert/cineGeral.js @@ -0,0 +1,48 @@ +/* +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/>. +*/ + +module.exports = function cineGeral(id) { + switch (id) { + case 0: + return 'Programas básicos'; + case 1: + return 'Educação'; + case 2: + return 'Artes e humanidades'; + case 3: + return 'Ciências sociais, jornalismo e informação'; + case 4: + return 'Negócios, administração e direito'; + case 5: + return 'Ciências naturais, matemática e estatística'; + case 6: + return 'Computação e Tecnologias da Informação e Comunicação (TIC)'; + case 7: + return 'Engenharia, produção e construção'; + case 8: + return 'Agricultura, silvicultura, pesca e veterinária'; + case 9: + return 'Saúde e bem-estar'; + case 10: + return 'Serviços'; + default: + return 'Não classificada'; + } +}; diff --git a/src/libs/convert/cineSpecific.js b/src/libs/convert/cineSpecific.js new file mode 100644 index 0000000000000000000000000000000000000000..8c900c350d49a4865b7df09e60e8933c4813e7c5 --- /dev/null +++ b/src/libs/convert/cineSpecific.js @@ -0,0 +1,99 @@ +/* +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: +return '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/>. +*/ + +module.exports = function cineSpecific(id) { + switch (id) { + case 1: + return 'Programas básicos'; + case 11: + return 'Educação'; + case 18: + return 'Programas interdisciplinares abrangendo educação'; + case 21: + return 'Artes'; + case 22: + return 'Humanidades (exceto línguas)'; + case 23: + return 'Línguas'; + case 28: + return 'Programas interdisciplinares abrangendo artes e humanidades'; + case 31: + return 'Ciências sociais e comportamentais'; + case 32: + return 'Jornalismo e informação'; + case 38: + return 'Programas interdisciplinares abrangendo ciências sociais, jornalismo e informação'; + case 41: + return 'Negócios e administração'; + case 42: + return 'Direito'; + case 48: + return 'Programas interdisciplinares abrangendo negócios, administração e direito'; + case 51: + return 'Ciências biológicas e correlatas'; + case 52: + return 'Meio ambiente'; + case 53: + return 'Ciências físicas'; + case 54: + return 'Matemática e estatística'; + case 58: + return 'Programas interdisciplinares abrangendo ciências naturais, matemática e estatística'; + case 61: + return 'Computação e Tecnologias da Informação e Comunicação (TIC)'; + case 68: + return 'Programas interdisciplinares abrangendo computação e Tecnologias da Informação e Comunicação (TIC)'; + case 71: + return 'Engenharia e profissões correlatas'; + case 72: + return 'Produção e processamento'; + case 73: + return 'Arquitetura e construção'; + case 78: + return 'Programas interdisciplinares abrangendo engenharia, produção e construção'; + case 81: + return 'Agricultura'; + case 82: + return 'Silvicultura'; + case 83: + return 'Pesca'; + case 84: + return 'Veterinária'; + case 88: + return 'Programas interdisciplinares abrangendo agricultura, silvicultura, pesca e veterinária'; + case 91: + return 'Saúde'; + case 92: + return 'Bem-estar'; + case 98: + return 'Programas interdisciplinares abrangendo saúde e bem-estar'; + case 101: + return 'Serviços pessoais'; + case 102: + return 'Higiene e serviços de saúde ocupacional'; + case 103: + return 'Serviços de segurança'; + case 104: + return 'Serviços de transporte'; + default: + return 'Não classificada'; + } +}; diff --git a/src/libs/convert/nightTime.js b/src/libs/convert/nightTime.js new file mode 100644 index 0000000000000000000000000000000000000000..1e84007145b7bf1af29d4f44dc057bd4860d5b6e --- /dev/null +++ b/src/libs/convert/nightTime.js @@ -0,0 +1,32 @@ +'use strict'; + +/* +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/>. +*/ + +module.exports = function nightTime(id) { + switch (id) { + case 0: + return 'Não'; + case 1: + return 'Sim'; + default: + return 'Curso a distância'; + } +}; \ No newline at end of file diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js index 327ce2a4ca31230f7599cf1ddca1ab744b04c554..78fd170dc392b106f6de7a7d628df15c7f0c430e 100644 --- a/src/libs/middlewares/id2str.js +++ b/src/libs/middlewares/id2str.js @@ -61,6 +61,9 @@ const academicOrganization = require(`${libs}/convert/academicOrganization`); const ocdeSpecific = require(`${libs}/convert/ocdeSpecific`); const ocdeGeral = require(`${libs}/convert/ocdeGeral`); const ocdeDetailed = require(`${libs}/convert/ocdeDetailed`); +const cineSpecific = require(`${libs}/convert/cineSpecific`); +const cineGeral = require(`${libs}/convert/cineGeral`); +const cineDetailed = require(`${libs}/convert/cineDetailed`); const academicLevel = require(`${libs}/convert/academicLevel`); const upperEducationMod = require(`${libs}/convert/upperEducationMod`); const studentDeficiency = require(`${libs}/convert/studentDeficiency`); @@ -80,6 +83,7 @@ const genderIES = require(`${libs}/convert/genderIES`); const deficiency = require(`${libs}/convert/studentDeficiency`); const govermentAgreement = require(`${libs}/convert/govermentAgreement`); const arrangement = require(`${libs}/convert/arrangement`); +const nightTime = require(`${libs}/convert/nightTime`); const ids = { gender_id: gender, @@ -129,13 +133,16 @@ const ids = { ocde_specific_id: ocdeSpecific, ocde_geral_id: ocdeGeral, ocde_detailed_id: ocdeDetailed, + cine_specific_id: cineSpecific, + cine_geral_id: cineGeral, + cine_detailed_id: cineDetailed, academic_level_id: academicLevel, upper_education_mod_id: upperEducationMod, student_deficiency_id: studentDeficiency, school_type_id: schoolType, upper_turn_id: upperTurn, is_free_id: booleanVariable, - night_time_id: booleanVariable, + night_time_id: nightTime, capital_id: booleanVariable, ethnic_group_ies_id: ethnicGroupIES, teacher_situation_id: teacherSituation, @@ -231,6 +238,9 @@ module.exports = { ocdeSpecific, ocdeGeral, ocdeDetailed, + cineSpecific, + cineGeral, + cineDetailed, academicLevel, upperEducationMod, studentDeficiency, @@ -251,5 +261,6 @@ module.exports = { deficiency, transport, govermentAgreement, - arrangement + arrangement, + nightTime }; diff --git a/src/libs/routes/api.js b/src/libs/routes/api.js index 7d312660f454b362e5988bf319e9742917cdcf42..45bdea870e8ec629ba3b8e877a62f0fed29bdeba 100644 --- a/src/libs/routes/api.js +++ b/src/libs/routes/api.js @@ -114,6 +114,14 @@ const university = require(`${libs}/routes/university`); const universityTeacher = require(`${libs}/routes/universityTeacher`); +const educationalBudget = require(`${libs}/routes/educationalBudget`); + +const schoolLocation = require(`${libs}/routes/schoolLocation`); + +const mesoregion = require(`${libs}/routes/mesoregion`); + +const microregion = require(`${libs}/routes/microregion`); + api.get('/', (req, res) => { res.json({ msg: 'SimCAQ API is running' }); }); @@ -163,5 +171,7 @@ api.use('/university_enrollment', universityEnrollment); api.use('/university', university); api.use('/university_teacher', universityTeacher); api.use('/course_count', courseCount); - +api.use('/school_location', schoolLocation); +api.use('/mesoregion', mesoregion); +api.use('/microregion', microregion); module.exports = api; diff --git a/src/libs/routes/city.js b/src/libs/routes/city.js index 4249487876a24ee3788160f1676e33207cf6d3a6..ef28500f275b237c9be2d4ec3a860da7d9e960cf 100644 --- a/src/libs/routes/city.js +++ b/src/libs/routes/city.js @@ -91,7 +91,9 @@ cityApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { .field('municipio.id') .field('municipio.estado_id', 'state_id') .field('municipio.longitude', 'longitude') - .field('municipio.latitude', 'latitude'); + .field('municipio.latitude', 'latitude') + .field('municipio.mesorregiao_id', 'mesoregion_id') + .field('municipio.microrregiao_id', 'microregion_id'); next(); }, query, response('city')); diff --git a/src/libs/routes/classCount.js b/src/libs/routes/classCount.js index efa330119c0804720eab15756d186faec4b42ad4..2713238305d705af7f5d8cc06ce10e09b64568c1 100644 --- a/src/libs/routes/classCount.js +++ b/src/libs/routes/classCount.js @@ -367,7 +367,7 @@ classCountApp.get('/count', rqf.parse(), (req, res, next) => { .from('turma') .group('turma.ano_censo') .order('turma.ano_censo') - .where('turma.tipo_turma_id = 0 AND turma.dependencia_adm_id <= 3 AND ((turma.etapa_resumida >= 1 AND turma.etapa_resumida <= 7) OR turma.etapa_resumida = 99)'); + .where('turma.local_turma = 0 AND turma.dependencia_adm_id <= 3 AND ((turma.etapa_resumida >= 1 AND turma.etapa_resumida <= 7) OR turma.etapa_resumida = 99)'); next(); }, rqf.build(), query, addMissing(rqf), id2str.transform(), response('class_count')); diff --git a/src/libs/routes/classroom.js b/src/libs/routes/classroom.js index 538ca7b066b3ef08d6ef3e53508d6e234341c3b9..8e2b6a7ef4a826386e0ef04d431a4f0396b18eb0 100644 --- a/src/libs/routes/classroom.js +++ b/src/libs/routes/classroom.js @@ -244,7 +244,7 @@ rqf.addField({ classroomApp.get('/', cache('15 day'), rqf.parse(), rqf.build(), (req, res, next) => { req.sql.from('escola') - .field('SUM(escola.num_salas)', 'total') + .field('SUM(escola.qtde_salas_utilizadas_dentro)', 'total') .field("'Brasil'", 'name') .field('escola.ano_censo', 'year') .group('escola.ano_censo') diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js index bf447a3ba3924b6bf8a1b7f17c732119d4a21448..4f1c19913bbac3ebfa612afb250d7453d3f93a26 100644 --- a/src/libs/routes/classroomCount.js +++ b/src/libs/routes/classroomCount.js @@ -285,7 +285,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => { req.dims.location = true; req.dims.school_building = true; - req.sql.field('SUM(escola.num_salas)', 'total') + req.sql.field('SUM(escola.qtde_salas_utilizadas_dentro)', 'total') .field("'Brasil'", 'name') .field('escola.ano_censo', 'year') .from('escola') diff --git a/src/libs/routes/cub.js b/src/libs/routes/cub.js index 5310f0be248f191f0e41325fb84d03525f638e40..3707e7f0df6daa731ae482a0d261184a7a32ce7f 100644 --- a/src/libs/routes/cub.js +++ b/src/libs/routes/cub.js @@ -173,6 +173,6 @@ cubApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { } next(); -}, query, addMissing(rqf), id2str.transform(), response('cub')); +}, query, id2str.transform(), response('cub')); module.exports = cubApp; diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js index 4eef5dcd17670c39c0fa1521fdf99dc8f09ece28..4af6cb7d378442e789962ab5fe86d6dea1ed6776 100644 --- a/src/libs/routes/dailyChargeAmount.js +++ b/src/libs/routes/dailyChargeAmount.js @@ -42,7 +42,7 @@ const config = require(`${libs}/config`); const addMissing = require(`${libs}/middlewares/addMissing`); -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; +const cache = require('apicache').options({ debug: config.debug, statusCodes: { include: [200] } }).middleware; let rqf = new ReqQueryFields(); @@ -52,27 +52,27 @@ let rqfCount = new ReqQueryFields(); dailyChargeAmountApp.get('/year_range', (req, res, next) => { req.sql.from('turma') - .field('MIN(turma.ano_censo)', 'start_year') - .field('MAX(turma.ano_censo)', 'end_year'); + .field('MIN(turma.ano_censo)', 'start_year') + .field('MAX(turma.ano_censo)', 'end_year'); next(); }, query, response('range')); dailyChargeAmountApp.get('/years', (req, res, next) => { req.sql.from('turma') - .field('DISTINCT turma.ano_censo', 'year'); + .field('DISTINCT turma.ano_censo', 'year'); next(); }, query, response('years')); dailyChargeAmountApp.get('/source', (req, res, next) => { req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'turma\''); + .field('fonte', 'source') + .where('tabela = \'turma\''); next(); }, query, response('source')); dailyChargeAmountApp.get('/adm_dependency', (req, res, next) => { req.result = []; - for(let i = 1; i <= 4; ++i) { + for (let i = 1; i <= 4; ++i) { req.result.push({ id: i, name: id2str.admDependency(i) @@ -83,7 +83,7 @@ dailyChargeAmountApp.get('/adm_dependency', (req, res, next) => { dailyChargeAmountApp.get('/adm_dependency_detailed', cache('15 day'), (req, res, next) => { req.result = []; - for(let i = 1; i <= 6; ++i) { + for (let i = 1; i <= 6; ++i) { req.result.push({ id: i, name: id2str.admDependencyPriv(i) @@ -94,58 +94,58 @@ dailyChargeAmountApp.get('/adm_dependency_detailed', cache('15 day'), (req, res, dailyChargeAmountApp.get('/location', cache('15 day'), (req, res, next) => { req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} + { id: 1, name: 'Urbana' }, + { id: 2, name: 'Rural' } ]; next(); }, response('location')); dailyChargeAmountApp.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"} + { 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')); dailyChargeAmountApp.get('/education_level_short', (req, res, next) => { req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Ensino Fundamental - anos iniciais'}, - {id: 4, name: 'Ensino Fundamental - anos finais'}, - {id: 5, name: 'Ensino Médio'}, - {id: 6, name: 'EJA'}, - {id: 7, name: 'EE exclusiva'} + { id: null, name: 'Não classificada' }, + { id: 1, name: 'Creche' }, + { id: 2, name: 'Pré-Escola' }, + { id: 3, name: 'Ensino Fundamental - anos iniciais' }, + { id: 4, name: 'Ensino Fundamental - anos finais' }, + { id: 5, name: 'Ensino Médio' }, + { id: 6, name: 'EJA' }, + { id: 7, name: 'EE exclusiva' } ]; next(); }, response('education_level_short')); dailyChargeAmountApp.get('/average/education_level_mod', (req, res, next) => { req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Educação Infantil Unificada'}, - {id: 4, name: 'Ensino Fundamental - anos iniciais'}, - {id: 5, name: 'Ensino Fundamental - anos finais'}, - {id: 6, name: 'Ensino Médio'}, - {id: 7, name: 'Turma Multisseriadas e Multietapas'}, - {id: 8, name: 'EJA - Ensino Fundamental'}, - {id: 9, name: 'EJA - Ensino Médio'}, - {id: 10, name: 'Educação Profissional'} + { id: null, name: 'Não classificada' }, + { id: 1, name: 'Creche' }, + { id: 2, name: 'Pré-Escola' }, + { id: 3, name: 'Educação Infantil Unificada' }, + { id: 4, name: 'Ensino Fundamental - anos iniciais' }, + { id: 5, name: 'Ensino Fundamental - anos finais' }, + { id: 6, name: 'Ensino Médio' }, + { id: 7, name: 'Turma Multisseriadas e Multietapas' }, + { id: 8, name: 'EJA - Ensino Fundamental' }, + { id: 9, name: 'EJA - Ensino Médio' }, + { id: 10, name: 'Educação Profissional' } ]; next(); }, response('education_level_mod')); dailyChargeAmountApp.get('/period', (req, res, next) => { req.result = []; - for(let i = 1; i <= 3; ++i) { + for (let i = 1; i <= 3; ++i) { req.result.push({ id: i, name: id2str.period(i) @@ -160,9 +160,9 @@ dailyChargeAmountApp.get('/period', (req, res, next) => { dailyChargeAmountApp.get('/integral_time', (req, res, next) => { req.result = [ - {id: null, name: 'Não Disponível'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} + { id: null, name: 'Não Disponível' }, + { id: 0, name: 'Não' }, + { id: 1, name: 'Sim' } ]; next(); }, response('integral_time')); @@ -343,37 +343,30 @@ rqf.addField({ dailyChargeAmountApp.get('/', rqf.parse(), (req, res, next) => { var status = 0; - if ('integral_time' in req.filter) { - if (req.filter['integral_time'] == '0' - && ('period' in req.filter)) { - if (req.filter['period'].length == 1 - && req.filter['period'][0] == '3') { - status = 1; - } else if (req.filter['period'].length <= 2 - && (req.filter['period'].includes('1') - || req.filter['period'].includes('2')) - && (!req.filter['period'].includes('3'))) { - status = 1; - } - } else if (req.filter['integral_time'] == '1') { + if ('period' in req.filter) { + if (req.filter['period'].length == 1 && (req.filter['period'][0] == '3' || req.filter['period'][0] === '4')) { + status = 1; + } else if (req.filter['period'].length <= 2 && (req.filter['period'].includes('1') || req.filter['period'].includes('2')) && (!req.filter['period'].includes('3'))) { status = 1; } + } else if (req.filter['integral_time'] == '1') { + status = 1; } if (status) { req.sql.from('turma') - .field('turma.ano_censo', 'year') - .field('turma.etapa_resumida', 'education_level_short_id') - .field('AVG(turma.duracao_turma)/60.0', 'average_class_duration') - .field('MEDIAN(turma.duracao_turma)/60.0', 'median_class_duration') - .field('STDDEV_SAMP(turma.duracao_turma)/60.0', 'std_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.25)/60.0', 'fstqt_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.75)/60.0', 'thdqt_class_duration') - .group('turma.ano_censo') - .group('turma.etapa_resumida') - .order('turma.ano_censo') - .order('turma.etapa_resumida') - .where('turma.tipo_turma_id <= 3 and turma.dependencia_adm_id <= 3') + .field('turma.ano_censo', 'year') + .field('turma.etapa_resumida', 'education_level_short_id') + .field('AVG(turma.duracao_turma)/60.0', 'average_class_duration') + .field('MEDIAN(turma.duracao_turma)/60.0', 'median_class_duration') + .field('STDDEV_SAMP(turma.duracao_turma)/60.0', 'std_class_duration') + .field('QUANTILE(turma.duracao_turma, 0.25)/60.0', 'fstqt_class_duration') + .field('QUANTILE(turma.duracao_turma, 0.75)/60.0', 'thdqt_class_duration') + .group('turma.ano_censo') + .group('turma.etapa_resumida') + .order('turma.ano_censo') + .order('turma.etapa_resumida') + .where('((turma.tipo_turma_id <= 3 AND turma.tipo_atendimento_id is NULL) OR (turma.tipo_atendimento_id <= 2 AND turma.tipo_turma_id is NULL)) and turma.dependencia_adm_id <= 3') } else { res.status(400); next({ @@ -403,16 +396,16 @@ dailyChargeAmountApp.get('/', rqf.parse(), (req, res, next) => { dailyChargeAmountApp.get('/average', rqf.parse(), rqf.build(), (req, res, next) => { var status = 0; if (('education_level_mod' in req.filter || 'education_level_mod' in req.dims) - && ('integral_time' in req.filter)) { + && ('integral_time' in req.filter)) { if (req.filter['integral_time'] == '0' - && ('period' in req.filter)) { + && ('period' in req.filter)) { if (req.filter['period'].length == 1 - && req.filter['period'][0] == '3') { + && req.filter['period'][0] == '3') { status = 1; } else if (req.filter['period'].length <= 2 - && (req.filter['period'].includes('1') - || req.filter['period'].includes('2')) - && (!req.filter['period'].includes('3'))) { + && (req.filter['period'].includes('1') + || req.filter['period'].includes('2')) + && (!req.filter['period'].includes('3'))) { status = 1; } } else if (req.filter['integral_time'] == '1') { @@ -425,40 +418,41 @@ dailyChargeAmountApp.get('/average', rqf.parse(), rqf.build(), (req, res, next) let tableR = baseQ.clone(); tableR.from('turma') - .field('duracao_turma') - .field('etapas_mod_ensino_segmento_id') - .field('ROW_NUMBER() OVER(PARTITION BY etapas_mod_ensino_segmento_id ORDER BY duracao_turma)', 'rowno') - .where('tipo_turma_id <= 3') + .field('duracao_turma') + .field('etapas_mod_ensino_segmento_id') + .field('ROW_NUMBER() OVER(PARTITION BY etapas_mod_ensino_segmento_id ORDER BY duracao_turma)', 'rowno') + .where('((turma.tipo_turma_id <= 3 AND turma.tipo_atendimento_id is NULL) OR (turma.tipo_atendimento_id <= 2 AND turma.tipo_turma_id is NULL))') let tableG = baseQ.clone(); tableG.from('turma') - .field('1+COUNT(*)', 'counter') - .field('etapas_mod_ensino_segmento_id') - .where('tipo_turma_id <= 3') - .group('etapas_mod_ensino_segmento_id') + .field('1+COUNT(*)', 'counter') + .field('etapas_mod_ensino_segmento_id') + .where('((turma.tipo_turma_id <= 3 AND turma.tipo_atendimento_id is NULL) OR (turma.tipo_atendimento_id <= 2 AND turma.tipo_turma_id is NULL))') + .group('etapas_mod_ensino_segmento_id') let joinRG = squel.select(); joinRG.from(tableR, 'R') - .field('R.etapas_mod_ensino_segmento_id') - .field('AVG(1.0*R.duracao_turma)/60', 'median_value') - .join(tableG, 'G', 'R.etapas_mod_ensino_segmento_id = G.etapas_mod_ensino_segmento_id AND R.rowNo BETWEEN G.counter/2 AND G.counter/2+G.counter%2') - .group('R.etapas_mod_ensino_segmento_id') + .field('R.etapas_mod_ensino_segmento_id') + .field('AVG(1.0*R.duracao_turma)/60', 'median_value') + .join(tableG, 'G', 'R.etapas_mod_ensino_segmento_id = G.etapas_mod_ensino_segmento_id AND R.rowNo BETWEEN G.counter/2 AND G.counter/2+G.counter%2') + .group('R.etapas_mod_ensino_segmento_id') req.sql - .from('turma') - .from(joinRG, 'm') - .field('turma.ano_censo', 'year') - .field('turma.etapas_mod_ensino_segmento_id', 'education_level_mod_id') - .field('AVG(turma.duracao_turma)/60.0', 'average_class_duration') - .field('AVG(m.median_value)', 'median_class_duration') - .field('STDDEV_SAMP(turma.duracao_turma)/60.0', 'std_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.25)/60.0', 'fstqt_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.75)/60.0', 'thdqt_class_duration') - .group('turma.ano_censo') - .group('turma.etapas_mod_ensino_segmento_id') - .order('turma.ano_censo') - .order('turma.etapas_mod_ensino_segmento_id') - .where('turma.tipo_turma_id <= 3 and m.etapas_mod_ensino_segmento_id = turma.etapas_mod_ensino_segmento_id') + .from('turma') + .from(joinRG, 'm') + .field('turma.ano_censo', 'year') + .field('turma.etapas_mod_ensino_segmento_id', 'education_level_mod_id') + .field('AVG(turma.duracao_turma)/60.0', 'average_class_duration') + .field('AVG(m.median_value)', 'median_class_duration') + .field('STDDEV_SAMP(turma.duracao_turma)/60.0', 'std_class_duration') + .field('QUANTILE(turma.duracao_turma, 0.25)/60.0', 'fstqt_class_duration') + .field('QUANTILE(turma.duracao_turma, 0.75)/60.0', 'thdqt_class_duration') + .group('turma.ano_censo') + .group('turma.etapas_mod_ensino_segmento_id') + .order('turma.ano_censo') + .order('turma.etapas_mod_ensino_segmento_id') + .where('((turma.tipo_turma_id <= 3 AND turma.tipo_atendimento_id is NULL) OR (turma.tipo_atendimento_id <= 2 AND turma.tipo_turma_id is NULL)) \ + and m.etapas_mod_ensino_segmento_id = turma.etapas_mod_ensino_segmento_id') } else { res.status(400); next({ diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js index 87083fcf8d38eeca2b75eafc9b68e84a1dd3f096..91b4fafe2da58f890b7405ff2e69d46a69baba33 100644 --- a/src/libs/routes/enrollment.js +++ b/src/libs/routes/enrollment.js @@ -341,6 +341,38 @@ rqf.addField({ foreign: 'regiao_id', foreignTable: 'matricula' } +}).addValue({ + name: 'mesoregion', + table: 'municipio', + tableField: ['nome_mesorregiao', 'mesorregiao_id'], + resultField: ['mesoregion_name', 'mesoregion_id'], + where: { + relation: '=', + type: 'integer', + field: 'mesorregiao_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'municipio_id', + foreignTable: 'matricula' + } +}).addValue({ + name: 'microregion', + table: 'municipio', + tableField: ['nome_microrregiao', 'microrregiao_id'], + resultField: ['microregion_name', 'microregion_id'], + where: { + relation: '=', + type: 'integer', + field: 'microrregiao_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'municipio_id', + foreignTable: 'matricula' + } }).addValueToField({ name: 'state', table: 'estado', diff --git a/src/libs/routes/mesoregion.js b/src/libs/routes/mesoregion.js new file mode 100644 index 0000000000000000000000000000000000000000..0feb76270835ba64e9c4a7adfed6bd8f8a676c09 --- /dev/null +++ b/src/libs/routes/mesoregion.js @@ -0,0 +1,76 @@ +/* +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 mesoregionApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const config = require(`${libs}/config`); + +const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; + +let rqf = new ReqQueryFields(); + +mesoregionApp.use(cache('15 day')); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addValue({ + name: 'state', + table: 'estado', + tableField: ['nome', 'id'], + resultField: ['state_name', 'state_id'], + where: { + relation: '=', + type: 'integer', + field: 'estado_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'estado_id', + foreignTable: 'municipio' + } +}); + +mesoregionApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.from('municipio') + .field('municipio.nome_mesorregiao', 'name') + .field('municipio.mesorregiao_id', 'id') + .field('municipio.estado_id', 'state_id') + .group('municipio.nome_mesorregiao') + .group('municipio.mesorregiao_id') + .group('municipio.estado_id'); + next(); +}, query, response('mesoregion')); + +module.exports = mesoregionApp; diff --git a/src/libs/routes/microregion.js b/src/libs/routes/microregion.js new file mode 100644 index 0000000000000000000000000000000000000000..0b9b0e1a3f5f04b0a768283d7aaffa7b353aafc6 --- /dev/null +++ b/src/libs/routes/microregion.js @@ -0,0 +1,80 @@ +/* +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 microregionApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const config = require(`${libs}/config`); + +const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; + +let rqf = new ReqQueryFields(); + +microregionApp.use(cache('15 day')); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addValue({ + name: 'state', + table: 'estado', + tableField: ['nome', 'id'], + resultField: ['state_name', 'state_id'], + where: { + relation: '=', + type: 'integer', + field: 'estado_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'estado_id', + foreignTable: 'municipio' + } +}); + +microregionApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.from('municipio') + .field('municipio.nome_microrregiao', 'name') + .field('municipio.microrregiao_id', 'id') + .field('municipio.nome_mesorregiao', 'mesoregion_name') + .field('municipio.mesorregiao_id', 'mesoregion_id') + .field('municipio.estado_id', 'state_id') + .group('municipio.nome_microrregiao') + .group('municipio.microrregiao_id') + .group('municipio.nome_mesorregiao') + .group('municipio.mesorregiao_id') + .group('municipio.estado_id'); + next(); +}, query, response('microregion')); + +module.exports = microregionApp; diff --git a/src/libs/routes/outOfSchool.js b/src/libs/routes/outOfSchool.js index 91bac8dda9bb3a4057f0a3aa892899e99e94bd61..fcd57867675e0556f57c46fccc71af4cfacb787e 100644 --- a/src/libs/routes/outOfSchool.js +++ b/src/libs/routes/outOfSchool.js @@ -345,16 +345,29 @@ simcaqRqf.addField({ } }); -outOfSchoolApp.get('/simcaq', simcaqRqf.parse(), simcaqRqf.build(), (req, res, next) => { - req.sql.from('populacao_fora_da_escola') - .field('SUM(populacao_fora_da_escola.pop_fora_escola)', 'total') - .field("'Brasil'", 'name') - .field('populacao_fora_da_escola.ano_censo') - .group('populacao_fora_da_escola.ano_censo') - .order('populacao_fora_da_escola.ano_censo'); +outOfSchoolApp.get('/simcaq', simcaqRqf.parse(), (req, res, next) => { + if ('state' in req.filter || 'city' in req.filter || 'state' in req.dims || 'city' in req.dims) { // Query in state/city level + + if ('city' in req.filter && 'state' in req.filter) delete req.filter.state // use only the city filter because of the table particularities + + req.sql.from('populacao_fora_da_escola') + .field('SUM(populacao_fora_da_escola.pop_fora_escola)', 'total') + .field("'Brasil'", 'name') + .field('populacao_fora_da_escola.ano_censo') + .group('populacao_fora_da_escola.ano_censo') + .order('populacao_fora_da_escola.ano_censo'); + } else { // Query in 'Brasil' level + req.sql.from('populacao_fora_da_escola') + .field('SUM(populacao_fora_da_escola.pop_fora_escola)', 'total') + .field("'Brasil'", 'name') + .field('populacao_fora_da_escola.ano_censo') + .where('populacao_fora_da_escola.brasil = 1') + .group('populacao_fora_da_escola.ano_censo') + .order('populacao_fora_da_escola.ano_censo'); + } next(); -}, query, (req, res, next) => { +}, simcaqRqf.build(), query, (req, res, next) => { req.result.forEach((i) => { i.total = parseInt(i.total); }); diff --git a/src/libs/routes/schoolInfrastructure.js b/src/libs/routes/schoolInfrastructure.js index 32f316a4bff24d78a893ddc60f39e8381e4b64c4..c74f0e303b10407bb56faa9eb12c86f8ed6a9419 100644 --- a/src/libs/routes/schoolInfrastructure.js +++ b/src/libs/routes/schoolInfrastructure.js @@ -360,35 +360,24 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.allSchoolsNotSchoolBuilding = req.querySet.push(allSchoolsNotSchoolBuilding) - 1; // Bibliotecas - // Se (situacao_de_funcionamento=1) & (dependencia_adm_id<=3) & (CEBES027P1=1) & - // (ensino_regular=1 | ensino_eja=1 | educacao_profissional=1) & - // (reg_fund_ai_t1=1 | reg_fund_af_t1=1 | reg_medio_medio_t1=1 | ensino_eja_fund= 1 | - // ensino_eja_medio= 1 | ensino_eja_prof= 1 | esp_eja_fund=1 | esp_eja_medio=1 | ensino_esp_exclusiva_eja_prof=1) & (localizacao_id=1) então conta id - let allLibraries = allUrbanSchools.clone(); - allLibraries.where('reg_fund_ai_t1=1 OR reg_fund_af_t1=1 OR reg_medio_medio_t1=1 OR ensino_eja_fund= 1 OR ensino_eja_medio= 1 OR ensino_eja_prof= 1 OR esp_eja_fund=1 OR esp_eja_medio=1 OR ensino_esp_exclusiva_eja_prof=1'); - req.queryIndex.allLibraries = req.querySet.push(allLibraries) - 1; + req.queryIndex.allLibraries = req.queryIndex.allUrbanSchools; - let haveLibraries = allLibraries.clone(); + let haveLibraries = allUrbanSchools.clone(); haveLibraries.where('escola.biblioteca = 1'); req.queryIndex.haveLibraries = req.querySet.push(haveLibraries) - 1; - let needLibraries = allLibraries.clone(); + let needLibraries = allUrbanSchools.clone(); needLibraries.where('escola.biblioteca = 0'); req.queryIndex.needLibraries = req.querySet.push(needLibraries) - 1; - // Bibliotecas/Sala de leitura - // Se (situacao_de_funcionamento=1) & (dependencia_adm_id<=3) & (CEBES027P1=1) & (ensino_regular=1 | ensino_eja=1 | educacao_profissional=1) & - // (reg_fund_ai_t1=1 | reg_fund_af_t1=1 | reg_medio_medio_t1=1 | ensino_eja_fund= 1 | ensino_eja_medio= 1 | - // ensino_eja_prof= 1 | esp_eja_fund=1 | esp_eja_medio=1 | ensino_esp_exclusiva_eja_prof=1) & (localizacao_id=2) então conta id - let allLibrariesReadingRoom = allCountrySchools.clone(); - allLibrariesReadingRoom.where('reg_fund_ai_t1=1 OR reg_fund_af_t1=1 OR reg_medio_medio_t1=1 OR ensino_eja_fund=1 OR ensino_eja_medio=1 OR ensino_eja_prof=1 OR esp_eja_fund=1 OR esp_eja_medio=1 OR ensino_esp_exclusiva_eja_prof=1'); - req.queryIndex.allLibrariesReadingRoom = req.querySet.push(allLibrariesReadingRoom) - 1; + // Sala de leitura + req.queryIndex.allLibrariesReadingRoom = req.queryIndex.allCountrySchools; - let haveLibrariesReadingRoom = allLibrariesReadingRoom.clone(); + let haveLibrariesReadingRoom = allCountrySchools.clone(); haveLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = true'); req.queryIndex.haveLibrariesReadingRoom = req.querySet.push(haveLibrariesReadingRoom) - 1; - let needLibrariesReadingRoom = allLibrariesReadingRoom.clone(); + let needLibrariesReadingRoom = allCountrySchools.clone(); needLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = false'); req.queryIndex.needLibrariesReadingRoom = req.querySet.push(needLibrariesReadingRoom) - 1; @@ -437,20 +426,20 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { needKidsPark.where('escola.parque_infantil = 0'); req.queryIndex.needKidsPark = req.querySet.push(needKidsPark) - 1; - // Berçário - let allCribs = allSchools.clone(); - allCribs.where('escola.reg_infantil_creche_t1 = 1'); - req.queryIndex.allCribs = req.querySet.push(allCribs) - 1; + // // Berçário + // let allCribs = allSchools.clone(); + // allCribs.where('escola.reg_infantil_creche_t1 = 1'); + // req.queryIndex.allCribs = req.querySet.push(allCribs) - 1; - let haveCribs = allCribs.clone(); - haveCribs.where('escola.bercario = 1'); - req.queryIndex.haveCribs = req.querySet.push(haveCribs) - 1; + // let haveCribs = allCribs.clone(); + // haveCribs.where('escola.bercario = 1'); + // req.queryIndex.haveCribs = req.querySet.push(haveCribs) - 1; - let needCribs = allCribs.clone(); - needCribs.where('escola.bercario = 0'); - req.queryIndex.needCribs = req.querySet.push(needCribs) - 1; + // let needCribs = allCribs.clone(); + // needCribs.where('escola.bercario = 0'); + // req.queryIndex.needCribs = req.querySet.push(needCribs) - 1; - // Quadra Coberta + // Quadra de esportes let allSportsCourt = allSchools.clone(); allSportsCourt.where('reg_fund_ai_t1=1 or reg_fund_af_t1=1 or reg_medio_medio_t1=1 or ensino_eja_fund= 1 or ensino_eja_medio= 1 or ensino_eja_prof= 1 or esp_eja_fund=1 or esp_eja_medio=1 or ensino_esp_exclusiva_eja_prof=1'); req.queryIndex.allSportsCourt = req.querySet.push(allSportsCourt) - 1; @@ -463,7 +452,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { needSportsCourt.where('escola.quadra_esportes = 0'); req.queryIndex.needSportsCourt = req.querySet.push(needSportsCourt) - 1; - // Cobertura de quadra esportiva + // Quadras a serem cobertas // Se (situacao_de_funcionamento=1) and (ensino_regular=1 OR ensino_eja=1 OR educacao_profissional=1) and (local_func_predio_escolar=1) and // (dependencia_adm_id<=3) and (reg_fund_ai_t1=1 or reg_fund_af_t1=1 or reg_medio_medio_t1=1 or ensino_eja_fund= 1 or ensino_eja_medio= 1 or // ensino_eja_prof= 1 or esp_eja_fund=1 or esp_eja_medio=1 or ensino_esp_exclusiva_eja_prof=1) and (quadra_esportes_descoberta=1) então conta id @@ -479,14 +468,14 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.allCourtyard = req.queryIndex.allSchools; let haveCourtyard = allSchools.clone(); - haveCourtyard.where('escola.patio = 2 OR escola.patio = 1'); + haveCourtyard.where('escola.patio = 1 OR escola.patio = 2'); req.queryIndex.haveCourtyard = req.querySet.push(haveCourtyard) - 1; let needCourtyard = allSchools.clone(); needCourtyard.where('escola.patio = 0'); req.queryIndex.needCourtyard = req.querySet.push(needCourtyard) - 1; - // Cobertura do Pátio + // Pátios a serem cobertos let allCourtyardCoverage = allSchools.clone(); allCourtyardCoverage.where('escola.patio = 1'); req.queryIndex.allCourtyardCoverage = req.querySet.push(allCourtyardCoverage) - 1; @@ -585,15 +574,15 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { needBroadbandInternet.where('escola.internet_banda_larga = 0'); req.queryIndex.needBroadbandInternet = req.querySet.push(needBroadbandInternet) - 1; - // Sanitário dentro do prédio + // Banheiro req.queryIndex.allInsideBathroom = req.queryIndex.allSchools; let haveInsideBathroom = allSchools.clone(); - haveInsideBathroom.where('escola.sanitario_dentro_predio = 1'); + haveInsideBathroom.where('escola.banheiro = 1'); req.queryIndex.haveInsideBathroom = req.querySet.push(haveInsideBathroom) - 1; let needInsideBathroom = allSchools.clone(); - needInsideBathroom.where('escola.sanitario_dentro_predio = 0'); + needInsideBathroom.where('escola.banheiro = 0'); req.queryIndex.needInsideBathroom = req.querySet.push(needInsideBathroom) - 1; // Banheiro adequado para educação infantil dentro do prédio @@ -615,55 +604,55 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.allEletricPower = req.queryIndex.allSchools; let haveEletricPower = allSchools.clone(); - haveEletricPower.where('escola.fornecimento_energia = 1'); + haveEletricPower.where('escola.energia_inexistente = 0'); req.queryIndex.haveEletricPower = req.querySet.push(haveEletricPower) - 1; let needEletricPower = allSchools.clone(); - needEletricPower.where('escola.fornecimento_energia = 0'); + needEletricPower.where('escola.energia_inexistente = 1'); req.queryIndex.needEletricPower = req.querySet.push(needEletricPower) - 1; // Abastecimento de água req.queryIndex.allWaterSupply = req.queryIndex.allSchools; let haveWaterSupply = allSchools.clone(); - haveWaterSupply.where('escola.fornecimento_agua = 1'); + haveWaterSupply.where('escola.agua_inexistente = 0'); req.queryIndex.haveWaterSupply = req.querySet.push(haveWaterSupply) - 1; let needWaterSupply = allSchools.clone(); - needWaterSupply.where('escola.fornecimento_agua = 0'); + needWaterSupply.where('escola.agua_inexistente = 1'); req.queryIndex.needWaterSupply = req.querySet.push(needWaterSupply) - 1; - // Água filtrada + // Água Potável req.queryIndex.allFilteredWater = req.queryIndex.allSchools; let haveFilteredWater = allSchools.clone(); - haveFilteredWater.where('escola.agua_filtrada = 1'); + haveFilteredWater.where('escola.agua_potavel = 1'); req.queryIndex.haveFilteredWater = req.querySet.push(haveFilteredWater) - 1; let needFilteredWater = allSchools.clone(); - needFilteredWater.where('escola.agua_filtrada = 0'); + needFilteredWater.where('escola.agua_potavel = 0'); req.queryIndex.needFilteredWater = req.querySet.push(needFilteredWater) - 1; // Coleta de esgoto req.queryIndex.allSewage = req.queryIndex.allSchools; let haveSewage = allSchools.clone(); - haveSewage.where('escola.esgoto_sanitario = 1'); + haveSewage.where('escola.esgoto_rede_publica = 1 OR escola.esgoto_fossa_septica = 1'); req.queryIndex.haveSewage = req.querySet.push(haveSewage) - 1; let needSewage = allSchools.clone(); - needSewage.where('escola.esgoto_sanitario = 0'); + needSewage.where('escola.esgoto_rede_publica = 0 AND escola.esgoto_fossa_septica = 0'); req.queryIndex.needSewage = req.querySet.push(needSewage) - 1; // Dependências adaptada para pessoas com deficiências req.queryIndex.allAdaptedBuilding = req.queryIndex.allSchools; let haveAdaptedBuilding = allSchools.clone(); - haveAdaptedBuilding.where('escola.dependencias_pne = 1'); + haveAdaptedBuilding.where('escola.acessibilidade_inexistente = 0'); req.queryIndex.haveAdaptedBuilding = req.querySet.push(haveAdaptedBuilding) - 1; let needAdaptedBuilding = allSchools.clone(); - needAdaptedBuilding.where('escola.dependencias_pne = 0'); + needAdaptedBuilding.where('escola.acessibilidade_inexistente = 1'); req.queryIndex.needAdaptedBuilding = req.querySet.push(needAdaptedBuilding) - 1; // Banheiros adaptados para pessoas com deficiências @@ -692,7 +681,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { let computer_lab = matchQueries(req.result[req.queryIndex.allInfLab], req.result[req.queryIndex.haveInfLab], req.result[req.queryIndex.needInfLab]); let science_lab = matchQueries(req.result[req.queryIndex.allScienceLab], req.result[req.queryIndex.haveScienceLab], req.result[req.queryIndex.needScienceLab]); let kids_park = matchQueries(req.result[req.queryIndex.allKidsPark], req.result[req.queryIndex.haveKidsPark], req.result[req.queryIndex.needKidsPark]); - let nursery = matchQueries(req.result[req.queryIndex.allCribs], req.result[req.queryIndex.haveCribs], req.result[req.queryIndex.needCribs]); + // let nursery = matchQueries(req.result[req.queryIndex.allCribs], req.result[req.queryIndex.haveCribs], req.result[req.queryIndex.needCribs]); let sports_court = matchQueries(req.result[req.queryIndex.allSportsCourt], req.result[req.queryIndex.haveSportsCourt], req.result[req.queryIndex.needSportsCourt]); let sports_court_coverage = matchQueries(req.result[req.queryIndex.allSportsCourtCoverage], [], req.result[req.queryIndex.needSportsCourtCoverage], true); // have = [] let courtyard = matchQueries(req.result[req.queryIndex.allCourtyard], req.result[req.queryIndex.haveCourtyard], req.result[req.queryIndex.needCourtyard]); @@ -724,7 +713,6 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { computer_lab, science_lab, kids_park, - nursery, sports_court, sports_court_coverage, courtyard, diff --git a/src/libs/routes/schoolLocation.js b/src/libs/routes/schoolLocation.js new file mode 100644 index 0000000000000000000000000000000000000000..5c0d98ff96fd30d232119a17e906eb14df5cd76e --- /dev/null +++ b/src/libs/routes/schoolLocation.js @@ -0,0 +1,114 @@ +const express = require('express'); + +const schoolLocationApp = 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 id2str = require(`${libs}/middlewares/id2str`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const request = require(`request`); + +const config = require(`${libs}/config`); + +const passport = require('passport'); + +const addMissing = require(`${libs}/middlewares/addMissing`); + +const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; + +let rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'id', + table: 'localizacao_escolas', + tableField: 'id', + where: { + relation: '=', + type: 'integer', + field: 'id' + } +}).addValue({ + name: 'mesoregion', + table: 'municipio', + tableField: ['nome_mesorregiao', 'mesorregiao_id'], + resultField: ['mesoregion_name', 'mesoregion_id'], + where: { + relation: '=', + type: 'integer', + field: 'mesorregiao_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'municipio_id', + foreignTable: 'localizacao_escolas' + } +}).addValue({ + name: 'microregion', + table: 'municipio', + tableField: ['nome_microrregiao', 'microrregiao_id'], + resultField: ['microregion_name', 'microregion_id'], + where: { + relation: '=', + type: 'integer', + field: 'microrregiao_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'municipio_id', + foreignTable: 'localizacao_escolas' + } +}).addValueToField({ + name: 'city', + table: 'municipio', + tableField: ['nome', 'id'], + resultField: ['city_name', 'city_id'], + where: { + relation: '=', + type: 'integer', + field: 'municipio_id', + }, + join: { + primary: 'id', + foreign: 'municipio_id', + foreignTable: '@' + } +}, 'dims'); + +schoolLocationApp.get('/', rqf.parse(), (req, res, next) => { + req.dims.city=true; + req.dims.mesoregion=true; + req.dims.microregion=true; + + req.sql.from('localizacao_escolas') + .field('localizacao_escolas.nome', 'name') + .field('localizacao_escolas.id', 'id') + .field('localizacao_escolas.latitude', 'latitude') + .field('localizacao_escolas.longitude', 'longitude') + .group('localizacao_escolas.nome') + .group('localizacao_escolas.id') + .group('localizacao_escolas.latitude') + .group('localizacao_escolas.longitude'); + next(); +}, rqf.build(), query, id2str.transform(), response('school_location')); + +module.exports = schoolLocationApp; diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js index 59d6f8db333ae285cadc96dd75dad9030ea41bcb..2b2037c4208b1d68f3fe498613918b4362bb3bdb 100644 --- a/src/libs/routes/teacher.js +++ b/src/libs/routes/teacher.js @@ -265,6 +265,38 @@ rqf.addField({ foreign: 'escola_regiao_id', foreignTable: 'docente' } +}).addValue({ + name: 'mesoregion', + table: 'municipio', + tableField: ['nome_mesorregiao', 'mesorregiao_id'], + resultField: ['mesoregion_name', 'mesoregion_id'], + where: { + relation: '=', + type: 'integer', + field: 'mesorregiao_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'escola_municipio_id', + foreignTable: 'docente' + } +}).addValue({ + name: 'microregion', + table: 'municipio', + tableField: ['nome_microrregiao', 'microrregiao_id'], + resultField: ['microregion_name', 'microregion_id'], + where: { + relation: '=', + type: 'integer', + field: 'microrregiao_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'escola_municipio_id', + foreignTable: 'docente' + } }).addValue({ name: 'state', table: 'estado', diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js index a618a7be5d9eb56dc169b36e70ca2cd04c703f21..748df1c4c754382b5cf869ffdc88a9b4148bfdea 100644 --- a/src/libs/routes/universityEnrollment.js +++ b/src/libs/routes/universityEnrollment.js @@ -285,6 +285,38 @@ rqf.addField({ foreign: 'cod_municipio_ies', foreignTable: '@' } +}).addValue({ + name: 'mesoregion', + table: 'municipio', + tableField: ['nome_mesorregiao', 'mesorregiao_id'], + resultField: ['mesoregion_name', 'mesoregion_id'], + where: { + relation: '=', + type: 'integer', + field: 'mesorregiao_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'cod_municipio_ies', + foreignTable: 'aluno_ens_superior' + } +}).addValue({ + name: 'microregion', + table: 'municipio', + tableField: ['nome_microrregiao', 'microrregiao_id'], + resultField: ['microregion_name', 'microregion_id'], + where: { + relation: '=', + type: 'integer', + field: 'microrregiao_id', + table: 'municipio' + }, + join: { + primary: 'id', + foreign: 'cod_municipio_ies', + foreignTable: 'aluno_ens_superior' + } }).addValue({ name: 'region', table: 'regiao',