diff --git a/.gitignore b/.gitignore index 99a279fb87ba4d97734e25ed4d26cfef532ea04e..57b7432f5ea27a42c6acb12ffaede094c0457c19 100644 --- a/.gitignore +++ b/.gitignore @@ -19,7 +19,6 @@ build/* .gulp-cache -config.json docs/ .vscode/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 2cfd1adfd30e95fcc86afa8f389450e666b68f85..7e4203293b315ce384149e0a60efab347b686a7a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,3 +1,5 @@ +image: node:9.2.1 + stages: - test @@ -9,14 +11,21 @@ variables: 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 + - apt update && apt install curl + - curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py + - python get-pip.py run_tests: stage: test script: + - git clone https://gitlab.c3sl.ufpr.br/simcaq/lde-api-regression-test.git + - cd lde-api-regression-test + - pip install -r requirements.txt + - python regression_test.py --compare - ping -W1 -c1 mongo - - mv config.json.example config.json - sed -i -e 's/false/true/g' config.json - gulp build - gulp test diff --git a/config.json.example b/config.json similarity index 63% rename from config.json.example rename to config.json index e3d309200d160d47b17dbe57f23dee11cdbccd23..9d206c7d5daafbe6d397911e10343c5212eda01c 100644 --- a/config.json.example +++ b/config.json @@ -10,17 +10,15 @@ "dbname": "simcaq_dev4", "user": "monetdb", "password":"monetdb", - "nrConnections": "4" + "nrConnections": "1" }, "cdn" : { "url": "http://simcaqdb3.c3sl.ufpr.br:3000", "download": "https://simcaqdev.c3sl.ufpr.br/download/" }, - "mongodb" : { - "uri": "mongodb://localhost/dev_users" - }, - "monq": { - "uri": "mongodb://localhost/dev_monq" + "mongodb": { + "uri": "mongodb://simcaqdb3/dev_monq", + "secret": "SimCAQC3SL" }, "default": { "api": { @@ -33,6 +31,9 @@ "url": "http://simcaqdev.c3sl.ufpr.br/#" } }, + "lde_api": { + "url": "https://dadoseducacionaisdev.c3sl.ufpr.br/api/v1/" + }, "email": { "port": 25, "host": "mx.c3sl.ufpr.br", @@ -46,7 +47,7 @@ }, "test": { - "port": 4000, + "port": 3000, "ip": "127.0.0.1", "debug" : true, "monetdb": { @@ -55,18 +56,61 @@ "dbname": "simcaq_dev4", "user": "monetdb", "password":"monetdb", - "nrConnections": "4" + "nrConnections": "1" }, "cdn" : { "url": "http://simcaqdb3.c3sl.ufpr.br:3000", "download": "https://simcaqdev.c3sl.ufpr.br/download/" }, - "mongodb" : { - "uri": "mongodb://localhost/test_users", + "mongodb": { + "uri": "mongodb://simcaqdb3/dev_monq", "secret": "SimCAQC3SL" }, - "monq": { - "uri": "mongodb://localhost/test_monq" + "default": { + "api": { + "version" : "v1" + }, + "lde": { + "url": "http://ldedev.c3sl.ufpr.br/#" + }, + "simcaq": { + "url": "http://simcaqdev.c3sl.ufpr.br/#" + } + }, + "lde_api": { + "url": "https://dadoseducacionaisdev.c3sl.ufpr.br/api/v1/" + }, + "email": { + "port": 25, + "host": "mx.c3sl.ufpr.br", + "secure": false, + "ignoreTLS": true, + "from": "\"Laboratório de Dados Educacionais\" <lde@c3sl.ufpr.br>" + }, + "security": { + "tokenLife": 3600 + } + }, + "homologa": + { + "port": 3000, + "ip": "127.0.0.1", + "debug" : true, + "monetdb": { + "host": "simcaqdb3.c3sl.ufpr.br", + "port": 50000, + "dbname": "simcaq_dev4", + "user": "monetdb", + "password":"monetdb", + "nrConnections": "4" + }, + "cdn" : { + "url": "http://simcaqdb3.c3sl.ufpr.br:3000", + "download": "https://simcaqdev.c3sl.ufpr.br/download/" + }, + "mongodb": { + "uri": "mongodb://simcaqdb3/monq", + "secret": "SimCAQC3SL" }, "default": { "api": { @@ -86,6 +130,9 @@ "ignoreTLS": true, "from": "\"Laboratório de Dados Educacionais\" <lde@c3sl.ufpr.br>" }, + "lde_api": { + "url": "https://dadoseducacionaishom.c3sl.ufpr.br/api/v1/" + }, "security": { "tokenLife": 3600 } @@ -107,13 +154,10 @@ "url": "http://simcaqdb3.c3sl.ufpr.br:7000", "download": "https://simcaq.c3sl.ufpr.br/download/" }, - "mongodb" : { - "uri": "mongodb://localhost/users", + "mongodb": { + "uri": "mongodb://simcaqdb3/monq", "secret": "SimCAQC3SL" }, - "monq": { - "uri": "mongodb://localhost/monq" - }, "default": { "api": { "version" : "v1" @@ -132,6 +176,9 @@ "ignoreTLS": true, "from": "\"Laboratório de Dados Educacionais\" <lde@c3sl.ufpr.br>" }, + "lde_api": { + "url": "https://dadoseducacionais.c3sl.ufpr.br/api/v1/" + }, "security": { "tokenLife": 3600 } diff --git a/gulpfile.babel.js b/gulpfile.babel.js index 11e9416f87c8528c84d0bbb64f5312c8455215b4..2619732963962d94d24323b0b87e4751ddb4e3e0 100644 --- a/gulpfile.babel.js +++ b/gulpfile.babel.js @@ -106,12 +106,19 @@ gulp.task('watch', ['compile'], () => { gulp.task('run', () => { process.chdir('build'); + let node_env = 'development'; + if(process.env.NODE_ENV === 'production') + node_env = 'production'; + else if(process.env.NODE_ENV === 'homologa') + node_env = 'homologa'; + + console.log(node_env); nodemon({ script: 'server.js', tasks: ['watch'], ignore: ["test/test.js", "gulpfile.babel.js"], ext: 'js html json', - env: { 'NODE_ENV': 'development' } + env: { 'NODE_ENV': node_env } }); }); diff --git a/package.json b/package.json index bb9438bfbcf40e8adfddb2dd27896bbe557a4dc5..df8ba0c9eec5624512a48a8d06e7baed52b5381e 100644 --- a/package.json +++ b/package.json @@ -51,6 +51,7 @@ "mocha": "^3.5.3", "monetdb-pool": "0.0.8", "mongoose": "^4.13.17", + "natives": "^1.1.6", "nconf": "^0.8.5", "node-uuid": "^1.4.8", "nodemailer": "^4.6.8", diff --git a/src/libs/app.js b/src/libs/app.js index b8b953c1ca4b23d2cc743611d6570b1d500de1e1..746fe6b955a8dc18e6924b6832d63e216cec9147 100644 --- a/src/libs/app.js +++ b/src/libs/app.js @@ -1,3 +1,23 @@ +/* +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 cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); @@ -16,14 +36,10 @@ const app = express(); const api = require('./routes/api'); -const passport = require('passport'); - const mongoose = require(`${libs}/db/mongoose`); const db = mongoose(); -require(`${libs}/middlewares/passport`); - app.use(bodyParser.json({limit: '50mb'})); app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' })); app.use(cookieParser()); @@ -55,10 +71,9 @@ app.use((req, res, next) => { }; return cloned; }; + next(); }); -app.use(passport.initialize()); -app.use(passport.session()); app.use((req, res, next) => { res.setHeader('Last-Modified', (new Date()).toUTCString()); diff --git a/src/libs/config.js b/src/libs/config.js index 2c07d19e94ba2505205d613a9ac6d5596c388502..cdc58c2f648e66d644c25c50da7a451c7e764ac1 100644 --- a/src/libs/config.js +++ b/src/libs/config.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + let conf = require(`${process.cwd()}/config.json`); conf = conf[process.env.NODE_ENV]; diff --git a/src/libs/convert/academicLevel.js b/src/libs/convert/academicLevel.js new file mode 100644 index 0000000000000000000000000000000000000000..3f76bc115a7e7897ef7aea4967fa872d07409bf2 --- /dev/null +++ b/src/libs/convert/academicLevel.js @@ -0,0 +1,32 @@ +/* +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 academicLevel(id) { + switch (id) { + case 1: + return 'Bacharelado'; + case 2: + return 'Licenciatura'; + case 3: + return 'Tecnológico'; + default: + return 'Não classificada'; + } +}; diff --git a/src/libs/convert/academicOrganization.js b/src/libs/convert/academicOrganization.js new file mode 100644 index 0000000000000000000000000000000000000000..14611d15af395aa85678efff3d38ad9d08692d53 --- /dev/null +++ b/src/libs/convert/academicOrganization.js @@ -0,0 +1,36 @@ +/* +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 academicOrganization(id) { + switch (id) { + case 1: + return 'Universidade'; + case 2: + return 'Centro Universitário'; + case 3: + return 'Faculdade'; + case 4: + return 'Instituto Federal de Educação, Ciência e Tecnologia'; + case 5: + return 'Centro Federal de Educação Tecnológica'; + default: + return 'Não classificada'; + } +}; diff --git a/src/libs/convert/admDependency.js b/src/libs/convert/admDependency.js index 16017f06634d2d9b69ad1e605c4922c2b29ff243..fca63f3fba14afd01f482fbdc4222d4852c96fdf 100644 --- a/src/libs/convert/admDependency.js +++ b/src/libs/convert/admDependency.js @@ -1,3 +1,23 @@ +/* +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 admDependency(id) { switch (id) { case 1: diff --git a/src/libs/convert/admDependencyPriv.js b/src/libs/convert/admDependencyPriv.js index 62afaa8354d2ebabe30826e66aceeb2a8c036790..0c5036fb1b0a070497dfc268f1b851bfc1e48b43 100644 --- a/src/libs/convert/admDependencyPriv.js +++ b/src/libs/convert/admDependencyPriv.js @@ -1,3 +1,23 @@ +/* +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 admDependencyPriv(id) { switch (id) { case 1: diff --git a/src/libs/convert/ageRange.js b/src/libs/convert/ageRange.js index 30bc9f6c0cd64123a3673f248a222351634627ed..4a88182998b7af0f07713984f161dd3a6fb8125a 100644 --- a/src/libs/convert/ageRange.js +++ b/src/libs/convert/ageRange.js @@ -1,3 +1,23 @@ +/* +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 ageRange(id) { switch (id) { case 1: diff --git a/src/libs/convert/ageRangeAll.js b/src/libs/convert/ageRangeAll.js index 2b4cab9cbf786a1a568912d9b3f7085e2789d26a..1ad1c54ee82d26a9d93d9608b38e9cc624a82428 100644 --- a/src/libs/convert/ageRangeAll.js +++ b/src/libs/convert/ageRangeAll.js @@ -1,3 +1,23 @@ +/* +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 ageRange(id) { switch (id) { case 1: diff --git a/src/libs/convert/ageStudentCode.js b/src/libs/convert/ageStudentCode.js new file mode 100644 index 0000000000000000000000000000000000000000..450c93610b221fc7af6334690571bba595eee5b3 --- /dev/null +++ b/src/libs/convert/ageStudentCode.js @@ -0,0 +1,38 @@ +/* +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 ageStudentCode(id) { + switch (id) { + case 1: + return 'Menor que 18 anos'; + case 2: + return 'Entre 18 anos e 24 anos'; + case 3: + return 'Entre 25 anos e 29 anos'; + case 4: + return 'Entre 30 anos e 34 anos'; + case 5: + return 'Entre 35 anos e 39 anos'; + case 6: + return 'Maior que 39 anos'; + default: + return 'Não classificado'; + } +}; diff --git a/src/libs/convert/agreement.js b/src/libs/convert/agreement.js index e9c5c774b0af69ed5b47d23e20893d7a953b8a4c..3490ef69770686f6f48880f373e4125d71038a04 100644 --- a/src/libs/convert/agreement.js +++ b/src/libs/convert/agreement.js @@ -1,3 +1,23 @@ +/* +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 agreement(id) { switch (id) { case 1: diff --git a/src/libs/convert/booleanVariable.js b/src/libs/convert/booleanVariable.js index 8ed8e007e2597049009072955c46319e32891a1c..64966010de42b0da4a9f8381f0811e081c734596 100644 --- a/src/libs/convert/booleanVariable.js +++ b/src/libs/convert/booleanVariable.js @@ -1,3 +1,23 @@ +/* +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 booleanVariable(id) { if (id == null) return 'Não Declarado'; diff --git a/src/libs/convert/citySize.js b/src/libs/convert/citySize.js index 3f50462b097d9340a0d7973460412a463aca7a17..9e1089b1bd4c25a8ea78b1ae5e7a6b6b8da08bc6 100644 --- a/src/libs/convert/citySize.js +++ b/src/libs/convert/citySize.js @@ -1,3 +1,23 @@ +/* +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 citySize(id) { switch (id) { case 1: diff --git a/src/libs/convert/contractType.js b/src/libs/convert/contractType.js index a20ab853531d6fde809b7f85ff197ab0a003a268..98ffcb84e02f2894a888d78a2d9422b670f841b0 100644 --- a/src/libs/convert/contractType.js +++ b/src/libs/convert/contractType.js @@ -1,3 +1,23 @@ +/* +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 contractType(id) { switch (id) { case 1: diff --git a/src/libs/convert/educationLevel.js b/src/libs/convert/educationLevel.js index e01c8be0f2a5ea682281bca1d95e396d9b2d9068..cc82319c491355d61b7a25d03335a34ead96a042 100644 --- a/src/libs/convert/educationLevel.js +++ b/src/libs/convert/educationLevel.js @@ -1,3 +1,23 @@ +/* +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 educationLevel(id) { switch (id) { case 1: diff --git a/src/libs/convert/educationLevelBasic.js b/src/libs/convert/educationLevelBasic.js index d667d09d57aa5cbe0b38d36f5f9a5aaece124fd8..3d166fe525019ab06f6ecbb59ede4e382ca57fa6 100644 --- a/src/libs/convert/educationLevelBasic.js +++ b/src/libs/convert/educationLevelBasic.js @@ -1,3 +1,23 @@ +/* +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 educationLevelBasic(id) { switch (id) { case 1: diff --git a/src/libs/convert/educationLevelMod.js b/src/libs/convert/educationLevelMod.js index f3797ee93a25085c444654923fe80d816ff671b3..e659517307f425170f8b5b5f0801388c4c2b55ae 100644 --- a/src/libs/convert/educationLevelMod.js +++ b/src/libs/convert/educationLevelMod.js @@ -1,3 +1,23 @@ +/* +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 educationLevelMod(id) { switch (id) { case 1: diff --git a/src/libs/convert/educationLevelSchoolYear.js b/src/libs/convert/educationLevelSchoolYear.js index f4fe43b73539fdf47650994f5773463d98f05a5f..07cc64f7f577d7984c1c1bfdee5cd55325d3d9be 100644 --- a/src/libs/convert/educationLevelSchoolYear.js +++ b/src/libs/convert/educationLevelSchoolYear.js @@ -1,3 +1,23 @@ +/* +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 educationLevelSchoolYear(id) { switch(id) { case 1: return 'Creche'; diff --git a/src/libs/convert/educationLevelShort.js b/src/libs/convert/educationLevelShort.js index ee97e956453c30af7ae7d37d60a6e2708b5dab2c..96b67f1521694ba815b5fb84cce07630b5cfd0f4 100644 --- a/src/libs/convert/educationLevelShort.js +++ b/src/libs/convert/educationLevelShort.js @@ -1,3 +1,23 @@ +/* +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 educationLevelShort(id) { switch (id) { case 1: diff --git a/src/libs/convert/educationType.js b/src/libs/convert/educationType.js index 0fffb330c453b0c6f71cbdd9e25078f1ac6e246b..8686822e1904c2e6fd67b0557f4b95294800d573 100644 --- a/src/libs/convert/educationType.js +++ b/src/libs/convert/educationType.js @@ -1,3 +1,23 @@ +/* +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 educationType(id) { switch (id) { case 1: diff --git a/src/libs/convert/ethnicGroup.js b/src/libs/convert/ethnicGroup.js index dfa51c810879cdd3655b73939766c2eae29333dd..1b6b92ea5827ba63b6d6ec181394872cf78b69ba 100644 --- a/src/libs/convert/ethnicGroup.js +++ b/src/libs/convert/ethnicGroup.js @@ -1,3 +1,23 @@ +/* +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 ethnicGroup(id) { switch (id) { case 0: diff --git a/src/libs/convert/ethnicGroupIES.js b/src/libs/convert/ethnicGroupIES.js new file mode 100644 index 0000000000000000000000000000000000000000..a57150fcc30d5e46df45ba9c1cd7d97761fc612f --- /dev/null +++ b/src/libs/convert/ethnicGroupIES.js @@ -0,0 +1,38 @@ +/* +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 ethnicGroupIES(id) { + switch (id) { + case 0: + return 'Aluno não quis declarar cor/raça'; + case 1: + return 'Branca'; + case 2: + return 'Preta'; + case 3: + return 'Parda'; + case 4: + return 'Amarela'; + case 5: + return 'Indígena'; + default: + return 'Não dispõe da informação (Não resposta)'; + } +}; diff --git a/src/libs/convert/ethnicGroupPnad.js b/src/libs/convert/ethnicGroupPnad.js index 93428cd4440f4559dda7ff10c429c135e263960a..3110d2cba2ef83a8cc2d2dd749fc0055797f7f1a 100644 --- a/src/libs/convert/ethnicGroupPnad.js +++ b/src/libs/convert/ethnicGroupPnad.js @@ -1,3 +1,23 @@ +/* +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 ethnicGroupPnad(id) { switch (id) { case 0: diff --git a/src/libs/convert/ethnicGroupTeacherIES.js b/src/libs/convert/ethnicGroupTeacherIES.js new file mode 100644 index 0000000000000000000000000000000000000000..7db2936ccc04200a58a7680f32c4a0d2c3122aaa --- /dev/null +++ b/src/libs/convert/ethnicGroupTeacherIES.js @@ -0,0 +1,38 @@ +/* +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 ethnicGroupTeacherIES(id) { + switch (id) { + case 0: + return 'Docente não quis declarar cor/raça'; + case 1: + return 'Branca'; + case 2: + return 'Preta'; + case 3: + return 'Parda'; + case 4: + return 'Amarela'; + case 5: + return 'Indígena'; + default: + return 'Não dispõe da informação (Não resposta)'; + } +}; diff --git a/src/libs/convert/extremesHouseholdIncome.js b/src/libs/convert/extremesHouseholdIncome.js index 67904c4ff2a4418f4dcb1f3516c8552bdabdcac7..2ef4ad9b158131898a0305e7b7db0ef1c7a5c1ac 100644 --- a/src/libs/convert/extremesHouseholdIncome.js +++ b/src/libs/convert/extremesHouseholdIncome.js @@ -1,3 +1,23 @@ +/* +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 extremesHouseholdIncome(id) { switch (id) { case 1: diff --git a/src/libs/convert/fifthHouseholdIncome.js b/src/libs/convert/fifthHouseholdIncome.js index ec7669a2a6180ce95d64888f1841fe2c017eeaa5..3b6a528d2fdace2ef4325d291e8a1c59e71496b4 100644 --- a/src/libs/convert/fifthHouseholdIncome.js +++ b/src/libs/convert/fifthHouseholdIncome.js @@ -1,3 +1,23 @@ +/* +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 fifthHouseholdIncome(id) { switch (id) { case 1: diff --git a/src/libs/convert/fullAgeRange.js b/src/libs/convert/fullAgeRange.js index e18b9156ed4e723fec83c939e8b01f148580d018..473de7656040aee942a84e663377c2f75715758e 100644 --- a/src/libs/convert/fullAgeRange.js +++ b/src/libs/convert/fullAgeRange.js @@ -1,3 +1,23 @@ +/* +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 ageRange(id) { switch (id) { case 1: diff --git a/src/libs/convert/gender.js b/src/libs/convert/gender.js index 085eb20e0aa7fa18c2e9c3106fc6c8869b0bd639..48ed9a1a88f04b9ebe68a3f1ef259f20fc1febbb 100644 --- a/src/libs/convert/gender.js +++ b/src/libs/convert/gender.js @@ -1,3 +1,23 @@ +/* +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 gender(id) { switch(id) { case 1: diff --git a/src/libs/convert/genderIES.js b/src/libs/convert/genderIES.js new file mode 100644 index 0000000000000000000000000000000000000000..8eba4fe45cfa21daaaa0d8ea96accb894d8e7453 --- /dev/null +++ b/src/libs/convert/genderIES.js @@ -0,0 +1,30 @@ +/* +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 genderIES(id) { + switch(id) { + case 1: + return 'Feminino'; + case 2: + return 'Masculino'; + default: + return 'Não declarado'; + } +}; diff --git a/src/libs/convert/genderPnad.js b/src/libs/convert/genderPnad.js index 9d5da51e6e8115d4c7de9baacd14b4e77756c11a..67ae37fd14df5c94d6ebff688e751d3c414d46df 100644 --- a/src/libs/convert/genderPnad.js +++ b/src/libs/convert/genderPnad.js @@ -1,3 +1,23 @@ +/* +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 genderPnad(id) { switch(id) { case 2: diff --git a/src/libs/convert/idhmLevel.js b/src/libs/convert/idhmLevel.js index c9f1845c6147e4f59bbbcf7aaecd5934ac5c8017..f92729b7d1fb8a7e4d947c54fc9927d59572e568 100644 --- a/src/libs/convert/idhmLevel.js +++ b/src/libs/convert/idhmLevel.js @@ -1,3 +1,23 @@ +/* +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 idhmLevel(id) { switch (id) { case 1: diff --git a/src/libs/convert/incomeLevel.js b/src/libs/convert/incomeLevel.js index f80faf8692c93bee328e8051cb39ab5b05745deb..f834e0c6fa95510a764aafca87965756bdbebecf 100644 --- a/src/libs/convert/incomeLevel.js +++ b/src/libs/convert/incomeLevel.js @@ -1,3 +1,23 @@ +/* +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 incomeLevel(id) { switch (id) { case 1: diff --git a/src/libs/convert/integralTime.js b/src/libs/convert/integralTime.js index 48f69c43af8b570e131c70ed5a795727530b2e29..57dab5b43e68aa351252d21bb9ccd2a05a3277f4 100644 --- a/src/libs/convert/integralTime.js +++ b/src/libs/convert/integralTime.js @@ -1,8 +1,30 @@ +/* +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 integralTime(id) { - if (id == null) - return 'Não se aplica (semi presencial e EaD)'; - else if (id == false) - return 'Não'; - else if (id == true) - return 'Sim'; + switch (id) { + case true: + return 'Sim'; + case false: + return 'Não'; + default: + return 'Não se aplica (semi presencial e EaD)'; + } }; diff --git a/src/libs/convert/location.js b/src/libs/convert/location.js index 606e06fc46a87bc5f1d1bf9c61aa8ad5ad06a353..da1dda6526b3686e25c39817b0823b5ad69d5604 100644 --- a/src/libs/convert/location.js +++ b/src/libs/convert/location.js @@ -1,3 +1,23 @@ +/* +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 location(id) { switch (id) { case 1: diff --git a/src/libs/convert/ocdeDetailed.js b/src/libs/convert/ocdeDetailed.js new file mode 100644 index 0000000000000000000000000000000000000000..e83dc4d933dc997e97c9ded6799bbc72f93ae376 --- /dev/null +++ b/src/libs/convert/ocdeDetailed.js @@ -0,0 +1,183 @@ +/* +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 ocdeDetailed(id) { + switch (id) { + case 142: + return 'Ciências da educação'; + case 144: + return 'Formação de professor da educação básica'; + case 145: + return 'Formação de professor de matérias específicas'; + case 146: + return 'Formação de professor de disciplinas profissionais'; + case 210: + return 'Artes (cursos gerais)'; + case 211: + return 'Belas artes'; + case 212: + return 'Música e artes cênicas'; + case 213: + return 'Técnicas audiovisuais e produção de mídia'; + case 214: + return 'Design e estilismo'; + case 215: + return 'Artesanato'; + case 220: + return 'Humanidades e letras (cursos gerais)'; + case 221: + return 'Religião e teologia'; + case 222: + return 'Línguas e culturas estrangeiras'; + case 223: + return 'Língua materna (vernácula)'; + case 225: + return 'História e arqueologia'; + case 226: + return 'Filosofia e ética'; + case 310: + return 'Ciências sociais e comportamentais (cursos gerais)'; + case 311: + return 'Psicologia'; + case 312: + return 'Sociologia e estudos culturais'; + case 313: + return 'Ciência política e educação cívica'; + case 314: + return 'Economia'; + case 321: + return 'Jornalismo e reportagem'; + case 322: + return 'Biblioteconomia, informação, arquivos'; + case 340: + return 'Comércio e administração (cursos gerais)'; + case 341: + return 'Vendas em atacado e varejo'; + case 342: + return 'Marketing e publicidade'; + case 343: + return 'Finanças, bancos, seguros'; + case 344: + return 'Contabilidade e tributação'; + case 345: + return 'Gerenciamento e administração'; + case 346: + return 'Secretariado e trabalhos de escritório'; + case 380: + return 'Direito'; + case 420: + return 'Ciências (cursos gerais)'; + case 421: + return 'Biologia e bioquímica'; + case 422: + return 'Ciências ambientais'; + case 440: + return 'Ciências físicas (cursos gerais)'; + case 441: + return 'Física'; + case 442: + return 'Química'; + case 443: + return 'Ciências da terra'; + case 461: + return 'Matemática'; + case 462: + return 'Estatística'; + case 481: + return 'Ciência da computação'; + case 482: + return 'Uso do computador'; + case 483: + return 'Processamento da informação'; + case 520: + return 'Engenharia e profissões de engenharia (cursos gerais)'; + case 521: + return 'Engenharia mecânica e metalurgia (trabalhos com metais)'; + case 522: + return 'Eletricidade e energia'; + case 523: + return 'Eletrônica e automação'; + case 524: + return 'Química e engenharia de processos'; + case 525: + return 'Veículos a motor, construção naval e aeronáutica'; + case 540: + return 'Fabricação e processamento (cursos gerais)'; + case 541: + return 'Processamento de alimentos'; + case 542: + return 'Têxteis, roupas, calçados, couros'; + case 543: + return 'Materiais (madeira, papel, plástico, vidro)'; + case 544: + return 'Mineração e extração'; + case 581: + return 'Arquitetura e urbanismo'; + case 582: + return 'Engenharia civil e de construção'; + case 621: + return 'Produção agrícola e pecuária'; + case 622: + return 'Horticultura'; + case 623: + return 'Engenharia florestal - silvicultura'; + case 624: + return 'Recursos pesqueiros'; + case 641: + return 'Veterinária'; + case 720: + return 'Saúde (cursos gerais)'; + case 721: + return 'Medicina'; + case 723: + return 'Enfermagem e atenção primária (assistência básica)'; + case 724: + return 'Odontologia'; + case 725: + return 'Tecnologias de diagnóstico e tratamento médico'; + case 726: + return 'Terapia e reabilitação'; + case 727: + return 'Farmácia'; + case 762: + return 'Serviço social e orientação'; + case 811: + return 'Hotelaria, restaurantes e serviços de alimentação'; + case 812: + return 'Viagens, turismo e lazer'; + case 813: + return 'Esportes'; + case 814: + return 'Ciências domésticas'; + case 815: + return 'Serviços de beleza'; + case 840: + return 'Transportes e serviços (cursos gerais)'; + case 850: + return 'Proteção ambiental (cursos gerais)'; + case 861: + return 'Proteção de pessoas e de propriedades'; + case 862: + return 'Saúde e segurança do trabalho'; + case 863: + return 'Setor militar e de defesa'; + default: + return 'Não classificada'; + } +}; \ No newline at end of file diff --git a/src/libs/convert/ocdeGeral.js b/src/libs/convert/ocdeGeral.js new file mode 100644 index 0000000000000000000000000000000000000000..70671edb3dbbb1083f10e8953c886a2a85bf29c4 --- /dev/null +++ b/src/libs/convert/ocdeGeral.js @@ -0,0 +1,44 @@ +/* +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 ocdeGeral(id) { + switch (id) { + case 0: + return 'Área básica'; + case 1: + return 'Educação'; + case 2: + return 'Humanidades e artes'; + case 3: + return 'Ciências sociais, negócios e direito'; + case 4: + return 'Ciências, matemática e computação'; + case 5: + return 'Engenharia, produção e construção'; + case 6: + return 'Agricultura e veterinária'; + case 7: + return 'Saúde e bem estar social'; + case 8: + return 'Serviços'; + default: + return 'Não classificada'; + } +}; diff --git a/src/libs/convert/ocdeSpecific.js b/src/libs/convert/ocdeSpecific.js new file mode 100644 index 0000000000000000000000000000000000000000..0133fa97a143dc342799c3a8b3b68c4d6dbb5fa5 --- /dev/null +++ b/src/libs/convert/ocdeSpecific.js @@ -0,0 +1,72 @@ +/* +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 ocdeSpecific(id) { + switch (id) { + case 1: + return 'Área básica de cursos'; + case 14: + return 'Formação de professor e ciências da educação'; + case 21: + return 'Artes'; + case 22: + return 'Humanidades e letras'; + case 31: + return 'Ciências sociais e comportamentais'; + case 32: + return 'Jornalismo e informação'; + case 34: + return 'Comércio e administração'; + case 38: + return 'Direito'; + case 42: + return 'Ciências da vida'; + case 44: + return 'Ciências físicas'; + case 46: + return 'Matemática e estatística'; + case 48: + return 'Computação'; + case 52: + return 'Engenharia e profissões correlatas'; + case 54: + return 'Produção e processamento'; + case 58: + return 'Arquitetura e construção'; + case 62: + return 'Agricultura, florestas e recursos pasqueiros'; + case 64: + return 'Veterinária'; + case 72: + return 'Saúde'; + case 76: + return 'Serviço social'; + case 81: + return 'Serviços pessoais'; + case 84: + return 'Serviços de transportes (cursos gerais)'; + case 85: + return 'Proteção ambiental'; + case 86: + return 'Serviços de segurança'; + default: + return 'Não classificada'; + } +}; diff --git a/src/libs/convert/period.js b/src/libs/convert/period.js index 600a71dfde47d9a09421434fe5b9a29599063a53..8e15e74cb8b89a2ba62f07e379d2c76866260b65 100644 --- a/src/libs/convert/period.js +++ b/src/libs/convert/period.js @@ -1,3 +1,23 @@ +/* +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 period(id) { switch(id) { case 1: diff --git a/src/libs/convert/pfe.js b/src/libs/convert/pfe.js index 8ef82c87554dec7a6bb6246083c2bda7fd771d29..c67a7141af9779bac92b145a06d084753bcf9c49 100644 --- a/src/libs/convert/pfe.js +++ b/src/libs/convert/pfe.js @@ -1,3 +1,23 @@ +/* +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 pfeName(id) { switch(id) { case 1: return 'População fora da escola menor de 1 ano'; diff --git a/src/libs/convert/ruralLocation.js b/src/libs/convert/ruralLocation.js index 7fa97d527a5001cf8d8ebf2f0a2fac4fcdd6cfe5..1c1bbc5ab41e86f2f39e1ff56a278ac7e4714728 100644 --- a/src/libs/convert/ruralLocation.js +++ b/src/libs/convert/ruralLocation.js @@ -1,3 +1,23 @@ +/* +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 ruralLocation(id) { switch (id) { case 1: diff --git a/src/libs/convert/schoolType.js b/src/libs/convert/schoolType.js new file mode 100644 index 0000000000000000000000000000000000000000..f485ecb9fabf74e860e34d1d082b0de1eacce36d --- /dev/null +++ b/src/libs/convert/schoolType.js @@ -0,0 +1,30 @@ +/* +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 studentDeficiency(id) { + switch (id) { + case 1: + return 'Pública'; + case 2: + return 'Privada'; + default: + return 'Não classificado'; + } +}; diff --git a/src/libs/convert/schoolYear.js b/src/libs/convert/schoolYear.js index f6b677ccd7c9ac39b8439504b0495e5d0e6dcbf0..40d9e638399b6ca3e08042d05c2abe8b53613168 100644 --- a/src/libs/convert/schoolYear.js +++ b/src/libs/convert/schoolYear.js @@ -1,3 +1,23 @@ +/* +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 schoolYear(id) { switch(id) { case 11: diff --git a/src/libs/convert/stateName.js b/src/libs/convert/stateName.js index 3fdfdba4cf8ad67cda3b922a4ffd5f43e1e96011..4760d2424316c3d80220098ad2e356b6cce811d9 100644 --- a/src/libs/convert/stateName.js +++ b/src/libs/convert/stateName.js @@ -1,3 +1,23 @@ +/* +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 stateName(id) { switch (id) { case 11: diff --git a/src/libs/convert/studentDeficiency.js b/src/libs/convert/studentDeficiency.js new file mode 100644 index 0000000000000000000000000000000000000000..c5ad0e0184de5f4eecf1ed889c7ea526f634ee0d --- /dev/null +++ b/src/libs/convert/studentDeficiency.js @@ -0,0 +1,30 @@ +/* +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 studentDeficiency(id) { + switch (id) { + case 0: + return 'Não'; + case 1: + return 'Sim'; + default: + return 'Não declarado' + } +}; diff --git a/src/libs/convert/teacherSchooling.js b/src/libs/convert/teacherSchooling.js new file mode 100644 index 0000000000000000000000000000000000000000..d31bd2ee9ff6b27fca20e2a2946dea75996e6cbb --- /dev/null +++ b/src/libs/convert/teacherSchooling.js @@ -0,0 +1,36 @@ +/* +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 teacherSchooling(id) { + switch (id) { + case 1: + return 'Sem graduação'; + case 2: + return 'Graduação'; + case 3: + return 'Especialização'; + case 4: + return 'Mestrado'; + case 5: + return 'Doutorado'; + default: + return 'Não declarado'; + } +}; diff --git a/src/libs/convert/teacherSituation.js b/src/libs/convert/teacherSituation.js new file mode 100644 index 0000000000000000000000000000000000000000..ae77189bdf25b7117c7a0618ed9f8c8aaaa0a71c --- /dev/null +++ b/src/libs/convert/teacherSituation.js @@ -0,0 +1,36 @@ +/* +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 teacherSituation(id) { + switch (id) { + case 1: + return 'Em exercício'; + case 2: + return 'Afastado para qualificação'; + case 3: + return 'Afastado para exercício em outros órgãos/entidades'; + case 4: + return 'Afastado por outros motivos'; + case 5: + return 'Afastado para tratamento de saúde'; + case 6: + return 'Falecido'; + } +}; diff --git a/src/libs/convert/transport.js b/src/libs/convert/transport.js new file mode 100644 index 0000000000000000000000000000000000000000..f5dbeadbcbfa0c6a90e29514edf288b4c61510c8 --- /dev/null +++ b/src/libs/convert/transport.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 teacherSituation(id) { + switch (id) { + case 1: + return 'public_transport'; + case 2: + return 'van_and_kombi'; + case 3: + return 'micro_bus'; + case 4: + return 'bus'; + case 5: + return 'bike'; + case 6: + return 'animal_traction'; + case 7: + return 'other_vehicle'; + case 8: + return 'waterway_5_Students'; + case 9: + return 'waterway_15_Students'; + case 10: + return 'waterway_35_Students'; + case 11: + return 'waterway_More_Than_35'; + case 12: + return 'subway_and_train'; + } +}; diff --git a/src/libs/convert/transportationManager.js b/src/libs/convert/transportationManager.js index 28961db9f23316bc66730dc2c2554a904322c18f..f0ab70290001d3a6d7596511e483ad4573fccd7d 100644 --- a/src/libs/convert/transportationManager.js +++ b/src/libs/convert/transportationManager.js @@ -1,3 +1,23 @@ +/* +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 transportationManager(id) { switch(id) { case 1: diff --git a/src/libs/convert/upperAdmDependency.js b/src/libs/convert/upperAdmDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..311475ff7774ba18eac407bf4b78a3d93bf438fb --- /dev/null +++ b/src/libs/convert/upperAdmDependency.js @@ -0,0 +1,40 @@ +/* +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 upperAdmDependency(id) { + switch (id) { + case 1: + return 'Pública Federal'; + case 2: + return 'Pública Estadual'; + case 3: + return 'Pública Municipal'; + case 4: + return 'Privada com fins lucrativos'; + case 5: + return 'Privada sem fins lucrativos'; + case 6: + return 'Privada confessional'; + case 7: + return 'Especial'; + default: + return 'Não classificada'; + } +}; diff --git a/src/libs/convert/upperEducationMod.js b/src/libs/convert/upperEducationMod.js new file mode 100644 index 0000000000000000000000000000000000000000..47fa9573cf6477f47f7ee435cbd733e9ce3e152b --- /dev/null +++ b/src/libs/convert/upperEducationMod.js @@ -0,0 +1,30 @@ +/* +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 upperEducationMod(id) { + switch (id) { + case 1: + return 'Presencial'; + case 2: + return 'A Distância'; + default: + return 'Não classificada'; + } +}; diff --git a/src/libs/convert/upperTurn.js b/src/libs/convert/upperTurn.js new file mode 100644 index 0000000000000000000000000000000000000000..b5cac83f361bebe821ef9be7b4a442500bd43985 --- /dev/null +++ b/src/libs/convert/upperTurn.js @@ -0,0 +1,34 @@ +/* +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 upperTurn(id) { + switch (id) { + case 1: + return 'Matutino'; + case 2: + return 'Vespertino'; + case 3: + return 'Noturno'; + case 4: + return 'Integral'; + default: + return 'Não aplicavel (Ead)'; + } +}; diff --git a/src/libs/convert/workRegime.js b/src/libs/convert/workRegime.js new file mode 100644 index 0000000000000000000000000000000000000000..f03d97a8ec20ff4466b9024e16a38a425c3465b1 --- /dev/null +++ b/src/libs/convert/workRegime.js @@ -0,0 +1,34 @@ +/* +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 workRegime(id) { + switch (id) { + case 1: + return 'Tempo Integral com dedicação exclusiva'; + case 2: + return 'Tempo Integral sem dedicação exclusiva'; + case 3: + return 'Tempo Parcial'; + case 4: + return 'Horista'; + default: + return 'Não declarado'; + } +}; diff --git a/src/libs/db/monet.js b/src/libs/db/monet.js index d19fb37dfac5ed68cc15c1762a822818dbbc82da..824a438c5d4956e8a0e601525c866feebac53e21 100644 --- a/src/libs/db/monet.js +++ b/src/libs/db/monet.js @@ -1,3 +1,23 @@ +/* +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 MonetDBPool = require('monetdb-pool'); const libs = `${process.cwd()}/libs`; diff --git a/src/libs/db/mongoose.js b/src/libs/db/mongoose.js index f9d2ed8ef59767e262f77fa21e2a93d444139145..e1927339fa242dfee3998f5fe04d96517d399bb9 100644 --- a/src/libs/db/mongoose.js +++ b/src/libs/db/mongoose.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; const config = require(`${libs}/config`); diff --git a/src/libs/db/query_exec.js b/src/libs/db/query_exec.js index 691117c5672df92ed565c2d4db5e27937b34dfbf..0437bf24cc75e8343cb99ed4a4d844fcfb2299f5 100644 --- a/src/libs/db/query_exec.js +++ b/src/libs/db/query_exec.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; diff --git a/src/libs/log.js b/src/libs/log.js index ddf0303f8481514b047aa6678894316500d25a96..58f8bfbab7ec0528070c387e310f60312fc975d6 100644 --- a/src/libs/log.js +++ b/src/libs/log.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; const config = require(`${libs}/config`); diff --git a/src/libs/middlewares/addMissing.js b/src/libs/middlewares/addMissing.js index f3d1b300abb37b388532b65d8cc3abc344fcca26..c98fa373f098c760af9ef0d21d67beb522ccf55c 100644 --- a/src/libs/middlewares/addMissing.js +++ b/src/libs/middlewares/addMissing.js @@ -1,3 +1,23 @@ +/* +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 addMissing(rqf){ return (req, res, next) => { let dims = Object.keys(req.dims).filter(i => {return i !== 'size';}); @@ -7,6 +27,7 @@ module.exports = function addMissing(rqf){ if(req.result.length === 0) return next(); let result = req.result; + let dimsValues = {}; result.forEach((r) => { dims.forEach((dim) => { @@ -54,7 +75,7 @@ module.exports = function addMissing(rqf){ if(r[rqfName] > newEntry[rqfName]) break; if(r[rqfName] == newEntry[rqfName] && r[rqfName2] > newEntry[rqfName2]) break; } - if (newEntry.dim1Value != undefined && newEntry.dim2Value != undefined) { + if (newEntry.dim1Value == undefined && newEntry.dim2Value == undefined) { let newResult = [...result.slice(0, index), newEntry, ...result.slice(index, result.length)]; result = newResult; } diff --git a/src/libs/middlewares/auth.js b/src/libs/middlewares/auth.js new file mode 100644 index 0000000000000000000000000000000000000000..2a9cb5b0964372cb18113a966092d54a877ff7a2 --- /dev/null +++ b/src/libs/middlewares/auth.js @@ -0,0 +1,62 @@ +/* +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 libs = `${process.cwd()}/libs`; + +const log = require(`${libs}/log`)(module); + +const request = require(`request`); + +const config = require(`${libs}/config`); + +const LDE_API_URL = config.lde_api.url; + +function auth(origin) { + return (req, res, next) => { + const options = { + url: `${LDE_API_URL}/verifyDownload`, + headers: { + 'Authorization': req.header('Authorization'), + 'origin': origin + } + }; + request.get(options, (err, response, body) => { + console.log("--------------->> "+body); + if(err) + console.log("ERRO!"); + let resp; + try { + resp = JSON.parse(body); + } catch(e) { + return res.json({access: 'Unauthorized'}); + } + if(resp.access === 'Authorized') { + req.name = resp.name; + req.email = resp.email; + req.userId = resp.userId; + console.log("==========>"+req.userId); + return next(); + } + res.json({access: 'Unauthorized'}); + }); + } +} + +module.exports = auth; diff --git a/src/libs/middlewares/checkVersion.js b/src/libs/middlewares/checkVersion.js index c3187adba9081e2a992d09df36e839efc23dfca0..a103afa6d995b8213c9d424ca452128c037aeedc 100644 --- a/src/libs/middlewares/checkVersion.js +++ b/src/libs/middlewares/checkVersion.js @@ -1,3 +1,23 @@ +/* +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 curPath = process.cwd(); const libs = `${process.cwd()}/libs`; const log = require(`${libs}/log`)(module); diff --git a/src/libs/middlewares/downloadDatabase.js b/src/libs/middlewares/downloadDatabase.js deleted file mode 100644 index c4672ff0bf5d925d7d8d0466a260d3025fbc4e09..0000000000000000000000000000000000000000 --- a/src/libs/middlewares/downloadDatabase.js +++ /dev/null @@ -1,88 +0,0 @@ -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const execute = require(`${libs}/middlewares/query`).execute; - -const request = require(`request`); - -const config = require(`${libs}/config`); - -const Download = require(`${libs}/models/download`); - -module.exports = function download(table, mappingTable) { - return (req, res, next) => { - // First, query the mapping - execute(`SELECT target_name, name FROM ${mappingTable}`, undefined, (err, result) => { - if(err) { - log.error(err.stack); - next(new Error('Request could not be satisfied due to a database error.')); - } else { - let header = ''; - req.sql.from(table); - result.forEach((field) => { - req.sql.field(`CASE ${table}.${field.name} WHEN true THEN 1 WHEN false THEN 0 ELSE ${table}.${field.name} END AS ${field.target_name}`); - // req.sql.field(table + '.' + field.name, field.target_name); - if(header === '') header += field.target_name; - else header = header + ';' + field.target_name; - }); - - let form = { - query: req.sql.toString(), - table: req.sql.tableFrom, - name: req.sql.tableFrom, - username: req.user.name, - email: req.user.email, - header - }; - - request.post(config.cdn.url + '/api/v1/file', {form}, (err, response, body) => { - if(err) { - log.error(err); - return res.json({error: err}); - } - - Download.findOne({query: req.sql.toString()}, (err, download) => { - if(download) { - download.updatedAt = Date.now(); - if(download.userId != req.user._id) { - let dl = new Download({ - userId: req.user._id, - table, - name: req.query.name, - mappingTable, - query: req.sql.toString(), - status: 'Enviando', - expired: false - }); - console.log(dl); - dl.save((err) => { - if(err) log.error(err); - }); - } - } else { - download = new Download({ - userId: req.user._id, - table, - name: req.query.name, - mappingTable, - query: req.sql.toString(), - query: req.sql.toString(), - status: 'Enviando', - expired: false - }); - console.log(download); - } - - download.save((err) => { - if(err) { - log.error(err); - } - res.json({msg: 'Wait for download email', waitForIt: true}); - }); - }); - }); - } - }); - } -}; \ No newline at end of file diff --git a/src/libs/middlewares/email.js b/src/libs/middlewares/email.js index 7e0403d423cebd1bd0a8c6c31f57eef5773860f4..66c4740cae8b649a711e3ad311c5ef894cc59517 100644 --- a/src/libs/middlewares/email.js +++ b/src/libs/middlewares/email.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; const log = require(`${libs}/log`)(module); const config = require(`${libs}/config`); diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js index cb4c8cc1553ae711719878eb84d30ec29d3e993c..d800505c1e7d9213199f0e0aa5b28d70a2c3c5ba 100644 --- a/src/libs/middlewares/id2str.js +++ b/src/libs/middlewares/id2str.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; const gender = require(`${libs}/convert/gender`); const period = require(`${libs}/convert/period`); @@ -7,6 +27,7 @@ const admDependencyPriv = require(`${libs}/convert/admDependencyPriv`); const location = require(`${libs}/convert/location`); const ruralLocation = require(`${libs}/convert/ruralLocation`); const ethnicGroup = require(`${libs}/convert/ethnicGroup`); +const ethnicGroupIES = require(`${libs}/convert/ethnicGroupIES`); const agreement = require(`${libs}/convert/agreement`); const booleanVariable = require(`${libs}/convert/booleanVariable`); const educationLevel = require(`${libs}/convert/educationLevel`); @@ -21,18 +42,42 @@ const contractType = require(`${libs}/convert/contractType`); const ethnicGroupPnad = require(`${libs}/convert/ethnicGroupPnad`); const ageRange = require(`${libs}/convert/ageRange`); const ageRangeAll = require(`${libs}/convert/ageRangeAll`); +const ageStudentCode = require(`${libs}/convert/ageStudentCode`); const fullAgeRange = require(`${libs}/convert/fullAgeRange`); const genderPnad = require(`${libs}/convert/genderPnad`); const fifthHouseholdIncome = require(`${libs}/convert/fifthHouseholdIncome`); const extremesHouseholdIncome = require(`${libs}/convert/extremesHouseholdIncome`); const educationLevelBasic = require(`${libs}/convert/educationLevelBasic`); const useTransport = require(`${libs}/convert/booleanVariable`); +const transport = require(`${libs}/convert/transport`); const useTransportPublic = require(`${libs}/convert/booleanVariable`); const transportationManager = require(`${libs}/convert/transportationManager`); const specialClass = require(`${libs}/convert/booleanVariable`); const integralTime = require(`${libs}/convert/integralTime`); const educationLevelSchoolYear = require(`${libs}/convert/educationLevelSchoolYear`); const pfe = require(`${libs}/convert/pfe`); +const upperAdmDependency = require(`${libs}/convert/upperAdmDependency`); +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 academicLevel = require(`${libs}/convert/academicLevel`); +const upperEducationMod = require(`${libs}/convert/upperEducationMod`); +const studentDeficiency = require(`${libs}/convert/studentDeficiency`); +const schoolType = require(`${libs}/convert/schoolType`); +const upperTurn = require(`${libs}/convert/upperTurn`); +const teacherSituation = require(`${libs}/convert/teacherSituation`); +const workRegime = require(`${libs}/convert/workRegime`); +const substitute = require(`${libs}/convert/booleanVariable`); +const visitor = require(`${libs}/convert/booleanVariable`); +const eadTeacher = require(`${libs}/convert/booleanVariable`); +const graduationPresential = require(`${libs}/convert/booleanVariable`); +const postgraduateEadTeacher = require(`${libs}/convert/booleanVariable`); +const postgraduatePresentialTeacher = require(`${libs}/convert/booleanVariable`); +const teacherSchooling = require(`${libs}/convert/teacherSchooling`); +const ethnicGroupTeacherIES = require(`${libs}/convert/ethnicGroupTeacherIES`); +const genderIES = require(`${libs}/convert/genderIES`); +const deficiency = require(`${libs}/convert/studentDeficiency`); const ids = { gender_id: gender, @@ -77,6 +122,34 @@ const ids = { special_class_id: specialClass, education_level_school_year_id: educationLevelSchoolYear, pfe_id: pfe, + upper_adm_dependency_id: upperAdmDependency, + academic_organization_id: academicOrganization, + ocde_specific_id: ocdeSpecific, + ocde_geral_id: ocdeGeral, + ocde_detailed_id: ocdeDetailed, + 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, + capital_id: booleanVariable, + ethnic_group_ies_id: ethnicGroupIES, + teacher_situation_id: teacherSituation, + work_regime_id: workRegime, + substitute_id: booleanVariable, + visitor_id: booleanVariable, + ead_teacher_id: eadTeacher, + graduation_presential_id: graduationPresential, + postgraduate_ead_teacher_id: postgraduateEadTeacher, + postgraduate_presential_teacher_id: postgraduatePresentialTeacher, + teacher_schooling_id: teacherSchooling, + ethnic_group_teacher_ies_id: ethnicGroupTeacherIES, + gender_ies_id: genderIES, + deficiency_id: deficiency, + age_student_code_id: ageStudentCode, + transport_id: transport }; function transform(removeId=false) { @@ -124,6 +197,7 @@ module.exports = { educationLevelBasic, educationLevelMod, educationLevelShort, + educationLevelSchoolYear, admDependency, admDependencyPriv, location, @@ -140,6 +214,7 @@ module.exports = { ethnicGroupPnad, ageRange, ageRangeAll, + ageStudentCode, fullAgeRange, genderPnad, fifthHouseholdIncome, @@ -147,5 +222,29 @@ module.exports = { useTransport, transportationManager, specialClass, - integralTime + integralTime, + upperAdmDependency, + academicOrganization, + ocdeSpecific, + ocdeGeral, + ocdeDetailed, + academicLevel, + upperEducationMod, + studentDeficiency, + schoolType, + ethnicGroupIES, + upperTurn, + teacherSituation, + workRegime, + substitute, + visitor, + eadTeacher, + graduationPresential, + postgraduateEadTeacher, + postgraduatePresentialTeacher, + teacherSchooling, + ethnicGroupTeacherIES, + genderIES, + deficiency, + transport }; diff --git a/src/libs/middlewares/multiQuery.js b/src/libs/middlewares/multiQuery.js index 7bf37c5d9086f3a97405ef2bfbb61553afd0d2bf..9dc5b3df9833c897ba2ac9f9a2000b68112b5642 100644 --- a/src/libs/middlewares/multiQuery.js +++ b/src/libs/middlewares/multiQuery.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; const log = require(`${libs}/log`)(module); const db = require(`${libs}/db/query_exec`); diff --git a/src/libs/middlewares/oauth2.js b/src/libs/middlewares/oauth2.js deleted file mode 100644 index cc9a45ede4a3158bc055166202c6d20fb84a6dff..0000000000000000000000000000000000000000 --- a/src/libs/middlewares/oauth2.js +++ /dev/null @@ -1,121 +0,0 @@ -const oauth2orize = require('oauth2orize'); -const passport = require('passport'); -const crypto = require('crypto'); - -const libs = `${process.cwd()}/libs`; - -const config = require(`${libs}/config`); -const log = require(`${libs}/log`)(module); - -const db = require(`${libs}/db/mongoose`); -const User = require(`${libs}/models/user`); -const AccessToken = require(`${libs}/models/accessToken`); -const RefreshToken = require(`${libs}/models/refreshToken`); - -// create OAuth 2.0 server -let aserver = oauth2orize.createServer() - -// Generic error handler -let errFn = (cb, err) => { - if (err) { - return cb(err) - } -} - -// Destroys any old tokens and generates a new access and refresh token -let generateTokens = (data, done) => { - // curries in `done` callback so we don't need to pass it - let errorHandler = errFn.bind(undefined, done); - let refreshToken; - let refreshTokenValue; - let token; - let tokenValue; - - RefreshToken.remove(data, errorHandler); - AccessToken.remove(data, errorHandler); - - tokenValue = crypto.randomBytes(32).toString('hex'); - refreshTokenValue = crypto.randomBytes(32).toString('hex'); - - data.token = tokenValue; - token = new AccessToken(data); - - data.token = refreshTokenValue; - refreshToken = new RefreshToken(data); - - refreshToken.save(errorHandler); - - token.save((err) => { - if (err) { - log.error(err); - return done(err); - } - done(null, tokenValue, refreshTokenValue, { - 'expires_in': config.security.tokenLife - }); - }) -}; - -// Exchange username & password for access token. -aserver.exchange(oauth2orize.exchange.password((client, username, password, scope, done) => { - User.findOne({ email: username }, (err, user) => { - if (err) { - return done(err); - } - - if (!user || !user.checkPassword(password)) { - return done(null, false); - } - - var model = { - userId: user._id, - clientId: client._id - }; - log.info(`Gerando token para usuário ${user.name}`); - generateTokens(model, done); - }) - -})); - -// Exchange refreshToken for access token. -aserver.exchange(oauth2orize.exchange.refreshToken((client, refreshToken, scope, done) =>{ - RefreshToken.findOne({ token: refreshToken, clientId: client._id }, (err, token) => { - if (err) { - return done(err); - } - - if (!token) { - return done(null, false); - } - - User.findById(token.userId, (err, user) => { - if (err) { - log.error(err); - return done(err); - } - if (!user) { - return done(null, false); - } - - var model = { - userId: user._id, - clientId: client._id - }; - - generateTokens(model, done); - }) - }) -})) - -// token endpoint -// -// `token` middleware handles client requests to exchange authorization grants -// for access tokens. Based on the grant type being exchanged, the above -// exchange middleware will be invoked to handle the request. Clients must -// authenticate when making requests to this endpoint. - -exports.token = [ - passport.authenticate(['oauth2-client-password'], { session: false }), - aserver.token(), - aserver.errorHandler() -]; diff --git a/src/libs/middlewares/passport.js b/src/libs/middlewares/passport.js deleted file mode 100644 index ab895a9604072e3b77a6384ac0c0f9066dcf6753..0000000000000000000000000000000000000000 --- a/src/libs/middlewares/passport.js +++ /dev/null @@ -1,67 +0,0 @@ -const passport = require('passport'); -const ClientPasswordStrategy = require('passport-oauth2-client-password'); -const BearerStrategy = require('passport-http-bearer').Strategy; - -const libs = `${process.cwd()}/libs`; -const config = require(`${libs}/config`); - -const User = require(`${libs}/models/user`); -const Client = require(`${libs}/models/client`); -const AccessToken = require(`${libs}/models/accessToken`); -const RefreshToken = require(`${libs}/models/refreshToken`); -const email = require(`${libs}/middlewares/email`); - -passport.use(new ClientPasswordStrategy( (clientId, clientSecret, done) => { - Client.findOne({ _id: clientId }, (err, client) => { - if (err) { - return done(err); - } - - if (!client) { - return done(null, false); - } - - if (client.clientSecret !== clientSecret) { - return done(null, false); - } - - return done(null, client); - }) - } -)); - -passport.use(new BearerStrategy( (accessToken, done) => { - AccessToken.findOne({ token: accessToken }, (err, token) => { - if (err) { - return done(err); - } - - if (!token) { - return done(null, false); - } - - if( Math.round((Date.now()-token.created)/1000) > config.security.tokenLife) { - AccessToken.remove({ token: accessToken }, (err) => { - if (err) { - return done(err); - } - }); - - return done(null, false, { msg: 'Token expired' }); - } - - User.findById(token.userId, function(err, usuario) { - if (err) { - return done(err); - } - - if (!usuario) { - return done(null, false, { msg: 'Unknown user' }); - } - - var info = { scope: '*' }; - done(null, usuario, info); - }) - }) - } -)); diff --git a/src/libs/middlewares/query.js b/src/libs/middlewares/query.js index b724d93dd8e36709033eb171cceaafe9b6ff7659..68077aa982e4fe69760c9ab33d5150cbb6471e94 100644 --- a/src/libs/middlewares/query.js +++ b/src/libs/middlewares/query.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; const log = require(`${libs}/log`)(module); const db = require(`${libs}/db/query_exec`); diff --git a/src/libs/middlewares/reqQueryFields.js b/src/libs/middlewares/reqQueryFields.js index 61f989630effb5bd5a03519641eb0ca94bf781b0..8ac231fc2f0f98e83c5dedd5e466400655f7ad51 100644 --- a/src/libs/middlewares/reqQueryFields.js +++ b/src/libs/middlewares/reqQueryFields.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; const log = require(`${libs}/log`)(module); diff --git a/src/libs/middlewares/response.js b/src/libs/middlewares/response.js index 62e1d9601c971b67abcf3a596160c9087850df03..c7bb6ffee9d8fd6376cb9a4538d6dcb22a9d60d0 100644 --- a/src/libs/middlewares/response.js +++ b/src/libs/middlewares/response.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; const log = require(`${libs}/log`)(module); const xml = require('js2xmlparser'); diff --git a/src/libs/models/accessToken.js b/src/libs/models/accessToken.js deleted file mode 100644 index daab5898a66b952f72359d9685e951b1acf980b7..0000000000000000000000000000000000000000 --- a/src/libs/models/accessToken.js +++ /dev/null @@ -1,29 +0,0 @@ -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const User = require(`${libs}/models/user`); -const Client = require(`${libs}/models/client`); - -let AccessToken = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - clientId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'Client' - }, - token: { - type: String, - unique: true, - required: true - }, - createdAt: { - type: Date, - default: Date.now - } -}); - -module.exports = mongoose.model('AccessToken', AccessToken); diff --git a/src/libs/models/client.js b/src/libs/models/client.js deleted file mode 100644 index 8ac80d8d158705f63efbbecc72de37d1fef6a3ac..0000000000000000000000000000000000000000 --- a/src/libs/models/client.js +++ /dev/null @@ -1,17 +0,0 @@ -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; - -let Client = new Schema({ - name: { - type: String, - unique: true, - required: true - }, - clientSecret: { - type: String, - required: true, - unique: true - } -}); - -module.exports = mongoose.model('Client', Client); diff --git a/src/libs/models/download.js b/src/libs/models/download.js deleted file mode 100644 index 989896d9a2b6547c11c9b1bc71019db3bb7617a5..0000000000000000000000000000000000000000 --- a/src/libs/models/download.js +++ /dev/null @@ -1,53 +0,0 @@ -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); - -let Download = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - table: { - type: String, - required: true - }, - name: { - type: String, - required: true - }, - mappingTable: { - type: String, - required: true - }, - query: { - type: String, - required: true - }, - createdAt: { - type: Date, - required: true, - default: Date.now - }, - updatedAt: { - type: Date, - required: true, - default: Date.now - }, - status: { - type: String - }, - size: { - type: Number - }, - expired: { - type: Boolean - }, - link: { - type: String - } -}); - -module.exports = mongoose.model('Download', Download); diff --git a/src/libs/models/pqr.js b/src/libs/models/pqr.js index f92703188323cef17807f70f1f2198b54a13aa1b..46fa3c7de00c87e35260b20190084b500e839735 100644 --- a/src/libs/models/pqr.js +++ b/src/libs/models/pqr.js @@ -1,8 +1,27 @@ +/* +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 mongoose = require('mongoose') const libs = `${process.cwd()}/libs`; const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); const Schema = mongoose.Schema; diff --git a/src/libs/models/refreshToken.js b/src/libs/models/refreshToken.js deleted file mode 100644 index c5f8fd63cdd30733bb60f341e6617420d945b037..0000000000000000000000000000000000000000 --- a/src/libs/models/refreshToken.js +++ /dev/null @@ -1,30 +0,0 @@ -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const User = require(`${libs}/models/user`); -const Client = require(`${libs}/models/client`); - -let RefreshToken = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - clientId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'Client' - }, - token: { - type: String, - unique: true, - required: true - }, - createdAt: { - type: Date, - default: Date.now - } -}); - -module.exports = mongoose.model('RefreshToken', RefreshToken); - diff --git a/src/libs/models/resetToken.js b/src/libs/models/resetToken.js deleted file mode 100644 index 322d528188a78525b4e003a65c6355fc0c2039c6..0000000000000000000000000000000000000000 --- a/src/libs/models/resetToken.js +++ /dev/null @@ -1,46 +0,0 @@ -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); -const uuid = require('node-uuid'); - -let ResetToken = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - token: { - type: String, - required: true - }, - reset: { - type: Boolean, - required: true, - default: false - }, - createdAt: { - type: Date, - required: true, - default: Date.now - } -}); - -ResetToken.methods.createResetToken = function (done) { - let resetToken = this; - let token = uuid.v4(); - resetToken.set('token', token); - resetToken.reset = false; - resetToken.save(function(err) { - if (err) - return done(err); - return done(null, token); - }) -} -ResetToken.methods.hasExpired = function () { - var now = new Date(); - return (now - this.createdAt) > 86400; //Expire if token is 1 day old -}; - -module.exports = mongoose.model('ResetToken', ResetToken); diff --git a/src/libs/models/simulation.js b/src/libs/models/simulation.js index f1d3b0bd2448fe7640affd57e3d33d330ad7912c..e5aa6a1f07e5313de636e5d5da0166e18e9cb67d 100644 --- a/src/libs/models/simulation.js +++ b/src/libs/models/simulation.js @@ -1,16 +1,34 @@ +/* +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 mongoose = require('mongoose') const libs = `${process.cwd()}/libs`; const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); const Schema = mongoose.Schema; let SimulationSchema = new Schema({ userId: { - type: Schema.Types.ObjectId, + type: Number, required: true, - ref: 'User' }, content: { type: String, diff --git a/src/libs/models/user.js b/src/libs/models/user.js deleted file mode 100644 index 0d54e4175fbf3336c4386bcc252d235dc6b478ce..0000000000000000000000000000000000000000 --- a/src/libs/models/user.js +++ /dev/null @@ -1,119 +0,0 @@ -const mongoose = require('mongoose'); -const crypto = require('crypto') -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const Schema = mongoose.Schema; - -// set up a mongoose model -var UserSchema = new Schema({ - email: { - type: String, - unique: true, - required: [true, 'O campo Email é obrigatório.'] - }, - hashedPassword: { - type: String, - required: [true, 'O campo Senha é obrigatório.'] - }, - salt: { - type: String, - required: true - }, - name: { - type: String, - required: [true, 'O campo Nome é obrigatório.'] - }, - nickname: { - type: String, - required: [true, 'O campo Apelido é obrigatório.'] - }, - cpf:{ - type: String, - unique: true, - required: [true, 'O campo CPF é obrigatório.'] - }, - cep:{ - type: String, - required: [true, 'O campo CEP é obrigatório.'] - }, - schooling: { - type: String, - required: [true, 'O campo Formação é obrigatório.'] - }, - course: { - type: String, - }, - complement: { - type: String, - }, - address: { - type: String, - }, - phone: { - type: String, - }, - segment: { - type: String, - required: [true, 'O campo Segmento é obrigatório.'] - }, - role: { - type: String, - required: [true, 'O campo Função é obrigatório.'] - }, - institutionName: { - type: String, - required: [true, 'O campo Instituição em que trabalha ou estuda é obrigatório.'] - }, - state: { - type: String, - required: [true, 'O campo Estado é obrigatório.'] - }, - city: { - type: String, - required: [true, 'O campo Cidade é obrigatório.'] - }, - receiveEmails: { - type: Boolean - }, - createdAt: { - type: Date, - default: Date.now - }, - origin: { - type: String, - enum: ['LDE', 'SimCAQ'], - required: [true, 'O campo origem é obrigatória e aceita apenas os valores "LDE" ou "SimCAQ"'] - }, - verified: { - type: Boolean, - default: false - }, - citesegment: { - type: String - }, - citerole: { - type: String - }, - admin: { - type: Boolean, - default: false - } -}); - -UserSchema.methods.encryptPassword = function(password) { - return crypto.pbkdf2Sync(password+'', this.salt, 10000, 512, 'sha512'); -}; - -UserSchema.virtual('password').set(function(password) { - this._plainPassword = password+''; - this.salt = crypto.randomBytes(128).toString('hex'); - this.hashedPassword = this.encryptPassword(password).toString('hex'); -}).get(function() { - return this._plainPassword; -}); - -UserSchema.methods.checkPassword = function(password) { - return this.encryptPassword(password).toString('hex') === this.hashedPassword; -} - -module.exports = mongoose.model('User', UserSchema); diff --git a/src/libs/models/verificationToken.js b/src/libs/models/verificationToken.js deleted file mode 100644 index ef7e109e16364874ea7d3f4b07b6e19ce74c3eae..0000000000000000000000000000000000000000 --- a/src/libs/models/verificationToken.js +++ /dev/null @@ -1,41 +0,0 @@ -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); -const uuid = require('node-uuid'); - -let VerificationToken = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - token: { - type: String, - required: true - }, - verified: { - type: Boolean, - required: true, - default: false - }, - createdAt: { - type: Date, - required: true, - default: Date.now - } -}); - -VerificationToken.methods.createVerificationToken = function(done) { - let verificationToken = this; - let token = uuid.v4(); - verificationToken.set('token', token); - verificationToken.verified = false; - verificationToken.save(function(err) { - if (err) return done(err); - return done(null, token); - }) -} - -module.exports = mongoose.model('VerificationToken', VerificationToken); diff --git a/src/libs/routes/api.js b/src/libs/routes/api.js index c9150981ec646981c8999d25b21ab93cbb3a9c5a..e52745ed784ae50fb3c15fae72cf4a27fa59bd30 100644 --- a/src/libs/routes/api.js +++ b/src/libs/routes/api.js @@ -1,3 +1,23 @@ +/* +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 api = express(); @@ -20,8 +40,6 @@ const school = require('./school'); const simulation = require('./simulation'); -const user = require('./user'); - const classroom = require('./classroom'); const teacher = require('./teacher'); @@ -44,16 +62,8 @@ const idhmr = require('./idhmr'); const idhml = require('./idhml'); -const oauth2 = require(`${libs}/middlewares/oauth2`); - -const verifyToken = require(`${libs}/routes/verifyToken`); - -const resetToken = require(`${libs}/routes/resetToken`); - const educationYears = require(`${libs}/routes/educationYears`); -const downloads = require(`${libs}/routes/downloads`); - const infrastructure = require(`${libs}/routes/infrastructure`); const schoolInfrastructure = require(`${libs}/routes/schoolInfrastructure`); @@ -86,12 +96,19 @@ const employees = require(`${libs}/routes/employees`); const financial = require(`${libs}/routes/financial`); +const universityEnrollment = require(`${libs}/routes/universityEnrollment`); + +const courseCount = require(`${libs}/routes/courseCount`); + +const university = require(`${libs}/routes/university`); + +const universityTeacher = require(`${libs}/routes/universityTeacher`); + api.get('/', (req, res) => { res.json({ msg: 'SimCAQ API is running' }); }); // mount API routes -api.use('/user', user); api.use('/simulation', simulation); api.use('/class', classes); api.use('/enrollment', enrollment); @@ -110,11 +127,7 @@ api.use('/rate_school', rateSchool); api.use('/gloss_enrollment_ratio', glossEnrollmentRatio); api.use('/liquid_enrollment_ratio', liquidEnrollmentRatio); api.use('/idhml', idhml); -api.use('/auth/token', oauth2.token); -api.use('/verify', verifyToken); -api.use('/reset', resetToken); api.use('/education_years', educationYears); -api.use('/downloads', downloads); api.use('/infrastructure', infrastructure); api.use('/school_infrastructure', schoolInfrastructure); api.use('/distribution_factor', distributionFactor); @@ -131,6 +144,9 @@ api.use('/portal_mec_inep', portalMecInep); api.use('/enrollment_projection', enrollmentProjection); api.use('/employees', employees); api.use('/financial', financial); - +api.use('/university_enrollment', universityEnrollment); +api.use('/university', university); +api.use('/university_teacher', universityTeacher); +api.use('/course_count', courseCount); module.exports = api; diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js index a52ce99d6cc55562bc719f93ccc11f92e0d72ecc..c1b8d4e4033dc59fd09ae5e36cc7d7df39d8ee58 100644 --- a/src/libs/routes/auxiliar.js +++ b/src/libs/routes/auxiliar.js @@ -1,3 +1,23 @@ +/* +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 auxiliarApp = express.Router(); @@ -18,10 +38,6 @@ const id2str = require(`${libs}/middlewares/id2str`); const config = require(`${libs}/config`); -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - const addMissing = require(`${libs}/middlewares/addMissing`); const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; @@ -39,7 +55,8 @@ auxiliarApp.get('/year_range', (req, res, next) => { auxiliarApp.get('/years', (req, res, next) => { req.sql.from('docente'). - field('DISTINCT docente.ano_censo', 'year'); + field('DISTINCT docente.ano_censo', 'year') + .where('docente.ano_censo <= 2017'); next(); }, query, response('years')); @@ -271,12 +288,12 @@ rqf.addField({ }, 'filter').addValue({ name: 'location', table: 'docente', - tableField: 'cod_localizacao', + tableField: 'localizacao_id', resultField: 'location_id', where: { relation: '=', type: 'integer', - field: 'cod_localizacao' + field: 'localizacao_id' } }).addValue({ name: 'min_year', @@ -322,7 +339,7 @@ rqf.addField({ // LDE auxiliarApp.get('/', rqf.parse(), (req, res, next) => { - req.sql.field('COUNT(DISTINCT docente.id)', 'total') + req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total') .field("'Brasil'", 'name') .field('docente.ano_censo', 'year') .from('docente') @@ -334,7 +351,7 @@ auxiliarApp.get('/', rqf.parse(), (req, res, next) => { // SimCAQ auxiliarApp.get('/count', rqf.parse(), (req, res, next) => { - req.sql.field('COUNT(DISTINCT docente.id)', 'total') + req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total') .field("'Brasil'", 'name') .field('docente.ano_censo', 'year') .from('docente') @@ -344,6 +361,4 @@ auxiliarApp.get('/count', rqf.parse(), (req, res, next) => { next(); }, rqf.build(), query, addMissing(rqf), id2str.transform(), response('auxiliar')); -auxiliarApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('docente', 'mapping_docente')); - module.exports = auxiliarApp; diff --git a/src/libs/routes/city.js b/src/libs/routes/city.js index 1f6aee12630ba58b48f2f53bb17fc9ab10b4fad1..09a2763050a7897829a6c249fc538c3afb947610 100644 --- a/src/libs/routes/city.js +++ b/src/libs/routes/city.js @@ -1,3 +1,23 @@ +/* +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 cityApp = express.Router(); @@ -69,7 +89,9 @@ cityApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.sql.from('municipio') .field('municipio.nome', 'name') .field('municipio.id') - .field('municipio.estado_id', 'state_id'); + .field('municipio.estado_id', 'state_id') + .field('municipio.longitude', 'longitude') + .field('municipio.latitude', 'latitude'); next(); }, query, response('city')); diff --git a/src/libs/routes/class.js b/src/libs/routes/class.js index a01fa0ab2a1e6e347f994ff24f399835a29dbc48..6967ddf8502c98c991ab455b254c37b66d5b1872 100644 --- a/src/libs/routes/class.js +++ b/src/libs/routes/class.js @@ -1,3 +1,23 @@ +/* +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 classApp = express.Router(); @@ -18,12 +38,8 @@ const id2str = require(`${libs}/middlewares/id2str`); const config = require(`${libs}/config`); -const download = require(`${libs}/middlewares/downloadDatabase`); - const addMissing = require(`${libs}/middlewares/addMissing`); -const passport = require('passport'); - const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; let rqfCount = new ReqQueryFields(); @@ -369,6 +385,4 @@ classApp.get('/', rqfCount.parse(), rqfCount.build(), (req, res, next) => { next(); }, query, addMissing(rqfCount), id2str.transform(), response('class')); -classApp.get('/download', passport.authenticate('bearer', { session: false }), rqfCount.parse(), rqfCount.build(), download('turma', 'mapping_turma')); - module.exports = classApp; diff --git a/src/libs/routes/classCount.js b/src/libs/routes/classCount.js index aba72e13eeeaa5c78d29ac42c3faba7d8dadb525..8bea388537c4ef63ac5e554befc4aa0ee0052645 100644 --- a/src/libs/routes/classCount.js +++ b/src/libs/routes/classCount.js @@ -1,3 +1,23 @@ +/* +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 classCountApp = express.Router(); @@ -318,6 +338,23 @@ function addNullFields(result) { } prevFirstDimId = d; }); + console.log("FUNCTION"); + console.log(result); +} + +function addZeroFields(result) { + let i; + for (i=0; i < result.length; i++) { + let hasTotal = result[i].hasOwnProperty("total"); + if (hasTotal == true) { + result[i].average = 0.0; + result[i].median = 0.0; + result[i].stddev = 0.0; + result[i].first_qt = 0.0; + result[i].third_qt = 0.0; + } + } + return result; } // SimCAQ @@ -337,7 +374,7 @@ classCountApp.get('/count', rqf.parse(), (req, res, next) => { }, rqf.build(), query, addMissing(rqf), id2str.transform(), response('class_count')); // LDE -classCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { +classCountApp.get('/', rqf.parse(), (req, res, next) => { // Faz a consulta do número de alunos pelas dimensões if(("education_level_mod" in req.dims) || ("education_level_mod" in req.filter) || ("education_level_short" in req.dims)) { req.sql.field("'Brasil'", 'name') @@ -405,8 +442,10 @@ classCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { }) } // Caso tenha mais de uma dimensão, retorna a consulta só pelas dimensões, sem linha de total - else + else { addNullFields(req.result); + req.result = addZeroFields(req.result); + } next(); }, response('class_count')); diff --git a/src/libs/routes/classroom.js b/src/libs/routes/classroom.js index 2a8ee3913344bd78c5ac43545c5ac7597be7a1ec..a445e9412d7edc8337186e4cc6b448eaaded7961 100644 --- a/src/libs/routes/classroom.js +++ b/src/libs/routes/classroom.js @@ -1,3 +1,23 @@ +/* +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 classroomApp = express.Router(); @@ -210,12 +230,12 @@ rqf.addField({ }).addValue({ name: 'location', table: 'escola', - tableField: 'cod_localizacao', + tableField: 'localizacao_id', resultField: 'location_id', where: { relation: '=', type: 'integer', - field: 'cod_localizacao' + field: 'localizacao_id' } }); diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js index 71d6f54e24403ee4fef2b56d08a188ff46ba2f28..fe3e3c31f7ee2487ef1df439dbeb2b4483462658 100644 --- a/src/libs/routes/classroomCount.js +++ b/src/libs/routes/classroomCount.js @@ -1,3 +1,24 @@ +/* +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 classroomCountApp = express.Router(); @@ -157,11 +178,32 @@ rqf.addField({ type: 'integer', field: 'turma_turno_id' } +}).addValue({ + name: 'school_building', + table: 'escola', + tableField: 'local_func_predio_escolar', + resultField: 'school_building', + where: { + relation: '=', + type: 'boolean', + field: 'local_func_predio_escolar' + } +}).addValue({ + name: 'night_time', + table: 'matricula', + tableField: 'periodo_noturno', + resultField: 'night_time', + where: { + relation: '=', + type: 'boolean', + field: 'periodo_noturno' + } }); classroomCountApp.post('/', rqf.parse(), (req, res, next) => { let classSize = JSON.parse(req.body.class_size) || null; let integralTime = JSON.parse(req.body.integral_time) || null; + let enrollmentProjection = (req.body.projections !== undefined) ? JSON.parse(req.body.projections) : null; if(classSize == null || integralTime == null) { res.statusCode = 400; @@ -169,21 +211,23 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => { } req.classSize = classSize; req.integralTime = integralTime; + req.projections = (enrollmentProjection !== null) ? enrollmentProjection : false; req.dims.state = true; req.dims.city = true; - req.dims.period = true; req.dims.school_year = true; req.dims.location = true; - req.sql.field('COUNT(*)', 'total') + req.sql.field('dia_total', 'total_day') + .field('noite_total', 'total_night') .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .from('matricula') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo<=3') - .where('matricula.dependencia_adm_id < 4'); + .field('matricula_por_localizacao.ano_censo', 'year') + .from('matricula_por_localizacao') + .where('matricula_por_localizacao.serie_ano_id < 15') + .group('matricula_por_localizacao.ano_censo') + .group('matricula_por_localizacao.dia_total') + .group('matricula_por_localizacao.noite_total') + .order('matricula_por_localizacao.ano_censo') next(); }, rqf.build(), query, id2str.transform(), (req, res, next) => { @@ -191,25 +235,26 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => { // Gera a relação etapa de ensino X ano escolar req.educationSchoolYear = {}; - for(let i = 10; i < 80; ++i) { - if(id2str.schoolYear(i) !== id2str.schoolYear(99)) { - let educationLevelId = Math.floor(i/10); + for(let i = 1; i < 15; ++i) { + if(id2str.educationLevelSchoolYear(i) !== id2str.educationLevelSchoolYear(99)) { + let educationLevelId = (i > 10) ? Math.floor(i/10) : i; let classSize = req.classSize.find((el) => {return el.id === educationLevelId || el.id === i}); let integralTime = req.integralTime.find((el) => {return el.id === educationLevelId}); let numberStudentClass = (typeof classSize !== 'undefined') ? classSize.numberStudentClass : null; - let offerGoal = (typeof integralTime !== 'undefined') ? integralTime.offerGoal : null; + let integralTimeOfferGoal = (typeof integralTime !== 'undefined') ? integralTime.offerGoal : null; req.educationSchoolYear[i] = { id: educationLevelId, name: id2str.educationLevelShort(educationLevelId), numberStudentClass, - offerGoal + integralTimeOfferGoal }; } } - + delete req.dims; + delete req.filter; req.resetSql(); next(); }, rqf.parse(), (req, res, next) => { @@ -217,6 +262,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => { req.dims.state = true; req.dims.city = true; req.dims.location = true; + req.dims.school_building = true; req.sql.field('SUM(escola.num_salas)', 'total') .field("'Brasil'", 'name') @@ -224,261 +270,383 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => { .from('escola') .group('escola.ano_censo') .order('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1 AND escola.local_func_predio_escolar = 1') + .where('escola.situacao_de_funcionamento = 1') .where('escola.dependencia_adm_id < 4'); next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { +}, rqf.build(), query, id2str.transform(), (req, res, next) => { + req.classroom = req.result; delete req.dims; delete req.filter; + req.resetSql(); next(); -}, rqf.parse(), rqf.build(), (req, res, next) => { - req.classroom = req.result; - let classroom = []; +}, rqf.parse(), (req, res, next) => { + if ("state" in req.filter) { + req.dims.state = true; + req.dims.city = true; + req.dims.school_year = true; + req.dims.location = true; + req.sql.field('indice_distribuicao_matriculas.indice', 'total') + .field("'Brasil'", 'name') + .field('indice_distribuicao_matriculas.ano_censo', 'year') + .from('indice_distribuicao_matriculas') + .where('indice_distribuicao_matriculas.nivel_simulacao = 2') + .where('indice_distribuicao_matriculas.serie_ano_id < 15') + .group('indice_distribuicao_matriculas.ano_censo') + .group('indice_distribuicao_matriculas.indice') + .order('indice_distribuicao_matriculas.ano_censo') + } + else { + req.dims.state = true; + req.dims.city = true; + req.dims.school_year = true; + req.dims.location = true; + req.sql.field('indice_distribuicao_matriculas.indice', 'idm') + .field("'Brasil'", 'name') + .field('indice_distribuicao_matriculas.ano_censo', 'year') + .from('indice_distribuicao_matriculas') + .where('indice_distribuicao_matriculas.nivel_simulacao = 1') + .where('indice_distribuicao_matriculas.serie_ano_id < 15') + .group('indice_distribuicao_matriculas.ano_censo') + .group('indice_distribuicao_matriculas.indice') + .order('indice_distribuicao_matriculas.ano_censo') + } + + next(); +}, rqf.build(), query, id2str.transform(), (req, res, next) => { + delete req.dims; + delete req.filter; + next(); +},rqf.parse(), rqf.build(), (req, res, next) => { + // req.classroom = req.result; + req.idm = req.result; // req.result = [{classroom: req.classroom, enrollment: req.enrollment}]; return next(); - // Cria estrutura de resposta requisitada: - let i = 0; - let j = 0; - let result = []; - let hashSet = new Set(); - let enrollments = [...req.enrollment]; - let leftovers = []; - while (i < req.classroom.length) { - let classroom = req.classroom[i]; - // Cria hash única para cada espacialidade, dado um ano - let hash = '' + classroom.year + classroom.state_id + classroom.city_id; - // Estrutura do objeto do resultado final - let obj = { - year: classroom.year, - name: classroom.name, - state_id: classroom.state_id, - state_name: classroom.state_name, - city_id: classroom.city_id, - city_name: classroom.city_name, - locations: [] - }; - - let currentClassroomObj = null; - if( !hashSet.has(hash) ) { - hashSet.add(hash); - result.push(obj); - currentClassroomObj = obj; - } else { // Se a hash já existe, já temos a cidade nos resultados. Como está ordenado, é o último valor nos resultados - currentClassroomObj = result[result.length - 1]; + let enrollmentProjectionNight = []; + let enrollmentProjectionDay = []; + if (req.projections) { + for (let i = 0; i < req.projections.length; i++) { + if (req.projections[i].periods === 3) { + enrollmentProjectionNight.push(req.projections[i]); + } else { + enrollmentProjectionDay.push(req.projections[i]); + } } + } + let qntYears = 1; + if (req.projections) { + qntYears = enrollmentProjectionDay[0].stagesEnrollments[0].seriesEnrollments[0].enrollments.length; + } + let result = []; - // Inserimos a localidade no array de locations da sala - let location = { - location_id: classroom.location_id, - location_name: classroom.location_name, - total_classroom: parseInt(classroom.total, 10), - total_classroom_be_built: 0, - education_level: [] - }; - currentClassroomObj.locations.push(location); - - // Partimos para as etapas de ensino/anos escolares - - let enrollmentMatch = true; - j = 0; - let educationLevelSet = new Set(); - let schoolYearSet = new Set(); - let enrollment = enrollments[j]; - - while(enrollmentMatch && j < enrollments.length) { - enrollment = enrollments[j]; - - // Remove se o período é nulo (não dá pra usar no cálculo) - if(enrollment.period_id == null) { - enrollments.splice(j, 1); - continue; - } + // Cria estrutura de resposta requisitada: + for(let yearCount = 0; yearCount < qntYears; yearCount++) { + let i = 0; + let j = 0; + let hashSet = new Set(); + let enrollments = [...req.enrollment]; + let ei = 0; + let eiCityStart = 0; + let verifySchoolYear; // Matriz para verificar se o idm já foi inserido no school year. + while (i < req.classroom.length) { + let classroom = req.classroom[i]; + // Cria hash única para cada espacialidade, dado um ano + let hash = '' + yearCount + classroom.state_id + classroom.city_id; + // Estrutura do objeto do resultado final + let obj = { + year: classroom.year + yearCount, + name: classroom.name, + state_id: classroom.state_id, + state_name: classroom.state_name, + city_id: classroom.city_id, + city_name: classroom.city_name, + locations: [] + }; - if(typeof enrollment === 'undefined') { - ++j; - continue; + // Inserimos a localidade no array de locations da sala + let location = { + location_id: classroom.location_id, + location_name: classroom.location_name, + total_classroom: (classroom.school_building == 1) ? parseInt(classroom.total, 10) : 0, // Conta apenas salas de prédios próprios + total_classroom_be_built: 0, + education_level: [] + }; + + let currentClassroomObj = null; + if( !hashSet.has(hash) ) { + if (result[result.length - 1] !== undefined) { // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id + let last_locations = result[result.length - 1].locations + for (let i = 0; i < last_locations.length - 1; i++) { + if (last_locations[i].location_id === last_locations[i+1].location_id) { + last_locations[i].total_classroom_be_built += last_locations[i+1].total_classroom_be_built; + last_locations[i].total_classroom += last_locations[i+1].total_classroom; + last_locations.splice(i+1, 1); + } + } + for (let i = 0; i < last_locations.length; i++) { // Passamos agora para não deixar to_be_built < 0 + last_locations[i].total_classroom_be_built = (last_locations[i].total_classroom_be_built < 0) ? 0 : last_locations[i].total_classroom_be_built; + } + } + hashSet.add(hash); + result.push(obj); + currentClassroomObj = obj; + eiCityStart = ei; + verifySchoolYear = Array.from(Array(2), () => new Array(15)); + } else { // Se a hash já existe, já temos a cidade nos resultados. Como está ordenado, é o último valor nos resultados + currentClassroomObj = result[result.length - 1]; + ei = eiCityStart; } + currentClassroomObj.locations.push(location); + + // Partimos para as etapas de ensino/anos escolares + let enrollmentMatch = true; + j = 0; + let educationLevelSet = new Set(); + let schoolYearSet = new Set(); + let enrollment; + while(enrollmentMatch && j < enrollments.length) { + enrollment = enrollments[j]; + + if(typeof enrollment === 'undefined') { + ++j; + continue; + } - if(classroom.city_name < enrollment.city_name) { // Se as cidades não são iguais, já passamos do range - enrollmentMatch = false; - continue; - } else if(classroom.city_name > enrollment.city_name) { - let enrollmentHash = '' + enrollment.year + enrollment.state_id + enrollment.city_id; - if(hashSet.has(enrollmentHash)) { - leftovers.push(enrollments.splice(j, 1)); // Para inspeção, adiciona os que "sobram" no array de sobras - } else { + if(classroom.city_id !== enrollment.city_id) { // Se as cidades não são iguais, já passamos do range + enrollmentMatch = false; + while (req.idm[ei].city_id !== enrollment.city_id) { + ei++; + } + continue; + } + + if(enrollment.year != classroom.year || enrollment.location_id != classroom.location_id) { // Se ano ou localização são diferentes, passa para o próximo ++j; + continue; } - continue; - } - if(enrollment.year != classroom.year || enrollment.location_id != classroom.location_id) { // Se ano ou localização são diferentes, passa para o próximo - ++j; - continue; - } + // Temos uma matrícula com cidade, ano e localidades certos + // "Consome" a matrícula (remove do vetor de matrículas) + enrollments.splice(j, 1); - // Temos uma matrícula com cidade, ano e localidades certos - // "Consome" a matrícula (remove do vetor de matrículas) - enrollments.splice(j, 1); + // Cria a etapa de ensino adequada + let enrollmentEducationLevel = req.educationSchoolYear[enrollment.school_year_id]; + // Se não há um número de alunos por turna para a etapa de ensino, ignoramos a entrada - // Cria a etapa de ensino adequada - let enrollmentEducationLevel = req.educationSchoolYear[enrollment.school_year_id]; - // Se não há um número de alunos por turna para a etapa de ensino, ignoramos a entrada - if(enrollmentEducationLevel.numberStudentClass == null) continue; - - let educationLevel = null; - if(!educationLevelSet.has(enrollmentEducationLevel.id)) { - educationLevelSet.add(enrollmentEducationLevel.id); - - educationLevel = { - education_level_short_id: enrollmentEducationLevel.id, - education_level_short_name: enrollmentEducationLevel.name, - enrollment: { - total_enrollment_day: 0, - total_enrollment_night: 0, - full_period_classes: 0, - day_classes: 0, - night_classes: 0, - total_classrooms_needed: 0 - } - }; + if(enrollmentEducationLevel.numberStudentClass == null) continue; + + let educationLevel = null; + if(!educationLevelSet.has(enrollmentEducationLevel.id)) { + educationLevelSet.add(enrollmentEducationLevel.id); + + educationLevel = { + education_level_short_id: enrollmentEducationLevel.id, + education_level_short_name: enrollmentEducationLevel.name, + enrollment: { + total_enrollment_day: 0, + total_enrollment_night: 0, + full_period_classes: 0, + day_classes: 0, + night_classes: 0, + total_classrooms_needed: 0 + } + }; - if(enrollmentEducationLevel.id == 1) { - educationLevel.classes_school_year = []; - } + if(enrollmentEducationLevel.id == 1) { + educationLevel.classes_school_year = []; + } - // Para manter a ordem da etapa de ensino - if (location.education_level.length == 0) { - location.education_level.push(educationLevel); + // Para manter a ordem da etapa de ensino + if (location.education_level.length == 0) { + location.education_level.push(educationLevel); + } else { + let k = location.education_level.length - 1; + let el = location.education_level[k]; + while (k >= 0) { + if(educationLevel.education_level_short_id < el.education_level_short_id) { + --k; + if(k>=0) el = location.education_level[k]; + } else break; + } + k++; + location.education_level.splice(k, 0, educationLevel); + } } else { - let k = location.education_level.length - 1; + let k = 0; let el = location.education_level[k]; - while (k >= 0) { - if(educationLevel.education_level_short_id < el.education_level_short_id) { - --k; - if(k>=0) el = location.education_level[k]; + while(k < location.education_level.length) { + if(el.education_level_short_id != enrollmentEducationLevel.id) { + ++k; + if(k<location.education_level.length) el = location.education_level[k]; } else break; } - k++; - location.education_level.splice(k, 0, educationLevel); + if(k >= location.education_level.length) --k; + educationLevel = location.education_level[k]; } - } else { - let k = 0; - let el = location.education_level[k]; - while(k < location.education_level.length) { - if(el.education_level_short_id != enrollmentEducationLevel.id) { - ++k; - if(k<location.education_level.length) el = location.education_level[k]; - } else break; + + // Adiciona as séries da creche + let currentSchoolYear = null; + if(enrollmentEducationLevel.id == 1){ + let schoolYearHash = '' + enrollment.year + enrollment.city_id + enrollment.location_id + enrollment.school_year_id; + if(schoolYearSet.has(schoolYearHash)) { // Busca a série escolar + let k = 0; + let el = educationLevel.classes_school_year[k]; + while(k < educationLevel.classes_school_year.length) { + if(el.school_year_id != enrollment.school_year_id) { + ++k; + if(k < educationLevel.classes_school_year.length) el = educationLevel.classes_school_year[k]; + } else break; + } + if(k >= educationLevel.classes_school_year.length) --k; + currentSchoolYear = educationLevel.classes_school_year[k]; + } else { // Adiciona uma nova série escolar + let school_year = { + school_year_id: enrollment.school_year_id, + school_year_name: enrollment.school_year_name, + total_enrollment_day: 0, + total_enrollment_night: 0, + full_period_classes: 0, + day_classes: 0, + night_classes: 0, + total_classrooms_needed: 0 + } + schoolYearSet.add(schoolYearHash); + // Busca a posição para inserir + let k = 0; + let el = educationLevel.classes_school_year[k]; + while((typeof el !== 'undefined') && school_year.school_year_id > el.school_year_id) { + el = educationLevel.classes_school_year[++k]; + } + // educationLevel.classes_school_year.push(school_year); + educationLevel.classes_school_year.splice(k, 0, school_year); + currentSchoolYear = school_year; + } } - if(k >= location.education_level.length) --k; - educationLevel = location.education_level[k]; - } - // Adiciona as séries da creche - let currentSchoolYear = null; - if(enrollmentEducationLevel.id == 1){ - let schoolYearHash = '' + enrollment.year + enrollment.city_id + enrollment.location_id + enrollment.school_year_id; - if(schoolYearSet.has(schoolYearHash)) { // Busca a série escolar - let k = 0; - let el = educationLevel.classes_school_year[k]; - while(k < educationLevel.classes_school_year.length) { - if(el.school_year_id != enrollment.school_year_id) { - ++k; - if(k < educationLevel.classes_school_year.length) el = educationLevel.classes_school_year[k]; - } else break; + // Faz match da tabela de idm com a de enrollment + if (educationLevel.education_level_short_id !== 1) { + while (req.idm[ei].school_year_id < educationLevel.education_level_short_id) ei++; + while (req.idm[ei].school_year_id > educationLevel.education_level_short_id) ei--; + + if (req.idm[ei].location_id < location.location_id) { + ei++; } - if(k >= educationLevel.classes_school_year.length) --k; - currentSchoolYear = educationLevel.classes_school_year[k]; - } else { // Adiciona uma nova série escolar - let school_year = { - school_year_id: enrollment.school_year_id, - school_year_name: enrollment.school_year_name, - total_enrollment_day: 0, - total_enrollment_night: 0, - full_period_classes: 0, - day_classes: 0, - night_classes: 0, - total_classrooms_needed: 0 + else if(req.idm[ei].location_id > location.location_id) { + ei--; } - schoolYearSet.add(schoolYearHash); - // Busca a posição para inserir - let k = 0; - let el = educationLevel.classes_school_year[k]; - while((typeof el !== 'undefined') && school_year.school_year_id > el.school_year_id) { - el = educationLevel.classes_school_year[++k]; - } - // educationLevel.classes_school_year.push(school_year); - educationLevel.classes_school_year.splice(k, 0, school_year); - currentSchoolYear = school_year; } - } + let enrollmentIdm = req.idm[ei]; - let currentOfferGoal = enrollmentEducationLevel.offerGoal; - let currentNumberStudentClass = (enrollment.location_id == 1) ? enrollmentEducationLevel.numberStudentClass.urban : enrollmentEducationLevel.numberStudentClass.country; - // Soma os totais de matrícula da etapa de ensino - educationLevel.enrollment.total_enrollment_day += (enrollment.period_id < 3 && enrollment.period_id != null) ? enrollment.total : 0; - educationLevel.enrollment.total_enrollment_night += (enrollment.period_id == 3) ? enrollment.total : 0; + let currentIntegralOfferGoal = enrollmentEducationLevel.integralTimeOfferGoal; + let currentNumberStudentClass = (enrollment.location_id == 1) ? enrollmentEducationLevel.numberStudentClass.urban : enrollmentEducationLevel.numberStudentClass.country; + + // Soma os totais de matrícula da etapa de ensino + educationLevel.enrollment.total_enrollment_day += enrollment.total_day; + educationLevel.enrollment.total_enrollment_night += (educationLevel.education_level_short_id > 2) ? enrollment.total_night : 0; //Não contamos matrículas noturnos de pré-escola e creche + + let currentEnrollmentOfferDay; + let currentEnrollmentOfferNight; + if (req.projections) { + currentEnrollmentOfferDay = enrollmentProjectionDay[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1]; + currentEnrollmentOfferNight = enrollmentProjectionNight[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1]; + } + if (req.projections && (!verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id]) && (currentEnrollmentOfferDay.enrollments !== undefined)) { // Garantimos que será somado apenas uma vez por localização. + // Projeção de matricula multiplicada pelo indice de distribuição de matriculas da localização. + verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] = 1; + + educationLevel.enrollment.total_enrollment_day += Math.ceil((currentEnrollmentOfferDay.enrollments[yearCount].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm); + if (educationLevel.enrollment.total_enrollment_day < 0) educationLevel.enrollment.total_enrollment_day = 0; + educationLevel.enrollment.total_enrollment_night += (educationLevel.education_level_short_id > 2) ? Math.ceil((currentEnrollmentOfferNight.enrollments[yearCount].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm) : 0; + if (educationLevel.enrollment.total_enrollment_night < 0) educationLevel.enrollment.total_enrollment_night = 0; + } - // Calcula o número de turmas parcial - // Turmas de período integral - educationLevel.enrollment.full_period_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (currentOfferGoal/100)) / currentNumberStudentClass); + // Calcula o número de turmas parcial + // Turmas de período integral + educationLevel.enrollment.full_period_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (currentIntegralOfferGoal/100)) / currentNumberStudentClass); - // Turmas diurnas (matrículas diurnas - matrículas integrais) - educationLevel.enrollment.day_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (1 - currentOfferGoal/100)) / currentNumberStudentClass); + // Turmas diurnas (matrículas diurnas - matrículas integrais) + educationLevel.enrollment.day_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (1 - currentIntegralOfferGoal/100)) / currentNumberStudentClass); - // Turmas noturnas - educationLevel.enrollment.night_classes = Math.ceil((educationLevel.enrollment.total_enrollment_night / currentNumberStudentClass)) || 0; + // Turmas noturnas + educationLevel.enrollment.night_classes = Math.ceil((educationLevel.enrollment.total_enrollment_night / currentNumberStudentClass)) || 0; - // Total de salas - educationLevel.enrollment.total_classrooms_needed = (educationLevel.enrollment.full_period_classes + educationLevel.enrollment.day_classes/2); + // Total de salas + educationLevel.enrollment.total_classrooms_needed = (educationLevel.enrollment.full_period_classes + educationLevel.enrollment.day_classes/2); - if(educationLevel.enrollment.night_classes > (educationLevel.enrollment.day_classes/2)) educationLevel.enrollment.total_classrooms_needed += (educationLevel.enrollment.night_classes - (educationLevel.enrollment.day_classes/2)); + if(educationLevel.enrollment.night_classes > (educationLevel.enrollment.day_classes/2)) educationLevel.enrollment.total_classrooms_needed += (educationLevel.enrollment.night_classes - (educationLevel.enrollment.day_classes/2)); - educationLevel.enrollment.total_classrooms_needed = Math.ceil(educationLevel.enrollment.total_classrooms_needed); + educationLevel.enrollment.total_classrooms_needed = Math.ceil(educationLevel.enrollment.total_classrooms_needed); - // Faz os mesmos cálculos para a série escolar - if(currentSchoolYear) { - // Totais de matrícula - currentSchoolYear.total_enrollment_day += (enrollment.period_id < 3 && enrollment.period_id != null) ? enrollment.total : 0; - currentSchoolYear.total_enrollment_night += (enrollment.period_id == 3) ? enrollment.total : 0; - - // Número de turmas parcial - currentSchoolYear.full_period_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (currentOfferGoal/100)) / currentNumberStudentClass); + // Faz os mesmos cálculos para a série escolar + if(currentSchoolYear) { + // Faz match da enrollment com o idm, no caso de não usar o mod + while (req.idm[ei].school_year_id < enrollment.school_year_id) ei++; + while (req.idm[ei].school_year_id > enrollment.school_year_id) ei--; - currentSchoolYear.day_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (1 - currentOfferGoal/100)) / currentNumberStudentClass); + if (req.idm[ei].location_id < location.location_id) { + ei++; + } + else if(req.idm[ei].location_id > location.location_id) { + ei--; + } + enrollmentIdm = req.idm[ei]; - currentSchoolYear.night_classes = Math.ceil((currentSchoolYear.total_enrollment_night / enrollmentEducationLevel.numberStudentClass)) || 0; - // Total de salas - currentSchoolYear.total_classrooms_needed = (currentSchoolYear.full_period_classes + currentSchoolYear.day_classes/2); + // Totais de matrícula + currentSchoolYear.total_enrollment_day += enrollment.total_day; - if(currentSchoolYear.night_classes > (currentSchoolYear.day_classes/2)) currentSchoolYear.total_classrooms_needed += (currentSchoolYear.night_classes - (currentSchoolYear.day_classes/2)); + if (req.projections && !verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id]) { // Garantimos que será somado apenas uma vez por localização. + verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] = 1; - currentSchoolYear.total_classrooms_needed = Math.ceil(currentSchoolYear.total_classrooms_needed); + let currentEnrollmentSchoolYear = currentEnrollmentOfferDay.seriesEnrollments[Math.trunc(currentSchoolYear.school_year_id/10) - 1]; + currentSchoolYear.total_enrollment_day += (currentEnrollmentSchoolYear !== undefined) ? Math.ceil((currentEnrollmentSchoolYear.enrollments[yearCount].quantity - currentEnrollmentSchoolYear.currentOffer)*enrollmentIdm.idm) : 0; + if (currentSchoolYear.total_enrollment_day < 0) currentSchoolYear.total_enrollment_day = 0; + } + + // Número de turmas parcial + currentSchoolYear.full_period_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (currentIntegralOfferGoal/100)) / currentNumberStudentClass); - function reducer(key) { return (sum, elem) => sum + elem[key]} - educationLevel.enrollment.full_period_classes = educationLevel.classes_school_year.reduce(reducer('full_period_classes'), 0); - educationLevel.enrollment.day_classes = educationLevel.classes_school_year.reduce(reducer('day_classes'), 0); - educationLevel.enrollment.night_classes = educationLevel.classes_school_year.reduce(reducer('night_classes'), 0); - educationLevel.enrollment.total_classrooms_needed = educationLevel.classes_school_year.reduce(reducer('total_classrooms_needed'), 0); - } + currentSchoolYear.day_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (1 - currentIntegralOfferGoal/100)) / currentNumberStudentClass); - enrollment = enrollments[j]; - } - // Calculamos o total classroom be built para o município usando reduce - location.total_classroom_be_built = location.education_level.reduce((total, atual) => { - return total + atual.enrollment.total_classrooms_needed; - }, 0) - location.total_classroom; + // Total de salas + currentSchoolYear.total_classrooms_needed = (currentSchoolYear.full_period_classes + currentSchoolYear.day_classes/2); - if(location.total_classroom_be_built < 0) location.total_classroom_be_built = 0; + currentSchoolYear.total_classrooms_needed = Math.ceil(currentSchoolYear.total_classrooms_needed); - ++i; + function reducer(key) { return (sum, elem) => sum + elem[key]} + educationLevel.enrollment.total_enrollment_day = educationLevel.classes_school_year.reduce(reducer('total_enrollment_day'), 0); + educationLevel.enrollment.full_period_classes = educationLevel.classes_school_year.reduce(reducer('full_period_classes'), 0); + educationLevel.enrollment.day_classes = educationLevel.classes_school_year.reduce(reducer('day_classes'), 0); + educationLevel.enrollment.total_classrooms_needed = educationLevel.classes_school_year.reduce(reducer('total_classrooms_needed'), 0); + } + enrollment = enrollments[j]; + } + + // Calculamos o total classroom be built para o município usando reduce + location.total_classroom_be_built = location.education_level.reduce((total, atual) => { + return total + atual.enrollment.total_classrooms_needed; + }, 0) - location.total_classroom; + ++i; + } + + // Tratamento do último resultado, para remover double location, tirar negativo do to_be_built. + if (result[result.length - 1] !== undefined) { // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id + let last_locations = result[result.length - 1].locations + for (let i = 0; i < last_locations.length - 1; i++) { + if (last_locations[i].location_id === last_locations[i+1].location_id) { + last_locations[i].total_classroom_be_built += last_locations[i+1].total_classroom_be_built; + last_locations[i].total_classroom += last_locations[i+1].total_classroom; + last_locations.splice(i+1, 1); + } + } + for (let i = 0; i < last_locations.length; i++) { // Passamos agora para não deixar to_be_built < 0 + last_locations[i].total_classroom_be_built = (last_locations[i].total_classroom_be_built < 0) ? 0 : last_locations[i].total_classroom_be_built; + } + } } // Agregar por estado e brasil @@ -517,6 +685,15 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => { if(currentObj.locations.length == 0) { // Pode ser que a cidade atual tenha menos localidades que o total (só urbana ou só rural) currentObj.locations = [...city.locations]; + if (currentObj.locations.length === 1) { // Se a cidade só tinha uma, adcionamos a outra manualmente. + currentObj.locations[1] = { + location_id: (currentObj.locations[0].location_id === 1) ? 2 : 1, // Oposto da adcionada + location_name: (currentObj.locations[0].location_id === 1) ? 'Rural' : 'Urbana', // Oposto da adcionada + total_classroom: 0, + total_classroom_be_built: 0, + education_level: [] + } + } } else { let j = 0; let k = 0; @@ -532,12 +709,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => { } else if(cityLocation.location_id > currentLocation.location_id) { ++k; currentLocation = currentObj.locations[k]; - // Se a localidade da cidade é maior que a localidade do objeto atual E o vetor de localidades do objeto atual - // acaba, então esta localidade falta no objeto atual, pois as localidades estão ordenadas - if(typeof currentLocation == 'undefined' && typeof cityLocation !== 'undefined') { - currentObj.locations[k] = cityLocation; - currentLocation = currentObj.locations[k]; - } continue; } diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js new file mode 100644 index 0000000000000000000000000000000000000000..c59892e7fe5e928978b43e5f5ea94959c746c4e5 --- /dev/null +++ b/src/libs/routes/courseCount.js @@ -0,0 +1,413 @@ +/* +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 courseCountApp = 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 rqf = new ReqQueryFields(); + +courseCountApp.use(cache('15 day')); + +courseCountApp.get('/upper_adm_dependency', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 7; ++i) { + req.result.push({ + id: i, + name: id2str.upperAdmDependency(i) + }); + }; + next(); +}, response('upper_adm_dependency')); + +courseCountApp.get('/years', (req, res, next) => { + req.sql.from('curso_ens_superior') + .field('DISTINCT curso_ens_superior.ano_censo', 'year'); + next(); +}, query, response('years')); + +courseCountApp.get('/year_range', (req, res, next) => { + req.sql.from('curso_ens_superior') + .field('MIN(curso_ens_superior.ano_censo)', 'start_year') + .field('MAX(curso_ens_superior.ano_censo)', 'end_year'); + next(); +}, query, response('range')); + +courseCountApp.get('/academic_organization', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 5; ++i) { + req.result.push({ + id: i, + name: id2str.academicOrganization(i) + }); + }; + next(); +}, response('academic_organization')); + +courseCountApp.get('/capital', (req, res, next) => { + req.result = [ + {id: null, name: 'Não Classificado'}, + {id: 0, name: 'Não'}, + {id: 1, name: 'Sim'} + ]; + next(); +}, response('capital')); + +courseCountApp.get('/ocde_geral', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 8; ++i) { + req.result.push({ + id: i, + name: id2str.ocdeGeral(i) + }); + }; + next(); +}, response('ocde_geral')); + +courseCountApp.get('/ocde_specific', (req, res, next) => { + req.result = []; + const defaultCase = null; + for(let i = 1; i <= 86; ++i) { + let obj = { + id: i, + name: id2str.ocdeSpecific(i) + }; + if (obj.name !== id2str.ocdeSpecific(defaultCase)){ + req.result.push(obj); + } + }; + req.result.push({ + id: defaultCase, + name: id2str.ocdeSpecific(defaultCase) + }); + next(); +}, response('ocde_specific')); + +courseCountApp.get('/ocde_detailed', (req, res, next) => { + req.result = []; + const defaultCase = null; + for(let i = 142; i <= 863; ++i) { + let obj = { + id: i, + name: id2str.ocdeDetailed(i) + }; + if (obj.name !== id2str.ocdeDetailed(defaultCase)){ + req.result.push(obj); + } + }; + req.result.push({ + id: defaultCase, + name: id2str.ocdeDetailed(defaultCase) + }); + next(); +}, response('ocde_detailed')); + +courseCountApp.get('/academic_level', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 4; ++i) { + req.result.push({ + id: i, + name: id2str.academicLevel(i) + }); + }; + next(); +}, response('academic_level')); + +courseCountApp.get('/upper_education_mod', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 3; ++i) { + req.result.push({ + id: i, + name: id2str.upperEducationMod(i) + }); + }; + next(); +}, response('upper_education_mod')); + +courseCountApp.get('/is_free', (req, res, next) => { + req.result = [ + {id: null, name: 'Não Classificado'}, + {id: 0, name: 'Não'}, + {id: 1, name: 'Sim'} + ]; + next(); +}, response('is_free')); + +courseCountApp.get('/night_time', (req, res, next) => { + req.result = [ + {id: null, name: 'Não Classificado'}, + {id: 0, name: 'Não'}, + {id: 1, name: 'Sim'} + ]; + next(); +}, response('night_time')); + +courseCountApp.get('/university', (req, res, next) => { + req.sql.from('curso_ens_superior') + .field('DISTINCT curso_ens_superior.nome_ies', 'nome') + .field('curso_ens_superior.cod_ies', 'cod') + next(); +}, query, response('university')); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'region', + table: 'regiao', + tableField: ['nome', 'id'], + resultField: ['region_name', 'region_id'], + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'nome', + foreign: 'nome_regiao_curso', + foreignTable: 'curso_ens_superior' + } +}).addValue({ + name: 'state', + table: 'estado', + tableField: ['nome', 'id'], + resultField: ['state_name', 'state_id'], + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'id', + foreign: 'cod_uf_curso', + foreignTable: 'curso_ens_superior' + } +}).addValue({ + name: 'city', + table: 'curso_ens_superior', + tableField: ['municipio_curso', 'cod_municipio_curso'], + resultField: ['city_name', 'city_id'], + where: { + relation: '=', + type: 'integer', + field: 'cod_municipio_curso' + } +}).addValue({ + name: 'university', + table: 'curso_ens_superior', + tableField: ['cod_ies', 'nome_ies'], + resultField: ['university_id', 'university_name'], + where: { + relation: '=', + type: 'integer', + field: 'cod_ies' + } +}).addValue({ + name:'upper_adm_dependency', + table: 'curso_ens_superior', + tableField: 'par_categoria_administrativa', + resultField: 'upper_adm_dependency_id', + where: { + relation: '=', + type: 'integer', + field: 'par_categoria_administrativa' + } +}).addValue({ + name:'academic_organization', + table: 'curso_ens_superior', + tableField: 'cod_organizacao_academica', + resultField: 'academic_organization_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_organizacao_academica' + } +}).addValue({ + name:'capital', + table: 'curso_ens_superior', + tableField: 'tfd_capital_curso', + resultField: 'capital_id', + where: { + relation: '=', + type: 'integer', + field: 'tfd_capital_curso' + } +}).addValue({ + name:'course', + table: 'curso_ens_superior', + tableField: 'nome_curso', + resultField: 'course_name', + where: { + relation: 'LIKE', + type: 'string', + field: 'nome_curso' + } +}).addValue({ + name:'ocde_specific', + table: 'curso_ens_superior', + tableField: ['cod_ocde_area_especifica', 'nome_ocde_area_especifica'], + resultField: ['ocde_specific_id', 'ocde_specific_name'], + where: { + relation: '=', + type: 'integer', + field: 'cod_ocde_area_especifica' + } +}).addValue({ + name:'ocde_geral', + table: 'curso_ens_superior', + tableField: ['cod_ocde_area_geral', 'nome_ocde_area_geral'], + resultField: ['ocde_geral_id', 'ocde_geral_name'], + where: { + relation: '=', + type: 'integer', + field: 'cod_ocde_area_geral' + } +}).addValue({ + name:'ocde_detailed', + table: 'curso_ens_superior', + tableField: ['cod_ocde_area_detalhada', 'nome_ocde_area_detalhada'], + resultField: ['ocde_detailed_id', 'ocde_datailed_name'], + where: { + relation: '=', + type: 'integer', + field: 'cod_ocde_area_detalhada' + } +}).addValue({ + name:'academic_level', + table: 'curso_ens_superior', + tableField: 'cod_grau_academico', + resultField: 'academic_level_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_grau_academico' + } +}).addValue({ + name:'upper_education_mod', + table: 'curso_ens_superior', + tableField: 'cod_modalidade_ensino', + resultField: 'upper_education_mod_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_modalidade_ensino' + } +}).addValue({ + name:'is_free', + table: 'curso_ens_superior', + tableField: 'gratuito', + resultField: 'is_free_id', + where: { + relation: '=', + type: 'boolean', + field: 'gratuito' + } +}).addValue({ + name:'night_time', + table: 'curso_ens_superior', + tableField: 'noturno_curso', + resultField: 'night_time_id', + where: { + relation: '=', + type: 'boolean', + field: 'noturno_curso' + } +}).addValue({ + name:'situation', + table: 'curso_ens_superior', + tableField: 'cod_situacao_curso', + resultField: 'situacao_curso_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_situacao_curso' + } +}).addValue({ + name:'year', + table: 'curso_ens_superior', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo' + } +}).addValue({ + name: 'min_year', + table: 'curso_ens_superior', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + table: 'curso_ens_superior', + field: 'ano_censo' + } +}).addValue({ + name: 'max_year', + table: 'curso_ens_superior', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + table: 'curso_ens_superior', + field: 'ano_censo' + } +}); + +courseCountApp.get('/', rqf.parse(), (req, res, next) => { + req.sql.from('curso_ens_superior') + .field('COUNT(curso_ens_superior.cod_curso)', 'total') + .field("'Brasil'", 'name') + .field('curso_ens_superior.ano_censo', 'year') + .group('curso_ens_superior.ano_censo') + .order('curso_ens_superior.ano_censo') + .where('curso_ens_superior.tipo_atributo_ingresso <> 1 OR curso_ens_superior.tipo_atributo_ingresso is NULL') + .where('curso_ens_superior.cod_nivel_academico = 1'); + next(); +}, rqf.build(), query, id2str.transform(), addMissing(rqf), response('course_count')); + +module.exports = courseCountApp; diff --git a/src/libs/routes/cub.js b/src/libs/routes/cub.js index 5310f0be248f191f0e41325fb84d03525f638e40..944122598acc9c1166b4433a50d60d4a4f69b3d7 100644 --- a/src/libs/routes/cub.js +++ b/src/libs/routes/cub.js @@ -1,3 +1,23 @@ +/* +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 cubApp = express.Router(); @@ -20,10 +40,6 @@ const request = require(`request`); const config = require(`${libs}/config`); -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - const addMissing = require(`${libs}/middlewares/addMissing`); const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js index d9a02d779ad0355683769910b40780d8bac77c3d..9efd71a8a904146f60630f5e05aac4bfa37df6a3 100644 --- a/src/libs/routes/dailyChargeAmount.js +++ b/src/libs/routes/dailyChargeAmount.js @@ -1,3 +1,23 @@ +/* +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 dailyChargeAmountApp = express.Router(); @@ -20,10 +40,6 @@ const request = require(`request`); const config = require(`${libs}/config`); -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - const addMissing = require(`${libs}/middlewares/addMissing`); const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; @@ -407,21 +423,23 @@ 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') 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') let joinRG = squel.select(); joinRG.from(tableR, 'R') - .field('R.education_level_mod_id') + .field('R.etapas_mod_ensino_segmento_id') .field('AVG(1.0*R.duracao_turma)/60', 'median_value') - .join(tableG, 'G', 'R.education_level_mod_id = G.education_level_mod_id AND R.rowNo BETWEEN G.counter/2 AND G.counter/2+G.counter%2') - .group('R.education_level_mod_id') + .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') @@ -437,7 +455,7 @@ dailyChargeAmountApp.get('/average', rqf.parse(), rqf.build(), (req, res, next) .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.education_level_mod_id = 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') } else { res.status(400); next({ diff --git a/src/libs/routes/distributionFactor.js b/src/libs/routes/distributionFactor.js index df4d84b797884f71f92e55456ed365317d98679a..99e1a77a9e9dea2fc2b49551d2b9d9760ec680fa 100644 --- a/src/libs/routes/distributionFactor.js +++ b/src/libs/routes/distributionFactor.js @@ -1,3 +1,23 @@ +/* +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 distributionApp = express.Router(); diff --git a/src/libs/routes/downloads.js b/src/libs/routes/downloads.js deleted file mode 100644 index 2ec83b9ee7ffa82bbaf3e873c949c842dd6b6ab1..0000000000000000000000000000000000000000 --- a/src/libs/routes/downloads.js +++ /dev/null @@ -1,54 +0,0 @@ -const express = require('express'); - -const downloadApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const Download = require(`${libs}/models/download`); - -const User = require(`${libs}/models/user`); - -const passport = require('passport'); - -const request = require(`request`); - -const config = require(`${libs}/config`); - -downloadApp.get('/', passport.authenticate('bearer', {session: false}), (req, res, next) => { - request.get(config.cdn.url + '/api/v1/file', (err, response, body) => { - let cdn = JSON.parse(body); - Download.find({userId: req.user._id}, (err, downloads) => { - if (err) { - log.error(err); - return next(err); - } - - if(!downloads) { - res.statusCode = 404; - return res.json({msg: 'Nenhum download encontrado'}); - } else { - downloads.forEach((dl) => { - for(let i = 0; i < cdn.length; ++i) { - if(cdn[i].query == dl.query) { - dl.status = cdn[i].expired ? 'Expirado' : 'Enviado'; - dl.size = cdn[i].size; - dl.expired = cdn[i].expired; - dl.updatedAt = cdn[i].lastAccess; - dl.link = config.cdn.download + '/' + cdn[i]._id; - - dl.save((err) => { - if(err) log.error(err); - }); - return; - } - } - }); - } - res.json(downloads); - }); - }); -}); - -module.exports = downloadApp; diff --git a/src/libs/routes/educationYears.js b/src/libs/routes/educationYears.js index 0d103883f53fc53dbd8770fa983dc5fe568564dd..b8173d060e8f29183ccc65926815dc3594a2ce24 100644 --- a/src/libs/routes/educationYears.js +++ b/src/libs/routes/educationYears.js @@ -1,3 +1,23 @@ +/* +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 educationYearsApp = express.Router(); diff --git a/src/libs/routes/employees.js b/src/libs/routes/employees.js index 523eb6bc3cca09977153c7f75d6c31d24e671179..40a968e993d8ba2978ab47289dbb3e667a5d9fdd 100644 --- a/src/libs/routes/employees.js +++ b/src/libs/routes/employees.js @@ -1,3 +1,23 @@ +/* +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(); @@ -18,8 +38,6 @@ const id2str = require(`${libs}/middlewares/id2str`); 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; @@ -208,12 +226,12 @@ rqfSchool.addField({ }, 'filter').addValue({ name: 'location', table: '@', - tableField: 'cod_localizacao', + tableField: 'localizacao_id', resultField: 'location_id', where: { relation: '=', type: 'integer', - field: 'cod_localizacao' + field: 'localizacao_id' } }).addValue({ name: 'rural_location', @@ -368,12 +386,12 @@ rqfTeacher.addField({ }, 'filter').addValue({ name: 'location', table: '@', - tableField: 'cod_localizacao', + tableField: 'localizacao_id', resultField: 'location_id', where: { relation: '=', type: 'integer', - field: 'cod_localizacao' + field: 'localizacao_id' } }).addValue({ name: 'rural_location', diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js index 66268b11409cf918ce8de61779a16b5323669639..695d624bd1bb9903248e15e603a8fe1e14211ca2 100644 --- a/src/libs/routes/enrollment.js +++ b/src/libs/routes/enrollment.js @@ -1,3 +1,23 @@ +/* +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 enrollmentApp = express.Router(); @@ -18,10 +38,6 @@ const id2str = require(`${libs}/middlewares/id2str`); const config = require(`${libs}/config`); -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - const addMissing = require(`${libs}/middlewares/addMissing`); const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; @@ -398,6 +414,31 @@ rqf.addField({ foreign: ['escola_id', 'ano_censo'], foreignTable: 'matricula' } +}, 'dims').addValueToField({ + name: 'locale_id', + table: 'matricula', + tableField: 'localizacao_id', + resultField: 'locale_id', + where: { + relation: '=', + type: 'integer', + field: 'localizacao_id' + } +}, 'dims').addValueToField({ + name: 'school_id', + table: 'escola', + tableField: 'id', + resultField: 'school_id', + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: ['id', 'ano_censo'], + foreign: ['escola_id', 'ano_censo'], + foreignTable: 'matricula' + } }, 'dims').addValueToField({ name: 'school', table: 'escola', @@ -515,18 +556,15 @@ rqf.addField({ } }); -enrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { +enrollmentApp.get('/', rqf.parse(), (req, res, next) => { req.sql.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') .field('matricula.ano_censo', 'year') .from('matricula') .group('matricula.ano_censo') .order('matricula.ano_censo') .where('matricula.tipo<=3'); next(); -}, query, addMissing(rqf), id2str.transform(false), response('enrollment')); - -enrollmentApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('matricula', 'mapping_matricula')); +}, rqf.build(), query, id2str.transform(false), /*addMissing(rqf),*/ response('enrollment')); enrollmentApp.get('/diagnosis', rqf.parse(), (req, res, next) => { req.dims = {}; @@ -779,8 +817,6 @@ enrollmentApp.get('/projection', rqf.parse(), (req, res, next) => { } } - console.log(educationSchoolYear); - let result = []; let educationLevelSet = new Set(); let schoolYearSet = new Set(); diff --git a/src/libs/routes/enrollmentProjection.js b/src/libs/routes/enrollmentProjection.js index 1bbe8ea3934a4fe59116ec0a3d96d292a446d59f..00c75b00fdf29b329295384a5d91f9b67711ebd9 100644 --- a/src/libs/routes/enrollmentProjection.js +++ b/src/libs/routes/enrollmentProjection.js @@ -1,3 +1,23 @@ +/* +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 enrollmentProjectionApp = express.Router(); @@ -110,29 +130,99 @@ rqf.addField({ enrollmentProjectionApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.sql.field("'Brasil'", 'name') - .field('SUM(projecao_matricula.urbano_dia_total)', 'urban_day_total') - .field('SUM(projecao_matricula.urbano_noite_total)', 'urban_night_total') - .field('SUM(projecao_matricula.rural_dia_total)', 'rural_day_total') - .field('SUM(projecao_matricula.rural_noite_total)', 'rural_night_total') - .field('projecao_matricula.etapa_ensino_escola_ano_id', 'education_level_school_year_id') - .field('projecao_matricula.ano_censo', 'year') - .from('projecao_matricula') - .where('projecao_matricula.etapa_ensino_escola_ano_id <> 7 AND projecao_matricula.etapa_ensino_escola_ano_id < 71') - .group('projecao_matricula.etapa_ensino_escola_ano_id') - .group('projecao_matricula.ano_censo') - .order('projecao_matricula.ano_censo') - .order('projecao_matricula.etapa_ensino_escola_ano_id'); + .field('SUM(projecao_matricula.urbano_dia_total)', 'urban_day_total') + .field('SUM(projecao_matricula.urbano_noite_total)', 'urban_night_total') + .field('SUM(projecao_matricula.rural_dia_total)', 'rural_day_total') + .field('SUM(projecao_matricula.rural_noite_total)', 'rural_night_total') + .field('projecao_matricula.etapa_ensino_escola_ano_id', 'education_level_school_year_id') + .field('projecao_matricula.ano_censo', 'year') + .from('projecao_matricula') + .where('projecao_matricula.etapa_ensino_escola_ano_id <> 7 AND projecao_matricula.etapa_ensino_escola_ano_id < 71') + .group('projecao_matricula.etapa_ensino_escola_ano_id') + .group('projecao_matricula.ano_censo') + .order('projecao_matricula.ano_censo') + .order('projecao_matricula.etapa_ensino_escola_ano_id'); next(); }, query, id2str.transform(), (req, res, next) => { - req.result.forEach((r) => { - r.urban_day_total = parseInt(r.urban_day_total, 10); - r.urban_night_total = parseInt(r.urban_night_total, 10); - r.rural_day_total = parseInt(r.rural_day_total, 10); - r.rural_night_total = parseInt(r.rural_night_total, 10); - }); - + let result = []; + let i = 0; + let j = 1; + let base_year = req.result[0].year; + + let hashSet = new Set(); + let atual_city_name; + let atual_city_id; + let atual_state_name; + let atual_state_id; + while (i < req.result.length || j <= 63) { // Adciona séries não existentes no banco com 0 nos totais. + let atual = req.result[i]; + if (j > 63) { // Caso j passou da última série existente, mudamos de dimensão. + j = 1; + + if (base_year !== atual.year) { + base_year = atual.year; + hashSet = new Set(); + } + } + if (id2str.educationLevelSchoolYear(j) === id2str.educationLevelSchoolYear(99) || j === 7) { + j++; + continue; + } + + if (j == 1) { + let hash = "" + if ('state' in req.dims) + hash += atual.state_id; + if ('city' in req.dims) + hash += atual.city_id; + + if (!hashSet.has(hash)) { + hashSet.add(hash); + atual_city_id = atual.city_id; + atual_city_name = atual.city_name; + atual_state_id = atual.state_id; + atual_state_name = atual.state_name; + } + } + + if (atual !== undefined && atual.education_level_school_year_id === j) { // Série existe. + atual.urban_day_total = parseInt(atual.urban_day_total, 10); + atual.urban_night_total = ((atual.education_level_school_year_id >= 3 && atual.education_level_school_year_id < 10) || (atual.education_level_school_year_id >= 30)) ? parseInt(atual.urban_night_total, 10) : 0; //Não conta matrículas noturnas da pré-escola e da creche + atual.rural_day_total = parseInt(atual.rural_day_total, 10); + atual.rural_night_total = ((atual.education_level_school_year_id >= 3 && atual.education_level_school_year_id < 10) || (atual.education_level_school_year_id >= 30)) ? parseInt(atual.rural_night_total, 10) : 0; + result.push(atual); + + i++; + } + else { // Série não existe, adcionamos 0 ao resultado. + let base_result = { + name: req.result[0].name, + urban_day_total: 0, + urban_night_total: 0, + rural_day_total: 0, + rural_night_total: 0, + education_level_school_year_id: j, + year: base_year, + education_level_school_year_name: id2str.educationLevelSchoolYear(j) + }; + + if ('city' in req.dims) { // adciona os campos de cidade e/ou estado + base_result.city_id = atual_city_id; + base_result.city_name = atual_city_name; + } + if ('state' in req.dims) { + base_result.state_id = atual_state_id; + base_result.state_name = atual_state_name; + } + + result.push(base_result) + } + j++; + } + + req.result = result; next(); }, response('enrollment_projection')); diff --git a/src/libs/routes/financial.js b/src/libs/routes/financial.js index 78c3b023f8991c64d813101c45cff2eeb62c468c..bfe272058ce1d385bce3934b49a094140c496f1e 100644 --- a/src/libs/routes/financial.js +++ b/src/libs/routes/financial.js @@ -1,3 +1,23 @@ +/* +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 financialApp = express.Router(); @@ -130,20 +150,36 @@ rqf.addField({ }); financialApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.from('indicadores_financeiros') - .field('indicadores_financeiros.estado_id', 'state_id') - .field('indicadores_financeiros.ano_censo', 'year') - .field('estado.sigla', 'state_abbreviation') - .field('indicadores_financeiros.valor', 'valor') - .field('indicadores_financeiros.esfera_adm', 'sphere_adm_id') - .field('indicadores_financeiros.dados_financeiros', 'financial_data_id') - .join('estado', null, 'indicadores_financeiros.estado_id=estado.id') - .group('indicadores_financeiros.ano_censo') - .group('indicadores_financeiros.estado_id') - .group('estado.sigla') - .group('indicadores_financeiros.valor') - .group('indicadores_financeiros.dados_financeiros') - .group('indicadores_financeiros.esfera_adm') + if ("state" in req.filter) { + req.sql.from('indicadores_financeiros') + .field('indicadores_financeiros.estado_id', 'state_id') + .field('indicadores_financeiros.ano_censo', 'year') + .field('estado.sigla', 'state_abbreviation') + .field('indicadores_financeiros.valor', 'valor') + .field('indicadores_financeiros.esfera_adm', 'sphere_adm_id') + .field('indicadores_financeiros.dados_financeiros', 'financial_data_id') + .group('indicadores_financeiros.ano_censo') + .group('indicadores_financeiros.estado_id') + .group('estado.sigla') + .group('indicadores_financeiros.valor') + .group('indicadores_financeiros.dados_financeiros') + .group('indicadores_financeiros.esfera_adm') + } else { + req.sql.from('indicadores_financeiros') + .field('indicadores_financeiros.estado_id', 'state_id') + .field('indicadores_financeiros.ano_censo', 'year') + .field('estado.sigla', 'state_abbreviation') + .field('indicadores_financeiros.valor', 'valor') + .field('indicadores_financeiros.esfera_adm', 'sphere_adm_id') + .field('indicadores_financeiros.dados_financeiros', 'financial_data_id') + .join('estado', null, 'indicadores_financeiros.estado_id=estado.id') + .group('indicadores_financeiros.ano_censo') + .group('indicadores_financeiros.estado_id') + .group('estado.sigla') + .group('indicadores_financeiros.valor') + .group('indicadores_financeiros.dados_financeiros') + .group('indicadores_financeiros.esfera_adm') + } next(); }, query, addMissing(rqf), id2str.transform(), response('financial')); diff --git a/src/libs/routes/glossEnrollmentRatio.js b/src/libs/routes/glossEnrollmentRatio.js index 041a93ad4d025cd835066b60783d386acd13d0f9..31d8903d8b0d92577f0a643db903937e789b4140 100644 --- a/src/libs/routes/glossEnrollmentRatio.js +++ b/src/libs/routes/glossEnrollmentRatio.js @@ -1,3 +1,23 @@ +/* +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 glossEnrollmentRatioApp = express.Router(); @@ -22,10 +42,6 @@ const addMissing = require(`${libs}/middlewares/addMissing`); const config = require(`${libs}/config`); -const download = require(`${libs}/middlewares/downloadDatabase`); - -const passport = require('passport'); - const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; let rqf = new ReqQueryFields(); diff --git a/src/libs/routes/idhm.js b/src/libs/routes/idhm.js index 45a193e7750aab100b417a25affae69b0678ea71..f21d2154506e28acbe9aa5dfb388d74debc2d164 100644 --- a/src/libs/routes/idhm.js +++ b/src/libs/routes/idhm.js @@ -1,3 +1,23 @@ +/* +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 idhmApp = express.Router(); diff --git a/src/libs/routes/idhme.js b/src/libs/routes/idhme.js index 2a1f4d033fc61b8f96a50d4a42001fca4da52b60..25d9e682039f17f6c9059cab30802b1a3c929ba2 100644 --- a/src/libs/routes/idhme.js +++ b/src/libs/routes/idhme.js @@ -1,3 +1,23 @@ +/* +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 idhmeApp = express.Router(); diff --git a/src/libs/routes/idhml.js b/src/libs/routes/idhml.js index 1fddee79146257c2f837a937bb5864fcdbab20af..aa811d8f0a4dee6febcede55f33468c75b49f338 100644 --- a/src/libs/routes/idhml.js +++ b/src/libs/routes/idhml.js @@ -1,3 +1,23 @@ +/* +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 idhmlApp = express.Router(); diff --git a/src/libs/routes/idhmr.js b/src/libs/routes/idhmr.js index 938d58a93db62f00185c08a22a75f34403541c27..d140cc541e3e36f85334a68c8a3815a40c057196 100644 --- a/src/libs/routes/idhmr.js +++ b/src/libs/routes/idhmr.js @@ -1,3 +1,23 @@ +/* +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 idhmrApp = express.Router(); diff --git a/src/libs/routes/infrastructure.js b/src/libs/routes/infrastructure.js index 8b01e338f0c7785a14fe29f93a7f54f2fc2c6582..8630cb947e57d07f48c75f1f6194a3be62f6d98e 100644 --- a/src/libs/routes/infrastructure.js +++ b/src/libs/routes/infrastructure.js @@ -1,3 +1,23 @@ +/* +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 infrastructureApp = express.Router(); @@ -178,12 +198,12 @@ rqf.addField({ }).addValue({ name: 'location', table: 'escola', - tableField: 'cod_localizacao', + tableField: 'localizacao_id', resultField: 'location_id', where: { relation: '=', type: 'integer', - field: 'cod_localizacao' + field: 'localizacao_id' } }).addValue({ name: 'rural_location', @@ -296,7 +316,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { // Bibliotecas let allLibraries = allSchools.clone(); - allLibraries.where('escola.func_predio_escolar = 1 AND escola.cod_localizacao = 1'); + allLibraries.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 1'); req.queryIndex.allLibraries = req.querySet.push(allLibraries) - 1; let haveLibraries = allLibraries.clone(); @@ -305,7 +325,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { // Bibliotecas/Sala de leitura let allLibrariesReadingRoom = allSchools.clone(); - allLibrariesReadingRoom.where('escola.func_predio_escolar = 1 AND escola.cod_localizacao = 2'); + allLibrariesReadingRoom.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 2'); req.queryIndex.allLibrariesReadingRoom = req.querySet.push(allLibrariesReadingRoom) - 1; let haveLibrariesReadingRoom = allLibrariesReadingRoom.clone(); @@ -352,7 +372,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { // Quadra let allSportsCourt = allScienceLab.clone(); - allSportsCourt.where('escola.cod_localizacao = 1'); + allSportsCourt.where('escola.localizacao_id = 1'); req.queryIndex.allSportsCourt = req.querySet.push(allSportsCourt) - 1; let haveSportsCourt = allSportsCourt.clone(); @@ -377,7 +397,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { // Sala de direção let allDirectorRoom = allSchools.clone(); - allDirectorRoom.where('escola.func_predio_escolar = 1 AND escola.cod_localizacao = 1'); + allDirectorRoom.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 1'); req.queryIndex.allDirectorRoom = req.querySet.push(allDirectorRoom) - 1; let haveDirectorRoom = allDirectorRoom.clone(); diff --git a/src/libs/routes/liquidEnrollmentRatio.js b/src/libs/routes/liquidEnrollmentRatio.js index 793e4f65309314f9ee12f53afa3230cb8e01bc84..eb8c634a649d53367cd4b70f6e2f4b30dbdd167f 100644 --- a/src/libs/routes/liquidEnrollmentRatio.js +++ b/src/libs/routes/liquidEnrollmentRatio.js @@ -1,3 +1,23 @@ +/* +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 liquidEnrollmentRatioApp = express.Router(); @@ -22,10 +42,6 @@ const addMissing = require(`${libs}/middlewares/addMissing`); const config = require(`${libs}/config`); -const download = require(`${libs}/middlewares/downloadDatabase`); - -const passport = require('passport'); - const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; let rqf = new ReqQueryFields(); diff --git a/src/libs/routes/outOfSchool.js b/src/libs/routes/outOfSchool.js index 3d8f33d9959d70906877f767ef242685f54f6350..6ccedf2142e378c462b4af216d729ce97247543c 100644 --- a/src/libs/routes/outOfSchool.js +++ b/src/libs/routes/outOfSchool.js @@ -1,3 +1,23 @@ +/* +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 outOfSchoolApp = express.Router(); @@ -252,14 +272,44 @@ simcaqRqf.addField({ field: true, where: false }).addValue({ - name: 'state', + name: 'brazil_total', table: 'populacao_fora_da_escola', - tableField: 'unidade_federativa', - resultField: 'state_id', + tableField: 'brasil', + resultField: 'brazil_total_id', + where: { + relation: '=', + type: 'boolean', + field: 'brasil' + } +}).addValue({ + name: 'state', + table: 'estado', + tableField: 'nome', + resultField: 'state_name', where: { relation: '=', type: 'integer', - field: 'unidade_federativa' + field: 'id' + }, + join: { + primary: 'id', + foreign: 'estado_id', + foreignTable: 'populacao_fora_da_escola' + } +}).addValue({ + name: 'city', + table: 'municipio', + tableField: 'nome', + resultField: 'city_name', + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'id', + foreign: 'municipio_id', + foreignTable: 'populacao_fora_da_escola' } }).addValue({ name: 'pfe', @@ -307,7 +357,6 @@ outOfSchoolApp.get('/simcaq', simcaqRqf.parse(), simcaqRqf.build(), (req, res, n }, query, (req, res, next) => { req.result.forEach((i) => { i.total = parseInt(i.total); - console.log(i.total); }); next(); }, addMissing(simcaqRqf), id2str.transform(), response('out_of_school')); diff --git a/src/libs/routes/pibpercapita.js b/src/libs/routes/pibpercapita.js index de1ec7d60b1699675701ac8c7906a6b24052eaff..3cb91c5b17f7bba08022b5ad485b34fd06e8ce5f 100644 --- a/src/libs/routes/pibpercapita.js +++ b/src/libs/routes/pibpercapita.js @@ -1,3 +1,23 @@ +/* +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 pibpercapitaApp = express.Router(); diff --git a/src/libs/routes/population.js b/src/libs/routes/population.js index f0402daa73c13eb6453b4e3d584bfe11b8145a01..ed644e9ee94259de5a484a9a43e951afb8d23043 100644 --- a/src/libs/routes/population.js +++ b/src/libs/routes/population.js @@ -1,3 +1,23 @@ +/* +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 populationApp = express.Router(); diff --git a/src/libs/routes/portalMec.js b/src/libs/routes/portalMec.js index afd84e8e019d27135b9e246580ed1c941e5b4acd..e54c90c2860e7c1e0906a6c7b25b5d606bd1852d 100644 --- a/src/libs/routes/portalMec.js +++ b/src/libs/routes/portalMec.js @@ -1,3 +1,23 @@ +/* +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 portalMecApp = express.Router(); @@ -100,7 +120,7 @@ rqf.addField({ portalMecApp.get('/', rqf.parse(), (req, res, next) => { - req.sql.field('docente.id') + req.sql.field('docente.docente_id') .field('docente.ano_censo', 'year') .field('docente.cod_quimica', 'Química') .field('docente.cod_fisica', 'Física') diff --git a/src/libs/routes/portalMecInep.js b/src/libs/routes/portalMecInep.js index 2b23589130d1775c89520af1b8ee2827ac31add7..f8108ce46b77928357fa5cdd8232e11a9de9d414 100644 --- a/src/libs/routes/portalMecInep.js +++ b/src/libs/routes/portalMecInep.js @@ -1,3 +1,23 @@ +/* +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 portalMecInepApp = express.Router(); diff --git a/src/libs/routes/rateSchool.js b/src/libs/routes/rateSchool.js index a45865a9337e027cdbec45bd8b0163bd4477112c..e5592dc550161fe2c73a63b67bd7a18cb3d6258c 100644 --- a/src/libs/routes/rateSchool.js +++ b/src/libs/routes/rateSchool.js @@ -1,3 +1,23 @@ +/* +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 rateSchoolApp = express.Router(); @@ -20,10 +40,6 @@ const id2str = require(`${libs}/middlewares/id2str`); const config = require(`${libs}/config`); -const download = require(`${libs}/middlewares/downloadDatabase`); - -const passport = require('passport'); - const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; rateSchoolApp.use(cache('15 day')); @@ -318,6 +334,4 @@ rateSchoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { next(); }, id2str.transform(false), response('rateSchool')); -rateSchoolApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('pnad', 'mapping_pnad')); - module.exports = rateSchoolApp; diff --git a/src/libs/routes/region.js b/src/libs/routes/region.js index b1076e6484836b8a4911b8d0ada3631f1304e3c0..f36760f3ba4f45ad56c98a95463ab370f5a6261a 100644 --- a/src/libs/routes/region.js +++ b/src/libs/routes/region.js @@ -1,3 +1,23 @@ +/* +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 regionApp = express.Router(); diff --git a/src/libs/routes/resetToken.js b/src/libs/routes/resetToken.js deleted file mode 100644 index 34ece8455adf7b77208dc200a95641ed04638609..0000000000000000000000000000000000000000 --- a/src/libs/routes/resetToken.js +++ /dev/null @@ -1,81 +0,0 @@ -const express = require('express'); - -const resetTokenApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const ResetToken = require(`${libs}/models/resetToken`); - -const User = require(`${libs}/models/user`); - -resetTokenApp.get('/:token', (req, res, next) => { - let token = req.params.token; - ResetToken.findOne({token: token}, (err, rToken) => { - if(err) { - log.error(err); - return next(err); - } - if(!rToken) { - // TODO: generate new reset token - res.statusCode = 404; - return next({msg: 'Token not found', status:404}); - } - if (rToken.hasExpired()) { - res.statusCode = 410; - ResetToken.remove({token: token}, (err) => { - if(err) { - log.error(err); - next(err); - } - }) - return next({msg: 'Token expired', status: 410}); - } - User.findById(rToken.userId, (err, user) => { - if(err) { - log.error(err); - next(err); - } - let u = user.toObject(); - delete u.salt; - delete u.hashedPassword; - res.json({user: u}); - }); - }); -}); -resetTokenApp.post('/:token', (req, res, next) => { - let token = req.params.token; - ResetToken.findOne({token: token}, (err, rToken) => { - if(err) { - log.error(err); - return next(err); - } - if(!rToken) { - res.statusCode = 404; - return next({msg: 'Token not found', status:404}); - } - User.findById(rToken.userId, (err, user) => { - if(err) { - log.error(err); - next(err); - } - user.password = req.body.password; - user.save((err) => { - if(err) { - log.error(err); - next(err); - } - ResetToken.remove({token: token}, (err) => { - if(err) { - log.error(err); - next(err); - } - }) - res.json({msg: "Senha alterada com sucesso"}); - }) - }); - }); -}) - -module.exports = resetTokenApp; diff --git a/src/libs/routes/school.js b/src/libs/routes/school.js index 3f4dd7141f6ce4c374969f37aaa5ee5335ee3498..ad5a4d071e43dc2d5dc6c40dfe1cd2fe4c6cac04 100644 --- a/src/libs/routes/school.js +++ b/src/libs/routes/school.js @@ -1,3 +1,23 @@ +/* +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 schoolApp = express.Router(); @@ -20,10 +40,6 @@ const request = require(`request`); const config = require(`${libs}/config`); -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - const addMissing = require(`${libs}/middlewares/addMissing`); const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; @@ -364,12 +380,12 @@ rqfCount.addField({ }).addValue({ name: 'location', table: 'escola', - tableField: 'cod_localizacao', + tableField: 'localizacao_id', resultField: 'location_id', where: { relation: '=', type: 'integer', - field: 'cod_localizacao' + field: 'localizacao_id' } }).addValue({ name: 'rural_location', @@ -545,6 +561,4 @@ schoolApp.get('/count', cache('15 day'), rqfCount.parse(), rqfCount.build(), (re next(); }, query, addMissing(rqfCount), id2str.transform(), response('school')); -schoolApp.get('/count/download', passport.authenticate('bearer', { session: false }), rqfCount.parse(), rqfCount.build(), download('escola', 'mapping_escola')); - module.exports = schoolApp; diff --git a/src/libs/routes/schoolInfrastructure.js b/src/libs/routes/schoolInfrastructure.js index 65c4677b4381b106b044f9e4fe129ce8691c0686..30780daf3c094d6d52d975e07a8f988547df2a1f 100644 --- a/src/libs/routes/schoolInfrastructure.js +++ b/src/libs/routes/schoolInfrastructure.js @@ -1,3 +1,23 @@ +/* +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 infrastructureApp = express.Router(); @@ -67,19 +87,26 @@ infrastructureApp.get('/rural_location', (req, res, next) => { }, response('rural_location')); infrastructureApp.get('/adm_dependency', (req, res, next) => { - req.sql.from('dependencia_adm') - .field('id') - .field('nome', 'name') - .where('id <= 4'); + req.result = []; + for(let i = 1; i <= 4; ++i) { + req.result.push({ + id: i, + name: id2str.admDependency(i) + }); + }; next(); -}, query, response('adm_dependency')); +}, response('adm_dependency')); infrastructureApp.get('/adm_dependency_detailed', (req, res, next) => { - req.sql.from('dependencia_adm_priv') - .field('id', 'id') - .field('nome', 'name'); + req.result = []; + for(let i = 1; i <= 6; ++i) { + req.result.push({ + id: i, + name: id2str.admDependencyPriv(i) + }); + }; next(); -}, query, response('adm_dependency_detailed')); +}, response('adm_dependency_detailed')); rqf.addField({ name: 'filter', @@ -171,12 +198,12 @@ rqf.addField({ }).addValue({ name: 'location', table: 'escola', - tableField: 'cod_localizacao', + tableField: 'localizacao_id', resultField: 'location_id', where: { relation: '=', type: 'integer', - field: 'cod_localizacao' + field: 'localizacao_id' } }).addValue({ name: 'rural_location', @@ -258,7 +285,6 @@ function matchQueries(queryTotal, queryPartial, queryNeeded, zeroPercentage=fals break; } } - if(queryPartial.length == 0) { partialMatch = JSON.parse(JSON.stringify(result)); partialMatch.total = 0; @@ -285,14 +311,12 @@ function matchQueries(queryTotal, queryPartial, queryNeeded, zeroPercentage=fals needMatch.total = 0; } - if(partialMatch && needMatch) { - newObj.percentage = (partialMatch.total / result.total) * 100; - if(zeroPercentage) newObj.percentage = 0; - newObj.partial = partialMatch.total; - newObj.total = result.total; - newObj.need_adaptation = needMatch.total; - match.push(newObj); - } + newObj.percentage = ( ( partialMatch ? partialMatch.total : 0) / result.total) * 100; + if(zeroPercentage) newObj.percentage = 0; + newObj.partial = ( partialMatch ? partialMatch.total : 0); + newObj.total = result.total; + newObj.need_adaptation = needMatch ? needMatch.total : 0; + match.push(newObj); }); return match; @@ -316,11 +340,11 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.allSchools = req.querySet.push(allSchools) - 1; let allUrbanSchools = allSchools.clone(); - allUrbanSchools.where('escola.cod_localizacao = 1'); + allUrbanSchools.where('escola.localizacao_id = 1'); req.queryIndex.allUrbanSchools = req.querySet.push(allUrbanSchools) - 1; let allCountrySchools = allSchools.clone(); - allCountrySchools.where('escola.cod_localizacao = 2'); + allCountrySchools.where('escola.localizacao_id = 2'); req.queryIndex.allCountrySchools = req.querySet.push(allCountrySchools) - 1; let allSchoolsNotSchoolBuilding = req.sql.clone(); @@ -336,30 +360,45 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.allSchoolsNotSchoolBuilding = req.querySet.push(allSchoolsNotSchoolBuilding) - 1; // Bibliotecas - req.queryIndex.allLibraries = req.queryIndex.allUrbanSchools; - - let haveLibraries = allUrbanSchools.clone(); + // 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; + + let haveLibraries = allLibraries.clone(); haveLibraries.where('escola.biblioteca = 1'); req.queryIndex.haveLibraries = req.querySet.push(haveLibraries) - 1; - let needLibraries = allUrbanSchools.clone(); + let needLibraries = allLibraries.clone(); needLibraries.where('escola.biblioteca = 0'); req.queryIndex.needLibraries = req.querySet.push(needLibraries) - 1; // Bibliotecas/Sala de leitura - req.queryIndex.allLibrariesReadingRoom = req.queryIndex.allCountrySchools; - - let haveLibrariesReadingRoom = allCountrySchools.clone(); + // 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; + + let haveLibrariesReadingRoom = allLibrariesReadingRoom.clone(); haveLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = true'); req.queryIndex.haveLibrariesReadingRoom = req.querySet.push(haveLibrariesReadingRoom) - 1; - let needLibrariesReadingRoom = allCountrySchools.clone(); + let needLibrariesReadingRoom = allLibrariesReadingRoom.clone(); needLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = false'); req.queryIndex.needLibrariesReadingRoom = req.querySet.push(needLibrariesReadingRoom) - 1; // Laboratório de informática + // 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) então conta id let allInfLab = allSchools.clone(); - allInfLab.where('escola.reg_infantil_preescola = 1 OR escola.reg_fund_ai = 1 OR escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado = 1 OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1'); + allInfLab.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.allInfLab = req.querySet.push(allInfLab) - 1; let haveInfLab = allInfLab.clone(); @@ -372,7 +411,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { // Laboratório de ciências let allScienceLab = allSchools.clone(); - allScienceLab.where('escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado = 1 OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1'); + allScienceLab.where('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.allScienceLab = req.querySet.push(allScienceLab) - 1; let haveScienceLab = allScienceLab.clone(); @@ -384,8 +423,10 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.needScienceLab = req.querySet.push(needScienceLab) - 1; // Parque infantil + // 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_infantil_creche_t1=1 or reg_infantil_preescola_t1=1 or reg_fund_ai_t1=1) então conta id let allKidsPark = allSchools.clone(); - allKidsPark.where('escola.reg_infantil_creche = 1 OR escola.reg_infantil_preescola = 1 OR escola.reg_fund_ai = 1'); + allKidsPark.where('reg_infantil_creche_t1=1 OR reg_infantil_preescola_t1=1 OR reg_fund_ai_t1=1'); req.queryIndex.allKidsPark = req.querySet.push(allKidsPark) - 1; let haveKidsPark = allKidsPark.clone(); @@ -398,7 +439,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { // Berçário let allCribs = allSchools.clone(); - allCribs.where('escola.reg_infantil_creche = 1'); + allCribs.where('escola.reg_infantil_creche_t1 = 1'); req.queryIndex.allCribs = req.querySet.push(allCribs) - 1; let haveCribs = allCribs.clone(); @@ -411,7 +452,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { // Quadra Coberta let allSportsCourt = allSchools.clone(); - allSportsCourt.where('escola.reg_fund_ai = 1 OR escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1'); + 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; let haveSportsCourt = allSportsCourt.clone(); @@ -423,9 +464,12 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.needSportsCourt = req.querySet.push(needSportsCourt) - 1; // Cobertura de quadra esportiva + // 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 let allSportsCourtCoverage = allSportsCourt.clone(); allSportsCourtCoverage.where('escola.quadra_esportes_descoberta = 1'); - req.queryIndex.allSportsCourtCoverage = req.querySet.push(allSportsCourtCoverage); + req.queryIndex.allSportsCourtCoverage = req.querySet.push(allSportsCourtCoverage) -1; req.queryIndex.haveSportsCourtCoverage = req.queryIndex.allSportsCourtCoverage; @@ -439,7 +483,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.haveCourtyard = req.querySet.push(haveCourtyard) - 1; let needCourtyard = allSchools.clone(); - needCourtyard.where('escola.patio = 1'); + needCourtyard.where('escola.patio = 0'); req.queryIndex.needCourtyard = req.querySet.push(needCourtyard) - 1; // Cobertura do Pátio @@ -452,7 +496,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.needCourtyardCoverage = req.queryIndex.allCourtyardCoverage; // Sala de direção - req.queryIndex.allDirectorRoom = req.queryIndex.allLibraries; + req.queryIndex.allDirectorRoom = req.queryIndex.allUrbanSchools; let haveDirectorRoom = allUrbanSchools.clone(); haveDirectorRoom.where('escola.sala_diretoria = 1'); @@ -514,11 +558,11 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.haveWarehouse = req.querySet.push(haveWarehouse) - 1; let needWarehouse = allSchools.clone(); - needWarehouse.where('escola.almoxarifado = 1'); + needWarehouse.where('escola.almoxarifado = 0'); req.queryIndex.needWarehouse = req.querySet.push(needWarehouse) - 1; // Internet - req.queryIndex.allInternet = req.queryIndex.allLibrariesReadingRoom; + req.queryIndex.allInternet = req.queryIndex.allCountrySchools; let haveInternet = allCountrySchools.clone(); haveInternet.where('escola.internet = 1'); @@ -529,7 +573,9 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.needInternet = req.querySet.push(needInternet) - 1; // Internet banda larga - req.queryIndex.allBroadbandInternet = req.queryIndex.allLibraries; + // 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 (localizacao_id=2) então conta id + req.queryIndex.allBroadbandInternet = req.queryIndex.allUrbanSchools; let haveBroadbandInternet = allUrbanSchools.clone(); haveBroadbandInternet.where('escola.internet_banda_larga = 1'); @@ -551,13 +597,17 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.needInsideBathroom = req.querySet.push(needInsideBathroom) - 1; // Banheiro adequado para educação infantil dentro do prédio - req.queryIndex.allInsideKidsBathroom = req.queryIndex.allKidsPark; + // 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_infantil_creche_t1=1 or reg_infantil_preescola_t1=1 or reg_fund_ai_t1=1) então conta id + let allInsideKidsBathroom = allSchools.clone(); + allInsideKidsBathroom.where('reg_infantil_creche_t1=1 OR reg_infantil_preescola_t1=1 OR reg_fund_ai_t1=1'); + req.queryIndex.allInsideKidsBathroom = req.querySet.push(allInsideKidsBathroom) - 1; - let haveInsideKidsBathroom = allKidsPark.clone(); + let haveInsideKidsBathroom = allInsideKidsBathroom.clone(); haveInsideKidsBathroom.where('escola.sanitario_ei = 1'); req.queryIndex.haveInsideKidsBathroom = req.querySet.push(haveInsideKidsBathroom) - 1; - let needInsideKidsBathroom = allKidsPark.clone(); + let needInsideKidsBathroom = allInsideKidsBathroom.clone(); needInsideKidsBathroom.where('escola.sanitario_ei = 0'); req.queryIndex.needInsideKidsBathroom = req.querySet.push(needInsideKidsBathroom) - 1; @@ -624,12 +674,13 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.queryIndex.haveSpecialBathroom = req.querySet.push(haveSpecialBathroom) - 1; let needSpecialBathroom = allSchools.clone(); - needSpecialBathroom.where('escola.sanitario_pne = 1'); + needSpecialBathroom.where('escola.sanitario_pne = 0'); req.queryIndex.needSpecialBathroom = req.querySet.push(needSpecialBathroom) - 1; next(); }, multiQuery, (req, res, next) => { + let schools_in_school_buildings = req.result[req.queryIndex.allSchools]; let urban_schools_in_school_buildings = req.result[req.queryIndex.allUrbanSchools]; let country_schools_in_school_buildings = req.result[req.queryIndex.allCountrySchools]; diff --git a/src/libs/routes/simulation.js b/src/libs/routes/simulation.js index 4b2e40c33dd1855116353f618a7c87c13078eb84..785b33cf51ff0d15be26ebd3f02c21980be8e09b 100644 --- a/src/libs/routes/simulation.js +++ b/src/libs/routes/simulation.js @@ -1,3 +1,23 @@ +/* +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 simulationApp = express(); @@ -18,6 +38,8 @@ const PQR = require(`${libs}/models/pqr`); const passport = require('passport'); +const auth = require(`${libs}/middlewares/auth`); + simulationApp.get('/time', (req, res, next) => { const maxTime = parseInt(req.query.max_time, 10); if(isNaN(maxTime)) { @@ -43,8 +65,7 @@ simulationApp.get('/pqr', (req, res) => { }); }); -simulationApp.put('/pqr', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); +simulationApp.put('/pqr', auth("SimCAQ"), (req, res, next) => { PQR.findOne((err, pqr) => { if(err) { @@ -52,8 +73,8 @@ simulationApp.put('/pqr', passport.authenticate('bearer', { session: false }), ( return next({err}); } - if(!user.admin) { - log.info(`Usuário ${user.email} tentou alterar o PQR, mas não tem privilégio`); + if(!req.adminSimcaqNode) { + log.info(`Usuário ${req.email} tentou alterar o PQR, mas não tem privilégio`); res.statusCode = 401; return next({err: { msg: 'Unauthorized'}}); } @@ -68,9 +89,8 @@ simulationApp.put('/pqr', passport.authenticate('bearer', { session: false }), ( }); }); -simulationApp.get('/', passport.authenticate('bearer', { session: false }), (req, res) => { - let user = req.user.toObject(); - let query = Simulation.find({userId: user._id}).select('userId name createdAt updatedAt'); +simulationApp.get('/', auth("SimCAQ"), (req, res) => { + let query = Simulation.find({userId: req.userId}).select('userId name createdAt updatedAt'); query.exec((err, simulations) => { if(err) { log.error(err); @@ -90,11 +110,10 @@ simulationApp.get('/', passport.authenticate('bearer', { session: false }), (req // }); }); -simulationApp.post('/', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); +simulationApp.post('/', auth("SimCAQ"), (req, res, next) => { let simulation = new Simulation({ - userId: user._id, + userId: req.userId, content: req.body.content, name: req.body.name }); @@ -109,10 +128,9 @@ simulationApp.post('/', passport.authenticate('bearer', { session: false }), (re }) }); -simulationApp.get('/:id', passport.authenticate('bearer', { session: false }), (req, res) => { - let user = req.user.toObject(); +simulationApp.get('/:id', auth("SimCAQ"), (req, res) => { - Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => { + Simulation.findOne({_id: req.params.id, userId: req.userId}, (err, simulation) => { if(err) { log.error(err); return next({err}); @@ -122,10 +140,9 @@ simulationApp.get('/:id', passport.authenticate('bearer', { session: false }), ( }); }); -simulationApp.put('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); +simulationApp.put('/:id', auth("SimCAQ"), (req, res, next) => { - Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => { + Simulation.findOne({_id: req.params.id, userId: req.userId}, (err, simulation) => { if(err) { log.error(err); return next({err}); @@ -151,10 +168,9 @@ simulationApp.put('/:id', passport.authenticate('bearer', { session: false }), ( }); }); -simulationApp.delete('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); +simulationApp.delete('/:id', auth("SimCAQ"), (req, res, next) => { - Simulation.remove({_id: req.params.id, userId: user._id}, (err, simulation) => { + Simulation.remove({_id: req.params.id, userId: req.userId}, (err, simulation) => { if(err) { log.error(err); return next({err}); diff --git a/src/libs/routes/siope.js b/src/libs/routes/siope.js index 51c1c36833b99ff097cf8a85a0c90c20598f737b..615e2225477a1631df2b862f3e75276632a183b0 100644 --- a/src/libs/routes/siope.js +++ b/src/libs/routes/siope.js @@ -1,3 +1,23 @@ +/* +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 siopeApp = express.Router(); diff --git a/src/libs/routes/spatial.js b/src/libs/routes/spatial.js index 5523de7ad8fa79fa357f16dce588cc53782bc2ff..dd7fe97a5b21eb49997866353ce3dc4e7513844b 100644 --- a/src/libs/routes/spatial.js +++ b/src/libs/routes/spatial.js @@ -1,3 +1,23 @@ +/* +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 libs = `${process.cwd()}/libs`; @@ -203,11 +223,11 @@ spatialApp.get('/educational', rqf.parse(), rqf.build(), (req, res, next) => { .from('localizacao') .from('turma') .from('escola') - .where('escola.cod_localizacao=localizacao.id') + .where('escola.localizacao_id=localizacao.id') .where('escola.ano_censo=turma.ano_censo AND escola.id=turma.escola_id') .where(`escola.ano_censo IN (${censusYearQry})`) .where('turma.tipo_turma_id = 0') - .group('escola.cod_localizacao') + .group('escola.localizacao_id') .group('escola.ano_censo') .group('localizacao.descricao') .order('localizacao.descricao'); diff --git a/src/libs/routes/state.js b/src/libs/routes/state.js index 33778869342216fe40e8e5104f327d4f2de804ef..6fab1fc811baebc1a6b779f22f2985cd7354a290 100644 --- a/src/libs/routes/state.js +++ b/src/libs/routes/state.js @@ -1,3 +1,23 @@ +/* +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 stateApp = express.Router(); @@ -66,14 +86,12 @@ rqf.addField({ stateApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { req.sql.from('estado') - .field('estado.id') - .group('estado.id') - .field('regiao_id', 'region_id') - .group('regiao_id') - .field('estado.nome', 'name') - .group('estado.nome') - .field('estado.sigla', 'abbreviation') - .group('estado.sigla'); + .field('estado.id').group('estado.id') + .field('regiao_id', 'region_id').group('regiao_id') + .field('estado.nome', 'name').group('estado.nome') + .field('estado.sigla', 'abbreviation').group('estado.sigla') + .field('estado.longitude', 'longitude').group('estado.longitude') + .field('estado.latitude', 'latitude').group('estado.latitude'); next(); }, query, response('state')); diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js index f3b2af7e3504e94eb62d75a4b7974563e68dcdd6..ff712b525f6e3bf066404167ee938fa1310f5998 100644 --- a/src/libs/routes/teacher.js +++ b/src/libs/routes/teacher.js @@ -1,3 +1,23 @@ +/* +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 teacherApp = express.Router(); @@ -18,10 +38,6 @@ const id2str = require(`${libs}/middlewares/id2str`); const config = require(`${libs}/config`); -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - const addMissing = require(`${libs}/middlewares/addMissing`); const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; @@ -81,11 +97,6 @@ teacherApp.get('/education_level_mod', (req, res, next) => { name: id2str.educationLevelMod(i) }); } - - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); next(); }, response('education_level_mod')); @@ -329,12 +340,12 @@ rqf.addField({ }, 'filter').addValue({ name: 'location', table: 'docente', - tableField: 'cod_localizacao', + tableField: 'localizacao_id', resultField: 'location_id', where: { relation: '=', type: 'integer', - field: 'cod_localizacao' + field: 'localizacao_id' } }).addValue({ name: 'rural_location', @@ -389,7 +400,7 @@ rqf.addField({ }); teacherApp.get('/', rqf.parse(), (req, res, next) => { - req.sql.field('COUNT(DISTINCT docente.id)', 'total') + req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total') .field("'Brasil'", 'name') .field('docente.ano_censo', 'year') .from('docente') @@ -408,37 +419,6 @@ teacherApp.get('/', rqf.parse(), (req, res, next) => { } next(); -}, rqf.build(), query, addMissing(rqf), (req, res, next) => { - req.oldResult = req.result; - if(req.hadEducationLevelMod) { - - req.sql = squel.select() - .field('COUNT(DISTINCT docente.id)', 'total') - .field("'Brasil'", 'name') - .field('docente.ano_censo', 'year') - .from('docente') - .join('turma', null, 'docente.turma_id=turma.id AND docente.ano_censo=turma.ano_censo') - .group('docente.ano_censo') - .order('docente.ano_censo') - .where('(docente.tipo_docente = 1 OR docente.tipo_docente = 5) AND (turma.tipo_turma_id <= 3)') - .where('docente.profissionalizante = 1'); - - rqf.build()(req, res, () => {}); - query(req, res, next); - } else { - next(); - } -}, (req, res, next) => { - if(req.hadEducationLevelMod) { - req.result.forEach((result) => { - result.education_level_mod_id = 11; - req.oldResult.push(result); - }); - } - req.result = req.oldResult; - next(); -}, id2str.transform(), response('teacher')); - -teacherApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('docente', 'mapping_docente')); +}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('teacher')); module.exports = teacherApp; diff --git a/src/libs/routes/transport.js b/src/libs/routes/transport.js index 409cb216c6cd62ea334df6eafce40c3f165dd7e0..8327c4f6db58bd6ff49a0ed7221e0a4e529b475d 100644 --- a/src/libs/routes/transport.js +++ b/src/libs/routes/transport.js @@ -1,3 +1,23 @@ +/* +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 transportApp = express.Router(); @@ -10,8 +30,6 @@ const squel = require('squel'); const query = require(`${libs}/middlewares/query`).query; -const multiQuery = require(`${libs}/middlewares/multiQuery`); - const response = require(`${libs}/middlewares/response`); const addMissing = require(`${libs}/middlewares/addMissing`); @@ -29,15 +47,15 @@ let rqf = new ReqQueryFields(); transportApp.use(cache('15 day')); transportApp.get('/year_range', (req, res, next) => { - req.sql.from('matricula') - .field('MIN(matricula.ano_censo)', 'start_year') - .field('MAX(matricula.ano_censo)', 'end_year'); + req.sql.from('transporte') + .field('MIN(transporte.ano_censo)', 'start_year') + .field('MAX(transporte.ano_censo)', 'end_year'); next(); }, query, response('range')); transportApp.get('/years', (req, res, next) => { - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); + req.sql.from('transporte') + .field('DISTINCT transporte.ano_censo', 'year'); next(); }, query, response('years')); @@ -148,7 +166,7 @@ rqf.addField({ join: { primary: ['id', 'ano_censo'], foreign: ['escola_id', 'ano_censo'], - foreignTable: 'matricula' + foreignTable: 'transporte' } }).addValue({ name: 'region', @@ -163,7 +181,7 @@ rqf.addField({ join: { primary: 'id', foreign: 'regiao_id', - foreignTable: 'matricula' + foreignTable: 'transporte' } }).addValue({ name: 'city', @@ -174,32 +192,27 @@ rqf.addField({ relation: '=', type: 'integer', field: 'municipio_id', - table: 'matricula' + table: 'transporte' }, join: { primary: 'id', foreign: 'municipio_id', - foreignTable: 'matricula' + foreignTable: 'transporte' } }).addValue({ name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', + table: 'transporte', + tableField: ['estado_nome', 'estado_id'], + resultField: ['state_name', 'state_id'], where: { relation: '=', type: 'integer', field: 'estado_id', - table: 'matricula' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'matricula' + table: 'transporte' } }).addValue({ name: 'rural_location', - table: 'matricula', + table: 'transporte', tableField: 'localidade_area_rural', resultField: 'rural_location_id', where: { @@ -209,7 +222,7 @@ rqf.addField({ } }).addValue({ name: 'location', - table: 'matricula', + table: 'transporte', tableField: 'localizacao_id', resultField: 'location_id', where: { @@ -219,7 +232,7 @@ rqf.addField({ } }).addValue({ name:'adm_dependency', - table: 'matricula', + table: 'transporte', tableField: 'dependencia_adm_id', resultField: 'adm_dependency_id', where: { @@ -229,7 +242,7 @@ rqf.addField({ } }).addValue({ name: 'adm_dependency_detailed', - table: 'matricula', + table: 'transporte', tableField: 'dependencia_adm_priv', resultField: 'adm_dependency_detailed_id', where: { @@ -239,7 +252,7 @@ rqf.addField({ } }).addValue({ name: 'transportation_manager', - table: 'matricula', + table: 'transporte', tableField: 'responsavel_transp', resultField: 'transportation_manager_id', where: { @@ -249,7 +262,7 @@ rqf.addField({ } }).addValue({ name: 'education_level_mod', - table: 'matricula', + table: 'transporte', tableField: 'etapas_mod_ensino_segmento_id', resultField: 'education_level_mod_id', where: { @@ -259,17 +272,7 @@ rqf.addField({ } }).addValue({ name: 'service_type', - table: 'matricula', - tableField: 'tipo', - resultField: 'service_type_id', - where: { - relation: '=', - type: 'integer', - field: 'tipo' - } -}).addValue({ - name: 'service_type', - table: 'matricula', + table: 'transporte', tableField: 'tipo', resultField: 'service_type_id', where: { @@ -279,7 +282,7 @@ rqf.addField({ } }).addValue({ name: 'min_year', - table: 'matricula', + table: 'transporte', tableField: 'ano_censo', resultField: 'year', where: { @@ -289,7 +292,7 @@ rqf.addField({ } }).addValue({ name: 'max_year', - table: 'matricula', + table: 'transporte', tableField: 'ano_censo', resultField: 'year', where: { @@ -297,217 +300,103 @@ rqf.addField({ type: 'integer', field: 'ano_censo' } +}).addValue({ + name: 'year', + table: 'transporte', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo' + } }); -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.percentage = (objMatch.total / result.total) * 100; - newObj.partial = objMatch.total; - newObj.total = result.total - match.push(newObj); - } - }); - - return match; -} - -transportApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - let allEnrollment = req.sql.clone() - allEnrollment.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .from('matricula') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3'); - req.queryIndex.allEnrollment = req.querySet.push(allEnrollment) - 1; - - let allEnrollmentTransport = req.sql.clone() - allEnrollmentTransport.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .field('matricula.transporte_escolar_publico', 'use_transport_id') - .from('matricula') - .group('matricula.ano_censo') - .group('matricula.transporte_escolar_publico') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3'); - req.queryIndex.allEnrollmentTransport = req.querySet.push(allEnrollmentTransport) - 1; - - let allTransports = req.sql.clone() - allTransports.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .from('matricula') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3 AND matricula.transporte_escolar_publico = 1'); - req.queryIndex.allTransports = req.querySet.push(allTransports) - 1; - - // Vans e Kombi - let goVansAndKombi = allTransports.clone(); - goVansAndKombi.field('matricula.transporte_vans_kombi','use_transport_id') - goVansAndKombi.where('matricula.transporte_vans_kombi = 1'); - goVansAndKombi.group('matricula.transporte_vans_kombi'); - req.queryIndex.goVansAndKombi = req.querySet.push(goVansAndKombi) - 1; - - // Micro - let goMicroBus = allTransports.clone(); - goMicroBus.field('matricula.transporte_micro_onibus', 'use_transport_id') - goMicroBus.where('matricula.transporte_micro_onibus = 1'); - goMicroBus.group('matricula.transporte_micro_onibus'); - req.queryIndex.goMicroBus = req.querySet.push(goMicroBus) - 1; - - - // Ônibus - let goBus = allTransports.clone(); - goBus.field("matricula.transporte_onibus", 'use_transport_id') - goBus.where('matricula.transporte_onibus = 1'); - goBus.group('matricula.transporte_onibus') - req.queryIndex.goBus = req.querySet.push(goBus) - 1; - - // Bicicleta - let goBikes = allTransports.clone(); - goBikes.field('matricula.transporte_bicicleta', 'use_transport_id') - goBikes.where('matricula.transporte_bicicleta = 1'); - goBikes.group('matricula.transporte_bicicleta') - req.queryIndex.goBikes = req.querySet.push(goBikes) - 1; - - // Tração Animal - let goAnimalTraction = allTransports.clone(); - goAnimalTraction.field('matricula.transporte_animal', 'use_transport_id') - goAnimalTraction.where('matricula.transporte_animal = 1'); - goAnimalTraction.group('matricula.transporte_animal') - req.queryIndex.goAnimalTraction = req.querySet.push(goAnimalTraction) - 1; - - // Outro Veículo - let goOtherVehicle = allTransports.clone(); - goOtherVehicle.field('matricula.transporte_outro', 'use_transport_id') - goOtherVehicle.where('matricula.transporte_outro = 1'); - goOtherVehicle.group('matricula.transporte_outro') - req.queryIndex.goOtherVehicle = req.querySet.push(goOtherVehicle) - 1; - - // Aquaviário/ Embarcação (capacidade até 5 alunos) - let goWaterway_5_Students = allTransports.clone(); - goWaterway_5_Students.field('matricula.transporte_embar_0_5','use_transport_id') - goWaterway_5_Students.where('matricula.transporte_embar_0_5 = 1'); - goWaterway_5_Students.group('matricula.transporte_embar_0_5') - req.queryIndex.goWaterway_5_Students = req.querySet.push(goWaterway_5_Students) - 1; - - // Aquaviário/ Embarcação (capacidade de 5 até 15 alunos) - let goWaterway_15_Students = allTransports.clone(); - goWaterway_15_Students.field('matricula.transporte_embar_5_15', 'use_transport_id') - goWaterway_15_Students.where('matricula.transporte_embar_5_15 = 1'); - goWaterway_15_Students.group('matricula.transporte_embar_5_15') - req.queryIndex.goWaterway_15_Students = req.querySet.push(goWaterway_15_Students) - 1; - - // Aquaviário/ Embarcação (capacidade de 15 até 35 alunos)r - let goWaterway_35_Students = allTransports.clone(); - goWaterway_35_Students.field('matricula.transporte_embar_15_35', 'use_transport_id') - goWaterway_35_Students.where('matricula.transporte_embar_15_35 = 1'); - goWaterway_35_Students.group('matricula.transporte_embar_15_35') - req.queryIndex.goWaterway_35_Students = req.querySet.push(goWaterway_35_Students) - 1; - - // Aquaviário/ Embarcação (capacidade mais 35 alunos) - let goWaterwayMoreThan_35 = allTransports.clone(); - goWaterwayMoreThan_35.field('matricula.transporte_embar_35', 'use_transport_id') - goWaterwayMoreThan_35.where('matricula.transporte_embar_35 = 1'); - goWaterwayMoreThan_35.group('matricula.transporte_embar_35') - req.queryIndex.goWaterwayMoreThan_35 = req.querySet.push(goWaterwayMoreThan_35) - 1; - - // Trêm / Metrô - let goSubwayAndTrain = allTransports.clone(); - goSubwayAndTrain.field('matricula.transporte_trem_metro', 'use_transport_id') - goSubwayAndTrain.where('matricula.transporte_trem_metro = 1'); - goSubwayAndTrain.group('matricula.transporte_trem_metro') - req.queryIndex.goSubwayAndTrain = req.querySet.push(goSubwayAndTrain) - 1; +transportApp.get('/', rqf.parse(), (req, res, next) => { + req.dims.year = true; + req.sql + .field('sum(transporte.total)', 'total') + .field("'Brasil'", 'name') + .from('transporte') + .where('transporte.transporte_id=0') + next(); +}, rqf.build(), query, id2str.transform(), (req, res, next) => { + req.total = req.result; + console.log('here'); + req.resetSql(); + next(); +}, rqf.parse(), (req, res, next) => { + req.dims.year = true; + req.sql + .field('sum(transporte.total)', 'total') + .field("'Brasil'", 'name') + .from('transporte') + .where('transporte.transporte_id=1') + next(); +}, rqf.build(), query, id2str.transform(), (req, res, next) => { + req.public_total = req.result; + console.log('here'); + req.resetSql(); + next(); +}, rqf.parse(), (req, res, next) => { + req.dims.year = true; + req.sql + .field('sum(transporte.total)', 'total') + .field("'Brasil'", 'name') + .field('transporte.transporte_id', 'id') + .from('transporte') + .where('transporte.transporte_id>0') + .group('transporte.transporte_id') + .order('transporte.transporte_id') next(); -}, multiQuery, (req, res, next) => { - let transport_match = []; - let transport_match_0 = JSON.parse(JSON.stringify(req.result[req.queryIndex.allTransports])); - let transport_match_1 = JSON.parse(JSON.stringify(req.result[req.queryIndex.allTransports])); - - let all_enrollment_match = []; - let all_enrollment_match_0 = JSON.parse(JSON.stringify(req.result[req.queryIndex.allEnrollment])); - let all_enrollment_match_1 = JSON.parse(JSON.stringify(req.result[req.queryIndex.allEnrollment])); - - //modifica adicionando use_transport_id=false, com os mesmos valores - //do transport_id=true, usado para dar o match e fazer a divisão. - for (let i = 0; i < transport_match_0.length; i++) { - transport_match_0[i].use_transport_id = true; - transport_match.push(transport_match_0[i]) - // transport_match_1[i].use_transport_id = false; - // transport_match.push(transport_match_1[i]) +}, rqf.build(), query, id2str.transform(), (req, res, next) => { + let transports = req.result; + + let results = []; + let obj = {}; + for (let i = 1; i < 13; i++) { + obj[id2str.transport(i)] = []; } - //modifica adicionando use_transport_id=false, com os mesmos valores - //do transport_id=true, usado para dar o match e fazer a divisão. - for (let i = 0; i < all_enrollment_match_0.length; i++) { - all_enrollment_match_0[i].use_transport_id = true; - all_enrollment_match.push(all_enrollment_match_0[i]) - // all_enrollment_match_1[i].use_transport_id = false; - // all_enrollment_match.push(all_enrollment_match_1[i]) + let i = 0 + while (i < transports.length) { + let result = []; + let j = 0; + let transport = transports[i]; + let totalArray = (transport.id == 1) ? req.total : req.public_total; + let match; + obj[id2str.transport(transport.id)] = result; + while (j < totalArray.length && i < transports.length) { + transport = transports[i]; + let transportTotal = totalArray[j]; + + let currentTransport = {}; + delete transport.id; + match = true; + Object.keys(transport).forEach(function(key) { + currentTransport[key] = transportTotal[key]; + if (key != 'total' && transport[key] != transportTotal[key]) { + match = false; + return; + } + }) + + if (match) { + currentTransport.partial = (match) ? transport.total : 0; + currentTransport.percentage = (match) ? transport.total/transportTotal.total * 100 : 0; + result.push(currentTransport); + i++; + j++; + } + else + j++; + } } + results.push(obj) + req.result = results; - let public_transport = matchQueries(all_enrollment_match, req.result[req.queryIndex.allEnrollmentTransport]); - let van_and_kombi = matchQueries(transport_match, req.result[req.queryIndex.goVansAndKombi]); - let micro_bus = matchQueries(transport_match, req.result[req.queryIndex.goMicroBus]); - let bus = matchQueries(transport_match, req.result[req.queryIndex.goBus]); - let bike = matchQueries(transport_match, req.result[req.queryIndex.goBikes]); - let animal_traction = matchQueries(transport_match, req.result[req.queryIndex.goAnimalTraction]); - let other_vehicle = matchQueries(transport_match, req.result[req.queryIndex.goOtherVehicle]); - let waterway_5_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_5_Students]); - let waterway_15_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_15_Students]); - let waterway_35_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_35_Students]); - let waterway_More_Than_35 = matchQueries(transport_match, req.result[req.queryIndex.goWaterwayMoreThan_35]); - let subway_and_train = matchQueries(transport_match, req.result[req.queryIndex.goSubwayAndTrain]); - - req.result = [{ - public_transport, - van_and_kombi, - micro_bus, - bus, - bike, - animal_traction, - other_vehicle, - waterway_5_Students, - waterway_15_Students, - waterway_35_Students, - waterway_More_Than_35, - subway_and_train - }]; next(); -}, id2str.multitransform(false), response('transports')); +}, response('transports')); module.exports = transportApp; diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js new file mode 100644 index 0000000000000000000000000000000000000000..959f4adb331344515f139582014150cebbe43749 --- /dev/null +++ b/src/libs/routes/university.js @@ -0,0 +1,331 @@ +/* +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 universityApp = 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 cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; + +const addMissing = require(`${libs}/middlewares/addMissing`); + +let rqf = new ReqQueryFields(); + +let rqfCount = new ReqQueryFields(); + +universityApp.use(cache('15 day')); + +universityApp.get('/upper_adm_dependency', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 7; ++i) { + req.result.push({ + id: i, + name: id2str.upperAdmDependency(i) + }); + }; + next(); +}, response('upper_adm_dependency')); + +universityApp.get('/years', (req, res, next) => { + req.sql.from('ies_ens_superior') + .field('DISTINCT ies_ens_superior.ano_censo', 'year') + next(); +}, query, response('years')); + +universityApp.get('/year_range', (req, res, next) => { + req.sql.from('ies_ens_superior') + .field('MIN(ies_ens_superior.ano_censo)', 'start_year') + .field('MAX(ies_ens_superior.ano_censo)', 'end_year'); + next(); +}, query, response('range')); + +universityApp.get('/academic_organization', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 5; ++i) { + req.result.push({ + id: i, + name: id2str.academicOrganization(i) + }); + }; + next(); +}, response('academic_organization')); + +universityApp.get('/capital', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 1; ++i) { + req.result.push({ + id: i, + name: id2str.booleanVariable(i) + }); + }; + next(); +}, response('capital')); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addValue({ + name: 'id', + table: 'ies_ens_superior', + tableField: 'cod_ies', + resultField: 'id', + where: { + relation: '=', + type: 'integer', + field: 'cod_ies' + } +}).addValue({ + name: 'city', + table: 'municipio', + tableField: 'nome', + resultField: 'city_name', + where: { + relation: '=', + type: 'integer', + field: 'cod_municipio_ies', + table: 'ies_ens_superior' + }, + join: { + primary: 'id', + foreign: 'cod_municipio_ies', + foreignTable: 'ies_ens_superior' + } +}).addValue({ + name: 'state', + table: 'estado', + tableField: 'nome', + resultField: 'state_name', + where: { + relation: '=', + type: 'integer', + field: 'cod_uf_ies', + table: 'ies_ens_superior' + }, + join: { + primary: 'id', + foreign: 'cod_uf_ies', + foreignTable: 'ies_ens_superior' + } +}).addValue({ + name: 'year', + table: 'ies_ens_superior', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + table: 'ies_ens_superior' + } +}).addField({ + name: 'search', + field: true, + where: true +}).addValueToField({ + name: 'city_name', + table: 'municipio', + tableField: 'nome', + resultField: 'city_name', + dontGroup: true, + where: { + relation: 'LIKE', + type: 'string', + field: 'nome' + }, + join: { + primary: 'id', + foreign: 'cod_municipio_ies', + foreignTable: 'ies_ens_superior' + } +}, 'search') +.addValueToField({ + name: 'state_name', + table: 'estado', + tableField: 'nome', + resultField: 'state_name', + dontGroup: true, + where: { + relation: 'LIKE', + type: 'string', + field: 'sigla' + }, + join: { + primary: 'id', + foreign: 'cod_uf_ies', + foreignTable: 'ies_ens_superior' + } +}, 'search'); + + +rqfCount.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'city', + table: 'municipio', + tableField: ['nome', 'id'], + resultField: ['city_name', 'city_id'], + where: { + relation: '=', + type: 'integer', + field: 'cod_municipio_ies', + table: 'ies_ens_superior' + }, + join: { + primary: 'id', + foreign: 'cod_municipio_ies', + foreignTable: 'ies_ens_superior' + } +}).addValue({ + name: 'region', + table: 'regiao', + tableField: ['nome', 'id'], + resultField: ['region_name', 'region_id'], + where: { + relation: 'LIKE', + type: 'string', + field: 'id' + }, + join: { + primary: 'nome', + foreign: 'nome_regiao_ies', + foreignTable: 'ies_ens_superior' + } + +}).addValue({ + name: 'min_year', + table: '@', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + table: '@', + field: 'ano_censo' + } +}).addValue({ + name: 'max_year', + table: '@', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + table: '@', + field: 'ano_censo' + } +}).addValue({ + name: 'state', + table: 'estado', + tableField: ['nome', 'id'], + resultField: ['state_name', 'state_id'], + where: { + relation: '=', + type: 'integer', + field: 'cod_uf_ies', + table: '@' + }, + join: { + primary: 'id', + foreign: 'cod_uf_ies', + foreignTable: '@' + } +}).addValue({ + name: 'upper_adm_dependency', + table: 'ies_ens_superior', + tableField: 'par_categoria_administrativa', + resultField: 'upper_adm_dependency_id', + where: { + relation: '=', + type: 'integer', + table: 'ies_ens_superior', + field: 'cod_categoria_administrativa' + } +}).addValue({ + name: 'academic_organization', + table: 'ies_ens_superior', + tableField: 'cod_organizacao_academica', + resultField: 'academic_organization_id', + where: { + relation: '=', + type: 'integer', + table: 'ies_ens_superior', + field: 'cod_organizacao_academica' + } +}).addValue({ + name: 'capital', + table: 'ies_ens_superior', + tableField: 'tfd_capital_ies', + resultField: 'capital_id', + where: { + relation: '=', + type: 'integer', + table: 'ies_ens_superior', + field: 'capital_ies' + } +}); + +universityApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.from('ies_ens_superior') + .field('ies_ens_superior.cod_ies', 'id') + .field('ies_ens_superior.ano_censo', 'year') + .field('ies_ens_superior.nome_ies', 'name') + .field('ies_ens_superior.cod_uf_ies', 'state_id') + .field('ies_ens_superior.cod_municipio_ies', 'city_id'); + next(); + +}, query, response('university')); + +universityApp.get('/count', rqfCount.parse(), (req, res, next) => { + req.sql.field('COUNT(*)', 'total') + .field("'Brasil'", 'name') + .field('ies_ens_superior.ano_censo', 'year') + .from('ies_ens_superior') + .group('ies_ens_superior.ano_censo') + .order('ies_ens_superior.ano_censo') + + next(); +}, rqfCount.build(), query, addMissing(rqfCount), id2str.transform(), response('university')); + +module.exports = universityApp; diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js new file mode 100644 index 0000000000000000000000000000000000000000..9eb452fd6dc5cbc8a5663514cd5c1557513a578b --- /dev/null +++ b/src/libs/routes/universityEnrollment.js @@ -0,0 +1,479 @@ +/* +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 universityEnrollmentApp = 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 addMissing = require(`${libs}/middlewares/addMissing`); + +const config = require(`${libs}/config`); + +const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; + +let rqf = new ReqQueryFields(); + +universityEnrollmentApp.get('/years', (req, res, next) => { + req.sql.from('aluno_ens_superior') + .field('DISTINCT aluno_ens_superior.ano_censo', 'year'); + next(); +}, query, response('years')); + +universityEnrollmentApp.get('/year_range', (req, res, next) => { + req.sql.from('aluno_ens_superior') + .field('MIN(aluno_ens_superior.ano_censo)', 'start_year') + .field('MAX(aluno_ens_superior.ano_censo)', 'end_year'); + next(); +}, query, response('range')); + +universityEnrollmentApp.get('/academic_organization', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 5; ++i) { + req.result.push({ + id: i, + name: id2str.academicOrganization(i) + }); + }; + next(); +}, response('academic_organization')); + +universityEnrollmentApp.get('/upper_adm_dependency', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 7; ++i) { + req.result.push({ + id: i, + name: id2str.upperAdmDependency(i) + }); + }; + next(); +}, response('upper_adm_dependency')); + +universityEnrollmentApp.get('/ocde_geral', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 8; ++i) { + req.result.push({ + id: i, + name: id2str.ocdeGeral(i) + }); + }; + next(); +}, response('ocde_geral')); + +universityEnrollmentApp.get('/ocde_specific', (req, res, next) => { + req.result = []; + const defaultCase = null; + for(let i = 1; i <= 86; ++i) { + let obj = { + id: i, + name: id2str.ocdeSpecific(i) + }; + if (obj.name !== id2str.ocdeSpecific(defaultCase)){ + req.result.push(obj); + } + }; + req.result.push({ + id: defaultCase, + name: id2str.ocdeSpecific(defaultCase) + }); + next(); +}, response('ocde_specific')); + +universityEnrollmentApp.get('/ocde_detailed', (req, res, next) => { + req.result = []; + const defaultCase = null; + for(let i = 142; i <= 863; ++i) { + let obj = { + id: i, + name: id2str.ocdeDetailed(i) + }; + if (obj.name !== id2str.ocdeDetailed(defaultCase)){ + req.result.push(obj); + } + }; + req.result.push({ + id: defaultCase, + name: id2str.ocdeDetailed(defaultCase) + }); + next(); +}, response('ocde_detailed')); + +universityEnrollmentApp.get('/upper_turn', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 4; ++i) { + req.result.push({ + id: i, + name: id2str.upperTurn(i) + }); + }; + next(); +}, response('upper_turn')); + +universityEnrollmentApp.get('/student_deficiency', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 1; ++i) { + req.result.push({ + id: i, + name: id2str.studentDeficiency(i) + }); + }; + next(); +}, response('student_deficiency')); + +universityEnrollmentApp.get('/ethnic_group_ies', (req, res, next) => { + req.result = []; + for(let i = 1; i <=5; ++i) { + req.result.push({ + id: i, + name: id2str.ethnicGroupIES(i) + }); + } + next(); +}, response('ethnic_group_ies')); + +universityEnrollmentApp.get('/school_type', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 2; ++i) { + req.result.push({ + id: i, + name: id2str.schoolType(i) + }); + }; + next(); +}, response('school_type')); + +universityEnrollmentApp.get('/university', (req, res, next) => { + req.sql.from('aluno_ens_superior') + .field('DISTINCT aluno_ens_superior.nome_ies', 'nome') + .field('aluno_ens_superior.cod_ies', 'cod') + next(); +}, query, response('university')); + +universityEnrollmentApp.get('/academic_level', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 4; ++i) { + req.result.push({ + id: i, + name: id2str.academicLevel(i) + }); + }; + next(); +}, response('academic_level')); + +universityEnrollmentApp.get('/gender_ies', function (req, res, next) { + req.result = []; + for (var i = 1; i <= 2; ++i) { + req.result.push({ + id: i, + name: id2str.genderIES(i) + }); + }; + next(); +}, response('gender_ies')); + +universityEnrollmentApp.get('/upper_education_mod', function (req, res, next) { + req.result = []; + for (var i = 1; i <= 3; ++i) { + req.result.push({ + id: i, + name: id2str.upperEducationMod(i) + }); + }; + next(); +}, response('upper_education_mod')); + +universityEnrollmentApp.get('/age_student_code', function (req, res, next) { + req.result = []; + for (var i = 1; i <= 6; ++i) { + req.result.push({ + id: i, + name: id2str.ageStudentCode(i) + }); + }; + next(); +}, response('age_student_code')); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'min_year', + table: '@', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + table: '@', + field: 'ano_censo' + } +}).addValue({ + name: 'max_year', + table: '@', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + table: '@', + field: 'ano_censo' + } +}).addValue({ + name: 'state', + table: 'estado', + tableField: ['nome', 'id'], + resultField: ['state_name', 'state_id'], + where: { + relation: '=', + type: 'integer', + field: 'cod_uf_ies', + table: '@' + }, + join: { + primary: 'id', + foreign: 'cod_uf_ies', + foreignTable: '@' + } +}).addValue({ + name: 'city', + table: 'municipio', + tableField: ['nome', 'id'], + resultField: ['city_name', 'city_id'], + where: { + relation: '=', + type: 'integer', + field: 'cod_municipio_ies', + table: '@' + }, + join: { + primary: 'id', + foreign: 'cod_municipio_ies', + foreignTable: '@' + } +}).addValue({ + name: 'region', + table: 'regiao', + tableField: ['nome', 'id'], + resultField: ['region_name', 'region_id'], + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'id', + foreign: 'cod_regiao_ies', + foreignTable: 'aluno_ens_superior' + } +}).addValue({ + name: 'university', + table: 'aluno_ens_superior', + tableField: ['cod_ies', 'nome_ies'], + resultField: ['university_id', 'university_name'], + where: { + relation: '=', + type: 'integer', + field: 'cod_ies' + } +}).addValue({ + name: 'age_student_code', + table: 'aluno_ens_superior', + tableField: 'idade_aluno_codigo', + resultField: 'age_student_code_id', + where: { + relation: '=', + type: 'integer', + field: 'idade_aluno_codigo' + } +}).addValue({ + name: 'upper_adm_dependency', + table: 'aluno_ens_superior', + tableField: 'cod_categoria_administrativa', + resultField: 'upper_adm_dependency_id', + where: { + relation: '=', + type: 'integer', + table: 'aluno_ens_superior', + field: 'cod_categoria_administrativa' + } +}).addValue({ + name: 'academic_organization', + table: 'aluno_ens_superior', + tableField: 'cod_organizacao_academica', + resultField: 'academic_organization_id', + where: { + relation: '=', + type: 'integer', + table: 'aluno_ens_superior', + field: 'cod_organizacao_academica' + } +}).addValue({ + name:'ocde_specific', + table: 'aluno_ens_superior', + tableField: 'cod_ocde_area_especifica', + resultField: 'ocde_specific_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_ocde_area_especifica' + } +}).addValue({ + name:'ocde_geral', + table: 'aluno_ens_superior', + tableField: 'cod_ocde_area_geral', + resultField: 'ocde_geral_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_ocde_area_geral' + } +}).addValue({ + name:'ocde_detailed', + table: 'aluno_ens_superior', + tableField: 'cod_ocde_area_detalhada', + resultField: 'ocde_detailed_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_ocde_area_detalhada' + } +}).addValue({ + name:'academic_level', + table: 'aluno_ens_superior', + tableField: 'cod_grau_academico', + resultField: 'academic_level_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_grau_academico' + } +}).addValue({ + name:'upper_education_mod', + table: 'aluno_ens_superior', + tableField: 'cod_modalidade_ensino', + resultField: 'upper_education_mod_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_modalidade_ensino' + } +}).addValue({ + name:'upper_turn', + table: 'aluno_ens_superior', + tableField: 'cod_turno_aluno', + resultField: 'upper_turn_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_turno_aluno' + } +}).addValue({ + name:'ethnic_group_ies', + table: 'aluno_ens_superior', + tableField: 'cod_cor_raca_aluno', + resultField: 'ethnic_group_ies_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_cor_raca_aluno' + } +}).addValue({ + name:'student_deficiency', + table: 'aluno_ens_superior', + tableField: 'aluno_deficiencia_transtorno_superdotacao', + resultField: 'student_deficiency_id', + where: { + relation: '=', + type: 'integer', + field: 'aluno_deficiencia_transtorno_superdotacao' + } +}).addValue({ + name:'school_type', + table: 'aluno_ens_superior', + tableField: 'tipo_escola_ensino_medio', + resultField: 'school_type_id', + where: { + relation: '=', + type: 'integer', + field: 'tipo_escola_ensino_medio' + } +}).addValue({ + name: 'university', + table: 'aluno_ens_superior', + tableField: ['cod_ies', 'nome_ies'], + resultField: ['university_id', 'university_name'], + where: { + relation: '=', + type: 'integer', + field: 'cod_ies' + } +}).addValue({ + name: 'gender_ies', + table: 'aluno_ens_superior', + tableField: 'genero_aluno', + resultField: 'gender_ies_id', + where: { + relation: '=', + type: 'integer', + field: 'genero_aluno' + } +}).addValue({ + name:'academic_level', + table: 'aluno_ens_superior', + tableField: 'cod_grau_academico', + resultField: 'academic_level_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_grau_academico' + } +}); + +universityEnrollmentApp.get('/', rqf.parse(), (req, res, next) => { + req.sql.field('COUNT(*)', 'total') + .field("'Brasil'", 'name') + .field('aluno_ens_superior.ano_censo', 'year') + .from('aluno_ens_superior') + .where('aluno_ens_superior.matriculado = 1 AND aluno_ens_superior.cod_nivel_academico = 1') + .group('aluno_ens_superior.ano_censo') + .order('aluno_ens_superior.ano_censo') + + next(); +}, rqf.build(), query, addMissing(rqf), id2str.transform(false), response('universityEnrollment')); + +module.exports = universityEnrollmentApp; diff --git a/src/libs/routes/universityTeacher.js b/src/libs/routes/universityTeacher.js new file mode 100644 index 0000000000000000000000000000000000000000..58a9164e29bdb911c9828217902b4cfbcb3993be --- /dev/null +++ b/src/libs/routes/universityTeacher.js @@ -0,0 +1,477 @@ +/* +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 teacherEnrollmentApp = 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 addMissing = require(`${libs}/middlewares/addMissing`); + +const config = require(`${libs}/config`); + +const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; + +let rqf = new ReqQueryFields(); + +teacherEnrollmentApp.get('/years', (req, res, next) => { + req.sql.from('docente_ens_superior') + .field('DISTINCT docente_ens_superior.ano_censo', 'year'); + next(); +}, query, response('years')); + +teacherEnrollmentApp.get('/year_range', (req, res, next) => { + req.sql.from('docente_ens_superior') + .field('MIN(docente_ens_superior.ano_censo)', 'start_year') + .field('MAX(docente_ens_superior.ano_censo)', 'end_year'); + next(); +}, query, response('range')); + +teacherEnrollmentApp.get('/academic_organization', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 5; ++i) { + req.result.push({ + id: i, + name: id2str.academicOrganization(i) + }); + }; + next(); +}, response('academic_organization')); + +teacherEnrollmentApp.get('/upper_adm_dependency', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 7; ++i) { + req.result.push({ + id: i, + name: id2str.upperAdmDependency(i) + }); + }; + next(); +}, response('upper_adm_dependency')); + +teacherEnrollmentApp.get('/teacher_situation', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 6; ++i) { + req.result.push({ + id: i, + name: id2str.teacherSituation(i) + }); + }; + next(); +}, response('teacher_situation')); + +teacherEnrollmentApp.get('/work_regime', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 4; ++i) { + req.result.push({ + id: i, + name: id2str.workRegime(i) + }); + }; + next(); +}, response('work_regime')); + +teacherEnrollmentApp.get('/substitute', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 1; ++i) { + req.result.push({ + id: i, + name: id2str.booleanVariable(i) + }); + }; + next(); +}, response('substitute')); + +teacherEnrollmentApp.get('/visitor', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 1; ++i) { + req.result.push({ + id: i, + name: id2str.booleanVariable(i) + }); + }; + next(); +}, response('visitor')); + +teacherEnrollmentApp.get('/ead_teacher', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 1; ++i) { + req.result.push({ + id: i, + name: id2str.booleanVariable(i) + }); + }; + next(); +}, response('ead_teacher')); + +teacherEnrollmentApp.get('/graduation_presential', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 1; ++i) { + req.result.push({ + id: i, + name: id2str.booleanVariable(i) + }); + }; + next(); +}, response('graduation_presential')); + +teacherEnrollmentApp.get('/postgraduate_ead_teacher', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 1; ++i) { + req.result.push({ + id: i, + name: id2str.booleanVariable(i) + }); + }; + next(); +}, response('postgraduate_ead_teacher')); + +teacherEnrollmentApp.get('/postgraduate_presential_teacher', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 1; ++i) { + req.result.push({ + id: i, + name: id2str.booleanVariable(i) + }); + }; + next(); +}, response('postgraduate_presential_teacher')); + +teacherEnrollmentApp.get('/deficiency', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 1; ++i) { + req.result.push({ + id: i, + name: id2str.booleanVariable(i) + }); + }; + next(); +}, response('deficiency')); + +teacherEnrollmentApp.get('/ethnic_group_teacher_ies', (req, res, next) => { + req.result = []; + for(let i = 0; i <= 5; ++i) { + req.result.push({ + id: i, + name: id2str.ethnicGroupTeacherIES(i) + }); + }; + next(); +}, response('ethnic_group_teacher_ies')); + +teacherEnrollmentApp.get('/teacher_schooling', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 5; ++i) { + req.result.push({ + id: i, + name: id2str.teacherSchooling(i) + }); + }; + next(); +}, response('teacher_schooling')); + +teacherEnrollmentApp.get('/gender_ies', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 2; ++i) { + req.result.push({ + id: i, + name: id2str.genderIES(i) + }); + }; + next(); +}, response('gender_ies')); + + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'min_year', + table: '@', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + table: '@', + field: 'ano_censo' + } +}).addValue({ + name: 'max_year', + table: '@', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + table: '@', + field: 'ano_censo' + } +}).addValue({ + name: 'state', + table: 'estado', + tableField: ['nome', 'id'], + resultField: ['state_name', 'state_id'], + where: { + relation: '=', + type: 'integer', + field: 'cod_uf_ies', + table: '@' + }, + join: { + primary: 'id', + foreign: 'cod_uf_ies', + foreignTable: '@' + } +}).addValue({ + name: 'city', + table: 'municipio', + tableField: ['nome', 'id'], + resultField: ['city_name', 'city_id'], + where: { + relation: '=', + type: 'integer', + field: 'cod_municipio_ies', + table: '@' + }, + join: { + primary: 'id', + foreign: 'cod_municipio_ies', + foreignTable: '@' + } +}).addValue({ + name: 'region', + table: 'regiao', + tableField: ['nome', 'id'], + resultField: ['region_name', 'region_id'], + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'id', + foreign: 'cod_regiao_ies', + foreignTable: 'docente_ens_superior' + } +}).addValue({ + name: 'university', + table: 'docente_ens_superior', + tableField: ['cod_ies', 'nome_ies'], + resultField: ['university_id', 'university_name'], + where: { + relation: '=', + type: 'integer', + field: 'cod_ies' + } +}).addValue({ + name: 'upper_adm_dependency', + table: 'docente_ens_superior', + tableField: 'cod_categoria_administrativa', + resultField: 'upper_adm_dependency_id', + where: { + relation: '=', + type: 'integer', + table: 'docente_ens_superior', + field: 'cod_categoria_administrativa' + } +}).addValue({ + name: 'academic_organization', + table: 'docente_ens_superior', + tableField: 'cod_organizacao_academica', + resultField: 'academic_organization_id', + where: { + relation: '=', + type: 'integer', + table: 'docente_ens_superior', + field: 'cod_organizacao_academica' + } +}).addValue({ + name:'academic_level', + table: 'docente_ens_superior', + tableField: 'cod_grau_academico', + resultField: 'academic_level_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_grau_academico' + } +}).addValue({ + name:'upper_education_mod', + table: 'docente_ens_superior', + tableField: 'cod_modalidade_ensino', + resultField: 'upper_education_mod_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_modalidade_ensino' + } +}).addValue({ + name:'teacher_situation', + table: 'docente_ens_superior', + tableField: 'cod_situacao_docente', + resultField: 'teacher_situation_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_situacao_docente' + } +}).addValue({ + name:'work_regime', + table: 'docente_ens_superior', + tableField: 'cod_regime_trabalho', + resultField: 'work_regime_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_regime_trabalho' + } +}).addValue({ + name:'substitute', + table: 'docente_ens_superior', + tableField: 'docente_substituto', + resultField: 'substitute_id', + where: { + relation: '=', + type: 'integer', + field: 'docente_substituto' + } +}).addValue({ + name:'visitor', + table: 'docente_ens_superior', + tableField: 'docente_visitante', + resultField: 'visitor_id', + where: { + relation: '=', + type: 'integer', + field: 'docente_visitante' + } +}).addValue({ + name:'ead_teacher', + table: 'docente_ens_superior', + tableField: 'ministra_aula_ead', + resultField: 'ead_teacher_id', + where: { + relation: '=', + type: 'integer', + field: 'ministra_aula_ead' + } +}).addValue({ + name:'graduation_presential', + table: 'docente_ens_superior', + tableField: 'atua_atividade_graduacao_presencial', + resultField: 'graduation_presential_id', + where: { + relation: '=', + type: 'integer', + field: 'atua_atividade_graduacao_presencial' + } +}).addValue({ + name:'postgraduate_ead_teacher', + table: 'docente_ens_superior', + tableField: 'atua_atividade_posgraduacao_distancia', + resultField: 'postgraduate_ead_teacher_id', + where: { + relation: '=', + type: 'integer', + field: 'atua_atividade_posgraduacao_distancia' + } +}).addValue({ + name:'postgraduate_presential_teacher', + table: 'docente_ens_superior', + tableField: 'atua_atividade_posgraduacao_presencial', + resultField: 'postgraduate_presential_teacher_id', + where: { + relation: '=', + type: 'integer', + field: 'atua_atividade_posgraduacao_presencial' + } +}).addValue({ + name:'teacher_schooling', + table: 'docente_ens_superior', + tableField: 'cod_escolaridade_docente', + resultField: 'teacher_schooling_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_escolaridade_docente' + } +}).addValue({ + name:'ethnic_group_teacher_ies', + table: 'docente_ens_superior', + tableField: 'cod_cor_raca_docente', + resultField: 'ethnic_group_teacher_ies_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_cor_raca_docente' + } +}).addValue({ + name:'gender_ies', + table: 'docente_ens_superior', + tableField: 'sexo_docente', + resultField: 'gender_ies_id', + where: { + relation: '=', + type: 'integer', + field: 'sexo_docente' + } +}).addValue({ + name:'deficiency', + table: 'docente_ens_superior', + tableField: 'docente_deficiencia', + resultField: 'deficiency_id', + where: { + relation: '=', + type: 'integer', + field: 'docente_deficiencia' + } +}); + +teacherEnrollmentApp.get('/', rqf.parse(), (req, res, next) => { + req.sql.field('COUNT(*)', 'total') + .field("'Brasil'", 'name') + .field('docente_ens_superior.ano_censo', 'year') + .from('docente_ens_superior') + .group('docente_ens_superior.ano_censo') + .order('docente_ens_superior.ano_censo') + + next(); +}, rqf.build(), query, addMissing(rqf), id2str.transform(false), response('teacherEnrollment')); + +module.exports = teacherEnrollmentApp; diff --git a/src/libs/routes/user.js b/src/libs/routes/user.js deleted file mode 100644 index af123a588d41a37c1e64fb0cfa20abe3928a84b4..0000000000000000000000000000000000000000 --- a/src/libs/routes/user.js +++ /dev/null @@ -1,308 +0,0 @@ -const express = require('express'); - -const userApp = express(); - -const libs = `${process.cwd()}/libs`; - -const config = require(`${libs}/config`); - -const log = require(`${libs}/log`)(module); - -const User = require(`${libs}/models/user`); - -const VerificationToken = require(`${libs}/models/verificationToken`); - -const ResetToken = require(`${libs}/models/resetToken`); - -const response = require(`${libs}/middlewares/response`); - -const email = require(`${libs}/middlewares/email`); - -const passport = require('passport'); - -function emailSyntax(email) { - const regex = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; - return regex.test(email); -} - -userApp.get('/schooling', (req, res, next) => { - req.result = [ - 'Não estudou', - 'Ensino Fundamental Incompleto', - 'Ensino Fundamental Completo', - 'Ensino Médio', - 'Graduação', - 'Mestrado', - 'Doutorado' - ]; - next(); -}, response('schooling')); - -userApp.get('/segment', (req, res, next) => { - req.result = [ - 'Gestores e equipe gestora das secretarias e ministério da Educação', - 'Gestores dos órgãos de planejamento e finanças (das três esferas de governo)', - 'Agentes do poder legislativo', - 'Agentes dos conselhos de educação', - 'Profissionais da educação', - 'Sindicato', - 'Sociedade civil interessada no financiamento da Educação Básica de qualidade', - 'Comunidade acadêmica', - 'Imprensa', - 'Outro [citar segmento]' - ]; - next(); -}, response('segment')); - -userApp.get('/role', (req, res, next) => { - req.result = [ - {"Gestores e equipe gestora das secretarias e ministério da Educação" : ["Dirigente municipal, estadual e federal", "Secretário do MEC", "Servidor da área de planejamento educacional", "Membro de associação de gestores (Ex. Undime, Consed, etc)", "Outro [citar função]"]}, - {"Gestores dos órgãos de planejamento e finanças (das três esferas de governo)" : ["Equipe gestora dos órgãos de planejamento", "Equipe gestora dos órgãos de finanças", "Outro [citar função]"]}, - {"Agentes do poder legislativo" : ["Parlamentar", "Assessor/a parlamentar", "Auditor/a dos tribunais de conta", "Conselheiro/a de tribunais de conta.", "Outro [citar função]"]}, - {"Agentes dos conselhos de educação" : ["Conselheiro/a municipais, estaduais e federais", "Conselheiro/a do Fundeb", "Outro [citar função]"]}, - {"Profissionais da educação" : ["Professor/a da Educação Básica", "Profissional da educação não-docente", "Outro [citar função]"]}, - {"Sindicato" : ["Agente de sindicatos"]}, - {"Sociedade civil interessada no financiamento da Educação Básica de qualidade" : ["Membro de fóruns educacionais", "Membro de ONGs e demais entidades sem fins lucrativos", "Estudante da educação básica e membro de entidades estudantis", "Pais e membros de entidades de pais", "Outro [citar função]"]}, - {"Comunidade acadêmica" : ["Pesquisador/a", "Estudantes de graduação e pós-graduação", "Representantes de entidades de pesquisa (Ex.: ANPED, ANPAE e FINEDUCA)", "Outro [citar função]"]}, - {"Imprensa" : ["Jornalista", "Outro [citar função]"]}, - {"Outro [citar segmento]" : []} - ] - next(); -}, response('role')); - -userApp.get('/', passport.authenticate('bearer', {session: false}), (req, res, next) => { - User.find((err, users) => { - if(err) { - log.error(err); - return next(err); - } - - let result = []; - users.forEach((user) => { - let u = user.toObject(); - delete u.hashedPassword; - delete u.salt; - result.push(u); - }); - req.result = result; - next(); - }); -}, response('users')); - -userApp.get('/me', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - delete user.hashedPassword; - delete user.salt; - req.result = user; - next(); -}, response('user')); - -userApp.get('/:id', (req, res, next) => { - User.findById(req.params.id, (err, user) => { - if(err) { - log.error(err); - return next(err); - } - if(!user) { - req.statusCode = 404; - next({msg: 'User not found'}); - } else { - let u = user.toObject; - delete u.hashedPassword; - delete u.salt; - req.result = u; - next(); - } - }); -}, response('user')); - -userApp.post('/', (req, res, next) => { - let user = new User({ - email: req.body.email, - password: req.body.password, - name: req.body.name, - nickname: req.body.nickname, - cpf: req.body.cpf, - cep: req.body.cep, - complement: req.body.complement, - address: req.body.address, - phone: req.body.phone, - schooling: req.body.schooling, - course: req.body.course, - segment: req.body.segment, - role: req.body.role, - institutionName: req.body.institutionName, - state: req.body.state, - city: req.body.city, - receiveEmails: false || req.body.receiveEmails, - origin: req.body.origin, - citesegment: req.body.citesegment, - citerole: req.body.citerole, - admin: false - }); - - if (typeof req.body.password === 'undefined' || !req.body.password) { - res.statusCode = 400; - return res.json({errors: ["O campo senha é obrigatório"]}); - } else { - user.save((err) => { - if(err) { - log.error(err); - let errors = []; - for(let errName in err.errors) { - errors.push(err.errors[errName].message); - } - log.error(errors); - res.statusCode = 400; - return res.json({err, errors}); - } - - // Create verification token - let verificationToken = new VerificationToken({ - userId: user._id - }); - - verificationToken.createVerificationToken((err, token) => { - if(err) { - log.error(err); - return next(err); - } - let url = config.default.lde.url + '/verify'; - let text = `Olá, ${user.name}, seja bem vindo/a ao Laboratório de Dados Educacionais.\n\nClique neste link para confirmar sua conta: ${url}/${token}`; - // Send confirmation email - let mailOptions = { - to: `"${user.name} <${user.email}>"`, - subject: "Confirme seu cadastro - Laboratório de Dados Educacionais", - text - } - email(mailOptions, (err, info) => { - if(err) { - log.error(err); - res.json({msg: 'User created'}); - } - if(info) { - log.info(`Message ${info.messageId} sent: ${info.response}`); - log.info(`Usuário ${user.email} foi criado`); - } - res.json({msg: 'User created'}); - }); - }); - }); - } - -}); - -userApp.put('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => { - console.log(req.params.id); - console.log(req.user._id); - User.findById(req.params.id, (err, user) => { - if (err) { - log.error(err); - return next({err}); - } - - if(!user) { - res.statusCode = 404; - return next({err: { - message: 'Usuário não encontrado' - }}); - } - - console.log(req.body); - - user.email = req.body.email || user.email; - user.name = req.body.name || user.name; - user.nickname = req.body.nickname || user.nickname || user.name; - user.cep = req.body.cep || user.cep; - user.complement = req.body.complement || user.complement; - user.address = req.body.address || user.address; - user.phone = req.body.phone || user.phone; - user.schooling = req.body.schooling || user.schooling; - user.course = req.body.course || user.course; - user.segment = req.body.segment || user.segment; - user.role = req.body.role || user.role; - user.institutionName = req.body.institutionName || user.institutionName; - user.state = req.body.state || user.state; - user.city = req.body.city || user.city; - user.receiveEmails = req.body.receiveEmails || user.receiveEmails; - user.citesegment = req.body.citesegment || user.citesegment; - user.citerole = req.body.citerole || user.citerole; - - // console.log(user.checkPassword(req.body.password)); - if ((req.body.password) && (req.body.newpassword)) { - if (req.body.password != req.body.newpassword) { - if (user.checkPassword(req.body.password)) { - user.password = req.body.newpassword; - } else { - res.statusCode = 500; - return res.json({error: { - message: 'A senha atual está incorreta' - }}); - } - } else { - res.statusCode = 500; - return res.json({error: { - message: 'A nova senha é a mesma da senha atual' - }}); - } - } - - user.save(err => { - if(err) { - log.error(err); - return next({message: 'Erro ao atualizar usuário'}); - } - let u = user.toObject(); - delete u.hashedPassword; - delete u.salt; - res.json({user: u}); - }) - }) -}); - -userApp.get('/reset/password', (req, res, next) => { - let emailAddress = req.query.email; - User.findOne({email: emailAddress}, (err, user)=> { - if(err) { - log.error(err); - let errors = []; - for(let errName in err.errors) { - errors.push(err.errors[errName].message); - } - res.statusCode = 400; - return res.json({err, errors}); - } - if (!user) { - res.statusCode = 404; - res.json({msg: "O usuário não está cadastrado"}); - } - else { - let resetToken = new ResetToken({ - userId: user._id - }); - resetToken.createResetToken((err, token) => { - if (err) { - log.error(err); - return next(err); - } - let url = config.default.lde.url + '/reset-password'; - let text = `Olá, ${user.name}.\n\nRecebemos uma solicitação para redefinir sua senha do Laboratório de Dados Educacionais. Clique neste link para redefinir a sua senha: ${url}/${token}`; - let mailOptions = { - to: `"${user.name} <${user.email}>"`, - subject: "Redefinição de Senha - Laboratório de Dados Educacionais", - text - } - email(mailOptions, (err, info) => { - if(err) { - log.error(err); - res.json({msg: 'Undelivered Reset Password Mail'}); - } - log.info(`Message ${info.messageId} sent: ${info.response}`); - res.json({msg: 'Reset Password Mail Successfully Delivered'}); - }); - }) - } - }) -}) - -module.exports = userApp; diff --git a/src/libs/routes/verifyToken.js b/src/libs/routes/verifyToken.js deleted file mode 100644 index d54f64aa162c767c765784398dbcab455a9d666e..0000000000000000000000000000000000000000 --- a/src/libs/routes/verifyToken.js +++ /dev/null @@ -1,52 +0,0 @@ -const express = require('express'); - -const verifyTokenApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const VerificationToken = require(`${libs}/models/verificationToken`); - -const User = require(`${libs}/models/user`); - -verifyTokenApp.get('/:token', (req, res, next) => { - let token = req.params.token; - VerificationToken.findOne({token: token}, (err, vToken) => { - if(err) { - log.error(err); - return next(err); - } - if(!vToken) { - // TODO: generate new verification token - res.statusCode = 404; - return next({msg: 'Token not found', status:404}); - } - User.findById(vToken.userId, (err, user) => { - if(err) { - log.error(err); - next(err); - } - user.verified = true; - user.save((err) => { - if(err) { - log.error(err); - next(err); - } - }); - let u = user.toObject(); - delete u.salt; - delete u.hashedPassword; - vToken.verified = true; - vToken.save((err) => { - if(err) { - log.error(err); - next(err); - } - }); - res.json({msg: 'User verified', user: u}); - }); - }); -}); - -module.exports = verifyTokenApp; diff --git a/src/server.js b/src/server.js index 889151c27370bdcce968e3b3c76689288405f689..37c55df65e5cfcc79b74b5cd357e17c559b472d7 100644 --- a/src/server.js +++ b/src/server.js @@ -1,3 +1,23 @@ +/* +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 debug = require('debug')('simcaq-api'); const libs = `${process.cwd()}/libs`; const config = require(`${libs}/config`); diff --git a/src/test/api.js b/src/test/api.js index b5476ea6352d086cb8d43f8e1f091686bc4f91c4..cd37a5f76b18d22d01d45943b339e496f35416fb 100644 --- a/src/test/api.js +++ b/src/test/api.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/auxiliar.js b/src/test/auxiliar.js index 1bb0d309c8fa5ef6165fabae2018f5a6bbd1a090..9732499d6065dd637f48744c649344ac9dcc22b1 100644 --- a/src/test/auxiliar.js +++ b/src/test/auxiliar.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/city.js b/src/test/city.js index 1ea61a62f5d31be3c2789df5bc577a137ea50afa..9defbeb61c352b37690f6f97d1c79b44f92d9a5b 100644 --- a/src/test/city.js +++ b/src/test/city.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/class.js b/src/test/class.js index 3000476ce8f5008dae9e9d8b51132a7512081a9d..dd283b55ac5a0bb84378ff49d14c5254135b76d2 100644 --- a/src/test/class.js +++ b/src/test/class.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -107,7 +127,7 @@ describe('request class', () => { }); }); - it('should list the administrative dependencies', (done) => { + it('should list the administrative dependencies detailed', (done) => { chai.request(server) .get('/api/v1/class/adm_dependency_detailed') .end((err, res) => { @@ -121,7 +141,7 @@ describe('request class', () => { }); }); - it('should list the administrative dependencies detailed', (done) => { + it('should list the administrative dependencies', (done) => { chai.request(server) .get('/api/v1/class/adm_dependency') .end((err, res) => { diff --git a/src/test/classCount.js b/src/test/classCount.js new file mode 100644 index 0000000000000000000000000000000000000000..9880db28f2468054dd9cf54cc149b9b32a002838 --- /dev/null +++ b/src/test/classCount.js @@ -0,0 +1,318 @@ +/* +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/>. +*/ + +process.env.NODE_ENV = 'test'; + +const chai = require('chai'); + +const dirtyChai = require('dirty-chai'); + +chai.use(dirtyChai); + +const chaiXml = require('chai-xml'); + +chai.use(chaiXml); + +const chaiHttp = require('chai-http'); + +const assert = chai.assert; + +const expect = chai.expect; + +const should = chai.should(); // actually call the function + +const libs = `${process.cwd()}/libs`; + +const server = require(`${libs}/app`); + +chai.use(chaiHttp); +describe('request classCount', () => { + it('should return 400 with no filters', (done) => { + chai.request(server) + .get('/api/v1/class_count/') + .end((err, res) => { + res.should.have.status(400); + res.should.be.json; + res.body.should.have.property('error'); + res.body.error.should.be.equal('Wrong/No filter specified'); + done(); + }); + }); + + it('should list the rural locations', (done) => { + chai.request(server) + .get('/api/v1/class_count/rural_location') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the education level mod', (done) => { + chai.request(server) + .get('/api/v1/class_count/education_level_mod') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the education level short', (done) => { + chai.request(server) + .get('/api/v1/class_count/education_level_short') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/class_count/year_range') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('start_year'); + res.body.result[0].should.have.property('end_year'); + done(); + }); + }); + + it('should list the years', (done) => { + chai.request(server) + .get('/api/v1/class_count/years') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + done(); + }); + }); + + it('should list the administrative dependencies', (done) => { + chai.request(server) + .get('/api/v1/class_count/adm_dependency') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the administrative dependencies detailed', (done) => { + chai.request(server) + .get('/api/v1/class_count/adm_dependency_detailed') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the locations', (done) => { + chai.request(server) + .get('/api/v1/class_count/location') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the source', (done) => { + chai.request(server) + .get('/api/v1/class_count/source') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('source'); + done(); + }); + }); + + it('should list the simcaq class count', (done) => { + chai.request(server) + .get('/api/v1/class_count/count') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('average'); + res.body.result[0].should.have.property('median'); + res.body.result[0].should.have.property('stddev'); + res.body.result[0].should.have.property('first_qt'); + res.body.result[0].should.have.property('third_qt'); + done(); + }); + }); + + it('should list the simcaq class count with valid filter', (done) => { + chai.request(server) + .get('/api/v1/class_count/count?filter=state:14') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('average'); + res.body.result[0].should.have.property('median'); + res.body.result[0].should.have.property('stddev'); + res.body.result[0].should.have.property('first_qt'); + res.body.result[0].should.have.property('third_qt'); + done(); + }); + }); + + it('should list the simcaq class count with valid dim', (done) => { + chai.request(server) + .get('/api/v1/class_count/count?dims=region') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('average'); + res.body.result[0].should.have.property('median'); + res.body.result[0].should.have.property('stddev'); + res.body.result[0].should.have.property('first_qt'); + res.body.result[0].should.have.property('third_qt'); + res.body.result[0].should.have.property('region_name'); + done(); + }); + }); + + it('should list class count with education level filter', (done) => { + chai.request(server) + .get('/api/v1/class_count?filter=education_level_mod:["1"]') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('average'); + res.body.result[0].should.have.property('median'); + res.body.result[0].should.have.property('stddev'); + res.body.result[0].should.have.property('first_qt'); + res.body.result[0].should.have.property('third_qt'); + done(); + }); + }); + + it('should list class count with education level dims', (done) => { + chai.request(server) + .get('/api/v1/class_count?dims=education_level_mod') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('average'); + res.body.result[0].should.have.property('median'); + res.body.result[0].should.have.property('stddev'); + res.body.result[0].should.have.property('first_qt'); + res.body.result[0].should.have.property('third_qt'); + res.body.result[0].should.have.property('education_level_mod_id'); + res.body.result[0].should.have.property('education_level_mod_name'); + done(); + }); + }); + + it('should list class count with valid dims', (done) => { + chai.request(server) + .get('/api/v1/class_count?dims=education_level_mod,location') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('average'); + res.body.result[0].should.have.property('median'); + res.body.result[0].should.have.property('stddev'); + res.body.result[0].should.have.property('first_qt'); + res.body.result[0].should.have.property('third_qt'); + res.body.result[0].should.have.property('education_level_mod_id'); + res.body.result[0].should.have.property('education_level_mod_name'); + res.body.result[0].should.have.property('location_id'); + res.body.result[0].should.have.property('location_name'); + done(); + }); + }); + + it('should list class count with education level year limiter', (done) => { + chai.request(server) + .get('/api/v1/class_count?dims=education_level_mod&filter=min_year:2014,max_year:2014') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('average'); + res.body.result[0].should.have.property('median'); + res.body.result[0].should.have.property('stddev'); + res.body.result[0].should.have.property('first_qt'); + res.body.result[0].should.have.property('third_qt'); + res.body.result[0].should.have.property('education_level_mod_id'); + res.body.result[0].should.have.property('education_level_mod_name'); + done(); + }); + }); + +}); diff --git a/src/test/classroom.js b/src/test/classroom.js index 9a6fd00a18afe4f1c584bea4f033dd0dcb3a84a6..3f1d60f201dbc696c8d669e4d81f0ea04c052fd9 100644 --- a/src/test/classroom.js +++ b/src/test/classroom.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/cub.js b/src/test/cub.js index 751ca40a2a77ff9fe7275f0a2f3c769c5318e4f3..475e718f920bd51ce78d5b4150983d84a3d36fc5 100644 --- a/src/test/cub.js +++ b/src/test/cub.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -80,29 +100,46 @@ describe('request cub', () => { }); }); - it('should list the years and months', (done) => { + it('should list the price type', (done) => { chai.request(server) - .get('/api/v1/cub/year_range') + .get('/api/v1/cub/price_type') .end((err, res) => { res.should.have.status(200); res.should.be.json; res.body.should.have.property('result'); res.body.result.should.be.a('array'); - res.body.result[0].should.have.property('year'); - res.body.result[0].should.have.property('month'); + res.body.result[0].should.have.property('price_type'); done(); }); }); - it('should list the price type', (done) => { + it('should return query cub wtih state dim', (done) => { chai.request(server) - .get('/api/v1/cub/price_type') + .get('/api/v1/cub?dims=state') .end((err, res) => { res.should.have.status(200); res.should.be.json; res.body.should.have.property('result'); res.body.result.should.be.a('array'); - res.body.result[0].should.have.property('price_type'); + res.body.result[0].should.have.property('cod_uf'); + res.body.result[0].should.have.property('sigla_uf'); + res.body.result[0].should.have.property('tipo_preco'); + res.body.result[0].should.have.property('preco'); + done(); + }); + }); + + it('should return query cub wtih valid filter', (done) => { + chai.request(server) + .get('/api/v1/cub?filter=min_year:2017') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('sigla_uf'); + res.body.result[0].should.have.property('tipo_preco'); + res.body.result[0].should.have.property('preco'); done(); }); }); diff --git a/src/test/dailyChargeAmount.js b/src/test/dailyChargeAmount.js index 6cef69f46622bb13cc031234dc19279e5ca7ddb4..2c37d2749a1661b307cc37b64b643f8c76f2cb41 100644 --- a/src/test/dailyChargeAmount.js +++ b/src/test/dailyChargeAmount.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -38,7 +58,7 @@ describe('request daily charge amount', () => { }); }); - it('should list the year range', (done) => { + it('should list the years', (done) => { chai.request(server) .get('/api/v1/daily_charge_amount/years') .end((err, res) => { @@ -51,6 +71,47 @@ describe('request daily charge amount', () => { }); }); + it('should list the source', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/source') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('source'); + done(); + }); + }); + + it('should list the adm dependency', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/adm_dependency') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the adm dependency detailed', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/adm_dependency_detailed') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + it('should list the locations', (done) => { chai.request(server) .get('/api/v1/daily_charge_amount/location') @@ -65,6 +126,21 @@ describe('request daily charge amount', () => { }); }); + it('should list the rural locations', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/rural_location') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list education level short', (done) => { chai.request(server) .get('/api/v1/daily_charge_amount/education_level_short') @@ -81,7 +157,21 @@ describe('request daily charge amount', () => { it('should list education level mod', (done) => { chai.request(server) - .get('/api/v1/daily_charge_amount/education_level_mod') + .get('/api/v1/daily_charge_amount/average/education_level_mod') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the periods', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/period') .end((err, res) => { res.should.have.status(200); res.should.be.json; @@ -144,16 +234,53 @@ describe('request daily charge amount', () => { it('should return 400 with no filters', (done) => { chai.request(server) .get('/api/v1/daily_charge_amount/average?filter=education_level_mod:["3","4","5","6"]') + .end((err, res) => { + res.should.have.status(400); + res.should.be.json; + res.body.should.have.property('error'); + res.body.error.should.be.equal('Wrong/No filter specified'); + done(); + }); + }); + + it('should list the filter of integral time', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount?filter=integral_time:"1"') .end((err, res) => { res.should.have.status(200); res.should.be.json; res.body.should.have.property('result'); res.body.result.should.be.a('array'); res.body.result[0].should.have.property('year'); - res.body.result[0].should.have.property('education_level_mod_id'); - res.body.result[0].should.have.property('education_level_mod_name'); + res.body.result[0].should.have.property('education_level_short_id'); res.body.result[0].should.have.property('average_class_duration'); + res.body.result[0].should.have.property('median_class_duration'); + res.body.result[0].should.have.property('std_class_duration'); + res.body.result[0].should.have.property('fstqt_class_duration'); + res.body.result[0].should.have.property('thdqt_class_duration'); + res.body.result[0].should.have.property('education_level_short_name'); done(); }); }); + + it('should list daily charge amount for period 2', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount?filter=integral_time:"0",period:["2"]') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('education_level_short_id'); + res.body.result[0].should.have.property('average_class_duration'); + res.body.result[0].should.have.property('median_class_duration'); + res.body.result[0].should.have.property('std_class_duration'); + res.body.result[0].should.have.property('fstqt_class_duration'); + res.body.result[0].should.have.property('thdqt_class_duration'); + res.body.result[0].should.have.property('education_level_short_name'); + done(); + }); + }); + }); diff --git a/src/test/distributionFactor.js b/src/test/distributionFactor.js index e733fc5908cd0791490645abed718ffb5aa0dcfb..1233ad85dc265790167baec390aa870d9ba21a8a 100644 --- a/src/test/distributionFactor.js +++ b/src/test/distributionFactor.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/educationYears.js b/src/test/educationYears.js index 7a47b3079c827bf9e47d1392e08522ce74874402..7d21d8ef56eebfb0a7670db22fe7f8179698b60a 100644 --- a/src/test/educationYears.js +++ b/src/test/educationYears.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/employees.js b/src/test/employees.js new file mode 100644 index 0000000000000000000000000000000000000000..2eff61c43f4aef2db2adf562548f9fcfa4259146 --- /dev/null +++ b/src/test/employees.js @@ -0,0 +1,215 @@ +/* +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/>. +*/ + +process.env.NODE_ENV = 'test'; + +const chai = require('chai'); + +const dirtyChai = require('dirty-chai'); + +chai.use(dirtyChai); + +const chaiXml = require('chai-xml'); + +chai.use(chaiXml); + +const chaiHttp = require('chai-http'); + +const assert = chai.assert; + +const expect = chai.expect; + +const should = chai.should(); // actually call the function + +const libs = `${process.cwd()}/libs`; + +const server = require(`${libs}/app`); + +chai.use(chaiHttp); +describe('request employees', () => { + it('should list the employees default query', (done) => { + chai.request(server) + .get('/api/v1/employees') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('name'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('total_employees'); + res.body.result[0].should.have.property('total_teachers'); + done(); + }); + }); + + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/employees/year_range') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('start_year'); + res.body.result[0].should.have.property('end_year'); + done(); + }); + }); + + it('should list the years', (done) => { + chai.request(server) + .get('/api/v1/employees/years') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + done(); + }); + }); + + it('should list the source', (done) => { + chai.request(server) + .get('/api/v1/employees/source') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('source'); + done(); + }); + }); + + + it('should list the adm dependency', (done) => { + chai.request(server) + .get('/api/v1/employees/adm_dependency') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the adm dependency detailed', (done) => { + chai.request(server) + .get('/api/v1/employees/adm_dependency_detailed') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the location', (done) => { + chai.request(server) + .get('/api/v1/employees/location') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the rural location', (done) => { + chai.request(server) + .get('/api/v1/employees/rural_location') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list employees with valid filter', (done) => { + chai.request(server) + .get('/api/v1/employees?filter=min_year:2017') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('name'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('total_employees'); + res.body.result[0].should.have.property('total_teachers'); + done(); + }); + }); + + it('should list employees with school dim', (done) => { + chai.request(server) + .get('/api/v1/employees?dims=school&filter=state:11') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('name'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('total_employees'); + res.body.result[0].should.have.property('total_teachers'); + res.body.result[0].should.have.property('school_name'); + res.body.result[0].should.have.property('school_id'); + done(); + }); + }); + + + it('should list employees with school filter', (done) => { + chai.request(server) + .get('/api/v1/employees?filter=school:41126882') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('name'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('total_employees'); + res.body.result[0].should.have.property('total_teachers'); + done(); + }); + }); + +}); \ No newline at end of file diff --git a/src/test/enrollment.js b/src/test/enrollment.js index 997e5f70077c2d4b008845d33f452e0b7a9df679..9ec5cba3314877483999f29be2ef700eba35646f 100644 --- a/src/test/enrollment.js +++ b/src/test/enrollment.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -240,8 +260,8 @@ describe('request enrollments', () => { res.should.be.json; res.body.should.have.property('result'); res.body.result.should.be.a('array'); - res.body.result[0].should.have.property('name'); res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('year'); done(); }); }); @@ -254,8 +274,8 @@ describe('request enrollments', () => { res.should.be.json; res.body.should.have.property('result'); res.body.result.should.be.a('array'); - res.body.result[0].should.have.property('name'); res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('year'); done(); }); }); @@ -268,7 +288,7 @@ describe('request enrollments', () => { res.should.be.json; res.body.should.have.property('result'); res.body.result.should.be.a('array'); - res.body.result[0].should.have.property('name'); + res.body.result[0].should.have.property('year'); res.body.result[0].should.have.property('total'); done(); }); @@ -282,7 +302,7 @@ describe('request enrollments', () => { res.should.be.json; res.body.should.have.property('result'); res.body.result.should.be.a('array'); - res.body.result[0].should.have.property('name'); + res.body.result[0].should.have.property('year'); res.body.result[0].should.have.property('total'); done(); }); @@ -296,7 +316,7 @@ describe('request enrollments', () => { res.should.be.json; res.body.should.have.property('result'); res.body.result.should.be.a('array'); - res.body.result[0].should.have.property('name'); + res.body.result[0].should.have.property('year'); res.body.result[0].should.have.property('total'); done(); }); @@ -445,7 +465,7 @@ describe('request enrollments', () => { res.should.be.json; res.body.should.have.property('result'); res.body.result.should.be.a('array'); - res.body.result[0].should.have.property('ethnic_group_name'); + res.body.result[0].should.have.property('ethnic_group_id'); done(); }); }); @@ -475,4 +495,18 @@ describe('request enrollments', () => { done(); }); }); + + it('should list the age range', (done) => { + chai.request(server) + .get('/api/v1/enrollment/age_range_all') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); }); diff --git a/src/test/glossEnrollmentRatio.js b/src/test/glossEnrollmentRatio.js index 4043bf4a670b72864de89210b933eb992abd024c..39859b708082af41cdad78482b92a22aadcec21b 100644 --- a/src/test/glossEnrollmentRatio.js +++ b/src/test/glossEnrollmentRatio.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -24,6 +44,19 @@ const server = require(`${libs}/app`); chai.use(chaiHttp); describe('request gloss enrollment ratio', () => { + it('should list the source', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio/source') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('source'); + done(); + }); + }); + it('should list the year range', (done) => { chai.request(server) .get('/api/v1/gloss_enrollment_ratio/year_range') diff --git a/src/test/id2str.js b/src/test/id2str.js index 8d6f5457fac34c031612fd4cf8a9732a66690f67..5b0fd1150c9dc5b7071cbe6fd44eefb69cced72a 100644 --- a/src/test/id2str.js +++ b/src/test/id2str.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -120,17 +140,17 @@ describe('id2str middleware', () => { }); it('should transform a full age range id', (done) => { - expect(id2str.fullAgeRange(1)).to.deep.equal('0-3'); - expect(id2str.fullAgeRange(2)).to.deep.equal('4-5'); - expect(id2str.fullAgeRange(3)).to.deep.equal('6-10'); - expect(id2str.fullAgeRange(4)).to.deep.equal('11-14'); - expect(id2str.fullAgeRange(5)).to.deep.equal('15-17'); - expect(id2str.fullAgeRange(6)).to.deep.equal('18-24'); - expect(id2str.fullAgeRange(7)).to.deep.equal('25-29'); - expect(id2str.fullAgeRange(8)).to.deep.equal('30-40'); - expect(id2str.fullAgeRange(9)).to.deep.equal('41-50'); - expect(id2str.fullAgeRange(10)).to.deep.equal('51-64'); - expect(id2str.fullAgeRange(11)).to.deep.equal('64+'); + expect(id2str.fullAgeRange(1)).to.deep.equal('0 a 3 anos'); + expect(id2str.fullAgeRange(2)).to.deep.equal('4 a 5 anos'); + expect(id2str.fullAgeRange(3)).to.deep.equal('6 a 10 anos'); + expect(id2str.fullAgeRange(4)).to.deep.equal('11 a 14 anos'); + expect(id2str.fullAgeRange(5)).to.deep.equal('15 a 17 anos'); + expect(id2str.fullAgeRange(6)).to.deep.equal('18 a 24 anos'); + expect(id2str.fullAgeRange(7)).to.deep.equal('25 a 29 anos'); + expect(id2str.fullAgeRange(8)).to.deep.equal('30 a 40 anos'); + expect(id2str.fullAgeRange(9)).to.deep.equal('41 a 50 anos'); + expect(id2str.fullAgeRange(10)).to.deep.equal('51 a 64 anos'); + expect(id2str.fullAgeRange(11)).to.deep.equal('Mais de 64 anos'); expect(id2str.fullAgeRange(12)).to.deep.equal('Não declarada'); done(); diff --git a/src/test/idhm.js b/src/test/idhm.js index cea8893e9a4bbe92b6028615f3c8c841d9abdca1..82c06142102f0314a25badfcdae54e858ad363e7 100644 --- a/src/test/idhm.js +++ b/src/test/idhm.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/idhme.js b/src/test/idhme.js index dc338d38adbbb0ce8362a0a9f1e950671b49295b..767e788eb3404e483256200c9a2533e07cd3474d 100644 --- a/src/test/idhme.js +++ b/src/test/idhme.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/idhml.js b/src/test/idhml.js index 90312b0684f5b033d98e4f1b281a5e716a372cbd..c3bfd5dcb5c5f2f5f5e57735cf87d91c99af0a7c 100644 --- a/src/test/idhml.js +++ b/src/test/idhml.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/idhmr.js b/src/test/idhmr.js index eb06b37d0da0e2c5b03cf245906a4edb4e3c035e..4f7a308c0a36ccb65c45b41078de8d5d9c687bf0 100644 --- a/src/test/idhmr.js +++ b/src/test/idhmr.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/infrastructure.js b/src/test/infrastructure.js index 8714a73cd12a73ba81652ff13a9f3feacc661dc9..a600d8c3bc99d632f95ede395d16e94b1c89aa72 100644 --- a/src/test/infrastructure.js +++ b/src/test/infrastructure.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/liquidEnrollmentRatio.js b/src/test/liquidEnrollmentRatio.js index ec0489e905f1fd8360200adbdb603f4d888233a0..b61a8d8f144b383e41e1fbffe567db3080f7a93e 100644 --- a/src/test/liquidEnrollmentRatio.js +++ b/src/test/liquidEnrollmentRatio.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -24,6 +44,19 @@ const server = require(`${libs}/app`); chai.use(chaiHttp); describe('request liquid enrollment ratio', () => { + it('should list the source', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio/source') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('source'); + done(); + }); + }); + it('should list the year range', (done) => { chai.request(server) .get('/api/v1/liquid_enrollment_ratio/year_range') @@ -159,25 +192,9 @@ describe('request liquid enrollment ratio', () => { }); }); - it('should list the filter of education level basic', (done) => { - chai.request(server) - .get('/api/v1/liquid_enrollment_ratio?filter=education_level_basic:["1"]') - .end((err, res) => { - res.should.have.status(200); - res.should.be.json; - res.body.should.have.property('result'); - res.body.result.should.be.a('array'); - res.body.result[0].should.have.property('total'); - res.body.result[0].should.have.property('year'); - res.body.result[0].should.have.property('partial'); - res.body.result[0].should.have.property('denominator'); - done(); - }); - }); - - it('should list the filter of education level basic', (done) => { + it('should list liquid ratio with education level basic filter', (done) => { chai.request(server) - .get('/api/v1/liquid_enrollment_ratio?filter=education_level_basic:["1","2"]') + .get('/api/v1/liquid_enrollment_ratio?dims=education_level_basic&filter=education_level_basic:["1","2","4","5","6"]') .end((err, res) => { res.should.have.status(200); res.should.be.json; @@ -185,6 +202,9 @@ describe('request liquid enrollment ratio', () => { res.body.result.should.be.a('array'); res.body.result[0].should.have.property('total'); res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('age_range'); + res.body.result[0].should.have.property('education_level_basic_id'); + res.body.result[0].should.have.property('education_level_basic_name'); res.body.result[0].should.have.property('partial'); res.body.result[0].should.have.property('denominator'); done(); diff --git a/src/test/outOfSchool.js b/src/test/outOfSchool.js new file mode 100644 index 0000000000000000000000000000000000000000..bd265f39fc6d7f445648d5f562c2f178df44a66d --- /dev/null +++ b/src/test/outOfSchool.js @@ -0,0 +1,232 @@ +/* +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/>. +*/ + +process.env.NODE_ENV = 'test'; + +const chai = require('chai'); + +const dirtyChai = require('dirty-chai'); + +chai.use(dirtyChai); + +const chaiXml = require('chai-xml'); + +chai.use(chaiXml); + +const chaiHttp = require('chai-http'); + +const assert = chai.assert; + +const expect = chai.expect; + +const should = chai.should(); // actually call the function + +const libs = `${process.cwd()}/libs`; + +const server = require(`${libs}/app`); + +chai.use(chaiHttp); + +describe('request out of school', () => { + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/year_range') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('start_year'); + res.body.result[0].should.have.property('end_year'); + done(); + }); + }); + + it('should list the years', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/years') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + done(); + }); + }); + + it('should list the full age range', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/full_age_range') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the ethnic_group', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/ethnic_group') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the location', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/location') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the gender', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/gender') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the fifth household income', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/fifth_household_income') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the extremes household income', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/extremes_household_income') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list default query out of school', (done) => { + chai.request(server) + .get('/api/v1/out_of_school') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('year'); + done(); + }); + }); + + it('should list out of school with valid filters', (done) => { + chai.request(server) + .get('/api/v1/out_of_school?filter=max_year:2010') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('total'); + done(); + }); + }); + + it('should list the simcaq default query for out of school', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/simcaq') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('ano_censo'); + done(); + }); + }); + + it('should list simcaq out of school with valid filters', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/simcaq?filter=state:41') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('ano_censo'); + res.body.result[0].should.have.property('total'); + done(); + }); + }); + + it('should list simcaq out of school with valid dimensions', (done) => { + chai.request(server) + .get('/api/v1/out_of_school/simcaq?dims=state,pfe') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('pfe_id'); + res.body.result[0].should.have.property('pfe_name'); + res.body.result[0].should.have.property('ano_censo'); + res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('state_id'); + done(); + }); + }); + +}); \ No newline at end of file diff --git a/src/test/pibpercapita.js b/src/test/pibpercapita.js index e044b1c0ad631c7f236a9a67b9a50c2a111863f8..bd693bdcd1379902816845946d6b8394e739c2f3 100644 --- a/src/test/pibpercapita.js +++ b/src/test/pibpercapita.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/population.js b/src/test/population.js index 37be404fceaa84eb4e1b6d6a763096b2d557c675..785149464d492fe560ca0ba64ef8b499e82fcaa6 100644 --- a/src/test/population.js +++ b/src/test/population.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/query.js b/src/test/query.js index cad0102ff882c4eb2121cb99c804b3b8b84f0fa4..2bc37621a4fe7028ff8b2eb06fd34c7773c2901a 100644 --- a/src/test/query.js +++ b/src/test/query.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/rateSchool.js b/src/test/rateSchool.js index b029fa42e87e76aca2a65c95bd17400abcd4e40c..725dd5e61cdfbe377434fd447955a4749ae5fec5 100644 --- a/src/test/rateSchool.js +++ b/src/test/rateSchool.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/region.js b/src/test/region.js index daf45685c7a5298523afdf3e95446a715442429a..fc530c28e07a3ba60bc5402cbb8e9329001733d0 100644 --- a/src/test/region.js +++ b/src/test/region.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/response.js b/src/test/response.js index bdafc9d89eefa01966bc4171ebcbd373924479cf..c0c0855721cf69598cdd1f0306cace12531eb63a 100644 --- a/src/test/response.js +++ b/src/test/response.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/school.js b/src/test/school.js index 0ca4c78b47b93addb3aa5970588bfa1fc060d87f..7f05a6748c08e7c6a7eea711b74ecbe9d5057a66 100644 --- a/src/test/school.js +++ b/src/test/school.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -126,15 +146,4 @@ describe('request schools', () => { }); }); - it('should return 400 with no filters', (done) => { - chai.request(server) - .get('/api/v1/school') - .end((err, res) => { - res.should.have.status(400); - res.should.be.json; - res.body.should.have.property('error'); - res.body.error.should.be.equal('Wrong/No filter specified'); - done(); - }) - }); }); diff --git a/src/test/schoolCount.js b/src/test/schoolCount.js index 305045894b410b0c4215ce2d3d4d85aa065860c2..839415abbb8f0da1829573ddf9be65c71e56d299 100644 --- a/src/test/schoolCount.js +++ b/src/test/schoolCount.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/schoolInfrastructure.js b/src/test/schoolInfrastructure.js new file mode 100644 index 0000000000000000000000000000000000000000..f167fb1ff2aa7521a5018066e40616ff5b56f10b --- /dev/null +++ b/src/test/schoolInfrastructure.js @@ -0,0 +1,183 @@ +/* +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/>. +*/ + +process.env.NODE_ENV = 'test'; + +const chai = require('chai'); + +const dirtyChai = require('dirty-chai'); + +chai.use(dirtyChai); + +const chaiXml = require('chai-xml'); + +chai.use(chaiXml); + +const chaiHttp = require('chai-http'); + +const assert = chai.assert; + +const expect = chai.expect; + +const should = chai.should(); // actually call the function + +const libs = `${process.cwd()}/libs`; + +const server = require(`${libs}/app`); + +chai.use(chaiHttp); +describe('request school infrastructure', () => { + it('should list the default school insfrastructure query', (done) => { + chai.request(server) + .get('/api/v1/school_infrastructure') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('schools_in_school_buildings'); + res.body.result[0].should.have.property('urban_schools_in_school_buildings'); + res.body.result[0].should.have.property('country_schools_in_school_buildings'); + res.body.result[0].should.have.property('schools_not_in_school_buildings'); + res.body.result[0].should.have.property('libraries'); + res.body.result[0].should.have.property('libraries_reading_room'); + res.body.result[0].should.have.property('computer_lab'); + res.body.result[0].should.have.property('science_lab'); + res.body.result[0].should.have.property('kids_park'); + res.body.result[0].should.have.property('nursery'); + res.body.result[0].should.have.property('sports_court'); + res.body.result[0].should.have.property('sports_court_coverage'); + res.body.result[0].should.have.property('courtyard'); + res.body.result[0].should.have.property('courtyard_coverage'); + res.body.result[0].should.have.property('director_room'); + res.body.result[0].should.have.property('secretary'); + res.body.result[0].should.have.property('teacher_room'); + res.body.result[0].should.have.property('kitchen'); + res.body.result[0].should.have.property('storeroom'); + res.body.result[0].should.have.property('warehouse'); + res.body.result[0].should.have.property('internet'); + res.body.result[0].should.have.property('broadband_internet'); + res.body.result[0].should.have.property('inside_bathroom'); + res.body.result[0].should.have.property('inside_kids_bathroom'); + res.body.result[0].should.have.property('eletric_energy'); + res.body.result[0].should.have.property('water_supply'); + res.body.result[0].should.have.property('filtered_water'); + res.body.result[0].should.have.property('sewage_treatment'); + res.body.result[0].should.have.property('adapted_building'); + res.body.result[0].should.have.property('special_bathroom'); + done(); + }); + }); + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/school_infrastructure/year_range') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('start_year'); + res.body.result[0].should.have.property('end_year'); + done(); + }); + }); + + it('should list the years', (done) => { + chai.request(server) + .get('/api/v1/school_infrastructure/years') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + done(); + }); + }); + + it('should list the source', (done) => { + chai.request(server) + .get('/api/v1/school_infrastructure/source') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('source'); + done(); + }); + }); + + it('should list the location', (done) => { + chai.request(server) + .get('/api/v1/school_infrastructure/location') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the rural location', (done) => { + chai.request(server) + .get('/api/v1/school_infrastructure/rural_location') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the adm dependency', (done) => { + chai.request(server) + .get('/api/v1/school_infrastructure/adm_dependency') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the adm dependency detailed', (done) => { + chai.request(server) + .get('/api/v1/school_infrastructure/adm_dependency_detailed') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); +}); \ No newline at end of file diff --git a/src/test/simulation.js b/src/test/simulation.js index cd68d68048984fb7c23d22f20a64ce5fe3ab73f2..78633b10811bd5e6a4b3202f7d4df16563708619 100644 --- a/src/test/simulation.js +++ b/src/test/simulation.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -24,7 +44,6 @@ const server = require(`${libs}/app`); const mongoose = require('../libs/db/mongoose'); const Simulation = require('../libs/models/simulation'); -const User = require('../libs/models/user'); chai.use(chaiHttp); diff --git a/src/test/siope.js b/src/test/siope.js index ac13ead5ba92f76c6294f18fb324b90ed52396fd..4f88f314cb212ffe36164addae2afc073acf6c58 100644 --- a/src/test/siope.js +++ b/src/test/siope.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/state.js b/src/test/state.js index 5cea7a4f69d6169208367df71571ebefa541a13a..30a2548890a6aee921a6863f709c569514000d03 100644 --- a/src/test/state.js +++ b/src/test/state.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/teacher.js b/src/test/teacher.js index 30eddee8a20e6654c2db5f595c44e37f99868a5f..c6ed6508a6cc0ad176538aef1681fd7d2ef577d8 100644 --- a/src/test/teacher.js +++ b/src/test/teacher.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); diff --git a/src/test/transport.js b/src/test/transport.js index 78a4075b9dbc56a8fadcc3d55581f3338cbe613c..217d688f51abfadfcf3d1d14aee2dccfc9d0b4f6 100644 --- a/src/test/transport.js +++ b/src/test/transport.js @@ -1,3 +1,23 @@ +/* +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/>. +*/ + process.env.NODE_ENV = 'test'; const chai = require('chai'); @@ -37,7 +57,7 @@ describe('request transport', () => { }); }); - it('should list the year range', (done) => { + it('should list the years', (done) => { chai.request(server) .get('/api/v1/transport/years') .end((err, res) => { @@ -50,7 +70,7 @@ describe('request transport', () => { }); }); - it('should list the years', (done) => { + it('should list the year range', (done) => { chai.request(server) .get('/api/v1/transport/year_range') .end((err, res) => { @@ -147,9 +167,23 @@ describe('request transport', () => { }); }); - it('should list the education level basic', (done) => { + it('should list the education level mod', (done) => { + chai.request(server) + .get('/api/v1/transport/education_level_mod') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('id'); + res.body.result[0].should.have.property('name'); + done(); + }); + }); + + it('should list the service type', (done) => { chai.request(server) - .get('/api/v1/transport/education_level_basic') + .get('/api/v1/transport/service_type') .end((err, res) => { res.should.have.status(200); res.should.be.json; diff --git a/src/test/user.js b/src/test/user.js deleted file mode 100644 index 3109960bd98dfec2727c5ba7bf87b28148046ae7..0000000000000000000000000000000000000000 --- a/src/test/user.js +++ /dev/null @@ -1,37 +0,0 @@ -process.env.NODE_ENV = 'test'; - -const chai = require('chai'); - -const dirtyChai = require('dirty-chai'); - -chai.use(dirtyChai); - -const chaiXml = require('chai-xml'); - -chai.use(chaiXml); - -const chaiHttp = require('chai-http'); - -const assert = chai.assert; - -const expect = chai.expect; - -const should = chai.should(); // actually call the function - -const libs = `${process.cwd()}/libs`; - -const server = require(`${libs}/app`); - -const mongoose = require('../libs/db/mongoose'); -//const Simulation = require('../libs/models/simulation'); -const User = require('../libs/models/user'); - -chai.use(chaiHttp); - -describe('Saves a user', () => { - // beforeEach(() => { - // User.remove({}, (err) => { - // console.log('Test collection purged') - // }); - // }); -});