diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d3dbb013cec3a98716cbe86e5644659c987e7c8..ad2d90ae546c79c8e7cbba04bfc4125f841bb2dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 2019-07-03 +### Changed +- Remove mongoose dependency so it can be used in SMPPIR + ## 1.9.0 - 2018-11-24 ## Changed - Fix school infrastructure results when partial or needed schools query return empty diff --git a/config.json.example b/config.json.example index e3d309200d160d47b17dbe57f23dee11cdbccd23..bf1d212cb45a55ad2c1a23f6fb05df8d2fced569 100644 --- a/config.json.example +++ b/config.json.example @@ -16,12 +16,6 @@ "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" - }, "default": { "api": { "version" : "v1" @@ -61,13 +55,6 @@ "url": "http://simcaqdb3.c3sl.ufpr.br:3000", "download": "https://simcaqdev.c3sl.ufpr.br/download/" }, - "mongodb" : { - "uri": "mongodb://localhost/test_users", - "secret": "SimCAQC3SL" - }, - "monq": { - "uri": "mongodb://localhost/test_monq" - }, "default": { "api": { "version" : "v1" @@ -107,13 +94,6 @@ "url": "http://simcaqdb3.c3sl.ufpr.br:7000", "download": "https://simcaq.c3sl.ufpr.br/download/" }, - "mongodb" : { - "uri": "mongodb://localhost/users", - "secret": "SimCAQC3SL" - }, - "monq": { - "uri": "mongodb://localhost/monq" - }, "default": { "api": { "version" : "v1" diff --git a/package.json b/package.json index bb9438bfbcf40e8adfddb2dd27896bbe557a4dc5..f603817a79d175c397ddb03a822a8537dd0d30a2 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,6 @@ "method-override": "^2.3.10", "mocha": "^3.5.3", "monetdb-pool": "0.0.8", - "mongoose": "^4.13.17", "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 5a1097988e77bf77b555095c51a5a9ef350a7aa3..496b619b2762364bb2058eb4c846376e56f7bc80 100644 --- a/src/libs/app.js +++ b/src/libs/app.js @@ -36,13 +36,6 @@ 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' })); @@ -78,8 +71,6 @@ app.use((req, res, next) => { 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/db/mongoose.js b/src/libs/db/mongoose.js deleted file mode 100644 index e1927339fa242dfee3998f5fe04d96517d399bb9..0000000000000000000000000000000000000000 --- a/src/libs/db/mongoose.js +++ /dev/null @@ -1,41 +0,0 @@ -/* -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`); - -const log = require(`${libs}/log`)(module); - -const mongoose = require('mongoose'); - -mongoose.Promise = global.Promise; - -module.exports = () => { - // Get mongodb URI (ip and port) in config file - const mongoUri = process.env.MONGO_URI || config.mongodb.uri; - log.info(`Connecting to MongoDB on URI ${mongoUri}`); - // Connection singleton - const db = mongoose.connect(mongoUri); - - mongoose.connection.once('open', () => { log.info("MongoDB connected"); }); - - return db; -}; diff --git a/src/libs/middlewares/downloadDatabase.js b/src/libs/middlewares/downloadDatabase.js deleted file mode 100644 index ee1529228d1293939e260ea0d047260556f0ef63..0000000000000000000000000000000000000000 --- a/src/libs/middlewares/downloadDatabase.js +++ /dev/null @@ -1,108 +0,0 @@ -/* -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 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/oauth2.js b/src/libs/middlewares/oauth2.js deleted file mode 100644 index e7f7b446ed037cdb0c4843084bf9626556c19c97..0000000000000000000000000000000000000000 --- a/src/libs/middlewares/oauth2.js +++ /dev/null @@ -1,141 +0,0 @@ -/* -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 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 ea4fd95c1945786946ea5e82128d7bfbb37850c6..0000000000000000000000000000000000000000 --- a/src/libs/middlewares/passport.js +++ /dev/null @@ -1,87 +0,0 @@ -/* -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 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/models/accessToken.js b/src/libs/models/accessToken.js deleted file mode 100644 index b9c2a60ac4ce29ce45a944c2c23aa189db02cf72..0000000000000000000000000000000000000000 --- a/src/libs/models/accessToken.js +++ /dev/null @@ -1,49 +0,0 @@ -/* -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 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 2ddae28075d6d2d35eba0798ad425b00580ebd12..0000000000000000000000000000000000000000 --- a/src/libs/models/client.js +++ /dev/null @@ -1,37 +0,0 @@ -/* -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 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 21fdf683c38dfcce176bd44b5ae456e6b0e80a3c..0000000000000000000000000000000000000000 --- a/src/libs/models/download.js +++ /dev/null @@ -1,73 +0,0 @@ -/* -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 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 deleted file mode 100644 index d8c71c6df182297dbddbb5f4a4a12eb0cf951cb2..0000000000000000000000000000000000000000 --- a/src/libs/models/pqr.js +++ /dev/null @@ -1,36 +0,0 @@ -/* -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 PQRSchema = new Schema({ - content: { - type: String, - required: true, - } -}); - -module.exports = mongoose.model('PQR', PQRSchema); diff --git a/src/libs/models/refreshToken.js b/src/libs/models/refreshToken.js deleted file mode 100644 index 3a37ae96d69c08b698ebd6ab924ddb602d07722e..0000000000000000000000000000000000000000 --- a/src/libs/models/refreshToken.js +++ /dev/null @@ -1,50 +0,0 @@ -/* -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 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 d983436b9181a7f55aafd5eefcfc3f028038a345..0000000000000000000000000000000000000000 --- a/src/libs/models/resetToken.js +++ /dev/null @@ -1,66 +0,0 @@ -/* -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 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 deleted file mode 100644 index a4a6cc3cd5b2c26aa28f68953b82d85243cd0144..0000000000000000000000000000000000000000 --- a/src/libs/models/simulation.js +++ /dev/null @@ -1,54 +0,0 @@ -/* -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, - required: true, - ref: 'User' - }, - content: { - type: String, - required: true, - }, - name: { - type: String - }, - createdAt: { - type: Date, - required: true, - default: Date.now - }, - updatedAt: { - type: Date, - required: true, - default: Date.now - } -}); - -module.exports = mongoose.model('Simulation', SimulationSchema); diff --git a/src/libs/models/user.js b/src/libs/models/user.js deleted file mode 100644 index 7dc642e3cd6c81301677f89f27b8852751596cbc..0000000000000000000000000000000000000000 --- a/src/libs/models/user.js +++ /dev/null @@ -1,139 +0,0 @@ -/* -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 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 1047e4d0795165041b0b06d2c86c2884ed3f7481..0000000000000000000000000000000000000000 --- a/src/libs/models/verificationToken.js +++ /dev/null @@ -1,61 +0,0 @@ -/* -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 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 5622f9d23f676ea9388ce7dc16b292ca7417cd40..fd1bae834c25b56b570ed709cf30a70a6add8a43 100644 --- a/src/libs/routes/api.js +++ b/src/libs/routes/api.js @@ -26,86 +26,6 @@ const libs = `${process.cwd()}/libs`; const config = require(`${libs}/config`); -const classes = require('./class'); - -const enrollment = require('./enrollment'); - -const state = require('./state'); - -const region = require('./region'); - -const city = require('./city'); - -const school = require('./school'); - -const simulation = require('./simulation'); - -const user = require('./user'); - -const classroom = require('./classroom'); - -const teacher = require('./teacher'); - -const idhme = require('./idhme'); - -const pibpercapita = require('./pibpercapita') - -const population = require('./population') - -const rateSchool = require('./rateSchool') - -const glossEnrollmentRatio = require('./glossEnrollmentRatio') - -const liquidEnrollmentRatio = require('./liquidEnrollmentRatio') - -const idhm = require('./idhm'); - -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`); - -const distributionFactor = require(`${libs}/routes/distributionFactor`); - -const siope = require(`${libs}/routes/siope`); - -const verifyTeacher = require(`${libs}/routes/portalMec`); - -const outOfSchool = require(`${libs}/routes/outOfSchool`); - -const classroomCount = require(`${libs}/routes/classroomCount`); - -const transport = require(`./transport`); - -const auxiliar = require(`${libs}/routes/auxiliar`); - -const dailyChargeAmount = require(`${libs}/routes/dailyChargeAmount`); - -const cub = require(`${libs}/routes/cub`); - -const classCount = require(`${libs}/routes/classCount`); - -const portalMecInep = require(`${libs}/routes/portalMecInep`); - -const enrollmentProjection = require(`${libs}/routes/enrollmentProjection`); - -const employees = require(`${libs}/routes/employees`); - -const financial = require(`${libs}/routes/financial`); - // SMPPIR Routes @@ -143,10 +63,6 @@ const course = require(`${libs}/routes/SMPPIR/course`); const ibge_census = require(`${libs}/routes/SMPPIR/ibge_census`); -// const cad_unico = require(`${libs}/routes/SMPPIR/cad_unico`); - -// const cad_unico_count = require(`${libs}/routes/SMPPIR/cad_unico_count`); - const ibge_code = require(`${libs}/routes/SMPPIR/ibge_code`); const vacancies = require(`${libs}/routes/SMPPIR/vacancy`); @@ -172,56 +88,13 @@ const ciganos_culture = require(`${libs}/routes/SMPPIR/ciganos_culture`) const ciganos_sustentability = require(`${libs}/routes/SMPPIR/ciganos_sustentability`) -//const eixo_2_count = require(`${libs}/routes/SMPPIR/eixo_2_count`) - api.get('/', (req, res) => { res.json({ msg: 'SMPPIR API is running' }); }); // mount API routes -api.use('/user', user); -api.use('/simulation', simulation); -api.use('/class', classes); -api.use('/enrollment', enrollment); -api.use('/state', state); -api.use('/region', region); -api.use('/city', city); -api.use('/school', school); -api.use('/classroom', classroom); -api.use('/teacher', teacher); -api.use('/idhmr', idhmr); -api.use('/idhm', idhm); -api.use('/idhme', idhme); -api.use('/pibpercapita', pibpercapita); -api.use('/population', population); -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); -api.use('/siope', siope); -api.use('/out_of_school', outOfSchool); -api.use('/classroom_count', classroomCount); -api.use('/daily_charge_amount', dailyChargeAmount); -api.use('/transport', transport); -api.use('/cub', cub); -api.use('/auxiliar', auxiliar); -api.use('/verify_teacher', verifyTeacher); -api.use('/class_count', classCount); -api.use('/portal_mec_inep', portalMecInep); -api.use('/enrollment_projection', enrollmentProjection); -api.use('/employees', employees); -api.use('/financial', financial); - - // SMPPIR Routes + api.use('/evader', evader); api.use('/graduate', graduate); api.use('/prouni', prouni); @@ -239,8 +112,6 @@ api.use('/course', course); api.use('/courseprouni', coursePROUNI); api.use('/coursefies', courseFIES); api.use('/ibge_census', ibge_census); -// api.use('/cad_unico', cad_unico); -// api.use('/cad_unico_count', cad_unico_count); api.use('/ibge_code', ibge_code); api.use('/vacancy', vacancies); api.use('/eixo_2', eixo_2); @@ -255,6 +126,4 @@ api.use('/ciganos_culture', ciganos_culture); api.use('/ciganos_sustentability', ciganos_sustentability); -//api.use('/eixo_2_count', eixo_2_count) - -module.exports = api; +module.exports = api; \ No newline at end of file diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js deleted file mode 100644 index 74e05c77be3b38ca81619635a19bb37b6aa9db9e..0000000000000000000000000000000000000000 --- a/src/libs/routes/auxiliar.js +++ /dev/null @@ -1,369 +0,0 @@ -/* -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(); - -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 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; - -let rqf = new ReqQueryFields(); - -auxiliarApp.use(cache('15 day')); - -auxiliarApp.get('/year_range', (req, res, next) => { - req.sql.from('docente') - .field('MIN(docente.ano_censo)', 'start_year') - .field('MAX(docente.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -auxiliarApp.get('/years', (req, res, next) => { - req.sql.from('docente'). - field('DISTINCT docente.ano_censo', 'year'); - next(); -}, query, response('years')); - -auxiliarApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'docente\''); - next(); -}, query, response('source')) - -auxiliarApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -auxiliarApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -auxiliarApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -auxiliarApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -auxiliarApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 11; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -auxiliarApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -auxiliarApp.get('/ethnic_group', (req, res, next) => { - req.result = []; - for(let i = 0; i <=5; ++i) { - req.result.push({ - id: i, - name: id2str.ethnicGroup(i) - }); - } - next(); -}, response('ethnic_group')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: 'docente', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'docente', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'education_level_mod', - table: 'docente', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_regiao_id', - foreignTable: 'docente' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_estado_id', - foreignTable: 'docente' - } -}).addValue({ - name: 'rural_location', - table: 'docente', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_municipio_id', - foreignTable: 'docente' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_municipio_id', - foreignTable: 'docente' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'docente' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'docente' - } -}, 'filter').addValue({ - name: 'location', - table: 'docente', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'min_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'gender', - table: 'docente', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'ethnic_group', - table: 'docente', - tableField: 'cor_raca', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca' - } -}); - -// LDE -auxiliarApp.get('/', rqf.parse(), (req, res, next) => { - req.sql.field('COUNT(DISTINCT docente.id)', 'total') - .field("'Brasil'", 'name') - .field('docente.ano_censo', 'year') - .from('docente') - .group('docente.ano_censo') - .order('docente.ano_censo') - .where('(docente.tipo_turma_id <= 3 AND docente.tipo_docente = 2)'); - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('auxiliar')); - -// SimCAQ -auxiliarApp.get('/count', rqf.parse(), (req, res, next) => { - req.sql.field('COUNT(DISTINCT docente.id)', 'total') - .field("'Brasil'", 'name') - .field('docente.ano_censo', 'year') - .from('docente') - .group('docente.ano_censo') - .order('docente.ano_censo') - .where('(docente.tipo_turma_id <= 3 AND docente.dependencia_adm_id <= 3 AND docente.tipo_docente = 2)'); - 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 deleted file mode 100644 index 9342f64c92dbd1d1f1b3187606f7cd81fa00aa5d..0000000000000000000000000000000000000000 --- a/src/libs/routes/city.js +++ /dev/null @@ -1,96 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -cityApp.use(cache('15 day')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addValue({ - name: 'id', - table: 'municipio', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'municipio' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'municipio' - } -}).addField({ - name: 'search', - field: false, - where: true -}).addValueToField({ - name: 'name', - table: 'municipio', - tableField: 'nome', - where: { - relation: 'LIKE', - type: 'string', - field: 'nome' - } -}, 'search');; - -// Return all cities -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'); - next(); -}, query, response('city')); - -module.exports = cityApp; diff --git a/src/libs/routes/class.js b/src/libs/routes/class.js deleted file mode 100644 index 9819a23ba4483c6b1c72c3a3a32f2c75da97f245..0000000000000000000000000000000000000000 --- a/src/libs/routes/class.js +++ /dev/null @@ -1,394 +0,0 @@ -/* -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(); - -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 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(); - -classApp.use(cache('15 day')); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -classApp.get('/year_range', (req, res, next) => { - req.sql.from('turma') - .field('MIN(turma.ano_censo)', 'start_year') - .field('MAX(turma.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -classApp.get('/years', (req, res, next) => { - req.sql.from('turma') - .field('DISTINCT turma.ano_censo', 'year'); - next(); -}, query, response('years')); - -classApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'turma\''); - next(); -}, query, response('source')); - -classApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -classApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -// Returns all adm dependencies -classApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -classApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -// Returns all periods avaible -classApp.get('/period', (req, res, next) => { - req.result = []; - for(let i=1; i <= 3; ++i) { - req.result.push({ - id: i, - name: id2str.period(i) - }); - } - req.result.push({ - id: 99, - name: id2str.period(99) - }); - next(); -}, response('period')); - -// Returns integral-time avaible -classApp.get('/integral_time', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Disponível'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('integral_time')); - -// Returns all educational levels avaible -classApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <=11; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -classApp.get('/education_level_short', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Ensino Fundamental - anos iniciais'}, - {id: 4, name: 'Ensino Fundamental - anos finais'}, - {id: 5, name: 'Ensino Médio'}, - {id: 6, name: 'EJA'}, - {id: 7, name: 'EE exclusiva'} - ]; - next(); -}, response('education_level_short')); - -rqfCount.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}, 'filter').addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'min_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name:'adm_dependency', - table: 'turma', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'location', - table: 'turma', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'turma', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name:'education_level_mod', - table: 'turma', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'education_level_short', - table: 'turma', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'turma', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name:'period', - table: 'turma', - tableField: 'turma_turno_id', - resultField: 'period_id', - where: { - relation: '=', - type: 'integer', - field: 'turma_turno_id' - } -}).addValue({ - name:'integral_time', - table: 'turma', - tableField: 'tempo_integral', - resultField: 'integral_time_id', - where: { - relation: '=', - type: 'boolean', - field: 'tempo_integral' - } -}).addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'turma' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'turma' - } -}, 'filter'); - - -classApp.get('/', rqfCount.parse(), rqfCount.build(), (req, res, next) => { - req.sql.field('COUNT(turma.id)', 'total') - .field("'Brasil'", 'name') - .field('turma.ano_censo', 'year') - .from('turma') - .group('turma.ano_censo') - .order('turma.ano_censo') - .where('turma.tipo_turma_id = 0 OR turma.tipo_turma_id = 1 OR turma.tipo_turma_id = 2 OR turma.tipo_turma_id = 3'); - 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 deleted file mode 100644 index c7fa1d036eaa9f1b66988c52a14c1a8645f41ed1..0000000000000000000000000000000000000000 --- a/src/libs/routes/classCount.js +++ /dev/null @@ -1,434 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const 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(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}, 'filter') -.addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'min_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name:'adm_dependency', - table: 'turma', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'location', - table: 'turma', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'turma', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name:'education_level_mod', - table: 'turma', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name:'education_level_short', - table: 'turma', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'turma', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'turma' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'turma' - } -}, 'filter'); - -classCountApp.get('/year_range', (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -classCountApp.get('/years', (req, res, next) => { - req.sql.from('escola') - .field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -classCountApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -classCountApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -classCountApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -classCountApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -classCountApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 10; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -classCountApp.get('/education_level_short', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 7; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelShort(i) - }); - } - req.result.push({ - id: 99, - name: id2str.educationLevelShort(99) - }); - next(); -}, response('education_level_short')); - -classCountApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'turma\''); - next(); -}, query, response('source')); - -// Se a dimensão obrigatória do LDE (etapa de ensino) possui alguma etapa sem nenhum valor, então é criado um objeto -// com média 0.0 e é inserido no resultado. Usada para não quebrar a sequência de etapas na tabela do LDE. -function addNullFields(result) { - const firstYear = result[0].year; - var obj = result.filter(res => res.year == firstYear); - var prevFirstDimId = obj[0]; - obj.forEach((d) => { - if((d["education_level_mod_id"] > prevFirstDimId["education_level_mod_id"]) && (prevFirstDimId["education_level_mod_id"] != 10) && - (d["education_level_mod_id"] != prevFirstDimId["education_level_mod_id"] + 1)) { - let newObj = {}; - Object.keys(prevFirstDimId).forEach((key) => { - newObj[key] = prevFirstDimId[key]; - }); - newObj.education_level_mod_id = d["education_level_mod_id"] - 1; - newObj.education_level_mod_name = id2str.educationLevelMod(d["education_level_mod_id"] - 1); - newObj.average = 0.0; - result.splice(result.indexOf(prevFirstDimId) + 1, 0, newObj); - } - prevFirstDimId = d; - }); -} - -// SimCAQ -classCountApp.get('/count', rqf.parse(), (req, res, next) => { - req.sql.field("'Brasil'", 'name') - .field('turma.ano_censo', 'year') - .field('AVG(turma.num_matricula)', 'average') - .field('MEDIAN(turma.num_matricula)', 'median') - .field('STDDEV_POP(turma.num_matricula)', 'stddev') - .field('QUANTILE(turma.num_matricula, 0.25)', 'first_qt') - .field('QUANTILE(turma.num_matricula, 0.75)', 'third_qt') - .from('turma') - .group('turma.ano_censo') - .order('turma.ano_censo') - .where('turma.tipo_turma_id = 0 AND turma.dependencia_adm_id <= 3 AND ((turma.etapa_resumida >= 1 AND turma.etapa_resumida <= 7) OR turma.etapa_resumida = 99)'); - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('class_count')); - -// LDE -classCountApp.get('/', rqf.parse(), rqf.build(), (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') - .field('turma.ano_censo', 'year') - .field('AVG(turma.num_matricula)', 'average') - .field('MEDIAN(turma.num_matricula)', 'median') - .field('STDDEV_POP(turma.num_matricula)', 'stddev') - .field('QUANTILE(turma.num_matricula, 0.25)', 'first_qt') - .field('QUANTILE(turma.num_matricula, 0.75)', 'third_qt') - .from('turma') - .group('turma.ano_censo') - .order('turma.ano_censo') - .where('turma.tipo_turma_id = 0 AND turma.etapas_mod_ensino_segmento_id >= 1 AND turma.etapas_mod_ensino_segmento_id <= 10'); - next(); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.partial = []; - - // Caso tenha apenas uma dimensão, o indicador possuirá uma linha de total - if((req.dims) && (req.dims.size == 1)) { - req.partial = req.result; - - // A linha de total deverá conter o valor total do ano que está no banco de dados, então usa o mesmo filtro de anos da consulta anterior - let yearFilter = {}; - if("min_year" in req.filter) - yearFilter.min_year = req.filter.min_year; - if("max_year" in req.filter) - yearFilter.max_year = req.filter.max_year; - - // Faz a consulta sem dimensões, do total do(s) ano(s) escolhido(s) - req.resetSql(); - req.dims = {}; - req.filter = yearFilter; - req.sql.field("'Brasil'", 'name') - .field('turma.ano_censo', 'year') - .field('AVG(turma.num_matricula)', 'average') - .field('MEDIAN(turma.num_matricula)', 'median') - .field('STDDEV_POP(turma.num_matricula)', 'stddev') - .field('QUANTILE(turma.num_matricula, 0.25)', 'first_qt') - .field('QUANTILE(turma.num_matricula, 0.75)', 'third_qt') - .from('turma') - .group('turma.ano_censo') - .order('turma.ano_censo') - .where('turma.tipo_turma_id = 0 AND turma.etapas_mod_ensino_segmento_id >= 1 AND turma.etapas_mod_ensino_segmento_id <= 10'); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), (req, res, next) => { - // Se tem apenas uma dimensão - if(req.partial.length > 0) { - const yearClassCount = req.result; - req.result = req.partial; - - // Como a linha de total deve aparecer em um caso específico, ela é adicionada junto com a dimensão obrigatória - yearClassCount.forEach((result) => { - let obj = {}; - obj = result; - obj.education_level_mod_name = "Total"; - req.result.push(obj); - }) - } - // Caso tenha mais de uma dimensão, retorna a consulta só pelas dimensões, sem linha de total - else - addNullFields(req.result); - - next(); -}, response('class_count')); - -module.exports = classCountApp; diff --git a/src/libs/routes/classroom.js b/src/libs/routes/classroom.js deleted file mode 100644 index a445e9412d7edc8337186e4cc6b448eaaded7961..0000000000000000000000000000000000000000 --- a/src/libs/routes/classroom.js +++ /dev/null @@ -1,253 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const 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(); - -let rqfCount = new ReqQueryFields(); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -classroomApp.get('/year_range', (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -classroomApp.get('/years', (req, res, next) => { - req.sql.from('escola') - .field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -classroomApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'escola\''); - next(); -}, query, response('source')); - -classroomApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -classroomApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -classroomApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}, 'filter').addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'filter').addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'min_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'adm_dependency', - table: 'escola', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'escola', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'location', - table: 'escola', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}); - -classroomApp.get('/', cache('15 day'), rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.from('escola') - .field('SUM(escola.num_salas)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .order('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1 AND escola.local_func_predio_escolar = 1'); - next(); -}, query, addMissing(rqf), id2str.transform(), response('classroom')); - -module.exports = classroomApp; diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js deleted file mode 100644 index 7489ddcbef1ee1422d77f10d4c95555dacb0e4cf..0000000000000000000000000000000000000000 --- a/src/libs/routes/classroomCount.js +++ /dev/null @@ -1,653 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const 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(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'filter').addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}, 'filter').addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'id', - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}, 'dims').addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'school_year', - table: '@', - tableField: 'serie_ano_id', - resultField: 'school_year_id', - where: { - relation: '=', - type: 'integer', - field: 'serie_ano_id' - } -}).addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'period', - table: '@', - tableField: 'turma_turno_id', - resultField: 'period_id', - where: { - relation: '=', - type: 'integer', - field: 'turma_turno_id' - } -}); - -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; - - if(classSize == null || integralTime == null) { - res.statusCode = 400; - return res.json({err: {message: "There was an error processing class_size or integral_time. Check your JSON sintax and be sure you're sending both paramenters."}}); - } - req.classSize = classSize; - req.integralTime = integralTime; - - 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') - .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'); - - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.enrollment = req.result; - - // 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); - - 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; - - req.educationSchoolYear[i] = { - id: educationLevelId, - name: id2str.educationLevelShort(educationLevelId), - numberStudentClass, - offerGoal - }; - } - } - - req.resetSql(); - next(); -}, rqf.parse(), (req, res, next) => { - - req.dims.state = true; - req.dims.city = true; - req.dims.location = true; - - req.sql.field('SUM(escola.num_salas)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .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.dependencia_adm_id < 4'); - - 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; - let classroom = []; - - // 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]; - } - - // 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; - } - - 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 { - ++j; - } - 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); - - // 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.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); - } 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 = 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; - } - 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; - } - 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; - } - } - - 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; - - // 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); - - // Turmas diurnas (matrículas diurnas - matrículas integrais) - educationLevel.enrollment.day_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (1 - currentOfferGoal/100)) / currentNumberStudentClass); - - // 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); - - 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); - - // 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); - - currentSchoolYear.day_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (1 - currentOfferGoal/100)) / currentNumberStudentClass); - - 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); - - if(currentSchoolYear.night_classes > (currentSchoolYear.day_classes/2)) currentSchoolYear.total_classrooms_needed += (currentSchoolYear.night_classes - (currentSchoolYear.day_classes/2)); - - currentSchoolYear.total_classrooms_needed = Math.ceil(currentSchoolYear.total_classrooms_needed); - - 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); - } - - 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; - - if(location.total_classroom_be_built < 0) location.total_classroom_be_built = 0; - - ++i; - } - - // Agregar por estado e brasil - let reduction = null; - if(req.dims.state || !req.dims.city) { // Se um dos dois acontecer, sabemos que devemos agregar - let i = 0; - reduction = []; - let reductionSet = new Set(); - while (i < result.length) { - let city = result[i]; - let obj = { - year: city.year, - name: city.name - } - - if(req.dims.state) { - obj.state_id = city.state_id; - obj.state_name = city.state_name; - } - - obj.locations = []; - - let hash = '' + city.year; - if(req.dims.state) hash += '' + city.state_id; - - let currentObj = null; - if(!reductionSet.has(hash)) { - reductionSet.add(hash); - reduction.push(obj); - currentObj = obj; - } else { // Está ordenado, podemos pegar o último - currentObj = reduction[reduction.length - 1]; - } - - // Fazer "merge" do array locations da cidade com o da agregação - 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]; - } else { - let j = 0; - let k = 0; - let cityLocation = null; - let currentLocation = null; - while((typeof cityLocation !== 'undefined') && (typeof currentLocation !== 'undefined')) { - cityLocation = city.locations[j]; - currentLocation = currentObj.locations[k]; - if(cityLocation.location_id < currentLocation.location_id) { - ++j; - cityLocation = city.locations[j]; - continue; - } 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; - } - - // Faz "merge" do array education_level - // Se a localidade atual não tem o vetor - if(currentLocation.education_level.length == 0) { - currentLocation.education_level = [...cityLocation.education_level]; - } else { // Caso já tenha, atualiza os valores - let l = 0; - while(l < cityLocation.education_level.length) { - let cityEducation = cityLocation.education_level[l]; - let m = 0; - let currentEducation = currentLocation.education_level[m]; - while(m < currentLocation.education_level.length && cityEducation.education_level_short_id > currentEducation.education_level_short_id) { - ++m; - currentEducation = currentLocation.education_level[m]; - } - if(m >= currentLocation.education_level.length) --m; - currentEducation = currentLocation.education_level[m]; - - if(currentEducation.education_level_short_id == cityEducation.education_level_short_id) { - currentEducation.enrollment.total_enrollment_day += cityEducation.enrollment.total_enrollment_day; - currentEducation.enrollment.total_enrollment_night += cityEducation.enrollment.total_enrollment_night; - currentEducation.enrollment.full_period_classes += cityEducation.enrollment.full_period_classes; - currentEducation.enrollment.day_classes += cityEducation.enrollment.day_classes; - currentEducation.enrollment.night_classes += cityEducation.enrollment.night_classes; - currentEducation.enrollment.total_classrooms_needed += cityEducation.enrollment.total_classrooms_needed; - // Insere as séries escolares, se existirem - if((typeof cityEducation.classes_school_year !== 'undefined') && (typeof currentEducation.classes_school_year !== 'undefined')) { - let n = 0; - let o = 0; - let currentClass = currentEducation.classes_school_year[n]; - let cityClass = cityEducation.classes_school_year[o]; - while((typeof cityClass !== 'undefined') && (typeof currentClass !== 'undefined')) { - currentClass = currentEducation.classes_school_year[n]; - cityClass = cityEducation.classes_school_year[o]; - - // Se a série escolar é menor que a atual, ela não está no vetor, pois o vetor está ordenado e tem range limitado - if(cityClass.school_year_id < currentClass.school_year_id) { - currentEducation.classes_school_year.splice(n, 0, cityClass); - currentClass = currentEducation.classes_school_year[n]; - cityClass = cityEducation.classes_school_year[++o]; - continue; - } else if(cityClass.school_year_id > currentClass.school_year_id) { - currentClass = currentEducation.classes_school_year[++n]; - // Se o ano escolar da cidade é maior que do objeto atual E o vetor de ano escolar do objeto atual - // acaba, então este ano escolar falta no objeto atual, pois os anos escolares estão ordenados - if((typeof currentClass == 'undefined') && (typeof cityClass !== 'undefined')) { - currentEducation.classes_school_year[n] = cityClass; - currentClass = currentEducation.classes_school_year[n]; - } - continue; - } - - currentClass.total_enrollment_day += cityClass.total_enrollment_day; - currentClass.total_enrollment_night += cityClass.total_enrollment_night; - currentClass.full_period_classes += cityClass.full_period_classes; - currentClass.day_classes += cityClass.day_classes; - currentClass.night_classes += cityClass.night_classes; - currentClass.total_classrooms_needed += cityClass.total_classrooms_needed; - - cityClass = cityEducation.classes_school_year[++o]; - } - - } - } else { - if(currentEducation.education_level_short_id < cityEducation.education_level_short_id) { - currentLocation.education_level.splice(++m, 0, cityEducation); - } else { - currentLocation.education_level.splice(m, 0, cityEducation); - } - } - ++l; - } - } - - currentLocation.total_classroom += cityLocation.total_classroom; - currentLocation.total_classroom_be_built += cityLocation.total_classroom_be_built; - - ++j; - cityLocation = city.locations[j]; - } - } - ++i; - } - } - - req.result = reduction || result; - - next(); -}, response('classroom_count')); - -module.exports = classroomCountApp; diff --git a/src/libs/routes/cub.js b/src/libs/routes/cub.js deleted file mode 100644 index b6bb034cb579e9df82ac6180220aa463bc8b8432..0000000000000000000000000000000000000000 --- a/src/libs/routes/cub.js +++ /dev/null @@ -1,198 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const request = require(`request`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); -let rqfCount = new ReqQueryFields(); - -cubApp.get('/year_range', (req, res, next) => { - req.sql.from('cub') - .field('MIN(cub.ano_censo)', 'start_year') - .field('MAX(cub.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -cubApp.get('/years', (req, res, next) => { - req.sql.from('cub') - .field('DISTINCT cub.ano_censo', 'year'); - next(); -}, query, response('years')); - -cubApp.get('/months', (req, res, next) => { - req.sql.from('cub') - .field('DISTINCT cub.mes_censo', 'month'); - next(); -}, query, response('months')); - -cubApp.get('/years_months', (req, res, next) => { - req.sql.from('cub') - .field('DISTINCT cub.ano_censo AS "year", cub.mes_censo AS "month"'); - next(); -}, query, response('years_months')); - -cubApp.get('/price_type', (req, res, next) => { - req.sql.from('cub') - .field('DISTINCT cub.tipo_preco', 'price_type'); - next(); -}, query, response('price_type')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'state', - table: 'estado', - tableField: ['sigla', 'id'], - resultField: ['sigla_uf', 'cod_uf'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'cub' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'cub' - } -}).addValue({ - name: 'min_year', - table: 'cub', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'cub', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'cub', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'cub', - field: 'ano_censo' - } -}).addValue({ - name: 'min_month', - table: 'cub', - tableField: 'mes_censo', - resultField: 'month', - where: { - relation: '>=', - type: 'integer', - table: 'cub', - field: 'mes_censo' - } -}).addValue({ - name: 'max_month', - table: 'cub', - tableField: 'mes_censo', - resultField: 'month', - where: { - relation: '<=', - type: 'integer', - table: 'cub', - field: 'mes_censo' - } -}); - -cubApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - if (req.filter.size || req.filter.dims) { - if ('state' in req.filter || 'state' in req.dims) { - req.sql.from('cub') - .field('cub.estado_id', 'cod_uf') - .field('estado.sigla', 'sigla_uf') - .field('cub.tipo_preco', 'tipo_preco') - .field('cub.preco', 'preco') - .join('estado', null, 'cub.estado_id=estado.id') - .group('cub.ano_censo') - .group('cub.mes_censo') - .group('cub.estado_id') - .group('estado.sigla') - .group('cub.tipo_preco') - .group('cub.preco') - } else { - req.sql.from('cub') - .field("'BR'", 'sigla_uf') - .field("cub.tipo_preco", 'tipo_preco') - .field('AVG(cub.preco)', 'preco') - .join('estado', null, 'cub.estado_id=estado.id') - .group('cub.ano_censo') - .group('cub.mes_censo') - .group('cub.tipo_preco') - } - } else { - req.sql.from('cub') - .field('cub.estado_id', 'cod_uf') - .field('estado.sigla', 'sigla_uf') - .field('cub.tipo_preco', 'tipo_preco') - .field('cub.preco', 'preco') - .join('estado', null, 'cub.estado_id=estado.id') - .group('cub.ano_censo') - .group('cub.mes_censo') - .group('cub.estado_id') - .group('estado.sigla') - .group('cub.tipo_preco') - .group('cub.preco') - } - - next(); -}, query, addMissing(rqf), id2str.transform(), response('cub')); - -module.exports = cubApp; diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js deleted file mode 100644 index 3588a5475a763e88fb92a07a9d52cb557e0cd508..0000000000000000000000000000000000000000 --- a/src/libs/routes/dailyChargeAmount.js +++ /dev/null @@ -1,474 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const request = require(`request`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); -let rqfCount = new ReqQueryFields(); - -dailyChargeAmountApp.get('/year_range', (req, res, next) => { - req.sql.from('turma') - .field('MIN(turma.ano_censo)', 'start_year') - .field('MAX(turma.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -dailyChargeAmountApp.get('/years', (req, res, next) => { - req.sql.from('turma') - .field('DISTINCT turma.ano_censo', 'year'); - next(); -}, query, response('years')); - -dailyChargeAmountApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'turma\''); - next(); -}, query, response('source')); - -dailyChargeAmountApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -dailyChargeAmountApp.get('/adm_dependency_detailed', cache('15 day'), (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -dailyChargeAmountApp.get('/location', cache('15 day'), (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -dailyChargeAmountApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -dailyChargeAmountApp.get('/education_level_short', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Ensino Fundamental - anos iniciais'}, - {id: 4, name: 'Ensino Fundamental - anos finais'}, - {id: 5, name: 'Ensino Médio'}, - {id: 6, name: 'EJA'}, - {id: 7, name: 'EE exclusiva'} - ]; - next(); -}, response('education_level_short')); - -dailyChargeAmountApp.get('/average/education_level_mod', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Educação Infantil Unificada'}, - {id: 4, name: 'Ensino Fundamental - anos iniciais'}, - {id: 5, name: 'Ensino Fundamental - anos finais'}, - {id: 6, name: 'Ensino Médio'}, - {id: 7, name: 'Turma Multisseriadas e Multietapas'}, - {id: 8, name: 'EJA - Ensino Fundamental'}, - {id: 9, name: 'EJA - Ensino Médio'}, - {id: 10, name: 'Educação Profissional'} - ]; - next(); -}, response('education_level_mod')); - -dailyChargeAmountApp.get('/period', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 3; ++i) { - req.result.push({ - id: i, - name: id2str.period(i) - }); - }; - req.result.push({ - id: 99, - name: id2str.period(99) - }); - next(); -}, response('period')); - -dailyChargeAmountApp.get('/integral_time', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Disponível'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('integral_time')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'min_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'turma', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'turma', - field: 'ano_censo' - } -}).addValue({ - name: 'location', - table: 'turma', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'adm_dependency', - table: 'turma', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'turma', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'rural_location', - table: 'turma', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'education_level_mod', - table: 'turma', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - dontGroup: true, - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'period', - table: 'turma', - tableField: 'turma_turno_id', - resultField: 'period_id', - where: { - relation: '=', - type: 'integer', - field: 'turma_turno_id' - } -}).addValue({ - name: 'integral_time', - table: 'turma', - tableField: 'tempo_integral', - resultField: 'integral_time_id', - where: { - relation: '=', - type: 'boolean', - field: 'tempo_integral' - } -}).addValue({ - name: 'education_level_short', - table: 'turma', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}); - -dailyChargeAmountApp.get('/', rqf.parse(), (req, res, next) => { - var status = 0; - if ('integral_time' in req.filter) { - if (req.filter['integral_time'] == '0' - && ('period' in req.filter)) { - if (req.filter['period'].length == 1 - && req.filter['period'][0] == '3') { - status = 1; - } else if (req.filter['period'].length <= 2 - && (req.filter['period'].includes('1') - || req.filter['period'].includes('2')) - && (!req.filter['period'].includes('3'))) { - status = 1; - } - } else if (req.filter['integral_time'] == '1') { - status = 1; - } - } - - if (status) { - req.sql.from('turma') - .field('turma.ano_censo', 'year') - .field('turma.etapa_resumida', 'education_level_short_id') - .field('AVG(turma.duracao_turma)/60.0', 'average_class_duration') - .field('MEDIAN(turma.duracao_turma)/60.0', 'median_class_duration') - .field('STDDEV_SAMP(turma.duracao_turma)/60.0', 'std_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.25)/60.0', 'fstqt_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.75)/60.0', 'thdqt_class_duration') - .group('turma.ano_censo') - .group('turma.etapa_resumida') - .order('turma.ano_censo') - .order('turma.etapa_resumida') - .where('turma.tipo_turma_id <= 3 and turma.dependencia_adm_id <= 3') - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); - -}, rqf.build(), query, addMissing(rqf), (req, res, next) => { - - function sliced(object) { - return object['education_level_short_id'] > 3; - } - - if ('period' in req.filter || 'period' in req.dims) { - req.filter['period'].forEach((element) => { - if (element == '3') - req.result = req.result.filter(sliced); - }); - } - - next(); -}, id2str.transform(), response('turma')); - -dailyChargeAmountApp.get('/average', rqf.parse(), rqf.build(), (req, res, next) => { - var status = 0; - if (('education_level_mod' in req.filter || 'education_level_mod' in req.dims) - && ('integral_time' in req.filter)) { - if (req.filter['integral_time'] == '0' - && ('period' in req.filter)) { - if (req.filter['period'].length == 1 - && req.filter['period'][0] == '3') { - status = 1; - } else if (req.filter['period'].length <= 2 - && (req.filter['period'].includes('1') - || req.filter['period'].includes('2')) - && (!req.filter['period'].includes('3'))) { - status = 1; - } - } else if (req.filter['integral_time'] == '1') { - status = 1; - } - } - - if (status) { - let baseQ = req.sql.clone(); - - 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.etapas_mod_ensino_segmento_id') - .field('AVG(1.0*R.duracao_turma)/60', 'median_value') - .join(tableG, 'G', 'R.etapas_mod_ensino_segmento_id = G.etapas_mod_ensino_segmento_id AND R.rowNo BETWEEN G.counter/2 AND G.counter/2+G.counter%2') - .group('R.etapas_mod_ensino_segmento_id') - - req.sql - .from('turma') - .from(joinRG, 'm') - .field('turma.ano_censo', 'year') - .field('turma.etapas_mod_ensino_segmento_id', 'education_level_mod_id') - .field('AVG(turma.duracao_turma)/60.0', 'average_class_duration') - .field('AVG(m.median_value)', 'median_class_duration') - .field('STDDEV_SAMP(turma.duracao_turma)/60.0', 'std_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.25)/60.0', 'fstqt_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.75)/60.0', 'thdqt_class_duration') - .group('turma.ano_censo') - .group('turma.etapas_mod_ensino_segmento_id') - .order('turma.ano_censo') - .order('turma.etapas_mod_ensino_segmento_id') - .where('turma.tipo_turma_id <= 3 and m.etapas_mod_ensino_segmento_id = turma.etapas_mod_ensino_segmento_id') - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); -}, query, addMissing(rqf), id2str.transform(), response('turma')); - -module.exports = dailyChargeAmountApp; diff --git a/src/libs/routes/distributionFactor.js b/src/libs/routes/distributionFactor.js deleted file mode 100644 index 99e1a77a9e9dea2fc2b49551d2b9d9760ec680fa..0000000000000000000000000000000000000000 --- a/src/libs/routes/distributionFactor.js +++ /dev/null @@ -1,210 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -distributionApp.use(cache('15 day')); - -rqf.addField({ - name: 'dims', - field: true, - where: false -}).addField({ - name: 'filter', - field: false, - where: true -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'fatores_matricula' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'fatores_matricula' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'fatores_matricula' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'fatores_matricula' - } -}, 'filter').addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'fatores_matricula' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'fatores_matricula' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'fatores_matricula' - } -}) - -// Return all cities -distributionApp.get('/', rqf.parse(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - let relation = req.sql.clone(); - relation.from('relacao_fatores_matricula').field('*'); - req.queryIndex.relation = req.querySet.push(relation) - 1; - - req.sql.from('fatores_matricula') - .field('fatores_matricula.municipio_id', 'municipio_id') - .field('fatores_matricula."mais_CRE_0"') - .field('fatores_matricula."mais_CRE_1"') - .field('fatores_matricula."mais_CRE_2"') - .field('fatores_matricula."mais_CRE_3"') - .field('fatores_matricula."mais_PRE"') - .field('fatores_matricula."mais_EFAI"') - .field('fatores_matricula."mais_EFAF"') - .field('fatores_matricula."mais_EM"') - .field('fatores_matricula."mais_EJA"') - .field('fatores_matricula."menos_CRE_0"') - .field('fatores_matricula."menos_CRE_1"') - .field('fatores_matricula."menos_CRE_2"') - .field('fatores_matricula."menos_CRE_3"') - .field('fatores_matricula."menos_PRE"') - .field('fatores_matricula."menos_EFAI"') - .field('fatores_matricula."menos_EFAF"') - .field('fatores_matricula."menos_EM"') - .field('fatores_matricula."menos_EJA"') - .group('fatores_matricula.municipio_id') - .group('fatores_matricula."mais_CRE_0"') - .group('fatores_matricula."mais_CRE_1"') - .group('fatores_matricula."mais_CRE_2"') - .group('fatores_matricula."mais_CRE_3"') - .group('fatores_matricula."mais_PRE"') - .group('fatores_matricula."mais_EFAI"') - .group('fatores_matricula."mais_EFAF"') - .group('fatores_matricula."mais_EM"') - .group('fatores_matricula."mais_EJA"') - .group('fatores_matricula."menos_CRE_0"') - .group('fatores_matricula."menos_CRE_1"') - .group('fatores_matricula."menos_CRE_2"') - .group('fatores_matricula."menos_CRE_3"') - .group('fatores_matricula."menos_PRE"') - .group('fatores_matricula."menos_EFAI"') - .group('fatores_matricula."menos_EFAF"') - .group('fatores_matricula."menos_EM"') - .group('fatores_matricula."menos_EJA"'); - - if(typeof req.dims.state !== 'undefined' || typeof req.filter.state !== 'undefined') { - req.sql.where('fatores_matricula.nivel = \'UF\''); - } else { - req.sql.where('fatores_matricula.nivel = \'BR\''); - } - - next(); -}, rqf.build(), query, (req, res, next) => { - req.enrollmentFactor = req.result; - next(); -}, multiQuery, (req, res, next) => { - let relation = req.result[req.queryIndex.relation]; - let result = []; - let first = true; - req.enrollmentFactor.forEach((city) => { - // if(first) console.log(city); - let obj = { - level: city.nivel, - region_id: city.regiao_id, - region_name: city.region_name, - state_id: city.state_id, - state_name: city.state_name, - city_id: city.municipio_id, - city_name: city.city_name, - series: [] - }; - // if(first) console.log(obj); - first = false; - relation.forEach((serie) => { - obj.series.push({ - serie_id: serie.id, - distribution_factor_addition: city[serie.fator_adicao], - distribution_factor_reduction: city[serie.fator_reducao] - }); - }); - result.push(obj); - }); - req.result = result; - next(); -}, response('ditributionFactor')); - -module.exports = distributionApp; diff --git a/src/libs/routes/downloads.js b/src/libs/routes/downloads.js deleted file mode 100644 index 9f01479dc051b04daef6c683742d0b2762eae5ef..0000000000000000000000000000000000000000 --- a/src/libs/routes/downloads.js +++ /dev/null @@ -1,74 +0,0 @@ -/* -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 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 deleted file mode 100644 index b8173d060e8f29183ccc65926815dc3594a2ce24..0000000000000000000000000000000000000000 --- a/src/libs/routes/educationYears.js +++ /dev/null @@ -1,66 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const response = require(`${libs}/middlewares/response`); - -const config = require(`${libs}/config`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -educationYearsApp.use(cache('15 day')); - -educationYearsApp.get('/', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 7; ++i) { - let edLvlShort = { - id: i, - name: id2str.educationLevelShort(i), - schoolYears: [] - }; - - for(let j = i*10; j <= (i*10 + 9); ++j) { - - let schoolYear = { - id: j, - name: id2str.schoolYear(j) - }; - - if(schoolYear.name !== id2str.schoolYear(99)) { - edLvlShort.schoolYears.push(schoolYear); - } - } - if(edLvlShort.name !== id2str.schoolYear(99)) { - req.result.push(edLvlShort); - } - } - next(); -}, response('educationYears')); - -module.exports = educationYearsApp; diff --git a/src/libs/routes/employees.js b/src/libs/routes/employees.js deleted file mode 100644 index 9aedbcb1de07e1e769806e57483981cb9530981a..0000000000000000000000000000000000000000 --- a/src/libs/routes/employees.js +++ /dev/null @@ -1,537 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const employeesApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqfTeacher = new ReqQueryFields(); - -let rqfSchool = new ReqQueryFields(); - - -employeesApp.use(cache('15 day')); - -// Returns a tuple of start and ending years of the complete enrollments dataset. -employeesApp.get('/year_range', (req, res, next) => { - req.sql.from('docente') - .field('MIN(docente.ano_censo)', 'start_year') - .field('MAX(docente.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -employeesApp.get('/years', (req, res, next) => { - req.sql.from('docente'). - field('DISTINCT docente.ano_censo', 'year'); - next(); -}, query, response('years')); - -employeesApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'docente\''); - next(); -}, query, response('source')); - -employeesApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -employeesApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -employeesApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -employeesApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -rqfSchool.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: '@', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: '@', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, -}, 'filter').addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: '@', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - -rqfTeacher.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: '@', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: '@', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id','ano_censo'], - foreign: ['escola_id','ano_censo'], - foreignTable: '@' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id','ano_censo'], - foreign: ['escola_id','ano_censo'], - foreignTable: '@' - } -}, 'filter').addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: '@', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryTotal.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - let objMatch = null; - - for(let i = 0; i < queryPartial.length; ++i) { - let partial = queryPartial[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(partial[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - objMatch = partial; - break; - } - } - - if(objMatch) { - newObj.total = result.total - objMatch.total; - newObj.total_employees = result.total; - newObj.total_teachers = objMatch.total - match.push(newObj); - } - }); - - return match; -} - -employeesApp.get('/', rqfSchool.parse(), (req, res, next) => { - req.allEmployees = {} - req.allTeacher = {} - - if ("school" in req.filter) { - req.sql.field('SUM(escola.num_funcionarios)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .from('escola') - .group('escola.ano_censo') - .order('escola.ano_censo') - .where('(escola.situacao_de_funcionamento = 1) AND (escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1) AND (dependencia_adm_id = 2 OR dependencia_adm_id = 3 OR dependencia_adm_id = 4) AND (escola.id=' + req.filter.school + ')'); - delete req.filter.school; - next(); - } else { - req.sql.field('SUM(escola.num_funcionarios)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .from('escola') - .group('escola.ano_censo') - .order('escola.ano_censo') - .where('(escola.situacao_de_funcionamento = 1) AND (escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1) AND (dependencia_adm_id = 2 OR dependencia_adm_id = 3 OR dependencia_adm_id = 4)'); - next(); - } -}, rqfSchool.build(), query, rqfSchool.parse(), id2str.transform(), (req, res, next) => { - - req.allEmployees = req.result; - req.resetSql(); - - if ("school" in req.filter) { - req.sql.field('SUM(docente_por_escola.total_professores)', 'total') - .field("'Brasil'", 'name') - .field('docente_por_escola.ano_censo', 'year') - .from('docente_por_escola') - .join('escola', null, 'docente_por_escola.escola_id=escola.id AND docente_por_escola.ano_censo=escola.ano_censo') - .group('docente_por_escola.ano_censo') - .order('docente_por_escola.ano_censo') - .where('(docente_por_escola.dependencia_adm_id > 1) AND (docente_por_escola.escola_id=' + req.filter.school + ')'); - } else if ("school" in req.dims) { - req.sql.field('SUM(docente_por_escola.total_professores)', 'total') - .field("'Brasil'", 'name') - .field('docente_por_escola.ano_censo', 'year') - .field('escola.nome_escola', 'school_name') - .from('docente_por_escola') - .join('escola', null, 'docente_por_escola.escola_id=escola.id AND docente_por_escola.ano_censo=escola.ano_censo') - .group('docente_por_escola.ano_censo') - .order('docente_por_escola.ano_censo') - .where('(docente_por_escola.dependencia_adm_id > 1)'); - } else { - req.sql.field('SUM(docente_por_escola.total_professores)', 'total') - .field("'Brasil'", 'name') - .field('docente_por_escola.ano_censo', 'year') - .from('docente_por_escola') - .group('docente_por_escola.ano_censo') - .order('docente_por_escola.ano_censo') - .where('(docente_por_escola.dependencia_adm_id > 1)'); - } - next(); - -}, rqfSchool.build(), query, id2str.transform(), (req, res, next) => { - - req.allTeacher = req.result; - let aux_employees = matchQueries(req.allEmployees, req.allTeacher); - req.result = aux_employees; - next(); -}, response('employees')); - -module.exports = employeesApp; diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js deleted file mode 100644 index 65110003de781c01472300fe233dc03898c79d96..0000000000000000000000000000000000000000 --- a/src/libs/routes/enrollment.js +++ /dev/null @@ -1,934 +0,0 @@ -/* -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(); - -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 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; - -enrollmentApp.use(cache('15 day')); - -let rqf = new ReqQueryFields(); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -enrollmentApp.get('/year_range', (req, res, next) => { - req.sql.from('matricula') - .field('MIN(matricula.ano_censo)', 'start_year') - .field('MAX(matricula.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -enrollmentApp.get('/years', (req, res, next) => { - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, response('years')); - -enrollmentApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'matricula\''); - next(); -}, query, response('source')); - -enrollmentApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -enrollmentApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -// Returns all school years available -enrollmentApp.get('/school_year', (req, res, next) => { - req.result = []; - for(let i = 11; i <= 71; ++i) { - let obj = { - id: i, - name: id2str.schoolYear(i) - }; - - if(obj.name !== id2str.schoolYear(99)) { - req.result.push(obj); - } - } - req.result.push({ - id: 99, - name: id2str.schoolYear(99) - }); - next(); -}, response('school_year')); - -// Returns all school years available -enrollmentApp.get('/education_level', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 74; ++i) { - let obj = { - id: i, - name: id2str.educationLevel(i) - }; - - if(obj.name !== id2str.educationLevel(99)) { - req.result.push(obj); - } - } - req.result.push({ - id: 99, - name: id2str.educationLevel(99) - }); - next(); -}, response('education_level')); - -// Returns all school years available -enrollmentApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 10; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -enrollmentApp.get('/education_level_short', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Ensino Fundamental - anos iniciais'}, - {id: 4, name: 'Ensino Fundamental - anos finais'}, - {id: 5, name: 'Ensino Médio'}, - {id: 6, name: 'EJA'}, - {id: 7, name: 'EE exclusiva'} - ]; - next(); -}, response('education_level_short')); - -// Returns all adm dependencies -enrollmentApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -enrollmentApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -// Return genders -enrollmentApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -// Return ethnic group -enrollmentApp.get('/ethnic_group', (req, res, next) => { - req.result = []; - for(let i = 1; i <=5; ++i) { - req.result.push({ - id: i, - name: id2str.ethnicGroup(i) - }); - } - next(); -}, response('ethnic_group')); - -enrollmentApp.get('/period', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 3; ++i) { - req.result.push({ - id: i, - name: id2str.period(i) - }); - } - req.result.push({ - id: 99, - name: id2str.period(99) - }); - next(); -}, response('period')); - -// Returns integral-time avaible -enrollmentApp.get('/integral_time', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Disponível'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('integral_time')); - -enrollmentApp.get('/special_class', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('special_class')); - -enrollmentApp.get('/age_range_all', (req, res, next) => { - req.result = [ - {id: 1, name: '0 a 3 anos'}, - {id: 2, name: '4 a 5 anos'}, - {id: 3, name: '6 a 10 anos'}, - {id: 4, name: '11 a 14 anos'}, - {id: 5, name: '15 a 17 anos'}, - {id: 6, name: '18 a 24 anos'}, - {id: 7, name: '25 a 29 anos'}, - {id: 8, name: '30 a 40 anos'}, - {id: 9, name: '41 a 50 anos'}, - {id: 10, name: '51 a 64 anos'}, - {id: 11, name: 'Mais que 64 anos'} - ]; - next(); -}, response('age_range_all')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: 'matricula', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'matricula', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'school_year', - table: 'matricula', - tableField: 'serie_ano_id', - resultField: 'school_year_id', - where: { - relation: '=', - type: 'integer', - field: 'serie_ano_id' - } -}).addValue({ - name: 'education_level', - table: 'matricula', - tableField: 'etapa_ensino_id', - resultField: 'education_level_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_ensino_id' - } -}).addValue({ - name: 'education_level_mod', - table: 'matricula', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'education_level_short', - table: 'matricula', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'matricula' - } -}).addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'matricula' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'matricula' - } -}, 'filter').addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'matricula' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'matricula' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: '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', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'matricula' - } -}, 'filter').addValue({ - name: 'location', - table: 'matricula', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'matricula', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'min_year', - table: 'matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'gender', - table: 'matricula', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'ethnic_group', - table: 'matricula', - tableField: 'cor_raca_id', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca_id' - } -}).addValue({ - name: 'period', - table: 'matricula', - tableField: 'turma_turno_id', - resultField: 'period_id', - where: { - relation: '=', - type: 'integer', - field: 'turma_turno_id' - } -}).addValue({ - name:'integral_time', - table: 'matricula', - tableField: 'tempo_integral', - resultField: 'integral_time_id', - where: { - relation: '=', - type: 'boolean', - field: 'tempo_integral' - } -}).addValue({ - name:'age_range_all', - table: 'matricula', - tableField: 'faixa_etaria_31_03', - resultField: 'age_range_all_id', - where: { - relation: '=', - type: 'integer', - field: 'faixa_etaria_31_03' - } -}).addValue({ - name:'special_class', - table: 'matricula', - tableField: 'exclusiva_especial', - resultField: 'special_class_id', - where: { - relation: '=', - type: 'boolean', - field: 'exclusiva_especial' - } -}); - -enrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.field('COUNT(*)', 'total') - .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')); - -enrollmentApp.get('/diagnosis', rqf.parse(), (req, res, next) => { - req.dims = {}; - req.dims.state = true; - req.dims.city = true; - req.dims.school_year = true; - req.dims.location = true; - req.dims.adm_dependency_detailed = true; - - 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(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - let enrollments = req.result; - - // Gera a relação etapa de ensino X ano escolar - let educationSchoolYear = {}; - for(let i = 10; i < 80; ++i) { - if(id2str.schoolYear(i) !== id2str.schoolYear(99)) { - let educationLevelId = Math.floor(i/10); - educationSchoolYear[i] = { - id: educationLevelId, - name: id2str.educationLevelShort(educationLevelId), - }; - } - } - - let result = []; - let educationLevelSet = new Set(); - let schoolYearSet = new Set(); - let i = 0; - while(i < enrollments.length) { - let enrollment = enrollments[i]; - if(!educationSchoolYear[enrollment.school_year_id]) { - ++i; - continue; - } - let educationLevelHash = '' + enrollment.year + educationSchoolYear[enrollment.school_year_id].id + enrollment.city_id; - let schoolYearHash = '' + enrollment.year + enrollment.school_year_id + enrollment.city_id; - - let currentEducation = null; - // Busca ou cria a etapa de ensino adequada - if(educationLevelSet.has(educationLevelHash)) { - let j = 0; - let edu = result[j]; - while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != educationSchoolYear[enrollment.school_year_id].id)) { - ++j; - edu = result[j]; - } - if(j >= result.length) --j; - edu = result[j]; - - currentEducation = edu; - } else { - educationLevelSet.add(educationLevelHash); - let obj = { - year: enrollment.year, - name: enrollment.name, - state_id: enrollment.state_id, - state_name: enrollment.state_name, - city_id: enrollment.city_id, - city_name: enrollment.city_name, - education_level_school_year_id: educationSchoolYear[enrollment.school_year_id].id, - education_level_school_year_name: educationSchoolYear[enrollment.school_year_id].name, - total: 0, - adm_dependencies: [ - { - adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, - adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, - total: 0 - } - ], - locations: [ - { - location_id: enrollment.location_id, - location_name: enrollment.location_name, - total: 0 - } - ] - }; - - result.push(obj); - currentEducation = obj; - } - - let currentSchoolYear = null; - // Busca ou cria a série adequada - if(schoolYearSet.has(schoolYearHash)) { - let j = 0; - let edu = result[j]; - while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != enrollment.school_year_id)) { - ++j; - edu = result[j]; - } - if(j >= result.length) --j; - edu = result[j]; - - currentSchoolYear = edu; - } else { - schoolYearSet.add(schoolYearHash); - let obj = { - year: enrollment.year, - name: enrollment.name, - state_id: enrollment.state_id, - state_name: enrollment.state_name, - city_id: enrollment.city_id, - city_name: enrollment.city_name, - education_level_school_year_id: enrollment.school_year_id, - education_level_school_year_name: enrollment.school_year_name, - total: 0, - adm_dependencies: [ - { - adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, - adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, - total: 0 - } - ], - locations: [ - { - location_id: enrollment.location_id, - location_name: enrollment.location_name, - total: 0 - } - ] - }; - - result.push(obj); - currentSchoolYear = obj; - } - - // Adiciona ao total - currentEducation.total += enrollment.total; - currentSchoolYear.total += enrollment.total; - - // Adiciona ao total da dependência administrativa - let admDependencyIndex = 0; - let admDependency = currentEducation.adm_dependencies[admDependencyIndex]; - while (admDependencyIndex < currentEducation.adm_dependencies.length && enrollment.adm_dependency_detailed_id > admDependency.adm_dependency_detailed_id) { - ++admDependencyIndex; - admDependency = currentEducation.adm_dependencies[admDependencyIndex]; - } - if(admDependencyIndex >= currentEducation.adm_dependencies.length || admDependency.adm_dependency_detailed_id != enrollment.adm_dependency_detailed_id) { // não encontrou - let obj = { - adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, - adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, - total: 0 - } - currentEducation.adm_dependencies.splice(admDependencyIndex, 0, obj); - admDependency = obj; - } - admDependency.total += enrollment.total; - - admDependencyIndex = 0; - admDependency = currentSchoolYear.adm_dependencies[admDependencyIndex]; - while (admDependencyIndex < currentSchoolYear.adm_dependencies.length && enrollment.adm_dependency_detailed_id > admDependency.adm_dependency_detailed_id) { - ++admDependencyIndex; - admDependency = currentSchoolYear.adm_dependencies[admDependencyIndex]; - } - if(admDependencyIndex >= currentSchoolYear.adm_dependencies.length || admDependency.adm_dependency_detailed_id != enrollment.adm_dependency_detailed_id) { // não encontrou - let obj = { - adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, - adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, - total: 0 - } - currentSchoolYear.adm_dependencies.splice(admDependencyIndex, 0, obj); - admDependency = obj; - } - admDependency.total += enrollment.total; - - // Adiciona ao total da localidade - let locationIndex = 0; - let location = currentEducation.locations[locationIndex]; - while (locationIndex < currentEducation.locations.length && enrollment.location_id > location.location_id) { - ++locationIndex; - location = currentEducation.locations[locationIndex]; - } - if(locationIndex >= currentEducation.locations.length || location.location_id != enrollment.location_id) { - let obj = { - location_id: enrollment.location_id, - location_name: enrollment.location_name, - total: 0 - } - currentEducation.locations.splice(locationIndex, 0, obj); - location = obj; - } - location.total += enrollment.total; - - locationIndex = 0; - location = currentSchoolYear.locations[locationIndex]; - while (locationIndex < currentSchoolYear.locations.length && enrollment.location_id > location.location_id) { - ++locationIndex; - location = currentSchoolYear.locations[locationIndex]; - } - if(locationIndex >= currentSchoolYear.locations.length || location.location_id != enrollment.location_id) { - let obj = { - location_id: enrollment.location_id, - location_name: enrollment.location_name, - total: 0 - } - currentSchoolYear.locations.splice(locationIndex, 0, obj); - location = obj; - } - location.total += enrollment.total; - - ++i; - } - - req.result = result; - - next(); -}, response('enrollment_diagnosis')); - -enrollmentApp.get('/projection', rqf.parse(), (req, res, next) => { - req.dims = {}; - req.dims.state = true; - req.dims.city = true; - req.dims.location = true; - req.dims.school_year = true; - req.dims.adm_dependency = true; - req.dims.period = true; - req.filter.adm_dependency = [1,2,3]; - - 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(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - let enrollments = req.result; - - // Gera a relação etapa de ensino X ano escolar - let educationSchoolYear = {}; - for(let i = 10; i < 80; ++i) { - if(id2str.schoolYear(i) !== id2str.schoolYear(99)) { - let educationLevelId = Math.floor(i/10); - educationSchoolYear[i] = { - id: educationLevelId, - name: id2str.educationLevelShort(educationLevelId), - }; - } - } - - console.log(educationSchoolYear); - - let result = []; - let educationLevelSet = new Set(); - let schoolYearSet = new Set(); - let i = 0; - while(i < enrollments.length) { - let enrollment = enrollments[i]; - if(!educationSchoolYear[enrollment.school_year_id]) { - ++i; - continue; - } - let educationLevelHash = '' + enrollment.year + educationSchoolYear[enrollment.school_year_id].id + enrollment.city_id; - let schoolYearHash = '' + enrollment.year + enrollment.school_year_id + enrollment.city_id; - - let currentEducation = null; - // Busca ou cria a etapa de ensino adequada - if(educationLevelSet.has(educationLevelHash)) { - let j = 0; - let edu = result[j]; - while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != educationSchoolYear[enrollment.school_year_id].id)) { - ++j; - edu = result[j]; - } - if((j >= result.length)) --j; - edu = result[j]; - - currentEducation = edu; - } else { - educationLevelSet.add(educationLevelHash); - let obj = { - year: enrollment.year, - name: enrollment.name, - state_id: enrollment.state_id, - state_name: enrollment.state_name, - city_id: enrollment.city_id, - city_name: enrollment.city_name, - education_level_school_year_id: educationSchoolYear[enrollment.school_year_id].id, - education_level_school_year_name: educationSchoolYear[enrollment.school_year_id].name, - urban_day_total: 0, - urban_night_total: 0, - rural_day_total: 0, - rural_night_total: 0 - }; - result.push(obj); - currentEducation = obj; - } - - let currentSchoolYear = null; - // Busca ou cria a série adequada - if(schoolYearSet.has(schoolYearHash)) { - let j = 0; - let edu = result[j]; - while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != enrollment.school_year_id)){ - ++j; - edu = result[j]; - } - if(j >= result.length) --j; - edu = result[j]; - - currentSchoolYear = edu; - } else { - schoolYearSet.add(schoolYearHash); - let obj = { - year: enrollment.year, - name: enrollment.name, - state_id: enrollment.state_id, - state_name: enrollment.state_name, - city_id: enrollment.city_id, - city_name: enrollment.city_name, - education_level_school_year_id: enrollment.school_year_id, - education_level_school_year_name: enrollment.school_year_name, - urban_day_total: 0, - urban_night_total: 0, - rural_day_total: 0, - rural_night_total: 0 - }; - - result.push(obj); - currentSchoolYear = obj; - } - - if(enrollment.location_id == 1) { - if(enrollment.period_id < 3) { - currentEducation.urban_day_total += enrollment.total; - currentSchoolYear.urban_day_total += enrollment.total; - } else { - currentEducation.urban_night_total += enrollment.total; - currentSchoolYear.urban_night_total += enrollment.total; - } - } else { - if(enrollment.period_id < 3) { - currentEducation.rural_day_total += enrollment.total; - currentSchoolYear.rural_day_total += enrollment.total; - } else { - currentEducation.rural_night_total += enrollment.total; - currentSchoolYear.rural_night_total += enrollment.total; - } - } - - ++i; - } - - req.result = result; - - next(); -}, response('enrollment_projection')); - -module.exports = enrollmentApp; diff --git a/src/libs/routes/enrollmentProjection.js b/src/libs/routes/enrollmentProjection.js deleted file mode 100644 index 7ff2ab2379de73e63ff83f28399019accb7adb3a..0000000000000000000000000000000000000000 --- a/src/libs/routes/enrollmentProjection.js +++ /dev/null @@ -1,159 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -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`); - -let rqf = new ReqQueryFields(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'projecao_matricula' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'projecao_matricula' - } -}, 'filter').addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'projecao_matricula' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'projecao_matricula' - } -}, 'filter').addValue({ - name: 'min_year', - table: 'projecao_matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'projecao_matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - -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'); - - 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); - }); - - next(); -}, response('enrollment_projection')); - -module.exports = enrollmentProjectionApp; \ No newline at end of file diff --git a/src/libs/routes/financial.js b/src/libs/routes/financial.js deleted file mode 100644 index bfe272058ce1d385bce3934b49a094140c496f1e..0000000000000000000000000000000000000000 --- a/src/libs/routes/financial.js +++ /dev/null @@ -1,186 +0,0 @@ -/* -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(); - -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(); - -financialApp.get('/year_range', (req, res, next) => { - req.sql.from('indicadores_financeiros') - .field('MIN(indicadores_financeiros.ano_censo)', 'start_year') - .field('MAX(indicadores_financeiros.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -financialApp.get('/years', (req, res, next) => { - req.sql.from('indicadores_financeiros') - .field('DISTINCT indicadores_financeiros.ano_censo', 'year'); - next(); -}, query, response('years')); - -financialApp.get('/sphere_adm', (req, res, next) => { - req.result = [ - {id: 1, name: "1"}, - {id: 2, name: "2"} - ] - next(); -}, response('sphere_adm')); - -financialApp.get('/financial_data', (req, res, next) => { - req.sql.from('indicadores_financeiros') - .field('DISTINCT indicadores_financeiros.dados_financeiros', 'financial_data'); - next(); -}, query, response('financial_data')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'state', - table: 'estado', - tableField: ['sigla', 'id'], - resultField: ['sigla_uf', 'cod_uf'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'indicadores_financeiros' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'indicadores_financeiros' - } -}).addValue({ - name: 'min_year', - table: 'indicadores_financeiros', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'indicadores_financeiros', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'indicadores_financeiros', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'indicadores_financeiros', - field: 'ano_censo' - } -}).addValue({ - name: 'sphere_adm', - table: 'indicadores_financeiros', - tableField: 'esfera_adm', - resultField: 'sphere_adm_id', - where: { - relation: '=', - type: 'integer', - field: 'esfera_adm' - } -}).addValue({ - name: 'city', - table: 'indicadores_financeiros', - tableField: 'municipio_id', - resultField: 'city_id', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id' - } -}).addValue({ - name: 'financial_data', - table: 'indicadores_financeiros', - tableField: 'dados_financeiros', - resultField: 'financial_data_id', - where: { - relation: '=', - type: 'integer', - field: 'dados_financeiros' - } -}); - -financialApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - 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')); - -module.exports = financialApp; diff --git a/src/libs/routes/glossEnrollmentRatio.js b/src/libs/routes/glossEnrollmentRatio.js deleted file mode 100644 index 7183715a1778fbe4ee9ee9d058ba1b3d6d897189..0000000000000000000000000000000000000000 --- a/src/libs/routes/glossEnrollmentRatio.js +++ /dev/null @@ -1,404 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -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 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(); - -glossEnrollmentRatioApp.use(cache('15 day')); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -glossEnrollmentRatioApp.get('/year_range', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let distinct_years = []; - let new_result = []; - for (let i = 0; i < req.oldResult.length; i++) { - for (let j = 0; j < req.result.length; j++) { - if(req.oldResult[i].year == req.result[j].year) { - distinct_years.push(req.oldResult[i]); - } - } - } - new_result.push({start_year: distinct_years[distinct_years.length -1].year, end_year: distinct_years[0].year}); - req.result = new_result; - next(); -}, response('range')); - -glossEnrollmentRatioApp.get('/years', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let new_result = [] - for (let i = 0; i < req.oldResult.length; i++) { - for (let j = 0; j < req.result.length; j++) { - if(req.oldResult[i].year == req.result[j].year) { - new_result.push(req.oldResult[i]); - } - } - } - req.result = new_result; - next(); -}, response('years')); - -glossEnrollmentRatioApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'pnad\''); - next(); -}, query, response('source')); - -glossEnrollmentRatioApp.get('/education_level_basic', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 4, name: 'Ensino Fundamental - anos iniciais'}, - {id: 5, name: 'Ensino Fundamental - anos finais'}, - {id: 6, name: 'Ensino Médio'} - ]; - next(); -}, response('education_level_basic')); - -glossEnrollmentRatioApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -glossEnrollmentRatioApp.get('/ethnic_group', (req, res, next) => { - req.result = [ - {id: 0, name: 'Sem declaração'}, - {id: 1, name: 'Branca'}, - {id: 2, name: 'Preta'}, - {id: 3, name: 'Parda'}, - {id: 4, name: 'Amarela'}, - {id: 5, name: 'Indígena'} - ]; - next(); -}, response('ethnic_group')); - -glossEnrollmentRatioApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValue({ - name: 'ethnic_group', - table: '@', - tableField: 'cor_raca_id', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca_id' - } -}).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: 'gender', - table: '@', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'education_level_basic', - table: 'matricula', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_basic_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}); - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryPartial.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - // console.log('NEW OBJ'); - // console.log(newObj); - // remove total - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - // remove education_level_basic_id - index = keys.indexOf('education_level_basic_id'); - if(index > -1) keys.splice(index, 1); - // remove education_level_basic_name - index = keys.indexOf('education_level_basic_name'); - if(index > -1) keys.splice(index, 1); - let objMatch = null; - - for(let i = 0; i < queryTotal.length; ++i) { - let total = queryTotal[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(total[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - objMatch = total; - break; - } - } - - if(objMatch) { - // console.log('MATCH!!!!'); - // console.log(objMatch); - newObj.total = (result.total / objMatch.total) * 100; - newObj.partial = result.total; - newObj.denominator = objMatch.total - match.push(newObj); - } - }); - // console.log('TAMANHOS'); - // console.log(queryTotal.length); - // console.log(queryPartial.length); - // console.log(match.length); - return match; -} - -glossEnrollmentRatioApp.get('/', rqf.parse(),(req, res, next) => { - req.numerator = {}; - req.denominator = {}; - let glossEnrollmentRatioApp = {}; - - req.sql.from('matricula') - .field('count(*)', 'total') - .field('matricula.ano_censo', 'year') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3') - - if ( "education_level_basic" in req.dims ) { - req.sql.field('matricula.etapas_mod_ensino_segmento_id', 'age_range') - req.sql.where('matricula.etapas_mod_ensino_segmento_id = 1 OR matricula.etapas_mod_ensino_segmento_id = 2 OR matricula.etapas_mod_ensino_segmento_id = 4 OR matricula.etapas_mod_ensino_segmento_id = 5 OR matricula.etapas_mod_ensino_segmento_id = 6') - req.sql.group('matricula.etapas_mod_ensino_segmento_id', 'age_range'); - } - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.numerator = req.result; - req.resetSql(); - req.sql.field('sum(peso)', 'total') - .field('pnad.ano_censo','year') - .from('pnad') - .group('pnad.ano_censo') - .order('pnad.ano_censo') - - function convert(result) { - if (result == 1) { - return 'pnad.faixa_etaria_31_03 = 1' - } else if (result == 2) { - return 'pnad.faixa_etaria_31_03 = 2' - } else if (result == 4) { - return 'pnad.faixa_etaria_31_03 = 3' - } else if (result == 5) { - return 'pnad.faixa_etaria_31_03 = 4' - } else if (result == 6) { - return 'pnad.faixa_etaria_31_03 = 5' - } - } - - //remove education_level_basic how filter and add faixa_etaria_31_03 in filter - if ("education_level_basic" in req.filter) { - if (Array.isArray(req.filter.education_level_basic)) { - var string_query = ''; - for(let i = 0; i < req.filter.education_level_basic.length - 1; i++) { - string_query = string_query + convert(req.filter.education_level_basic[i]) + ' OR '; - } - string_query = string_query + convert(req.filter.education_level_basic[req.filter.education_level_basic.length - 1]); - req.sql.where(string_query); - req.sql.field('pnad.faixa_etaria_31_03','age_range') - req.sql.group('pnad.faixa_etaria_31_03', 'age_range') - } - } else if ( "education_level_basic" in req.dims ) { - req.sql.field('pnad.faixa_etaria_31_03','age_range') - req.sql.where('pnad.faixa_etaria_31_03 = 1 OR pnad.faixa_etaria_31_03 = 2 OR pnad.faixa_etaria_31_03 = 3 OR pnad.faixa_etaria_31_03 = 4 OR pnad.faixa_etaria_31_03 = 5') - req.sql.group('pnad.faixa_etaria_31_03', 'age_range'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); -}, rqf.parse(), (req, res, next) => { - if ("education_level_basic" in req.filter) { - delete req.filter.education_level_basic; - } - if ("education_level_basic" in req.dims) { - delete req.dims.education_level_basic; - } - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.denominator = req.result; - //change age range in denominator to match with numerator result - for(let i = 0; i < req.denominator.length; i++) { - if (req.denominator[i].age_range > 2) { - req.denominator[i].age_range = req.denominator[i].age_range + 1; - } - } - // log.debug("Numerador"); - // log.debug(req.numerator); - // log.debug("Denominador"); - // log.debug(req.denominator); - req.result = [] - let glossEnrollment = matchQueries(req.denominator, req.numerator); - req.result = glossEnrollment; - - next(); -}, response('glossEnrollmentRatio')); - -module.exports = glossEnrollmentRatioApp; diff --git a/src/libs/routes/idhm.js b/src/libs/routes/idhm.js deleted file mode 100644 index f21d2154506e28acbe9aa5dfb388d74debc2d164..0000000000000000000000000000000000000000 --- a/src/libs/routes/idhm.js +++ /dev/null @@ -1,212 +0,0 @@ -/* -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(); - -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(); - -idhmApp.use(cache('15 day')); - -idhmApp.get('/year_range', (req, res, next) => { - req.sql.from('adh_idh') - .field('MIN(adh_idh.ano_censo)', 'start_year') - .field('MAX(adh_idh.ano_censo)', 'end_year'); - next(); -}, query, (req, res, next) => { - req.sql.from('adh_idh_uf') - .field('MIN(adh_idh_uf.ano_censo)', 'start_year') - .field('MAX(adh_idh_uf.ano_censo)', 'end_year'); - req.old_result = req.result; - next(); -}, query, (req, res, next) => { - if (req.old_result[0].start_year < req.result[0].start_year) { - req.result[0].start_year = req.old_result[0].start_year; - } - if (req.old_result[0].end_year > req.result[0].end_year) { - req.result[0].end_year = req.old_result[0].old_result; - } - next(); -}, query, response('range')); - -idhmApp.get('/years', (req, res, next) => { - req.sql.from('adh_idh') - .field('DISTINCT adh_idh.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('adh_idh_uf') - .field('DISTINCT adh_idh_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -idhmApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'adh_idh\''); - next(); -}, query, response('source')); - -idhmApp.get('/IDHM_level', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Muito Baixa'}, - {id: 2, name: 'Baixo'}, - {id: 3, name: 'Médio'}, - {id: 4, name: 'Alto'}, - {id: 5, name: 'Muito Alto'} - ]; - next(); -}, response('IDHM_level')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'adh_idh' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'adh_idh' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).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: 'idhm_level', - table: '@', - tableField: 'idhm_nivel', - resultField: 'idhm_level_id', - where: { - relation: '=', - type: 'integer', - table: '@', - field: 'idhm_nivel' - } -}); - - -idhmApp.get('/', rqf.parse(), (req, res, next) => { - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('adh_idh') - .field('adh_idh.idhm', 'total') - .field('adh_idh.ano_censo', 'year') - .field('adh_idh.municipio_id', 'city_id') - .field('adh_idh.estado_id', 'state_id') - .group('adh_idh.idhm') - .group('adh_idh.ano_censo') - .group('adh_idh.municipio_id') - .group('adh_idh.estado_id') - } else if (("state" in req.filter) || ("state" in req.dims)) { - req.sql.from('adh_idh_uf') - .field('adh_idh_uf.idhm', 'total') - .field('adh_idh_uf.ano_censo', 'year') - .field('adh_idh_uf.estado_id', 'state_id') - .group('adh_idh_uf.idhm') - .group('adh_idh_uf.ano_censo') - .group('adh_idh_uf.estado_id') - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('idhm')); - -module.exports = idhmApp; diff --git a/src/libs/routes/idhme.js b/src/libs/routes/idhme.js deleted file mode 100644 index 25d9e682039f17f6c9059cab30802b1a3c929ba2..0000000000000000000000000000000000000000 --- a/src/libs/routes/idhme.js +++ /dev/null @@ -1,185 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -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 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(); - -idhmeApp.use(cache('15 day')); - -idhmeApp.get('/year_range', (req, res, next) => { - req.sql.from('adh_idh') - .field('MIN(adh_idh.ano_censo)', 'start_year') - .field('MAX(adh_idh.ano_censo)', 'end_year'); - next(); -}, query, (req, res, next) => { - req.sql.from('adh_idh_uf') - .field('MIN(adh_idh_uf.ano_censo)', 'start_year') - .field('MAX(adh_idh_uf.ano_censo)', 'end_year'); - req.old_result = req.result; - next(); -}, query, (req, res, next) => { - if (req.old_result[0].start_year < req.result[0].start_year) { - req.result[0].start_year = req.old_result[0].start_year; - } - if (req.old_result[0].end_year > req.result[0].end_year) { - req.result[0].end_year = req.old_result[0].old_result; - } - next(); -}, query, response('range')); - -idhmeApp.get('/years', (req, res, next) => { - req.sql.from('adh_idh') - .field('DISTINCT adh_idh.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('adh_idh_uf') - .field('DISTINCT adh_idh_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -idhmeApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'adh_idh\''); - next(); -}, query, response('source')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'adh_idh' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'adh_idh' - } -}).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', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}); - -idhmeApp.get('/', rqf.parse(), (req, res, next) => { - - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('adh_idh') - .field('adh_idh.idhm_e', 'total') - .field('adh_idh.ano_censo', 'year') - .field('adh_idh.municipio_id', 'city_id') - .group('adh_idh.idhm_e') - .group('adh_idh.ano_censo') - .group('adh_idh.municipio_id'); - } else if (("state" in req.filter) || ("state" in req.dims)) { - req.sql.from('adh_idh_uf') - .field('adh_idh_uf.idhm_e', 'total') - .field('adh_idh_uf.ano_censo', 'year') - .field('adh_idh_uf.estado_id', 'state_id') - .group('adh_idh_uf.idhm_e') - .group('adh_idh_uf.ano_censo') - .group('adh_idh_uf.estado_id'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('idhme')); - -module.exports = idhmeApp; diff --git a/src/libs/routes/idhml.js b/src/libs/routes/idhml.js deleted file mode 100644 index aa811d8f0a4dee6febcede55f33468c75b49f338..0000000000000000000000000000000000000000 --- a/src/libs/routes/idhml.js +++ /dev/null @@ -1,185 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -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 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(); - -idhmlApp.use(cache('15 day')); - -idhmlApp.get('/year_range', (req, res, next) => { - req.sql.from('adh_idh') - .field('MIN(adh_idh.ano_censo)', 'start_year') - .field('MAX(adh_idh.ano_censo)', 'end_year'); - next(); -}, query, (req, res, next) => { - req.sql.from('adh_idh_uf') - .field('MIN(adh_idh_uf.ano_censo)', 'start_year') - .field('MAX(adh_idh_uf.ano_censo)', 'end_year'); - req.old_result = req.result; - next(); -}, query, (req, res, next) => { - if (req.old_result[0].start_year < req.result[0].start_year) { - req.result[0].start_year = req.old_result[0].start_year; - } - if (req.old_result[0].end_year > req.result[0].end_year) { - req.result[0].end_year = req.old_result[0].old_result; - } - next(); -}, query, response('range')); - -idhmlApp.get('/years', (req, res, next) => { - req.sql.from('adh_idh') - .field('DISTINCT adh_idh.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('adh_idh_uf') - .field('DISTINCT adh_idh_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -idhmlApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'adh_idh\''); - next(); -}, query, response('source')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'adh_idh' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'adh_idh' - } -}).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', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}); - -idhmlApp.get('/', rqf.parse(), (req, res, next) => { - - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('adh_idh') - .field('adh_idh.idhm_l', 'total') - .field('adh_idh.ano_censo', 'year') - .field('adh_idh.municipio_id', 'city_id') - .group('adh_idh.idhm_l') - .group('adh_idh.ano_censo') - .group('adh_idh.municipio_id'); - } else if (("state" in req.filter) || ("state" in req.dims)) { - req.sql.from('adh_idh_uf') - .field('adh_idh_uf.idhm_l', 'total') - .field('adh_idh_uf.ano_censo', 'year') - .field('adh_idh_uf.estado_id', 'state_id') - .group('adh_idh_uf.idhm_l') - .group('adh_idh_uf.ano_censo') - .group('adh_idh_uf.estado_id'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('idhme')); - -module.exports = idhmlApp; diff --git a/src/libs/routes/idhmr.js b/src/libs/routes/idhmr.js deleted file mode 100644 index d140cc541e3e36f85334a68c8a3815a40c057196..0000000000000000000000000000000000000000 --- a/src/libs/routes/idhmr.js +++ /dev/null @@ -1,188 +0,0 @@ -/* -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(); - -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(); - -idhmrApp.use(cache('15 day')); - -idhmrApp.get('/year_range', (req, res, next) => { - req.sql.from('adh_idh') - .field('MIN(adh_idh.ano_censo)', 'start_year') - .field('MAX(adh_idh.ano_censo)', 'end_year'); - next(); -}, query, (req, res, next) => { - req.sql.from('adh_idh_uf') - .field('MIN(adh_idh_uf.ano_censo)', 'start_year') - .field('MAX(adh_idh_uf.ano_censo)', 'end_year'); - req.old_result = req.result; - next(); -}, query, (req, res, next) => { - if (req.old_result[0].start_year < req.result[0].start_year) { - req.result[0].start_year = req.old_result[0].start_year; - } - if (req.old_result[0].end_year > req.result[0].end_year) { - req.result[0].end_year = req.old_result[0].old_result; - } - next(); -}, query, response('range')); - -idhmrApp.get('/years', (req, res, next) => { - req.sql.from('adh_idh') - .field('DISTINCT adh_idh.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('adh_idh_uf') - .field('DISTINCT adh_idh_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -idhmrApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'adh_idh\''); - next(); -}, query, response('source')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'adh_idh' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'adh_idh' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).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' - } -}); - -idhmrApp.get('/', rqf.parse(), (req, res, next) => { - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('adh_idh') - .field('adh_idh.idhm_r', 'total') - .field('adh_idh.ano_censo', 'year') - .field('adh_idh.municipio_id', 'city_id') - .field('adh_idh.estado_id', 'state_id') - .group('adh_idh.idhm_r') - .group('adh_idh.ano_censo') - .group('adh_idh.municipio_id') - .group('adh_idh.estado_id') - } else if (("state" in req.filter) || ("state" in req.dims)) { - req.sql.from('adh_idh_uf') - .field('adh_idh_uf.idhm_r', 'total') - .field('adh_idh_uf.ano_censo', 'year') - .field('adh_idh_uf.estado_id', 'state_id') - .group('adh_idh_uf.idhm_r') - .group('adh_idh_uf.ano_censo') - .group('adh_idh_uf.estado_id') - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('idhmr')); - -module.exports = idhmrApp; diff --git a/src/libs/routes/infrastructure.js b/src/libs/routes/infrastructure.js deleted file mode 100644 index 8630cb947e57d07f48c75f1f6194a3be62f6d98e..0000000000000000000000000000000000000000 --- a/src/libs/routes/infrastructure.js +++ /dev/null @@ -1,585 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -infrastructureApp.use(cache('15 day')); - -infrastructureApp.get('/year_range', (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -infrastructureApp.get('/years', (req, res, next) => { - req.sql.from('escola') - .field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -infrastructureApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'escola\''); - next(); -}, query, response('source')); - -infrastructureApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -infrastructureApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -infrastructureApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -infrastructureApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'id', - resultField: 'city_id', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'filter').addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'id', - resultField: 'state_id', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}, 'filter').addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'location', - table: 'escola', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'escola', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'adm_dependency', - table: 'escola', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'escola', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'min_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'escola', - 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; -} - -infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - // Local de funcionamento - let allSchools = req.sql.clone(); - allSchools.from('escola').field('COUNT(escola.id)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1') - .order('escola.ano_censo'); - req.queryIndex.allSchools = req.querySet.push(allSchools) - 1; - - let schoolPlace = allSchools.clone(); - schoolPlace.where('escola.func_predio_escolar = 1 AND escola.func_salas_empresa = 0 AND escola.func_templo_igreja = 0 AND escola.func_casa_professor = 0 AND escola.func_galpao = 0 AND escola.biblioteca = 1'); - req.queryIndex.schoolPlace = req.querySet.push(schoolPlace) - 1; - - // Bibliotecas - let allLibraries = allSchools.clone(); - allLibraries.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 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; - - // Bibliotecas/Sala de leitura - let allLibrariesReadingRoom = allSchools.clone(); - allLibrariesReadingRoom.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 2'); - req.queryIndex.allLibrariesReadingRoom = req.querySet.push(allLibrariesReadingRoom) - 1; - - let haveLibrariesReadingRoom = allLibrariesReadingRoom.clone(); - haveLibrariesReadingRoom.where('escola.sala_leitura = 1'); - req.queryIndex.haveLibrariesReadingRoom = req.querySet.push(haveLibrariesReadingRoom) - 1; - - // Laboratório de informática - let allInfLab = allSchools.clone(); - allInfLab.where('escola.func_predio_escolar = 1') - .where('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'); - req.queryIndex.allInfLab = req.querySet.push(allInfLab) - 1; - - let haveInfLab = allInfLab.clone(); - haveInfLab.where('escola.lab_informatica = 1'); - req.queryIndex.haveInfLab = req.querySet.push(haveInfLab) - 1; - - // Laboratório de ciências - let allScienceLab = allInfLab.clone(); - req.queryIndex.allScienceLab = req.querySet.push(allScienceLab) - 1; - - let haveScienceLab = allScienceLab.clone(); - haveScienceLab.where('escola.lab_ciencias = 1'); - req.queryIndex.haveScienceLab = req.querySet.push(haveScienceLab) - 1; - - // Parque infantil - let allKidsPark = allSchools.clone(); - allKidsPark.where('escola.func_predio_escolar = 1') - .where('escola.reg_infantil_creche = 1 OR escola.reg_infantil_preescola = 1 OR escola.reg_fund_ai = 1 OR escola.esp_infantil_creche = 1 OR escola.esp_exclusiva_creche = 1 OR escola.reg_esp_exclusiva_fund_ai = 1'); - req.queryIndex.allKidsPark = req.querySet.push(allKidsPark) - 1; - - let haveKidsPark = allKidsPark.clone(); - haveKidsPark.where('escola.parque_infantil = 1'); - req.queryIndex.haveKidsPark = req.querySet.push(haveKidsPark) - 1; - - // Berçário - let allCribs = allSchools.clone(); - allCribs.where('escola.func_predio_escolar = 1') - .where('escola.reg_infantil_creche = 1 OR escola.esp_infantil_creche = 1'); - req.queryIndex.allCribs = req.querySet.push(allCribs) - 1; - - let haveCribs = allCribs.clone(); - haveCribs.where('escola.bercario = 1'); - req.queryIndex.haveCribs = req.querySet.push(haveCribs) - 1; - - // Quadra - let allSportsCourt = allScienceLab.clone(); - allSportsCourt.where('escola.localizacao_id = 1'); - req.queryIndex.allSportsCourt = req.querySet.push(allSportsCourt) - 1; - - let haveSportsCourt = allSportsCourt.clone(); - haveSportsCourt.where('escola.quadra_esportes = 1'); - req.queryIndex.haveSportsCourt = req.querySet.push(haveSportsCourt) - 1; - - // Quadra coberta - req.queryIndex.allCoveredSportsCourt = req.queryIndex.allSportsCourt; - - let haveCoveredSportsCourt = allSportsCourt.clone(); - haveCoveredSportsCourt.where('escola.quadra_esportes_coberta = 1'); - req.queryIndex.haveCoveredSportsCourt = req.querySet.push(haveCoveredSportsCourt) - 1; - - // Quadra Descoberta - let allUncoveredSportsCourt = allSportsCourt.clone(); - allUncoveredSportsCourt.where('escola.quadra_esportes_coberta = 0'); - req.queryIndex.allUncoveredSportsCourt = req.querySet.push(allUncoveredSportsCourt) - 1; - - let haveUncoveredSportsCourt = allUncoveredSportsCourt.clone(); - haveUncoveredSportsCourt.where('escola.quadra_esportes_descoberta = 1'); - req.queryIndex.haveUncoveredSportsCourt = req.querySet.push(haveUncoveredSportsCourt) - 1; - - // Sala de direção - let allDirectorRoom = allSchools.clone(); - allDirectorRoom.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 1'); - req.queryIndex.allDirectorRoom = req.querySet.push(allDirectorRoom) - 1; - - let haveDirectorRoom = allDirectorRoom.clone(); - haveDirectorRoom.where('escola.sala_diretoria = 1'); - req.queryIndex.haveDirectorRoom = req.querySet.push(haveDirectorRoom) - 1; - - // Secretaria - let allSecretary = allSchools.clone(); - allSecretary.where('escola.func_predio_escolar = 1'); - req.queryIndex.allSecretary = req.querySet.push(allSecretary) - 1; - - let haveSecretary = allSecretary.clone(); - haveSecretary.where('escola.secretaria = 1'); - req.queryIndex.haveSecretary = req.querySet.push(haveSecretary) - 1; - - // Sala de professores - req.queryIndex.allTeacherRoom = req.queryIndex.allSecretary; - - let haveTeacherRoom = allSecretary.clone(); - haveTeacherRoom.where('escola.sala_professor = 1'); - req.queryIndex.haveTeacherRoom = req.querySet.push(haveTeacherRoom) - 1; - - // Cozinha - req.queryIndex.allKitchen = req.queryIndex.allSecretary; - - let haveKitchen = allSecretary.clone(); - haveKitchen.where('escola.cozinha = 1'); - req.queryIndex.haveKitchen = req.querySet.push(haveKitchen) - 1; - - // Despensa - req.queryIndex.allStoreroom = req.queryIndex.allSecretary; - - let haveStoreroom = allSecretary.clone(); - haveStoreroom.where('escola.despensa = 1'); - req.queryIndex.haveStoreroom = req.querySet.push(haveStoreroom) - 1; - - // Almoxarifado - req.queryIndex.allWarehouse = req.queryIndex.allSecretary; - - let haveWarehouse = allSecretary.clone(); - haveWarehouse.where('escola.almoxarifado = 1'); - req.queryIndex.haveWarehouse = req.querySet.push(haveWarehouse) - 1; - - // Internet - req.queryIndex.allInternet = req.queryIndex.allLibrariesReadingRoom; - - let haveInternet = allLibrariesReadingRoom.clone(); - haveInternet.where('escola.internet = 1'); - req.queryIndex.haveInternet = req.querySet.push(haveInternet) - 1; - - // Internet banda larga - req.queryIndex.allBroadbandInternet = req.queryIndex.allLibraries; - - let haveBroadbandInternet = allLibraries.clone(); - haveBroadbandInternet.where('escola.internet_banda_larga = 1'); - req.queryIndex.haveBroadbandInternet = req.querySet.push(haveBroadbandInternet) - 1; - - // Banheiro dentro do prédio - req.queryIndex.allInsideBathroom = req.queryIndex.allSecretary; - - let haveInsideBathroom = allSecretary.clone(); - haveInsideBathroom.where('escola.sanitario_dentro_predio = 1'); - req.queryIndex.haveInsideBathroom = req.querySet.push(haveInsideBathroom) - 1; - - // Banheiro adequado para educação infantil dentro do prédio - req.queryIndex.allInsideKidsBathroom = req.queryIndex.allKidsPark; - - let haveInsideKidsBathroom = allKidsPark.clone(); - haveInsideKidsBathroom.where('escola.sanitario_ei = 1'); - req.queryIndex.haveInsideKidsBathroom = req.querySet.push(haveInsideKidsBathroom) - 1; - - // Fornecimento de energia - req.queryIndex.allEletricEnergy = req.queryIndex.allSecretary; - - let haveEletricEnergy = allSecretary.clone(); - haveEletricEnergy.where('escola.fornecimento_energia = 1'); - req.queryIndex.haveEletricEnergy = req.querySet.push(haveEletricEnergy) - 1; - - // Abastecimento de água - req.queryIndex.allWaterSupply = req.queryIndex.allSecretary; - - let haveWaterSupply = allSecretary.clone(); - haveWaterSupply.where('escola.fornecimento_agua = 1'); - req.queryIndex.haveWaterSupply = req.querySet.push(haveWaterSupply) - 1; - - // Água filtrada - req.queryIndex.allFilteredWater = req.queryIndex.allSecretary; - - let haveFilteredWater = allSecretary.clone(); - haveFilteredWater.where('escola.agua_filtrada = 1'); - req.queryIndex.haveFilteredWater = req.querySet.push(haveFilteredWater) - 1; - - // Coleta de esgoto - req.queryIndex.allSewage = req.queryIndex.allSecretary; - - let haveSewage = allSecretary.clone(); - haveSewage.where('escola.esgoto_sanitario = 1'); - req.queryIndex.haveSewage = req.querySet.push(haveSewage) - 1; - - // Sala de recursos multifuncionais para Atendimento Educacional Especializado - req.queryIndex.allMultifunctionRoom = req.queryIndex.allSecretary; - - let haveMultifunctionRoom = allSecretary.clone(); - haveMultifunctionRoom.where('escola.sala_atendimento_especial = 1'); - req.queryIndex.haveMultifunctionRoom = req.querySet.push(haveMultifunctionRoom) - 1; - - // Banheiros adaptados para pessoas com deficiências - req.queryIndex.allSpecialBathroom = req.queryIndex.allSecretary; - - let haveSpecialBathroom = allSecretary.clone(); - haveSpecialBathroom.where('escola.sanitario_pne = 1'); - req.queryIndex.haveSpecialBathroom = req.querySet.push(haveSpecialBathroom) - 1; - - // Dependências adaptada para pessoas com deficiências - req.queryIndex.allAdaptedBuilding = req.queryIndex.allSecretary; - - let haveAdaptedBuilding = allSecretary.clone(); - haveAdaptedBuilding.where('escola.dependencias_pne = 1'); - req.queryIndex.haveAdaptedBuilding = req.querySet.push(haveAdaptedBuilding) - 1; - - next(); -}, multiQuery, (req, res, next) => { - // Faz o matching entre os resultados - let school_place = matchQueries(req.result[req.queryIndex.allSchools], req.result[req.queryIndex.schoolPlace]); - let libraries = matchQueries(req.result[req.queryIndex.allLibraries], req.result[req.queryIndex.haveLibraries]); - let libraries_reading_room = matchQueries(req.result[req.queryIndex.allLibrariesReadingRoom], req.result[req.queryIndex.haveLibrariesReadingRoom]); - let computer_lab = matchQueries(req.result[req.queryIndex.allInfLab], req.result[req.queryIndex.haveInfLab]); - let science_lab = matchQueries(req.result[req.queryIndex.allScienceLab], req.result[req.queryIndex.haveScienceLab]); - let kids_park = matchQueries(req.result[req.queryIndex.allKidsPark], req.result[req.queryIndex.haveKidsPark]); - let nursery = matchQueries(req.result[req.queryIndex.allCribs], req.result[req.queryIndex.haveCribs]); - let sports_court = matchQueries(req.result[req.queryIndex.allSportsCourt], req.result[req.queryIndex.haveSportsCourt]); - let covered_sports_court = matchQueries(req.result[req.queryIndex.allCoveredSportsCourt], req.result[req.queryIndex.haveCoveredSportsCourt]); - let uncovered_sports_court = matchQueries(req.result[req.queryIndex.allUncoveredSportsCourt], req.result[req.queryIndex.haveUncoveredSportsCourt]); - let director_room = matchQueries(req.result[req.queryIndex.allDirectorRoom], req.result[req.queryIndex.haveDirectorRoom]); - let secretary = matchQueries(req.result[req.queryIndex.allSecretary], req.result[req.queryIndex.haveSecretary]); - let teacher_room = matchQueries(req.result[req.queryIndex.allTeacherRoom], req.result[req.queryIndex.haveTeacherRoom]); - let kitchen = matchQueries(req.result[req.queryIndex.allKitchen], req.result[req.queryIndex.haveKitchen]); - let storeroom = matchQueries(req.result[req.queryIndex.allStoreroom], req.result[req.queryIndex.haveStoreroom]); - let warehouse = matchQueries(req.result[req.queryIndex.allWarehouse], req.result[req.queryIndex.haveWarehouse]); - let internet = matchQueries(req.result[req.queryIndex.allInternet], req.result[req.queryIndex.haveInternet]); - let broadband_internet = matchQueries(req.result[req.queryIndex.allBroadbandInternet], req.result[req.queryIndex.haveBroadbandInternet]); - let inside_bathroom = matchQueries(req.result[req.queryIndex.allInsideBathroom], req.result[req.queryIndex.haveInsideBathroom]); - let inside_kids_bathroom = matchQueries(req.result[req.queryIndex.allInsideKidsBathroom], req.result[req.queryIndex.haveInsideKidsBathroom]); - let eletric_energy = matchQueries(req.result[req.queryIndex.allEletricEnergy], req.result[req.queryIndex.haveEletricEnergy]); - let water_supply = matchQueries(req.result[req.queryIndex.allWaterSupply], req.result[req.queryIndex.haveWaterSupply]); - let filtered_water = matchQueries(req.result[req.queryIndex.allFilteredWater], req.result[req.queryIndex.haveFilteredWater]); - let sewage_treatment = matchQueries(req.result[req.queryIndex.allSewage], req.result[req.queryIndex.haveSewage]); - let special_multifunction_room = matchQueries(req.result[req.queryIndex.allMultifunctionRoom], req.result[req.queryIndex.haveMultifunctionRoom]); - let special_bathroom = matchQueries(req.result[req.queryIndex.allSpecialBathroom], req.result[req.queryIndex.haveSpecialBathroom]); - let adapted_building = matchQueries(req.result[req.queryIndex.allAdaptedBuilding], req.result[req.queryIndex.haveAdaptedBuilding]); - - req.result = [{ - school_place, - libraries, - libraries_reading_room, - computer_lab, - science_lab, - kids_park, - nursery, - sports_court, - covered_sports_court, - uncovered_sports_court, - director_room, - secretary, - teacher_room, - kitchen, - storeroom, - warehouse, - internet, - broadband_internet, - inside_bathroom, - inside_kids_bathroom, - eletric_energy, - water_supply, - filtered_water, - sewage_treatment, - special_multifunction_room, - special_bathroom, - adapted_building - }]; - - next(); -}, id2str.multitransform(false), response('infrastructure')); - -module.exports = infrastructureApp; diff --git a/src/libs/routes/liquidEnrollmentRatio.js b/src/libs/routes/liquidEnrollmentRatio.js deleted file mode 100644 index fd06c5281c870eb8ae208a7312e234e3501940c7..0000000000000000000000000000000000000000 --- a/src/libs/routes/liquidEnrollmentRatio.js +++ /dev/null @@ -1,429 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -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 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(); - -liquidEnrollmentRatioApp.use(cache('15 day')); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -liquidEnrollmentRatioApp.get('/year_range', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let distinct_years = []; - let new_result = []; - for (let i = 0; i < req.oldResult.length; i++) { - for (let j = 0; j < req.result.length; j++) { - if(req.oldResult[i].year == req.result[j].year) { - distinct_years.push(req.oldResult[i]); - } - } - } - new_result.push({start_year: distinct_years[distinct_years.length -1].year, end_year: distinct_years[0].year}); - req.result = new_result; - next(); -}, response('range')); - -liquidEnrollmentRatioApp.get('/years', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let new_result = [] - for (let i = 0; i < req.oldResult.length; i++) { - for (let j = 0; j < req.result.length; j++) { - if(req.oldResult[i].year == req.result[j].year) { - new_result.push(req.oldResult[i]); - } - } - } - req.result = new_result; - next(); -}, response('years')); - -liquidEnrollmentRatioApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'pnad\''); - next(); -}, query, response('source')); - -liquidEnrollmentRatioApp.get('/education_level_basic', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 4, name: 'Ensino Fundamental - anos iniciais'}, - {id: 5, name: 'Ensino Fundamental - anos finais'}, - {id: 6, name: 'Ensino Médio'} - ]; - next(); -}, response('education_level_basic')); - -liquidEnrollmentRatioApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -liquidEnrollmentRatioApp.get('/ethnic_group', (req, res, next) => { - req.result = [ - {id: 0, name: 'Sem declaração'}, - {id: 1, name: 'Branca'}, - {id: 2, name: 'Preta'}, - {id: 3, name: 'Parda'}, - {id: 4, name: 'Amarela'}, - {id: 5, name: 'Indígena'} - ]; - next(); -}, response('ethnic_group')); - -liquidEnrollmentRatioApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValue({ - name: 'ethnic_group', - table: '@', - tableField: 'cor_raca_id', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca_id' - } -}).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: 'gender', - table: '@', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'education_level_basic', - table: 'matricula', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_basic_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}); - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryPartial.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - // console.log('NEW OBJ'); - // console.log(newObj); - // remove total - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - // remove education_level_basic_id - index = keys.indexOf('education_level_basic_id'); - if(index > -1) keys.splice(index, 1); - // remove education_level_basic_name - index = keys.indexOf('education_level_basic_name'); - if(index > -1) keys.splice(index, 1); - let objMatch = null; - - for(let i = 0; i < queryTotal.length; ++i) { - let total = queryTotal[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(total[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - objMatch = total; - break; - } - } - - if(objMatch) { - // console.log('MATCH!!!!'); - // console.log(objMatch); - newObj.total = (result.total / objMatch.total) * 100; - newObj.partial = result.total; - newObj.denominator = objMatch.total - match.push(newObj); - } - }); - // console.log('TAMANHOS'); - // console.log(queryTotal.length); - // console.log(queryPartial.length); - // console.log(match.length); - return match; -} - - -liquidEnrollmentRatioApp.get('/', rqf.parse(),(req, res, next) => { - req.numerator = {}; - req.denominator = {}; - let liquidEnrollmentRatioApp = {}; - - req.sql.from('matricula') - .field('count(*)', 'total') - .field('matricula.ano_censo', 'year') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3') - - function ConvertMatricula(result) { - if (result == 1) { - return '(matricula.faixa_etaria_31_03 = 1 AND matricula.etapas_mod_ensino_segmento_id = 1)' - } else if (result == 2) { - return '(matricula.faixa_etaria_31_03 = 2 AND matricula.etapas_mod_ensino_segmento_id = 2)' - } else if (result == 4) { - return '(matricula.faixa_etaria_31_03 = 3 AND matricula.etapas_mod_ensino_segmento_id = 4)' - } else if (result == 5) { - return '(matricula.faixa_etaria_31_03 = 4 AND matricula.etapas_mod_ensino_segmento_id = 5)' - } else if (result == 6) { - return '(matricula.faixa_etaria_31_03 = 5 AND matricula.etapas_mod_ensino_segmento_id = 6)' - } - } - if ("education_level_basic" in req.filter) { - if (Array.isArray(req.filter.education_level_basic)) { - var string_query_enrollment = ''; - for(let i = 0; i < req.filter.education_level_basic.length - 1; i++) { - string_query_enrollment = string_query_enrollment + ConvertMatricula(req.filter.education_level_basic[i]) + ' OR '; - - } - string_query_enrollment = string_query_enrollment + ConvertMatricula(req.filter.education_level_basic[req.filter.education_level_basic.length - 1]); - delete req.filter.education_level_basic; - req.sql.where(string_query_enrollment); - req.sql.field('matricula.faixa_etaria_31_03', 'age_range') - req.sql.group('matricula.faixa_etaria_31_03', 'age_range'); - } - } else if ( "education_level_basic" in req.dims ) { - req.sql.field('matricula.faixa_etaria_31_03', 'age_range') - req.sql.where('(matricula.etapas_mod_ensino_segmento_id = 1 AND matricula.faixa_etaria_31_03 = 1) OR (matricula.etapas_mod_ensino_segmento_id = 2 AND matricula.faixa_etaria_31_03 = 2) OR (matricula.etapas_mod_ensino_segmento_id = 4 AND matricula.faixa_etaria_31_03 = 3) OR (matricula.etapas_mod_ensino_segmento_id = 5 AND matricula.faixa_etaria_31_03 = 4) OR (matricula.etapas_mod_ensino_segmento_id = 6 AND matricula.faixa_etaria_31_03 = 5)'); - req.sql.group('matricula.faixa_etaria_31_03', 'age_range'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.numerator = req.result; - req.resetSql(); - req.sql.field('sum(peso)', 'total') - .field('pnad.ano_censo','year') - .from('pnad') - .group('pnad.ano_censo') - .order('pnad.ano_censo') - - function convertPnad(result) { - if (result == 1) { - return 'pnad.faixa_etaria_31_03 = 1' - } else if (result == 2) { - return 'pnad.faixa_etaria_31_03 = 2' - } else if (result == 4) { - return 'pnad.faixa_etaria_31_03 = 3' - } else if (result == 5) { - return 'pnad.faixa_etaria_31_03 = 4' - } else if (result == 6) { - return 'pnad.faixa_etaria_31_03 = 5' - } - } - - //remove education_level_basic how filter and add faixa_etaria_31_03 in filter - if ("education_level_basic" in req.filter) { - if (Array.isArray(req.filter.education_level_basic)) { - var string_query = ''; - for(let i = 0; i < req.filter.education_level_basic.length - 1; i++) { - string_query = string_query + convertPnad(req.filter.education_level_basic[i]) + ' OR '; - } - string_query = string_query + convertPnad(req.filter.education_level_basic[req.filter.education_level_basic.length - 1]); - req.sql.where(string_query); - } - req.sql.field('pnad.faixa_etaria_31_03', 'age_range') - req.sql.group('pnad.faixa_etaria_31_03', 'age_range'); - } else if ( "education_level_basic" in req.dims ) { - req.sql.field('pnad.faixa_etaria_31_03','age_range') - req.sql.where('pnad.faixa_etaria_31_03 = 1 OR pnad.faixa_etaria_31_03 = 2 OR pnad.faixa_etaria_31_03 = 3 OR pnad.faixa_etaria_31_03 = 4 OR pnad.faixa_etaria_31_03 = 5') - req.sql.group('pnad.faixa_etaria_31_03', 'age_range'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); -}, rqf.parse(), (req, res, next) => { - if ("education_level_basic" in req.filter) { - delete req.filter.education_level_basic; - } - if ("education_level_basic" in req.dims) { - delete req.dims.education_level_basic; - } - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.denominator = req.result; - - //division to generate req.result final - req.result = [] - let liquidEnrollment = matchQueries(req.denominator, req.numerator); - req.result = liquidEnrollment; - next(); -}, response('liquidEnrollmentRatio')); - -module.exports = liquidEnrollmentRatioApp; diff --git a/src/libs/routes/outOfSchool.js b/src/libs/routes/outOfSchool.js deleted file mode 100644 index 16c5660f482cb1457c05ee81273d1847c1e55c81..0000000000000000000000000000000000000000 --- a/src/libs/routes/outOfSchool.js +++ /dev/null @@ -1,335 +0,0 @@ -/* -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(); - -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(); - -outOfSchoolApp.use(cache('15 day')); - -outOfSchoolApp.get('/year_range', (req, res, next) => { - req.sql.from('pnad') - .field('MIN(pnad.ano_censo)', 'start_year') - .field('MAX(pnad.ano_censo)', 'end_year') - .where('pnad.ano_censo >= 2007 AND pnad.ano_censo <= 2015'); - next(); -}, query, response('range')); - -outOfSchoolApp.get('/years', (req, res, next) => { - req.sql.from('pnad'). - field('DISTINCT pnad.ano_censo', 'year') - .where('pnad.ano_censo >= 2007 AND pnad.ano_censo <= 2015'); - next(); -}, query, response('years')); - -outOfSchoolApp.get('/full_age_range', (req, res, next) => { - req.result = [ - {id: 1, name: '0 a 3 anos'}, - {id: 2, name: '4 a 5 anos'}, - {id: 3, name: '6 a 10 anos'}, - {id: 4, name: '11 a 14 anos'}, - {id: 5, name: '15 a 17 anos'}, - {id: 6, name: '18 a 24 anos'}, - {id: 7, name: '25 a 29 anos'}, - {id: 8, name: '30 a 40 anos'}, - {id: 9, name: '41 a 50 anos'}, - {id: 10, name: '51 a 64 anos'}, - {id: 11, name: 'Mais de 64 anos'} - ]; - next(); -}, response('full_age_range')); - -outOfSchoolApp.get('/ethnic_group', (req, res, next) => { - req.result = [ - {id: 0, name: 'Sem declaração'}, - {id: 1, name: 'Branca'}, - {id: 2, name: 'Preta'}, - {id: 3, name: 'Parda'}, - {id: 4, name: 'Amarela'}, - {id: 5, name: 'Indígena'} - ]; - next(); -}, response('ethnic_group')); - -outOfSchoolApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -outOfSchoolApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -outOfSchoolApp.get('/fifth_household_income', (req, res, next) => { - req.result = [ - {id: 1, name: '20% menores'}, - {id: 2, name: '2o quinto'}, - {id: 3, name: '3o quinto'}, - {id: 4, name: '4o quinto'}, - {id: 5, name: '20% maiores'}, - {id: -1, name: 'Sem declaração'} - ]; - next(); -},response('fifth_household_income')); - -outOfSchoolApp.get('/extremes_household_income', (req, res, next) => { - req.result = [ - {id: 1, name: '10% menores'}, - {id: 2, name: '10% maiores'}, - {id: -1, name: 'Sem declaração'} - ]; - next(); -}, response('extremes_household_income')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'pnad' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'pnad' - } -}).addValue({ - name: 'ethnic_group', - table: 'pnad', - tableField: 'cor_raca_id', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca_id' - } -}).addValue({ - name: 'min_year', - table: 'pnad', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'pnad', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'pnad', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'pnad', - field: 'ano_censo' - } -}).addValue({ - name: 'full_age_range', - table: 'pnad', - tableField: 'faixa_etaria_31_03', - resultField: 'full_age_range_id', - where: { - relation: '=', - type: 'integer', - field: 'faixa_etaria_31_03' - } -}).addValue({ - name: 'gender', - table: 'pnad', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'location', - table: 'pnad', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'extremes_household_income', - table: 'pnad', - tableField: 'extremos_nivel_rendimento', - resultField: 'extremes_household_income_id', - where: { - relation: '=', - type: 'integer', - field: 'extremos_nivel_rendimento' - } -}).addValue({ - name: 'fifth_household_income', - table: 'pnad', - tableField: 'quintil_nivel_rendimento', - resultField: 'fifth_household_income_id', - where: { - relation: '=', - type: 'integer', - field: 'quintil_nivel_rendimento' - } -}); - -outOfSchoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.from('pnad') - .field('SUM(pnad.peso)', 'total') - .field('pnad.ano_censo', 'year') - .where('pnad.escolaridade_familiar >= 1 AND pnad.escolaridade_familiar <= 4 AND pnad.frequenta_escola_creche = 4') - .group('pnad.ano_censo') - .order('pnad.ano_censo'); - - next(); -}, query, addMissing(rqf), id2str.transform(), response('out_of_school')); - -// Versão para o SimCAQ -let simcaqRqf = new ReqQueryFields(); - -simcaqRqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'state', - table: 'populacao_fora_da_escola', - tableField: 'unidade_federativa', - resultField: 'state_id', - where: { - relation: '=', - type: 'integer', - field: 'unidade_federativa' - } -}).addValue({ - name: 'pfe', - table: 'populacao_fora_da_escola', - tableField: 'codigo_pfe', - resultField: 'pfe_id', - where: { - relation: '=', - type: 'integer', - field: 'codigo_pfe' - } -}).addValue({ - name: 'min_year', - table: 'populacao_fora_da_escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'populacao_fora_da_escola', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'populacao_fora_da_escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'populacao_fora_da_escola', - field: 'ano_censo' - } -}); - -outOfSchoolApp.get('/simcaq', simcaqRqf.parse(), simcaqRqf.build(), (req, res, next) => { - req.sql.from('populacao_fora_da_escola') - .field('SUM(populacao_fora_da_escola.pop_fora_escola)', 'total') - .field("'Brasil'", 'name') - .field('populacao_fora_da_escola.ano_censo') - .group('populacao_fora_da_escola.ano_censo') - .order('populacao_fora_da_escola.ano_censo'); - - next(); -}, 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')); - -module.exports = outOfSchoolApp; diff --git a/src/libs/routes/pibpercapita.js b/src/libs/routes/pibpercapita.js deleted file mode 100644 index 3cb91c5b17f7bba08022b5ad485b34fd06e8ce5f..0000000000000000000000000000000000000000 --- a/src/libs/routes/pibpercapita.js +++ /dev/null @@ -1,211 +0,0 @@ -/* -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(); - -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(); - -pibpercapitaApp.use(cache('15 day')); - -pibpercapitaApp.get('/year_range', (req, res, next) => { - req.sql.from('ibge_pib') - .field('MIN(ibge_pib.ano_censo)', 'start_year') - .field('MAX(ibge_pib.ano_censo)', 'end_year') - .where('ibge_pib.ano_censo > 2013'); - next(); -}, query, response('range')); - -pibpercapitaApp.get('/years', (req, res, next) => { - req.sql.from('ibge_pib'). - field('DISTINCT ibge_pib.ano_censo', 'year') - .where('ibge_pib.ano_censo > 2013'); - next(); -}, query, response('years')); - -pibpercapitaApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'ibge_pib\''); - next(); -}, query, response('source')); - -pibpercapitaApp.get('/income_level', (req, res, next) => { - req.result = [ - {id: 1, name: "1º quintil – 20% menores"}, - {id: 2, name: "2º quintil"}, - {id: 3, name: "3º quintil"}, - {id: 4, name: "4º quintil"}, - {id: 5, name: "5º quintil – 20% maiores"}, - ]; - next(); -}, response('income_level')); - -rqf.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: 'municipio_id', - table: 'ibge_pib' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'ibge_pib' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'ibge_pib' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'ibge_pib' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'regiao_id', - table: 'ibge_pib' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'ibge_pib' - } -}).addValue({ - name: 'min_year', - table: 'ibge_pib', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'ibge_pib', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'income_level', - table: 'ibge_pib', - tableField: 'nivel_renda_per_capita', - resultField: 'income_level_id', - where: { - relation: '=', - type: 'integer', - field: 'nivel_renda_per_capita' - } -}); - -pibpercapitaApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('ibge_pib') - .field('ibge_pib.pib_per_capita', 'total') - .field('ibge_pib.ano_censo', 'year') - .group('ibge_pib.ano_censo') - .group('ibge_pib.pib_per_capita') - .order('ibge_pib.ano_censo') - console.log("CiTy") - } else { - req.sql.from('ibge_pib') - .field('SUM(ibge_pib.pib)/SUM(ibge_pib.populacao)', 'total') - .field('ibge_pib.ano_censo', 'year') - .group('ibge_pib.ano_censo') - .order('ibge_pib.ano_censo') - } - next(); -}, query, (req, res, next) => { - req.result.forEach((i) => { - let value = parseFloat(i.total); - let isnum = /^\d+$/.test(value); - if (isnum == true) { - value = value.toFixed(2) - } - // console.log(i.total); - - let res = value.toString().split("."); - //rounding decimal. - let decimal = Math.round(res[1].toString().substring(0,2) + (".") + res[1].toString().substring(2,3)); - //case 0 after comma - if (res[1].toString().substring(0,1) == 0) { - i.total = parseFloat(res[0] + "." + "0" + decimal); - } else { - i.total = parseFloat(res[0] + "." + decimal); - } - // console.log(i.total); - }); - next(); - }, addMissing(rqf), id2str.transform(false), response("pibpercapita")); - - -module.exports = pibpercapitaApp; diff --git a/src/libs/routes/population.js b/src/libs/routes/population.js deleted file mode 100644 index ed644e9ee94259de5a484a9a43e951afb8d23043..0000000000000000000000000000000000000000 --- a/src/libs/routes/population.js +++ /dev/null @@ -1,173 +0,0 @@ -/* -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(); - -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(); - -populationApp.use(cache('15 day')); - -populationApp.get('/year_range', (req, res, next) => { - req.sql.from('ibge_populacao') - .field('MIN(ibge_populacao.ano_censo)', 'start_year') - .field('MAX(ibge_populacao.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -populationApp.get('/years', (req, res, next) => { - req.sql.from('ibge_populacao'). - field('DISTINCT ibge_populacao.ano_censo', 'year'); - next(); -}, query, response('years')); - -populationApp.get('/city_size', (req, res, next) => { - req.result = [ - {id: 1, name: "0 - 5000"}, - {id: 2, name: "5001 - 10000"}, - {id: 3, name: "10001 - 20000"}, - {id: 4, name: "20001 - 50000"}, - {id: 5, name: "50001 - 100000"}, - {id: 6, name: "100001 - 500000"}, - {id: 7, name: "mais que 500000"} - ]; - next(); -}, response('city_size')); - -rqf.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: 'municipio_id', - table: 'ibge_populacao' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'ibge_populacao' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'ibge_populacao' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'ibge_populacao' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'regiao_id', - table: 'ibge_populacao' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'ibge_populacao' - } -}).addValue({ - name: 'min_year', - table: 'ibge_populacao', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'ibge_populacao', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'city_size', - table: 'ibge_populacao', - tableField: 'porte', - resultField: 'city_size_id', - where: { - relation: '=', - type: 'integer', - field: 'porte' - } -}); - -populationApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.from('ibge_populacao') - .field('SUM(ibge_populacao.populacao)', 'total') - .field('ibge_populacao.ano_censo', 'year') - .group('ibge_populacao.ano_censo') - .order('ibge_populacao.ano_censo') - - next(); -}, query, addMissing(rqf), id2str.transform(false), response('population')); - -module.exports = populationApp; diff --git a/src/libs/routes/portalMec.js b/src/libs/routes/portalMec.js deleted file mode 100644 index 29a1be6b39fae2f62351e000bf3e80dd11df1fb0..0000000000000000000000000000000000000000 --- a/src/libs/routes/portalMec.js +++ /dev/null @@ -1,156 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -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 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(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'day', - table: 'docente', - tableField: 'nasc_dia', - resultField: 'born_day_id', - where: { - relation: '=', - type: 'integer', - table: 'docente', - field: 'nasc_dia' - } -}).addValue({ - name: 'month', - table: 'docente', - tableField: 'nasc_mes_id', - resultField: 'born_month', - where: { - relation: '=', - type: 'integer', - table: 'docente', - field: 'nasc_mes' - } -}).addValue({ - name: 'year', - table: 'docente', - tableField: 'nasc_ano_id', - resultField: 'born_year', - where: { - relation: '=', - type: 'integer', - table: 'docente', - field: 'nasc_ano' - } -}).addValue({ - name: 'teacher', - table: 'docente', - tableField: 'id', - resultField: 'teacher_id', - where: { - relation: '=', - type: 'integer', - table: 'docente', - field: 'id' - } -}).addValue({ - name: 'min_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'docente', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'docente', - field: 'ano_censo' - } -}); - -portalMecApp.get('/', rqf.parse(), (req, res, next) => { - - req.sql.field('docente.id') - .field('docente.ano_censo', 'year') - .field('docente.cod_quimica', 'Química') - .field('docente.cod_fisica', 'Física') - .field('docente.cod_matematica', 'Matemática') - .field('docente.cod_biologia', 'Biologia') - .field('docente.cod_ciencias', 'Ciências') - .field('docente.cod_literat_port', 'Língua/ Literatura Portuguesa') - .field('docente.cod_literat_ing', 'Língua/ Literatura estrangeira - Inglês') - .field('docente.cod_literat_esp', 'Língua/ Literatura estrangeira - Espanhol') - .field('docente.cod_literat_frances', 'Língua/ Literatura estrangeira - Francês') - .field('docente.literat_outra', 'Língua/ Literatura estrangeira - Outra') - .field('docente.cod_literat_indigena', 'Língua/ Literatura estrangeira - Língua Indígena') - .field('docente.cod_artes', 'Artes (Educação Artística, Teatro, Dança, Música, Artes Plásticas e outras)') - .field('docente.cod_ed_fisica', 'Educação Física') - .field('docente.cod_hist', 'História') - .field('docente.cod_geo', 'Geografia') - .field('docente.cod_filos', 'Filosofia') - .field('docente.cod_ensino_religioso', 'Ensino Religioso') - .field('docente.cod_estudos_sociais', 'Estudos Sociais') - .field('docente.cod_sociologia', 'Sociologia') - .field('docente.cod_inf_comp', 'Informática/ Computação') - .field('docente.cod_profissionalizante', 'Disciplinas profissionalizantes') - .field('docente.cod_disc_atendimento_especiais', 'Disciplinas voltadas ao atendimento às necessidades educacionais específicas dos alunos que são público alvo da educação especial e às práticas educacionais inclusivas') - .field('docente.cod_disc_diversidade_socio_cult', 'Disciplinas voltadas à diversidade sociocultural (Disciplinas pedagógicas)') - .field('docente.cod_libras', 'Libras') - .field('docente.cod_disciplina_pedag', 'Disciplinas pedagógicas') - .field('docente.cod_outras_disciplina', 'Outras disciplinas') - .from('docente') - next(); - -}, rqf.build(), query, response('portalMec')); - -module.exports = portalMecApp; diff --git a/src/libs/routes/portalMecInep.js b/src/libs/routes/portalMecInep.js deleted file mode 100644 index f8108ce46b77928357fa5cdd8232e11a9de9d414..0000000000000000000000000000000000000000 --- a/src/libs/routes/portalMecInep.js +++ /dev/null @@ -1,80 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -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 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(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'school_cod', - table: 'escola', - tableField: 'id', - resultField: 'school_cod_id', - where: { - relation: '=', - type: 'integer', - table: 'escola', - field: 'id' - } -}); - -portalMecInepApp.get('/', rqf.parse(), (req, res, next) => { - - req.sql.field('DISTINCT escola.id', 'id') - .field('escola.nome_escola', 'name') - .from('escola') - .join('estado', null, 'estado.id=escola.estado_id') - .field('estado.nome', 'state_name') - .join('municipio', null, 'municipio.id=escola.municipio_id') - .field('municipio.nome', 'city_name') - - next(); - -}, rqf.build(), query, response('portalMec_inep')); - -module.exports = portalMecInepApp; diff --git a/src/libs/routes/rateSchool.js b/src/libs/routes/rateSchool.js deleted file mode 100644 index a8e9253e38a7241721a61c262ede57c0d1d0562c..0000000000000000000000000000000000000000 --- a/src/libs/routes/rateSchool.js +++ /dev/null @@ -1,343 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -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')); - -let rqf = new ReqQueryFields(); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -rateSchoolApp.get('/year_range', (req, res, next) => { - req.sql.from('pnad') - .field('MIN(pnad.ano_censo)', 'start_year') - .field('MAX(pnad.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -rateSchoolApp.get('/years', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, response('years')); - -rateSchoolApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'pnad\''); - next(); -}, query, response('source')); - -rateSchoolApp.get('/ethnic_group_pnad', (req, res, next) => { - req.result = [ - {id: 0, name: 'Indígena'}, - {id: 1, name: 'Branca e amarela'}, - {id: 2, name: 'Preta e parda'}, - {id: 9, name: 'Sem declaração'} - ]; - next(); -}, response('ethnic_group_pnad')); - -rateSchoolApp.get('/age_range', (req, res, next) => { - req.result = [ - {id: 1, name: '0 a 3 anos'}, - {id: 2, name: '4 a 5 anos'}, - {id: 3, name: '6 a 10 anos'}, - {id: 4, name: '11 a 14 anos'}, - {id: 5, name: '15 a 17 anos'}, - {id: 6, name: '18 a 24 anos'} - ]; - next(); -}, response('age_range')); - -rateSchoolApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -rateSchoolApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -rateSchoolApp.get('/fifth_household_income', (req, res, next) => { - req.result = [ - {id: 1, name: '20% menores'}, - {id: 2, name: '2o quinto'}, - {id: 3, name: '3o quinto'}, - {id: 4, name: '4o quinto'}, - {id: 5, name: '20% maiores'}, - {id: -1, name: 'Sem declaração'} - ]; - next(); -},response('fifth_household_income')); - -rateSchoolApp.get('/extremes_household_income', (req, res, next) => { - req.result = [ - {id: 1, name: '10% menores'}, - {id: 2, name: '10% maiores'}, - {id: -1, name: 'Sem declaração'} - ]; - next(); -}, response('extremes_household_income')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'pnad' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'pnad' - } -}).addValue({ - name: 'ethnic_group_pnad', - table: 'pnad', - tableField: 'cor_raca', - resultField: 'ethnic_group_pnad_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca' - } -}).addValue({ - name: 'min_year', - table: 'pnad', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'pnad', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'pnad', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'pnad', - field: 'ano_censo' - } -}).addValue({ - name: 'age_range', - table: 'pnad', - tableField: 'faixa_etaria_31_03', - resultField: 'age_range_id', - where: { - relation: '=', - type: 'integer', - field: 'faixa_etaria_31_03' - } -}).addValue({ - name: 'gender', - table: 'pnad', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'location', - table: 'pnad', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'extremes_household_income', - table: 'pnad', - tableField: 'extremos_nivel_rendimento', - resultField: 'extremes_household_income_id', - where: { - relation: '=', - type: 'integer', - field: 'extremos_nivel_rendimento' - } -}).addValue({ - name: 'fifth_household_income', - table: 'pnad', - tableField: 'quintil_nivel_rendimento', - resultField: 'fifth_household_income_id', - where: { - relation: '=', - type: 'integer', - field: 'quintil_nivel_rendimento' - } -}); - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryTotal.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - // console.log('NEW OBJ'); - // console.log(newObj); - 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) { - // console.log(objMatch); - newObj.denominator = result.total; - newObj.partial = objMatch.total; - newObj.total = (objMatch.total / result.total) * 100; - match.push(newObj); - } - }); - - return match; -} - -rateSchoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - log.debug(req.sql.toParam()); - if ("age_range" in req.filter || "age_range" in req.dims) { - let freq_total = req.sql.clone(); - freq_total.field('sum(pnad.peso)', 'total') - .field('pnad.ano_censo','year') - .from('pnad') - .group('pnad.ano_censo') - .order('pnad.ano_censo') - .where('pnad.faixa_etaria_31_03 < 7') - req.queryIndex.freq_total = req.querySet.push(freq_total) - 1; - - let freq_nursery = req.sql.clone(); - freq_nursery.field('sum(pnad.peso)', 'total') - .field('pnad.ano_censo','year') - .from('pnad') - .group('pnad.ano_censo') - .order('pnad.ano_censo') - .where('pnad.frequenta_escola_creche = 2') - .where('pnad.faixa_etaria_31_03 < 7') - req.queryIndex.freq_nursery = req.querySet.push(freq_nursery) - 1; - } - next(); -}, multiQuery, (req, res, next) => { - if ("age_range" in req.filter || "age_range" in req.dims) { - log.debug(req.result[req.queryIndex.freq_total]); - log.debug(req.result[req.queryIndex.freq_nursery]) - let school_attendance_rate = matchQueries(req.result[req.queryIndex.freq_total], req.result[req.queryIndex.freq_nursery]); - req.result = school_attendance_rate; - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - log.debug(req.result) - 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 deleted file mode 100644 index f36760f3ba4f45ad56c98a95463ab370f5a6261a..0000000000000000000000000000000000000000 --- a/src/libs/routes/region.js +++ /dev/null @@ -1,82 +0,0 @@ -/* -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(); - -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 config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -regionApp.use(cache('15 day')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addValue({ - name: 'id', - table: '@', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id', - table: '@' - } -}).addField({ - name: 'search', - field: false, - where: true -}).addValueToField({ - name: 'name', - table: '@', - tableField: 'nome', - where: { - relation: 'LIKE', - type: 'string', - field: 'nome', - table: '@' - } -}, 'search'); - -regionApp.get('/', rqf.parse(), (req, res, next) => { - req.sql.from('regiao') - .field('id') - .field('nome', 'name'); - next(); -}, rqf.build(), query, response('region')); - -module.exports = regionApp; diff --git a/src/libs/routes/resetToken.js b/src/libs/routes/resetToken.js deleted file mode 100644 index 5fa96b018c68f827e9ea203d5a652e04b0329704..0000000000000000000000000000000000000000 --- a/src/libs/routes/resetToken.js +++ /dev/null @@ -1,101 +0,0 @@ -/* -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 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 deleted file mode 100644 index 13abdfa8b8ee17f10af1f3c946f903f9353eef9c..0000000000000000000000000000000000000000 --- a/src/libs/routes/school.js +++ /dev/null @@ -1,570 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const request = require(`request`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); -let rqfCount = new ReqQueryFields(); - -// Return location -schoolApp.get('/year_range', cache('15 day'), (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -schoolApp.get('/years', cache('15 day'), (req, res, next) => { - req.sql.from('escola'). - field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -schoolApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'escola\''); - next(); -}, query, response('source')); - -schoolApp.get('/location', cache('15 day'), (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -schoolApp.get('/rural_location', cache('15 day'), (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -schoolApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -schoolApp.get('/adm_dependency_detailed', cache('15 day'), (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -schoolApp.get('/government_agreement', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('government_agreement')); - -schoolApp.get('/agreement', cache('15 day'), (req, res, next) => { - req.result = [ - {id: 1, name: 'Municipal'}, - {id: 2, name: 'Estadual'}, - {id: 3, name: 'Estadual e Municipal'} - ]; - next(); -}, response('agreement')); - -schoolApp.get('/education_day_care_child', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_day_care_child')); - -schoolApp.get('/education_preschool_child', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_preschool_child')); - -schoolApp.get('/education_begin_elementary_school', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_begin_elementary_school')); - -schoolApp.get('/education_end_elementary_school', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_end_elementary_school')); - -schoolApp.get('/education_middle_school', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_middle_school')); - -schoolApp.get('/education_professional', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_professional')); - -schoolApp.get('/education_eja', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_eja')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addValue({ - name: 'id', - table: 'escola', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '=', - type: 'integer', - field: 'ano_censo', - table: 'escola' - } -}).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: 'municipio_id', - foreignTable: 'escola' - } -}, '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: 'estado_id', - foreignTable: 'escola' - } -}, 'search'); - -rqfCount.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'id', - table: 'escola', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'filter').addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '=', - type: 'integer', - field: 'ano_censo', - table: 'escola' - } -}).addValue({ - name: 'location', - table: 'escola', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'escola', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'adm_dependency', - table: 'escola', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'escola', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'government_agreement', - table: 'escola', - tableField: 'conveniada_pp', - resultField: 'government_agreement_id', - where: { - relation: '=', - type: 'boolean', - field: 'conveniada_pp' - } -}).addValue({ - name: 'agreement', - table: 'escola', - tableField: 'tipo_convenio_pp', - resultField: 'agreement_id', - where: { - relation: '=', - type: 'integer', - field: 'tipo_convenio_pp' - } -}).addValue({ - name: 'education_day_care_child', - table: 'escola', - tableField: 'reg_infantil_creche_t1', - resultField: 'education_day_care_child_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_infantil_creche_t1' - } -}).addValue({ - name: 'education_preschool_child', - table: 'escola', - tableField: 'reg_infantil_preescola_t1', - resultField: 'education_preschool_child_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_infantil_preescola_t1' - } -}).addValue({ - name: 'education_begin_elementary_school', - table: 'escola', - tableField: 'reg_fund_ai_t1', - resultField: 'education_begin_elementary_school_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_fund_ai_t1' - } -}).addValue({ - name: 'education_end_elementary_school', - table: 'escola', - tableField: 'reg_fund_af_t1', - resultField: 'education_end_elementary_school_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_fund_af_t1' - } -}).addValue({ - name: 'education_middle_school', - table: 'escola', - tableField: 'reg_medio_medio_t1', - resultField: 'education_middle_school_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_medio_medio_t1' - } -}).addValue({ - name: 'education_professional', - table: 'escola', - tableField: 'educacao_profissional', - resultField: 'education_professional_id', - where: { - relation: '=', - type: 'boolean', - field: 'educacao_profissional' - } -}).addValue({ - name: 'education_eja', - table: 'escola', - tableField: 'ensino_eja', - resultField: 'education_eja_id', - where: { - relation: '=', - type: 'boolean', - field: 'ensino_eja' - } -}).addValue({ - name: 'min_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'school_building', - table: 'escola', - tableField: 'local_func_predio_escolar', - resultField: 'school_building', - where: { - relation: '=', - type: 'boolean', - field: 'local_func_predio_escolar' - } -}); -schoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - - req.sql.from('escola') - .field('escola.id') - .field('escola.ano_censo', 'year') - .field('escola.nome_escola', 'name') - .field('escola.estado_id', 'state_id') - .field('escola.municipio_id', 'city_id'); - next(); -}, query, response('school')); - -schoolApp.get('/count', cache('15 day'), rqfCount.parse(), rqfCount.build(), (req, res, next) => { - - req.sql.from('escola') - .field('COUNT(escola.id)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .order('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1 AND (escola.ensino_regular = 1 OR escola.ensino_eja=1 or escola.educacao_profissional=1)'); - 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 deleted file mode 100644 index f805e8827768eec1c4c6122c25da4be2672d43ce..0000000000000000000000000000000000000000 --- a/src/libs/routes/schoolInfrastructure.js +++ /dev/null @@ -1,728 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -infrastructureApp.use(cache('15 day')); - -infrastructureApp.get('/year_range', (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -infrastructureApp.get('/years', (req, res, next) => { - req.sql.from('escola') - .field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -infrastructureApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'escola\''); - next(); -}, query, response('source')); - -infrastructureApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -infrastructureApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -infrastructureApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -infrastructureApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'id', - resultField: 'city_id', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'filter').addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'id', - resultField: 'state_id', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}, 'filter').addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'location', - table: 'escola', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'escola', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'adm_dependency', - table: 'escola', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'escola', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'min_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - -function matchQueries(queryTotal, queryPartial, queryNeeded, zeroPercentage=false) { - 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 partialMatch = null; - let needMatch = 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) { - partialMatch = partial; - break; - } - } - - if(queryPartial.length == 0) { - partialMatch = JSON.parse(JSON.stringify(result)); - partialMatch.total = 0; - } - - for(let i = 0; i < queryNeeded.length; ++i) { - let needed = queryNeeded[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(needed[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - needMatch = needed; - break; - } - } - - if(queryNeeded.length == 0) { - needMatch = JSON.parse(JSON.stringify(result)); - 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); - } - }); - - return match; -} - -infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - // Local de funcionamento - let allSchools = req.sql.clone(); - allSchools.from('escola').field('COUNT(escola.id)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1') - .where('escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1') - .where('escola.local_func_predio_escolar = 1') - .where('escola.dependencia_adm_id <= 3') - .order('escola.ano_censo'); - req.queryIndex.allSchools = req.querySet.push(allSchools) - 1; - - let allUrbanSchools = allSchools.clone(); - allUrbanSchools.where('escola.localizacao_id = 1'); - req.queryIndex.allUrbanSchools = req.querySet.push(allUrbanSchools) - 1; - - let allCountrySchools = allSchools.clone(); - allCountrySchools.where('escola.localizacao_id = 2'); - req.queryIndex.allCountrySchools = req.querySet.push(allCountrySchools) - 1; - - let allSchoolsNotSchoolBuilding = req.sql.clone(); - allSchoolsNotSchoolBuilding.from('escola').field('COUNT(escola.id)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1') - .where('escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1') - .where('escola.local_func_predio_escolar = 0') - .where('escola.dependencia_adm_id <= 3') - .order('escola.ano_censo'); - req.queryIndex.allSchoolsNotSchoolBuilding = req.querySet.push(allSchoolsNotSchoolBuilding) - 1; - - // Bibliotecas - req.queryIndex.allLibraries = req.queryIndex.allUrbanSchools; - - let haveLibraries = allUrbanSchools.clone(); - haveLibraries.where('escola.biblioteca = 1'); - req.queryIndex.haveLibraries = req.querySet.push(haveLibraries) - 1; - - let needLibraries = allUrbanSchools.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(); - haveLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = true'); - req.queryIndex.haveLibrariesReadingRoom = req.querySet.push(haveLibrariesReadingRoom) - 1; - - let needLibrariesReadingRoom = allCountrySchools.clone(); - needLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = false'); - req.queryIndex.needLibrariesReadingRoom = req.querySet.push(needLibrariesReadingRoom) - 1; - - // Laboratório de informática - 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'); - req.queryIndex.allInfLab = req.querySet.push(allInfLab) - 1; - - let haveInfLab = allInfLab.clone(); - haveInfLab.where('escola.lab_informatica = 1'); - req.queryIndex.haveInfLab = req.querySet.push(haveInfLab) - 1; - - let needInfLab = allInfLab.clone(); - needInfLab.where('escola.lab_informatica = 0'); - req.queryIndex.needInfLab = req.querySet.push(needInfLab) - 1; - - // 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'); - req.queryIndex.allScienceLab = req.querySet.push(allScienceLab) - 1; - - let haveScienceLab = allScienceLab.clone(); - haveScienceLab.where('escola.lab_ciencias = true'); - req.queryIndex.haveScienceLab = req.querySet.push(haveScienceLab) - 1; - - let needScienceLab = allScienceLab.clone(); - needScienceLab.where('escola.lab_ciencias = false'); - req.queryIndex.needScienceLab = req.querySet.push(needScienceLab) - 1; - - // Parque infantil - let allKidsPark = allSchools.clone(); - allKidsPark.where('escola.reg_infantil_creche = 1 OR escola.reg_infantil_preescola = 1 OR escola.reg_fund_ai = 1'); - req.queryIndex.allKidsPark = req.querySet.push(allKidsPark) - 1; - - let haveKidsPark = allKidsPark.clone(); - haveKidsPark.where('escola.parque_infantil = 1'); - req.queryIndex.haveKidsPark = req.querySet.push(haveKidsPark) - 1; - - let needKidsPark = allKidsPark.clone(); - needKidsPark.where('escola.parque_infantil = 0'); - req.queryIndex.needKidsPark = req.querySet.push(needKidsPark) - 1; - - // Berçário - let allCribs = allSchools.clone(); - allCribs.where('escola.reg_infantil_creche = 1'); - req.queryIndex.allCribs = req.querySet.push(allCribs) - 1; - - let haveCribs = allCribs.clone(); - haveCribs.where('escola.bercario = 1'); - req.queryIndex.haveCribs = req.querySet.push(haveCribs) - 1; - - let needCribs = allCribs.clone(); - needCribs.where('escola.bercario = 0'); - req.queryIndex.needCribs = req.querySet.push(needCribs) - 1; - - // 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'); - req.queryIndex.allSportsCourt = req.querySet.push(allSportsCourt) - 1; - - let haveSportsCourt = allSportsCourt.clone(); - haveSportsCourt.where('escola.quadra_esportes = 1'); - req.queryIndex.haveSportsCourt = req.querySet.push(haveSportsCourt) - 1; - - let needSportsCourt = allSportsCourt.clone(); - needSportsCourt.where('escola.quadra_esportes = 0'); - req.queryIndex.needSportsCourt = req.querySet.push(needSportsCourt) - 1; - - // Cobertura de quadra esportiva - let allSportsCourtCoverage = allSportsCourt.clone(); - allSportsCourtCoverage.where('escola.quadra_esportes_descoberta = 1'); - req.queryIndex.allSportsCourtCoverage = req.querySet.push(allSportsCourtCoverage); - - req.queryIndex.haveSportsCourtCoverage = req.queryIndex.allSportsCourtCoverage; - - req.queryIndex.needSportsCourtCoverage = req.queryIndex.allSportsCourtCoverage; - - // Pátio - req.queryIndex.allCourtyard = req.queryIndex.allSchools; - - let haveCourtyard = allSchools.clone(); - haveCourtyard.where('escola.patio = 2 OR escola.patio = 1'); - req.queryIndex.haveCourtyard = req.querySet.push(haveCourtyard) - 1; - - let needCourtyard = allSchools.clone(); - needCourtyard.where('escola.patio = 1'); - req.queryIndex.needCourtyard = req.querySet.push(needCourtyard) - 1; - - // Cobertura do Pátio - let allCourtyardCoverage = allSchools.clone(); - allCourtyardCoverage.where('escola.patio = 1'); - req.queryIndex.allCourtyardCoverage = req.querySet.push(allCourtyardCoverage) - 1; - - req.queryIndex.haveCourtyardCoverage = req.queryIndex.allCourtyardCoverage; - - req.queryIndex.needCourtyardCoverage = req.queryIndex.allCourtyardCoverage; - - // Sala de direção - req.queryIndex.allDirectorRoom = req.queryIndex.allLibraries; - - let haveDirectorRoom = allUrbanSchools.clone(); - haveDirectorRoom.where('escola.sala_diretoria = 1'); - req.queryIndex.haveDirectorRoom = req.querySet.push(haveDirectorRoom) - 1; - - let needDirectorRoom = allUrbanSchools.clone(); - needDirectorRoom.where('escola.sala_diretoria = 0'); - req.queryIndex.needDirectorRoom = req.querySet.push(needDirectorRoom) - 1; - - // Secretaria - req.queryIndex.allSecretary = req.queryIndex.allSchools; - - let haveSecretary = allSchools.clone(); - haveSecretary.where('escola.secretaria = 1'); - req.queryIndex.haveSecretary = req.querySet.push(haveSecretary) - 1; - - let needSecretary = allSchools.clone(); - needSecretary.where('escola.secretaria = 0'); - req.queryIndex.needSecretary = req.querySet.push(needSecretary) - 1; - - // Sala de professores - req.queryIndex.allTeacherRoom = req.queryIndex.allSchools; - - let haveTeacherRoom = allSchools.clone(); - haveTeacherRoom.where('escola.sala_professor = 1'); - req.queryIndex.haveTeacherRoom = req.querySet.push(haveTeacherRoom) - 1; - - let needTeacherRoom = allSchools.clone(); - needTeacherRoom.where('escola.sala_professor = 0'); - req.queryIndex.needTeacherRoom = req.querySet.push(needTeacherRoom) - 1; - - // Cozinha - req.queryIndex.allKitchen = req.queryIndex.allSchools; - - let haveKitchen = allSchools.clone(); - haveKitchen.where('escola.cozinha = 1'); - req.queryIndex.haveKitchen = req.querySet.push(haveKitchen) - 1; - - let needKitchen = allSchools.clone(); - needKitchen.where('escola.cozinha = 0'); - req.queryIndex.needKitchen = req.querySet.push(needKitchen) - 1; - - // Despensa - req.queryIndex.allStoreroom = req.queryIndex.allSchools; - - let haveStoreroom = allSchools.clone(); - haveStoreroom.where('escola.despensa = 1'); - req.queryIndex.haveStoreroom = req.querySet.push(haveStoreroom) - 1; - - let needStoreroom = allSchools.clone(); - needStoreroom.where('escola.despensa = 0'); - req.queryIndex.needStoreroom = req.querySet.push(needStoreroom) - 1; - - // Almoxarifado - req.queryIndex.allWarehouse = req.queryIndex.allSchools; - - let haveWarehouse = allSchools.clone(); - haveWarehouse.where('escola.almoxarifado = 1'); - req.queryIndex.haveWarehouse = req.querySet.push(haveWarehouse) - 1; - - let needWarehouse = allSchools.clone(); - needWarehouse.where('escola.almoxarifado = 1'); - req.queryIndex.needWarehouse = req.querySet.push(needWarehouse) - 1; - - // Internet - req.queryIndex.allInternet = req.queryIndex.allLibrariesReadingRoom; - - let haveInternet = allCountrySchools.clone(); - haveInternet.where('escola.internet = 1'); - req.queryIndex.haveInternet = req.querySet.push(haveInternet) - 1; - - let needInternet = allCountrySchools.clone(); - needInternet.where('escola.internet = 0'); - req.queryIndex.needInternet = req.querySet.push(needInternet) - 1; - - // Internet banda larga - req.queryIndex.allBroadbandInternet = req.queryIndex.allLibraries; - - let haveBroadbandInternet = allUrbanSchools.clone(); - haveBroadbandInternet.where('escola.internet_banda_larga = 1'); - req.queryIndex.haveBroadbandInternet = req.querySet.push(haveBroadbandInternet) - 1; - - let needBroadbandInternet = allUrbanSchools.clone(); - needBroadbandInternet.where('escola.internet_banda_larga = 0'); - req.queryIndex.needBroadbandInternet = req.querySet.push(needBroadbandInternet) - 1; - - // Sanitário dentro do prédio - req.queryIndex.allInsideBathroom = req.queryIndex.allSchools; - - let haveInsideBathroom = allSchools.clone(); - haveInsideBathroom.where('escola.sanitario_dentro_predio = 1'); - req.queryIndex.haveInsideBathroom = req.querySet.push(haveInsideBathroom) - 1; - - let needInsideBathroom = allSchools.clone(); - needInsideBathroom.where('escola.sanitario_dentro_predio = 0'); - req.queryIndex.needInsideBathroom = req.querySet.push(needInsideBathroom) - 1; - - // Banheiro adequado para educação infantil dentro do prédio - req.queryIndex.allInsideKidsBathroom = req.queryIndex.allKidsPark; - - let haveInsideKidsBathroom = allKidsPark.clone(); - haveInsideKidsBathroom.where('escola.sanitario_ei = 1'); - req.queryIndex.haveInsideKidsBathroom = req.querySet.push(haveInsideKidsBathroom) - 1; - - let needInsideKidsBathroom = allKidsPark.clone(); - needInsideKidsBathroom.where('escola.sanitario_ei = 0'); - req.queryIndex.needInsideKidsBathroom = req.querySet.push(needInsideKidsBathroom) - 1; - - // Fornecimento de energia - req.queryIndex.allEletricPower = req.queryIndex.allSchools; - - let haveEletricPower = allSchools.clone(); - haveEletricPower.where('escola.fornecimento_energia = 1'); - req.queryIndex.haveEletricPower = req.querySet.push(haveEletricPower) - 1; - - let needEletricPower = allSchools.clone(); - needEletricPower.where('escola.fornecimento_energia = 0'); - req.queryIndex.needEletricPower = req.querySet.push(needEletricPower) - 1; - - // Abastecimento de água - req.queryIndex.allWaterSupply = req.queryIndex.allSchools; - - let haveWaterSupply = allSchools.clone(); - haveWaterSupply.where('escola.fornecimento_agua = 1'); - req.queryIndex.haveWaterSupply = req.querySet.push(haveWaterSupply) - 1; - - let needWaterSupply = allSchools.clone(); - needWaterSupply.where('escola.fornecimento_agua = 0'); - req.queryIndex.needWaterSupply = req.querySet.push(needWaterSupply) - 1; - - // Água filtrada - req.queryIndex.allFilteredWater = req.queryIndex.allSchools; - - let haveFilteredWater = allSchools.clone(); - haveFilteredWater.where('escola.agua_filtrada = 1'); - req.queryIndex.haveFilteredWater = req.querySet.push(haveFilteredWater) - 1; - - let needFilteredWater = allSchools.clone(); - needFilteredWater.where('escola.agua_filtrada = 0'); - req.queryIndex.needFilteredWater = req.querySet.push(needFilteredWater) - 1; - - // Coleta de esgoto - req.queryIndex.allSewage = req.queryIndex.allSchools; - - let haveSewage = allSchools.clone(); - haveSewage.where('escola.esgoto_sanitario = 1'); - req.queryIndex.haveSewage = req.querySet.push(haveSewage) - 1; - - let needSewage = allSchools.clone(); - needSewage.where('escola.esgoto_sanitario = 0'); - req.queryIndex.needSewage = req.querySet.push(needSewage) - 1; - - // Dependências adaptada para pessoas com deficiências - req.queryIndex.allAdaptedBuilding = req.queryIndex.allSchools; - - let haveAdaptedBuilding = allSchools.clone(); - haveAdaptedBuilding.where('escola.dependencias_pne = 1'); - req.queryIndex.haveAdaptedBuilding = req.querySet.push(haveAdaptedBuilding) - 1; - - let needAdaptedBuilding = allSchools.clone(); - needAdaptedBuilding.where('escola.dependencias_pne = 0'); - req.queryIndex.needAdaptedBuilding = req.querySet.push(needAdaptedBuilding) - 1; - - // Banheiros adaptados para pessoas com deficiências - req.queryIndex.allSpecialBathroom = req.queryIndex.allSchools; - - let haveSpecialBathroom = allSchools.clone(); - haveSpecialBathroom.where('escola.sanitario_pne = 1'); - req.queryIndex.haveSpecialBathroom = req.querySet.push(haveSpecialBathroom) - 1; - - let needSpecialBathroom = allSchools.clone(); - needSpecialBathroom.where('escola.sanitario_pne = 1'); - 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]; - let schools_not_in_school_buildings = req.result[req.queryIndex.allSchoolsNotSchoolBuilding]; - // Faz o matching entre os resultados - let libraries = matchQueries(req.result[req.queryIndex.allLibraries], req.result[req.queryIndex.haveLibraries], req.result[req.queryIndex.needLibraries]); - let libraries_reading_room = matchQueries(req.result[req.queryIndex.allLibrariesReadingRoom], req.result[req.queryIndex.haveLibrariesReadingRoom], req.result[req.queryIndex.needLibrariesReadingRoom]); - let computer_lab = matchQueries(req.result[req.queryIndex.allInfLab], req.result[req.queryIndex.haveInfLab], req.result[req.queryIndex.needInfLab]); - let science_lab = matchQueries(req.result[req.queryIndex.allScienceLab], req.result[req.queryIndex.haveScienceLab], req.result[req.queryIndex.needScienceLab]); - let kids_park = matchQueries(req.result[req.queryIndex.allKidsPark], req.result[req.queryIndex.haveKidsPark], req.result[req.queryIndex.needKidsPark]); - let nursery = matchQueries(req.result[req.queryIndex.allCribs], req.result[req.queryIndex.haveCribs], req.result[req.queryIndex.needCribs]); - let sports_court = matchQueries(req.result[req.queryIndex.allSportsCourt], req.result[req.queryIndex.haveSportsCourt], req.result[req.queryIndex.needSportsCourt]); - let sports_court_coverage = matchQueries(req.result[req.queryIndex.allSportsCourtCoverage], req.result[req.queryIndex.haveSportsCourtCoverage], req.result[req.queryIndex.needSportsCourtCoverage], true); - let courtyard = matchQueries(req.result[req.queryIndex.allCourtyard], req.result[req.queryIndex.haveCourtyard], req.result[req.queryIndex.needCourtyard]); - let courtyard_coverage = matchQueries(req.result[req.queryIndex.allCourtyardCoverage], req.result[req.queryIndex.haveCourtyardCoverage], req.result[req.queryIndex.needCourtyardCoverage], true); - let director_room = matchQueries(req.result[req.queryIndex.allDirectorRoom], req.result[req.queryIndex.haveDirectorRoom], req.result[req.queryIndex.needDirectorRoom]); - let secretary = matchQueries(req.result[req.queryIndex.allSecretary], req.result[req.queryIndex.haveSecretary], req.result[req.queryIndex.needSecretary]); - let teacher_room = matchQueries(req.result[req.queryIndex.allTeacherRoom], req.result[req.queryIndex.haveTeacherRoom], req.result[req.queryIndex.needTeacherRoom]); - let kitchen = matchQueries(req.result[req.queryIndex.allKitchen], req.result[req.queryIndex.haveKitchen], req.result[req.queryIndex.needKitchen]); - let storeroom = matchQueries(req.result[req.queryIndex.allStoreroom], req.result[req.queryIndex.haveStoreroom], req.result[req.queryIndex.needStoreroom]); - let warehouse = matchQueries(req.result[req.queryIndex.allWarehouse], req.result[req.queryIndex.haveWarehouse], req.result[req.queryIndex.needWarehouse]); - let internet = matchQueries(req.result[req.queryIndex.allInternet], req.result[req.queryIndex.haveInternet], req.result[req.queryIndex.needInternet]); - let broadband_internet = matchQueries(req.result[req.queryIndex.allBroadbandInternet], req.result[req.queryIndex.haveBroadbandInternet], req.result[req.queryIndex.needBroadbandInternet]); - let inside_bathroom = matchQueries(req.result[req.queryIndex.allInsideBathroom], req.result[req.queryIndex.haveInsideBathroom], req.result[req.queryIndex.needInsideBathroom]); - let inside_kids_bathroom = matchQueries(req.result[req.queryIndex.allInsideKidsBathroom], req.result[req.queryIndex.haveInsideKidsBathroom], req.result[req.queryIndex.needInsideKidsBathroom]); - let eletrical_power = matchQueries(req.result[req.queryIndex.allEletricPower], req.result[req.queryIndex.haveEletricPower], req.result[req.queryIndex.needEletricPower]); - let water_supply = matchQueries(req.result[req.queryIndex.allWaterSupply], req.result[req.queryIndex.haveWaterSupply], req.result[req.queryIndex.needWaterSupply]); - let filtered_water = matchQueries(req.result[req.queryIndex.allFilteredWater], req.result[req.queryIndex.haveFilteredWater], req.result[req.queryIndex.needFilteredWater]); - let sewage = matchQueries(req.result[req.queryIndex.allSewage], req.result[req.queryIndex.haveSewage], req.result[req.queryIndex.needSewage]); - let adapted_building = matchQueries(req.result[req.queryIndex.allAdaptedBuilding], req.result[req.queryIndex.haveAdaptedBuilding], req.result[req.queryIndex.needAdaptedBuilding]); - let adapted_bathroom = matchQueries(req.result[req.queryIndex.allSpecialBathroom], req.result[req.queryIndex.haveSpecialBathroom], req.result[req.queryIndex.needSpecialBathroom]); - - req.result = [{ - schools_in_school_buildings, - urban_schools_in_school_buildings, - country_schools_in_school_buildings, - schools_not_in_school_buildings, - libraries, - libraries_reading_room, - computer_lab, - science_lab, - kids_park, - nursery, - sports_court, - sports_court_coverage, - courtyard, - courtyard_coverage, - director_room, - secretary, - teacher_room, - kitchen, - storeroom, - warehouse, - internet, - broadband_internet, - inside_bathroom, - inside_kids_bathroom, - eletric_energy: eletrical_power, - water_supply, - filtered_water, - sewage_treatment: sewage, - adapted_building, - special_bathroom: adapted_bathroom - }]; - - next(); -}, id2str.multitransform(false), response('infrastructure')); - -module.exports = infrastructureApp; diff --git a/src/libs/routes/simulation.js b/src/libs/routes/simulation.js deleted file mode 100644 index 8003b54dcdf7eea11d98e051de865c919b896744..0000000000000000000000000000000000000000 --- a/src/libs/routes/simulation.js +++ /dev/null @@ -1,187 +0,0 @@ -/* -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(); - -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 Simulation = require(`${libs}/models/simulation`); - -const PQR = require(`${libs}/models/pqr`); - -const passport = require('passport'); - -simulationApp.get('/time', (req, res, next) => { - const maxTime = parseInt(req.query.max_time, 10); - if(isNaN(maxTime)) { - res.status(400); - next({ - status: 400, - message: 'Invalid value for mandatory parameter max_time' - }); - } - res.json({ - result: Array.apply(null, {length: maxTime}).map(Number.call, Number).map((i)=>i+1) - }); -}); - -simulationApp.get('/pqr', (req, res) => { - PQR.findOne((err, pqr) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json(pqr); - }); -}); - -simulationApp.put('/pqr', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - - PQR.findOne((err, pqr) => { - if(err) { - log.error(err) - return next({err}); - } - - if(!user.admin) { - log.info(`Usuário ${user.email} tentou alterar o PQR, mas não tem privilégio`); - res.statusCode = 401; - return next({err: { msg: 'Unauthorized'}}); - } - pqr.content = req.body.content || pqr.content; - pqr.save((err) => { - if(err) { - log.error(err); - return next({err}); - } - res.json({msg: 'PQR updated'}) - }); - }); -}); - -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'); - query.exec((err, simulations) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json(simulations); - }); - - // Simulation.find({userId: user._id}, (err, simulations) => { - // if(err) { - // log.error(err); - // return next({err}); - // } - - // res.json(simulations); - // }); -}); - -simulationApp.post('/', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - - let simulation = new Simulation({ - userId: user._id, - content: req.body.content, - name: req.body.name - }); - - simulation.save((err) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json({msg: 'Simulation created', simulation}); - }) -}); - -simulationApp.get('/:id', passport.authenticate('bearer', { session: false }), (req, res) => { - let user = req.user.toObject(); - - Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json(simulation); - }); -}); - -simulationApp.put('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - - Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => { - if(err) { - log.error(err); - return next({err}); - } - - if(!simulation) { - res.statusCode = 404; - return next({err: { msg: 'Simulation not found'}}); - } - - simulation.content = req.body.content || simulation.content; - simulation.name = req.body.name || simulation.name; - simulation.updatedAt = Date.now(); - - simulation.save((err) => { - if(err) { - log.error(err); - return next(err); - } - - res.json(simulation); - }); - }); -}); - -simulationApp.delete('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - - Simulation.remove({_id: req.params.id, userId: user._id}, (err, simulation) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json({msg: 'Simulation removed'}); - }); -}); - -module.exports = simulationApp; diff --git a/src/libs/routes/siope.js b/src/libs/routes/siope.js deleted file mode 100644 index 615e2225477a1631df2b862f3e75276632a183b0..0000000000000000000000000000000000000000 --- a/src/libs/routes/siope.js +++ /dev/null @@ -1,186 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -siopeApp.use(cache('15 day')); - -siopeApp.get('/years', (req, res, next) => { - req.sql.from('siope_mun') - .field('DISTINCT siope_mun.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('siope_uf') - .field('DISTINCT siope_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -rqf.addField({ - name: 'filter', - field: true, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'siope_mun' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'siope_mun' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: ['id','nome','sigla'], - resultField: ['state_id','state_name','state_abbreviation'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).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' - } -}); - - - -siopeApp.get('/', rqf.parse(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - let siopeUf = req.sql.clone(); - siopeUf.from('siope_uf') - .field('siope_uf.ano_censo', 'year') - .field('siope_uf.estado_id', 'state_id') - .field('siope_uf.fundeb', 'fundeb') - .field('siope_uf.total_impostos', 'impostos') - .field('siope_uf.total_mde', 'MDE') - .group('siope_uf.ano_censo') - .group('siope_uf.estado_id') - .group('siope_uf.fundeb') - .group('siope_uf.total_impostos') - .group('siope_uf.total_mde') - .order('siope_uf.ano_censo'); - req.queryIndex.siopeUf = req.querySet.push(siopeUf) - 1; - - let siopeMun = req.sql.clone(); - siopeMun.from('siope_mun') - .field('siope_mun.ano_censo', 'year') - .field('siope_mun.estado_id', 'state_id') - .field('siope_mun.municipio_id', 'city_id') - .field('siope_mun.fundeb', 'fundeb') - .field('siope_mun.total_impostos', 'impostos') - .field('siope_mun.total_mde', 'MDE') - .group('siope_mun.ano_censo') - .group('siope_mun.estado_id') - .group('siope_mun.municipio_id') - .group('siope_mun.fundeb') - .group('siope_mun.total_impostos') - .group('siope_mun.total_mde') - .order('siope_mun.ano_censo'); - req.queryIndex.siopeMun = req.querySet.push(siopeMun) - 1; - - next(); -}, rqf.multibuild(), multiQuery, (req, res, next) => { - - let result = [] - - req.result[req.queryIndex.siopeUf].forEach((item) => { - result.push(item) - }); - req.result[req.queryIndex.siopeMun].forEach((item) => { - result.push(item) - }); - - req.result = result; - next(); - -}, response('siope')); - -module.exports = siopeApp; diff --git a/src/libs/routes/spatial.js b/src/libs/routes/spatial.js deleted file mode 100644 index dd7fe97a5b21eb49997866353ce3dc4e7513844b..0000000000000000000000000000000000000000 --- a/src/libs/routes/spatial.js +++ /dev/null @@ -1,373 +0,0 @@ -/* -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`; - -const squel = require('squel'); - -const log = require(`${libs}/log`)(module); - -const query = require(`${libs}/middlewares/query`).query; - -const sqlQuery = require(`${libs}/db/query_exec`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const spatialApp = express(); - -let rqf = new ReqQueryFields(); - -function processResultSet(querySet, querySetLabels = ["result"], singleResult = false) { - const resultMap = new Map(); - let resultIdx = 0; - // loop relies on the fact that Promise.all maintains the order of the original iterable - for(let result of querySet) { - const resultLbl = querySetLabels[resultIdx]; - resultMap[resultLbl] = []; - if (singleResult) { - resultMap[resultLbl] = result[0]; - } else { - for(let row of result) { - resultMap[resultLbl].push(row); - } - } - resultIdx++; - } - return resultMap; -} - -function dbExecAll(querySet = []) { - // Issue all queries concurrently to the database, for every query object in the iterable - // NOTE: Array.map() returns a copy of the original array with each object 'mapped'. - return querySet.map((qry) => { return sqlQuery(qry.toString()); }); -} - -rqf.addField({ - name: 'filter', - field: true, - where: true -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id' - } -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id' - } -}).addValue({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}); - -spatialApp.get('/sociodemographic', rqf.parse(), rqf.build(), (req, res, next) => { - const populationYearQry = squel.select() - .field('MAX(ibge_populacao.ano_censo)') - .from('ibge_populacao'); - - const populationQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('SUM(populacao)', 'population') - .field('ibge_populacao.ano_censo', 'census_year') - .from('ibge_populacao') - .where(`ibge_populacao.ano_censo IN (${populationYearQry.toString()})`) - .group('ibge_populacao.ano_censo'); - - const pibYearQry = squel.select() - .field('MAX(ibge_pib.ano_censo)') - .from('ibge_pib'); - - const pibQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('AVG(ibge_pib.pib_per_capita)', 'gdp_per_capita') - .field('ibge_pib.ano_censo', 'census_year') - .from('ibge_pib') - .where(`ibge_pib.ano_censo IN (${pibYearQry.toString()})`) - .group('ibge_pib.ano_censo'); - - const idhYearQry = squel.select() - .field('MAX(adh_idh.ano_censo)') - .from('adh_idh'); - - const idhQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('AVG(idhm)', 'idhm') - .field('adh_idh.ano_censo', 'census_year') - .from('adh_idh') - .where(`adh_idh.ano_censo IN (${idhYearQry.toString()})`) - .group('adh_idh.ano_censo'); - - const analfabYearQry = squel.select() - .field('MAX(adh_analfabetismo.ano_censo)') - .from('adh_analfabetismo'); - - const analfabQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('AVG(t_analf15m)', 'analfabetism') - .field('adh_analfabetismo.ano_censo', 'census_year') - .from('adh_analfabetismo') - .where(`adh_analfabetismo.ano_censo IN (${analfabYearQry.toString()})`) - .group('adh_analfabetismo.ano_censo'); - - const giniYearQry = squel.select() - .field('MAX(adh_gini.ano_censo)') - .from('adh_gini'); - - const giniQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('AVG(gini)', 'gini') - .field('adh_gini.ano_censo', 'census_year') - .from('adh_gini') - .where(`adh_gini.ano_censo IN (${giniYearQry.toString()})`) - .group('adh_gini.ano_censo'); - - // map query objects to their respective response labels - const queryLabels = [ "population", "gdp", "idh", "analfab", "gini" ]; - const querySet = [ populationQry, pibQry, idhQry, analfabQry, giniQry ]; - // wait until all queries finish or one of them fail - Promise.all(dbExecAll(querySet)).then((queryResults) => { - req.result = processResultSet(queryResults, queryLabels, true); - next(); - }).catch((error) => { - log.error(`[SQL query error] ${error}`); - next(error); - }); -}, response('spatial')); - -spatialApp.get('/educational', rqf.parse(), rqf.build(), (req, res, next) => { - const censusYearQry = squel.select() - .field('MAX(escola.ano_censo)', 'ano_censo') - .from('escola') - .toString(); - - const totalSchoolsQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('\'Total\'', 'location_name') - .field('COUNT(DISTINCT(escola.id))', 'total') - .field('escola.ano_censo', 'census_year') - .from('turma') - .from('escola') - .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.ano_censo'); - - const schoolsPerLocationQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COUNT(DISTINCT(escola.id))', 'total') - .field('escola.ano_censo', 'census_year') - .field('localizacao.descricao', 'location_name') - .from('localizacao') - .from('turma') - .from('escola') - .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.localizacao_id') - .group('escola.ano_censo') - .group('localizacao.descricao') - .order('localizacao.descricao'); - - const schoolsPerAdmDependencyQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COUNT(DISTINCT(escola.id))', 'total') - .field('escola.ano_censo', 'census_year') - .field('dependencia_adm.nome', 'adm_dependency_name') - .from('dependencia_adm') - .from('escola') - .where('escola.dependencia_adm_id=dependencia_adm.id') - .where(`escola.ano_censo IN (${censusYearQry})`) - .group('escola.ano_censo') - .group('dependencia_adm.nome') - .order('escola.ano_censo') - .order('dependencia_adm.nome'); - - const enrollmentsQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COALESCE(SUM(uc201.matriculas), 0)', 'total') - .field('uc201.ano_censo', 'census_year') - .from('uc201') - .group('uc201.ano_censo'); - - const enrollmentsPerAdmDepQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COALESCE(SUM(uc201.matriculas), 0)', 'total') - .field('uc201.ano_censo', 'census_year') - .field('dependencia_adm.nome', 'adm_dependency_name') - .from('dependencia_adm') - .from('uc201') - .where('uc201.dependencia_adm_id=dependencia_adm.id') - .group('dependencia_adm.nome') - .group('uc201.ano_censo'); - - const enrollmentsPerSchoolLevelQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COALESCE(SUM(uc201.matriculas), 0)', 'total') - .field('uc201.ano_censo', 'census_year') - .field('etapa_ensino.desc_etapa', 'school_level_name') - .field('dependencia_adm.nome', 'adm_dependency_name') - .from('etapa_ensino') - .from('dependencia_adm') - .from('uc201') - .where('uc201.etapas_mod_ensino_segmento_id=etapa_ensino.id') - .where('uc201.dependencia_adm_id=dependencia_adm.id') - .group('etapa_ensino.desc_etapa') - .group('dependencia_adm.nome') - .group('uc201.ano_censo'); - - const enrollmentsPerLocationQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COALESCE(SUM(uc201.matriculas), 0)', 'total') - .field('uc201.ano_censo', 'census_year') - .field('localizacao.descricao', 'location_name') - .from('localizacao') - .from('uc201') - .where('uc201.localizacao=localizacao.id') - .group('localizacao.descricao') - .group('uc201.ano_censo'); - - const queryLabels = [ "school", "school_per_location", "school_per_adm_dependency", "enrollment", "enrollment_per_adm_dep", - "enrollment_per_school_level", "enrollment_per_location" ]; - const querySet = [ totalSchoolsQry, schoolsPerLocationQry, schoolsPerAdmDependencyQry, enrollmentsQry, - enrollmentsPerAdmDepQry, enrollmentsPerSchoolLevelQry, enrollmentsPerLocationQry]; - // wait until all queries finish or one of them fail - Promise.all(dbExecAll(querySet)).then((queryResults) => { - req.result = processResultSet(queryResults, queryLabels); - next(); - }).catch((error) => { - log.error(`[SQL query error] ${error}`); - next(error); - }); -}, response('spatial')); - -spatialApp.get('/educational/school_level', rqf.parse(), rqf.build(), (req, res, next) => { - const enrollmentsPerSchoolLevelYearQry = squel.select() - .field('MAX(matricula.ano_censo)', 'census_year') - .from('matricula'); - - const enrollmentsPerSchoolLevelQry = req.sql.clone() - .field('COALESCE(COUNT(matricula.id), 0)', 'total') - .field('matricula.ano_censo', 'census_year') - .field('matricula.serie_ano_id', 'school_year') - .field('etapa_ensino.desc_etapa', 'school_level') - .from('etapa_ensino') - .from('matricula') - .where(`matricula.ano_censo IN (${enrollmentsPerSchoolLevelYearQry.toString()})`) - .where('matricula.etapa_ensino_id = etapa_ensino.id') - .where('matricula.tipo <= 3') - .group('etapa_ensino.desc_etapa') - .group('etapa_ensino.id') - .group('matricula.serie_ano_id') - .group('matricula.ano_censo') - .order('etapa_ensino.id') - .order('matricula.serie_ano_id') - .order('matricula.ano_censo'); - - const queryLabels = [ 'enrollment_per_school_level', 'enrollment_census_year' ]; - const querySet = [ enrollmentsPerSchoolLevelQry, enrollmentsPerSchoolLevelYearQry ]; - // wait until all queries finish or one of them fail - Promise.all(dbExecAll(querySet, enrollmentsPerSchoolLevelYearQry)).then((queryResults) => { - const result = queryResults[0]; - const censusYear = queryResults[1][0]['census_year']; - - let school_levels = {}; - for(let i = 0; i < result.length; ++i) { - const school_year = id2str.schoolYear(result[i].school_year); - const school_level = result[i].school_level; - const census_year = result[i].census_year; - if (typeof school_levels[school_level] === 'undefined') { - school_levels[school_level] = {}; - } - school_levels[school_level][school_year] = parseInt(result[i].total, 10); - } - - let response = []; - for(let level in school_levels) { - if (school_levels.hasOwnProperty(level)) { - let sclevel = {}; - sclevel["degree"] = level; - sclevel["census_year"] = parseInt(censusYear, 10); - sclevel["table"] = []; - for(let school_year in school_levels[level]) { - if (school_levels[level].hasOwnProperty(school_year)) { - let enrollment = { 'title' : school_year, - 'value' : school_levels[level][school_year] }; - sclevel["table"].push(enrollment); - } - } - response.push(sclevel); - } - } - req.result = response; - next(); - }).catch((error) => { - log.error(`[SQL query error] ${error}`); - next(error); - }); -}, response('spatial')); - -module.exports = spatialApp; diff --git a/src/libs/routes/state.js b/src/libs/routes/state.js deleted file mode 100644 index cb84a09662e886ffcc3b28a3d602d9192b5d1c14..0000000000000000000000000000000000000000 --- a/src/libs/routes/state.js +++ /dev/null @@ -1,100 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -stateApp.use(cache('15 day')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addValue({ - name: 'id', - table: 'estado', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'regiao_id', - table: 'estado' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'estado' - } -}).addField({ - name: 'search', - field: false, - where: true -}).addValueToField({ - name: 'name', - table: 'estado', - tableField: 'nome', - where: { - relation: 'LIKE', - type: 'string', - field: 'nome' - } -}, 'search'); - -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'); - next(); -}, query, response('state')); - -module.exports = stateApp; diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js deleted file mode 100644 index b9a862269ab4cfa76f2ac8d576b227bbd1be10bd..0000000000000000000000000000000000000000 --- a/src/libs/routes/teacher.js +++ /dev/null @@ -1,464 +0,0 @@ -/* -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(); - -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 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; - -let rqf = new ReqQueryFields(); - -teacherApp.use(cache('15 day')); - -// Returns a tuple of start and ending years of the complete enrollments dataset. -teacherApp.get('/year_range', (req, res, next) => { - req.sql.from('docente') - .field('MIN(docente.ano_censo)', 'start_year') - .field('MAX(docente.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -teacherApp.get('/years', (req, res, next) => { - req.sql.from('docente'). - field('DISTINCT docente.ano_censo', 'year'); - next(); -}, query, response('years')); - -teacherApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'docente\''); - next(); -}, query, response('source')); - -teacherApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -teacherApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -teacherApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 11; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -teacherApp.get('/education_level_short', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Ensino Fundamental - anos iniciais'}, - {id: 4, name: 'Ensino Fundamental - anos finais'}, - {id: 5, name: 'Ensino Médio'}, - {id: 6, name: 'EJA'}, - {id: 7, name: 'EE exclusiva'} - ]; - next(); -}, response('education_level_short')); - -teacherApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -teacherApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -teacherApp.get('/education_type', (req, res, next) => { - req.sql.from('docente') - .field('DISTINCT nivel_tipo_formacao', 'id') - .order('id'); - next(); -}, query, (req, res, next) => { - req.result.forEach((result) => { - result.name = id2str.educationType(result.id); - }); - next(); -}, response('education_type')); - -teacherApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - - -teacherApp.get('/contract_type', (req, res, next) => { - req.result = [ - {id: 1, name: 'Concursado/Efetivo/Estável'}, - {id: 2, name: 'Contrato temporário'}, - {id: 3, name: 'Contrato terceirizado'}, - {id: 4, name: 'Contrato CLT'} - ]; - next(); -}, response('contract_type')); - -teacherApp.get('/ethnic_group', (req, res, next) => { - req.result = []; - for(let i = 0; i <=5; ++i) { - req.result.push({ - id: i, - name: id2str.ethnicGroup(i) - }); - } - next(); -}, response('ethnic_group')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: 'docente', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'docente', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'contract_type', - table: 'docente', - tableField: 'tipo_contratacao', - resultField: 'contract_type_id', - where: { - relation: '=', - type: 'integer', - field: 'tipo_contratacao' - } -}).addValue({ - name: 'education_level_mod', - table: 'docente', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'education_level_short', - table: 'docente', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}).addValue({ - name: 'education_type', - table: 'docente', - tableField: 'nivel_tipo_formacao', - resultField: 'education_type_id', - where: { - relation: '=', - type: 'integer', - field: 'nivel_tipo_formacao' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_regiao_id', - foreignTable: 'docente' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_estado_id', - foreignTable: 'docente' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_municipio_id', - foreignTable: 'docente' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_municipio_id', - foreignTable: 'docente' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'docente' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'docente' - } -}, 'filter').addValue({ - name: 'location', - table: 'docente', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'docente', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'min_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'gender', - table: 'docente', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'ethnic_group', - table: 'docente', - tableField: 'cor_raca', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca' - } -}); - -teacherApp.get('/', rqf.parse(), (req, res, next) => { - req.sql.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)'); - - if("education_level_mod" in req.dims) { - delete req.dims.education_level_mod; - req.hadEducationLevelMod = true; - req.sql.field('docente.etapas_mod_ensino_segmento_id', 'education_level_mod_id') - .where('docente.etapas_mod_ensino_segmento_id < 11') - .group('docente.etapas_mod_ensino_segmento_id') - .order('docente.etapas_mod_ensino_segmento_id'); - } - - 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')); - -module.exports = teacherApp; diff --git a/src/libs/routes/transport.js b/src/libs/routes/transport.js deleted file mode 100644 index 6435833b591e75e3af451aeb4cce420904fb2449..0000000000000000000000000000000000000000 --- a/src/libs/routes/transport.js +++ /dev/null @@ -1,523 +0,0 @@ -/* -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(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -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`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -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'); - next(); -}, query, response('range')); - -transportApp.get('/years', (req, res, next) => { - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, response('years')); - -transportApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -transportApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -transportApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -transportApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -transportApp.get('/education_level_mod', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 4, name: 'Ensino Fundamental - anos iniciais'}, - {id: 5, name: 'Ensino Fundamental - anos finais'}, - {id: 6, name: 'Ensino Médio'}, - {id: 7, name: 'Turmas multiseriadas e multietapas'}, - {id: 8, name: 'EJA - Ensino Fundamental'}, - {id: 9, name: 'EJA - Ensino Médio'}, - {id: 10, name: 'Educação Profissional'} - ]; - next(); -}, response('education_level_mod')); - -transportApp.get('/service_type', (req, res, next) => { - req.result = [ - {id: 0, name: 'Não se aplica'}, - {id: 1, name: 'Classe hospitalar'}, - {id: 2, name: 'Unidade de Atendimento Socioeducativo'}, - {id: 3, name: 'Unidade Prisional'}, - {id: 4, name: 'Atividade Complementar '}, - {id: 5, name: 'Atendimento Educacional Especializado (AEE)'} - ]; - next(); -}, response('service_type')); - -transportApp.get('/transportation_manager', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Estadual'}, - {id: 2, name: 'Municipal'}, - ]; - next(); -}, response('transportation_manager')); - -transportApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'matricula\''); - next(); -}, query, response('source')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'matricula' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'matricula' - } -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'matricula' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'matricula' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'matricula' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'matricula' - } -}).addValue({ - name: 'rural_location', - table: 'matricula', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'location', - table: 'matricula', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name:'adm_dependency', - table: 'matricula', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'matricula', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'transportation_manager', - table: 'matricula', - tableField: 'responsavel_transp', - resultField: 'transportation_manager_id', - where: { - relation: '=', - type: 'integer', - field: 'responsavel_transp' - } -}).addValue({ - name: 'education_level_mod', - table: 'matricula', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'service_type', - table: 'matricula', - tableField: 'tipo', - resultField: 'service_type_id', - where: { - relation: '=', - type: 'integer', - field: 'tipo' - } -}).addValue({ - name: 'min_year', - table: 'matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'matricula', - 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; - - 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]) - } - - //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 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')); - -module.exports = transportApp; diff --git a/src/libs/routes/user.js b/src/libs/routes/user.js deleted file mode 100644 index f32f41ab602dfe3c0c119dcb89b5cfff02edb0ad..0000000000000000000000000000000000000000 --- a/src/libs/routes/user.js +++ /dev/null @@ -1,328 +0,0 @@ -/* -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 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 a2a278c549c6ef095cab09ee243a48772e11ea5b..0000000000000000000000000000000000000000 --- a/src/libs/routes/verifyToken.js +++ /dev/null @@ -1,72 +0,0 @@ -/* -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 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/test/simulation.js b/src/test/simulation.js deleted file mode 100644 index d7a99a970a7f0b5f886c0d20b9df28a0291e35ce..0000000000000000000000000000000000000000 --- a/src/test/simulation.js +++ /dev/null @@ -1,453 +0,0 @@ -/* -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`); - -const mongoose = require('../libs/db/mongoose'); -const Simulation = require('../libs/models/simulation'); -const User = require('../libs/models/user'); - -chai.use(chaiHttp); - -describe('Requires a simulation', () => { - let newSimulation; - - beforeEach(() => { - Simulation.remove({}, (err) => { - console.log('Test collection purged'); - }); - }); - - // it('should create a new simulation', (done) => { - // chai.request(server) - // .post('/api/v1/simulation') - // .set('content-type', 'application/x-www-form-urlencoded') - // .set('x-apicache-bypass', 'true') - // .send({ name: 'test_entry' }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.name.should.equal('test_entry'); - // done(); - // }); - // }); - // }); - // it('should not create a nameless simulation', (done) => { - // chai.request(server) - // .post('/api/v1/simulation') - // .set('content-type', 'application/x-www-form-urlencoded') - // .set('x-apicache-bypass', 'true') - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.not.have.property('id'); - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // Simulation.findById(res.body.id, (err, simulation) => { - // expect(simulation).to.not.exist; - // done(); - // }); - // }); - // }); - // it('should find an existing simulation', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .get(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('_id'); - // res.body._id.should.be.a('string'); - // res.body.should.have.property('name'); - // res.body._id.should.be.a('string'); - // done(); - // }); - // }); - // }); - // it('should not find an unexisting simulation', (done) => { - // newSimulation = new Simulation(); - // let id = newSimulation._id; - // chai.request(server) - // .get(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // it('should update an existing simulation\'s location', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ location: 5 }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.name.should.equal('test'); - // simulation.should.have.property('location'); - // simulation.location.should.be.a('number'); - // simulation.location.should.equal(5); - // done(); - // }); - // }); - // }); - // }); - // it('should update multiple fields on a single request', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // name: 'new_name', - // location: 5, - // time: 3, - // failure_rate: [0.1, 0.2, 0.3], - // goals_care: [0.3, 0.2, 0.1], - // goals_inclusion: [0.8, 0.9, 1] - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.name.should.equal('new_name'); - // simulation.should.have.property('location'); - // simulation.location.should.be.a('number'); - // simulation.location.should.equal(5); - // simulation.should.have.property('time'); - // simulation.time.should.be.a('number'); - // simulation.time.should.equal(3); - // simulation.should.have.property('failure_rate'); - // simulation.failure_rate.should.be.a('array'); - // simulation.failure_rate.length.should.equal(3); - // simulation.should.have.property('goals_care'); - // simulation.goals_care.should.be.a('array'); - // simulation.goals_care.length.should.equal(3); - // simulation.should.have.property('goals_inclusion'); - // simulation.goals_inclusion.should.be.a('array'); - // simulation.goals_inclusion.length.should.equal(3); - // done(); - // }); - // }); - // }); - // }); - // it('should not update an unexisting simulation', (done) => { - // newSimulation = new Simulation(); - // let id = newSimulation._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ location: 5 }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // it('should update an existing simulation\'s time', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ time: 5 }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.should.have.property('time'); - // simulation.time.should.be.a('number'); - // simulation.time.should.equal(5); - // done(); - // }); - // }); - // }); - // }); - // it('should not change results for empty post requests', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should not update in case of invalid field', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // name: 'other_name', - // totally_not_valid_value_for_an_entry: 'not hacking this api', - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // Simulation.findById(id, (err, simulation) => { - // simulation.name.should.equal('test'); - // done(); - // }); - // }); - // }); - // }); - // it('should include consistent enrollment tables', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "[[100, 150, 200, 250, 300]]", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.should.have.property('time'); - // simulation.time.should.be.a('number'); - // simulation.time.should.equal(5); - // done(); - // }); - // }); - // }); - // }); - // it('should not accept an invalid time', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: "I'm an inocent time entry, don't mind me", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // }); - // done(); - // }); - // }); - // it('should not accept enrollments table different than provided time', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "[[1,2,3]]", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should not include arrays of non arrays as enrollments', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "[\"Tomato\"]", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should not accept non array enrollments', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "Am I still wanted here?", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should not accept an enrollment with anything other than a number', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "[[1,2,\"malicious payload\",4,5]]", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should delete an entry', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .delete(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(true); - // done(); - // }); - // }); - // }); - // it('should not delete an unexisting entry', (done) => { - // let sim = new Simulation(); - // let id = sim._id; - // chai.request(server) - // .delete(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - - // it('should returns an array in simulation/time', (done) => { - // let max_time = 10; - // chai.request(server) - // .get(`/api/v1/simulation/time?max_time=${max_time}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('result'); - // res.body.result.should.be.array; - // done(); - // }); - // }); - - // it('should return an error when no max_time is specified in simulation/time', (done) => { - // chai.request(server) - // .get(`/api/v1/simulation/time`) - // .end((err, res) => { - // res.should.have.status(400); - // res.should.be.json; - // res.body.should.have.property('error'); - // res.body.error.should.equal('Invalid value for mandatory parameter max_time'); - // done(); - // }); - // }); -}); diff --git a/src/test/user.js b/src/test/user.js deleted file mode 100644 index ab44a78ddcd71b20d7c9944d6bf5cea7cd359f9d..0000000000000000000000000000000000000000 --- a/src/test/user.js +++ /dev/null @@ -1,57 +0,0 @@ -/* -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`); - -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') - // }); - // }); -});