From ad2192101848d37be5ed6e35e4e3c7c39563b40d Mon Sep 17 00:00:00 2001
From: Vytor Calixto <vytorcalixto@gmail.com>
Date: Fri, 23 Nov 2018 10:11:54 -0200
Subject: [PATCH 001/142] Update CHANGELOG

---
 CHANGELOG.md | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b263b2b..ac2425a8 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/).
 
+# UNRELEASED
+### Changed
+- Fix bug in classroom count with school_year order
+
 ## 1.8.1 - 2018-11-13
 ### Changed
 - Fixed bug in id2str with inexistent convert function
-- 
GitLab


From 5c7832c9e0adb1c36a04dd5047217efaef02c4b1 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Fri, 23 Nov 2018 11:22:47 -0200
Subject: [PATCH 002/142] [fix_da]median fixed

---
 src/libs/app.js                      |  1 +
 src/libs/middlewares/query.js        |  1 +
 src/libs/routes/dailyChargeAmount.js | 44 +++++++++++++++++++++-------
 3 files changed, 36 insertions(+), 10 deletions(-)

diff --git a/src/libs/app.js b/src/libs/app.js
index b8b953c1..5e6d4c1d 100644
--- a/src/libs/app.js
+++ b/src/libs/app.js
@@ -55,6 +55,7 @@ app.use((req, res, next) => {
         };
         return cloned;
     };
+
     next();
 });
 app.use(passport.initialize());
diff --git a/src/libs/middlewares/query.js b/src/libs/middlewares/query.js
index ae002df2..b724d93d 100644
--- a/src/libs/middlewares/query.js
+++ b/src/libs/middlewares/query.js
@@ -6,6 +6,7 @@ const db = require(`${libs}/db/query_exec`);
 function query(req, res, next) {
     let sql = req.sql.toParam();
     log.info(`Executando query ${req.sql.toString()}`);
+    sql.text = sql.text.replace(/`/g, "");
     execute(sql.text, sql.values, (err, result) => {
         if(err) {
             log.error(err.stack);
diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js
index 54ef5bea..773cdff9 100644
--- a/src/libs/routes/dailyChargeAmount.js
+++ b/src/libs/routes/dailyChargeAmount.js
@@ -54,7 +54,7 @@ dailyChargeAmountApp.get('/source', (req, res, next) => {
 dailyChargeAmountApp.get('/adm_dependency', (req, res, next) => {
     req.result = [];
     for(let i = 1; i <= 4; ++i) {
-        req.result.push({
+        req.resulturma.push({
             id: i,
             name: id2str.admDependency(i)
         });
@@ -65,7 +65,7 @@ dailyChargeAmountApp.get('/adm_dependency', (req, res, next) => {
 dailyChargeAmountApp.get('/adm_dependency_detailed', cache('15 day'), (req, res, next) => {
     req.result = [];
     for(let i = 1; i <= 6; ++i) {
-        req.result.push({
+        req.resulturma.push({
             id: i,
             name: id2str.admDependencyPriv(i)
         });
@@ -127,12 +127,12 @@ dailyChargeAmountApp.get('/average/education_level_mod', (req, res, next) => {
 dailyChargeAmountApp.get('/period', (req, res, next) => {
     req.result = [];
     for(let i = 1; i <= 3; ++i) {
-        req.result.push({
+        req.resulturma.push({
             id: i,
             name: id2str.period(i)
         });
     };
-    req.result.push({
+    req.resulturma.push({
         id: 99,
         name: id2str.period(99)
     });
@@ -284,6 +284,7 @@ rqf.addField({
     table: 'turma',
     tableField: 'etapas_mod_ensino_segmento_id',
     resultField: 'education_level_mod_id',
+    dontGroup: true,
     where: {
         relation: '=',
         type: 'integer',
@@ -373,14 +374,14 @@ dailyChargeAmountApp.get('/', rqf.parse(), (req, res, next) => {
     if ('period' in req.filter || 'period' in req.dims) {
         req.filter['period'].forEach((element) => {
             if (element == '3')
-                req.result = req.result.filter(sliced);
+                req.result = req.resulturma.filter(sliced);
         });
     }
 
     next();
 }, id2str.transform(), response('turma'));
 
-dailyChargeAmountApp.get('/average', rqf.parse(), (req, res, next) => {
+dailyChargeAmountApp.get('/average', rqf.parse(), rqf.build(), (req, res, next) => {
     var status = 0;
     if (('education_level_mod' in req.filter || 'education_level_mod' in req.dims)
     && ('integral_time' in req.filter)) {
@@ -401,11 +402,34 @@ dailyChargeAmountApp.get('/average', rqf.parse(), (req, res, next) => {
     }
 
     if (status) {
-        req.sql.from('turma')
+        let baseQ = req.sql.clone();
+
+        let tableR = baseQ.clone();
+        tableR.from('turma')
+        .field('duracao_turma')
+        .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')
+        .where('tipo_turma_id <= 3')
+        .group('etapas_mod_ensino_segmento_id')
+
+        let joinRG = squel.select();
+        joinRG.from(tableR, 'R')
+        .field('R.education_level_mod_id')
+        .field('AVG(1.0*R.duracao_turma)/60', 'median_value')
+        .join(tableG, 'G', 'R.education_level_mod_id = G.education_level_mod_id AND R.rowNo BETWEEN G.counter/2 AND G.counter/2+G.counter%2')
+        .group('R.education_level_mod_id')
+
+        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('MEDIAN(turma.duracao_turma)/60.0', 'median_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')
@@ -413,7 +437,7 @@ dailyChargeAmountApp.get('/average', rqf.parse(), (req, res, next) => {
         .group('turma.etapas_mod_ensino_segmento_id')
         .order('turma.ano_censo')
         .order('turma.etapas_mod_ensino_segmento_id')
-        .where('turma.tipo_turma_id <= 3')
+        .where('turma.tipo_turma_id <= 3 and m.education_level_mod_id = turma.etapas_mod_ensino_segmento_id')
     } else {
         res.status(400);
         next({
@@ -423,6 +447,6 @@ dailyChargeAmountApp.get('/average', rqf.parse(), (req, res, next) => {
     }
 
     next();
-}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('turma'));
+}, query, addMissing(rqf), id2str.transform(), response('turma'));
 
 module.exports = dailyChargeAmountApp;
-- 
GitLab


From f78a85b8f723cb886ed4ba0e58f8b3b9a06cd90b Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Fri, 23 Nov 2018 11:40:16 -0200
Subject: [PATCH 003/142] string fix

---
 src/libs/routes/dailyChargeAmount.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js
index 773cdff9..06f34a9e 100644
--- a/src/libs/routes/dailyChargeAmount.js
+++ b/src/libs/routes/dailyChargeAmount.js
@@ -127,12 +127,12 @@ dailyChargeAmountApp.get('/average/education_level_mod', (req, res, next) => {
 dailyChargeAmountApp.get('/period', (req, res, next) => {
     req.result = [];
     for(let i = 1; i <= 3; ++i) {
-        req.resulturma.push({
+        req.result.push({
             id: i,
             name: id2str.period(i)
         });
     };
-    req.resulturma.push({
+    req.result.push({
         id: 99,
         name: id2str.period(99)
     });
-- 
GitLab


From d0e53b01c50033d8202e3f5851fafc93fc55940b Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Mon, 10 Dec 2018 10:05:39 -0200
Subject: [PATCH 004/142] Fix Daily

---
 src/libs/routes/dailyChargeAmount.js | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js
index 06f34a9e..d9a02d77 100644
--- a/src/libs/routes/dailyChargeAmount.js
+++ b/src/libs/routes/dailyChargeAmount.js
@@ -54,7 +54,7 @@ dailyChargeAmountApp.get('/source', (req, res, next) => {
 dailyChargeAmountApp.get('/adm_dependency', (req, res, next) => {
     req.result = [];
     for(let i = 1; i <= 4; ++i) {
-        req.resulturma.push({
+        req.result.push({
             id: i,
             name: id2str.admDependency(i)
         });
@@ -65,7 +65,7 @@ dailyChargeAmountApp.get('/adm_dependency', (req, res, next) => {
 dailyChargeAmountApp.get('/adm_dependency_detailed', cache('15 day'), (req, res, next) => {
     req.result = [];
     for(let i = 1; i <= 6; ++i) {
-        req.resulturma.push({
+        req.result.push({
             id: i,
             name: id2str.admDependencyPriv(i)
         });
@@ -374,7 +374,7 @@ dailyChargeAmountApp.get('/', rqf.parse(), (req, res, next) => {
     if ('period' in req.filter || 'period' in req.dims) {
         req.filter['period'].forEach((element) => {
             if (element == '3')
-                req.result = req.resulturma.filter(sliced);
+                req.result = req.result.filter(sliced);
         });
     }
 
-- 
GitLab


From 0917c5fb725f1e39460d38d354b9f71fac404710 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Wed, 9 Jan 2019 10:59:21 -0200
Subject: [PATCH 005/142] [fix_da]Fix result variable and query problem

---
 src/libs/routes/dailyChargeAmount.js | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js
index d9a02d77..7847c1a3 100644
--- a/src/libs/routes/dailyChargeAmount.js
+++ b/src/libs/routes/dailyChargeAmount.js
@@ -407,21 +407,23 @@ dailyChargeAmountApp.get('/average', rqf.parse(), rqf.build(), (req, res, next)
         let tableR = baseQ.clone();
         tableR.from('turma')
         .field('duracao_turma')
+        .field('etapas_mod_ensino_segmento_id')
         .field('ROW_NUMBER() OVER(PARTITION BY etapas_mod_ensino_segmento_id ORDER BY duracao_turma)', 'rowno')
         .where('tipo_turma_id <= 3')
 
         let tableG = baseQ.clone();
         tableG.from('turma')
         .field('1+COUNT(*)', 'counter')
+        .field('etapas_mod_ensino_segmento_id')
         .where('tipo_turma_id <= 3')
         .group('etapas_mod_ensino_segmento_id')
 
         let joinRG = squel.select();
         joinRG.from(tableR, 'R')
-        .field('R.education_level_mod_id')
+        .field('R.etapas_mod_ensino_segmento_id')
         .field('AVG(1.0*R.duracao_turma)/60', 'median_value')
-        .join(tableG, 'G', 'R.education_level_mod_id = G.education_level_mod_id AND R.rowNo BETWEEN G.counter/2 AND G.counter/2+G.counter%2')
-        .group('R.education_level_mod_id')
+        .join(tableG, 'G', 'R.etapas_mod_ensino_segmento_id = G.etapas_mod_ensino_segmento_id AND R.rowNo BETWEEN G.counter/2 AND G.counter/2+G.counter%2')
+        .group('R.etapas_mod_ensino_segmento_id')
 
         req.sql
         .from('turma')
@@ -437,7 +439,7 @@ dailyChargeAmountApp.get('/average', rqf.parse(), rqf.build(), (req, res, next)
         .group('turma.etapas_mod_ensino_segmento_id')
         .order('turma.ano_censo')
         .order('turma.etapas_mod_ensino_segmento_id')
-        .where('turma.tipo_turma_id <= 3 and m.education_level_mod_id = turma.etapas_mod_ensino_segmento_id')
+        .where('turma.tipo_turma_id <= 3 and m.etapas_mod_ensino_segmento_id = turma.etapas_mod_ensino_segmento_id')
     } else {
         res.status(400);
         next({
-- 
GitLab


From e36194a5388619466e84a440485442489d90a31f Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 10 Jan 2019 09:44:40 -0200
Subject: [PATCH 006/142] Add GNU GPL in convert directory

---
 src/libs/convert/admDependency.js            | 20 ++++++++++++++++++++
 src/libs/convert/admDependencyPriv.js        | 20 ++++++++++++++++++++
 src/libs/convert/ageRange.js                 | 20 ++++++++++++++++++++
 src/libs/convert/ageRangeAll.js              | 20 ++++++++++++++++++++
 src/libs/convert/agreement.js                | 20 ++++++++++++++++++++
 src/libs/convert/booleanVariable.js          | 20 ++++++++++++++++++++
 src/libs/convert/citySize.js                 | 20 ++++++++++++++++++++
 src/libs/convert/contractType.js             | 20 ++++++++++++++++++++
 src/libs/convert/educationLevel.js           | 20 ++++++++++++++++++++
 src/libs/convert/educationLevelBasic.js      | 20 ++++++++++++++++++++
 src/libs/convert/educationLevelMod.js        | 20 ++++++++++++++++++++
 src/libs/convert/educationLevelSchoolYear.js | 20 ++++++++++++++++++++
 src/libs/convert/educationLevelShort.js      | 20 ++++++++++++++++++++
 src/libs/convert/educationType.js            | 20 ++++++++++++++++++++
 src/libs/convert/ethnicGroup.js              | 20 ++++++++++++++++++++
 src/libs/convert/ethnicGroupPnad.js          | 20 ++++++++++++++++++++
 src/libs/convert/extremesHouseholdIncome.js  | 20 ++++++++++++++++++++
 src/libs/convert/fifthHouseholdIncome.js     | 20 ++++++++++++++++++++
 src/libs/convert/fullAgeRange.js             | 20 ++++++++++++++++++++
 src/libs/convert/gender.js                   | 20 ++++++++++++++++++++
 src/libs/convert/genderPnad.js               | 20 ++++++++++++++++++++
 src/libs/convert/idhmLevel.js                | 20 ++++++++++++++++++++
 src/libs/convert/incomeLevel.js              | 20 ++++++++++++++++++++
 src/libs/convert/integralTime.js             | 20 ++++++++++++++++++++
 src/libs/convert/location.js                 | 20 ++++++++++++++++++++
 src/libs/convert/period.js                   | 20 ++++++++++++++++++++
 src/libs/convert/pfe.js                      | 20 ++++++++++++++++++++
 src/libs/convert/ruralLocation.js            | 20 ++++++++++++++++++++
 src/libs/convert/schoolYear.js               | 20 ++++++++++++++++++++
 src/libs/convert/stateName.js                | 20 ++++++++++++++++++++
 src/libs/convert/transportationManager.js    | 20 ++++++++++++++++++++
 31 files changed, 620 insertions(+)

diff --git a/src/libs/convert/admDependency.js b/src/libs/convert/admDependency.js
index 16017f06..fca63f3f 100644
--- a/src/libs/convert/admDependency.js
+++ b/src/libs/convert/admDependency.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function admDependency(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/admDependencyPriv.js b/src/libs/convert/admDependencyPriv.js
index 62afaa83..0c5036fb 100644
--- a/src/libs/convert/admDependencyPriv.js
+++ b/src/libs/convert/admDependencyPriv.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function admDependencyPriv(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/ageRange.js b/src/libs/convert/ageRange.js
index 30bc9f6c..4a881829 100644
--- a/src/libs/convert/ageRange.js
+++ b/src/libs/convert/ageRange.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function ageRange(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/ageRangeAll.js b/src/libs/convert/ageRangeAll.js
index 2b4cab9c..1ad1c54e 100644
--- a/src/libs/convert/ageRangeAll.js
+++ b/src/libs/convert/ageRangeAll.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function ageRange(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/agreement.js b/src/libs/convert/agreement.js
index e9c5c774..3490ef69 100644
--- a/src/libs/convert/agreement.js
+++ b/src/libs/convert/agreement.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function agreement(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/booleanVariable.js b/src/libs/convert/booleanVariable.js
index 8ed8e007..64966010 100644
--- a/src/libs/convert/booleanVariable.js
+++ b/src/libs/convert/booleanVariable.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function booleanVariable(id) {
   if (id == null)
     return 'Não Declarado';
diff --git a/src/libs/convert/citySize.js b/src/libs/convert/citySize.js
index 3f50462b..9e1089b1 100644
--- a/src/libs/convert/citySize.js
+++ b/src/libs/convert/citySize.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function citySize(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/contractType.js b/src/libs/convert/contractType.js
index a20ab853..98ffcb84 100644
--- a/src/libs/convert/contractType.js
+++ b/src/libs/convert/contractType.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function contractType(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/educationLevel.js b/src/libs/convert/educationLevel.js
index e01c8be0..cc82319c 100644
--- a/src/libs/convert/educationLevel.js
+++ b/src/libs/convert/educationLevel.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function educationLevel(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/educationLevelBasic.js b/src/libs/convert/educationLevelBasic.js
index d667d09d..3d166fe5 100644
--- a/src/libs/convert/educationLevelBasic.js
+++ b/src/libs/convert/educationLevelBasic.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function educationLevelBasic(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/educationLevelMod.js b/src/libs/convert/educationLevelMod.js
index f3797ee9..e6595173 100644
--- a/src/libs/convert/educationLevelMod.js
+++ b/src/libs/convert/educationLevelMod.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function educationLevelMod(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/educationLevelSchoolYear.js b/src/libs/convert/educationLevelSchoolYear.js
index f4fe43b7..07cc64f7 100644
--- a/src/libs/convert/educationLevelSchoolYear.js
+++ b/src/libs/convert/educationLevelSchoolYear.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function educationLevelSchoolYear(id) {
     switch(id) {
         case 1: return 'Creche';
diff --git a/src/libs/convert/educationLevelShort.js b/src/libs/convert/educationLevelShort.js
index ee97e956..96b67f15 100644
--- a/src/libs/convert/educationLevelShort.js
+++ b/src/libs/convert/educationLevelShort.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function educationLevelShort(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/educationType.js b/src/libs/convert/educationType.js
index 0fffb330..8686822e 100644
--- a/src/libs/convert/educationType.js
+++ b/src/libs/convert/educationType.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function educationType(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/ethnicGroup.js b/src/libs/convert/ethnicGroup.js
index dfa51c81..1b6b92ea 100644
--- a/src/libs/convert/ethnicGroup.js
+++ b/src/libs/convert/ethnicGroup.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function ethnicGroup(id) {
     switch (id) {
         case 0:
diff --git a/src/libs/convert/ethnicGroupPnad.js b/src/libs/convert/ethnicGroupPnad.js
index 93428cd4..3110d2cb 100644
--- a/src/libs/convert/ethnicGroupPnad.js
+++ b/src/libs/convert/ethnicGroupPnad.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function ethnicGroupPnad(id) {
     switch (id) {
         case 0:
diff --git a/src/libs/convert/extremesHouseholdIncome.js b/src/libs/convert/extremesHouseholdIncome.js
index 67904c4f..2ef4ad9b 100644
--- a/src/libs/convert/extremesHouseholdIncome.js
+++ b/src/libs/convert/extremesHouseholdIncome.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function extremesHouseholdIncome(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/fifthHouseholdIncome.js b/src/libs/convert/fifthHouseholdIncome.js
index ec7669a2..3b6a528d 100644
--- a/src/libs/convert/fifthHouseholdIncome.js
+++ b/src/libs/convert/fifthHouseholdIncome.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function fifthHouseholdIncome(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/fullAgeRange.js b/src/libs/convert/fullAgeRange.js
index e18b9156..473de765 100644
--- a/src/libs/convert/fullAgeRange.js
+++ b/src/libs/convert/fullAgeRange.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function ageRange(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/gender.js b/src/libs/convert/gender.js
index 085eb20e..48ed9a1a 100644
--- a/src/libs/convert/gender.js
+++ b/src/libs/convert/gender.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function gender(id) {
     switch(id) {
         case 1:
diff --git a/src/libs/convert/genderPnad.js b/src/libs/convert/genderPnad.js
index 9d5da51e..67ae37fd 100644
--- a/src/libs/convert/genderPnad.js
+++ b/src/libs/convert/genderPnad.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function genderPnad(id) {
     switch(id) {
         case 2:
diff --git a/src/libs/convert/idhmLevel.js b/src/libs/convert/idhmLevel.js
index c9f1845c..f92729b7 100644
--- a/src/libs/convert/idhmLevel.js
+++ b/src/libs/convert/idhmLevel.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function idhmLevel(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/incomeLevel.js b/src/libs/convert/incomeLevel.js
index f80faf86..f834e0c6 100644
--- a/src/libs/convert/incomeLevel.js
+++ b/src/libs/convert/incomeLevel.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function incomeLevel(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/integralTime.js b/src/libs/convert/integralTime.js
index 48f69c43..b231be33 100644
--- a/src/libs/convert/integralTime.js
+++ b/src/libs/convert/integralTime.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function integralTime(id) {
   if (id == null)
     return 'Não se aplica (semi presencial e EaD)';
diff --git a/src/libs/convert/location.js b/src/libs/convert/location.js
index 606e06fc..da1dda65 100644
--- a/src/libs/convert/location.js
+++ b/src/libs/convert/location.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function location(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/period.js b/src/libs/convert/period.js
index 600a71df..8e15e74c 100644
--- a/src/libs/convert/period.js
+++ b/src/libs/convert/period.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function period(id) {
     switch(id) {
         case 1:
diff --git a/src/libs/convert/pfe.js b/src/libs/convert/pfe.js
index 8ef82c87..c67a7141 100644
--- a/src/libs/convert/pfe.js
+++ b/src/libs/convert/pfe.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function pfeName(id) {
     switch(id) {
         case 1: return 'População fora da escola menor de 1 ano';
diff --git a/src/libs/convert/ruralLocation.js b/src/libs/convert/ruralLocation.js
index 7fa97d52..1c1bbc5a 100644
--- a/src/libs/convert/ruralLocation.js
+++ b/src/libs/convert/ruralLocation.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function ruralLocation(id) {
     switch (id) {
         case 1:
diff --git a/src/libs/convert/schoolYear.js b/src/libs/convert/schoolYear.js
index f6b677cc..40d9e638 100644
--- a/src/libs/convert/schoolYear.js
+++ b/src/libs/convert/schoolYear.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function schoolYear(id) {
     switch(id) {
         case 11:
diff --git a/src/libs/convert/stateName.js b/src/libs/convert/stateName.js
index 3fdfdba4..4760d242 100644
--- a/src/libs/convert/stateName.js
+++ b/src/libs/convert/stateName.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function stateName(id) {
     switch (id) {
         case 11:
diff --git a/src/libs/convert/transportationManager.js b/src/libs/convert/transportationManager.js
index 28961db9..f0ab7029 100644
--- a/src/libs/convert/transportationManager.js
+++ b/src/libs/convert/transportationManager.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function transportationManager(id) {
     switch(id) {
         case 1:
-- 
GitLab


From 94113538b5b6ce0fb1322e9ea288bbf2983b3354 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 10 Jan 2019 09:47:53 -0200
Subject: [PATCH 007/142] Add GNU GPL in db directory

---
 src/libs/db/monet.js      | 20 ++++++++++++++++++++
 src/libs/db/mongoose.js   | 20 ++++++++++++++++++++
 src/libs/db/query_exec.js | 20 ++++++++++++++++++++
 3 files changed, 60 insertions(+)

diff --git a/src/libs/db/monet.js b/src/libs/db/monet.js
index d19fb37d..824a438c 100644
--- a/src/libs/db/monet.js
+++ b/src/libs/db/monet.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const MonetDBPool = require('monetdb-pool');
 
 const libs = `${process.cwd()}/libs`;
diff --git a/src/libs/db/mongoose.js b/src/libs/db/mongoose.js
index f9d2ed8e..e1927339 100644
--- a/src/libs/db/mongoose.js
+++ b/src/libs/db/mongoose.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const libs = `${process.cwd()}/libs`;
 
 const config = require(`${libs}/config`);
diff --git a/src/libs/db/query_exec.js b/src/libs/db/query_exec.js
index 691117c5..0437bf24 100644
--- a/src/libs/db/query_exec.js
+++ b/src/libs/db/query_exec.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+   
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 
 const libs = `${process.cwd()}/libs`;
 
-- 
GitLab


From f4676c3641b159b51d7659f50bf7e3afe70e23c2 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 10 Jan 2019 09:51:41 -0200
Subject: [PATCH 008/142] Add GNU GPL in middlewares directory

---
 src/libs/middlewares/addMissing.js       | 20 ++++++++++++++++++++
 src/libs/middlewares/checkVersion.js     | 20 ++++++++++++++++++++
 src/libs/middlewares/downloadDatabase.js | 20 ++++++++++++++++++++
 src/libs/middlewares/email.js            | 20 ++++++++++++++++++++
 src/libs/middlewares/id2str.js           | 20 ++++++++++++++++++++
 src/libs/middlewares/multiQuery.js       | 20 ++++++++++++++++++++
 src/libs/middlewares/oauth2.js           | 20 ++++++++++++++++++++
 src/libs/middlewares/passport.js         | 20 ++++++++++++++++++++
 src/libs/middlewares/query.js            | 20 ++++++++++++++++++++
 src/libs/middlewares/reqQueryFields.js   | 20 ++++++++++++++++++++
 src/libs/middlewares/response.js         | 20 ++++++++++++++++++++
 11 files changed, 220 insertions(+)

diff --git a/src/libs/middlewares/addMissing.js b/src/libs/middlewares/addMissing.js
index f3d1b300..6f5ef699 100644
--- a/src/libs/middlewares/addMissing.js
+++ b/src/libs/middlewares/addMissing.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 module.exports = function addMissing(rqf){
     return (req, res, next) => {
         let dims = Object.keys(req.dims).filter(i => {return i !== 'size';});
diff --git a/src/libs/middlewares/checkVersion.js b/src/libs/middlewares/checkVersion.js
index c3187adb..a103afa6 100644
--- a/src/libs/middlewares/checkVersion.js
+++ b/src/libs/middlewares/checkVersion.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const curPath = process.cwd();
 const libs = `${process.cwd()}/libs`;
 const log = require(`${libs}/log`)(module);
diff --git a/src/libs/middlewares/downloadDatabase.js b/src/libs/middlewares/downloadDatabase.js
index c4672ff0..ee152922 100644
--- a/src/libs/middlewares/downloadDatabase.js
+++ b/src/libs/middlewares/downloadDatabase.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const libs = `${process.cwd()}/libs`;
 
 const log = require(`${libs}/log`)(module);
diff --git a/src/libs/middlewares/email.js b/src/libs/middlewares/email.js
index 7e0403d4..66c4740c 100644
--- a/src/libs/middlewares/email.js
+++ b/src/libs/middlewares/email.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const libs = `${process.cwd()}/libs`;
 const log = require(`${libs}/log`)(module);
 const config = require(`${libs}/config`);
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index cb4c8cc1..65a8b3ca 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const libs = `${process.cwd()}/libs`;
 const gender = require(`${libs}/convert/gender`);
 const period = require(`${libs}/convert/period`);
diff --git a/src/libs/middlewares/multiQuery.js b/src/libs/middlewares/multiQuery.js
index 7bf37c5d..9dc5b3df 100644
--- a/src/libs/middlewares/multiQuery.js
+++ b/src/libs/middlewares/multiQuery.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const libs = `${process.cwd()}/libs`;
 const log = require(`${libs}/log`)(module);
 const db = require(`${libs}/db/query_exec`);
diff --git a/src/libs/middlewares/oauth2.js b/src/libs/middlewares/oauth2.js
index cc9a45ed..e7f7b446 100644
--- a/src/libs/middlewares/oauth2.js
+++ b/src/libs/middlewares/oauth2.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const oauth2orize = require('oauth2orize');
 const passport = require('passport');
 const crypto = require('crypto');
diff --git a/src/libs/middlewares/passport.js b/src/libs/middlewares/passport.js
index ab895a96..ea4fd95c 100644
--- a/src/libs/middlewares/passport.js
+++ b/src/libs/middlewares/passport.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const passport = require('passport');
 const ClientPasswordStrategy = require('passport-oauth2-client-password');
 const BearerStrategy = require('passport-http-bearer').Strategy;
diff --git a/src/libs/middlewares/query.js b/src/libs/middlewares/query.js
index b724d93d..68077aa9 100644
--- a/src/libs/middlewares/query.js
+++ b/src/libs/middlewares/query.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const libs = `${process.cwd()}/libs`;
 const log = require(`${libs}/log`)(module);
 const db = require(`${libs}/db/query_exec`);
diff --git a/src/libs/middlewares/reqQueryFields.js b/src/libs/middlewares/reqQueryFields.js
index 61f98963..8ac231fc 100644
--- a/src/libs/middlewares/reqQueryFields.js
+++ b/src/libs/middlewares/reqQueryFields.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const libs = `${process.cwd()}/libs`;
 
 const log = require(`${libs}/log`)(module);
diff --git a/src/libs/middlewares/response.js b/src/libs/middlewares/response.js
index 62e1d960..c7bb6ffe 100644
--- a/src/libs/middlewares/response.js
+++ b/src/libs/middlewares/response.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const libs = `${process.cwd()}/libs`;
 const log = require(`${libs}/log`)(module);
 const xml = require('js2xmlparser');
-- 
GitLab


From cc5002d610593e2caad627fb13c80efb758b990f Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 10 Jan 2019 09:56:15 -0200
Subject: [PATCH 009/142] Add GNU GPL in models directory

---
 src/libs/models/accessToken.js       | 20 ++++++++++++++++++++
 src/libs/models/client.js            | 20 ++++++++++++++++++++
 src/libs/models/download.js          | 20 ++++++++++++++++++++
 src/libs/models/pqr.js               | 20 ++++++++++++++++++++
 src/libs/models/refreshToken.js      | 20 ++++++++++++++++++++
 src/libs/models/resetToken.js        | 20 ++++++++++++++++++++
 src/libs/models/simulation.js        | 20 ++++++++++++++++++++
 src/libs/models/user.js              | 20 ++++++++++++++++++++
 src/libs/models/verificationToken.js | 20 ++++++++++++++++++++
 9 files changed, 180 insertions(+)

diff --git a/src/libs/models/accessToken.js b/src/libs/models/accessToken.js
index daab5898..b9c2a60a 100644
--- a/src/libs/models/accessToken.js
+++ b/src/libs/models/accessToken.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const mongoose = require('mongoose');
 const Schema = mongoose.Schema;
 const libs = `${process.cwd()}/libs`;
diff --git a/src/libs/models/client.js b/src/libs/models/client.js
index 8ac80d8d..2ddae280 100644
--- a/src/libs/models/client.js
+++ b/src/libs/models/client.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const mongoose = require('mongoose');
 const Schema = mongoose.Schema;
 
diff --git a/src/libs/models/download.js b/src/libs/models/download.js
index 989896d9..21fdf683 100644
--- a/src/libs/models/download.js
+++ b/src/libs/models/download.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const mongoose = require('mongoose');
 const Schema = mongoose.Schema;
 const libs = `${process.cwd()}/libs`;
diff --git a/src/libs/models/pqr.js b/src/libs/models/pqr.js
index f9270318..d8c71c6d 100644
--- a/src/libs/models/pqr.js
+++ b/src/libs/models/pqr.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const mongoose = require('mongoose')
 
 const libs = `${process.cwd()}/libs`;
diff --git a/src/libs/models/refreshToken.js b/src/libs/models/refreshToken.js
index c5f8fd63..3a37ae96 100644
--- a/src/libs/models/refreshToken.js
+++ b/src/libs/models/refreshToken.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const mongoose = require('mongoose');
 const Schema = mongoose.Schema;
 const libs = `${process.cwd()}/libs`;
diff --git a/src/libs/models/resetToken.js b/src/libs/models/resetToken.js
index 322d5281..d983436b 100644
--- a/src/libs/models/resetToken.js
+++ b/src/libs/models/resetToken.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const mongoose = require('mongoose');
 const Schema = mongoose.Schema;
 const libs = `${process.cwd()}/libs`;
diff --git a/src/libs/models/simulation.js b/src/libs/models/simulation.js
index f1d3b0bd..a4a6cc3c 100644
--- a/src/libs/models/simulation.js
+++ b/src/libs/models/simulation.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const mongoose = require('mongoose')
 
 const libs = `${process.cwd()}/libs`;
diff --git a/src/libs/models/user.js b/src/libs/models/user.js
index 0d54e417..7dc642e3 100644
--- a/src/libs/models/user.js
+++ b/src/libs/models/user.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const mongoose = require('mongoose');
 const crypto = require('crypto')
 const libs = `${process.cwd()}/libs`;
diff --git a/src/libs/models/verificationToken.js b/src/libs/models/verificationToken.js
index ef7e109e..1047e4d0 100644
--- a/src/libs/models/verificationToken.js
+++ b/src/libs/models/verificationToken.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const mongoose = require('mongoose');
 const Schema = mongoose.Schema;
 const libs = `${process.cwd()}/libs`;
-- 
GitLab


From 3be20681ca6ffc5e420fd870a283b60531b5224d Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 10 Jan 2019 10:16:38 -0200
Subject: [PATCH 010/142] Add GNU GPL in routes directory

---
 src/libs/routes/api.js                   | 20 ++++++++++++++++++++
 src/libs/routes/auxiliar.js              | 20 ++++++++++++++++++++
 src/libs/routes/city.js                  | 20 ++++++++++++++++++++
 src/libs/routes/class.js                 | 20 ++++++++++++++++++++
 src/libs/routes/classCount.js            | 20 ++++++++++++++++++++
 src/libs/routes/classroom.js             | 20 ++++++++++++++++++++
 src/libs/routes/classroomCount.js        | 20 ++++++++++++++++++++
 src/libs/routes/cub.js                   | 20 ++++++++++++++++++++
 src/libs/routes/dailyChargeAmount.js     | 20 ++++++++++++++++++++
 src/libs/routes/distributionFactor.js    | 20 ++++++++++++++++++++
 src/libs/routes/downloads.js             | 20 ++++++++++++++++++++
 src/libs/routes/educationYears.js        | 20 ++++++++++++++++++++
 src/libs/routes/employees.js             | 20 ++++++++++++++++++++
 src/libs/routes/enrollment.js            | 20 ++++++++++++++++++++
 src/libs/routes/enrollmentProjection.js  | 20 ++++++++++++++++++++
 src/libs/routes/financial.js             | 20 ++++++++++++++++++++
 src/libs/routes/glossEnrollmentRatio.js  | 20 ++++++++++++++++++++
 src/libs/routes/idhm.js                  | 20 ++++++++++++++++++++
 src/libs/routes/idhme.js                 | 20 ++++++++++++++++++++
 src/libs/routes/idhml.js                 | 20 ++++++++++++++++++++
 src/libs/routes/idhmr.js                 | 20 ++++++++++++++++++++
 src/libs/routes/infrastructure.js        | 20 ++++++++++++++++++++
 src/libs/routes/liquidEnrollmentRatio.js | 20 ++++++++++++++++++++
 src/libs/routes/outOfSchool.js           | 20 ++++++++++++++++++++
 src/libs/routes/pibpercapita.js          | 20 ++++++++++++++++++++
 src/libs/routes/population.js            | 20 ++++++++++++++++++++
 src/libs/routes/portalMec.js             | 20 ++++++++++++++++++++
 src/libs/routes/portalMecInep.js         | 20 ++++++++++++++++++++
 src/libs/routes/rateSchool.js            | 20 ++++++++++++++++++++
 src/libs/routes/region.js                | 20 ++++++++++++++++++++
 src/libs/routes/resetToken.js            | 20 ++++++++++++++++++++
 src/libs/routes/school.js                | 20 ++++++++++++++++++++
 src/libs/routes/schoolInfrastructure.js  | 20 ++++++++++++++++++++
 src/libs/routes/simulation.js            | 20 ++++++++++++++++++++
 src/libs/routes/siope.js                 | 20 ++++++++++++++++++++
 src/libs/routes/spatial.js               | 20 ++++++++++++++++++++
 src/libs/routes/state.js                 | 20 ++++++++++++++++++++
 src/libs/routes/teacher.js               | 20 ++++++++++++++++++++
 src/libs/routes/transport.js             | 20 ++++++++++++++++++++
 src/libs/routes/user.js                  | 20 ++++++++++++++++++++
 src/libs/routes/verifyToken.js           | 20 ++++++++++++++++++++
 41 files changed, 820 insertions(+)

diff --git a/src/libs/routes/api.js b/src/libs/routes/api.js
index c9150981..5141ec78 100644
--- a/src/libs/routes/api.js
+++ b/src/libs/routes/api.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const api = express();
diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js
index a52ce99d..c7ca3bc6 100644
--- a/src/libs/routes/auxiliar.js
+++ b/src/libs/routes/auxiliar.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const auxiliarApp = express.Router();
diff --git a/src/libs/routes/city.js b/src/libs/routes/city.js
index 1f6aee12..9342f64c 100644
--- a/src/libs/routes/city.js
+++ b/src/libs/routes/city.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const cityApp = express.Router();
diff --git a/src/libs/routes/class.js b/src/libs/routes/class.js
index a01fa0ab..9819a23b 100644
--- a/src/libs/routes/class.js
+++ b/src/libs/routes/class.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const classApp = express.Router();
diff --git a/src/libs/routes/classCount.js b/src/libs/routes/classCount.js
index aba72e13..c7fa1d03 100644
--- a/src/libs/routes/classCount.js
+++ b/src/libs/routes/classCount.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const classCountApp = express.Router();
diff --git a/src/libs/routes/classroom.js b/src/libs/routes/classroom.js
index 2a8ee391..a2267779 100644
--- a/src/libs/routes/classroom.js
+++ b/src/libs/routes/classroom.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const classroomApp = express.Router();
diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 71d6f54e..7489ddcb 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const classroomCountApp = express.Router();
diff --git a/src/libs/routes/cub.js b/src/libs/routes/cub.js
index 5310f0be..b6bb034c 100644
--- a/src/libs/routes/cub.js
+++ b/src/libs/routes/cub.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const cubApp = express.Router();
diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js
index 7847c1a3..3588a547 100644
--- a/src/libs/routes/dailyChargeAmount.js
+++ b/src/libs/routes/dailyChargeAmount.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const dailyChargeAmountApp = express.Router();
diff --git a/src/libs/routes/distributionFactor.js b/src/libs/routes/distributionFactor.js
index df4d84b7..99e1a77a 100644
--- a/src/libs/routes/distributionFactor.js
+++ b/src/libs/routes/distributionFactor.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const distributionApp = express.Router();
diff --git a/src/libs/routes/downloads.js b/src/libs/routes/downloads.js
index 2ec83b9e..9f01479d 100644
--- a/src/libs/routes/downloads.js
+++ b/src/libs/routes/downloads.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const downloadApp = express.Router();
diff --git a/src/libs/routes/educationYears.js b/src/libs/routes/educationYears.js
index 0d103883..b8173d06 100644
--- a/src/libs/routes/educationYears.js
+++ b/src/libs/routes/educationYears.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const educationYearsApp = express.Router();
diff --git a/src/libs/routes/employees.js b/src/libs/routes/employees.js
index 523eb6bc..d60ac2b6 100644
--- a/src/libs/routes/employees.js
+++ b/src/libs/routes/employees.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const employeesApp = express.Router();
diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js
index 66268b11..37629e53 100644
--- a/src/libs/routes/enrollment.js
+++ b/src/libs/routes/enrollment.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const enrollmentApp = express.Router();
diff --git a/src/libs/routes/enrollmentProjection.js b/src/libs/routes/enrollmentProjection.js
index 1bbe8ea3..7ff2ab23 100644
--- a/src/libs/routes/enrollmentProjection.js
+++ b/src/libs/routes/enrollmentProjection.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const enrollmentProjectionApp = express.Router();
diff --git a/src/libs/routes/financial.js b/src/libs/routes/financial.js
index 78c3b023..c4de6092 100644
--- a/src/libs/routes/financial.js
+++ b/src/libs/routes/financial.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const financialApp = express.Router();
diff --git a/src/libs/routes/glossEnrollmentRatio.js b/src/libs/routes/glossEnrollmentRatio.js
index 041a93ad..7183715a 100644
--- a/src/libs/routes/glossEnrollmentRatio.js
+++ b/src/libs/routes/glossEnrollmentRatio.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const glossEnrollmentRatioApp = express.Router();
diff --git a/src/libs/routes/idhm.js b/src/libs/routes/idhm.js
index 45a193e7..f21d2154 100644
--- a/src/libs/routes/idhm.js
+++ b/src/libs/routes/idhm.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const idhmApp = express.Router();
diff --git a/src/libs/routes/idhme.js b/src/libs/routes/idhme.js
index 2a1f4d03..25d9e682 100644
--- a/src/libs/routes/idhme.js
+++ b/src/libs/routes/idhme.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const idhmeApp = express.Router();
diff --git a/src/libs/routes/idhml.js b/src/libs/routes/idhml.js
index 1fddee79..aa811d8f 100644
--- a/src/libs/routes/idhml.js
+++ b/src/libs/routes/idhml.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const idhmlApp = express.Router();
diff --git a/src/libs/routes/idhmr.js b/src/libs/routes/idhmr.js
index 938d58a9..d140cc54 100644
--- a/src/libs/routes/idhmr.js
+++ b/src/libs/routes/idhmr.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const idhmrApp = express.Router();
diff --git a/src/libs/routes/infrastructure.js b/src/libs/routes/infrastructure.js
index 8b01e338..d4f08dee 100644
--- a/src/libs/routes/infrastructure.js
+++ b/src/libs/routes/infrastructure.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const infrastructureApp = express.Router();
diff --git a/src/libs/routes/liquidEnrollmentRatio.js b/src/libs/routes/liquidEnrollmentRatio.js
index 793e4f65..fd06c528 100644
--- a/src/libs/routes/liquidEnrollmentRatio.js
+++ b/src/libs/routes/liquidEnrollmentRatio.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const liquidEnrollmentRatioApp = express.Router();
diff --git a/src/libs/routes/outOfSchool.js b/src/libs/routes/outOfSchool.js
index 3d8f33d9..16c5660f 100644
--- a/src/libs/routes/outOfSchool.js
+++ b/src/libs/routes/outOfSchool.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const outOfSchoolApp = express.Router();
diff --git a/src/libs/routes/pibpercapita.js b/src/libs/routes/pibpercapita.js
index de1ec7d6..3cb91c5b 100644
--- a/src/libs/routes/pibpercapita.js
+++ b/src/libs/routes/pibpercapita.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const pibpercapitaApp = express.Router();
diff --git a/src/libs/routes/population.js b/src/libs/routes/population.js
index f0402daa..ed644e9e 100644
--- a/src/libs/routes/population.js
+++ b/src/libs/routes/population.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const populationApp = express.Router();
diff --git a/src/libs/routes/portalMec.js b/src/libs/routes/portalMec.js
index afd84e8e..29a1be6b 100644
--- a/src/libs/routes/portalMec.js
+++ b/src/libs/routes/portalMec.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const portalMecApp = express.Router();
diff --git a/src/libs/routes/portalMecInep.js b/src/libs/routes/portalMecInep.js
index 2b235891..f8108ce4 100644
--- a/src/libs/routes/portalMecInep.js
+++ b/src/libs/routes/portalMecInep.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const portalMecInepApp = express.Router();
diff --git a/src/libs/routes/rateSchool.js b/src/libs/routes/rateSchool.js
index a45865a9..a8e9253e 100644
--- a/src/libs/routes/rateSchool.js
+++ b/src/libs/routes/rateSchool.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const rateSchoolApp = express.Router();
diff --git a/src/libs/routes/region.js b/src/libs/routes/region.js
index b1076e64..f36760f3 100644
--- a/src/libs/routes/region.js
+++ b/src/libs/routes/region.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const regionApp = express.Router();
diff --git a/src/libs/routes/resetToken.js b/src/libs/routes/resetToken.js
index 34ece845..5fa96b01 100644
--- a/src/libs/routes/resetToken.js
+++ b/src/libs/routes/resetToken.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const resetTokenApp = express.Router();
diff --git a/src/libs/routes/school.js b/src/libs/routes/school.js
index 3f4dd714..120b7254 100644
--- a/src/libs/routes/school.js
+++ b/src/libs/routes/school.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const schoolApp = express.Router();
diff --git a/src/libs/routes/schoolInfrastructure.js b/src/libs/routes/schoolInfrastructure.js
index 65c4677b..f51102fe 100644
--- a/src/libs/routes/schoolInfrastructure.js
+++ b/src/libs/routes/schoolInfrastructure.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const infrastructureApp = express.Router();
diff --git a/src/libs/routes/simulation.js b/src/libs/routes/simulation.js
index 4b2e40c3..8003b54d 100644
--- a/src/libs/routes/simulation.js
+++ b/src/libs/routes/simulation.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const simulationApp = express();
diff --git a/src/libs/routes/siope.js b/src/libs/routes/siope.js
index 51c1c368..615e2225 100644
--- a/src/libs/routes/siope.js
+++ b/src/libs/routes/siope.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const siopeApp = express.Router();
diff --git a/src/libs/routes/spatial.js b/src/libs/routes/spatial.js
index 5523de7a..27341b80 100644
--- a/src/libs/routes/spatial.js
+++ b/src/libs/routes/spatial.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const libs = `${process.cwd()}/libs`;
diff --git a/src/libs/routes/state.js b/src/libs/routes/state.js
index 33778869..cb84a096 100644
--- a/src/libs/routes/state.js
+++ b/src/libs/routes/state.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const stateApp = express.Router();
diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js
index f3b2af7e..5df9ef44 100644
--- a/src/libs/routes/teacher.js
+++ b/src/libs/routes/teacher.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const teacherApp = express.Router();
diff --git a/src/libs/routes/transport.js b/src/libs/routes/transport.js
index 409cb216..b286c001 100644
--- a/src/libs/routes/transport.js
+++ b/src/libs/routes/transport.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const transportApp = express.Router();
diff --git a/src/libs/routes/user.js b/src/libs/routes/user.js
index af123a58..f32f41ab 100644
--- a/src/libs/routes/user.js
+++ b/src/libs/routes/user.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const userApp = express();
diff --git a/src/libs/routes/verifyToken.js b/src/libs/routes/verifyToken.js
index d54f64aa..a2a278c5 100644
--- a/src/libs/routes/verifyToken.js
+++ b/src/libs/routes/verifyToken.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const verifyTokenApp = express.Router();
-- 
GitLab


From 03061aa20d77e7c037b6017e8574813e1dc40687 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 10 Jan 2019 10:22:42 -0200
Subject: [PATCH 011/142] Add GNU GPL in lib/app.js and libs/config.js

---
 src/libs/app.js    | 20 ++++++++++++++++++++
 src/libs/config.js | 20 ++++++++++++++++++++
 2 files changed, 40 insertions(+)

diff --git a/src/libs/app.js b/src/libs/app.js
index 5e6d4c1d..5a109798 100644
--- a/src/libs/app.js
+++ b/src/libs/app.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 const cookieParser = require('cookie-parser');
 const bodyParser = require('body-parser');
diff --git a/src/libs/config.js b/src/libs/config.js
index 2c07d19e..cdc58c2f 100644
--- a/src/libs/config.js
+++ b/src/libs/config.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 let conf = require(`${process.cwd()}/config.json`);
 
 conf = conf[process.env.NODE_ENV];
-- 
GitLab


From 0c577658a83a3ae1e2f51d0bd5e7b71f8f5da1b9 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 10 Jan 2019 10:26:41 -0200
Subject: [PATCH 012/142] Add GNU GPL in lib/log.js file

---
 src/libs/log.js | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/src/libs/log.js b/src/libs/log.js
index ddf0303f..58f8bfba 100644
--- a/src/libs/log.js
+++ b/src/libs/log.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const libs = `${process.cwd()}/libs`;
 const config = require(`${libs}/config`);
 
-- 
GitLab


From 332a9a3882726ac12ce7668d45853ed65afe0c47 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 10 Jan 2019 10:58:17 -0200
Subject: [PATCH 013/142] Add GNU GPL in tests directory

---
 src/test/api.js                   | 20 ++++++++++++++++++++
 src/test/auxiliar.js              | 20 ++++++++++++++++++++
 src/test/city.js                  | 20 ++++++++++++++++++++
 src/test/class.js                 | 20 ++++++++++++++++++++
 src/test/classroom.js             | 20 ++++++++++++++++++++
 src/test/cub.js                   | 20 ++++++++++++++++++++
 src/test/dailyChargeAmount.js     | 20 ++++++++++++++++++++
 src/test/distributionFactor.js    | 20 ++++++++++++++++++++
 src/test/educationYears.js        | 20 ++++++++++++++++++++
 src/test/enrollment.js            | 20 ++++++++++++++++++++
 src/test/glossEnrollmentRatio.js  | 20 ++++++++++++++++++++
 src/test/id2str.js                | 20 ++++++++++++++++++++
 src/test/idhm.js                  | 20 ++++++++++++++++++++
 src/test/idhme.js                 | 20 ++++++++++++++++++++
 src/test/idhml.js                 | 20 ++++++++++++++++++++
 src/test/idhmr.js                 | 20 ++++++++++++++++++++
 src/test/infrastructure.js        | 20 ++++++++++++++++++++
 src/test/liquidEnrollmentRatio.js | 20 ++++++++++++++++++++
 src/test/pibpercapita.js          | 20 ++++++++++++++++++++
 src/test/population.js            | 20 ++++++++++++++++++++
 src/test/query.js                 | 20 ++++++++++++++++++++
 src/test/rateSchool.js            | 20 ++++++++++++++++++++
 src/test/region.js                | 20 ++++++++++++++++++++
 src/test/response.js              | 20 ++++++++++++++++++++
 src/test/school.js                | 20 ++++++++++++++++++++
 src/test/schoolCount.js           | 20 ++++++++++++++++++++
 src/test/simulation.js            | 20 ++++++++++++++++++++
 src/test/siope.js                 | 20 ++++++++++++++++++++
 src/test/state.js                 | 20 ++++++++++++++++++++
 src/test/teacher.js               | 20 ++++++++++++++++++++
 src/test/transport.js             | 20 ++++++++++++++++++++
 src/test/user.js                  | 20 ++++++++++++++++++++
 32 files changed, 640 insertions(+)

diff --git a/src/test/api.js b/src/test/api.js
index b5476ea6..cd37a5f7 100644
--- a/src/test/api.js
+++ b/src/test/api.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/auxiliar.js b/src/test/auxiliar.js
index 1bb0d309..9732499d 100644
--- a/src/test/auxiliar.js
+++ b/src/test/auxiliar.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/city.js b/src/test/city.js
index 1ea61a62..9defbeb6 100644
--- a/src/test/city.js
+++ b/src/test/city.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/class.js b/src/test/class.js
index 3000476c..a10ee1f1 100644
--- a/src/test/class.js
+++ b/src/test/class.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/classroom.js b/src/test/classroom.js
index 9a6fd00a..3f1d60f2 100644
--- a/src/test/classroom.js
+++ b/src/test/classroom.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/cub.js b/src/test/cub.js
index 751ca40a..931ada9a 100644
--- a/src/test/cub.js
+++ b/src/test/cub.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/dailyChargeAmount.js b/src/test/dailyChargeAmount.js
index 6cef69f4..60c4f118 100644
--- a/src/test/dailyChargeAmount.js
+++ b/src/test/dailyChargeAmount.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/distributionFactor.js b/src/test/distributionFactor.js
index e733fc59..1233ad85 100644
--- a/src/test/distributionFactor.js
+++ b/src/test/distributionFactor.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/educationYears.js b/src/test/educationYears.js
index 7a47b307..7d21d8ef 100644
--- a/src/test/educationYears.js
+++ b/src/test/educationYears.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/enrollment.js b/src/test/enrollment.js
index 997e5f70..fb4ca877 100644
--- a/src/test/enrollment.js
+++ b/src/test/enrollment.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/glossEnrollmentRatio.js b/src/test/glossEnrollmentRatio.js
index 4043bf4a..562244cb 100644
--- a/src/test/glossEnrollmentRatio.js
+++ b/src/test/glossEnrollmentRatio.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/id2str.js b/src/test/id2str.js
index 8d6f5457..fdf97cbf 100644
--- a/src/test/id2str.js
+++ b/src/test/id2str.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/idhm.js b/src/test/idhm.js
index cea8893e..82c06142 100644
--- a/src/test/idhm.js
+++ b/src/test/idhm.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/idhme.js b/src/test/idhme.js
index dc338d38..767e788e 100644
--- a/src/test/idhme.js
+++ b/src/test/idhme.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/idhml.js b/src/test/idhml.js
index 90312b06..c3bfd5dc 100644
--- a/src/test/idhml.js
+++ b/src/test/idhml.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/idhmr.js b/src/test/idhmr.js
index eb06b37d..4f7a308c 100644
--- a/src/test/idhmr.js
+++ b/src/test/idhmr.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/infrastructure.js b/src/test/infrastructure.js
index 8714a73c..a600d8c3 100644
--- a/src/test/infrastructure.js
+++ b/src/test/infrastructure.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/liquidEnrollmentRatio.js b/src/test/liquidEnrollmentRatio.js
index ec0489e9..e20e97d1 100644
--- a/src/test/liquidEnrollmentRatio.js
+++ b/src/test/liquidEnrollmentRatio.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/pibpercapita.js b/src/test/pibpercapita.js
index e044b1c0..bd693bdc 100644
--- a/src/test/pibpercapita.js
+++ b/src/test/pibpercapita.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/population.js b/src/test/population.js
index 37be404f..78514946 100644
--- a/src/test/population.js
+++ b/src/test/population.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/query.js b/src/test/query.js
index cad0102f..2bc37621 100644
--- a/src/test/query.js
+++ b/src/test/query.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/rateSchool.js b/src/test/rateSchool.js
index b029fa42..725dd5e6 100644
--- a/src/test/rateSchool.js
+++ b/src/test/rateSchool.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/region.js b/src/test/region.js
index daf45685..fc530c28 100644
--- a/src/test/region.js
+++ b/src/test/region.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/response.js b/src/test/response.js
index bdafc9d8..c0c08557 100644
--- a/src/test/response.js
+++ b/src/test/response.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/school.js b/src/test/school.js
index 0ca4c78b..7e578dc9 100644
--- a/src/test/school.js
+++ b/src/test/school.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/schoolCount.js b/src/test/schoolCount.js
index 30504589..839415ab 100644
--- a/src/test/schoolCount.js
+++ b/src/test/schoolCount.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/simulation.js b/src/test/simulation.js
index cd68d680..d7a99a97 100644
--- a/src/test/simulation.js
+++ b/src/test/simulation.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/siope.js b/src/test/siope.js
index ac13ead5..4f88f314 100644
--- a/src/test/siope.js
+++ b/src/test/siope.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/state.js b/src/test/state.js
index 5cea7a4f..30a25488 100644
--- a/src/test/state.js
+++ b/src/test/state.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/teacher.js b/src/test/teacher.js
index 30eddee8..c6ed6508 100644
--- a/src/test/teacher.js
+++ b/src/test/teacher.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/transport.js b/src/test/transport.js
index 78a4075b..70ed9e42 100644
--- a/src/test/transport.js
+++ b/src/test/transport.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
diff --git a/src/test/user.js b/src/test/user.js
index 3109960b..ab44a78d 100644
--- a/src/test/user.js
+++ b/src/test/user.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 process.env.NODE_ENV = 'test';
 
 const chai = require('chai');
-- 
GitLab


From 6ea4d400b3b4bee1f5d513caec3a6919504c83fe Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 10 Jan 2019 10:59:18 -0200
Subject: [PATCH 014/142] Add GNU GPL in src/server.js file

---
 src/server.js | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/src/server.js b/src/server.js
index 889151c2..37c55df6 100644
--- a/src/server.js
+++ b/src/server.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const debug = require('debug')('simcaq-api');
 const libs = `${process.cwd()}/libs`;
 const config = require(`${libs}/config`);
-- 
GitLab


From 120521bc484c86aef272bed13104436bd2c56d3b Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Wed, 30 Jan 2019 11:23:15 -0200
Subject: [PATCH 015/142] [new_enrollment_variable]reducing size of query with
 new variable

---
 src/libs/routes/enrollment.js | 28 ++++++++++++++++++++++++++--
 1 file changed, 26 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js
index 66268b11..a601cf0e 100644
--- a/src/libs/routes/enrollment.js
+++ b/src/libs/routes/enrollment.js
@@ -398,6 +398,31 @@ rqf.addField({
         foreign: ['escola_id', 'ano_censo'],
         foreignTable: 'matricula'
     }
+}, 'dims').addValueToField({
+    name: 'locale_id',
+    table: 'matricula',
+    tableField: 'localizacao_id',
+    resultField: 'locale_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'localizacao_id'
+    }
+}, 'dims').addValueToField({
+    name: 'school_id',
+    table: 'escola',
+    tableField: 'id',
+    resultField: 'school_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'id'
+    },
+    join: {
+        primary: ['id', 'ano_censo'],
+        foreign: ['escola_id', 'ano_censo'],
+        foreignTable: 'matricula'
+    }
 }, 'dims').addValueToField({
     name: 'school',
     table: 'escola',
@@ -467,8 +492,8 @@ rqf.addField({
     name: 'ethnic_group',
     table: 'matricula',
     tableField: 'cor_raca_id',
-    resultField: 'ethnic_group_id',
     where: {
+      resultField: 'ethnic_group_id',
         relation: '=',
         type: 'integer',
         field: 'cor_raca_id'
@@ -517,7 +542,6 @@ rqf.addField({
 
 enrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.sql.field('COUNT(*)', 'total')
-    .field("'Brasil'", 'name')
     .field('matricula.ano_censo', 'year')
     .from('matricula')
     .group('matricula.ano_censo')
-- 
GitLab


From b317718038899b78a85245e518530b85be809ac5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 7 Feb 2019 09:58:18 -0200
Subject: [PATCH 016/142] Fixed tests

---
 src/test/cub.js                   | 14 --------------
 src/test/dailyChargeAmount.js     | 12 ++++--------
 src/test/enrollment.js            | 12 ++++++------
 src/test/id2str.js                | 22 ++++++++++-----------
 src/test/liquidEnrollmentRatio.js | 32 -------------------------------
 src/test/school.js                | 11 -----------
 src/test/transport.js             |  4 ++--
 7 files changed, 23 insertions(+), 84 deletions(-)

diff --git a/src/test/cub.js b/src/test/cub.js
index 931ada9a..ea6c0d68 100644
--- a/src/test/cub.js
+++ b/src/test/cub.js
@@ -100,20 +100,6 @@ describe('request cub', () => {
             });
     });
 
-    it('should list the years and months', (done) => {
-        chai.request(server)
-            .get('/api/v1/cub/year_range')
-            .end((err, res) => {
-                res.should.have.status(200);
-                res.should.be.json;
-                res.body.should.have.property('result');
-                res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('year');
-                res.body.result[0].should.have.property('month');
-                done();
-            });
-    });
-
     it('should list the price type', (done) => {
         chai.request(server)
             .get('/api/v1/cub/price_type')
diff --git a/src/test/dailyChargeAmount.js b/src/test/dailyChargeAmount.js
index 60c4f118..20fb9aea 100644
--- a/src/test/dailyChargeAmount.js
+++ b/src/test/dailyChargeAmount.js
@@ -101,7 +101,7 @@ describe('request daily charge amount', () => {
 
     it('should list education level mod', (done) => {
         chai.request(server)
-            .get('/api/v1/daily_charge_amount/education_level_mod')
+            .get('/api/v1/daily_charge_amount/average/education_level_mod')
             .end((err, res) => {
                 res.should.have.status(200);
                 res.should.be.json;
@@ -165,14 +165,10 @@ describe('request daily charge amount', () => {
         chai.request(server)
             .get('/api/v1/daily_charge_amount/average?filter=education_level_mod:["3","4","5","6"]')
             .end((err, res) => {
-                res.should.have.status(200);
+                res.should.have.status(400);
                 res.should.be.json;
-                res.body.should.have.property('result');
-                res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('year');
-                res.body.result[0].should.have.property('education_level_mod_id');
-                res.body.result[0].should.have.property('education_level_mod_name');
-                res.body.result[0].should.have.property('average_class_duration');
+                res.body.should.have.property('error');
+                res.body.error.should.be.equal('Wrong/No filter specified');
                 done();
             });
     });
diff --git a/src/test/enrollment.js b/src/test/enrollment.js
index fb4ca877..af5f50a1 100644
--- a/src/test/enrollment.js
+++ b/src/test/enrollment.js
@@ -260,8 +260,8 @@ describe('request enrollments', () => {
                 res.should.be.json;
                 res.body.should.have.property('result');
                 res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('name');
                 res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('year');
                 done();
             });
     });
@@ -274,8 +274,8 @@ describe('request enrollments', () => {
                 res.should.be.json;
                 res.body.should.have.property('result');
                 res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('name');
                 res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('year');
                 done();
             });
     });
@@ -288,7 +288,7 @@ describe('request enrollments', () => {
                 res.should.be.json;
                 res.body.should.have.property('result');
                 res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('name');
+                res.body.result[0].should.have.property('year');
                 res.body.result[0].should.have.property('total');
                 done();
             });
@@ -302,7 +302,7 @@ describe('request enrollments', () => {
                 res.should.be.json;
                 res.body.should.have.property('result');
                 res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('name');
+                res.body.result[0].should.have.property('year');
                 res.body.result[0].should.have.property('total');
                 done();
             });
@@ -316,7 +316,7 @@ describe('request enrollments', () => {
                 res.should.be.json;
                 res.body.should.have.property('result');
                 res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('name');
+                res.body.result[0].should.have.property('year');
                 res.body.result[0].should.have.property('total');
                 done();
             });
@@ -465,7 +465,7 @@ describe('request enrollments', () => {
                 res.should.be.json;
                 res.body.should.have.property('result');
                 res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('ethnic_group_name');
+                res.body.result[0].should.have.property('cor_raca_id');
                 done();
             });
     });
diff --git a/src/test/id2str.js b/src/test/id2str.js
index fdf97cbf..5b0fd115 100644
--- a/src/test/id2str.js
+++ b/src/test/id2str.js
@@ -140,17 +140,17 @@ describe('id2str middleware', () => {
     });
 
     it('should transform a full age range id', (done) => {
-        expect(id2str.fullAgeRange(1)).to.deep.equal('0-3');
-        expect(id2str.fullAgeRange(2)).to.deep.equal('4-5');
-        expect(id2str.fullAgeRange(3)).to.deep.equal('6-10');
-        expect(id2str.fullAgeRange(4)).to.deep.equal('11-14');
-        expect(id2str.fullAgeRange(5)).to.deep.equal('15-17');
-        expect(id2str.fullAgeRange(6)).to.deep.equal('18-24');
-        expect(id2str.fullAgeRange(7)).to.deep.equal('25-29');
-        expect(id2str.fullAgeRange(8)).to.deep.equal('30-40');
-        expect(id2str.fullAgeRange(9)).to.deep.equal('41-50');
-        expect(id2str.fullAgeRange(10)).to.deep.equal('51-64');
-        expect(id2str.fullAgeRange(11)).to.deep.equal('64+');
+        expect(id2str.fullAgeRange(1)).to.deep.equal('0 a 3 anos');
+        expect(id2str.fullAgeRange(2)).to.deep.equal('4 a 5 anos');
+        expect(id2str.fullAgeRange(3)).to.deep.equal('6 a 10 anos');
+        expect(id2str.fullAgeRange(4)).to.deep.equal('11 a 14 anos');
+        expect(id2str.fullAgeRange(5)).to.deep.equal('15 a 17 anos');
+        expect(id2str.fullAgeRange(6)).to.deep.equal('18 a 24 anos');
+        expect(id2str.fullAgeRange(7)).to.deep.equal('25 a 29 anos');
+        expect(id2str.fullAgeRange(8)).to.deep.equal('30 a 40 anos');
+        expect(id2str.fullAgeRange(9)).to.deep.equal('41 a 50 anos');
+        expect(id2str.fullAgeRange(10)).to.deep.equal('51 a 64 anos');
+        expect(id2str.fullAgeRange(11)).to.deep.equal('Mais de 64 anos');
         expect(id2str.fullAgeRange(12)).to.deep.equal('Não declarada');
 
         done();
diff --git a/src/test/liquidEnrollmentRatio.js b/src/test/liquidEnrollmentRatio.js
index e20e97d1..bbea4bb6 100644
--- a/src/test/liquidEnrollmentRatio.js
+++ b/src/test/liquidEnrollmentRatio.js
@@ -179,36 +179,4 @@ describe('request liquid enrollment ratio', () => {
             });
     });
 
-    it('should list the filter of education level basic', (done) => {
-        chai.request(server)
-            .get('/api/v1/liquid_enrollment_ratio?filter=education_level_basic:["1"]')
-            .end((err, res) => {
-                res.should.have.status(200);
-                res.should.be.json;
-                res.body.should.have.property('result');
-                res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('total');
-                res.body.result[0].should.have.property('year');
-                res.body.result[0].should.have.property('partial');
-                res.body.result[0].should.have.property('denominator');
-                done();
-            });
-    });
-
-    it('should list the filter of education level basic', (done) => {
-        chai.request(server)
-            .get('/api/v1/liquid_enrollment_ratio?filter=education_level_basic:["1","2"]')
-            .end((err, res) => {
-                res.should.have.status(200);
-                res.should.be.json;
-                res.body.should.have.property('result');
-                res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('total');
-                res.body.result[0].should.have.property('year');
-                res.body.result[0].should.have.property('partial');
-                res.body.result[0].should.have.property('denominator');
-                done();
-            });
-    });
-
 });
diff --git a/src/test/school.js b/src/test/school.js
index 7e578dc9..7f05a674 100644
--- a/src/test/school.js
+++ b/src/test/school.js
@@ -146,15 +146,4 @@ describe('request schools', () => {
             });
     });
 
-    it('should return 400 with no filters', (done) => {
-        chai.request(server)
-            .get('/api/v1/school')
-            .end((err, res) => {
-                res.should.have.status(400);
-                res.should.be.json;
-                res.body.should.have.property('error');
-                res.body.error.should.be.equal('Wrong/No filter specified');
-                done();
-            })
-    });
 });
diff --git a/src/test/transport.js b/src/test/transport.js
index 70ed9e42..39374999 100644
--- a/src/test/transport.js
+++ b/src/test/transport.js
@@ -167,9 +167,9 @@ describe('request transport', () => {
             });
     });
 
-    it('should list the education level basic', (done) => {
+    it('should list the education level mod', (done) => {
         chai.request(server)
-            .get('/api/v1/transport/education_level_basic')
+            .get('/api/v1/transport/education_level_mod')
             .end((err, res) => {
                 res.should.have.status(200);
                 res.should.be.json;
-- 
GitLab


From 959db733ce8a56c5780aef560bff26831b6f1401 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 7 Feb 2019 11:33:16 -0200
Subject: [PATCH 017/142] Changed cod_locazicao to localizao_id

---
 src/libs/routes/school.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/school.js b/src/libs/routes/school.js
index 120b7254..13abdfa8 100644
--- a/src/libs/routes/school.js
+++ b/src/libs/routes/school.js
@@ -384,12 +384,12 @@ rqfCount.addField({
 }).addValue({
     name: 'location',
     table: 'escola',
-    tableField: 'cod_localizacao',
+    tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_localizacao'
+        field: 'localizacao_id'
     }
 }).addValue({
     name: 'rural_location',
-- 
GitLab


From 994455d3a96ad02b3c4f64d33e69efaf42bdaeba Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 7 Feb 2019 11:53:16 -0200
Subject: [PATCH 018/142] Changed cod_localizacao to localizao_id

---
 src/libs/routes/auxiliar.js             |  4 ++--
 src/libs/routes/classroom.js            |  4 ++--
 src/libs/routes/employees.js            |  8 ++++----
 src/libs/routes/infrastructure.js       | 12 ++++++------
 src/libs/routes/schoolInfrastructure.js |  8 ++++----
 src/libs/routes/spatial.js              |  4 ++--
 src/libs/routes/teacher.js              |  4 ++--
 7 files changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js
index c7ca3bc6..74e05c77 100644
--- a/src/libs/routes/auxiliar.js
+++ b/src/libs/routes/auxiliar.js
@@ -291,12 +291,12 @@ rqf.addField({
 }, 'filter').addValue({
     name: 'location',
     table: 'docente',
-    tableField: 'cod_localizacao',
+    tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_localizacao'
+        field: 'localizacao_id'
     }
 }).addValue({
     name: 'min_year',
diff --git a/src/libs/routes/classroom.js b/src/libs/routes/classroom.js
index a2267779..a445e941 100644
--- a/src/libs/routes/classroom.js
+++ b/src/libs/routes/classroom.js
@@ -230,12 +230,12 @@ rqf.addField({
 }).addValue({
     name: 'location',
     table: 'escola',
-    tableField: 'cod_localizacao',
+    tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_localizacao'
+        field: 'localizacao_id'
     }
 });
 
diff --git a/src/libs/routes/employees.js b/src/libs/routes/employees.js
index d60ac2b6..9aedbcb1 100644
--- a/src/libs/routes/employees.js
+++ b/src/libs/routes/employees.js
@@ -228,12 +228,12 @@ rqfSchool.addField({
 }, 'filter').addValue({
     name: 'location',
     table: '@',
-    tableField: 'cod_localizacao',
+    tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_localizacao'
+        field: 'localizacao_id'
     }
 }).addValue({
     name: 'rural_location',
@@ -388,12 +388,12 @@ rqfTeacher.addField({
 }, 'filter').addValue({
     name: 'location',
     table: '@',
-    tableField: 'cod_localizacao',
+    tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_localizacao'
+        field: 'localizacao_id'
     }
 }).addValue({
     name: 'rural_location',
diff --git a/src/libs/routes/infrastructure.js b/src/libs/routes/infrastructure.js
index d4f08dee..8630cb94 100644
--- a/src/libs/routes/infrastructure.js
+++ b/src/libs/routes/infrastructure.js
@@ -198,12 +198,12 @@ rqf.addField({
 }).addValue({
     name: 'location',
     table: 'escola',
-    tableField: 'cod_localizacao',
+    tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_localizacao'
+        field: 'localizacao_id'
     }
 }).addValue({
     name: 'rural_location',
@@ -316,7 +316,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
 
     // Bibliotecas
     let allLibraries = allSchools.clone();
-    allLibraries.where('escola.func_predio_escolar = 1 AND escola.cod_localizacao = 1');
+    allLibraries.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 1');
     req.queryIndex.allLibraries = req.querySet.push(allLibraries) - 1;
 
     let haveLibraries = allLibraries.clone();
@@ -325,7 +325,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
 
     // Bibliotecas/Sala de leitura
     let allLibrariesReadingRoom = allSchools.clone();
-    allLibrariesReadingRoom.where('escola.func_predio_escolar = 1 AND escola.cod_localizacao = 2');
+    allLibrariesReadingRoom.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 2');
     req.queryIndex.allLibrariesReadingRoom = req.querySet.push(allLibrariesReadingRoom) - 1;
 
     let haveLibrariesReadingRoom = allLibrariesReadingRoom.clone();
@@ -372,7 +372,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
 
     // Quadra
     let allSportsCourt = allScienceLab.clone();
-    allSportsCourt.where('escola.cod_localizacao = 1');
+    allSportsCourt.where('escola.localizacao_id = 1');
     req.queryIndex.allSportsCourt = req.querySet.push(allSportsCourt) - 1;
 
     let haveSportsCourt = allSportsCourt.clone();
@@ -397,7 +397,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
 
     // Sala de direção
     let allDirectorRoom = allSchools.clone();
-    allDirectorRoom.where('escola.func_predio_escolar = 1 AND escola.cod_localizacao = 1');
+    allDirectorRoom.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 1');
     req.queryIndex.allDirectorRoom = req.querySet.push(allDirectorRoom) - 1;
 
     let haveDirectorRoom = allDirectorRoom.clone();
diff --git a/src/libs/routes/schoolInfrastructure.js b/src/libs/routes/schoolInfrastructure.js
index f51102fe..ca7cbd28 100644
--- a/src/libs/routes/schoolInfrastructure.js
+++ b/src/libs/routes/schoolInfrastructure.js
@@ -191,12 +191,12 @@ rqf.addField({
 }).addValue({
     name: 'location',
     table: 'escola',
-    tableField: 'cod_localizacao',
+    tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_localizacao'
+        field: 'localizacao_id'
     }
 }).addValue({
     name: 'rural_location',
@@ -336,11 +336,11 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.allSchools = req.querySet.push(allSchools) - 1;
 
     let allUrbanSchools = allSchools.clone();
-    allUrbanSchools.where('escola.cod_localizacao = 1');
+    allUrbanSchools.where('escola.localizacao_id = 1');
     req.queryIndex.allUrbanSchools = req.querySet.push(allUrbanSchools) - 1;
 
     let allCountrySchools = allSchools.clone();
-    allCountrySchools.where('escola.cod_localizacao = 2');
+    allCountrySchools.where('escola.localizacao_id = 2');
     req.queryIndex.allCountrySchools = req.querySet.push(allCountrySchools) - 1;
 
     let allSchoolsNotSchoolBuilding = req.sql.clone();
diff --git a/src/libs/routes/spatial.js b/src/libs/routes/spatial.js
index 27341b80..dd7fe97a 100644
--- a/src/libs/routes/spatial.js
+++ b/src/libs/routes/spatial.js
@@ -223,11 +223,11 @@ spatialApp.get('/educational', rqf.parse(), rqf.build(), (req, res, next) => {
         .from('localizacao')
         .from('turma')
         .from('escola')
-        .where('escola.cod_localizacao=localizacao.id')
+        .where('escola.localizacao_id=localizacao.id')
         .where('escola.ano_censo=turma.ano_censo AND escola.id=turma.escola_id')
         .where(`escola.ano_censo IN (${censusYearQry})`)
         .where('turma.tipo_turma_id = 0')
-        .group('escola.cod_localizacao')
+        .group('escola.localizacao_id')
         .group('escola.ano_censo')
         .group('localizacao.descricao')
         .order('localizacao.descricao');
diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js
index 5df9ef44..b9a86226 100644
--- a/src/libs/routes/teacher.js
+++ b/src/libs/routes/teacher.js
@@ -349,12 +349,12 @@ rqf.addField({
 }, 'filter').addValue({
     name: 'location',
     table: 'docente',
-    tableField: 'cod_localizacao',
+    tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_localizacao'
+        field: 'localizacao_id'
     }
 }).addValue({
     name: 'rural_location',
-- 
GitLab


From 76c4d41bbf2cd6048200344132aa8a4e6a08fc77 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Fri, 8 Feb 2019 09:25:16 -0200
Subject: [PATCH 019/142] Add route number of university

---
 src/libs/convert/academicOrganization.js |  36 ++++++
 src/libs/convert/upperAdmDependency.js   |  40 ++++++
 src/libs/middlewares/id2str.js           |   5 +-
 src/libs/routes/api.js                   |   3 +
 src/libs/routes/university.js            | 155 +++++++++++++++++++++++
 5 files changed, 238 insertions(+), 1 deletion(-)
 create mode 100644 src/libs/convert/academicOrganization.js
 create mode 100644 src/libs/convert/upperAdmDependency.js
 create mode 100644 src/libs/routes/university.js

diff --git a/src/libs/convert/academicOrganization.js b/src/libs/convert/academicOrganization.js
new file mode 100644
index 00000000..14611d15
--- /dev/null
+++ b/src/libs/convert/academicOrganization.js
@@ -0,0 +1,36 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function academicOrganization(id) {
+    switch (id) {
+        case 1:
+        return 'Universidade';
+        case 2:
+        return 'Centro Universitário';
+        case 3:
+        return 'Faculdade';
+        case 4:
+        return 'Instituto Federal de Educação, Ciência e Tecnologia';
+        case 5:
+        return 'Centro Federal de Educação Tecnológica';
+        default:
+        return 'Não classificada';
+    }
+};
diff --git a/src/libs/convert/upperAdmDependency.js b/src/libs/convert/upperAdmDependency.js
new file mode 100644
index 00000000..311475ff
--- /dev/null
+++ b/src/libs/convert/upperAdmDependency.js
@@ -0,0 +1,40 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function upperAdmDependency(id) {
+    switch (id) {
+        case 1:
+        return 'Pública Federal';
+        case 2:
+        return 'Pública Estadual';
+        case 3:
+        return 'Pública Municipal';
+        case 4:
+        return 'Privada com fins lucrativos';
+        case 5:
+        return 'Privada sem fins lucrativos';
+        case 6:
+        return 'Privada confessional';
+        case 7:
+        return 'Especial';
+        default:
+        return 'Não classificada';
+    }
+};
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 65a8b3ca..549c733a 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -53,6 +53,7 @@ const specialClass = require(`${libs}/convert/booleanVariable`);
 const integralTime = require(`${libs}/convert/integralTime`);
 const educationLevelSchoolYear = require(`${libs}/convert/educationLevelSchoolYear`);
 const pfe = require(`${libs}/convert/pfe`);
+const upperAdmDependency = require(`${libs}/convert/upperAdmDependency`);
 
 const ids = {
     gender_id: gender,
@@ -97,6 +98,7 @@ const ids = {
     special_class_id: specialClass,
     education_level_school_year_id: educationLevelSchoolYear,
     pfe_id: pfe,
+    upper_adm_dependency_id: upperAdmDependency,
 };
 
 function transform(removeId=false) {
@@ -167,5 +169,6 @@ module.exports = {
     useTransport,
     transportationManager,
     specialClass,
-    integralTime
+    integralTime,
+    upperAdmDependency
 };
diff --git a/src/libs/routes/api.js b/src/libs/routes/api.js
index 5141ec78..680bf7bb 100644
--- a/src/libs/routes/api.js
+++ b/src/libs/routes/api.js
@@ -106,6 +106,8 @@ const employees = require(`${libs}/routes/employees`);
 
 const financial = require(`${libs}/routes/financial`);
 
+const university = require(`${libs}/routes/university`);
+
 api.get('/', (req, res) => {
     res.json({ msg: 'SimCAQ API is running' });
 });
@@ -151,6 +153,7 @@ api.use('/portal_mec_inep', portalMecInep);
 api.use('/enrollment_projection', enrollmentProjection);
 api.use('/employees', employees);
 api.use('/financial', financial);
+api.use('/university', university);
 
 
 module.exports = api;
diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
new file mode 100644
index 00000000..ead91a2a
--- /dev/null
+++ b/src/libs/routes/university.js
@@ -0,0 +1,155 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+const express = require('express');
+
+const universityApp = express.Router();
+
+const libs = `${process.cwd()}/libs`;
+
+const 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();
+
+universityApp.use(cache('15 day'));
+
+universityApp.get('/upper_adm_dependency', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 7; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.upperAdmDependency(i)
+        });
+    };
+    next();
+}, response('upper_adm_dependency'));
+
+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: 'evader_ag'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'municipio_id',
+        foreignTable: 'evader_ag'
+    }
+}).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: '@'
+    }
+}).addValue({
+    name: 'upper_adm_dependency',
+    table: 'ies_ens_superior',
+    tableField: 'cod_categoria_administrativa',
+    resultField: 'upper_adm_dependency_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        table: 'ies_ens_superior',
+        field: 'cod_categoria_administrativa'
+    }
+}).addValue({
+    name: 'organization_academic',
+    table: 'ies_ens_superior',
+    tableField: 'cod_organizacao_academica',
+    resultField: 'organization_academic_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        table: 'ies_ens_superior',
+        field: 'cod_organizacao_academica'
+    }
+});
+
+universityApp.get('/', rqf.parse(), (req, res, next) => {
+    req.sql.field('COUNT(*)', 'total')
+    .field("'Brasil'", 'name')
+    .field('ies_ens_superior.ano_censo', 'year')
+    .from('ies_ens_superior')
+    .group('ies_ens_superior.ano_censo')
+    .order('ies_ens_superior.ano_censo')
+
+    next();
+}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('university'));
+
+module.exports = universityApp;
-- 
GitLab


From 0cc27c84af3200354491febe27549807644ed700 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Mon, 11 Feb 2019 09:08:02 -0200
Subject: [PATCH 020/142] Add year range

---
 src/libs/middlewares/id2str.js |  5 ++++-
 src/libs/routes/university.js  | 24 ++++++++++++++++++++++++
 2 files changed, 28 insertions(+), 1 deletion(-)

diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 549c733a..bfa4dc7e 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -54,6 +54,7 @@ const integralTime = require(`${libs}/convert/integralTime`);
 const educationLevelSchoolYear = require(`${libs}/convert/educationLevelSchoolYear`);
 const pfe = require(`${libs}/convert/pfe`);
 const upperAdmDependency = require(`${libs}/convert/upperAdmDependency`);
+const academicOrganization = require(`${libs}/convert/academicOrganization`);
 
 const ids = {
     gender_id: gender,
@@ -99,6 +100,7 @@ const ids = {
     education_level_school_year_id: educationLevelSchoolYear,
     pfe_id: pfe,
     upper_adm_dependency_id: upperAdmDependency,
+    academic_organization_id: academicOrganization,
 };
 
 function transform(removeId=false) {
@@ -170,5 +172,6 @@ module.exports = {
     transportationManager,
     specialClass,
     integralTime,
-    upperAdmDependency
+    upperAdmDependency,
+    academicOrganization
 };
diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index ead91a2a..37dc5d22 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -55,6 +55,30 @@ universityApp.get('/upper_adm_dependency', (req, res, next) => {
     next();
 }, response('upper_adm_dependency'));
 
+universityApp.get('/years', (req, res, next) => {
+    req.sql.from('ies_ens_superior')
+    .field('DISTINCT ies_ens_superior.ano_censo', 'year');
+    next();
+}, query, response('years'));
+
+universityApp.get('/year_range', (req, res, next) => {
+    req.sql.from('ies_ens_superior')
+    .field('MIN(ies_ens_superior.ano_censo)', 'start_year')
+    .field('MAX(ies_ens_superior.ano_censo)', 'end_year');
+    next();
+}, query, response('range'));
+
+universityApp.get('/academic_organization', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 5; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.academicOrganization(i)
+        });
+    };
+    next();
+}, response('academic_organization'));
+
 rqf.addField({
     name: 'filter',
     field: false,
-- 
GitLab


From 8a9c80f9e1c3dfb2e0a2b3dc5ae317fdd8c33a5f Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Mon, 11 Feb 2019 10:17:12 -0200
Subject: [PATCH 021/142] Fix ethnic_group in enrollment

---
 src/libs/routes/enrollment.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js
index 389595ec..65110003 100644
--- a/src/libs/routes/enrollment.js
+++ b/src/libs/routes/enrollment.js
@@ -512,8 +512,8 @@ rqf.addField({
     name: 'ethnic_group',
     table: 'matricula',
     tableField: 'cor_raca_id',
+    resultField: 'ethnic_group_id',
     where: {
-      resultField: 'ethnic_group_id',
         relation: '=',
         type: 'integer',
         field: 'cor_raca_id'
-- 
GitLab


From 3ac123d34b5ccfd5f88fc902fd6ee78ff6397a2e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Tue, 12 Feb 2019 08:15:45 -0200
Subject: [PATCH 022/142] Add new tests

---
 src/libs/routes/transport.js      |  10 -
 src/test/class.js                 |   4 +-
 src/test/classCount.js            | 318 ++++++++++++++++++++++++++++++
 src/test/cub.js                   |  31 +++
 src/test/dailyChargeAmount.js     | 113 ++++++++++-
 src/test/employees.js             | 215 ++++++++++++++++++++
 src/test/enrollment.js            |  14 ++
 src/test/glossEnrollmentRatio.js  |  13 ++
 src/test/liquidEnrollmentRatio.js |  32 +++
 src/test/outOfSchool.js           | 232 ++++++++++++++++++++++
 src/test/schoolCount.js           |  56 +++---
 src/test/transport.js             |  18 +-
 12 files changed, 1013 insertions(+), 43 deletions(-)
 create mode 100644 src/test/classCount.js
 create mode 100644 src/test/employees.js
 create mode 100644 src/test/outOfSchool.js

diff --git a/src/libs/routes/transport.js b/src/libs/routes/transport.js
index b286c001..6435833b 100644
--- a/src/libs/routes/transport.js
+++ b/src/libs/routes/transport.js
@@ -287,16 +287,6 @@ rqf.addField({
         type: 'integer',
         field: 'tipo'
     }
-}).addValue({
-    name: 'service_type',
-    table: 'matricula',
-    tableField: 'tipo',
-    resultField: 'service_type_id',
-    where: {
-        relation: '=',
-        type: 'integer',
-        field: 'tipo'
-    }
 }).addValue({
     name: 'min_year',
     table: 'matricula',
diff --git a/src/test/class.js b/src/test/class.js
index a10ee1f1..dd283b55 100644
--- a/src/test/class.js
+++ b/src/test/class.js
@@ -127,7 +127,7 @@ describe('request class', () => {
             });
     });
 
-    it('should list the administrative dependencies', (done) => {
+    it('should list the administrative dependencies detailed', (done) => {
         chai.request(server)
             .get('/api/v1/class/adm_dependency_detailed')
             .end((err, res) => {
@@ -141,7 +141,7 @@ describe('request class', () => {
             });
     });
 
-    it('should list the administrative dependencies detailed', (done) => {
+    it('should list the administrative dependencies', (done) => {
         chai.request(server)
             .get('/api/v1/class/adm_dependency')
             .end((err, res) => {
diff --git a/src/test/classCount.js b/src/test/classCount.js
new file mode 100644
index 00000000..9880db28
--- /dev/null
+++ b/src/test/classCount.js
@@ -0,0 +1,318 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+process.env.NODE_ENV = 'test';
+
+const chai = require('chai');
+
+const dirtyChai = require('dirty-chai');
+
+chai.use(dirtyChai);
+
+const chaiXml = require('chai-xml');
+
+chai.use(chaiXml);
+
+const chaiHttp = require('chai-http');
+
+const assert = chai.assert;
+
+const expect = chai.expect;
+
+const should = chai.should(); // actually call the function
+
+const libs = `${process.cwd()}/libs`;
+
+const server = require(`${libs}/app`);
+
+chai.use(chaiHttp);
+describe('request classCount', () => {
+    it('should return 400 with no filters', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/')
+            .end((err, res) => {
+                res.should.have.status(400);
+                res.should.be.json;
+                res.body.should.have.property('error');
+                res.body.error.should.be.equal('Wrong/No filter specified');
+                done();
+            });
+    });
+
+    it('should list the rural locations', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/rural_location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the education level mod', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/education_level_mod')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the education level short', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/education_level_short')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the year range', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/year_range')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('start_year');
+                res.body.result[0].should.have.property('end_year');
+                done();
+            });
+    });
+
+    it('should list the years', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/years')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                done();
+            });
+    });
+
+    it('should list the administrative dependencies', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/adm_dependency')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the administrative dependencies detailed', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/adm_dependency_detailed')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the locations', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the source', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/source')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('source');
+                done();
+            });
+    });
+
+    it('should list the simcaq class count', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/count')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('average');
+                res.body.result[0].should.have.property('median');
+                res.body.result[0].should.have.property('stddev');
+                res.body.result[0].should.have.property('first_qt');
+                res.body.result[0].should.have.property('third_qt');
+                done();
+            });
+    });
+
+    it('should list the simcaq class count with valid filter', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/count?filter=state:14')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('average');
+                res.body.result[0].should.have.property('median');
+                res.body.result[0].should.have.property('stddev');
+                res.body.result[0].should.have.property('first_qt');
+                res.body.result[0].should.have.property('third_qt');
+                done();
+            });
+    });
+
+    it('should list the simcaq class count with valid dim', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count/count?dims=region')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('average');
+                res.body.result[0].should.have.property('median');
+                res.body.result[0].should.have.property('stddev');
+                res.body.result[0].should.have.property('first_qt');
+                res.body.result[0].should.have.property('third_qt');
+                res.body.result[0].should.have.property('region_name');
+                done();
+            });
+    });
+
+    it('should list class count with education level filter', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count?filter=education_level_mod:["1"]')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('average');
+                res.body.result[0].should.have.property('median');
+                res.body.result[0].should.have.property('stddev');
+                res.body.result[0].should.have.property('first_qt');
+                res.body.result[0].should.have.property('third_qt');
+                done();
+            });
+    });
+
+    it('should list class count with education level dims', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count?dims=education_level_mod')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('average');
+                res.body.result[0].should.have.property('median');
+                res.body.result[0].should.have.property('stddev');
+                res.body.result[0].should.have.property('first_qt');
+                res.body.result[0].should.have.property('third_qt');
+                res.body.result[0].should.have.property('education_level_mod_id');
+                res.body.result[0].should.have.property('education_level_mod_name');
+                done();
+            });
+    });
+
+    it('should list class count with valid dims', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count?dims=education_level_mod,location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('average');
+                res.body.result[0].should.have.property('median');
+                res.body.result[0].should.have.property('stddev');
+                res.body.result[0].should.have.property('first_qt');
+                res.body.result[0].should.have.property('third_qt');
+                res.body.result[0].should.have.property('education_level_mod_id');
+                res.body.result[0].should.have.property('education_level_mod_name');
+                res.body.result[0].should.have.property('location_id');
+                res.body.result[0].should.have.property('location_name');
+                done();
+            });
+    });
+
+    it('should list class count with education level year limiter', (done) => {
+        chai.request(server)
+            .get('/api/v1/class_count?dims=education_level_mod&filter=min_year:2014,max_year:2014')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('average');
+                res.body.result[0].should.have.property('median');
+                res.body.result[0].should.have.property('stddev');
+                res.body.result[0].should.have.property('first_qt');
+                res.body.result[0].should.have.property('third_qt');
+                res.body.result[0].should.have.property('education_level_mod_id');
+                res.body.result[0].should.have.property('education_level_mod_name');
+                done();
+            });
+    });
+
+});    
diff --git a/src/test/cub.js b/src/test/cub.js
index ea6c0d68..475e718f 100644
--- a/src/test/cub.js
+++ b/src/test/cub.js
@@ -112,4 +112,35 @@ describe('request cub', () => {
                 done();
             });
     });
+
+    it('should return query cub wtih state dim', (done) => {
+        chai.request(server)
+            .get('/api/v1/cub?dims=state')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('cod_uf');
+                res.body.result[0].should.have.property('sigla_uf');
+                res.body.result[0].should.have.property('tipo_preco');
+                res.body.result[0].should.have.property('preco');
+                done();
+            });
+    });
+
+    it('should return query cub wtih valid filter', (done) => {
+        chai.request(server)
+            .get('/api/v1/cub?filter=min_year:2017')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('sigla_uf');
+                res.body.result[0].should.have.property('tipo_preco');
+                res.body.result[0].should.have.property('preco');
+                done();
+            });
+    });
 });
diff --git a/src/test/dailyChargeAmount.js b/src/test/dailyChargeAmount.js
index 20fb9aea..2c37d274 100644
--- a/src/test/dailyChargeAmount.js
+++ b/src/test/dailyChargeAmount.js
@@ -58,7 +58,7 @@ describe('request daily charge amount', () => {
             });
     });
 
-    it('should list the year range', (done) => {
+    it('should list the years', (done) => {
         chai.request(server)
             .get('/api/v1/daily_charge_amount/years')
             .end((err, res) => {
@@ -71,6 +71,47 @@ describe('request daily charge amount', () => {
             });
     });
 
+    it('should list the source', (done) => {
+        chai.request(server)
+            .get('/api/v1/daily_charge_amount/source')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('source');
+                done();
+            });
+    });
+
+    it('should list the adm dependency', (done) => {
+        chai.request(server)
+            .get('/api/v1/daily_charge_amount/adm_dependency')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the adm dependency detailed', (done) => {
+        chai.request(server)
+            .get('/api/v1/daily_charge_amount/adm_dependency_detailed')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
     it('should list the locations', (done) => {
         chai.request(server)
             .get('/api/v1/daily_charge_amount/location')
@@ -85,6 +126,21 @@ describe('request daily charge amount', () => {
             });
     });
 
+    it('should list the rural locations', (done) => {
+        chai.request(server)
+            .get('/api/v1/daily_charge_amount/rural_location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+
     it('should list education level short', (done) => {
         chai.request(server)
             .get('/api/v1/daily_charge_amount/education_level_short')
@@ -113,6 +169,20 @@ describe('request daily charge amount', () => {
             });
     });
 
+    it('should list the periods', (done) => {
+        chai.request(server)
+            .get('/api/v1/daily_charge_amount/period')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
     it('should list the dimensions of education_level_short', (done) => {
         chai.request(server)
             .get('/api/v1/daily_charge_amount?dims=education_level_short&filter=min_year:"2015",max_year:"2015",integral_time:"0",period:["3"]')
@@ -172,4 +242,45 @@ describe('request daily charge amount', () => {
                 done();
             });
     });
+
+    it('should list the filter of integral time', (done) => {
+        chai.request(server)
+            .get('/api/v1/daily_charge_amount?filter=integral_time:"1"')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('education_level_short_id');
+                res.body.result[0].should.have.property('average_class_duration');
+                res.body.result[0].should.have.property('median_class_duration');
+                res.body.result[0].should.have.property('std_class_duration');
+                res.body.result[0].should.have.property('fstqt_class_duration');
+                res.body.result[0].should.have.property('thdqt_class_duration');
+                res.body.result[0].should.have.property('education_level_short_name');
+                done();
+            });
+    });
+
+    it('should list daily charge amount for period 2', (done) => {
+        chai.request(server)
+            .get('/api/v1/daily_charge_amount?filter=integral_time:"0",period:["2"]')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('education_level_short_id');
+                res.body.result[0].should.have.property('average_class_duration');
+                res.body.result[0].should.have.property('median_class_duration');
+                res.body.result[0].should.have.property('std_class_duration');
+                res.body.result[0].should.have.property('fstqt_class_duration');
+                res.body.result[0].should.have.property('thdqt_class_duration');
+                res.body.result[0].should.have.property('education_level_short_name');
+                done();
+            });
+    });
+
 });
diff --git a/src/test/employees.js b/src/test/employees.js
new file mode 100644
index 00000000..2eff61c4
--- /dev/null
+++ b/src/test/employees.js
@@ -0,0 +1,215 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+process.env.NODE_ENV = 'test';
+
+const chai = require('chai');
+
+const dirtyChai = require('dirty-chai');
+
+chai.use(dirtyChai);
+
+const chaiXml = require('chai-xml');
+
+chai.use(chaiXml);
+
+const chaiHttp = require('chai-http');
+
+const assert = chai.assert;
+
+const expect = chai.expect;
+
+const should = chai.should(); // actually call the function
+
+const libs = `${process.cwd()}/libs`;
+
+const server = require(`${libs}/app`);
+
+chai.use(chaiHttp);
+describe('request employees', () => {
+    it('should list the employees default query', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('name');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('total_employees');
+                res.body.result[0].should.have.property('total_teachers');
+                done();
+            });
+    });
+
+    it('should list the year range', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees/year_range')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('start_year');
+                res.body.result[0].should.have.property('end_year');
+                done();
+            });
+    });
+
+    it('should list the years', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees/years')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                done();
+            });
+    });
+
+    it('should list the source', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees/source')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('source');
+                done();
+            });
+    });
+
+
+    it('should list the adm dependency', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees/adm_dependency')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the adm dependency detailed', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees/adm_dependency_detailed')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the location', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees/location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the rural location', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees/rural_location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list employees with valid filter', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees?filter=min_year:2017')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('name');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('total_employees');
+                res.body.result[0].should.have.property('total_teachers');
+                done();
+            });
+    });
+
+    it('should list employees with school dim', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees?dims=school&filter=state:11')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('name');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('total_employees');
+                res.body.result[0].should.have.property('total_teachers');
+                res.body.result[0].should.have.property('school_name');
+                res.body.result[0].should.have.property('school_id');
+                done();
+            });
+    });
+
+
+    it('should list employees with school filter', (done) => {
+        chai.request(server)
+            .get('/api/v1/employees?filter=school:41126882')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('name');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('total_employees');
+                res.body.result[0].should.have.property('total_teachers');
+                done();
+            });
+    });
+
+});
\ No newline at end of file
diff --git a/src/test/enrollment.js b/src/test/enrollment.js
index af5f50a1..066a23a2 100644
--- a/src/test/enrollment.js
+++ b/src/test/enrollment.js
@@ -495,4 +495,18 @@ describe('request enrollments', () => {
                 done();
             });
     });
+
+    it('should list the age range', (done) => {
+        chai.request(server)
+            .get('/api/v1/enrollment/age_range_all')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
 });
diff --git a/src/test/glossEnrollmentRatio.js b/src/test/glossEnrollmentRatio.js
index 562244cb..39859b70 100644
--- a/src/test/glossEnrollmentRatio.js
+++ b/src/test/glossEnrollmentRatio.js
@@ -44,6 +44,19 @@ const server = require(`${libs}/app`);
 
 chai.use(chaiHttp);
 describe('request gloss enrollment ratio', () => {
+    it('should list the source', (done) => {
+        chai.request(server)
+            .get('/api/v1/gloss_enrollment_ratio/source')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('source');
+                done();
+            });
+    });
+
     it('should list the year range', (done) => {
         chai.request(server)
             .get('/api/v1/gloss_enrollment_ratio/year_range')
diff --git a/src/test/liquidEnrollmentRatio.js b/src/test/liquidEnrollmentRatio.js
index bbea4bb6..b61a8d8f 100644
--- a/src/test/liquidEnrollmentRatio.js
+++ b/src/test/liquidEnrollmentRatio.js
@@ -44,6 +44,19 @@ const server = require(`${libs}/app`);
 
 chai.use(chaiHttp);
 describe('request liquid enrollment ratio', () => {
+    it('should list the source', (done) => {
+        chai.request(server)
+            .get('/api/v1/liquid_enrollment_ratio/source')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('source');
+                done();
+            });
+    });
+
     it('should list the year range', (done) => {
         chai.request(server)
             .get('/api/v1/liquid_enrollment_ratio/year_range')
@@ -179,4 +192,23 @@ describe('request liquid enrollment ratio', () => {
             });
     });
 
+    it('should list liquid ratio with education level basic filter', (done) => {
+        chai.request(server)
+            .get('/api/v1/liquid_enrollment_ratio?dims=education_level_basic&filter=education_level_basic:["1","2","4","5","6"]')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('age_range');
+                res.body.result[0].should.have.property('education_level_basic_id');
+                res.body.result[0].should.have.property('education_level_basic_name');
+                res.body.result[0].should.have.property('partial');
+                res.body.result[0].should.have.property('denominator');
+                done();
+            });
+    });
+
 });
diff --git a/src/test/outOfSchool.js b/src/test/outOfSchool.js
new file mode 100644
index 00000000..bd265f39
--- /dev/null
+++ b/src/test/outOfSchool.js
@@ -0,0 +1,232 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+process.env.NODE_ENV = 'test';
+
+const chai = require('chai');
+
+const dirtyChai = require('dirty-chai');
+
+chai.use(dirtyChai);
+
+const chaiXml = require('chai-xml');
+
+chai.use(chaiXml);
+
+const chaiHttp = require('chai-http');
+
+const assert = chai.assert;
+
+const expect = chai.expect;
+
+const should = chai.should(); // actually call the function
+
+const libs = `${process.cwd()}/libs`;
+
+const server = require(`${libs}/app`);
+
+chai.use(chaiHttp);
+
+describe('request out of school', () => {
+    it('should list the year range', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/year_range')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('start_year');
+                res.body.result[0].should.have.property('end_year');
+                done();
+            });
+    });
+
+    it('should list the years', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/years')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                done();
+            });
+    });
+
+    it('should list the full age range', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/full_age_range')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the ethnic_group', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/ethnic_group')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the location', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the gender', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/gender')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the fifth household income', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/fifth_household_income')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the extremes household income', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/extremes_household_income')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list default query out of school', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('year');
+                done();
+            });
+    });
+
+    it('should list out of school with valid filters', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school?filter=max_year:2010')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                res.body.result[0].should.have.property('total');
+                done();
+            });
+    });
+
+    it('should list the simcaq default query for out of school', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/simcaq')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('ano_censo');
+                done();
+            });
+    });
+
+    it('should list simcaq out of school with valid filters', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/simcaq?filter=state:41')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('ano_censo');
+                res.body.result[0].should.have.property('total');
+                done();
+            });
+    });
+
+    it('should list simcaq out of school with valid dimensions', (done) => {
+        chai.request(server)
+            .get('/api/v1/out_of_school/simcaq?dims=state,pfe')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('pfe_id');
+                res.body.result[0].should.have.property('pfe_name');
+                res.body.result[0].should.have.property('ano_censo');
+                res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('state_id');
+                done();
+            });
+    });
+
+});
\ No newline at end of file
diff --git a/src/test/schoolCount.js b/src/test/schoolCount.js
index 839415ab..ebdcd8ef 100644
--- a/src/test/schoolCount.js
+++ b/src/test/schoolCount.js
@@ -199,22 +199,22 @@ describe('request schools count', () => {
             });
     });
 
-    it('should list school with valid dimensions and filters', (done) => {
-        chai.request(server)
-            .get('/api/v1/school/count?dims=location,adm_dependency,government_agreement')
-            .end((err, res) => {
-                res.should.have.status(200);
-                res.should.be.json;
-                res.body.should.have.property('result');
-                res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('location_name');
-                res.body.result[0].should.have.property('adm_dependency_name');
-                res.body.result[0].should.have.property('government_agreement_name');
-                res.body.result[0].should.have.property('total');
-                res.body.result[0].should.have.property('year');
-                done();
-            });
-    });
+    // it('should list school with valid dimensions and filters', (done) => {
+    //     chai.request(server)
+    //         .get('/api/v1/school/count?dims=location,adm_dependency,government_agreement')
+    //         .end((err, res) => {
+    //             res.should.have.status(200);
+    //             res.should.be.json;
+    //             res.body.should.have.property('result');
+    //             res.body.result.should.be.a('array');
+    //             res.body.result[0].should.have.property('location_name');
+    //             res.body.result[0].should.have.property('adm_dependency_name');
+    //             res.body.result[0].should.have.property('government_agreement_name');
+    //             res.body.result[0].should.have.property('total');
+    //             res.body.result[0].should.have.property('year');
+    //             done();
+    //         });
+    // });
 
     it('should list school with valid dimensions and filters', (done) => {
         chai.request(server)
@@ -309,18 +309,18 @@ describe('request schools count', () => {
             });
     });
 
-    it('should list school with dimension rural_location', (done) => {
-        chai.request(server)
-            .get('/api/v1/school/count?dims=location')
-            .end((err, res) => {
-                res.should.have.status(200);
-                res.should.be.json;
-                res.body.should.have.property('result');
-                res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('location_name');
-                done();
-            });
-    });
+    // it('should list school with dimension rural_location', (done) => {
+    //     chai.request(server)
+    //         .get('/api/v1/school/count?dims=location')
+    //         .end((err, res) => {
+    //             res.should.have.status(200);
+    //             res.should.be.json;
+    //             res.body.should.have.property('result');
+    //             res.body.result.should.be.a('array');
+    //             res.body.result[0].should.have.property('location_name');
+    //             done();
+    //         });
+    // });
 
     it('should list school with dimension agreement', (done) => {
         chai.request(server)
diff --git a/src/test/transport.js b/src/test/transport.js
index 39374999..217d688f 100644
--- a/src/test/transport.js
+++ b/src/test/transport.js
@@ -57,7 +57,7 @@ describe('request transport', () => {
             });
     });
 
-    it('should list the year range', (done) => {
+    it('should list the years', (done) => {
         chai.request(server)
             .get('/api/v1/transport/years')
             .end((err, res) => {
@@ -70,7 +70,7 @@ describe('request transport', () => {
             });
     });
 
-    it('should list the years', (done) => {
+    it('should list the year range', (done) => {
         chai.request(server)
             .get('/api/v1/transport/year_range')
             .end((err, res) => {
@@ -181,4 +181,18 @@ describe('request transport', () => {
             });
     });
 
+    it('should list the service type', (done) => {
+        chai.request(server)
+            .get('/api/v1/transport/service_type')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
 });
-- 
GitLab


From 9f5f948fb3a4aa8d20ba3543df01b833fac423ac Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Wed, 13 Feb 2019 09:28:49 -0200
Subject: [PATCH 023/142] Fixed school infrastructure subroutes and added tests

---
 src/libs/routes/schoolInfrastructure.js |  25 ++--
 src/test/schoolInfrastructure.js        | 183 ++++++++++++++++++++++++
 2 files changed, 199 insertions(+), 9 deletions(-)
 create mode 100644 src/test/schoolInfrastructure.js

diff --git a/src/libs/routes/schoolInfrastructure.js b/src/libs/routes/schoolInfrastructure.js
index f51102fe..835f0f6e 100644
--- a/src/libs/routes/schoolInfrastructure.js
+++ b/src/libs/routes/schoolInfrastructure.js
@@ -87,19 +87,26 @@ infrastructureApp.get('/rural_location', (req, res, next) => {
 }, response('rural_location'));
 
 infrastructureApp.get('/adm_dependency', (req, res, next) => {
-    req.sql.from('dependencia_adm')
-    .field('id')
-    .field('nome', 'name')
-    .where('id <= 4');
+    req.result = [];
+    for(let i = 1; i <= 4; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.admDependency(i)
+        });
+    };
     next();
-}, query, response('adm_dependency'));
+}, response('adm_dependency'));
 
 infrastructureApp.get('/adm_dependency_detailed', (req, res, next) => {
-    req.sql.from('dependencia_adm_priv')
-    .field('id', 'id')
-    .field('nome', 'name');
+    req.result = [];
+    for(let i = 1; i <= 6; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.admDependencyPriv(i)
+        });
+    };
     next();
-}, query, response('adm_dependency_detailed'));
+}, response('adm_dependency_detailed'));
 
 rqf.addField({
     name: 'filter',
diff --git a/src/test/schoolInfrastructure.js b/src/test/schoolInfrastructure.js
new file mode 100644
index 00000000..f167fb1f
--- /dev/null
+++ b/src/test/schoolInfrastructure.js
@@ -0,0 +1,183 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+process.env.NODE_ENV = 'test';
+
+const chai = require('chai');
+
+const dirtyChai = require('dirty-chai');
+
+chai.use(dirtyChai);
+
+const chaiXml = require('chai-xml');
+
+chai.use(chaiXml);
+
+const chaiHttp = require('chai-http');
+
+const assert = chai.assert;
+
+const expect = chai.expect;
+
+const should = chai.should(); // actually call the function
+
+const libs = `${process.cwd()}/libs`;
+
+const server = require(`${libs}/app`);
+
+chai.use(chaiHttp);
+describe('request school infrastructure', () => {
+    it('should list the default school insfrastructure query', (done) => {
+        chai.request(server)
+            .get('/api/v1/school_infrastructure')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('schools_in_school_buildings');
+                res.body.result[0].should.have.property('urban_schools_in_school_buildings');
+                res.body.result[0].should.have.property('country_schools_in_school_buildings');
+                res.body.result[0].should.have.property('schools_not_in_school_buildings');
+                res.body.result[0].should.have.property('libraries');
+                res.body.result[0].should.have.property('libraries_reading_room');
+                res.body.result[0].should.have.property('computer_lab');
+                res.body.result[0].should.have.property('science_lab');
+                res.body.result[0].should.have.property('kids_park');
+                res.body.result[0].should.have.property('nursery');
+                res.body.result[0].should.have.property('sports_court');
+                res.body.result[0].should.have.property('sports_court_coverage');
+                res.body.result[0].should.have.property('courtyard');
+                res.body.result[0].should.have.property('courtyard_coverage');
+                res.body.result[0].should.have.property('director_room');
+                res.body.result[0].should.have.property('secretary');
+                res.body.result[0].should.have.property('teacher_room');
+                res.body.result[0].should.have.property('kitchen');
+                res.body.result[0].should.have.property('storeroom');
+                res.body.result[0].should.have.property('warehouse');
+                res.body.result[0].should.have.property('internet');
+                res.body.result[0].should.have.property('broadband_internet');
+                res.body.result[0].should.have.property('inside_bathroom');
+                res.body.result[0].should.have.property('inside_kids_bathroom');
+                res.body.result[0].should.have.property('eletric_energy');
+                res.body.result[0].should.have.property('water_supply');
+                res.body.result[0].should.have.property('filtered_water');
+                res.body.result[0].should.have.property('sewage_treatment');
+                res.body.result[0].should.have.property('adapted_building');
+                res.body.result[0].should.have.property('special_bathroom');
+                done();
+            });
+    });
+    it('should list the year range', (done) => {
+        chai.request(server)
+            .get('/api/v1/school_infrastructure/year_range')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('start_year');
+                res.body.result[0].should.have.property('end_year');
+                done();
+            });
+    });
+    
+    it('should list the years', (done) => {
+        chai.request(server)
+            .get('/api/v1/school_infrastructure/years')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('year');
+                done();
+            });
+    });
+
+    it('should list the source', (done) => {
+        chai.request(server)
+            .get('/api/v1/school_infrastructure/source')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('source');
+                done();
+            });
+    });
+
+    it('should list the location', (done) => {
+        chai.request(server)
+            .get('/api/v1/school_infrastructure/location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the rural location', (done) => {
+        chai.request(server)
+            .get('/api/v1/school_infrastructure/rural_location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the adm dependency', (done) => {
+        chai.request(server)
+            .get('/api/v1/school_infrastructure/adm_dependency')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+
+    it('should list the adm dependency detailed', (done) => {
+        chai.request(server)
+            .get('/api/v1/school_infrastructure/adm_dependency_detailed')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('id');
+                res.body.result[0].should.have.property('name');
+                done();
+            });
+    });
+});
\ No newline at end of file
-- 
GitLab


From 562736b48680fec900943056356d50bae468cd4f Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 14 Feb 2019 09:45:14 -0200
Subject: [PATCH 024/142] Fix upper adm dependency

---
 src/libs/routes/university.js | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index 37dc5d22..b8e34848 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -95,13 +95,13 @@ rqf.addField({
     where: {
         relation: '=',
         type: 'integer',
-        field: 'municipio_id',
-        table: 'evader_ag'
+        field: 'cod_municipio_ies',
+        table: 'ies_ens_superior'
     },
     join: {
         primary: 'id',
-        foreign: 'municipio_id',
-        foreignTable: 'evader_ag'
+        foreign: 'cod_municipio_ies',
+        foreignTable: 'ies_ens_superior'
     }
 }).addValue({
     name: 'min_year',
@@ -133,19 +133,19 @@ rqf.addField({
     where: {
         relation: '=',
         type: 'integer',
-        field: 'estado_id',
+        field: 'cod_uf_ies',
         table: '@'
     },
     join: {
         primary: 'id',
-        foreign: 'estado_id',
+        foreign: 'cod_uf_ies',
         foreignTable: '@'
     }
 }).addValue({
     name: 'upper_adm_dependency',
     table: 'ies_ens_superior',
     tableField: 'cod_categoria_administrativa',
-    resultField: 'upper_adm_dependency_name',
+    resultField: 'upper_adm_dependency_id',
     where: {
         relation: '=',
         type: 'integer',
@@ -153,10 +153,10 @@ rqf.addField({
         field: 'cod_categoria_administrativa'
     }
 }).addValue({
-    name: 'organization_academic',
+    name: 'academic_organization',
     table: 'ies_ens_superior',
     tableField: 'cod_organizacao_academica',
-    resultField: 'organization_academic_name',
+    resultField: 'academic_organization_id',
     where: {
         relation: '=',
         type: 'integer',
-- 
GitLab


From 3f9465baffcf3c8309d0b9888b74453653606f82 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 14 Feb 2019 09:49:09 -0200
Subject: [PATCH 025/142] Fix location_id in school route

---
 src/libs/routes/school.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/school.js b/src/libs/routes/school.js
index 120b7254..13abdfa8 100644
--- a/src/libs/routes/school.js
+++ b/src/libs/routes/school.js
@@ -384,12 +384,12 @@ rqfCount.addField({
 }).addValue({
     name: 'location',
     table: 'escola',
-    tableField: 'cod_localizacao',
+    tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_localizacao'
+        field: 'localizacao_id'
     }
 }).addValue({
     name: 'rural_location',
-- 
GitLab


From d04112ca1c9913f6e23dcbee7caed2b654ba1107 Mon Sep 17 00:00:00 2001
From: jvfpw18 <jvfpw18@inf.ufpr.br>
Date: Thu, 14 Feb 2019 10:09:13 -0200
Subject: [PATCH 026/142] update schoolCount test

---
 src/test/schoolCount.js | 56 ++++++++++++++++++++---------------------
 1 file changed, 28 insertions(+), 28 deletions(-)

diff --git a/src/test/schoolCount.js b/src/test/schoolCount.js
index ebdcd8ef..839415ab 100644
--- a/src/test/schoolCount.js
+++ b/src/test/schoolCount.js
@@ -199,22 +199,22 @@ describe('request schools count', () => {
             });
     });
 
-    // it('should list school with valid dimensions and filters', (done) => {
-    //     chai.request(server)
-    //         .get('/api/v1/school/count?dims=location,adm_dependency,government_agreement')
-    //         .end((err, res) => {
-    //             res.should.have.status(200);
-    //             res.should.be.json;
-    //             res.body.should.have.property('result');
-    //             res.body.result.should.be.a('array');
-    //             res.body.result[0].should.have.property('location_name');
-    //             res.body.result[0].should.have.property('adm_dependency_name');
-    //             res.body.result[0].should.have.property('government_agreement_name');
-    //             res.body.result[0].should.have.property('total');
-    //             res.body.result[0].should.have.property('year');
-    //             done();
-    //         });
-    // });
+    it('should list school with valid dimensions and filters', (done) => {
+        chai.request(server)
+            .get('/api/v1/school/count?dims=location,adm_dependency,government_agreement')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('location_name');
+                res.body.result[0].should.have.property('adm_dependency_name');
+                res.body.result[0].should.have.property('government_agreement_name');
+                res.body.result[0].should.have.property('total');
+                res.body.result[0].should.have.property('year');
+                done();
+            });
+    });
 
     it('should list school with valid dimensions and filters', (done) => {
         chai.request(server)
@@ -309,18 +309,18 @@ describe('request schools count', () => {
             });
     });
 
-    // it('should list school with dimension rural_location', (done) => {
-    //     chai.request(server)
-    //         .get('/api/v1/school/count?dims=location')
-    //         .end((err, res) => {
-    //             res.should.have.status(200);
-    //             res.should.be.json;
-    //             res.body.should.have.property('result');
-    //             res.body.result.should.be.a('array');
-    //             res.body.result[0].should.have.property('location_name');
-    //             done();
-    //         });
-    // });
+    it('should list school with dimension rural_location', (done) => {
+        chai.request(server)
+            .get('/api/v1/school/count?dims=location')
+            .end((err, res) => {
+                res.should.have.status(200);
+                res.should.be.json;
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                res.body.result[0].should.have.property('location_name');
+                done();
+            });
+    });
 
     it('should list school with dimension agreement', (done) => {
         chai.request(server)
-- 
GitLab


From b3e41ed04780b321e491583b5404783ed5683d7a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 14 Feb 2019 11:08:40 -0200
Subject: [PATCH 027/142] Fixed enrollment test

---
 src/test/enrollment.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/test/enrollment.js b/src/test/enrollment.js
index 066a23a2..9ec5cba3 100644
--- a/src/test/enrollment.js
+++ b/src/test/enrollment.js
@@ -465,7 +465,7 @@ describe('request enrollments', () => {
                 res.should.be.json;
                 res.body.should.have.property('result');
                 res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('cor_raca_id');
+                res.body.result[0].should.have.property('ethnic_group_id');
                 done();
             });
     });
-- 
GitLab


From aa598040be531c971bee35f8404dbec21fbd5653 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 14 Feb 2019 11:37:21 -0200
Subject: [PATCH 028/142] Fix enrollment test

---
 src/test/enrollment.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/test/enrollment.js b/src/test/enrollment.js
index 066a23a2..9ec5cba3 100644
--- a/src/test/enrollment.js
+++ b/src/test/enrollment.js
@@ -465,7 +465,7 @@ describe('request enrollments', () => {
                 res.should.be.json;
                 res.body.should.have.property('result');
                 res.body.result.should.be.a('array');
-                res.body.result[0].should.have.property('cor_raca_id');
+                res.body.result[0].should.have.property('ethnic_group_id');
                 done();
             });
     });
-- 
GitLab


From 1bcdf926536fc9ca681f7af0697726e80d8d9c93 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 14 Feb 2019 19:02:32 -0200
Subject: [PATCH 029/142] Fix Join's in financial route

---
 src/libs/routes/financial.js | 44 ++++++++++++++++++++++++------------
 1 file changed, 30 insertions(+), 14 deletions(-)

diff --git a/src/libs/routes/financial.js b/src/libs/routes/financial.js
index c4de6092..bfe27205 100644
--- a/src/libs/routes/financial.js
+++ b/src/libs/routes/financial.js
@@ -150,20 +150,36 @@ rqf.addField({
 });
 
 financialApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
-    req.sql.from('indicadores_financeiros')
-    .field('indicadores_financeiros.estado_id', 'state_id')
-    .field('indicadores_financeiros.ano_censo', 'year')
-    .field('estado.sigla', 'state_abbreviation')
-    .field('indicadores_financeiros.valor', 'valor')
-    .field('indicadores_financeiros.esfera_adm', 'sphere_adm_id')
-    .field('indicadores_financeiros.dados_financeiros', 'financial_data_id')
-    .join('estado', null, 'indicadores_financeiros.estado_id=estado.id')
-    .group('indicadores_financeiros.ano_censo')
-    .group('indicadores_financeiros.estado_id')
-    .group('estado.sigla')
-    .group('indicadores_financeiros.valor')
-    .group('indicadores_financeiros.dados_financeiros')
-    .group('indicadores_financeiros.esfera_adm')
+		if ("state" in req.filter) {
+	    req.sql.from('indicadores_financeiros')
+	    .field('indicadores_financeiros.estado_id', 'state_id')
+	    .field('indicadores_financeiros.ano_censo', 'year')
+	    .field('estado.sigla', 'state_abbreviation')
+	    .field('indicadores_financeiros.valor', 'valor')
+	    .field('indicadores_financeiros.esfera_adm', 'sphere_adm_id')
+	    .field('indicadores_financeiros.dados_financeiros', 'financial_data_id')
+	    .group('indicadores_financeiros.ano_censo')
+	    .group('indicadores_financeiros.estado_id')
+	    .group('estado.sigla')
+	    .group('indicadores_financeiros.valor')
+	    .group('indicadores_financeiros.dados_financeiros')
+	    .group('indicadores_financeiros.esfera_adm')
+		} else {
+	    req.sql.from('indicadores_financeiros')
+	    .field('indicadores_financeiros.estado_id', 'state_id')
+	    .field('indicadores_financeiros.ano_censo', 'year')
+	    .field('estado.sigla', 'state_abbreviation')
+	    .field('indicadores_financeiros.valor', 'valor')
+	    .field('indicadores_financeiros.esfera_adm', 'sphere_adm_id')
+	    .field('indicadores_financeiros.dados_financeiros', 'financial_data_id')
+	    .join('estado', null, 'indicadores_financeiros.estado_id=estado.id')
+	    .group('indicadores_financeiros.ano_censo')
+	    .group('indicadores_financeiros.estado_id')
+	    .group('estado.sigla')
+	    .group('indicadores_financeiros.valor')
+	    .group('indicadores_financeiros.dados_financeiros')
+	    .group('indicadores_financeiros.esfera_adm')
+		}
     next();
 }, query, addMissing(rqf), id2str.transform(), response('financial'));
 
-- 
GitLab


From 3dde8c1456b36e5c0bd2e2221ebc32c5991a9186 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Fri, 15 Feb 2019 09:18:34 -0200
Subject: [PATCH 030/142] Created courseCount route

---
 src/libs/routes/api.js         |   5 +
 src/libs/routes/courseCount.js | 227 +++++++++++++++++++++++++++++++++
 2 files changed, 232 insertions(+)
 create mode 100644 src/libs/routes/courseCount.js

diff --git a/src/libs/routes/api.js b/src/libs/routes/api.js
index 5141ec78..05d6f3d2 100644
--- a/src/libs/routes/api.js
+++ b/src/libs/routes/api.js
@@ -106,6 +106,8 @@ const employees = require(`${libs}/routes/employees`);
 
 const financial = require(`${libs}/routes/financial`);
 
+const courseCount = require(`${libs}/routes/courseCount`);
+
 api.get('/', (req, res) => {
     res.json({ msg: 'SimCAQ API is running' });
 });
@@ -152,5 +154,8 @@ api.use('/enrollment_projection', enrollmentProjection);
 api.use('/employees', employees);
 api.use('/financial', financial);
 
+api.use('/course_count', courseCount);
+
+
 
 module.exports = api;
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
new file mode 100644
index 00000000..ef4da72b
--- /dev/null
+++ b/src/libs/routes/courseCount.js
@@ -0,0 +1,227 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+const express = require('express');
+
+const courseCountApp = express.Router();
+
+const libs = `${process.cwd()}/libs`;
+
+const log = require(`${libs}/log`)(module);
+
+const squel = require('squel');
+
+const query = require(`${libs}/middlewares/query`).query;
+
+const response = require(`${libs}/middlewares/response`);
+
+const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);
+
+const id2str = require(`${libs}/middlewares/id2str`);
+
+const config = require(`${libs}/config`); 
+
+const 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 rqf = new ReqQueryFields();
+
+courseCountApp.use(cache('15 day'));
+
+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: 'nome',
+        foreign: 'nome_regiao_curso',
+        foreignTable: 'curso_ens_superior'
+    }
+}).addValue({
+    name: 'state',
+    table: 'estado',
+    tableField: 'nome',
+    resultField: 'state_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'id'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'cod_uf_curso',
+        foreignTable: 'curso_ens_superior'
+    }
+}).addValue({       
+    name: 'city',
+    table: 'curso_ens_superior',
+    tableField: ['municipio_curso', 'cod_municipio_curso'],
+    resultField: ['city_name', 'city_id'],
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_municipio_curso'
+    }
+}).addValue({
+    name:'upper_adm_dependency',
+    table: 'curso_ens_superior',
+    tableField: 'cod_categoria_administrativa',
+    resultField: 'adm_dependency_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_categoria_administrativa'
+    }
+}).addValue({
+    name:'academic_organization',
+    table: 'curso_ens_superior',
+    tableField: 'cod_organizacao_academica',
+    resultField: 'academic_type_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_organizacao_academica'
+    }
+}).addValue({
+    name:'capital',
+    table: 'curso_ens_superior',
+    tableField: 'capital_curso',
+    resultField: 'in_capital',
+    where: {
+        relation: '=',
+        type: 'boolean',
+        field: 'capital_curso'
+    }
+}).addValue({       //add missing
+    name:'course',
+    table: 'curso_ens_superior',
+    tableField: ['nome_curso', 'cod_curso'],
+    resultField: ['course_name', 'course_id'],
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_curso'
+    }
+}).addValue({       //add missing
+    name:'ocde_specific',
+    table: 'curso_ens_superior',
+    tableField: 'cod_ocde_area_especifica',
+    resultField: 'ocde_area_specific_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ocde_area_especifica'
+    }
+}).addValue({       //add missing
+    name:'ocde',
+    table: 'curso_ens_superior',
+    tableField: 'cod_ocde_area_geral',
+    resultField: 'ocde_area_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ocde_area_geral'
+    }
+}).addValue({       //add missing
+    name:'ocde_detailed',
+    table: 'curso_ens_superior',
+    tableField: 'cod_ocde_area_detalhada',
+    resultField: 'ocde_area_detailed_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ocde_area_detalhada'
+    }
+}).addValue({       //add missing
+    name:'academic_level',
+    table: 'curso_ens_superior',
+    tableField: 'cod_grau_academico',
+    resultField: 'academic_level_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_grau_academico'
+    }
+}).addValue({       //add missing
+    name:'academic_mod',
+    table: 'curso_ens_superior',
+    tableField: 'cod_modalidade_ensino',
+    resultField: 'academic_mod_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_modalidade_ensino'
+    }
+}).addValue({
+    name:'free',
+    table: 'curso_ens_superior',
+    tableField: 'gratuito',
+    resultField: 'is_free',
+    where: {
+        relation: '=',
+        type: 'boolean',
+        field: 'gratuito'
+    }
+}).addValue({
+    name:'night_time',
+    table: 'curso_ens_superior',
+    tableField: 'noturno_curso',
+    resultField: 'night_time_id',
+    where: {
+        relation: '=',
+        type: 'boolean',
+        field: 'noturno_curso'
+    }
+});
+
+courseCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
+    req.sql.field('COUNT(cod_curso)', 'total')
+    .field("'Brasil'", 'name')
+    .field('curso_ens_superior.ano_censo', 'year')
+    .from('curso_ens_superior')
+    .group('curso_ens_superior.ano_censo')
+    .order('curso_ens_superior.ano_censo')
+    .where('curso_ens_superior.cod_situacao_curso = 1 OR curso_ens_superior.cod_situacao_curso = 3')
+    .where('curso_ens_superior.tipo_atributo_ingresso <> 1')
+    .where('curso_ens_superior.cod_nivel_academico = 1');
+
+    next();
+}, query, addMissing(rqf), id2str.transform(), response('course_count'));
+
+module.exports = courseCountApp;
\ No newline at end of file
-- 
GitLab


From 17b7fb1e19f5e46c1c047a8c51a9665bbe533507 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Tue, 19 Feb 2019 09:58:07 -0300
Subject: [PATCH 031/142] Created route course_count

---
 src/libs/convert/academicLevel.js |  32 ++++++
 src/libs/convert/academicMod.js   |  30 +++++
 src/libs/convert/ocdeDetailed.js  | 183 ++++++++++++++++++++++++++++++
 src/libs/convert/ocdeGeral.js     |  44 +++++++
 src/libs/convert/ocdeSpecific.js  |  70 ++++++++++++
 src/libs/routes/courseCount.js    | 101 +++++++++++++++--
 6 files changed, 448 insertions(+), 12 deletions(-)
 create mode 100644 src/libs/convert/academicLevel.js
 create mode 100644 src/libs/convert/academicMod.js
 create mode 100644 src/libs/convert/ocdeDetailed.js
 create mode 100644 src/libs/convert/ocdeGeral.js
 create mode 100644 src/libs/convert/ocdeSpecific.js

diff --git a/src/libs/convert/academicLevel.js b/src/libs/convert/academicLevel.js
new file mode 100644
index 00000000..3f76bc11
--- /dev/null
+++ b/src/libs/convert/academicLevel.js
@@ -0,0 +1,32 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function academicLevel(id) {
+    switch (id) {
+        case 1:
+        return 'Bacharelado';
+        case 2:
+        return 'Licenciatura';
+        case 3:
+        return 'Tecnológico';
+        default:
+        return 'Não classificada';
+    }
+};
diff --git a/src/libs/convert/academicMod.js b/src/libs/convert/academicMod.js
new file mode 100644
index 00000000..89c85e5f
--- /dev/null
+++ b/src/libs/convert/academicMod.js
@@ -0,0 +1,30 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function academicMod(id) {
+    switch (id) {
+        case 1:
+        return 'Presencial';
+        case 2:
+        return 'A Distância';
+        default:
+        return 'Não classificada';
+    }
+};
diff --git a/src/libs/convert/ocdeDetailed.js b/src/libs/convert/ocdeDetailed.js
new file mode 100644
index 00000000..e83dc4d9
--- /dev/null
+++ b/src/libs/convert/ocdeDetailed.js
@@ -0,0 +1,183 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+module.exports = function ocdeDetailed(id) {
+	switch (id) {
+		case 142:
+		return 'Ciências da educação';
+		case 144:
+		return 'Formação de professor da educação básica';
+		case 145:
+		return 'Formação de professor de matérias específicas';
+		case 146:
+		return 'Formação de professor de disciplinas profissionais';
+		case 210:
+		return 'Artes (cursos gerais)';
+		case 211:
+		return 'Belas artes';
+		case 212:
+		return 'Música e artes cênicas';
+		case 213:
+		return 'Técnicas audiovisuais e produção de mídia';
+		case 214:
+		return 'Design e estilismo';
+		case 215:
+		return 'Artesanato';
+		case 220:
+		return 'Humanidades e letras (cursos gerais)';
+		case 221:
+		return 'Religião e teologia';
+		case 222:
+		return 'Línguas e culturas estrangeiras';
+		case 223:
+		return 'Língua materna (vernácula)';
+		case 225:
+		return 'História e arqueologia';
+		case 226:
+		return 'Filosofia e ética';
+		case 310:
+		return 'Ciências sociais e comportamentais (cursos gerais)';
+		case 311:
+		return 'Psicologia';
+		case 312:
+		return 'Sociologia e estudos culturais';
+		case 313:
+		return 'Ciência política e educação cívica';
+		case 314:
+		return 'Economia';
+		case 321:
+		return 'Jornalismo e reportagem';
+		case 322:
+		return 'Biblioteconomia, informação, arquivos';
+		case 340:
+		return 'Comércio e administração (cursos gerais)';
+		case 341:
+		return 'Vendas em atacado e varejo';
+		case 342:
+		return 'Marketing e publicidade';
+		case 343:
+		return 'Finanças, bancos, seguros';
+		case 344:
+		return 'Contabilidade e tributação';
+		case 345:
+		return 'Gerenciamento e administração';
+		case 346:
+		return 'Secretariado e trabalhos de escritório';
+		case 380:
+		return 'Direito';
+		case 420:
+		return 'Ciências (cursos gerais)';
+		case 421:
+		return 'Biologia e bioquímica';
+		case 422:
+		return 'Ciências ambientais';
+		case 440:
+		return 'Ciências físicas (cursos gerais)';
+		case 441:
+		return 'Física';
+		case 442:
+		return 'Química';
+		case 443:
+		return 'Ciências da terra';
+		case 461:
+		return 'Matemática';
+		case 462:
+		return 'Estatística';
+		case 481:
+		return 'Ciência da computação';
+		case 482:
+		return 'Uso do computador';
+		case 483:
+		return 'Processamento da informação';
+		case 520:
+		return 'Engenharia e profissões de engenharia (cursos gerais)';
+		case 521:
+		return 'Engenharia mecânica e metalurgia (trabalhos com metais)';
+		case 522:
+		return 'Eletricidade e energia';
+		case 523:
+		return 'Eletrônica e automação';
+		case 524:
+		return 'Química e engenharia de processos';
+		case 525:
+		return 'Veículos a motor, construção naval e aeronáutica';
+		case 540:
+		return 'Fabricação e processamento (cursos gerais)';
+		case 541:
+		return 'Processamento de alimentos';
+		case 542:
+		return 'Têxteis, roupas, calçados, couros';
+		case 543:
+		return 'Materiais (madeira, papel, plástico, vidro)';
+		case 544:
+		return 'Mineração e extração';
+		case 581:
+		return 'Arquitetura e urbanismo';
+		case 582:
+		return 'Engenharia civil e de construção';
+		case 621:
+		return 'Produção agrícola e pecuária';
+		case 622:
+		return 'Horticultura';
+		case 623:
+		return 'Engenharia florestal - silvicultura';
+		case 624:
+		return 'Recursos pesqueiros';
+		case 641:
+		return 'Veterinária';
+		case 720:
+		return 'Saúde (cursos gerais)';
+		case 721:
+		return 'Medicina';
+		case 723:
+		return 'Enfermagem e atenção primária (assistência básica)';
+		case 724:
+		return 'Odontologia';
+		case 725:
+		return 'Tecnologias de diagnóstico e tratamento médico';
+		case 726:
+		return 'Terapia e reabilitação';
+		case 727:
+		return 'Farmácia';
+		case 762:
+		return 'Serviço social e orientação';
+		case 811:
+		return 'Hotelaria, restaurantes  e serviços de alimentação';
+		case 812:
+		return 'Viagens, turismo e lazer';
+		case 813:
+		return 'Esportes';
+		case 814:
+		return 'Ciências domésticas';
+		case 815:
+		return 'Serviços de beleza';
+		case 840:
+		return 'Transportes e serviços (cursos gerais)';
+		case 850:
+		return 'Proteção ambiental (cursos gerais)';
+		case 861:
+		return 'Proteção de pessoas e de propriedades';
+		case 862:
+		return 'Saúde e segurança do trabalho';
+		case 863:
+		return 'Setor militar e de defesa';
+		default:
+		return 'Não classificada';
+	}
+};
\ No newline at end of file
diff --git a/src/libs/convert/ocdeGeral.js b/src/libs/convert/ocdeGeral.js
new file mode 100644
index 00000000..88cc0646
--- /dev/null
+++ b/src/libs/convert/ocdeGeral.js
@@ -0,0 +1,44 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function ocdeGeral(id) {
+    switch (id) {
+        case 0:
+        return 'Área básica';
+        case 1:
+        return 'Educação';
+        case 2:
+        return 'Humanidades e artes';
+        case 3:
+        return 'Ciências sociais, negócios e direitor';
+        case 4:
+        return 'Ciências, matemática e computação';
+        case 5:
+        return 'Engenharia, produção e construção';
+        case 6:
+        return 'Agricultura e veterinária';
+        case 7:
+        return 'Saúde e bem estar social';
+        case 8:
+        return 'Serviços';
+        default:
+        return 'Não classificada';
+    }
+};
diff --git a/src/libs/convert/ocdeSpecific.js b/src/libs/convert/ocdeSpecific.js
new file mode 100644
index 00000000..7b360d86
--- /dev/null
+++ b/src/libs/convert/ocdeSpecific.js
@@ -0,0 +1,70 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function ocdeSpecific(id) {
+    switch (id) {
+        case 1:
+        return 'Área básica de cursos';
+        case 14:
+        return 'Formação de professor e ciências da educação';
+        case 21:
+        return 'Artes';
+        case 22:
+        return 'Humanidades e letras';
+        case 31:
+        return 'Ciências sociais e comportamentais';
+        case 32:
+        return 'Jornalismo e informação';
+        case 34:
+        return 'Comércio e administração';
+        case 38:
+        return 'Direito';
+        case 42:
+        return 'Ciências';
+        case 44:
+        return 'Ciências físicas';
+        case 48:
+        return 'Computação';
+        case 52:
+        return 'Engenharia e profissões correlatas';
+        case 54:
+        return 'Produção e processamento';
+        case 58:
+        return 'Arquitetura e construção';
+        case 62:
+        return 'Agricultura, florestas e recursos pasqueiros';
+        case 64:
+        return 'Veterinária';
+        case 72:
+        return 'Saúde';
+        case 76:
+        return 'Serviço social';
+        case 81:
+        return 'Serviços pessoais';
+        case 84:
+        return 'Serviços de transportes (cursos gerais)';
+        case 85:
+        return 'Proteção ambiental';
+        case 86:
+        return 'Serviços de segurança';
+        default:
+        return 'Não classificada';
+    }
+};
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index ef4da72b..c11c9155 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -50,6 +50,41 @@ let rqf = new ReqQueryFields();
 
 courseCountApp.use(cache('15 day'));
 
+courseCountApp.get('/upper_adm_dependency', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 7; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.upperAdmDependency(i)
+        });
+    };
+    next();
+}, response('upper_adm_dependency'));
+
+courseCountApp.get('/years', (req, res, next) => {
+    req.sql.from('curso_ens_superior')
+    .field('DISTINCT curso_ens_superior.ano_censo', 'year');
+    next();
+}, query, response('years'));
+
+courseCountApp.get('/year_range', (req, res, next) => {
+    req.sql.from('curso_ens_superior')
+    .field('MIN(curso_ens_superior.ano_censo)', 'start_year')
+    .field('MAX(curso_ens_superior.ano_censo)', 'end_year');
+    next();
+}, query, response('range'));
+
+courseCountApp.get('/academic_organization', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 5; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.academicOrganization(i)
+        });
+    };
+    next();
+}, response('academic_organization'));
+
 rqf.addField({
     name: 'filter',
     field: false,
@@ -102,7 +137,7 @@ rqf.addField({
     name:'upper_adm_dependency',
     table: 'curso_ens_superior',
     tableField: 'cod_categoria_administrativa',
-    resultField: 'adm_dependency_id',
+    resultField: 'upper_adm_dependency_id',
     where: {
         relation: '=',
         type: 'integer',
@@ -112,7 +147,7 @@ rqf.addField({
     name:'academic_organization',
     table: 'curso_ens_superior',
     tableField: 'cod_organizacao_academica',
-    resultField: 'academic_type_id',
+    resultField: 'academic_organization_id',
     where: {
         relation: '=',
         type: 'integer',
@@ -128,17 +163,17 @@ rqf.addField({
         type: 'boolean',
         field: 'capital_curso'
     }
-}).addValue({       //add missing
-    name:'course',
+}).addValue({
+    name:'name',
     table: 'curso_ens_superior',
     tableField: ['nome_curso', 'cod_curso'],
     resultField: ['course_name', 'course_id'],
     where: {
-        relation: '=',
-        type: 'integer',
-        field: 'cod_curso'
+        relation: 'LIKE',
+        type: 'string',
+        field: 'nome_curso'
     }
-}).addValue({       //add missing
+}).addValue({
     name:'ocde_specific',
     table: 'curso_ens_superior',
     tableField: 'cod_ocde_area_especifica',
@@ -148,7 +183,7 @@ rqf.addField({
         type: 'integer',
         field: 'cod_ocde_area_especifica'
     }
-}).addValue({       //add missing
+}).addValue({
     name:'ocde',
     table: 'curso_ens_superior',
     tableField: 'cod_ocde_area_geral',
@@ -158,7 +193,7 @@ rqf.addField({
         type: 'integer',
         field: 'cod_ocde_area_geral'
     }
-}).addValue({       //add missing
+}).addValue({
     name:'ocde_detailed',
     table: 'curso_ens_superior',
     tableField: 'cod_ocde_area_detalhada',
@@ -168,7 +203,7 @@ rqf.addField({
         type: 'integer',
         field: 'cod_ocde_area_detalhada'
     }
-}).addValue({       //add missing
+}).addValue({
     name:'academic_level',
     table: 'curso_ens_superior',
     tableField: 'cod_grau_academico',
@@ -178,7 +213,7 @@ rqf.addField({
         type: 'integer',
         field: 'cod_grau_academico'
     }
-}).addValue({       //add missing
+}).addValue({
     name:'academic_mod',
     table: 'curso_ens_superior',
     tableField: 'cod_modalidade_ensino',
@@ -208,6 +243,48 @@ rqf.addField({
         type: 'boolean',
         field: 'noturno_curso'
     }
+}).addValue({
+    name:'situation',
+    table: 'curso_ens_superior',
+    tableField: 'cod_situacao_curso',
+    resultField: 'situacao_curso_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_situacao_curso'
+    }
+}).addValue({
+    name:'year',
+    table: 'curso_ens_superior',
+    tableField: 'ano_censo',
+    resultField: 'year',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'ano_censo'
+    }
+}).addValue({
+    name: 'min_year',
+    table: 'curso_ens_superior',
+    tableField: 'ano_censo',
+    resultField: 'year',
+    where: {
+        relation: '>=',
+        type: 'integer',
+        table: 'curso_ens_superior',
+        field: 'ano_censo'
+    }
+}).addValue({
+    name: 'max_year',
+    table: 'curso_ens_superior',
+    tableField: 'ano_censo',
+    resultField: 'year',
+    where: {
+        relation: '<=',
+        type: 'integer',
+        table: 'curso_ens_superior',
+        field: 'ano_censo'
+    }
 });
 
 courseCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
-- 
GitLab


From 16c12eca2869295f68a72ace69ab0e35b6fc5441 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Tue, 19 Feb 2019 10:25:46 -0300
Subject: [PATCH 032/142] =?UTF-8?q?Add=20agrega=C3=A7=C3=A3o=20por=20ies?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 src/libs/middlewares/id2str.js | 10 ++++++++++
 src/libs/routes/courseCount.js | 10 ++++++++++
 2 files changed, 20 insertions(+)

diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index bfa4dc7e..cfe7b074 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -55,6 +55,11 @@ const educationLevelSchoolYear = require(`${libs}/convert/educationLevelSchoolYe
 const pfe = require(`${libs}/convert/pfe`);
 const upperAdmDependency = require(`${libs}/convert/upperAdmDependency`);
 const academicOrganization = require(`${libs}/convert/academicOrganization`);
+const ocdeSpecific = require(`${libs}/convert/ocdeSpecific`);
+const ocdeGeral = require(`${libs}/convert/ocdeGeral`);
+const ocdeDetailed = require(`${libs}/convert/ocdeDetailed`);
+const academicLevel = require(`${libs}/convert/academicLevel`);
+const academicMod = require(`${libs}/convert/academicMod`);
 
 const ids = {
     gender_id: gender,
@@ -101,6 +106,11 @@ const ids = {
     pfe_id: pfe,
     upper_adm_dependency_id: upperAdmDependency,
     academic_organization_id: academicOrganization,
+    ocde_area_id: ocdeGeral,
+    ocde_area_specific_id: ocdeSpecific,
+    ocde_area_detailed_id: ocdeDetailed,
+    academic_level_id: academicLevel,
+    academic_mod_id: academicMod,
 };
 
 function transform(removeId=false) {
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index c11c9155..a54662b6 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -133,6 +133,16 @@ rqf.addField({
         type: 'integer',
         field: 'cod_municipio_curso'
     }
+}).addValue({       
+    name: 'ies',
+    table: 'curso_ens_superior',
+    tableField: ['cod_ies', 'nome_ies'],
+    resultField: ['ies_id', 'ies_name'],
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ies'
+    }
 }).addValue({
     name:'upper_adm_dependency',
     table: 'curso_ens_superior',
-- 
GitLab


From 1bfc125110ec78211b4142702d7a64c552e5e47c Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Wed, 20 Feb 2019 10:10:02 -0300
Subject: [PATCH 033/142] Init university name route

---
 src/libs/routes/university.js | 121 +++++++++++++++++++++++++++++++++-
 1 file changed, 118 insertions(+), 3 deletions(-)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index b8e34848..6ab0fbc3 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -24,6 +24,8 @@ const universityApp = express.Router();
 
 const libs = `${process.cwd()}/libs`;
 
+const log = require(`${libs}/log`)(module);
+
 const squel = require('squel');
 
 const query = require(`${libs}/middlewares/query`).query;
@@ -34,14 +36,20 @@ const id2str = require(`${libs}/middlewares/id2str`);
 
 const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);
 
-const addMissing = require(`${libs}/middlewares/addMissing`);
+const request = require(`request`);
 
 const config = require(`${libs}/config`);
 
+const passport = require('passport');
+
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
 
+const addMissing = require(`${libs}/middlewares/addMissing`);
+
 let rqf = new ReqQueryFields();
 
+let rqfCount = new ReqQueryFields();
+
 universityApp.use(cache('15 day'));
 
 universityApp.get('/upper_adm_dependency', (req, res, next) => {
@@ -83,6 +91,102 @@ 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: 'cod_uf_ies',
+        table: 'ies_ens_superior'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'cod_uf_ies',
+        foreignTable: 'ies_ens_superior'
+    }
+}).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,
@@ -165,7 +269,18 @@ rqf.addField({
     }
 });
 
-universityApp.get('/', rqf.parse(), (req, res, next) => {
+universityApp.get('/', rqf.parse(),  rqf.build(), (req, res, next) => {
+    req.sql.from('ies_ens_superior')
+        .field('ies_ens_superior.cod_ies')
+        .field('ies_ens_superior.ano_censo', 'year')
+        .field('ies_ens_superior.nome_ies', 'name')
+        .field('ies_ens_superior.cod_uf_ies', 'state_id')
+        .field('ies_ens_superior.cod_municipio_ies', 'city_id');
+    next();
+
+}, query, response('university'));
+
+universityApp.get('/count', rqfCount.parse(), (req, res, next) => {
     req.sql.field('COUNT(*)', 'total')
     .field("'Brasil'", 'name')
     .field('ies_ens_superior.ano_censo', 'year')
@@ -174,6 +289,6 @@ universityApp.get('/', rqf.parse(), (req, res, next) => {
     .order('ies_ens_superior.ano_censo')
 
     next();
-}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('university'));
+}, rqfCount.build(), query, addMissing(rqf), id2str.transform(), response('university'));
 
 module.exports = universityApp;
-- 
GitLab


From 9a0e2715dfe1ae2dba66051a5d98ad6f768b0898 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Wed, 20 Feb 2019 10:26:22 -0300
Subject: [PATCH 034/142] Finish search university

---
 src/libs/routes/university.js | 26 +++++++++++++-------------
 1 file changed, 13 insertions(+), 13 deletions(-)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index 6ab0fbc3..0504eea9 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -93,12 +93,12 @@ rqf.addField({
     where: true
 }).addValue({
     name: 'id',
-    table: 'escola',
-    tableField: 'id',
+    table: 'ies_ens_superior',
+    tableField: 'cod_ies',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'id'
+        field: 'cod_ies'
     }
 }).addValue({
     name: 'city',
@@ -108,13 +108,13 @@ rqf.addField({
     where: {
         relation: '=',
         type: 'integer',
-        field: 'municipio_id',
-        table: 'escola'
+        field: 'cod_municipio_ies',
+        table: 'ies_ens_superior'
     },
     join: {
         primary: 'id',
-        foreign: 'municipio_id',
-        foreignTable: 'escola'
+        foreign: 'cod_municipio_ies',
+        foreignTable: 'ies_ens_superior'
     }
 }).addValue({
     name: 'state',
@@ -134,14 +134,14 @@ rqf.addField({
     }
 }).addValue({
     name: 'year',
-    table: 'escola',
+    table: 'ies_ens_superior',
     tableField: 'ano_censo',
     resultField: 'year',
     where: {
         relation: '=',
         type: 'integer',
         field: 'ano_censo',
-        table: 'escola'
+        table: 'ies_ens_superior'
     }
 }).addField({
     name: 'search',
@@ -160,8 +160,8 @@ rqf.addField({
     },
     join: {
       primary: 'id',
-      foreign: 'municipio_id',
-      foreignTable: 'escola'
+      foreign: 'cod_municipio_ies',
+      foreignTable: 'ies_ens_superior'
     }
 }, 'search')
 .addValueToField({
@@ -177,8 +177,8 @@ rqf.addField({
     },
     join: {
       primary: 'id',
-      foreign: 'estado_id',
-      foreignTable: 'escola'
+      foreign: 'cod_uf_ies',
+      foreignTable: 'ies_ens_superior'
     }
 }, 'search');
 
-- 
GitLab


From 4b9927b726e295bd23ab54dbf477ffcfbd8ec1fa Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Wed, 20 Feb 2019 11:00:34 -0300
Subject: [PATCH 035/142] Add subroutes to course_count

---
 .../{academicMod.js => upperEducationMod.js}  |   2 +-
 src/libs/middlewares/id2str.js                |  17 ++-
 src/libs/routes/courseCount.js                | 140 +++++++++++++++---
 3 files changed, 134 insertions(+), 25 deletions(-)
 rename src/libs/convert/{academicMod.js => upperEducationMod.js} (95%)

diff --git a/src/libs/convert/academicMod.js b/src/libs/convert/upperEducationMod.js
similarity index 95%
rename from src/libs/convert/academicMod.js
rename to src/libs/convert/upperEducationMod.js
index 89c85e5f..47fa9573 100644
--- a/src/libs/convert/academicMod.js
+++ b/src/libs/convert/upperEducationMod.js
@@ -18,7 +18,7 @@ You should have received a copy of the GNU General Public License
 along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
 */
 
-module.exports = function academicMod(id) {
+module.exports = function upperEducationMod(id) {
     switch (id) {
         case 1:
         return 'Presencial';
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index cfe7b074..8e4f3398 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -59,7 +59,7 @@ const ocdeSpecific = require(`${libs}/convert/ocdeSpecific`);
 const ocdeGeral = require(`${libs}/convert/ocdeGeral`);
 const ocdeDetailed = require(`${libs}/convert/ocdeDetailed`);
 const academicLevel = require(`${libs}/convert/academicLevel`);
-const academicMod = require(`${libs}/convert/academicMod`);
+const upperEducationMod = require(`${libs}/convert/upperEducationMod`);
 
 const ids = {
     gender_id: gender,
@@ -106,11 +106,11 @@ const ids = {
     pfe_id: pfe,
     upper_adm_dependency_id: upperAdmDependency,
     academic_organization_id: academicOrganization,
-    ocde_area_id: ocdeGeral,
-    ocde_area_specific_id: ocdeSpecific,
-    ocde_area_detailed_id: ocdeDetailed,
+    ocde_id: ocdeGeral,
+    ocde_specific_id: ocdeSpecific,
+    ocde_detailed_id: ocdeDetailed,
     academic_level_id: academicLevel,
-    academic_mod_id: academicMod,
+    upper_education_mod_id: upperEducationMod,
 };
 
 function transform(removeId=false) {
@@ -183,5 +183,10 @@ module.exports = {
     specialClass,
     integralTime,
     upperAdmDependency,
-    academicOrganization
+    academicOrganization,
+    ocdeGeral,
+    ocdeSpecific,
+    ocdeDetailed,
+    academicLevel,
+    upperEducationMod
 };
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index a54662b6..9cb8783a 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -85,6 +85,110 @@ courseCountApp.get('/academic_organization', (req, res, next) => {
     next();
 }, response('academic_organization'));
 
+courseCountApp.get('/capital', (req, res, next) => {
+    req.result = [
+        {id: null, name: 'Não Classificado'},
+        {id: 0, name: 'Não'},
+        {id: 1, name: 'Sim'}
+    ];
+    next();
+}, response('capital'));
+
+courseCountApp.get('/ocde', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 9; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.ocdeGeral(i)
+        });
+    };
+    next();
+}, response('ocde'));
+
+courseCountApp.get('/ocde_specific', (req, res, next) => {
+    req.result = [];
+    const defaultCase = null;
+    for(let i = 1; i <= 86; ++i) {
+        let obj = {
+            id: i,
+            name: id2str.ocdeSpecific(i)
+        };
+        if (obj.name !== id2str.ocdeSpecific(defaultCase)){
+            req.result.push(obj);
+        }
+    };
+    req.result.push({
+        id: defaultCase,
+        name: id2str.ocdeSpecific(defaultCase)
+    });
+    next();
+}, response('ocde_specific'));
+
+courseCountApp.get('/ocde_detailed', (req, res, next) => {
+    req.result = [];
+    const defaultCase = null;
+    for(let i = 142; i <= 863; ++i) {
+        let obj = {
+            id: i,
+            name: id2str.ocdeDetailed(i)
+        };
+        if (obj.name !== id2str.ocdeDetailed(defaultCase)){
+            req.result.push(obj);
+        }
+    };
+    req.result.push({
+        id: defaultCase,
+        name: id2str.ocdeDetailed(defaultCase)
+    });
+    next();
+}, response('ocde_detailed'));
+
+courseCountApp.get('/academic_level', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 4; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.academicLevel(i)
+        });
+    };
+    next();
+}, response('academic_level'));
+
+courseCountApp.get('/upper_education_mod', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 3; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.upperEducationMod(i)
+        });
+    };
+    next();
+}, response('upper_education_mod'));
+
+courseCountApp.get('/free', (req, res, next) => {
+    req.result = [
+        {id: null, name: 'Não Classificado'},
+        {id: 0, name: 'Não'},
+        {id: 1, name: 'Sim'}
+    ];
+    next();
+}, response('free'));
+
+courseCountApp.get('/night_time', (req, res, next) => {
+    req.result = [
+        {id: null, name: 'Não Classificado'},
+        {id: 0, name: 'Não'},
+        {id: 1, name: 'Sim'}
+    ];
+    next();
+}, response('night_time'));
+
+courseCountApp.get('/course', (req, res, next) => {
+    req.sql.from('curso_ens_superior')
+    .field('DISTINCT curso_ens_superior.nome_curso', 'nome')
+    next();
+}, query, response('course'));
+
 rqf.addField({
     name: 'filter',
     field: false,
@@ -170,14 +274,14 @@ rqf.addField({
     resultField: 'in_capital',
     where: {
         relation: '=',
-        type: 'boolean',
+        type: 'integer',
         field: 'capital_curso'
     }
 }).addValue({
-    name:'name',
+    name:'course',
     table: 'curso_ens_superior',
-    tableField: ['nome_curso', 'cod_curso'],
-    resultField: ['course_name', 'course_id'],
+    tableField: 'nome_curso',
+    resultField: 'course_name',
     where: {
         relation: 'LIKE',
         type: 'string',
@@ -187,7 +291,7 @@ rqf.addField({
     name:'ocde_specific',
     table: 'curso_ens_superior',
     tableField: 'cod_ocde_area_especifica',
-    resultField: 'ocde_area_specific_id',
+    resultField: 'ocde_specific_id',
     where: {
         relation: '=',
         type: 'integer',
@@ -197,7 +301,7 @@ rqf.addField({
     name:'ocde',
     table: 'curso_ens_superior',
     tableField: 'cod_ocde_area_geral',
-    resultField: 'ocde_area_id',
+    resultField: 'ocde_id',
     where: {
         relation: '=',
         type: 'integer',
@@ -207,7 +311,7 @@ rqf.addField({
     name:'ocde_detailed',
     table: 'curso_ens_superior',
     tableField: 'cod_ocde_area_detalhada',
-    resultField: 'ocde_area_detailed_id',
+    resultField: 'ocde_detailed_id',
     where: {
         relation: '=',
         type: 'integer',
@@ -224,10 +328,10 @@ rqf.addField({
         field: 'cod_grau_academico'
     }
 }).addValue({
-    name:'academic_mod',
+    name:'upper_education_mod',
     table: 'curso_ens_superior',
     tableField: 'cod_modalidade_ensino',
-    resultField: 'academic_mod_id',
+    resultField: 'upper_education_mod_id',
     where: {
         relation: '=',
         type: 'integer',
@@ -298,15 +402,15 @@ rqf.addField({
 });
 
 courseCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
-    req.sql.field('COUNT(cod_curso)', 'total')
-    .field("'Brasil'", 'name')
-    .field('curso_ens_superior.ano_censo', 'year')
-    .from('curso_ens_superior')
-    .group('curso_ens_superior.ano_censo')
-    .order('curso_ens_superior.ano_censo')
-    .where('curso_ens_superior.cod_situacao_curso = 1 OR curso_ens_superior.cod_situacao_curso = 3')
-    .where('curso_ens_superior.tipo_atributo_ingresso <> 1')
-    .where('curso_ens_superior.cod_nivel_academico = 1');
+    req.sql.from('curso_ens_superior')
+        .field('COUNT(curso_ens_superior.cod_curso)', 'total')
+        .field("'Brasil'", 'name')
+        .field('curso_ens_superior.ano_censo', 'year')
+        .group('curso_ens_superior.ano_censo')
+        .order('curso_ens_superior.ano_censo')
+        .where('curso_ens_superior.cod_situacao_curso = 1 OR curso_ens_superior.cod_situacao_curso = 3')
+        .where('curso_ens_superior.tipo_atributo_ingresso <> 1')
+        .where('curso_ens_superior.cod_nivel_academico = 1');
 
     next();
 }, query, addMissing(rqf), id2str.transform(), response('course_count'));
-- 
GitLab


From 1cb37c822797da5ed14291601770080cd6c43f87 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Wed, 20 Feb 2019 11:05:06 -0300
Subject: [PATCH 036/142] Default university enrollment query

---
 src/libs/routes/api.js                  |  3 ++
 src/libs/routes/universityEnrollment.js | 60 +++++++++++++++++++++++++
 2 files changed, 63 insertions(+)
 create mode 100644 src/libs/routes/universityEnrollment.js

diff --git a/src/libs/routes/api.js b/src/libs/routes/api.js
index 5141ec78..fb1bd3f2 100644
--- a/src/libs/routes/api.js
+++ b/src/libs/routes/api.js
@@ -106,6 +106,8 @@ const employees = require(`${libs}/routes/employees`);
 
 const financial = require(`${libs}/routes/financial`);
 
+const universityEnrollment = require(`${libs}/routes/universityEnrollment`);
+
 api.get('/', (req, res) => {
     res.json({ msg: 'SimCAQ API is running' });
 });
@@ -151,6 +153,7 @@ api.use('/portal_mec_inep', portalMecInep);
 api.use('/enrollment_projection', enrollmentProjection);
 api.use('/employees', employees);
 api.use('/financial', financial);
+api.use('/university_enrollment', universityEnrollment);
 
 
 module.exports = api;
diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
new file mode 100644
index 00000000..c7ffe7bd
--- /dev/null
+++ b/src/libs/routes/universityEnrollment.js
@@ -0,0 +1,60 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+const express = require('express');
+
+const universityEnrollmentApp = express.Router();
+
+const libs = `${process.cwd()}/libs`;
+
+const log = require(`${libs}/log`)(module);
+
+const squel = require('squel');
+
+const query = require(`${libs}/middlewares/query`).query;
+
+const response = require(`${libs}/middlewares/response`);
+
+const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);
+
+const id2str = require(`${libs}/middlewares/id2str`);
+
+const addMissing = require(`${libs}/middlewares/addMissing`);
+
+const config = require(`${libs}/config`);
+
+const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
+
+let rqf = new ReqQueryFields();
+
+
+universityEnrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
+    req.sql.field('COUNT(*)', 'total')
+    .field("'Brasil'", 'name')
+    .field('aluno_ens_superior.ano_censo', 'year')
+    .from('aluno_ens_superior')
+    .where('aluno_ens_superior.matriculado = 1 AND aluno_ens_superior.cod_nivel_academico = 1')
+    .group('aluno_ens_superior.ano_censo')
+    .order('aluno_ens_superior.ano_censo')
+
+   next();
+}, query, addMissing(rqf), id2str.transform(false), response('universityEnrollment'));
+
+module.exports = universityEnrollmentApp;
-- 
GitLab


From 3e8cefd403ba00f8d818db032ba5ad6f8f72aaf2 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Wed, 20 Feb 2019 14:56:11 -0300
Subject: [PATCH 037/142] Add convert routes

---
 src/libs/convert/academicOrganization.js |  36 +++++++
 src/libs/middlewares/id2str.js           |   8 +-
 src/libs/routes/universityEnrollment.js  | 126 ++++++++++++++++++++++-
 3 files changed, 166 insertions(+), 4 deletions(-)
 create mode 100644 src/libs/convert/academicOrganization.js

diff --git a/src/libs/convert/academicOrganization.js b/src/libs/convert/academicOrganization.js
new file mode 100644
index 00000000..14611d15
--- /dev/null
+++ b/src/libs/convert/academicOrganization.js
@@ -0,0 +1,36 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function academicOrganization(id) {
+    switch (id) {
+        case 1:
+        return 'Universidade';
+        case 2:
+        return 'Centro Universitário';
+        case 3:
+        return 'Faculdade';
+        case 4:
+        return 'Instituto Federal de Educação, Ciência e Tecnologia';
+        case 5:
+        return 'Centro Federal de Educação Tecnológica';
+        default:
+        return 'Não classificada';
+    }
+};
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 65a8b3ca..bfa4dc7e 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -53,6 +53,8 @@ const specialClass = require(`${libs}/convert/booleanVariable`);
 const integralTime = require(`${libs}/convert/integralTime`);
 const educationLevelSchoolYear = require(`${libs}/convert/educationLevelSchoolYear`);
 const pfe = require(`${libs}/convert/pfe`);
+const upperAdmDependency = require(`${libs}/convert/upperAdmDependency`);
+const academicOrganization = require(`${libs}/convert/academicOrganization`);
 
 const ids = {
     gender_id: gender,
@@ -97,6 +99,8 @@ const ids = {
     special_class_id: specialClass,
     education_level_school_year_id: educationLevelSchoolYear,
     pfe_id: pfe,
+    upper_adm_dependency_id: upperAdmDependency,
+    academic_organization_id: academicOrganization,
 };
 
 function transform(removeId=false) {
@@ -167,5 +171,7 @@ module.exports = {
     useTransport,
     transportationManager,
     specialClass,
-    integralTime
+    integralTime,
+    upperAdmDependency,
+    academicOrganization
 };
diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index c7ffe7bd..107778db 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -44,8 +44,128 @@ const cache = require('apicache').options({ debug: config.debug, statusCodes: {i
 
 let rqf = new ReqQueryFields();
 
-
-universityEnrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
+universityEnrollmentApp.get('/years', (req, res, next) => {
+    req.sql.from('aluno_ens_superior')
+    .field('DISTINCT aluno_ens_superior.ano_censo', 'year');
+    next();
+}, query, response('years'));
+
+universityEnrollmentApp.get('/year_range', (req, res, next) => {
+    req.sql.from('aluno_ens_superior')
+    .field('MIN(aluno_ens_superior.ano_censo)', 'start_year')
+    .field('MAX(aluno_ens_superior.ano_censo)', 'end_year');
+    next();
+}, query, response('range'));
+
+universityEnrollmentApp.get('/academic_organization', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 5; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.academicOrganization(i)
+        });
+    };
+    next();
+}, response('academic_organization'));
+
+universityEnrollmentApp.get('/upper_adm_dependency', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 7; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.upperAdmDependency(i)
+        });
+    };
+    next();
+}, response('upper_adm_dependency'));
+
+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: 'cod_municipio_ies',
+        table: 'aluno_ens_superior'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'cod_municipio_ies',
+        foreignTable: 'aluno_ens_superior'
+    }
+}).addValue({
+    name: 'min_year',
+    table: '@',
+    tableField: 'ano_censo',
+    resultField: 'year',
+    where: {
+        relation: '>=',
+        type: 'integer',
+        table: '@',
+        field: 'ano_censo'
+    }
+}).addValue({
+    name: 'max_year',
+    table: '@',
+    tableField: 'ano_censo',
+    resultField: 'year',
+    where: {
+        relation: '<=',
+        type: 'integer',
+        table: '@',
+        field: 'ano_censo'
+    }
+}).addValue({
+    name: 'state',
+    table: 'estado',
+    tableField: 'nome',
+    resultField: 'state_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_uf_ies',
+        table: '@'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'cod_uf_ies',
+        foreignTable: '@'
+    }
+}).addValue({
+    name: 'upper_adm_dependency',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_categoria_administrativa',
+    resultField: 'upper_adm_dependency_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        table: 'aluno_ens_superior',
+        field: 'cod_categoria_administrativa'
+    }
+}).addValue({
+    name: 'academic_organization',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_organizacao_academica',
+    resultField: 'academic_organization_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        table: 'aluno_ens_superior',
+        field: 'cod_organizacao_academica'
+    }
+});
+
+universityEnrollmentApp.get('/', rqf.parse(), (req, res, next) => {
     req.sql.field('COUNT(*)', 'total')
     .field("'Brasil'", 'name')
     .field('aluno_ens_superior.ano_censo', 'year')
@@ -55,6 +175,6 @@ universityEnrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     .order('aluno_ens_superior.ano_censo')
 
    next();
-}, query, addMissing(rqf), id2str.transform(false), response('universityEnrollment'));
+},  rqf.build(), query, addMissing(rqf), id2str.transform(false), response('universityEnrollment'));
 
 module.exports = universityEnrollmentApp;
-- 
GitLab


From 723c0f2fda14d59c6ab459233e13a0cd262c3db4 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Wed, 20 Feb 2019 14:57:48 -0300
Subject: [PATCH 038/142] Add upper adm convert

---
 src/libs/convert/upperAdmDependency.js | 40 ++++++++++++++++++++++++++
 1 file changed, 40 insertions(+)
 create mode 100644 src/libs/convert/upperAdmDependency.js

diff --git a/src/libs/convert/upperAdmDependency.js b/src/libs/convert/upperAdmDependency.js
new file mode 100644
index 00000000..311475ff
--- /dev/null
+++ b/src/libs/convert/upperAdmDependency.js
@@ -0,0 +1,40 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function upperAdmDependency(id) {
+    switch (id) {
+        case 1:
+        return 'Pública Federal';
+        case 2:
+        return 'Pública Estadual';
+        case 3:
+        return 'Pública Municipal';
+        case 4:
+        return 'Privada com fins lucrativos';
+        case 5:
+        return 'Privada sem fins lucrativos';
+        case 6:
+        return 'Privada confessional';
+        case 7:
+        return 'Especial';
+        default:
+        return 'Não classificada';
+    }
+};
-- 
GitLab


From 2ef0b7d1fee5b3d7a4239430faa904f4b24cdb03 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 21 Feb 2019 09:38:24 -0300
Subject: [PATCH 039/142] Test git checkout

---
 src/libs/convert/ocdeGeral.js | 0
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 src/libs/convert/ocdeGeral.js

diff --git a/src/libs/convert/ocdeGeral.js b/src/libs/convert/ocdeGeral.js
new file mode 100644
index 00000000..e69de29b
-- 
GitLab


From 916a8c1363ebbad4defe701ec12d7ee7368634dd Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 21 Feb 2019 09:48:56 -0300
Subject: [PATCH 040/142] Add OCDE convert

---
 src/libs/convert/ocdeDetailed.js | 183 +++++++++++++++++++++++++++++++
 src/libs/convert/ocdeGeral.js    |  44 ++++++++
 src/libs/convert/ocdeSpecific.js |  70 ++++++++++++
 3 files changed, 297 insertions(+)
 create mode 100644 src/libs/convert/ocdeDetailed.js
 create mode 100644 src/libs/convert/ocdeSpecific.js

diff --git a/src/libs/convert/ocdeDetailed.js b/src/libs/convert/ocdeDetailed.js
new file mode 100644
index 00000000..e83dc4d9
--- /dev/null
+++ b/src/libs/convert/ocdeDetailed.js
@@ -0,0 +1,183 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+module.exports = function ocdeDetailed(id) {
+	switch (id) {
+		case 142:
+		return 'Ciências da educação';
+		case 144:
+		return 'Formação de professor da educação básica';
+		case 145:
+		return 'Formação de professor de matérias específicas';
+		case 146:
+		return 'Formação de professor de disciplinas profissionais';
+		case 210:
+		return 'Artes (cursos gerais)';
+		case 211:
+		return 'Belas artes';
+		case 212:
+		return 'Música e artes cênicas';
+		case 213:
+		return 'Técnicas audiovisuais e produção de mídia';
+		case 214:
+		return 'Design e estilismo';
+		case 215:
+		return 'Artesanato';
+		case 220:
+		return 'Humanidades e letras (cursos gerais)';
+		case 221:
+		return 'Religião e teologia';
+		case 222:
+		return 'Línguas e culturas estrangeiras';
+		case 223:
+		return 'Língua materna (vernácula)';
+		case 225:
+		return 'História e arqueologia';
+		case 226:
+		return 'Filosofia e ética';
+		case 310:
+		return 'Ciências sociais e comportamentais (cursos gerais)';
+		case 311:
+		return 'Psicologia';
+		case 312:
+		return 'Sociologia e estudos culturais';
+		case 313:
+		return 'Ciência política e educação cívica';
+		case 314:
+		return 'Economia';
+		case 321:
+		return 'Jornalismo e reportagem';
+		case 322:
+		return 'Biblioteconomia, informação, arquivos';
+		case 340:
+		return 'Comércio e administração (cursos gerais)';
+		case 341:
+		return 'Vendas em atacado e varejo';
+		case 342:
+		return 'Marketing e publicidade';
+		case 343:
+		return 'Finanças, bancos, seguros';
+		case 344:
+		return 'Contabilidade e tributação';
+		case 345:
+		return 'Gerenciamento e administração';
+		case 346:
+		return 'Secretariado e trabalhos de escritório';
+		case 380:
+		return 'Direito';
+		case 420:
+		return 'Ciências (cursos gerais)';
+		case 421:
+		return 'Biologia e bioquímica';
+		case 422:
+		return 'Ciências ambientais';
+		case 440:
+		return 'Ciências físicas (cursos gerais)';
+		case 441:
+		return 'Física';
+		case 442:
+		return 'Química';
+		case 443:
+		return 'Ciências da terra';
+		case 461:
+		return 'Matemática';
+		case 462:
+		return 'Estatística';
+		case 481:
+		return 'Ciência da computação';
+		case 482:
+		return 'Uso do computador';
+		case 483:
+		return 'Processamento da informação';
+		case 520:
+		return 'Engenharia e profissões de engenharia (cursos gerais)';
+		case 521:
+		return 'Engenharia mecânica e metalurgia (trabalhos com metais)';
+		case 522:
+		return 'Eletricidade e energia';
+		case 523:
+		return 'Eletrônica e automação';
+		case 524:
+		return 'Química e engenharia de processos';
+		case 525:
+		return 'Veículos a motor, construção naval e aeronáutica';
+		case 540:
+		return 'Fabricação e processamento (cursos gerais)';
+		case 541:
+		return 'Processamento de alimentos';
+		case 542:
+		return 'Têxteis, roupas, calçados, couros';
+		case 543:
+		return 'Materiais (madeira, papel, plástico, vidro)';
+		case 544:
+		return 'Mineração e extração';
+		case 581:
+		return 'Arquitetura e urbanismo';
+		case 582:
+		return 'Engenharia civil e de construção';
+		case 621:
+		return 'Produção agrícola e pecuária';
+		case 622:
+		return 'Horticultura';
+		case 623:
+		return 'Engenharia florestal - silvicultura';
+		case 624:
+		return 'Recursos pesqueiros';
+		case 641:
+		return 'Veterinária';
+		case 720:
+		return 'Saúde (cursos gerais)';
+		case 721:
+		return 'Medicina';
+		case 723:
+		return 'Enfermagem e atenção primária (assistência básica)';
+		case 724:
+		return 'Odontologia';
+		case 725:
+		return 'Tecnologias de diagnóstico e tratamento médico';
+		case 726:
+		return 'Terapia e reabilitação';
+		case 727:
+		return 'Farmácia';
+		case 762:
+		return 'Serviço social e orientação';
+		case 811:
+		return 'Hotelaria, restaurantes  e serviços de alimentação';
+		case 812:
+		return 'Viagens, turismo e lazer';
+		case 813:
+		return 'Esportes';
+		case 814:
+		return 'Ciências domésticas';
+		case 815:
+		return 'Serviços de beleza';
+		case 840:
+		return 'Transportes e serviços (cursos gerais)';
+		case 850:
+		return 'Proteção ambiental (cursos gerais)';
+		case 861:
+		return 'Proteção de pessoas e de propriedades';
+		case 862:
+		return 'Saúde e segurança do trabalho';
+		case 863:
+		return 'Setor militar e de defesa';
+		default:
+		return 'Não classificada';
+	}
+};
\ No newline at end of file
diff --git a/src/libs/convert/ocdeGeral.js b/src/libs/convert/ocdeGeral.js
index e69de29b..88cc0646 100644
--- a/src/libs/convert/ocdeGeral.js
+++ b/src/libs/convert/ocdeGeral.js
@@ -0,0 +1,44 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function ocdeGeral(id) {
+    switch (id) {
+        case 0:
+        return 'Área básica';
+        case 1:
+        return 'Educação';
+        case 2:
+        return 'Humanidades e artes';
+        case 3:
+        return 'Ciências sociais, negócios e direitor';
+        case 4:
+        return 'Ciências, matemática e computação';
+        case 5:
+        return 'Engenharia, produção e construção';
+        case 6:
+        return 'Agricultura e veterinária';
+        case 7:
+        return 'Saúde e bem estar social';
+        case 8:
+        return 'Serviços';
+        default:
+        return 'Não classificada';
+    }
+};
diff --git a/src/libs/convert/ocdeSpecific.js b/src/libs/convert/ocdeSpecific.js
new file mode 100644
index 00000000..7b360d86
--- /dev/null
+++ b/src/libs/convert/ocdeSpecific.js
@@ -0,0 +1,70 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function ocdeSpecific(id) {
+    switch (id) {
+        case 1:
+        return 'Área básica de cursos';
+        case 14:
+        return 'Formação de professor e ciências da educação';
+        case 21:
+        return 'Artes';
+        case 22:
+        return 'Humanidades e letras';
+        case 31:
+        return 'Ciências sociais e comportamentais';
+        case 32:
+        return 'Jornalismo e informação';
+        case 34:
+        return 'Comércio e administração';
+        case 38:
+        return 'Direito';
+        case 42:
+        return 'Ciências';
+        case 44:
+        return 'Ciências físicas';
+        case 48:
+        return 'Computação';
+        case 52:
+        return 'Engenharia e profissões correlatas';
+        case 54:
+        return 'Produção e processamento';
+        case 58:
+        return 'Arquitetura e construção';
+        case 62:
+        return 'Agricultura, florestas e recursos pasqueiros';
+        case 64:
+        return 'Veterinária';
+        case 72:
+        return 'Saúde';
+        case 76:
+        return 'Serviço social';
+        case 81:
+        return 'Serviços pessoais';
+        case 84:
+        return 'Serviços de transportes (cursos gerais)';
+        case 85:
+        return 'Proteção ambiental';
+        case 86:
+        return 'Serviços de segurança';
+        default:
+        return 'Não classificada';
+    }
+};
-- 
GitLab


From 5905461b1fef5e7df05081ab3d3dad68065f7b38 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Fri, 22 Feb 2019 11:48:10 -0300
Subject: [PATCH 041/142] Finish universy enrollment route

---
 src/libs/convert/academicLevel.js       |  33 +++++
 src/libs/convert/schoolType.js          |  30 +++++
 src/libs/convert/studentDeficiency.js   |  30 +++++
 src/libs/convert/upperEducationMod.js   |  31 +++++
 src/libs/convert/upperTurn.js           |  34 +++++
 src/libs/middlewares/id2str.js          |  24 +++-
 src/libs/routes/universityEnrollment.js | 172 ++++++++++++++++++++++++
 7 files changed, 353 insertions(+), 1 deletion(-)
 create mode 100644 src/libs/convert/academicLevel.js
 create mode 100644 src/libs/convert/schoolType.js
 create mode 100644 src/libs/convert/studentDeficiency.js
 create mode 100644 src/libs/convert/upperEducationMod.js
 create mode 100644 src/libs/convert/upperTurn.js

diff --git a/src/libs/convert/academicLevel.js b/src/libs/convert/academicLevel.js
new file mode 100644
index 00000000..467e010f
--- /dev/null
+++ b/src/libs/convert/academicLevel.js
@@ -0,0 +1,33 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function academicLevel(id) {
+    switch (id) {
+        case 1:
+        return 'Bacharelado';
+        case 2:
+        return 'Licenciatura';
+        case 3:
+        return 'Tecnológico';
+        default:
+        return 'Não classificada';
+    }
+};
+
diff --git a/src/libs/convert/schoolType.js b/src/libs/convert/schoolType.js
new file mode 100644
index 00000000..f485ecb9
--- /dev/null
+++ b/src/libs/convert/schoolType.js
@@ -0,0 +1,30 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function studentDeficiency(id) {
+    switch (id) {
+        case 1:
+        return 'Pública';
+        case 2:
+        return 'Privada';
+        default:
+        return 'Não classificado';
+    }
+};
diff --git a/src/libs/convert/studentDeficiency.js b/src/libs/convert/studentDeficiency.js
new file mode 100644
index 00000000..11c3c340
--- /dev/null
+++ b/src/libs/convert/studentDeficiency.js
@@ -0,0 +1,30 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function studentDeficiency(id) {
+    switch (id) {
+        case 0:
+        return 'Não';
+        case 1:
+        return 'Sim';
+        default:
+        return 'Não classificado'
+    }
+};
diff --git a/src/libs/convert/upperEducationMod.js b/src/libs/convert/upperEducationMod.js
new file mode 100644
index 00000000..d7a6c5c8
--- /dev/null
+++ b/src/libs/convert/upperEducationMod.js
@@ -0,0 +1,31 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function upperEducationMod(id) {
+    switch (id) {
+        case 1:
+        return 'Presencial';
+        case 2:
+        return 'A Distância';
+        default:
+        return 'Não classificada';
+    }
+};
+
diff --git a/src/libs/convert/upperTurn.js b/src/libs/convert/upperTurn.js
new file mode 100644
index 00000000..b5cac83f
--- /dev/null
+++ b/src/libs/convert/upperTurn.js
@@ -0,0 +1,34 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function upperTurn(id) {
+    switch (id) {
+        case 1:
+        return 'Matutino';
+        case 2:
+        return 'Vespertino';
+        case 3:
+        return 'Noturno';
+        case 4:
+        return 'Integral';
+        default:
+        return 'Não aplicavel (Ead)';
+    }
+};
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index bfa4dc7e..f5faf817 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -55,6 +55,14 @@ const educationLevelSchoolYear = require(`${libs}/convert/educationLevelSchoolYe
 const pfe = require(`${libs}/convert/pfe`);
 const upperAdmDependency = require(`${libs}/convert/upperAdmDependency`);
 const academicOrganization = require(`${libs}/convert/academicOrganization`);
+const ocdeSpecific = require(`${libs}/convert/ocdeSpecific`);
+const ocde = require(`${libs}/convert/ocdeGeral`);
+const ocdeDetailed = require(`${libs}/convert/ocdeDetailed`);
+const academicLevel = require(`${libs}/convert/academicLevel`);
+const upperEducationMod = require(`${libs}/convert/upperEducationMod`);
+const studentDeficiency = require(`${libs}/convert/studentDeficiency`);
+const schoolType = require(`${libs}/convert/schoolType`);
+
 
 const ids = {
     gender_id: gender,
@@ -101,6 +109,13 @@ const ids = {
     pfe_id: pfe,
     upper_adm_dependency_id: upperAdmDependency,
     academic_organization_id: academicOrganization,
+    ocde_specific_id: ocdeSpecific,
+    ocde_id: ocde,
+    ocde_detailed_id: ocdeDetailed,
+    academic_level_id: academicLevel,
+    upper_education_mod_id: upperEducationMod,
+    student_deficiency_id: studentDeficiency,
+    school_type_id: schoolType
 };
 
 function transform(removeId=false) {
@@ -173,5 +188,12 @@ module.exports = {
     specialClass,
     integralTime,
     upperAdmDependency,
-    academicOrganization
+    academicOrganization,
+    ocdeSpecific,
+    ocde,
+    ocdeDetailed,
+    academicLevel,
+    upperEducationMod,
+    studentDeficiency,
+    schoolType
 };
diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index 107778db..21f8f2f1 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -79,6 +79,88 @@ universityEnrollmentApp.get('/upper_adm_dependency', (req, res, next) => {
     next();
 }, response('upper_adm_dependency'));
 
+universityEnrollmentApp.get('/ocde', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 8; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.ocdeGeral(i)
+        });
+    };
+    next();
+}, response('ocde'));
+
+universityEnrollmentApp.get('/ocde_specific', (req, res, next) => {
+    req.result = [];
+    const defaultCase = null;
+    for(let i = 1; i <= 86; ++i) {
+        let obj = {
+            id: i,
+            name: id2str.ocdeSpecific(i)
+        };
+        if (obj.name !== id2str.ocdeSpecific(defaultCase)){
+            req.result.push(obj);
+        }
+    };
+    req.result.push({
+        id: defaultCase,
+        name: id2str.ocdeSpecific(defaultCase)
+    });
+    next();
+}, response('ocde_specific'));
+
+universityEnrollmentApp.get('/ocde_detailed', (req, res, next) => {
+    req.result = [];
+    const defaultCase = null;
+    for(let i = 142; i <= 863; ++i) {
+        let obj = {
+            id: i,
+            name: id2str.ocdeDetailed(i)
+        };
+        if (obj.name !== id2str.ocdeDetailed(defaultCase)){
+            req.result.push(obj);
+        }
+    };
+    req.result.push({
+        id: defaultCase,
+        name: id2str.ocdeDetailed(defaultCase)
+    });
+    next();
+}, response('ocde_detailed'));
+
+universityEnrollmentApp.get('/upper_turn', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 4; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.upperTurn(i)
+        });
+    };
+    next();
+}, response('upper_turn'));
+
+universityEnrollmentApp.get('/student_deficiency', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 2; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.studentDeficiency(i)
+        });
+    };
+    next();
+}, response('student_deficiency'));
+
+universityEnrollmentApp.get('/school_type', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 2; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.schoolType(i)
+        });
+    };
+    next();
+}, response('school_type'));
+
 rqf.addField({
     name: 'filter',
     field: false,
@@ -163,6 +245,96 @@ rqf.addField({
         table: 'aluno_ens_superior',
         field: 'cod_organizacao_academica'
     }
+}).addValue({
+    name:'ocde_specific',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_ocde_area_especifica',
+    resultField: 'ocde_specific_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ocde_area_especifica'
+    }
+}).addValue({
+    name:'ocde',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_ocde_area_geral',
+    resultField: 'ocde_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ocde_area_geral'
+    }
+}).addValue({
+    name:'ocde_detailed',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_ocde_area_detalhada',
+    resultField: 'ocde_detailed_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ocde_area_detalhada'
+    }
+}).addValue({
+    name:'academic_level',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_grau_academico',
+    resultField: 'academic_level_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_grau_academico'
+    }
+}).addValue({
+    name:'upper_education_mod',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_modalidade_ensino',
+    resultField: 'upper_education_mod_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_modalidade_ensino'
+    }
+}).addValue({
+    name:'upper_turn',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_turno_aluno',
+    resultField: 'upper_turn_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_turno_aluno'
+    }
+}).addValue({
+    name:'ethnic_group',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_cor_raca_aluno',
+    resultField: 'ethnic_group_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_cor_raca_aluno'
+    }
+}).addValue({
+    name:'student_deficiency',
+    table: 'aluno_ens_superior',
+    tableField: 'aluno_deficiencia_transtorno_superdotacao',
+    resultField: 'student_deficiency_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'aluno_deficiencia_transtorno_superdotacao'
+    }
+}).addValue({
+    name:'school_type',
+    table: 'aluno_ens_superior',
+    tableField: 'tipo_escola_ensino_medio',
+    resultField: 'school_type_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'tipo_escola_ensino_medio'
+    }
 });
 
 universityEnrollmentApp.get('/', rqf.parse(), (req, res, next) => {
-- 
GitLab


From 4521a2c58a63b2d0867b9db446417728f48cfe91 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Mon, 25 Feb 2019 11:06:04 -0300
Subject: [PATCH 042/142] Fix university enrollment route

---
 src/libs/middlewares/id2str.js          | 14 ++++---
 src/libs/routes/universityEnrollment.js | 53 +++++++++++++++----------
 2 files changed, 40 insertions(+), 27 deletions(-)

diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index f5faf817..cc1b69c2 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -56,13 +56,13 @@ const pfe = require(`${libs}/convert/pfe`);
 const upperAdmDependency = require(`${libs}/convert/upperAdmDependency`);
 const academicOrganization = require(`${libs}/convert/academicOrganization`);
 const ocdeSpecific = require(`${libs}/convert/ocdeSpecific`);
-const ocde = require(`${libs}/convert/ocdeGeral`);
+const ocdeGeral = require(`${libs}/convert/ocdeGeral`);
 const ocdeDetailed = require(`${libs}/convert/ocdeDetailed`);
 const academicLevel = require(`${libs}/convert/academicLevel`);
 const upperEducationMod = require(`${libs}/convert/upperEducationMod`);
 const studentDeficiency = require(`${libs}/convert/studentDeficiency`);
 const schoolType = require(`${libs}/convert/schoolType`);
-
+const upperTurn = require(`${libs}/convert/upperTurn`);
 
 const ids = {
     gender_id: gender,
@@ -110,12 +110,13 @@ const ids = {
     upper_adm_dependency_id: upperAdmDependency,
     academic_organization_id: academicOrganization,
     ocde_specific_id: ocdeSpecific,
-    ocde_id: ocde,
+    ocde_geral_id: ocdeGeral,
     ocde_detailed_id: ocdeDetailed,
     academic_level_id: academicLevel,
     upper_education_mod_id: upperEducationMod,
     student_deficiency_id: studentDeficiency,
-    school_type_id: schoolType
+    school_type_id: schoolType,
+    upper_turn_id: upperTurn
 };
 
 function transform(removeId=false) {
@@ -190,10 +191,11 @@ module.exports = {
     upperAdmDependency,
     academicOrganization,
     ocdeSpecific,
-    ocde,
+    ocdeGeral,
     ocdeDetailed,
     academicLevel,
     upperEducationMod,
     studentDeficiency,
-    schoolType
+    schoolType,
+    upperTurn
 };
diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index 21f8f2f1..d8c9fa3a 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -141,7 +141,7 @@ universityEnrollmentApp.get('/upper_turn', (req, res, next) => {
 
 universityEnrollmentApp.get('/student_deficiency', (req, res, next) => {
     req.result = [];
-    for(let i = 1; i <= 2; ++i) {
+    for(let i = 0; i <= 1; ++i) {
         req.result.push({
             id: i,
             name: id2str.studentDeficiency(i)
@@ -150,6 +150,17 @@ universityEnrollmentApp.get('/student_deficiency', (req, res, next) => {
     next();
 }, response('student_deficiency'));
 
+universityEnrollmentApp.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'));
+
 universityEnrollmentApp.get('/school_type', (req, res, next) => {
     req.result = [];
     for(let i = 1; i <= 2; ++i) {
@@ -169,22 +180,6 @@ rqf.addField({
     name: 'dims',
     field: true,
     where: false
-}).addValue({
-    name: 'city',
-    table: 'municipio',
-    tableField: 'nome',
-    resultField: 'city_name',
-    where: {
-        relation: '=',
-        type: 'integer',
-        field: 'cod_municipio_ies',
-        table: 'aluno_ens_superior'
-    },
-    join: {
-        primary: 'id',
-        foreign: 'cod_municipio_ies',
-        foreignTable: 'aluno_ens_superior'
-    }
 }).addValue({
     name: 'min_year',
     table: '@',
@@ -215,12 +210,28 @@ rqf.addField({
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_uf_ies',
+        field: 'cod_uf_nascimento',
+        table: '@'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'cod_uf_nascimento',
+        foreignTable: '@'
+    }
+}).addValue({
+    name: 'city',
+    table: 'municipio',
+    tableField: 'nome',
+    resultField: 'city_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_municipio_nascimento',
         table: '@'
     },
     join: {
         primary: 'id',
-        foreign: 'cod_uf_ies',
+        foreign: 'cod_municipio_nascimento',
         foreignTable: '@'
     }
 }).addValue({
@@ -256,10 +267,10 @@ rqf.addField({
         field: 'cod_ocde_area_especifica'
     }
 }).addValue({
-    name:'ocde',
+    name:'ocde_geral',
     table: 'aluno_ens_superior',
     tableField: 'cod_ocde_area_geral',
-    resultField: 'ocde_id',
+    resultField: 'ocde_geral_id',
     where: {
         relation: '=',
         type: 'integer',
-- 
GitLab


From 831bbe8fb42fa9dc360c7bc2d3b14f647a167aa2 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 28 Feb 2019 10:43:02 -0300
Subject: [PATCH 043/142] Change docente.id to docente.id_docente

---
 src/libs/routes/auxiliar.js  | 4 ++--
 src/libs/routes/portalMec.js | 2 +-
 src/libs/routes/teacher.js   | 4 ++--
 3 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js
index 74e05c77..dacf6bde 100644
--- a/src/libs/routes/auxiliar.js
+++ b/src/libs/routes/auxiliar.js
@@ -342,7 +342,7 @@ rqf.addField({
 
 // LDE
 auxiliarApp.get('/', rqf.parse(), (req, res, next) => {
-  req.sql.field('COUNT(DISTINCT docente.id)', 'total')
+  req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total')
   .field("'Brasil'", 'name')
   .field('docente.ano_censo', 'year')
   .from('docente')
@@ -354,7 +354,7 @@ auxiliarApp.get('/', rqf.parse(), (req, res, next) => {
 
 // SimCAQ
 auxiliarApp.get('/count', rqf.parse(), (req, res, next) => {
-  req.sql.field('COUNT(DISTINCT docente.id)', 'total')
+  req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total')
   .field("'Brasil'", 'name')
   .field('docente.ano_censo', 'year')
   .from('docente')
diff --git a/src/libs/routes/portalMec.js b/src/libs/routes/portalMec.js
index 29a1be6b..e54c90c2 100644
--- a/src/libs/routes/portalMec.js
+++ b/src/libs/routes/portalMec.js
@@ -120,7 +120,7 @@ rqf.addField({
 
 portalMecApp.get('/', rqf.parse(), (req, res, next) => {
 
-    req.sql.field('docente.id')
+    req.sql.field('docente.docente_id')
     .field('docente.ano_censo', 'year')
     .field('docente.cod_quimica', 'Química')
     .field('docente.cod_fisica', 'Física')
diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js
index b9a86226..e97d37e1 100644
--- a/src/libs/routes/teacher.js
+++ b/src/libs/routes/teacher.js
@@ -409,7 +409,7 @@ rqf.addField({
 });
 
 teacherApp.get('/', rqf.parse(), (req, res, next) => {
-    req.sql.field('COUNT(DISTINCT docente.id)', 'total')
+    req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total')
     .field("'Brasil'", 'name')
     .field('docente.ano_censo', 'year')
     .from('docente')
@@ -433,7 +433,7 @@ teacherApp.get('/', rqf.parse(), (req, res, next) => {
     if(req.hadEducationLevelMod) {
 
         req.sql = squel.select()
-        .field('COUNT(DISTINCT docente.id)', 'total')
+        .field('COUNT(DISTINCT docente.id_docente)', 'total')
         .field("'Brasil'", 'name')
         .field('docente.ano_censo', 'year')
         .from('docente')
-- 
GitLab


From d69cc374a6c4dc955b0b7c7efb14d7d960a3a545 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 7 Mar 2019 09:41:17 -0300
Subject: [PATCH 044/142] Fix addmissing function

---
 src/libs/routes/university.js | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index 0504eea9..fbe7d8f8 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -207,6 +207,22 @@ rqfCount.addField({
         foreign: 'cod_municipio_ies',
         foreignTable: 'ies_ens_superior'
     }
+}).addValue({
+    name: 'region',
+    table: 'regiao',
+    tableField: 'nome',
+    resultField: 'region_name',
+    where: {
+        relation: 'LIKE',
+        type: 'string',
+        field: 'id'
+    },
+    join: {
+        primary: 'nome',
+        foreign: 'nome_regiao_ies',
+        foreignTable: 'ies_ens_superior'
+    }
+
 }).addValue({
     name: 'min_year',
     table: '@',
@@ -289,6 +305,6 @@ universityApp.get('/count', rqfCount.parse(), (req, res, next) => {
     .order('ies_ens_superior.ano_censo')
 
     next();
-}, rqfCount.build(), query, addMissing(rqf), id2str.transform(), response('university'));
+}, rqfCount.build(), query, addMissing(rqfCount), id2str.transform(), response('university'));
 
 module.exports = universityApp;
-- 
GitLab


From af6bc88c88595b0690893695e7c5d0d802c0bef8 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 7 Mar 2019 11:39:57 -0300
Subject: [PATCH 045/142] Add region filter

---
 src/libs/routes/universityEnrollment.js | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index d8c9fa3a..2519ccae 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -234,6 +234,21 @@ rqf.addField({
         foreign: 'cod_municipio_nascimento',
         foreignTable: '@'
     }
+}).addValue({
+    name: 'region',
+    table: 'regiao',
+    tableField: 'nome',
+    resultField: 'region_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'id'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'regiao_id',
+        foreignTable: 'aluno_ens_superior'
+    }
 }).addValue({
     name: 'upper_adm_dependency',
     table: 'aluno_ens_superior',
-- 
GitLab


From a16a40c7451a1a7f11103012051ad5d505255211 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Tue, 12 Mar 2019 09:27:12 -0300
Subject: [PATCH 046/142] Fix subroutes in course count

---
 src/libs/middlewares/id2str.js |  3 +++
 src/libs/routes/courseCount.js | 18 +++++++++---------
 2 files changed, 12 insertions(+), 9 deletions(-)

diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 8e4f3398..31be56b9 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -111,6 +111,9 @@ const ids = {
     ocde_detailed_id: ocdeDetailed,
     academic_level_id: academicLevel,
     upper_education_mod_id: upperEducationMod,
+    is_free_id: booleanVariable,
+    night_time_id: booleanVariable,
+    capital_id: booleanVariable,
 };
 
 function transform(removeId=false) {
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index 9cb8783a..1cd1bea1 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -36,7 +36,7 @@ const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);
 
 const id2str = require(`${libs}/middlewares/id2str`);
 
-const config = require(`${libs}/config`); 
+const config = require(`${libs}/config`);
 
 const download = require(`${libs}/middlewares/downloadDatabase`);
 
@@ -165,14 +165,14 @@ courseCountApp.get('/upper_education_mod', (req, res, next) => {
     next();
 }, response('upper_education_mod'));
 
-courseCountApp.get('/free', (req, res, next) => {
+courseCountApp.get('/is_free', (req, res, next) => {
     req.result = [
         {id: null, name: 'Não Classificado'},
         {id: 0, name: 'Não'},
         {id: 1, name: 'Sim'}
     ];
     next();
-}, response('free'));
+}, response('is_free'));
 
 courseCountApp.get('/night_time', (req, res, next) => {
     req.result = [
@@ -227,7 +227,7 @@ rqf.addField({
         foreign: 'cod_uf_curso',
         foreignTable: 'curso_ens_superior'
     }
-}).addValue({       
+}).addValue({
     name: 'city',
     table: 'curso_ens_superior',
     tableField: ['municipio_curso', 'cod_municipio_curso'],
@@ -237,7 +237,7 @@ rqf.addField({
         type: 'integer',
         field: 'cod_municipio_curso'
     }
-}).addValue({       
+}).addValue({
     name: 'ies',
     table: 'curso_ens_superior',
     tableField: ['cod_ies', 'nome_ies'],
@@ -271,7 +271,7 @@ rqf.addField({
     name:'capital',
     table: 'curso_ens_superior',
     tableField: 'capital_curso',
-    resultField: 'in_capital',
+    resultField: 'capital_id',
     where: {
         relation: '=',
         type: 'integer',
@@ -338,10 +338,10 @@ rqf.addField({
         field: 'cod_modalidade_ensino'
     }
 }).addValue({
-    name:'free',
+    name:'is_free',
     table: 'curso_ens_superior',
     tableField: 'gratuito',
-    resultField: 'is_free',
+    resultField: 'is_free_id',
     where: {
         relation: '=',
         type: 'boolean',
@@ -415,4 +415,4 @@ courseCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     next();
 }, query, addMissing(rqf), id2str.transform(), response('course_count'));
 
-module.exports = courseCountApp;
\ No newline at end of file
+module.exports = courseCountApp;
-- 
GitLab


From 65cb89579ab7d316c2d1810131283619926343df Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 12 Mar 2019 11:11:42 -0300
Subject: [PATCH 047/142] [fix]addMissing fix

---
 src/libs/middlewares/addMissing.js | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/libs/middlewares/addMissing.js b/src/libs/middlewares/addMissing.js
index 6f5ef699..034ca80e 100644
--- a/src/libs/middlewares/addMissing.js
+++ b/src/libs/middlewares/addMissing.js
@@ -27,6 +27,7 @@ module.exports = function addMissing(rqf){
         if(req.result.length === 0) return next();
 
         let result = req.result;
+
         let dimsValues = {};
         result.forEach((r) => {
             dims.forEach((dim) => {
@@ -74,7 +75,7 @@ module.exports = function addMissing(rqf){
                         if(r[rqfName] > newEntry[rqfName]) break;
                         if(r[rqfName] == newEntry[rqfName] && r[rqfName2] > newEntry[rqfName2]) break;
                     }
-                    if (newEntry.dim1Value != undefined && newEntry.dim2Value != undefined) {
+                    if (newEntry.dim1Value == undefined && newEntry.dim2Value == undefined) {
                         let newResult = [...result.slice(0, index), newEntry, ...result.slice(index, result.length)];
                         result = newResult;
                     }
-- 
GitLab


From b1a72377cfdbc55518b6ac6b0b852342e7b4456d Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Thu, 14 Mar 2019 10:12:40 -0300
Subject: [PATCH 048/142] remove download routes

---
 config.json.example                      |  45 ++++++++++
 package.json                             |   1 +
 src/libs/middlewares/downloadDatabase.js | 108 -----------------------
 src/libs/routes/api.js                   |   3 -
 src/libs/routes/auxiliar.js              |   4 -
 src/libs/routes/class.js                 |   4 -
 src/libs/routes/courseCount.js           |   2 -
 src/libs/routes/cub.js                   |   2 -
 src/libs/routes/dailyChargeAmount.js     |   2 -
 src/libs/routes/downloads.js             |  74 ----------------
 src/libs/routes/enrollment.js            |   4 -
 src/libs/routes/glossEnrollmentRatio.js  |   2 -
 src/libs/routes/liquidEnrollmentRatio.js |   2 -
 src/libs/routes/rateSchool.js            |   4 -
 src/libs/routes/school.js                |   4 -
 src/libs/routes/teacher.js               |   4 -
 16 files changed, 46 insertions(+), 219 deletions(-)
 delete mode 100644 src/libs/middlewares/downloadDatabase.js
 delete mode 100644 src/libs/routes/downloads.js

diff --git a/config.json.example b/config.json.example
index e3d30920..1be79df9 100644
--- a/config.json.example
+++ b/config.json.example
@@ -90,6 +90,51 @@
             "tokenLife": 3600
         }
     },
+    "homologa":
+    {
+        "port": 3000,
+        "ip": "127.0.0.1",
+        "debug" : true,
+        "monetdb": {
+            "host": "simcaqdb3.c3sl.ufpr.br",
+            "port": 50000,
+            "dbname": "simcaq_dev4",
+            "user": "monetdb",
+            "password":"monetdb",
+            "nrConnections": "4"
+        },
+        "cdn" : {
+            "url": "http://simcaqdb3.c3sl.ufpr.br:3000",
+            "download": "https://simcaqdev.c3sl.ufpr.br/download/"
+        },
+        "mongodb" : {
+            "uri": "mongodb://localhost/dev_users"
+        },
+        "monq": {
+            "uri": "mongodb://localhost/dev_monq"
+        },
+        "default": {
+            "api": {
+                "version" : "v1"
+            },
+            "lde": {
+                "url": "http://ldedev.c3sl.ufpr.br/#"
+            },
+            "simcaq": {
+                "url": "http://simcaqdev.c3sl.ufpr.br/#"
+            }
+        },
+        "email": {
+            "port": 25,
+            "host": "mx.c3sl.ufpr.br",
+            "secure": false,
+            "ignoreTLS": true,
+            "from": "\"Laboratório de Dados Educacionais\" <lde@c3sl.ufpr.br>"
+        },
+        "security": {
+            "tokenLife": 3600
+        }
+    },
     "production":
     {
         "port": 6000,
diff --git a/package.json b/package.json
index bb9438bf..df8ba0c9 100644
--- a/package.json
+++ b/package.json
@@ -51,6 +51,7 @@
     "mocha": "^3.5.3",
     "monetdb-pool": "0.0.8",
     "mongoose": "^4.13.17",
+    "natives": "^1.1.6",
     "nconf": "^0.8.5",
     "node-uuid": "^1.4.8",
     "nodemailer": "^4.6.8",
diff --git a/src/libs/middlewares/downloadDatabase.js b/src/libs/middlewares/downloadDatabase.js
deleted file mode 100644
index ee152922..00000000
--- 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/routes/api.js b/src/libs/routes/api.js
index 03a2ca32..6a20b8b6 100644
--- a/src/libs/routes/api.js
+++ b/src/libs/routes/api.js
@@ -72,8 +72,6 @@ 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`);
@@ -138,7 +136,6 @@ 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);
diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js
index dacf6bde..af1f410b 100644
--- a/src/libs/routes/auxiliar.js
+++ b/src/libs/routes/auxiliar.js
@@ -40,8 +40,6 @@ const config = require(`${libs}/config`);
 
 const passport = require('passport');
 
-const download = require(`${libs}/middlewares/downloadDatabase`);
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]}  }).middleware;
@@ -364,6 +362,4 @@ auxiliarApp.get('/count', rqf.parse(), (req, res, next) => {
   next();
 }, rqf.build(), query, addMissing(rqf), id2str.transform(), response('auxiliar'));
 
-auxiliarApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('docente', 'mapping_docente'));
-
 module.exports = auxiliarApp;
diff --git a/src/libs/routes/class.js b/src/libs/routes/class.js
index 9819a23b..0cab76de 100644
--- a/src/libs/routes/class.js
+++ b/src/libs/routes/class.js
@@ -38,8 +38,6 @@ 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');
@@ -389,6 +387,4 @@ classApp.get('/', rqfCount.parse(), rqfCount.build(), (req, res, next) => {
    next();
 }, query, addMissing(rqfCount), id2str.transform(), response('class'));
 
-classApp.get('/download', passport.authenticate('bearer', { session: false }), rqfCount.parse(), rqfCount.build(), download('turma', 'mapping_turma'));
-
 module.exports = classApp;
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index 1cd1bea1..8da08784 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -38,8 +38,6 @@ 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');
diff --git a/src/libs/routes/cub.js b/src/libs/routes/cub.js
index b6bb034c..330ed64a 100644
--- a/src/libs/routes/cub.js
+++ b/src/libs/routes/cub.js
@@ -42,8 +42,6 @@ const config = require(`${libs}/config`);
 
 const passport = require('passport');
 
-const download = require(`${libs}/middlewares/downloadDatabase`);
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js
index 3588a547..2541c58c 100644
--- a/src/libs/routes/dailyChargeAmount.js
+++ b/src/libs/routes/dailyChargeAmount.js
@@ -42,8 +42,6 @@ const config = require(`${libs}/config`);
 
 const passport = require('passport');
 
-const download = require(`${libs}/middlewares/downloadDatabase`);
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
diff --git a/src/libs/routes/downloads.js b/src/libs/routes/downloads.js
deleted file mode 100644
index 9f01479d..00000000
--- 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/enrollment.js b/src/libs/routes/enrollment.js
index 65110003..ff9fa1d4 100644
--- a/src/libs/routes/enrollment.js
+++ b/src/libs/routes/enrollment.js
@@ -40,8 +40,6 @@ 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;
@@ -570,8 +568,6 @@ enrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     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;
diff --git a/src/libs/routes/glossEnrollmentRatio.js b/src/libs/routes/glossEnrollmentRatio.js
index 7183715a..ae53749c 100644
--- a/src/libs/routes/glossEnrollmentRatio.js
+++ b/src/libs/routes/glossEnrollmentRatio.js
@@ -42,8 +42,6 @@ const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const config = require(`${libs}/config`);
 
-const download = require(`${libs}/middlewares/downloadDatabase`);
-
 const passport = require('passport');
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
diff --git a/src/libs/routes/liquidEnrollmentRatio.js b/src/libs/routes/liquidEnrollmentRatio.js
index fd06c528..c096325d 100644
--- a/src/libs/routes/liquidEnrollmentRatio.js
+++ b/src/libs/routes/liquidEnrollmentRatio.js
@@ -42,8 +42,6 @@ const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const config = require(`${libs}/config`);
 
-const download = require(`${libs}/middlewares/downloadDatabase`);
-
 const passport = require('passport');
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
diff --git a/src/libs/routes/rateSchool.js b/src/libs/routes/rateSchool.js
index a8e9253e..0c944ea1 100644
--- a/src/libs/routes/rateSchool.js
+++ b/src/libs/routes/rateSchool.js
@@ -40,8 +40,6 @@ const id2str = require(`${libs}/middlewares/id2str`);
 
 const config = require(`${libs}/config`);
 
-const download = require(`${libs}/middlewares/downloadDatabase`);
-
 const passport = require('passport');
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
@@ -338,6 +336,4 @@ rateSchoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     next();
 }, id2str.transform(false), response('rateSchool'));
 
-rateSchoolApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('pnad', 'mapping_pnad'));
-
 module.exports = rateSchoolApp;
diff --git a/src/libs/routes/school.js b/src/libs/routes/school.js
index 13abdfa8..b6159cbe 100644
--- a/src/libs/routes/school.js
+++ b/src/libs/routes/school.js
@@ -42,8 +42,6 @@ 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;
@@ -565,6 +563,4 @@ schoolApp.get('/count', cache('15 day'), rqfCount.parse(), rqfCount.build(), (re
     next();
 }, query, addMissing(rqfCount), id2str.transform(), response('school'));
 
-schoolApp.get('/count/download', passport.authenticate('bearer', { session: false }), rqfCount.parse(), rqfCount.build(), download('escola', 'mapping_escola'));
-
 module.exports = schoolApp;
diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js
index e97d37e1..c485b52a 100644
--- a/src/libs/routes/teacher.js
+++ b/src/libs/routes/teacher.js
@@ -40,8 +40,6 @@ 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;
@@ -459,6 +457,4 @@ teacherApp.get('/', rqf.parse(), (req, res, next) => {
     next();
 }, id2str.transform(), response('teacher'));
 
-teacherApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('docente', 'mapping_docente'));
-
 module.exports = teacherApp;
-- 
GitLab


From 5a97bd3b3f9599eeb450628b4b1586e8f7e31c7c Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Thu, 14 Mar 2019 10:26:46 -0300
Subject: [PATCH 049/142] fix gulpfile node_enc conf

---
 gulpfile.babel.js | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/gulpfile.babel.js b/gulpfile.babel.js
index 11e9416f..ab298973 100644
--- a/gulpfile.babel.js
+++ b/gulpfile.babel.js
@@ -106,12 +106,18 @@ gulp.task('watch', ['compile'], () => {
 
 gulp.task('run', () => {
     process.chdir('build');
+    let node_env = 'development';
+    if(process.env.NODE_ENV === 'production')
+        node_env = 'production';
+    else if(process.env.NODE_ENV === 'homologa')
+        node_env = 'homologa';
+    
     nodemon({
         script: 'server.js',
         tasks: ['watch'],
         ignore: ["test/test.js", "gulpfile.babel.js"],
         ext: 'js html json',
-        env: { 'NODE_ENV': 'development' }
+        env: { 'NODE_ENV': node_env }
     });
 });
 
-- 
GitLab


From a10512c0709730407842156a3db5be67559074c1 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 14 Mar 2019 11:15:08 -0300
Subject: [PATCH 050/142] Fix docente id

---
 src/libs/routes/auxiliar.js | 27 ++++-----------------------
 1 file changed, 4 insertions(+), 23 deletions(-)

diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js
index dacf6bde..92681a74 100644
--- a/src/libs/routes/auxiliar.js
+++ b/src/libs/routes/auxiliar.js
@@ -1,23 +1,3 @@
-/*
-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();
@@ -59,7 +39,8 @@ auxiliarApp.get('/year_range', (req, res, next) => {
 
 auxiliarApp.get('/years', (req, res, next) => {
     req.sql.from('docente').
-    field('DISTINCT docente.ano_censo', 'year');
+    field('DISTINCT docente.ano_censo', 'year')
+    .where('docente.ano_censo <= 2017');
     next();
 }, query, response('years'));
 
@@ -342,7 +323,7 @@ rqf.addField({
 
 // LDE
 auxiliarApp.get('/', rqf.parse(), (req, res, next) => {
-  req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total')
+  req.sql.field('COUNT(DISTINCT docente.doncete_id)', 'total')
   .field("'Brasil'", 'name')
   .field('docente.ano_censo', 'year')
   .from('docente')
@@ -354,7 +335,7 @@ auxiliarApp.get('/', rqf.parse(), (req, res, next) => {
 
 // SimCAQ
 auxiliarApp.get('/count', rqf.parse(), (req, res, next) => {
-  req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total')
+  req.sql.field('COUNT(DISTINCT docente.docente_id)', 'total')
   .field("'Brasil'", 'name')
   .field('docente.ano_censo', 'year')
   .from('docente')
-- 
GitLab


From 15205d04c174f2f69a1a12cf95694efc11aa2951 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 14 Mar 2019 11:23:44 -0300
Subject: [PATCH 051/142] Fix auxilar docente_id

---
 src/libs/routes/auxiliar.js | 24 ++++++++++++++++++++++--
 1 file changed, 22 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js
index 92681a74..90dbea60 100644
--- a/src/libs/routes/auxiliar.js
+++ b/src/libs/routes/auxiliar.js
@@ -1,3 +1,23 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
 const express = require('express');
 
 const auxiliarApp = express.Router();
@@ -323,7 +343,7 @@ rqf.addField({
 
 // LDE
 auxiliarApp.get('/', rqf.parse(), (req, res, next) => {
-  req.sql.field('COUNT(DISTINCT docente.doncete_id)', 'total')
+  req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total')
   .field("'Brasil'", 'name')
   .field('docente.ano_censo', 'year')
   .from('docente')
@@ -335,7 +355,7 @@ auxiliarApp.get('/', rqf.parse(), (req, res, next) => {
 
 // SimCAQ
 auxiliarApp.get('/count', rqf.parse(), (req, res, next) => {
-  req.sql.field('COUNT(DISTINCT docente.docente_id)', 'total')
+  req.sql.field('COUNT(DISTINCT docente.id_docente)', 'total')
   .field("'Brasil'", 'name')
   .field('docente.ano_censo', 'year')
   .from('docente')
-- 
GitLab


From d4595fd5d833ff8ad77ccfe6fc700d093debb5af Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Fri, 15 Mar 2019 13:00:32 -0300
Subject: [PATCH 052/142] Add ethnic group ies

---
 src/libs/convert/ethnicGroupIES.js      | 38 +++++++++++++++++++++++++
 src/libs/middlewares/id2str.js          |  7 +++--
 src/libs/routes/universityEnrollment.js | 10 +++----
 3 files changed, 48 insertions(+), 7 deletions(-)
 create mode 100644 src/libs/convert/ethnicGroupIES.js

diff --git a/src/libs/convert/ethnicGroupIES.js b/src/libs/convert/ethnicGroupIES.js
new file mode 100644
index 00000000..a57150fc
--- /dev/null
+++ b/src/libs/convert/ethnicGroupIES.js
@@ -0,0 +1,38 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function ethnicGroupIES(id) {
+    switch (id) {
+        case 0:
+        return 'Aluno não quis declarar cor/raça';
+        case 1:
+        return 'Branca';
+        case 2:
+        return 'Preta';
+        case 3:
+        return 'Parda';
+        case 4:
+        return 'Amarela';
+        case 5:
+        return 'Indígena';
+        default:
+        return 'Não dispõe da informação (Não resposta)';
+    }
+};
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 2defe10f..693d5387 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -27,6 +27,7 @@ const admDependencyPriv = require(`${libs}/convert/admDependencyPriv`);
 const location = require(`${libs}/convert/location`);
 const ruralLocation = require(`${libs}/convert/ruralLocation`);
 const ethnicGroup = require(`${libs}/convert/ethnicGroup`);
+const ethnicGroupIES = require(`${libs}/convert/ethnicGroupIES`);
 const agreement = require(`${libs}/convert/agreement`);
 const booleanVariable = require(`${libs}/convert/booleanVariable`);
 const educationLevel = require(`${libs}/convert/educationLevel`);
@@ -119,7 +120,8 @@ const ids = {
     upper_turn_id: upperTurn,
     is_free_id: booleanVariable,
     night_time_id: booleanVariable,
-    capital_id: booleanVariable
+    capital_id: booleanVariable,
+    ethnic_group_ies_id: ethnicGroupIES,
 };
 
 function transform(removeId=false) {
@@ -199,5 +201,6 @@ module.exports = {
     academicLevel,
     upperEducationMod,
     studentDeficiency,
-    schoolType
+    schoolType,
+    ethnicGroupIES
 };
diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index 2519ccae..3e3a5981 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -150,16 +150,16 @@ universityEnrollmentApp.get('/student_deficiency', (req, res, next) => {
     next();
 }, response('student_deficiency'));
 
-universityEnrollmentApp.get('/ethnic_group', (req, res, next) => {
+universityEnrollmentApp.get('/ethnic_group_ies', (req, res, next) => {
     req.result = [];
     for(let i = 1; i <=5; ++i) {
         req.result.push({
             id: i,
-            name: id2str.ethnicGroup(i)
+            name: id2str.ethnicGroupIES(i)
         });
     }
     next();
-}, response('ethnic_group'));
+}, response('ethnic_group_ies'));
 
 universityEnrollmentApp.get('/school_type', (req, res, next) => {
     req.result = [];
@@ -332,10 +332,10 @@ rqf.addField({
         field: 'cod_turno_aluno'
     }
 }).addValue({
-    name:'ethnic_group',
+    name:'ethnic_group_ies',
     table: 'aluno_ens_superior',
     tableField: 'cod_cor_raca_aluno',
-    resultField: 'ethnic_group_id',
+    resultField: 'ethnic_group_ies_id',
     where: {
         relation: '=',
         type: 'integer',
-- 
GitLab


From 9373a345f10991d552e35142f2c08cfd51ee81c7 Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Mon, 18 Mar 2019 09:03:57 -0300
Subject: [PATCH 053/142] remove all passport from routes

---
 gulpfile.babel.js                        |   3 +-
 src/libs/app.js                          |   6 -
 src/libs/middlewares/oauth2.js           | 141 ----------
 src/libs/middlewares/passport.js         |  87 ------
 src/libs/models/accessToken.js           |  49 ----
 src/libs/models/client.js                |  37 ---
 src/libs/models/download.js              |  73 -----
 src/libs/models/refreshToken.js          |  50 ----
 src/libs/models/resetToken.js            |  66 -----
 src/libs/models/user.js                  | 139 ----------
 src/libs/models/verificationToken.js     |  61 -----
 src/libs/routes/api.js                   |  12 -
 src/libs/routes/auxiliar.js              |   2 -
 src/libs/routes/class.js                 |   2 -
 src/libs/routes/courseCount.js           |   2 -
 src/libs/routes/cub.js                   |   2 -
 src/libs/routes/dailyChargeAmount.js     |   2 -
 src/libs/routes/employees.js             |   2 -
 src/libs/routes/enrollment.js            |   2 -
 src/libs/routes/glossEnrollmentRatio.js  |   2 -
 src/libs/routes/liquidEnrollmentRatio.js |   2 -
 src/libs/routes/rateSchool.js            |   2 -
 src/libs/routes/resetToken.js            | 101 -------
 src/libs/routes/school.js                |   2 -
 src/libs/routes/teacher.js               |   2 -
 src/libs/routes/university.js            |   2 -
 src/libs/routes/user.js                  | 328 -----------------------
 src/libs/routes/verifyToken.js           |  72 -----
 28 files changed, 2 insertions(+), 1249 deletions(-)
 delete mode 100644 src/libs/middlewares/oauth2.js
 delete mode 100644 src/libs/middlewares/passport.js
 delete mode 100644 src/libs/models/accessToken.js
 delete mode 100644 src/libs/models/client.js
 delete mode 100644 src/libs/models/download.js
 delete mode 100644 src/libs/models/refreshToken.js
 delete mode 100644 src/libs/models/resetToken.js
 delete mode 100644 src/libs/models/user.js
 delete mode 100644 src/libs/models/verificationToken.js
 delete mode 100644 src/libs/routes/resetToken.js
 delete mode 100644 src/libs/routes/user.js
 delete mode 100644 src/libs/routes/verifyToken.js

diff --git a/gulpfile.babel.js b/gulpfile.babel.js
index ab298973..26197329 100644
--- a/gulpfile.babel.js
+++ b/gulpfile.babel.js
@@ -111,7 +111,8 @@ gulp.task('run', () => {
         node_env = 'production';
     else if(process.env.NODE_ENV === 'homologa')
         node_env = 'homologa';
-    
+
+    console.log(node_env);    
     nodemon({
         script: 'server.js',
         tasks: ['watch'],
diff --git a/src/libs/app.js b/src/libs/app.js
index 5a109798..746fe6b9 100644
--- a/src/libs/app.js
+++ b/src/libs/app.js
@@ -36,14 +36,10 @@ const app = express();
 
 const api = require('./routes/api');
 
-const passport = require('passport');
-
 const mongoose = require(`${libs}/db/mongoose`);
 
 const db = mongoose();
 
-require(`${libs}/middlewares/passport`);
-
 app.use(bodyParser.json({limit: '50mb'}));
 app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
 app.use(cookieParser());
@@ -78,8 +74,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/middlewares/oauth2.js b/src/libs/middlewares/oauth2.js
deleted file mode 100644
index e7f7b446..00000000
--- 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 ea4fd95c..00000000
--- 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 b9c2a60a..00000000
--- 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 2ddae280..00000000
--- 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 21fdf683..00000000
--- 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/refreshToken.js b/src/libs/models/refreshToken.js
deleted file mode 100644
index 3a37ae96..00000000
--- 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 d983436b..00000000
--- 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/user.js b/src/libs/models/user.js
deleted file mode 100644
index 7dc642e3..00000000
--- 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 1047e4d0..00000000
--- 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 6a20b8b6..c1bece0b 100644
--- a/src/libs/routes/api.js
+++ b/src/libs/routes/api.js
@@ -40,8 +40,6 @@ const school = require('./school');
 
 const simulation = require('./simulation');
 
-const user = require('./user');
-
 const classroom = require('./classroom');
 
 const teacher = require('./teacher');
@@ -64,12 +62,6 @@ 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 infrastructure = require(`${libs}/routes/infrastructure`);
@@ -113,7 +105,6 @@ api.get('/', (req, res) => {
 });
 
 // mount API routes
-api.use('/user', user);
 api.use('/simulation', simulation);
 api.use('/class', classes);
 api.use('/enrollment', enrollment);
@@ -132,9 +123,6 @@ 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('/infrastructure', infrastructure);
 api.use('/school_infrastructure', schoolInfrastructure);
diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js
index e4e35945..c1b8d4e4 100644
--- a/src/libs/routes/auxiliar.js
+++ b/src/libs/routes/auxiliar.js
@@ -38,8 +38,6 @@ const id2str = require(`${libs}/middlewares/id2str`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]}  }).middleware;
diff --git a/src/libs/routes/class.js b/src/libs/routes/class.js
index 0cab76de..6967ddf8 100644
--- a/src/libs/routes/class.js
+++ b/src/libs/routes/class.js
@@ -40,8 +40,6 @@ const config = require(`${libs}/config`);
 
 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();
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index 8da08784..488761fb 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -40,8 +40,6 @@ const config = require(`${libs}/config`);
 
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
-const passport = require('passport');
-
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
 
 let rqf = new ReqQueryFields();
diff --git a/src/libs/routes/cub.js b/src/libs/routes/cub.js
index 330ed64a..94412259 100644
--- a/src/libs/routes/cub.js
+++ b/src/libs/routes/cub.js
@@ -40,8 +40,6 @@ const request = require(`request`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js
index 2541c58c..9efd71a8 100644
--- a/src/libs/routes/dailyChargeAmount.js
+++ b/src/libs/routes/dailyChargeAmount.js
@@ -40,8 +40,6 @@ const request = require(`request`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
diff --git a/src/libs/routes/employees.js b/src/libs/routes/employees.js
index 9aedbcb1..40a968e9 100644
--- a/src/libs/routes/employees.js
+++ b/src/libs/routes/employees.js
@@ -38,8 +38,6 @@ const id2str = require(`${libs}/middlewares/id2str`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]}  }).middleware;
diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js
index ff9fa1d4..d40fb5ec 100644
--- a/src/libs/routes/enrollment.js
+++ b/src/libs/routes/enrollment.js
@@ -38,8 +38,6 @@ const id2str = require(`${libs}/middlewares/id2str`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
diff --git a/src/libs/routes/glossEnrollmentRatio.js b/src/libs/routes/glossEnrollmentRatio.js
index ae53749c..31d8903d 100644
--- a/src/libs/routes/glossEnrollmentRatio.js
+++ b/src/libs/routes/glossEnrollmentRatio.js
@@ -42,8 +42,6 @@ const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
 
 let rqf = new ReqQueryFields();
diff --git a/src/libs/routes/liquidEnrollmentRatio.js b/src/libs/routes/liquidEnrollmentRatio.js
index c096325d..eb8c634a 100644
--- a/src/libs/routes/liquidEnrollmentRatio.js
+++ b/src/libs/routes/liquidEnrollmentRatio.js
@@ -42,8 +42,6 @@ const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
 
 let rqf = new ReqQueryFields();
diff --git a/src/libs/routes/rateSchool.js b/src/libs/routes/rateSchool.js
index 0c944ea1..e5592dc5 100644
--- a/src/libs/routes/rateSchool.js
+++ b/src/libs/routes/rateSchool.js
@@ -40,8 +40,6 @@ const id2str = require(`${libs}/middlewares/id2str`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
 
 rateSchoolApp.use(cache('15 day'));
diff --git a/src/libs/routes/resetToken.js b/src/libs/routes/resetToken.js
deleted file mode 100644
index 5fa96b01..00000000
--- 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
index b6159cbe..ad5a4d07 100644
--- a/src/libs/routes/school.js
+++ b/src/libs/routes/school.js
@@ -40,8 +40,6 @@ const request = require(`request`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js
index c485b52a..f503963e 100644
--- a/src/libs/routes/teacher.js
+++ b/src/libs/routes/teacher.js
@@ -38,8 +38,6 @@ const id2str = require(`${libs}/middlewares/id2str`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const addMissing = require(`${libs}/middlewares/addMissing`);
 
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]}  }).middleware;
diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index fbe7d8f8..d762d6a5 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -40,8 +40,6 @@ const request = require(`request`);
 
 const config = require(`${libs}/config`);
 
-const passport = require('passport');
-
 const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
 
 const addMissing = require(`${libs}/middlewares/addMissing`);
diff --git a/src/libs/routes/user.js b/src/libs/routes/user.js
deleted file mode 100644
index f32f41ab..00000000
--- 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 a2a278c5..00000000
--- 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;
-- 
GitLab


From e5ab8683bd80e0a0b8a3c9ea2f46755edb57043b Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Tue, 19 Mar 2019 11:30:33 -0300
Subject: [PATCH 054/142] fix simulation route

---
 src/libs/middlewares/auth.js  | 62 +++++++++++++++++++++++++++++++++++
 src/libs/routes/simulation.js | 14 ++++----
 2 files changed, 70 insertions(+), 6 deletions(-)
 create mode 100644 src/libs/middlewares/auth.js

diff --git a/src/libs/middlewares/auth.js b/src/libs/middlewares/auth.js
new file mode 100644
index 00000000..2a9cb5b0
--- /dev/null
+++ b/src/libs/middlewares/auth.js
@@ -0,0 +1,62 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+const libs = `${process.cwd()}/libs`;
+
+const log = require(`${libs}/log`)(module);
+
+const request = require(`request`);
+
+const config = require(`${libs}/config`);
+
+const LDE_API_URL = config.lde_api.url;
+
+function auth(origin) {
+    return (req, res, next) => {
+        const options = {
+            url: `${LDE_API_URL}/verifyDownload`,
+            headers: {
+                'Authorization': req.header('Authorization'),
+                'origin': origin
+            }
+        }; 
+        request.get(options, (err, response, body) => {
+            console.log("--------------->> "+body);
+            if(err)
+                console.log("ERRO!");
+            let resp;
+            try {
+                resp = JSON.parse(body);
+            } catch(e) {
+                return res.json({access: 'Unauthorized'});
+            }
+            if(resp.access === 'Authorized') {
+                req.name = resp.name;
+                req.email = resp.email; 
+                req.userId = resp.userId;
+                console.log("==========>"+req.userId);
+                return next();
+            }
+            res.json({access: 'Unauthorized'});
+        });
+    }
+}
+
+module.exports = auth;
diff --git a/src/libs/routes/simulation.js b/src/libs/routes/simulation.js
index 8003b54d..e64c1ba3 100644
--- a/src/libs/routes/simulation.js
+++ b/src/libs/routes/simulation.js
@@ -38,6 +38,8 @@ const PQR = require(`${libs}/models/pqr`);
 
 const passport = require('passport');
 
+const auth = require(`${libs}/middlewares/auth`);
+
 simulationApp.get('/time', (req, res, next) => {
     const maxTime = parseInt(req.query.max_time, 10);
     if(isNaN(maxTime)) {
@@ -63,7 +65,7 @@ simulationApp.get('/pqr', (req, res) => {
     });
 });
 
-simulationApp.put('/pqr', passport.authenticate('bearer', { session: false }), (req, res, next) => {
+simulationApp.put('/pqr', auth("SimCAQ"), (req, res, next) => {
     let user = req.user.toObject();
 
     PQR.findOne((err, pqr) => {
@@ -88,7 +90,7 @@ simulationApp.put('/pqr', passport.authenticate('bearer', { session: false }), (
     });
 });
 
-simulationApp.get('/', passport.authenticate('bearer', { session: false }), (req, res) => {
+simulationApp.get('/', auth("SimCAQ"), (req, res) => {
     let user = req.user.toObject();
     let query = Simulation.find({userId: user._id}).select('userId name createdAt updatedAt');
     query.exec((err, simulations) => {
@@ -110,7 +112,7 @@ simulationApp.get('/', passport.authenticate('bearer', { session: false }), (req
     // });
 });
 
-simulationApp.post('/', passport.authenticate('bearer', { session: false }), (req, res, next) => {
+simulationApp.post('/', auth("SimCAQ"), (req, res, next) => {
     let user = req.user.toObject();
 
     let simulation = new Simulation({
@@ -129,7 +131,7 @@ simulationApp.post('/', passport.authenticate('bearer', { session: false }), (re
     })
 });
 
-simulationApp.get('/:id', passport.authenticate('bearer', { session: false }), (req, res) => {
+simulationApp.get('/:id', auth("SimCAQ"), (req, res) => {
     let user = req.user.toObject();
 
     Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => {
@@ -142,7 +144,7 @@ simulationApp.get('/:id', passport.authenticate('bearer', { session: false }), (
     });
 });
 
-simulationApp.put('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => {
+simulationApp.put('/:id', auth("SimCAQ"), (req, res, next) => {
     let user = req.user.toObject();
 
     Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => {
@@ -171,7 +173,7 @@ simulationApp.put('/:id', passport.authenticate('bearer', { session: false }), (
     });
 });
 
-simulationApp.delete('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => {
+simulationApp.delete('/:id', auth("SimCAQ"), (req, res, next) => {
     let user = req.user.toObject();
 
     Simulation.remove({_id: req.params.id, userId: user._id}, (err, simulation) => {
-- 
GitLab


From 924172051bccd94034b09e2ae4151d30ab984c16 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fce15@inf.ufpr.br>
Date: Thu, 21 Mar 2019 09:41:55 -0300
Subject: [PATCH 055/142] Fix join in classCount

---
 src/libs/routes/classCount.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/libs/routes/classCount.js b/src/libs/routes/classCount.js
index c7fa1d03..3496c193 100644
--- a/src/libs/routes/classCount.js
+++ b/src/libs/routes/classCount.js
@@ -357,7 +357,7 @@ classCountApp.get('/count', rqf.parse(), (req, res, next) => {
 }, rqf.build(), query, addMissing(rqf), id2str.transform(), response('class_count'));
 
 // LDE
-classCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
+classCountApp.get('/', rqf.parse(), (req, res, next) => {
   // Faz a consulta do número de alunos pelas dimensões
   if(("education_level_mod" in req.dims) || ("education_level_mod" in req.filter) || ("education_level_short" in req.dims)) {
     req.sql.field("'Brasil'", 'name')
-- 
GitLab


From 93a939b2280a9a2e190cdab169a2b005403ce191 Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Fri, 22 Mar 2019 09:35:17 -0300
Subject: [PATCH 056/142] remove config.json.example

---
 .gitignore                         | 1 -
 config.json.example => config.json | 9 +++++++++
 2 files changed, 9 insertions(+), 1 deletion(-)
 rename config.json.example => config.json (94%)

diff --git a/.gitignore b/.gitignore
index 99a279fb..57b7432f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,7 +19,6 @@ build/*
 
 .gulp-cache
 
-config.json
 docs/
 .vscode/
 
diff --git a/config.json.example b/config.json
similarity index 94%
rename from config.json.example
rename to config.json
index 1be79df9..653ed6d3 100644
--- a/config.json.example
+++ b/config.json
@@ -33,6 +33,9 @@
                 "url": "http://simcaqdev.c3sl.ufpr.br/#"
             }
         },
+        "lde_api": {
+            "url": "https://dadoseducacionaisdev.c3sl.ufpr.br/api/v1/"
+        },
         "email": {
             "port": 25,
             "host": "mx.c3sl.ufpr.br",
@@ -131,6 +134,9 @@
             "ignoreTLS": true,
             "from": "\"Laboratório de Dados Educacionais\" <lde@c3sl.ufpr.br>"
         },
+        "lde_api": {
+            "url": "https://dadoseducacionaishom.c3sl.ufpr.br/api/v1/"
+        },
         "security": {
             "tokenLife": 3600
         }
@@ -177,6 +183,9 @@
             "ignoreTLS": true,
             "from": "\"Laboratório de Dados Educacionais\" <lde@c3sl.ufpr.br>"
         },
+        "lde_api": {
+            "url": "https://dadoseducacionais.c3sl.ufpr.br/api/v1/"
+        },
         "security": {
             "tokenLife": 3600
         }
-- 
GitLab


From 18d8bfeaa40001d4d9348a6cd7a0b7b5d077d887 Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Fri, 22 Mar 2019 11:54:26 -0300
Subject: [PATCH 057/142] fix auth user info in json

---
 src/libs/routes/simulation.js | 20 +++++++-------------
 1 file changed, 7 insertions(+), 13 deletions(-)

diff --git a/src/libs/routes/simulation.js b/src/libs/routes/simulation.js
index e64c1ba3..785b33cf 100644
--- a/src/libs/routes/simulation.js
+++ b/src/libs/routes/simulation.js
@@ -66,7 +66,6 @@ simulationApp.get('/pqr', (req, res) => {
 });
 
 simulationApp.put('/pqr', auth("SimCAQ"), (req, res, next) => {
-    let user = req.user.toObject();
 
     PQR.findOne((err, pqr) => {
         if(err) {
@@ -74,8 +73,8 @@ simulationApp.put('/pqr', auth("SimCAQ"), (req, res, next) => {
             return next({err});
         }
 
-        if(!user.admin) {
-            log.info(`Usuário ${user.email} tentou alterar o PQR, mas não tem privilégio`);
+        if(!req.adminSimcaqNode) {
+            log.info(`Usuário ${req.email} tentou alterar o PQR, mas não tem privilégio`);
             res.statusCode = 401;
             return next({err: { msg: 'Unauthorized'}});
         }
@@ -91,8 +90,7 @@ simulationApp.put('/pqr', auth("SimCAQ"), (req, res, next) => {
 });
 
 simulationApp.get('/', auth("SimCAQ"), (req, res) => {
-    let user = req.user.toObject();
-    let query = Simulation.find({userId: user._id}).select('userId name createdAt updatedAt');
+    let query = Simulation.find({userId: req.userId}).select('userId name createdAt updatedAt');
     query.exec((err, simulations) => {
         if(err) {
             log.error(err);
@@ -113,10 +111,9 @@ simulationApp.get('/', auth("SimCAQ"), (req, res) => {
 });
 
 simulationApp.post('/', auth("SimCAQ"), (req, res, next) => {
-    let user = req.user.toObject();
 
     let simulation = new Simulation({
-        userId: user._id,
+        userId: req.userId,
         content: req.body.content,
         name: req.body.name
     });
@@ -132,9 +129,8 @@ simulationApp.post('/', auth("SimCAQ"), (req, res, next) => {
 });
 
 simulationApp.get('/:id', auth("SimCAQ"), (req, res) => {
-    let user = req.user.toObject();
 
-    Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => {
+    Simulation.findOne({_id: req.params.id, userId: req.userId}, (err, simulation) => {
         if(err) {
             log.error(err);
             return next({err});
@@ -145,9 +141,8 @@ simulationApp.get('/:id', auth("SimCAQ"), (req, res) => {
 });
 
 simulationApp.put('/:id', auth("SimCAQ"), (req, res, next) => {
-    let user = req.user.toObject();
 
-    Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => {
+    Simulation.findOne({_id: req.params.id, userId: req.userId}, (err, simulation) => {
         if(err) {
             log.error(err);
             return next({err});
@@ -174,9 +169,8 @@ simulationApp.put('/:id', auth("SimCAQ"), (req, res, next) => {
 });
 
 simulationApp.delete('/:id', auth("SimCAQ"), (req, res, next) => {
-    let user = req.user.toObject();
 
-    Simulation.remove({_id: req.params.id, userId: user._id}, (err, simulation) => {
+    Simulation.remove({_id: req.params.id, userId: req.userId}, (err, simulation) => {
         if(err) {
             log.error(err);
             return next({err});
-- 
GitLab


From f87ba8a94831ba3a0262b24cc8f22091a1841539 Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Mon, 25 Mar 2019 10:51:22 -0300
Subject: [PATCH 058/142] fix refs to users

---
 src/libs/models/pqr.js        | 1 -
 src/libs/models/simulation.js | 4 +---
 2 files changed, 1 insertion(+), 4 deletions(-)

diff --git a/src/libs/models/pqr.js b/src/libs/models/pqr.js
index d8c71c6d..46fa3c7d 100644
--- a/src/libs/models/pqr.js
+++ b/src/libs/models/pqr.js
@@ -22,7 +22,6 @@ const mongoose = require('mongoose')
 
 const libs = `${process.cwd()}/libs`;
 const log = require(`${libs}/log`)(module);
-const User = require(`${libs}/models/user`);
 
 const Schema = mongoose.Schema;
 
diff --git a/src/libs/models/simulation.js b/src/libs/models/simulation.js
index a4a6cc3c..e5aa6a1f 100644
--- a/src/libs/models/simulation.js
+++ b/src/libs/models/simulation.js
@@ -22,15 +22,13 @@ const mongoose = require('mongoose')
 
 const libs = `${process.cwd()}/libs`;
 const log = require(`${libs}/log`)(module);
-const User = require(`${libs}/models/user`);
 
 const Schema = mongoose.Schema;
 
 let SimulationSchema = new Schema({
     userId: {
-        type: Schema.Types.ObjectId,
+        type: Number,
         required: true,
-        ref: 'User'
     },
     content: {
         type: String,
-- 
GitLab


From 05e807bd08767ec42f8f23c480be9e64c2677c94 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Tue, 26 Mar 2019 10:14:15 -0300
Subject: [PATCH 059/142] Add university dim/filter

---
 src/libs/routes/courseCount.js          |  4 ++--
 src/libs/routes/university.js           |  3 ++-
 src/libs/routes/universityEnrollment.js | 10 ++++++++++
 3 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index 488761fb..125ef449 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -234,10 +234,10 @@ rqf.addField({
         field: 'cod_municipio_curso'
     }
 }).addValue({
-    name: 'ies',
+    name: 'university',
     table: 'curso_ens_superior',
     tableField: ['cod_ies', 'nome_ies'],
-    resultField: ['ies_id', 'ies_name'],
+    resultField: ['university_id', 'university_name'],
     where: {
         relation: '=',
         type: 'integer',
diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index d762d6a5..ce214d94 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -93,6 +93,7 @@ rqf.addField({
     name: 'id',
     table: 'ies_ens_superior',
     tableField: 'cod_ies',
+    resultField: 'id',
     where: {
         relation: '=',
         type: 'integer',
@@ -285,7 +286,7 @@ rqfCount.addField({
 
 universityApp.get('/', rqf.parse(),  rqf.build(), (req, res, next) => {
     req.sql.from('ies_ens_superior')
-        .field('ies_ens_superior.cod_ies')
+        .field('ies_ens_superior.cod_ies', 'id')
         .field('ies_ens_superior.ano_censo', 'year')
         .field('ies_ens_superior.nome_ies', 'name')
         .field('ies_ens_superior.cod_uf_ies', 'state_id')
diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index 3e3a5981..9d92c27f 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -249,6 +249,16 @@ rqf.addField({
         foreign: 'regiao_id',
         foreignTable: 'aluno_ens_superior'
     }
+}).addValue({
+    name: 'university',
+    table: 'aluno_ens_superior',
+    tableField: ['cod_ies', 'nome_ies'],
+    resultField: ['university_id', 'university_name'],
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ies'
+    }
 }).addValue({
     name: 'upper_adm_dependency',
     table: 'aluno_ens_superior',
-- 
GitLab


From 563dc1ef70b60a19a35162e1e8418c65e3b20aad Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Tue, 26 Mar 2019 10:33:28 -0300
Subject: [PATCH 060/142] use mongo in simcaqdb3

---
 config.json | 30 ++++++++++--------------------
 1 file changed, 10 insertions(+), 20 deletions(-)

diff --git a/config.json b/config.json
index 653ed6d3..96246226 100644
--- a/config.json
+++ b/config.json
@@ -16,11 +16,9 @@
             "url": "http://simcaqdb3.c3sl.ufpr.br:3000",
             "download": "https://simcaqdev.c3sl.ufpr.br/download/"
         },
-        "mongodb" : {
-            "uri": "mongodb://localhost/dev_users"
-        },
-        "monq": {
-            "uri": "mongodb://localhost/dev_monq"
+        "mongodb": {
+            "uri": "mongodb://simcaqdb3/dev_monq",
+            "secret": "SimCAQC3SL"
         },
         "default": {
             "api": {
@@ -64,13 +62,10 @@
             "url": "http://simcaqdb3.c3sl.ufpr.br:3000",
             "download": "https://simcaqdev.c3sl.ufpr.br/download/"
         },
-        "mongodb" : {
-            "uri": "mongodb://localhost/test_users",
+        "mongodb": {
+            "uri": "mongodb://simcaqdb3/test_monq",
             "secret": "SimCAQC3SL"
         },
-        "monq": {
-            "uri": "mongodb://localhost/test_monq"
-        },
         "default": {
             "api": {
                 "version" : "v1"
@@ -110,11 +105,9 @@
             "url": "http://simcaqdb3.c3sl.ufpr.br:3000",
             "download": "https://simcaqdev.c3sl.ufpr.br/download/"
         },
-        "mongodb" : {
-            "uri": "mongodb://localhost/dev_users"
-        },
-        "monq": {
-            "uri": "mongodb://localhost/dev_monq"
+        "mongodb": {
+            "uri": "mongodb://simcaqdb3/monq",
+            "secret": "SimCAQC3SL"
         },
         "default": {
             "api": {
@@ -158,13 +151,10 @@
             "url": "http://simcaqdb3.c3sl.ufpr.br:7000",
             "download": "https://simcaq.c3sl.ufpr.br/download/"
         },
-        "mongodb" : {
-            "uri": "mongodb://localhost/users",
+        "mongodb": {
+            "uri": "mongodb://simcaqdb3/monq",
             "secret": "SimCAQC3SL"
         },
-        "monq": {
-            "uri": "mongodb://localhost/monq"
-        },
         "default": {
             "api": {
                 "version" : "v1"
-- 
GitLab


From e5fbb7215a99614c22cafbf478470783ef8f8125 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fernandoerd2012@gmail.com>
Date: Tue, 26 Mar 2019 11:13:46 -0300
Subject: [PATCH 061/142] Fix UpperTurn Error

---
 src/libs/middlewares/id2str.js | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 693d5387..206e7d18 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -202,5 +202,6 @@ module.exports = {
     upperEducationMod,
     studentDeficiency,
     schoolType,
-    ethnicGroupIES
+    ethnicGroupIES,
+    upperTurn
 };
-- 
GitLab


From 6cafe4b4281427b5b1a5f79d61796f4773e27760 Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Thu, 28 Mar 2019 10:53:34 -0300
Subject: [PATCH 062/142] fix monetdb nrConnections in simcaqdev

---
 config.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/config.json b/config.json
index 96246226..d4429c5a 100644
--- a/config.json
+++ b/config.json
@@ -10,7 +10,7 @@
             "dbname": "simcaq_dev4",
             "user": "monetdb",
             "password":"monetdb",
-            "nrConnections": "4"
+            "nrConnections": "1"
         },
         "cdn" : {
             "url": "http://simcaqdb3.c3sl.ufpr.br:3000",
-- 
GitLab


From c42bfa89cc93e2dfb6b8459ba90e786205a7173d Mon Sep 17 00:00:00 2001
From: Fernando Erd <fernandoerd2012@gmail.com>
Date: Thu, 28 Mar 2019 11:43:15 -0300
Subject: [PATCH 063/142] Teacher University Indicator

---
 src/libs/convert/ethnicGroupTeacherIES.js |  38 ++
 src/libs/convert/genderIES.js             |  28 ++
 src/libs/convert/teacherSchooling.js      |  34 ++
 src/libs/convert/teacherSituation.js      |  36 ++
 src/libs/convert/workRegime.js            |  32 ++
 src/libs/middlewares/id2str.js            |  38 +-
 src/libs/routes/universityTeacher.js      | 477 ++++++++++++++++++++++
 7 files changed, 682 insertions(+), 1 deletion(-)
 create mode 100644 src/libs/convert/ethnicGroupTeacherIES.js
 create mode 100644 src/libs/convert/genderIES.js
 create mode 100644 src/libs/convert/teacherSchooling.js
 create mode 100644 src/libs/convert/teacherSituation.js
 create mode 100644 src/libs/convert/workRegime.js
 create mode 100644 src/libs/routes/universityTeacher.js

diff --git a/src/libs/convert/ethnicGroupTeacherIES.js b/src/libs/convert/ethnicGroupTeacherIES.js
new file mode 100644
index 00000000..7498315e
--- /dev/null
+++ b/src/libs/convert/ethnicGroupTeacherIES.js
@@ -0,0 +1,38 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function ethnicGroupTeacherIES(id) {
+    switch (id) {
+        case 0:
+        return 'docente não quis declarar cor/raça';
+        case 1:
+        return 'Branca';
+        case 2:
+        return 'Preta';
+        case 3:
+        return 'Parda';
+        case 4:
+        return 'Amarela';
+        case 5:
+        return 'Indígena';
+        default:
+        return 'Não dispõe da informação (Não resposta)';
+    }
+};
diff --git a/src/libs/convert/genderIES.js b/src/libs/convert/genderIES.js
new file mode 100644
index 00000000..4ff855cd
--- /dev/null
+++ b/src/libs/convert/genderIES.js
@@ -0,0 +1,28 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function genderIES(id) {
+    switch(id) {
+        case 1:
+        return 'Feminino';
+        case 2:
+        return 'Masculino';
+    }
+};
diff --git a/src/libs/convert/teacherSchooling.js b/src/libs/convert/teacherSchooling.js
new file mode 100644
index 00000000..fc3f1539
--- /dev/null
+++ b/src/libs/convert/teacherSchooling.js
@@ -0,0 +1,34 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function teacherSchooling(id) {
+    switch (id) {
+        case 1:
+        return 'Sem graduação';
+        case 2:
+        return 'graduação';
+        case 3:
+        return 'Especialização';
+        case 4:
+        return 'Mestrado';
+        case 5:
+        return 'Doutorado';
+    }
+};
diff --git a/src/libs/convert/teacherSituation.js b/src/libs/convert/teacherSituation.js
new file mode 100644
index 00000000..ae77189b
--- /dev/null
+++ b/src/libs/convert/teacherSituation.js
@@ -0,0 +1,36 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function teacherSituation(id) {
+    switch (id) {
+        case 1:
+        return 'Em exercício';
+        case 2:
+        return 'Afastado para qualificação';
+        case 3:
+        return 'Afastado para exercício em outros órgãos/entidades';
+        case 4:
+        return 'Afastado por outros motivos';
+        case 5:
+        return 'Afastado para tratamento de saúde';
+        case 6:
+        return 'Falecido';
+    }
+};
diff --git a/src/libs/convert/workRegime.js b/src/libs/convert/workRegime.js
new file mode 100644
index 00000000..6cff902a
--- /dev/null
+++ b/src/libs/convert/workRegime.js
@@ -0,0 +1,32 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function workRegime(id) {
+    switch (id) {
+        case 1:
+        return 'Tempo Integral com dedicação exclusiva';
+        case 2:
+        return 'Tempo Integral sem dedicação exclusiva';
+        case 3:
+        return 'Tempo Parcial';
+        case 4:
+        return 'Horista';
+    }
+};
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 206e7d18..6a3504e7 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -64,6 +64,18 @@ const upperEducationMod = require(`${libs}/convert/upperEducationMod`);
 const studentDeficiency = require(`${libs}/convert/studentDeficiency`);
 const schoolType = require(`${libs}/convert/schoolType`);
 const upperTurn = require(`${libs}/convert/upperTurn`);
+const teacherSituation = require(`${libs}/convert/teacherSituation`);
+const workRegime = require(`${libs}/convert/workRegime`);
+const substitute = require(`${libs}/convert/booleanVariable`);
+const visitor = require(`${libs}/convert/booleanVariable`);
+const eadTeacher = require(`${libs}/convert/booleanVariable`);
+const graduationPresential = require(`${libs}/convert/booleanVariable`);
+const postgraduateEadTeacher = require(`${libs}/convert/booleanVariable`);
+const postgraduatePresentialTeacher = require(`${libs}/convert/booleanVariable`);
+const teacherSchooling = require(`${libs}/convert/teacherSchooling`);
+const ethnicGroupTeacherIES = require(`${libs}/convert/ethnicGroupTeacherIES`);
+const genderIES = require(`${libs}/convert/genderIES`);
+const deficiency = require(`${libs}/convert/booleanVariable`);
 
 const ids = {
     gender_id: gender,
@@ -122,6 +134,18 @@ const ids = {
     night_time_id: booleanVariable,
     capital_id: booleanVariable,
     ethnic_group_ies_id: ethnicGroupIES,
+    teacher_situation_id: teacherSituation,
+    work_regime_id: work_regime,
+    substitute_id: booleanVariable,
+    visitor_id: booleanVariable,
+    ead_teacher_id: eadTeacher,
+    graduation_presential_id: graduationPresential,
+    postgraduate_ead_teacher_id: postgraduateEadTeacher,
+    postgraduate_presential_teacher_id: postgraduatePresentialTeacher,
+    teacher_schooling_id: teacherSchooling,
+    ethnic_group_teacher_ies_id: ethnicGroupTeacherIES,
+    gender_ies_id: genderIES,
+    deficiency_id: deficiency
 };
 
 function transform(removeId=false) {
@@ -203,5 +227,17 @@ module.exports = {
     studentDeficiency,
     schoolType,
     ethnicGroupIES,
-    upperTurn
+    upperTurn,
+    teacherSituation,
+    work_regime,
+    substitute,
+    visitor,
+    eadTeacher,
+    graduationPresential,
+    postgraduateEadTeacher,
+    postgraduatePresentialTeacher,
+    teacherSchooling,
+    ethnicGroupTeacherIES,
+    genderIES,
+    deficiency
 };
diff --git a/src/libs/routes/universityTeacher.js b/src/libs/routes/universityTeacher.js
new file mode 100644
index 00000000..b56a06f1
--- /dev/null
+++ b/src/libs/routes/universityTeacher.js
@@ -0,0 +1,477 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+const express = require('express');
+
+const teacherEnrollmentApp = express.Router();
+
+const libs = `${process.cwd()}/libs`;
+
+const log = require(`${libs}/log`)(module);
+
+const squel = require('squel');
+
+const query = require(`${libs}/middlewares/query`).query;
+
+const response = require(`${libs}/middlewares/response`);
+
+const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);
+
+const id2str = require(`${libs}/middlewares/id2str`);
+
+const addMissing = require(`${libs}/middlewares/addMissing`);
+
+const config = require(`${libs}/config`);
+
+const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;
+
+let rqf = new ReqQueryFields();
+
+teacherEnrollmentApp.get('/years', (req, res, next) => {
+    req.sql.from('docente_ens_superior')
+    .field('DISTINCT docente_ens_superior.ano_censo', 'year');
+    next();
+}, query, response('years'));
+
+teacherEnrollmentApp.get('/year_range', (req, res, next) => {
+    req.sql.from('docente_ens_superior')
+    .field('MIN(docente_ens_superior.ano_censo)', 'start_year')
+    .field('MAX(docente_ens_superior.ano_censo)', 'end_year');
+    next();
+}, query, response('range'));
+
+teacherEnrollmentApp.get('/academic_organization', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 5; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.academicOrganization(i)
+        });
+    };
+    next();
+}, response('academic_organization'));
+
+teacherEnrollmentApp.get('/upper_adm_dependency', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 7; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.upperAdmDependency(i)
+        });
+    };
+    next();
+}, response('upper_adm_dependency'));
+
+teacherEnrollmentApp.get('/teacher_situation', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 6; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.teacherSituation(i)
+        });
+    };
+    next();
+}, response('teacher_situation'));
+
+teacherEnrollmentApp.get('/work_regime', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 4; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.workRegime(i)
+        });
+    };
+    next();
+}, response('work_regime'));
+
+teacherEnrollmentApp.get('/substitute', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 1; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.booleanVariable(i)
+        });
+    };
+    next();
+}, response('substitute'));
+
+teacherEnrollmentApp.get('/visitor', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 1; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.booleanVariable(i)
+        });
+    };
+    next();
+}, response('visitor'));
+
+teacherEnrollmentApp.get('/ead_teacher', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 1; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.booleanVariable(i)
+        });
+    };
+    next();
+}, response('ead_teacher'));
+
+teacherEnrollmentApp.get('/graduation_presential', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 1; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.booleanVariable(i)
+        });
+    };
+    next();
+}, response('graduation_presential'));
+
+teacherEnrollmentApp.get('/postgraduate_ead_teacher', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 1; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.booleanVariable(i)
+        });
+    };
+    next();
+}, response('postgraduate_ead_teacher'));
+
+teacherEnrollmentApp.get('/postgraduate_presential_teacher', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 1; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.booleanVariable(i)
+        });
+    };
+    next();
+}, response('postgraduate_presential_teacher'));
+
+teacherEnrollmentApp.get('/deficiency', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 1; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.booleanVariable(i)
+        });
+    };
+    next();
+}, response('deficiency'));
+
+teacherEnrollmentApp.get('/ethnic_group_teacher_ies', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 5; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.ethnicGroupTeacherIES(i)
+        });
+    };
+    next();
+}, response('ethnic_group_teacher_ies'));
+
+teacherEnrollmentApp.get('/teacher_schooling', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 5; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.teacherSchooling(i)
+        });
+    };
+    next();
+}, response('teacher_schooling'));
+
+teacherEnrollmentApp.get('/gender_ies', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 2; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.genderIES(i)
+        });
+    };
+    next();
+}, response('gender_ies'));
+
+
+rqf.addField({
+    name: 'filter',
+    field: false,
+    where: true
+}).addField({
+    name: 'dims',
+    field: true,
+    where: false
+}).addValue({
+    name: 'min_year',
+    table: '@',
+    tableField: 'ano_censo',
+    resultField: 'year',
+    where: {
+        relation: '>=',
+        type: 'integer',
+        table: '@',
+        field: 'ano_censo'
+    }
+}).addValue({
+    name: 'max_year',
+    table: '@',
+    tableField: 'ano_censo',
+    resultField: 'year',
+    where: {
+        relation: '<=',
+        type: 'integer',
+        table: '@',
+        field: 'ano_censo'
+    }
+}).addValue({
+    name: 'state',
+    table: 'estado',
+    tableField: 'nome',
+    resultField: 'state_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_uf_nascimento',
+        table: '@'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'cod_uf_nascimento',
+        foreignTable: '@'
+    }
+}).addValue({
+    name: 'city',
+    table: 'municipio',
+    tableField: 'nome',
+    resultField: 'city_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_municipio_nascimento',
+        table: '@'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'cod_municipio_nascimento',
+        foreignTable: '@'
+    }
+}).addValue({
+    name: 'region',
+    table: 'regiao',
+    tableField: 'nome',
+    resultField: 'region_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'id'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'regiao_id',
+        foreignTable: 'docente_ens_superior'
+    }
+}).addValue({
+    name: 'university',
+    table: 'docente_ens_superior',
+    tableField: ['cod_ies', 'nome_ies'],
+    resultField: ['university_id', 'university_name'],
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ies'
+    }
+}).addValue({
+    name: 'upper_adm_dependency',
+    table: 'docente_ens_superior',
+    tableField: 'cod_categoria_administrativa',
+    resultField: 'upper_adm_dependency_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        table: 'docente_ens_superior',
+        field: 'cod_categoria_administrativa'
+    }
+}).addValue({
+    name: 'academic_organization',
+    table: 'docente_ens_superior',
+    tableField: 'cod_organizacao_academica',
+    resultField: 'academic_organization_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        table: 'docente_ens_superior',
+        field: 'cod_organizacao_academica'
+    }
+}).addValue({
+    name:'academic_level',
+    table: 'docente_ens_superior',
+    tableField: 'cod_grau_academico',
+    resultField: 'academic_level_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_grau_academico'
+    }
+}).addValue({
+    name:'upper_education_mod',
+    table: 'docente_ens_superior',
+    tableField: 'cod_modalidade_ensino',
+    resultField: 'upper_education_mod_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_modalidade_ensino'
+    }
+}).addValue({
+    name:'teacher_situation',
+    table: 'docente_ens_superior',
+    tableField: 'cod_situacao_docente',
+    resultField: 'teacher_situation_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_situacao_docente'
+    }
+}).addValue({
+    name:'work_regime',
+    table: 'docente_ens_superior',
+    tableField: 'cod_regime_trabalho',
+    resultField: 'work_regime_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_regime_trabalho'
+    }
+}).addValue({
+    name:'substitute',
+    table: 'docente_ens_superior',
+    tableField: 'docente_substituto',
+    resultField: 'substitute_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'docente_substituto'
+    }
+}).addValue({
+    name:'visitor',
+    table: 'docente_ens_superior',
+    tableField: 'docente_visitante',
+    resultField: 'visitor_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'docente_visitante'
+    }
+}).addValue({
+    name:'ead_teacher',
+    table: 'docente_ens_superior',
+    tableField: 'ministra_aula_ead',
+    resultField: 'ead_teacher_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'ministra_aula_ead'
+    }
+}).addValue({
+    name:'graduation_presential',
+    table: 'docente_ens_superior',
+    tableField: 'atua_atividade_graduacao_presencial',
+    resultField: 'graduation_presential_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'atua_atividade_graduacao_presencial'
+    }
+}).addValue({
+    name:'postgraduate_ead_teacher',
+    table: 'docente_ens_superior',
+    tableField: 'atua_atividade_posgraduacao_distancia',
+    resultField: 'postgraduate_ead_teacher_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'atua_atividade_posgraduacao_distancia'
+    }
+}).addValue({
+    name:'postgraduate_presential_teacher',
+    table: 'docente_ens_superior',
+    tableField: 'atua_atividade_posgraduacao_presencial',
+    resultField: 'postgraduate_presential_teacher_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'atua_atividade_posgraduacao_presencial'
+    }
+}).addValue({
+    name:'teacher_schooling',
+    table: 'docente_ens_superior',
+    tableField: 'cod_escolaridade_docente',
+    resultField: 'teacher_schooling_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_escolaridade_docente'
+    }
+}).addValue({
+    name:'ethnic_group_teacher_ies',
+    table: 'docente_ens_superior',
+    tableField: 'cod_cor_raca_docente',
+    resultField: 'ethnic_group_teacher_ies_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_cor_raca_docente'
+    }
+}).addValue({
+    name:'gender_ies',
+    table: 'docente_ens_superior',
+    tableField: 'sexo_docente',
+    resultField: 'gender_ies_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'sexo_docente'
+    }
+}).addValue({
+    name:'deficiency',
+    table: 'docente_ens_superior',
+    tableField: 'docente_deficiencia',
+    resultField: 'deficiency_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'docente_deficiencia'
+    }
+});
+
+teacherEnrollmentApp.get('/', rqf.parse(), (req, res, next) => {
+    req.sql.field('COUNT(*)', 'total')
+    .field("'Brasil'", 'name')
+    .field('docente_ens_superior.ano_censo', 'year')
+    .from('docente_ens_superior')
+    .group('docente_ens_superior.ano_censo')
+    .order('docente_ens_superior.ano_censo')
+
+   next();
+},  rqf.build(), query, addMissing(rqf), id2str.transform(false), response('teacherEnrollment'));
+
+module.exports = teacherEnrollmentApp;
-- 
GitLab


From 3e4dcdbb843ebbed4a01934b48ca5ef40a117e37 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fernandoerd2012@gmail.com>
Date: Thu, 28 Mar 2019 11:46:16 -0300
Subject: [PATCH 064/142] Fix id2str error

---
 src/libs/middlewares/id2str.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 6a3504e7..0e2b9e9c 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -135,7 +135,7 @@ const ids = {
     capital_id: booleanVariable,
     ethnic_group_ies_id: ethnicGroupIES,
     teacher_situation_id: teacherSituation,
-    work_regime_id: work_regime,
+    work_regime_id: workRegime,
     substitute_id: booleanVariable,
     visitor_id: booleanVariable,
     ead_teacher_id: eadTeacher,
@@ -229,7 +229,7 @@ module.exports = {
     ethnicGroupIES,
     upperTurn,
     teacherSituation,
-    work_regime,
+    workRegime,
     substitute,
     visitor,
     eadTeacher,
-- 
GitLab


From 0289386fcd4d6a491881a171f923fd221123d0ee Mon Sep 17 00:00:00 2001
From: Fernando Erd <fernandoerd2012@gmail.com>
Date: Tue, 2 Apr 2019 09:20:50 -0300
Subject: [PATCH 065/142] Add map university teacher

---
 src/libs/convert/ethnicGroupTeacherIES.js | 2 +-
 src/libs/routes/api.js                    | 3 +++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/src/libs/convert/ethnicGroupTeacherIES.js b/src/libs/convert/ethnicGroupTeacherIES.js
index 7498315e..7db2936c 100644
--- a/src/libs/convert/ethnicGroupTeacherIES.js
+++ b/src/libs/convert/ethnicGroupTeacherIES.js
@@ -21,7 +21,7 @@ along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
 module.exports = function ethnicGroupTeacherIES(id) {
     switch (id) {
         case 0:
-        return 'docente não quis declarar cor/raça';
+        return 'Docente não quis declarar cor/raça';
         case 1:
         return 'Branca';
         case 2:
diff --git a/src/libs/routes/api.js b/src/libs/routes/api.js
index 48734ffd..e52745ed 100644
--- a/src/libs/routes/api.js
+++ b/src/libs/routes/api.js
@@ -102,6 +102,8 @@ const courseCount = require(`${libs}/routes/courseCount`);
 
 const university = require(`${libs}/routes/university`);
 
+const universityTeacher = require(`${libs}/routes/universityTeacher`);
+
 api.get('/', (req, res) => {
     res.json({ msg: 'SimCAQ API is running' });
 });
@@ -144,6 +146,7 @@ api.use('/employees', employees);
 api.use('/financial', financial);
 api.use('/university_enrollment', universityEnrollment);
 api.use('/university', university);
+api.use('/university_teacher', universityTeacher);
 api.use('/course_count', courseCount);
 
 module.exports = api;
-- 
GitLab


From 03068b3dbb6d04550989fa33774e6d899630e331 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fernandoerd2012@gmail.com>
Date: Tue, 2 Apr 2019 10:00:26 -0300
Subject: [PATCH 066/142] Fix integral time convert

---
 src/libs/convert/integralTime.js | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/src/libs/convert/integralTime.js b/src/libs/convert/integralTime.js
index b231be33..57dab5b4 100644
--- a/src/libs/convert/integralTime.js
+++ b/src/libs/convert/integralTime.js
@@ -1,7 +1,7 @@
 /*
 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
@@ -19,10 +19,12 @@ along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
 */
 
 module.exports = function integralTime(id) {
-  if (id == null)
-    return 'Não se aplica (semi presencial e EaD)';
-  else if (id == false)
-    return 'Não';
-  else if (id == true)
-    return 'Sim';
+    switch (id) {
+		case true:
+		return 'Sim';
+		case false:
+		return 'Não';
+		default:
+		return 'Não se aplica (semi presencial e EaD)';
+    }
 };
-- 
GitLab


From bb32985fc01b02e9b41bce29bfea27c44c2ae2db Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 4 Apr 2019 09:16:49 -0300
Subject: [PATCH 067/142] Change state/region/city to IES

---
 src/libs/routes/universityTeacher.js | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/src/libs/routes/universityTeacher.js b/src/libs/routes/universityTeacher.js
index b56a06f1..f5eb9582 100644
--- a/src/libs/routes/universityTeacher.js
+++ b/src/libs/routes/universityTeacher.js
@@ -250,12 +250,12 @@ rqf.addField({
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_uf_nascimento',
+        field: 'cod_uf_ies',
         table: '@'
     },
     join: {
         primary: 'id',
-        foreign: 'cod_uf_nascimento',
+        foreign: 'cod_uf_ies',
         foreignTable: '@'
     }
 }).addValue({
@@ -266,12 +266,12 @@ rqf.addField({
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_municipio_nascimento',
+        field: 'cod_municipio_ies',
         table: '@'
     },
     join: {
         primary: 'id',
-        foreign: 'cod_municipio_nascimento',
+        foreign: 'cod_municipio_ies',
         foreignTable: '@'
     }
 }).addValue({
@@ -286,7 +286,7 @@ rqf.addField({
     },
     join: {
         primary: 'id',
-        foreign: 'regiao_id',
+        foreign: 'cod_regiao_ies',
         foreignTable: 'docente_ens_superior'
     }
 }).addValue({
-- 
GitLab


From d2f61dcb9ac6c7663d04c7d33084b0724a81e5a6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 4 Apr 2019 09:44:11 -0300
Subject: [PATCH 068/142] Changed region/state/city to IES on
 univercityEnrollment

---
 src/libs/routes/universityEnrollment.js | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index 9d92c27f..56e1eea0 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -210,12 +210,12 @@ rqf.addField({
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_uf_nascimento',
+        field: 'cod_uf_ies',
         table: '@'
     },
     join: {
         primary: 'id',
-        foreign: 'cod_uf_nascimento',
+        foreign: 'cod_uf_ies',
         foreignTable: '@'
     }
 }).addValue({
@@ -226,12 +226,12 @@ rqf.addField({
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_municipio_nascimento',
+        field: 'cod_municipio_ies',
         table: '@'
     },
     join: {
         primary: 'id',
-        foreign: 'cod_municipio_nascimento',
+        foreign: 'cod_municipio_ies',
         foreignTable: '@'
     }
 }).addValue({
@@ -246,7 +246,7 @@ rqf.addField({
     },
     join: {
         primary: 'id',
-        foreign: 'regiao_id',
+        foreign: 'cod_regiao_ies',
         foreignTable: 'aluno_ens_superior'
     }
 }).addValue({
-- 
GitLab


From 2b8ad533575e121ab76bcc92ec44f1c81211a229 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Fri, 5 Apr 2019 09:09:37 -0300
Subject: [PATCH 069/142] Add id to region/state/city

---
 src/libs/routes/courseCount.js          |  8 ++++----
 src/libs/routes/university.js           | 12 ++++++------
 src/libs/routes/universityEnrollment.js | 12 ++++++------
 src/libs/routes/universityTeacher.js    | 12 ++++++------
 4 files changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index 125ef449..7ff6b010 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -196,8 +196,8 @@ rqf.addField({
 }).addValue({
     name: 'region',
     table: 'regiao',
-    tableField: 'nome',
-    resultField: 'region_name',
+    tableField: ['nome', 'id'],
+    resultField: ['region_name', 'region_id'],
     where: {
         relation: '=',
         type: 'integer',
@@ -211,8 +211,8 @@ rqf.addField({
 }).addValue({
     name: 'state',
     table: 'estado',
-    tableField: 'nome',
-    resultField: 'state_name',
+    tableField: ['nome', 'id'],
+    resultField: ['state_name', 'state_id'],
     where: {
         relation: '=',
         type: 'integer',
diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index ce214d94..648fbacd 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -193,8 +193,8 @@ rqfCount.addField({
 }).addValue({
     name: 'city',
     table: 'municipio',
-    tableField: 'nome',
-    resultField: 'city_name',
+    tableField: ['nome', 'id'],
+    resultField: ['city_name', 'city_id'],
     where: {
         relation: '=',
         type: 'integer',
@@ -209,8 +209,8 @@ rqfCount.addField({
 }).addValue({
     name: 'region',
     table: 'regiao',
-    tableField: 'nome',
-    resultField: 'region_name',
+    tableField: ['nome', 'id'],
+    resultField: ['region_name', 'region_id'],
     where: {
         relation: 'LIKE',
         type: 'string',
@@ -247,8 +247,8 @@ rqfCount.addField({
 }).addValue({
     name: 'state',
     table: 'estado',
-    tableField: 'nome',
-    resultField: 'state_name',
+    tableField: ['nome', 'id'],
+    resultField: ['state_name', 'state_id'],
     where: {
         relation: '=',
         type: 'integer',
diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index 56e1eea0..9fe86723 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -205,8 +205,8 @@ rqf.addField({
 }).addValue({
     name: 'state',
     table: 'estado',
-    tableField: 'nome',
-    resultField: 'state_name',
+    tableField: ['nome', 'id'],
+    resultField: ['state_name', 'state_id'],
     where: {
         relation: '=',
         type: 'integer',
@@ -221,8 +221,8 @@ rqf.addField({
 }).addValue({
     name: 'city',
     table: 'municipio',
-    tableField: 'nome',
-    resultField: 'city_name',
+    tableField: ['nome', 'id'],
+    resultField: ['city_name', 'city_id'],
     where: {
         relation: '=',
         type: 'integer',
@@ -237,8 +237,8 @@ rqf.addField({
 }).addValue({
     name: 'region',
     table: 'regiao',
-    tableField: 'nome',
-    resultField: 'region_name',
+    tableField: ['nome', 'id'],
+    resultField: ['region_name', 'region_id'],
     where: {
         relation: '=',
         type: 'integer',
diff --git a/src/libs/routes/universityTeacher.js b/src/libs/routes/universityTeacher.js
index f5eb9582..58a9164e 100644
--- a/src/libs/routes/universityTeacher.js
+++ b/src/libs/routes/universityTeacher.js
@@ -245,8 +245,8 @@ rqf.addField({
 }).addValue({
     name: 'state',
     table: 'estado',
-    tableField: 'nome',
-    resultField: 'state_name',
+    tableField: ['nome', 'id'],
+    resultField: ['state_name', 'state_id'],
     where: {
         relation: '=',
         type: 'integer',
@@ -261,8 +261,8 @@ rqf.addField({
 }).addValue({
     name: 'city',
     table: 'municipio',
-    tableField: 'nome',
-    resultField: 'city_name',
+    tableField: ['nome', 'id'],
+    resultField: ['city_name', 'city_id'],
     where: {
         relation: '=',
         type: 'integer',
@@ -277,8 +277,8 @@ rqf.addField({
 }).addValue({
     name: 'region',
     table: 'regiao',
-    tableField: 'nome',
-    resultField: 'region_name',
+    tableField: ['nome', 'id'],
+    resultField: ['region_name', 'region_id'],
     where: {
         relation: '=',
         type: 'integer',
-- 
GitLab


From b18982ba2001ad7f00be8532285d809faf67cdcc Mon Sep 17 00:00:00 2001
From: Fernando Erd <fcerd@inf.ufpr.br>
Date: Fri, 5 Apr 2019 10:31:42 -0300
Subject: [PATCH 070/142] Add function addZero in class count route

---
 src/libs/routes/classCount.js | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)

diff --git a/src/libs/routes/classCount.js b/src/libs/routes/classCount.js
index 3496c193..8bea3885 100644
--- a/src/libs/routes/classCount.js
+++ b/src/libs/routes/classCount.js
@@ -338,6 +338,23 @@ function addNullFields(result) {
     }
     prevFirstDimId = d;
   });
+  console.log("FUNCTION");
+  console.log(result);
+}
+
+function addZeroFields(result) {
+    let i;
+    for (i=0; i < result.length; i++) {
+        let hasTotal = result[i].hasOwnProperty("total");
+        if (hasTotal == true) {
+            result[i].average = 0.0;
+            result[i].median = 0.0;
+            result[i].stddev = 0.0;
+            result[i].first_qt = 0.0;
+            result[i].third_qt = 0.0;
+        }
+    }
+    return result;
 }
 
 // SimCAQ
@@ -425,8 +442,10 @@ classCountApp.get('/', rqf.parse(), (req, res, next) => {
     })
   }
   // Caso tenha mais de uma dimensão, retorna a consulta só pelas dimensões, sem linha de total
-  else
+  else {
     addNullFields(req.result);
+    req.result = addZeroFields(req.result);
+  }
 
   next();
 }, response('class_count'));
-- 
GitLab


From ad6f6caa2fad16ff79c146f24dff5e6afac7ec91 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fcerd@inf.ufpr.br>
Date: Fri, 12 Apr 2019 11:29:54 -0300
Subject: [PATCH 071/142] Standardize out of school

---
 src/libs/routes/outOfSchool.js | 38 ++++++++++++++++++++++++++++++----
 1 file changed, 34 insertions(+), 4 deletions(-)

diff --git a/src/libs/routes/outOfSchool.js b/src/libs/routes/outOfSchool.js
index 16c5660f..b5092130 100644
--- a/src/libs/routes/outOfSchool.js
+++ b/src/libs/routes/outOfSchool.js
@@ -272,14 +272,44 @@ simcaqRqf.addField({
     field: true,
     where: false
 }).addValue({
-    name: 'state',
+    name: 'brasil_total',
     table: 'populacao_fora_da_escola',
-    tableField: 'unidade_federativa',
-    resultField: 'state_id',
+    tableField: 'brasil',
+    resultField: 'brazil_total_id',
+    where: {
+        relation: '=',
+        type: 'boolean',
+        field: 'brasil'
+    }
+}).addValue({
+    name: 'state',
+    table: 'estado',
+    tableField: 'nome',
+    resultField: 'state_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'id'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'estado_id',
+        foreignTable: 'populacao_fora_da_escola'
+    }
+}).addValue({
+    name: 'city',
+    table: 'municipio',
+    tableField: 'nome',
+    resultField: 'city_name',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'unidade_federativa'
+        field: 'id'
+    },
+    join: {
+        primary: 'id',
+        foreign: 'municipio_id',
+        foreignTable: 'populacao_fora_da_escola'
     }
 }).addValue({
     name: 'pfe',
-- 
GitLab


From 98118a884d02d779cca929ca68ea79bbcf3be5ea Mon Sep 17 00:00:00 2001
From: Fernando Erd <fcerd@inf.ufpr.br>
Date: Tue, 16 Apr 2019 09:25:16 -0300
Subject: [PATCH 072/142] Standard out of school route

---
 src/libs/routes/outOfSchool.js | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/src/libs/routes/outOfSchool.js b/src/libs/routes/outOfSchool.js
index b5092130..6ccedf21 100644
--- a/src/libs/routes/outOfSchool.js
+++ b/src/libs/routes/outOfSchool.js
@@ -272,7 +272,7 @@ simcaqRqf.addField({
     field: true,
     where: false
 }).addValue({
-    name: 'brasil_total',
+    name: 'brazil_total',
     table: 'populacao_fora_da_escola',
     tableField: 'brasil',
     resultField: 'brazil_total_id',
@@ -357,7 +357,6 @@ outOfSchoolApp.get('/simcaq', simcaqRqf.parse(), simcaqRqf.build(), (req, res, n
 }, query, (req, res, next) => {
 	req.result.forEach((i) => {
 		i.total = parseInt(i.total);
-		console.log(i.total);
 	});
 	next();
 }, addMissing(simcaqRqf), id2str.transform(), response('out_of_school'));
-- 
GitLab


From 81adf7cc46e572af9bbde17f738532f8e50f00c1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 18 Apr 2019 11:38:19 -0300
Subject: [PATCH 073/142] Fixed enrollment number on classroomCount

---
 src/libs/routes/classroomCount.js | 10 +++-------
 1 file changed, 3 insertions(+), 7 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 7489ddcb..b64380f8 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -244,7 +244,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     .from('escola')
     .group('escola.ano_censo')
     .order('escola.ano_censo')
-    .where('escola.situacao_de_funcionamento = 1 AND escola.local_func_predio_escolar = 1')
+    .where('escola.situacao_de_funcionamento = 1 AND escola.local_func_predio_escolar <= 3')
     .where('escola.dependencia_adm_id < 4');
 
     next();
@@ -311,10 +311,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             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;
@@ -441,7 +437,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             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_day += (enrollment.period_id < 3) ? enrollment.total : 0;
             educationLevel.enrollment.total_enrollment_night += (enrollment.period_id == 3) ? enrollment.total : 0;
 
             // Calcula o número de turmas parcial
@@ -464,7 +460,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             // 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_day += (enrollment.period_id < 3) ? enrollment.total : 0;
                 currentSchoolYear.total_enrollment_night += (enrollment.period_id == 3) ? enrollment.total : 0;
                 
                 // Número de turmas parcial
-- 
GitLab


From 164ef97454650a292d329af20cacc2a97ba93adc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 25 Apr 2019 09:28:36 -0300
Subject: [PATCH 074/142] Fix number of classes, remove night enrollments from
 kindergarten

---
 src/libs/routes/classroomCount.js | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index b64380f8..2b9e08dc 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -241,10 +241,12 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     req.sql.field('SUM(escola.num_salas)', 'total')
     .field("'Brasil'", 'name')
     .field('escola.ano_censo', 'year')
+    .field('escola.local_func_predio_escolar', 'school_building')
     .from('escola')
     .group('escola.ano_censo')
+    .group('escola.local_func_predio_escolar')
     .order('escola.ano_censo')
-    .where('escola.situacao_de_funcionamento = 1 AND escola.local_func_predio_escolar <= 3')
+    .where('escola.situacao_de_funcionamento = 1')
     .where('escola.dependencia_adm_id < 4');
 
     next();
@@ -293,7 +295,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
         let location = {
             location_id: classroom.location_id,
             location_name: classroom.location_name,
-            total_classroom: parseInt(classroom.total, 10),
+            total_classroom: (classroom.school_building == 1) ? parseInt(classroom.total, 10) : 0,      // Conta apenas salas de prédios próprios
             total_classroom_be_built: 0,
             education_level: []
         };
@@ -310,8 +312,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
         while(enrollmentMatch && j < enrollments.length) {
             enrollment = enrollments[j];
 
-            // Remove se o período é nulo (não dá pra usar no cálculo)
-
             if(typeof enrollment === 'undefined') {
                 ++j;
                 continue;
@@ -438,7 +438,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
             // Soma os totais de matrícula da etapa de ensino
             educationLevel.enrollment.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
-            educationLevel.enrollment.total_enrollment_night += (enrollment.period_id == 3) ? enrollment.total : 0;
+            educationLevel.enrollment.total_enrollment_night += (enrollment.period_id == 3 && educationLevel.education_level_short_id > 2) ? enrollment.total : 0;      //Não contamos matrículas noturnos de pré-escola e creche
 
             // Calcula o número de turmas parcial
             // Turmas de período integral
@@ -461,7 +461,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             if(currentSchoolYear) {
                 // Totais de matrícula
                 currentSchoolYear.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
-                currentSchoolYear.total_enrollment_night += (enrollment.period_id == 3) ? enrollment.total : 0;
+                currentSchoolYear.total_enrollment_night += (enrollment.period_id == 3 && currentSchoolYear.school_year_id > 30) ? enrollment.total : 0;        //Não contamos matrículas noturnos de pré-escola e creche
                 
                 // Número de turmas parcial
                 currentSchoolYear.full_period_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (currentOfferGoal/100)) / currentNumberStudentClass);
-- 
GitLab


From 5b2648160779cafbd28a7925638472d6a409cabf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Fri, 26 Apr 2019 10:04:12 -0300
Subject: [PATCH 075/142] Remove night enrollments from kindergarten in
 enrollmentProjection

---
 src/libs/routes/enrollmentProjection.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/enrollmentProjection.js b/src/libs/routes/enrollmentProjection.js
index 7ff2ab23..47eb7b71 100644
--- a/src/libs/routes/enrollmentProjection.js
+++ b/src/libs/routes/enrollmentProjection.js
@@ -148,9 +148,9 @@ enrollmentProjectionApp.get('/', rqf.parse(), rqf.build(), (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.urban_night_total = ((r.education_level_school_year_id >= 3 && r.education_level_school_year_id < 10) || (r.education_level_school_year_id >= 30)) ? parseInt(r.urban_night_total, 10) : 0;   //Não conta matrículas noturnas da pré-escola e da creche
         r.rural_day_total = parseInt(r.rural_day_total, 10);
-        r.rural_night_total = parseInt(r.rural_night_total, 10);
+        r.rural_night_total = ((r.education_level_school_year_id >= 3 && r.education_level_school_year_id < 10) || (r.education_level_school_year_id >= 30)) ? parseInt(r.rural_night_total, 10) : 0;
     });
     
     next();
-- 
GitLab


From 306bdd66e56f22eaaf8bccd4e1f9d44c177f8bb3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 2 May 2019 09:47:53 -0300
Subject: [PATCH 076/142] Fix classroom to be built

---
 src/libs/routes/classroomCount.js | 46 +++++++++++++++++++++----------
 1 file changed, 32 insertions(+), 14 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 2b9e08dc..476969f0 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -177,6 +177,16 @@ rqf.addField({
         type: 'integer',
         field: 'turma_turno_id'
     }
+}).addValue({
+    name: 'school_building',
+    table: 'escola',
+    tableField: 'local_func_predio_escolar',
+    resultField: 'school_building',
+    where: {
+        relation: '=',
+        type: 'boolean',
+        field: 'local_func_predio_escolar'
+    }
 });
 
 classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
@@ -237,14 +247,13 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     req.dims.state = true;
     req.dims.city = true;
     req.dims.location = true;
+    req.dims.school_building = true;
 
     req.sql.field('SUM(escola.num_salas)', 'total')
     .field("'Brasil'", 'name')
     .field('escola.ano_censo', 'year')
-    .field('escola.local_func_predio_escolar', 'school_building')
     .from('escola')
     .group('escola.ano_censo')
-    .group('escola.local_func_predio_escolar')
     .order('escola.ano_censo')
     .where('escola.situacao_de_funcionamento = 1')
     .where('escola.dependencia_adm_id < 4');
@@ -282,15 +291,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             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,
@@ -299,10 +299,30 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             total_classroom_be_built: 0,
             education_level: []
         };
+        
+        let currentClassroomObj = null;
+        if( !hashSet.has(hash) ) {
+            if (result[result.length - 1] !== undefined) {      // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id
+                let last_locations = result[result.length - 1].locations
+                for (let i = 1; i < last_locations.length; i++) {
+                    if (last_locations[i].location_id === last_locations[i-1].location_id) {
+                        last_locations[i].total_classroom_be_built += last_locations[i-1].total_classroom_be_built;
+                        last_locations[i-1].total_classroom_be_built = 0;
+                    }
+                }
+                for (let i = 0; i < last_locations.length; i++) {   // Passamos agora para não deixar to_be_built < 0
+                    last_locations[i].total_classroom_be_built = (last_locations[i].total_classroom_be_built < 0) ? 0 : last_locations[i].total_classroom_be_built;
+                }
+            }
+            hashSet.add(hash);
+            result.push(obj);
+            currentClassroomObj = obj;
+        } 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];
+        }
         currentClassroomObj.locations.push(location);
 
         // Partimos para as etapas de ensino/anos escolares
-
         let enrollmentMatch = true;
         j = 0;
         let educationLevelSet = new Set();
@@ -492,8 +512,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             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;
     }
 
-- 
GitLab


From a83c7d6abb3089c321e21cd4f58b8220980def8d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Mon, 6 May 2019 09:34:24 -0300
Subject: [PATCH 077/142] Fix double location in classroom count

---
 src/libs/routes/classroomCount.js | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 476969f0..d595825d 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -304,10 +304,11 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
         if( !hashSet.has(hash) ) {
             if (result[result.length - 1] !== undefined) {      // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id
                 let last_locations = result[result.length - 1].locations
-                for (let i = 1; i < last_locations.length; i++) {
-                    if (last_locations[i].location_id === last_locations[i-1].location_id) {
-                        last_locations[i].total_classroom_be_built += last_locations[i-1].total_classroom_be_built;
-                        last_locations[i-1].total_classroom_be_built = 0;
+                for (let i = 0; i < last_locations.length - 1; i++) {
+                    if (last_locations[i].location_id === last_locations[i+1].location_id) {
+                        last_locations[i].total_classroom_be_built += last_locations[i+1].total_classroom_be_built;
+                        last_locations[i].total_classroom += last_locations[i+1].total_classroom;
+                        last_locations.splice(i+1, 1);
                     }
                 }
                 for (let i = 0; i < last_locations.length; i++) {   // Passamos agora para não deixar to_be_built < 0
@@ -569,6 +570,12 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                         // 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') {
+                            console.log(cityLocation, currentLocation);
+                            console.log(cityLocation.education_level);
+                            for (i = 0; i < cityLocation.education_level.length; i++) {
+                                console.log(cityLocation.education_level[i]);
+                                console.log(cityLocation.education_level.classes_school_year);
+                            }
                             currentObj.locations[k] = cityLocation;
                             currentLocation = currentObj.locations[k];
                         }
-- 
GitLab


From 2445147e051949dda7e0aa1765ca2f0ea735cef0 Mon Sep 17 00:00:00 2001
From: jvfpw18 <jvfpw18@inf.ufpr.br>
Date: Mon, 6 May 2019 09:46:40 -0300
Subject: [PATCH 078/142] Update classroomCount.js

---
 src/libs/routes/classroomCount.js | 6 ------
 1 file changed, 6 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index d595825d..0f89ff60 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -570,12 +570,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                         // 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') {
-                            console.log(cityLocation, currentLocation);
-                            console.log(cityLocation.education_level);
-                            for (i = 0; i < cityLocation.education_level.length; i++) {
-                                console.log(cityLocation.education_level[i]);
-                                console.log(cityLocation.education_level.classes_school_year);
-                            }
                             currentObj.locations[k] = cityLocation;
                             currentLocation = currentObj.locations[k];
                         }
-- 
GitLab


From 22906991e6f90ebcbc0d1e0b111bf20431069067 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Mon, 6 May 2019 11:12:45 -0300
Subject: [PATCH 079/142] Fix Santa Cantarina bug

---
 src/libs/routes/classroomCount.js | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 0f89ff60..15813956 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -552,6 +552,15 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             if(currentObj.locations.length == 0) {
                 // Pode ser que a cidade atual tenha menos localidades que o total (só urbana ou só rural)
                 currentObj.locations = [...city.locations];
+                if (currentObj.locations.length === 1) {        // Se a cidade só tinha uma, adcionamos a outra manualmente.
+                    currentObj.locations[1] = {
+                        location_id: (currentObj.locations[0].location_id === 1) ? 2 : 1,   // Oposto da adcionada
+                        location_name: (currentObj.locations[0].location_id === 1) ? 'Rural' : 'Urbana',    // Oposto da adcionada
+                        total_classroom: 0,
+                        total_classroom_be_built: 0,
+                        education_level: []
+                    }
+                }
             } else {
                 let j = 0;
                 let k = 0;
@@ -567,12 +576,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                     } else if(cityLocation.location_id > currentLocation.location_id) {
                         ++k;
                         currentLocation = currentObj.locations[k];
-                        // Se a localidade da cidade é  maior que a localidade do objeto atual E o vetor de localidades do objeto atual
-                        // acaba, então esta localidade falta no objeto atual, pois as localidades estão ordenadas
-                        if(typeof currentLocation == 'undefined' && typeof cityLocation !== 'undefined') {
-                            currentObj.locations[k] = cityLocation;
-                            currentLocation = currentObj.locations[k];
-                        }
                         continue;
                     }
 
-- 
GitLab


From 83e8c15a9f202325b7ac520a755c021c29e7cf0c Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 7 May 2019 10:59:52 -0300
Subject: [PATCH 080/142] [ies_filter]Add capital filter

---
 src/libs/routes/university.js | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index 648fbacd..852ddcf6 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -282,6 +282,17 @@ rqfCount.addField({
         table: 'ies_ens_superior',
         field: 'cod_organizacao_academica'
     }
+}).addValue({
+    name: 'ies_capital',
+    table: 'ies_ens_superior',
+    tableField: 'capital_ies',
+    resultField: 'ies_capital_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        table: 'ies_ens_superior',
+        field: 'capital_ies'
+    }
 });
 
 universityApp.get('/', rqf.parse(),  rqf.build(), (req, res, next) => {
-- 
GitLab


From 02b1ffb02fb3c388072d8bdaa7c07cfb1373d7c8 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 7 May 2019 11:25:49 -0300
Subject: [PATCH 081/142] [ies_filter]Name fix

---
 src/libs/routes/university.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index 852ddcf6..f157aeb7 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -283,10 +283,10 @@ rqfCount.addField({
         field: 'cod_organizacao_academica'
     }
 }).addValue({
-    name: 'ies_capital',
+    name: 'capital',
     table: 'ies_ens_superior',
     tableField: 'capital_ies',
-    resultField: 'ies_capital_id',
+    resultField: 'capital_id',
     where: {
         relation: '=',
         type: 'integer',
-- 
GitLab


From af262936fa56978ff2b78c18985bc9a8bdf7e575 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 7 May 2019 11:36:05 -0300
Subject: [PATCH 082/142] [ies_filter]Add id2str

---
 src/libs/routes/university.js | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index f157aeb7..c86fdc7f 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -85,6 +85,17 @@ universityApp.get('/academic_organization', (req, res, next) => {
     next();
 }, response('academic_organization'));
 
+universityApp.get('/capital', (req, res, next) => {
+    req.result = [];
+    for(let i = 0; i <= 1; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.booleanVariable(i)
+        });
+    };
+    next();
+}, response('capital'));
+
 rqf.addField({
     name: 'filter',
     field: false,
-- 
GitLab


From a8afef3d720a568027db3ca0d6632259a04c5d18 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Wed, 8 May 2019 09:28:03 -0300
Subject: [PATCH 083/142] [course_fix]Change count query

---
 src/libs/routes/courseCount.js | 1 -
 1 file changed, 1 deletion(-)

diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index 7ff6b010..81caf97e 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -404,7 +404,6 @@ courseCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
         .field('curso_ens_superior.ano_censo', 'year')
         .group('curso_ens_superior.ano_censo')
         .order('curso_ens_superior.ano_censo')
-        .where('curso_ens_superior.cod_situacao_curso = 1 OR curso_ens_superior.cod_situacao_curso = 3')
         .where('curso_ens_superior.tipo_atributo_ingresso <> 1')
         .where('curso_ens_superior.cod_nivel_academico = 1');
 
-- 
GitLab


From b0ced72df9c2b697fb99eb3a485700d0ec76167b Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Wed, 8 May 2019 09:44:35 -0300
Subject: [PATCH 084/142] [course_fix]Fix notation

---
 src/libs/convert/ocdeGeral.js  | 18 +++++++++---------
 src/libs/routes/courseCount.js |  2 +-
 2 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/src/libs/convert/ocdeGeral.js b/src/libs/convert/ocdeGeral.js
index 88cc0646..2750de03 100644
--- a/src/libs/convert/ocdeGeral.js
+++ b/src/libs/convert/ocdeGeral.js
@@ -20,23 +20,23 @@ along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
 
 module.exports = function ocdeGeral(id) {
     switch (id) {
-        case 0:
-        return 'Área básica';
         case 1:
-        return 'Educação';
+        return 'Área básica';
         case 2:
-        return 'Humanidades e artes';
+        return 'Educação';
         case 3:
-        return 'Ciências sociais, negócios e direitor';
+        return 'Humanidades e artes';
         case 4:
-        return 'Ciências, matemática e computação';
+        return 'Ciências sociais, negócios e direitor';
         case 5:
-        return 'Engenharia, produção e construção';
+        return 'Ciências, matemática e computação';
         case 6:
-        return 'Agricultura e veterinária';
+        return 'Engenharia, produção e construção';
         case 7:
-        return 'Saúde e bem estar social';
+        return 'Agricultura e veterinária';
         case 8:
+        return 'Saúde e bem estar social';
+        case 9:
         return 'Serviços';
         default:
         return 'Não classificada';
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index 81caf97e..bfd4620c 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -92,7 +92,7 @@ courseCountApp.get('/capital', (req, res, next) => {
 
 courseCountApp.get('/ocde', (req, res, next) => {
     req.result = [];
-    for(let i = 0; i <= 9; ++i) {
+    for(let i = 1; i <= 9; ++i) {
         req.result.push({
             id: i,
             name: id2str.ocdeGeral(i)
-- 
GitLab


From 372d5e4d857f33deae556418b5d2766c7cc23fbd Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Wed, 8 May 2019 10:16:56 -0300
Subject: [PATCH 085/142] [course_fix]Mod id2str

---
 src/libs/convert/ocdeGeral.js  | 18 +++++++++---------
 src/libs/routes/courseCount.js |  2 +-
 2 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/src/libs/convert/ocdeGeral.js b/src/libs/convert/ocdeGeral.js
index 2750de03..88cc0646 100644
--- a/src/libs/convert/ocdeGeral.js
+++ b/src/libs/convert/ocdeGeral.js
@@ -20,23 +20,23 @@ along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
 
 module.exports = function ocdeGeral(id) {
     switch (id) {
-        case 1:
+        case 0:
         return 'Área básica';
-        case 2:
+        case 1:
         return 'Educação';
-        case 3:
+        case 2:
         return 'Humanidades e artes';
-        case 4:
+        case 3:
         return 'Ciências sociais, negócios e direitor';
-        case 5:
+        case 4:
         return 'Ciências, matemática e computação';
-        case 6:
+        case 5:
         return 'Engenharia, produção e construção';
-        case 7:
+        case 6:
         return 'Agricultura e veterinária';
-        case 8:
+        case 7:
         return 'Saúde e bem estar social';
-        case 9:
+        case 8:
         return 'Serviços';
         default:
         return 'Não classificada';
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index bfd4620c..a2d6b90e 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -92,7 +92,7 @@ courseCountApp.get('/capital', (req, res, next) => {
 
 courseCountApp.get('/ocde', (req, res, next) => {
     req.result = [];
-    for(let i = 1; i <= 9; ++i) {
+    for(let i = 1; i <= 8; ++i) {
         req.result.push({
             id: i,
             name: id2str.ocdeGeral(i)
-- 
GitLab


From d5572fac74b23f69d286e10dee13fa8fed68ce0a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Wed, 8 May 2019 10:19:52 -0300
Subject: [PATCH 086/142] Fix duplicate name city bug

---
 src/libs/routes/classroomCount.js | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 15813956..92a390d4 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -265,7 +265,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     next();
 }, rqf.parse(), rqf.build(), (req, res, next) => {
     req.classroom = req.result;
-    let classroom = [];
     
     // req.result = [{classroom: req.classroom, enrollment: req.enrollment}]; return next();
 
@@ -338,10 +337,10 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 continue;
             }
 
-            if(classroom.city_name < enrollment.city_name) { // Se as cidades não são iguais, já passamos do range
+            if(classroom.city_id < enrollment.city_id) { // Se as cidades não são iguais, já passamos do range
                 enrollmentMatch = false;
                 continue;
-            } else if(classroom.city_name > enrollment.city_name) {
+            } else if(classroom.city_id > enrollment.city_id) {
                 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
-- 
GitLab


From 40a173cce9184b833e2460992488a59f5302e291 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Wed, 8 May 2019 10:36:20 -0300
Subject: [PATCH 087/142] [course_fix]Label fix

---
 src/libs/routes/courseCount.js | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index a2d6b90e..e4b174af 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -90,7 +90,7 @@ courseCountApp.get('/capital', (req, res, next) => {
     next();
 }, response('capital'));
 
-courseCountApp.get('/ocde', (req, res, next) => {
+courseCountApp.get('/ocde_geral', (req, res, next) => {
     req.result = [];
     for(let i = 1; i <= 8; ++i) {
         req.result.push({
@@ -99,7 +99,7 @@ courseCountApp.get('/ocde', (req, res, next) => {
         });
     };
     next();
-}, response('ocde'));
+}, response('ocde_geral'));
 
 courseCountApp.get('/ocde_specific', (req, res, next) => {
     req.result = [];
@@ -294,10 +294,10 @@ rqf.addField({
         field: 'cod_ocde_area_especifica'
     }
 }).addValue({
-    name:'ocde',
+    name:'ocde_geral',
     table: 'curso_ens_superior',
     tableField: 'cod_ocde_area_geral',
-    resultField: 'ocde_id',
+    resultField: 'ocde_geral_id',
     where: {
         relation: '=',
         type: 'integer',
-- 
GitLab


From 5338b0817e9a1f028e4abe7a9d56dbd336f01276 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Wed, 8 May 2019 10:52:03 -0300
Subject: [PATCH 088/142] Fix double location in the last result

---
 src/libs/routes/classroomCount.js | 27 +++++++++++++++++----------
 1 file changed, 17 insertions(+), 10 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 92a390d4..0606488b 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -337,18 +337,10 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 continue;
             }
 
-            if(classroom.city_id < enrollment.city_id) { // Se as cidades não são iguais, já passamos do range
+            if(classroom.city_id !== enrollment.city_id) { // Se as cidades não são iguais, já passamos do range
                 enrollmentMatch = false;
                 continue;
-            } else if(classroom.city_id > enrollment.city_id) {
-                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;
@@ -515,6 +507,21 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
         ++i;
     }
 
+    // Tratamento do último resultado, para remover double location, tirar negativo do to_be_built.
+    if (result[result.length - 1] !== undefined) {      // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id
+                let last_locations = result[result.length - 1].locations
+                for (let i = 0; i < last_locations.length - 1; i++) {
+                    if (last_locations[i].location_id === last_locations[i+1].location_id) {
+                        last_locations[i].total_classroom_be_built += last_locations[i+1].total_classroom_be_built;
+                        last_locations[i].total_classroom += last_locations[i+1].total_classroom;
+                        last_locations.splice(i+1, 1);
+                    }
+                }
+                for (let i = 0; i < last_locations.length; i++) {   // Passamos agora para não deixar to_be_built < 0
+                    last_locations[i].total_classroom_be_built = (last_locations[i].total_classroom_be_built < 0) ? 0 : last_locations[i].total_classroom_be_built;
+                }
+            }
+
     // Agregar por estado e brasil
     let reduction = null;
     if(req.dims.state || !req.dims.city) { // Se um dos dois acontecer, sabemos que devemos agregar
-- 
GitLab


From aad80db1d0b2eb6e03b0fc9a1d46219f6ed778a4 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Fri, 10 May 2019 09:41:04 -0300
Subject: [PATCH 089/142] [course_fix]Limit year

---
 src/libs/routes/university.js | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index c86fdc7f..826a6b76 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -63,7 +63,8 @@ universityApp.get('/upper_adm_dependency', (req, res, next) => {
 
 universityApp.get('/years', (req, res, next) => {
     req.sql.from('ies_ens_superior')
-    .field('DISTINCT ies_ens_superior.ano_censo', 'year');
+    .field('DISTINCT ies_ens_superior.ano_censo', 'year')
+    .where('ies_ens_superior.ano_censo = 2017');
     next();
 }, query, response('years'));
 
-- 
GitLab


From fc1282ae3926b7c536c67a3721f8d94489ede08d Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 14 May 2019 10:04:01 -0300
Subject: [PATCH 090/142] [fix]Name and identificator fix

---
 src/libs/convert/ocdeGeral.js    | 2 +-
 src/libs/convert/ocdeSpecific.js | 4 +++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/libs/convert/ocdeGeral.js b/src/libs/convert/ocdeGeral.js
index 88cc0646..70671edb 100644
--- a/src/libs/convert/ocdeGeral.js
+++ b/src/libs/convert/ocdeGeral.js
@@ -27,7 +27,7 @@ module.exports = function ocdeGeral(id) {
         case 2:
         return 'Humanidades e artes';
         case 3:
-        return 'Ciências sociais, negócios e direitor';
+        return 'Ciências sociais, negócios e direito';
         case 4:
         return 'Ciências, matemática e computação';
         case 5:
diff --git a/src/libs/convert/ocdeSpecific.js b/src/libs/convert/ocdeSpecific.js
index 7b360d86..d7026b65 100644
--- a/src/libs/convert/ocdeSpecific.js
+++ b/src/libs/convert/ocdeSpecific.js
@@ -37,9 +37,11 @@ module.exports = function ocdeSpecific(id) {
         case 38:
         return 'Direito';
         case 42:
-        return 'Ciências';
+        return 'Ciências da vida';
         case 44:
         return 'Ciências físicas';
+        case 46:
+        return 'Metemática e estatística';
         case 48:
         return 'Computação';
         case 52:
-- 
GitLab


From 88947d07aab48641715474f08417de7ad8290537 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 14 May 2019 10:50:08 -0300
Subject: [PATCH 091/142] [num_course]Add university filter

---
 src/libs/routes/courseCount.js | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index e4b174af..de9e6871 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -179,11 +179,12 @@ courseCountApp.get('/night_time', (req, res, next) => {
     next();
 }, response('night_time'));
 
-courseCountApp.get('/course', (req, res, next) => {
+courseCountApp.get('/university', (req, res, next) => {
     req.sql.from('curso_ens_superior')
-    .field('DISTINCT curso_ens_superior.nome_curso', 'nome')
+    .field('DISTINCT curso_ens_superior.nome_ies', 'nome')
+    .field('curso_ens_superior.cod_ies', 'cod')
     next();
-}, query, response('course'));
+}, query, response('university'));
 
 rqf.addField({
     name: 'filter',
-- 
GitLab


From b846110069f4fc8964a77472c92be109061c7b3d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Tue, 14 May 2019 11:59:52 -0300
Subject: [PATCH 092/142] Initial add idm

---
 src/libs/routes/classroomCount.js | 108 ++++++++++++++++++++++++++----
 1 file changed, 95 insertions(+), 13 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 0606488b..e355085f 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -192,6 +192,8 @@ rqf.addField({
 classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     let classSize = JSON.parse(req.body.class_size) || null;
     let integralTime = JSON.parse(req.body.integral_time) || null;
+    let enrollmentProjection = JSON.parse(req.body.enrollment_projection) || null;
+    req.projection = enrollmentProjection !== null;
 
     if(classSize == null || integralTime == null) {
         res.statusCode = 400;
@@ -199,6 +201,9 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     }
     req.classSize = classSize;
     req.integralTime = integralTime;
+    if (req.projection) {
+        req.enrollmentProjection = enrollmentProjection.projections;
+    }
 
     req.dims.state = true;
     req.dims.city = true;
@@ -229,13 +234,13 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             let integralTime = req.integralTime.find((el) => {return el.id === educationLevelId});
 
             let numberStudentClass = (typeof classSize !== 'undefined') ? classSize.numberStudentClass : null;
-            let offerGoal = (typeof integralTime !== 'undefined') ? integralTime.offerGoal : null;
+            let integralTimeOfferGoal = (typeof integralTime !== 'undefined') ? integralTime.offerGoal : null;
 
             req.educationSchoolYear[i] = {
                 id: educationLevelId,
                 name: id2str.educationLevelShort(educationLevelId),
                 numberStudentClass,
-                offerGoal
+                integralTimeOfferGoal
             };
         }
     }
@@ -259,22 +264,75 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     .where('escola.dependencia_adm_id < 4');
 
     next();
-}, rqf.build(), query, id2str.transform(), (req, res, next) => {
+}, rqf.build(), query, id2str.transform(), (req, res, next) =>  {
+    req.classroom = req.result;
     delete req.dims;
     delete req.filter;
+    req.resetSql();
     next();
-}, rqf.parse(), rqf.build(), (req, res, next) => {
-    req.classroom = req.result;
+}, rqf.parse(), (req, res, next) => {
+    if ("state" in req.filter) {
+        req.dims.state = true;
+        req.dims.city = true;
+        req.dims.school_year = true;
+        req.sql.field('indice_distribuicao_matriculas.indice', 'total')
+               .field("'Brasil'", 'name')
+               .field('indice_distribuicao_matriculas.ano_censo', 'year')
+               .from('indice_distribuicao_matriculas')
+               .where('indice_distribuicao_matriculas.nivel_simulacao = 2')
+               .group('indice_distribuicao_matriculas.ano_censo')
+               .group('indice_distribuicao_matriculas.indice')
+               .order('indice_distribuicao_matriculas.ano_censo')
+               .order('indice_distribuicao_matriculas.indice');
+    }
+    else {
+        console.log(req.dims);
+        req.dims.state = true;
+        req.dims.city = true;
+        req.dims.school_year = true;
+        req.sql.field('indice_distribuicao_matriculas.indice', 'index')
+               .field("'Brasil'", 'name')
+               .field('indice_distribuicao_matriculas.ano_censo', 'year')
+               .from('indice_distribuicao_matriculas')
+               .where('indice_distribuicao_matriculas.nivel_simulacao = 1')
+               .group('indice_distribuicao_matriculas.ano_censo')
+               .group('indice_distribuicao_matriculas.indice')
+               .order('indice_distribuicao_matriculas.ano_censo')
+    }
+
+    next();
+}, rqf.build(), query, id2str.transform(), (req, res, next) =>  {
+    delete req.dims;
+    delete req.filter;
+    next();
+},rqf.parse(), rqf.build(), (req, res, next) => {
+    // req.classroom = req.result;
+    req.index = req.result; 
     
     // req.result = [{classroom: req.classroom, enrollment: req.enrollment}]; return next();
 
+    let enrollmentProjectionNight = [];
+    let enrollmentProjectionDay = [];
+    if (req.projection) {
+        for (let i = 0; i < req.enrollmentProjection.length; i++) {
+            if (req.enrollmentProjection[i].periods === 3) {
+                enrollmentProjectionNight.push(req.enrollmentProjection[i]);
+            } else {
+                enrollmentProjectionDay.push(req.enrollmentProjection[i]);
+            }
+        }
+    }
+    console.log(enrollmentProjectionDay);
+
     // Cria estrutura de resposta requisitada:
     let i = 0;
     let j = 0;
     let result = [];
     let hashSet = new Set();
     let enrollments = [...req.enrollment];
-    let leftovers = [];
+    let ei = 0;
+    let eiCityStart = 0;
+    let enrollmentIndex = req.index[ei];
     while (i < req.classroom.length) {
         let classroom = req.classroom[i];
         // Cria hash única para cada espacialidade, dado um ano
@@ -317,10 +375,16 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             hashSet.add(hash);
             result.push(obj);
             currentClassroomObj = obj;
+            eiCityStart = ei;
+            if (enrollmentIndex.city_id != classroom.city_id) {
+                console.log(enrollmentIndex.city_id, classroom.city_id);
+            }
         } else { // Se a hash já existe, já temos a cidade nos resultados. Como está ordenado, é o último valor nos resultados
             currentClassroomObj = result[result.length - 1];
+            ei = eiCityStart;
         }
         currentClassroomObj.locations.push(location);
+        enrollmentIndex = req.index[ei];
 
         // Partimos para as etapas de ensino/anos escolares
         let enrollmentMatch = true;
@@ -334,6 +398,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
             if(typeof enrollment === 'undefined') {
                 ++j;
+                ei++;
                 continue;
             }
 
@@ -344,6 +409,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
             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;
+                ei++;
                 continue;
             }
 
@@ -445,19 +511,29 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 }
             }
 
-            let currentOfferGoal = enrollmentEducationLevel.offerGoal;
+            let currentIntegralOfferGoal = enrollmentEducationLevel.integralTimeOfferGoal;
             let currentNumberStudentClass = (enrollment.location_id == 1) ? enrollmentEducationLevel.numberStudentClass.urban : enrollmentEducationLevel.numberStudentClass.country;
-
+            
+            let currentEnrollmentOfferDay;
+            let currentEnrollmentOfferNight;
+            if (req.projection && classroom.school_building == 1) {     // Garantimos que será somado apenas uma vez por localização.
+                currentEnrollmentOfferDay = enrollmentProjectionDay[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
+                currentEnrollmentOfferNight = enrollmentProjectionNight[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
+                
+                // Adcionamos as mátriculas da projeção
+                educationLevel.enrollment.total_enrollment_day += (currentEnrollmentOfferDay.enrollments !== undefined) ? (currentEnrollmentOfferDay.enrollments[0].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIndex : 0;
+                educationLevel.enrollment.total_enrollment_night += (currentEnrollmentOfferNight.enrollments !== undefined) ? (currentEnrollmentOfferNight.enrollments[0].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIndex : 0;
+            }
             // Soma os totais de matrícula da etapa de ensino
             educationLevel.enrollment.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
             educationLevel.enrollment.total_enrollment_night += (enrollment.period_id == 3 && educationLevel.education_level_short_id > 2) ? enrollment.total : 0;      //Não contamos matrículas noturnos de pré-escola e creche
 
             // 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);
+            educationLevel.enrollment.full_period_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (currentIntegralOfferGoal/100)) / currentNumberStudentClass);
 
             // Turmas diurnas (matrículas diurnas - matrículas integrais)
-            educationLevel.enrollment.day_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (1 - currentOfferGoal/100)) / currentNumberStudentClass);
+            educationLevel.enrollment.day_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (1 - currentIntegralOfferGoal/100)) / currentNumberStudentClass);
 
             // Turmas noturnas
             educationLevel.enrollment.night_classes = Math.ceil((educationLevel.enrollment.total_enrollment_night / currentNumberStudentClass)) || 0;
@@ -474,11 +550,16 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 // Totais de matrícula
                 currentSchoolYear.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
                 currentSchoolYear.total_enrollment_night += (enrollment.period_id == 3 && currentSchoolYear.school_year_id > 30) ? enrollment.total : 0;        //Não contamos matrículas noturnos de pré-escola e creche
+
+                if (req.projection && classroom.school_building == 1) {
+                    let currentEnrollmentSchoolYear = currentEnrollmentOfferDay.seriesEnrollments[Math.trunc(currentSchoolYear.school_year_id/10) - 1];
+                    currentSchoolYear.total_enrollment_day += (currentEnrollmentSchoolYear !== undefined) ? (currentEnrollmentSchoolYear.enrollments[0].quantity - currentEnrollmentSchoolYear.currentOffer)*(1/5570) : 0;
+                }
                 
                 // Número de turmas parcial
-                currentSchoolYear.full_period_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (currentOfferGoal/100)) / currentNumberStudentClass);
+                currentSchoolYear.full_period_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (currentIntegralOfferGoal/100)) / currentNumberStudentClass);
 
-                currentSchoolYear.day_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (1 - currentOfferGoal/100)) / currentNumberStudentClass);
+                currentSchoolYear.day_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (1 - currentIntegralOfferGoal/100)) / currentNumberStudentClass);
 
                 currentSchoolYear.night_classes = Math.ceil((currentSchoolYear.total_enrollment_night / enrollmentEducationLevel.numberStudentClass)) || 0;
 
@@ -495,7 +576,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 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);
             }
-
+            ei++;
             enrollment = enrollments[j];
         }
 
@@ -505,6 +586,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
         }, 0) - location.total_classroom;
 
         ++i;
+        ei++;
     }
 
     // Tratamento do último resultado, para remover double location, tirar negativo do to_be_built.
-- 
GitLab


From 7cdd66e3b779a420b24390ee64946c535ccdd4c2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 16 May 2019 12:03:59 -0300
Subject: [PATCH 093/142] First working version of idm in classroomCount

---
 src/libs/routes/classroomCount.js | 66 ++++++++++++++++++++-----------
 1 file changed, 42 insertions(+), 24 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index e355085f..5f0d92a9 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -275,6 +275,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
         req.dims.state = true;
         req.dims.city = true;
         req.dims.school_year = true;
+        req.dims.location = true;
         req.sql.field('indice_distribuicao_matriculas.indice', 'total')
                .field("'Brasil'", 'name')
                .field('indice_distribuicao_matriculas.ano_censo', 'year')
@@ -290,7 +291,8 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
         req.dims.state = true;
         req.dims.city = true;
         req.dims.school_year = true;
-        req.sql.field('indice_distribuicao_matriculas.indice', 'index')
+        req.dims.location = true;
+        req.sql.field('indice_distribuicao_matriculas.indice', 'idm')
                .field("'Brasil'", 'name')
                .field('indice_distribuicao_matriculas.ano_censo', 'year')
                .from('indice_distribuicao_matriculas')
@@ -307,7 +309,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     next();
 },rqf.parse(), rqf.build(), (req, res, next) => {
     // req.classroom = req.result;
-    req.index = req.result; 
+    req.idm = req.result; 
     
     // req.result = [{classroom: req.classroom, enrollment: req.enrollment}]; return next();
 
@@ -332,7 +334,8 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     let enrollments = [...req.enrollment];
     let ei = 0;
     let eiCityStart = 0;
-    let enrollmentIndex = req.index[ei];
+    let verifySchoolYear;                                   // Matriz para verificar se o idm já foi inserido no school year.
+    let serieQuantMod = [0,4,2,5,4,4,3,1];                // Quantidade de séries em cada mod, utilizado para dividir o índice.
     while (i < req.classroom.length) {
         let classroom = req.classroom[i];
         // Cria hash única para cada espacialidade, dado um ano
@@ -376,15 +379,12 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             result.push(obj);
             currentClassroomObj = obj;
             eiCityStart = ei;
-            if (enrollmentIndex.city_id != classroom.city_id) {
-                console.log(enrollmentIndex.city_id, classroom.city_id);
-            }
+            verifySchoolYear = Array.from(Array(2), () => new Array(75));
         } else { // Se a hash já existe, já temos a cidade nos resultados. Como está ordenado, é o último valor nos resultados
             currentClassroomObj = result[result.length - 1];
             ei = eiCityStart;
         }
         currentClassroomObj.locations.push(location);
-        enrollmentIndex = req.index[ei];
 
         // Partimos para as etapas de ensino/anos escolares
         let enrollmentMatch = true;
@@ -392,27 +392,42 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
         let educationLevelSet = new Set();
         let schoolYearSet = new Set();
         let enrollment = enrollments[j];
-
         while(enrollmentMatch && j < enrollments.length) {
             enrollment = enrollments[j];
 
             if(typeof enrollment === 'undefined') {
                 ++j;
-                ei++;
                 continue;
             }
 
             if(classroom.city_id !== enrollment.city_id) { // Se as cidades não são iguais, já passamos do range
                 enrollmentMatch = false;
+                while (req.idm[ei].city_id !== enrollment.city_id) {
+                    ei++;
+                }
                 continue;
             } 
 
             if(enrollment.year != classroom.year || enrollment.location_id != classroom.location_id) { // Se ano ou localização são diferentes, passa para o próximo
                 ++j;
-                ei++;
                 continue;
             }
 
+            // Da match na tabela de idm com a de enrollment
+            while (req.idm[ei].school_year_id < enrollment.school_year_id) {
+                ei++;
+            }
+            while (req.idm[ei].school_year_id > enrollment.school_year_id) {
+                ei--;
+            }
+            if (req.idm[ei].location_id < location.location_id) {
+                ei++;
+            }
+            else if(req.idm[ei].location_id > location.location_id) {
+                ei--;
+            }
+            let enrollmentIdm = req.idm[ei];
+
 
             // Temos uma matrícula com cidade, ano e localidades certos
             // "Consome" a matrícula (remove do vetor de matrículas)
@@ -514,15 +529,14 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             let currentIntegralOfferGoal = enrollmentEducationLevel.integralTimeOfferGoal;
             let currentNumberStudentClass = (enrollment.location_id == 1) ? enrollmentEducationLevel.numberStudentClass.urban : enrollmentEducationLevel.numberStudentClass.country;
             
-            let currentEnrollmentOfferDay;
-            let currentEnrollmentOfferNight;
-            if (req.projection && classroom.school_building == 1) {     // Garantimos que será somado apenas uma vez por localização.
-                currentEnrollmentOfferDay = enrollmentProjectionDay[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
-                currentEnrollmentOfferNight = enrollmentProjectionNight[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
-                
-                // Adcionamos as mátriculas da projeção
-                educationLevel.enrollment.total_enrollment_day += (currentEnrollmentOfferDay.enrollments !== undefined) ? (currentEnrollmentOfferDay.enrollments[0].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIndex : 0;
-                educationLevel.enrollment.total_enrollment_night += (currentEnrollmentOfferNight.enrollments !== undefined) ? (currentEnrollmentOfferNight.enrollments[0].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIndex : 0;
+            let currentEnrollmentOfferDay = enrollmentProjectionDay[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
+            let currentEnrollmentOfferNight = enrollmentProjectionNight[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
+            if (req.projection && !verifySchoolYear[location.location_id-1][enrollment.school_year_id] && (currentEnrollmentOfferDay.enrollments !== undefined)) {     // Garantimos que será somado apenas uma vez por localização.
+                // Projeção matricula multiplicada pelo indice da cidade.
+                verifySchoolYear[location.location_id-1][enrollment.school_year_id] = 1;
+
+                educationLevel.enrollment.total_enrollment_day += (currentEnrollmentOfferDay.enrollments[0].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm/(serieQuantMod[educationLevel.education_level_short_id]);
+                educationLevel.enrollment.total_enrollment_night += (currentEnrollmentOfferNight.enrollments[0].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm/(serieQuantMod[educationLevel.education_level_short_id]);
             }
             // Soma os totais de matrícula da etapa de ensino
             educationLevel.enrollment.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
@@ -551,9 +565,12 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 currentSchoolYear.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
                 currentSchoolYear.total_enrollment_night += (enrollment.period_id == 3 && currentSchoolYear.school_year_id > 30) ? enrollment.total : 0;        //Não contamos matrículas noturnos de pré-escola e creche
 
-                if (req.projection && classroom.school_building == 1) {
+                if (req.projection && !verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id]) {     // Garantimos que será somado apenas uma vez por localização.
+                    verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] = 1;
+
                     let currentEnrollmentSchoolYear = currentEnrollmentOfferDay.seriesEnrollments[Math.trunc(currentSchoolYear.school_year_id/10) - 1];
-                    currentSchoolYear.total_enrollment_day += (currentEnrollmentSchoolYear !== undefined) ? (currentEnrollmentSchoolYear.enrollments[0].quantity - currentEnrollmentSchoolYear.currentOffer)*(1/5570) : 0;
+                    currentSchoolYear.total_enrollment_day += (currentEnrollmentSchoolYear !== undefined) ? (currentEnrollmentSchoolYear.enrollments[0].quantity - currentEnrollmentSchoolYear.currentOffer)*enrollmentIdm.idm : 0;
+                    currentSchoolYear.total_enrollment_night += (currentEnrollmentSchoolYear !== undefined) ? (currentEnrollmentSchoolYear.enrollments[0].quantity - currentEnrollmentSchoolYear.currentOffer)*enrollmentIdm.idm : 0;
                 }
                 
                 // Número de turmas parcial
@@ -571,12 +588,15 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 currentSchoolYear.total_classrooms_needed = Math.ceil(currentSchoolYear.total_classrooms_needed);
 
                 function reducer(key) { return (sum, elem) => sum + elem[key]}
+                educationLevel.enrollment.total_enrollment_day = educationLevel.classes_school_year.reduce(reducer('total_enrollment_day'), 0);
                 educationLevel.enrollment.full_period_classes = educationLevel.classes_school_year.reduce(reducer('full_period_classes'), 0);
                 educationLevel.enrollment.day_classes = educationLevel.classes_school_year.reduce(reducer('day_classes'), 0);
                 educationLevel.enrollment.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);
             }
-            ei++;
+            if (enrollment.school_year_id != enrollmentIdm.school_year_id) {
+                console.log(enrollment.school_year_id,enrollmentIdm.school_year_id);
+            }
             enrollment = enrollments[j];
         }
 
@@ -584,9 +604,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
         location.total_classroom_be_built = location.education_level.reduce((total, atual) => {
             return total + atual.enrollment.total_classrooms_needed;
         }, 0) - location.total_classroom;
-
         ++i;
-        ei++;
     }
 
     // Tratamento do último resultado, para remover double location, tirar negativo do to_be_built.
-- 
GitLab


From e68a303087e0f3ad3d98141fd5cdea3f1271c2cb Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Thu, 16 May 2019 16:23:44 -0300
Subject: [PATCH 094/142] [course_fix]Name fix and ocde code

---
 src/libs/convert/ocdeSpecific.js |  2 +-
 src/libs/routes/courseCount.js   | 12 ++++++------
 2 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/src/libs/convert/ocdeSpecific.js b/src/libs/convert/ocdeSpecific.js
index d7026b65..0133fa97 100644
--- a/src/libs/convert/ocdeSpecific.js
+++ b/src/libs/convert/ocdeSpecific.js
@@ -41,7 +41,7 @@ module.exports = function ocdeSpecific(id) {
         case 44:
         return 'Ciências físicas';
         case 46:
-        return 'Metemática e estatística';
+        return 'Matemática e estatística';
         case 48:
         return 'Computação';
         case 52:
diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index de9e6871..b80e38eb 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -287,8 +287,8 @@ rqf.addField({
 }).addValue({
     name:'ocde_specific',
     table: 'curso_ens_superior',
-    tableField: 'cod_ocde_area_especifica',
-    resultField: 'ocde_specific_id',
+    tableField: ['cod_ocde_area_especifica', 'nome_ocde_area_especifica'],
+    resultField: ['ocde_specific_id', 'ocde_specific_name'],
     where: {
         relation: '=',
         type: 'integer',
@@ -297,8 +297,8 @@ rqf.addField({
 }).addValue({
     name:'ocde_geral',
     table: 'curso_ens_superior',
-    tableField: 'cod_ocde_area_geral',
-    resultField: 'ocde_geral_id',
+    tableField: ['cod_ocde_area_geral', 'nome_ocde_area_geral'],
+    resultField: ['ocde_geral_id', 'ocde_geral_name'],
     where: {
         relation: '=',
         type: 'integer',
@@ -307,8 +307,8 @@ rqf.addField({
 }).addValue({
     name:'ocde_detailed',
     table: 'curso_ens_superior',
-    tableField: 'cod_ocde_area_detalhada',
-    resultField: 'ocde_detailed_id',
+    tableField: ['cod_ocde_area_detalhada', 'nome_ocde_area_detalhada'],
+    resultField: ['ocde_detailed_id', 'ocde_datailed_name'],
     where: {
         relation: '=',
         type: 'integer',
-- 
GitLab


From 119a6a2a7fcbe240048c8674dc98b226058f3f9f Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Fri, 17 May 2019 10:47:39 -0300
Subject: [PATCH 095/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 1 -
 1 file changed, 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 2cfd1adf..ef94b541 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -16,7 +16,6 @@ run_tests:
   stage: test
   script:
     - ping -W1 -c1 mongo
-    - mv config.json.example config.json
     - sed -i -e 's/false/true/g' config.json
     - gulp build
     - gulp test
-- 
GitLab


From c399c58872a1afa3d5e6525c34a7310a25ec5848 Mon Sep 17 00:00:00 2001
From: hi15 <hi15@inf.ufpr.br>
Date: Fri, 17 May 2019 11:14:42 -0300
Subject: [PATCH 096/142] fixed tests in config.json

---
 config.json | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/config.json b/config.json
index d4429c5a..9d206c7d 100644
--- a/config.json
+++ b/config.json
@@ -47,7 +47,7 @@
     },
     "test":
     {
-        "port": 4000,
+        "port": 3000,
         "ip": "127.0.0.1",
         "debug" : true,
         "monetdb": {
@@ -56,14 +56,14 @@
             "dbname": "simcaq_dev4",
             "user": "monetdb",
             "password":"monetdb",
-            "nrConnections": "4"
+            "nrConnections": "1"
         },
         "cdn" : {
             "url": "http://simcaqdb3.c3sl.ufpr.br:3000",
             "download": "https://simcaqdev.c3sl.ufpr.br/download/"
         },
         "mongodb": {
-            "uri": "mongodb://simcaqdb3/test_monq",
+            "uri": "mongodb://simcaqdb3/dev_monq",
             "secret": "SimCAQC3SL"
         },
         "default": {
@@ -77,6 +77,9 @@
                 "url": "http://simcaqdev.c3sl.ufpr.br/#"
             }
         },
+        "lde_api": {
+            "url": "https://dadoseducacionaisdev.c3sl.ufpr.br/api/v1/"
+        },
         "email": {
             "port": 25,
             "host": "mx.c3sl.ufpr.br",
-- 
GitLab


From 7f06508ac3a77ca242f5bf3f0bcb5609bf03c57c Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Fri, 17 May 2019 11:25:21 -0300
Subject: [PATCH 097/142] [enrollment_course_fix]Added filters

---
 src/libs/routes/universityEnrollment.js | 74 ++++++++++++++++++++++++-
 1 file changed, 72 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index 9fe86723..ddfd8272 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -79,7 +79,7 @@ universityEnrollmentApp.get('/upper_adm_dependency', (req, res, next) => {
     next();
 }, response('upper_adm_dependency'));
 
-universityEnrollmentApp.get('/ocde', (req, res, next) => {
+universityEnrollmentApp.get('/ocde_geral', (req, res, next) => {
     req.result = [];
     for(let i = 0; i <= 8; ++i) {
         req.result.push({
@@ -88,7 +88,7 @@ universityEnrollmentApp.get('/ocde', (req, res, next) => {
         });
     };
     next();
-}, response('ocde'));
+}, response('ocde_geral'));
 
 universityEnrollmentApp.get('/ocde_specific', (req, res, next) => {
     req.result = [];
@@ -172,6 +172,46 @@ universityEnrollmentApp.get('/school_type', (req, res, next) => {
     next();
 }, response('school_type'));
 
+universityEnrollmentApp.get('/university', (req, res, next) => {
+    req.sql.from('aluno_ens_superior')
+    .field('DISTINCT aluno_ens_superior.nome_ies', 'nome')
+    .field('aluno_ens_superior.cod_ies', 'cod')
+    next();
+}, query, response('university'));
+
+universityEnrollmentApp.get('/academic_level', (req, res, next) => {
+    req.result = [];
+    for(let i = 1; i <= 4; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.academicLevel(i)
+        });
+    };
+    next();
+}, response('academic_level'));
+
+universityEnrollmentApp.get('/gender_ies', function (req, res, next) {
+    req.result = [];
+    for (var i = 1; i <= 2; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.genderIES(i)
+        });
+    };
+    next();
+}, response('gender_ies'));
+
+universityEnrollmentApp.get('/upper_education_mod', function (req, res, next) {
+    req.result = [];
+    for (var i = 1; i <= 3; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.upperEducationMod(i)
+        });
+    };
+    next();
+}, response('upper_education_mod'));
+
 rqf.addField({
     name: 'filter',
     field: false,
@@ -371,6 +411,36 @@ rqf.addField({
         type: 'integer',
         field: 'tipo_escola_ensino_medio'
     }
+}).addValue({
+    name: 'university',
+    table: 'aluno_ens_superior',
+    tableField: ['cod_ies', 'nome_ies'],
+    resultField: ['university_id', 'university_name'],
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ies'
+    }
+}).addValue({
+    name: 'gender_ies',
+    table: 'aluno_ens_superior',
+    tableField: 'genero_aluno',
+    resultField: 'gender_ies_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'genero_aluno'
+    }
+}).addValue({
+    name:'academic_level',
+    table: 'aluno_ens_superior',
+    tableField: 'cod_grau_academico',
+    resultField: 'academic_level_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_grau_academico'
+    }
 });
 
 universityEnrollmentApp.get('/', rqf.parse(), (req, res, next) => {
-- 
GitLab


From 7362d4cc5562d6455cdc10780d10ac8473f369e3 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fcerd@inf.ufpr.br>
Date: Mon, 20 May 2019 09:53:23 -0300
Subject: [PATCH 098/142] Fix bugs in teacher university indicator

---
 src/libs/convert/genderIES.js         | 2 ++
 src/libs/convert/studentDeficiency.js | 2 +-
 src/libs/convert/teacherSchooling.js  | 4 +++-
 src/libs/convert/workRegime.js        | 2 ++
 4 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/src/libs/convert/genderIES.js b/src/libs/convert/genderIES.js
index 4ff855cd..8eba4fe4 100644
--- a/src/libs/convert/genderIES.js
+++ b/src/libs/convert/genderIES.js
@@ -24,5 +24,7 @@ module.exports = function genderIES(id) {
         return 'Feminino';
         case 2:
         return 'Masculino';
+        default:
+        return 'Não declarado';
     }
 };
diff --git a/src/libs/convert/studentDeficiency.js b/src/libs/convert/studentDeficiency.js
index 11c3c340..c5ad0e01 100644
--- a/src/libs/convert/studentDeficiency.js
+++ b/src/libs/convert/studentDeficiency.js
@@ -25,6 +25,6 @@ module.exports = function studentDeficiency(id) {
         case 1:
         return 'Sim';
         default:
-        return 'Não classificado'
+        return 'Não declarado'
     }
 };
diff --git a/src/libs/convert/teacherSchooling.js b/src/libs/convert/teacherSchooling.js
index fc3f1539..d31bd2ee 100644
--- a/src/libs/convert/teacherSchooling.js
+++ b/src/libs/convert/teacherSchooling.js
@@ -23,12 +23,14 @@ module.exports = function teacherSchooling(id) {
         case 1:
         return 'Sem graduação';
         case 2:
-        return 'graduação';
+        return 'Graduação';
         case 3:
         return 'Especialização';
         case 4:
         return 'Mestrado';
         case 5:
         return 'Doutorado';
+        default:
+        return 'Não declarado';
     }
 };
diff --git a/src/libs/convert/workRegime.js b/src/libs/convert/workRegime.js
index 6cff902a..f03d97a8 100644
--- a/src/libs/convert/workRegime.js
+++ b/src/libs/convert/workRegime.js
@@ -28,5 +28,7 @@ module.exports = function workRegime(id) {
         return 'Tempo Parcial';
         case 4:
         return 'Horista';
+        default:
+        return 'Não declarado';
     }
 };
-- 
GitLab


From 4380c2cf5005160b5316953820e4f2ef8785ecf2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Mon, 20 May 2019 10:09:52 -0300
Subject: [PATCH 099/142] Fix idm calc in classroomCount

---
 src/libs/routes/classroomCount.js | 59 ++++++++++++++++++-------------
 1 file changed, 35 insertions(+), 24 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 5f0d92a9..6ac9d9f6 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -281,6 +281,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                .field('indice_distribuicao_matriculas.ano_censo', 'year')
                .from('indice_distribuicao_matriculas')
                .where('indice_distribuicao_matriculas.nivel_simulacao = 2')
+               .where('indice_distribuicao_matriculas.serie_ano_id < 15')
                .group('indice_distribuicao_matriculas.ano_censo')
                .group('indice_distribuicao_matriculas.indice')
                .order('indice_distribuicao_matriculas.ano_censo')
@@ -297,6 +298,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                .field('indice_distribuicao_matriculas.ano_censo', 'year')
                .from('indice_distribuicao_matriculas')
                .where('indice_distribuicao_matriculas.nivel_simulacao = 1')
+               .where('indice_distribuicao_matriculas.serie_ano_id < 15')
                .group('indice_distribuicao_matriculas.ano_censo')
                .group('indice_distribuicao_matriculas.indice')
                .order('indice_distribuicao_matriculas.ano_censo')
@@ -335,7 +337,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     let ei = 0;
     let eiCityStart = 0;
     let verifySchoolYear;                                   // Matriz para verificar se o idm já foi inserido no school year.
-    let serieQuantMod = [0,4,2,5,4,4,3,1];                // Quantidade de séries em cada mod, utilizado para dividir o índice.
     while (i < req.classroom.length) {
         let classroom = req.classroom[i];
         // Cria hash única para cada espacialidade, dado um ano
@@ -379,7 +380,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             result.push(obj);
             currentClassroomObj = obj;
             eiCityStart = ei;
-            verifySchoolYear = Array.from(Array(2), () => new Array(75));
+            verifySchoolYear = Array.from(Array(2), () => new Array(15));
         } else { // Se a hash já existe, já temos a cidade nos resultados. Como está ordenado, é o último valor nos resultados
             currentClassroomObj = result[result.length - 1];
             ei = eiCityStart;
@@ -413,21 +414,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 continue;
             }
 
-            // Da match na tabela de idm com a de enrollment
-            while (req.idm[ei].school_year_id < enrollment.school_year_id) {
-                ei++;
-            }
-            while (req.idm[ei].school_year_id > enrollment.school_year_id) {
-                ei--;
-            }
-            if (req.idm[ei].location_id < location.location_id) {
-                ei++;
-            }
-            else if(req.idm[ei].location_id > location.location_id) {
-                ei--;
-            }
-            let enrollmentIdm = req.idm[ei];
-
 
             // Temos uma matrícula com cidade, ano e localidades certos
             // "Consome" a matrícula (remove do vetor de matrículas)
@@ -526,17 +512,32 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 }
             }
 
+            // Faz match da tabela de idm com a de enrollment
+            if (educationLevel.education_level_short_id !== 1) {
+                while (req.idm[ei].school_year_id < educationLevel.education_level_short_id) ei++;
+                while (req.idm[ei].school_year_id > educationLevel.education_level_short_id) ei--;
+
+                if (req.idm[ei].location_id < location.location_id) {
+                    ei++;
+                }
+                else if(req.idm[ei].location_id > location.location_id) {
+                    ei--;
+                }
+            }
+            let enrollmentIdm = req.idm[ei];
+
+
             let currentIntegralOfferGoal = enrollmentEducationLevel.integralTimeOfferGoal;
             let currentNumberStudentClass = (enrollment.location_id == 1) ? enrollmentEducationLevel.numberStudentClass.urban : enrollmentEducationLevel.numberStudentClass.country;
             
             let currentEnrollmentOfferDay = enrollmentProjectionDay[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
             let currentEnrollmentOfferNight = enrollmentProjectionNight[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
-            if (req.projection && !verifySchoolYear[location.location_id-1][enrollment.school_year_id] && (currentEnrollmentOfferDay.enrollments !== undefined)) {     // Garantimos que será somado apenas uma vez por localização.
+            if (req.projection && !verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] && (currentEnrollmentOfferDay.enrollments !== undefined)) {     // Garantimos que será somado apenas uma vez por localização.
                 // Projeção matricula multiplicada pelo indice da cidade.
-                verifySchoolYear[location.location_id-1][enrollment.school_year_id] = 1;
+                verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] = 1;
 
-                educationLevel.enrollment.total_enrollment_day += (currentEnrollmentOfferDay.enrollments[0].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm/(serieQuantMod[educationLevel.education_level_short_id]);
-                educationLevel.enrollment.total_enrollment_night += (currentEnrollmentOfferNight.enrollments[0].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm/(serieQuantMod[educationLevel.education_level_short_id]);
+                educationLevel.enrollment.total_enrollment_day += (currentEnrollmentOfferDay.enrollments[0].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm;
+                educationLevel.enrollment.total_enrollment_night += (currentEnrollmentOfferNight.enrollments[0].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm;
             }
             // Soma os totais de matrícula da etapa de ensino
             educationLevel.enrollment.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
@@ -561,6 +562,19 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
             // Faz os mesmos cálculos para a série escolar
             if(currentSchoolYear) {
+                // Faz match da enrollment com o idm, no caso de não usar o mod
+                while (req.idm[ei].school_year_id < enrollment.school_year_id) ei++;
+                while (req.idm[ei].school_year_id > enrollment.school_year_id) ei--;
+
+                if (req.idm[ei].location_id < location.location_id) {
+                    ei++;
+                }
+                else if(req.idm[ei].location_id > location.location_id) {
+                    ei--;
+                }
+                enrollmentIdm = req.idm[ei];
+
+
                 // Totais de matrícula
                 currentSchoolYear.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
                 currentSchoolYear.total_enrollment_night += (enrollment.period_id == 3 && currentSchoolYear.school_year_id > 30) ? enrollment.total : 0;        //Não contamos matrículas noturnos de pré-escola e creche
@@ -594,9 +608,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 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);
             }
-            if (enrollment.school_year_id != enrollmentIdm.school_year_id) {
-                console.log(enrollment.school_year_id,enrollmentIdm.school_year_id);
-            }
             enrollment = enrollments[j];
         }
 
-- 
GitLab


From 1ad068913b8396f335a964579ad68cc59f396b00 Mon Sep 17 00:00:00 2001
From: hi15 <hi15@inf.ufpr.br>
Date: Mon, 20 May 2019 11:48:18 -0300
Subject: [PATCH 100/142] Try -v

---
 .gitlab-ci.yml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index ef94b541..fae367e3 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -9,6 +9,7 @@ variables:
   NODE_ENV: 'test'
 
 before_script:
+  - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
 
-- 
GitLab


From ed5b4d737e3f573a4b5033ad8ea9cbd55877d35f Mon Sep 17 00:00:00 2001
From: hi15 <hi15@inf.ufpr.br>
Date: Mon, 20 May 2019 11:58:06 -0300
Subject: [PATCH 101/142] teste mudar imagem

Signed-off-by: hi15 <hi15@inf.ufpr.br>
---
 .gitlab-ci.yml | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index fae367e3..39587c79 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,3 +1,5 @@
+image: node:9.2.1
+
 stages:
   - test
 
-- 
GitLab


From fc42a2e04c5d19286ca791c8d863dc0ec684143b Mon Sep 17 00:00:00 2001
From: Fernando Erd <fcerd@inf.ufpr.br>
Date: Mon, 20 May 2019 12:14:42 -0300
Subject: [PATCH 102/142] Change null deficiency in teacher university

---
 src/libs/middlewares/id2str.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 0e2b9e9c..7f9f73fa 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -75,7 +75,7 @@ const postgraduatePresentialTeacher = require(`${libs}/convert/booleanVariable`)
 const teacherSchooling = require(`${libs}/convert/teacherSchooling`);
 const ethnicGroupTeacherIES = require(`${libs}/convert/ethnicGroupTeacherIES`);
 const genderIES = require(`${libs}/convert/genderIES`);
-const deficiency = require(`${libs}/convert/booleanVariable`);
+const deficiency = require(`${libs}/convert/studentDeficiency`);
 
 const ids = {
     gender_id: gender,
-- 
GitLab


From 3babbc956c636cf26e8b6f8d0ea913a62441aa71 Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Wed, 22 May 2019 10:45:50 -0300
Subject: [PATCH 103/142] fix infra routes

---
 src/libs/routes/schoolInfrastructure.js | 69 ++++++++++++++++---------
 1 file changed, 46 insertions(+), 23 deletions(-)

diff --git a/src/libs/routes/schoolInfrastructure.js b/src/libs/routes/schoolInfrastructure.js
index f805e882..27902c97 100644
--- a/src/libs/routes/schoolInfrastructure.js
+++ b/src/libs/routes/schoolInfrastructure.js
@@ -363,30 +363,45 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.allSchoolsNotSchoolBuilding = req.querySet.push(allSchoolsNotSchoolBuilding) - 1;
 
     // Bibliotecas
-    req.queryIndex.allLibraries = req.queryIndex.allUrbanSchools;
-
-    let haveLibraries = allUrbanSchools.clone();
+    // Se (situacao_de_funcionamento=1) & (dependencia_adm_id<=3) & (CEBES027P1=1) & 
+    // (ensino_regular=1 | ensino_eja=1 |    educacao_profissional=1) & 
+    // (reg_fund_ai_t1=1 | reg_fund_af_t1=1 | reg_medio_medio_t1=1 | ensino_eja_fund= 1 |  
+    // ensino_eja_medio= 1 | ensino_eja_prof= 1 | esp_eja_fund=1 | esp_eja_medio=1 | ensino_esp_exclusiva_eja_prof=1) & (localizacao_id=1) então conta id
+    let allLibraries = allUrbanSchools.clone();
+    allLibraries.where('reg_fund_ai_t1=1 OR reg_fund_af_t1=1 OR reg_medio_medio_t1=1 OR ensino_eja_fund= 1 OR ensino_eja_medio= 1 OR ensino_eja_prof= 1 OR esp_eja_fund=1 OR esp_eja_medio=1 OR ensino_esp_exclusiva_eja_prof=1');
+    req.queryIndex.allLibraries = req.querySet.push(allLibraries) - 1;
+
+    let haveLibraries = allLibraries.clone();
     haveLibraries.where('escola.biblioteca = 1');
     req.queryIndex.haveLibraries = req.querySet.push(haveLibraries) - 1;
 
-    let needLibraries = allUrbanSchools.clone();
+    let needLibraries = allLibraries.clone();
     needLibraries.where('escola.biblioteca = 0');
     req.queryIndex.needLibraries = req.querySet.push(needLibraries) - 1;
 
     // Bibliotecas/Sala de leitura
-    req.queryIndex.allLibrariesReadingRoom = req.queryIndex.allCountrySchools;
-
-    let haveLibrariesReadingRoom = allCountrySchools.clone();
+    // Se (situacao_de_funcionamento=1) & (dependencia_adm_id<=3) & (CEBES027P1=1) & (ensino_regular=1 | ensino_eja=1 | educacao_profissional=1) & 
+    // (reg_fund_ai_t1=1 | reg_fund_af_t1=1 | reg_medio_medio_t1=1 | ensino_eja_fund= 1 |  ensino_eja_medio= 1 | 
+    // ensino_eja_prof= 1 | esp_eja_fund=1 | esp_eja_medio=1 | ensino_esp_exclusiva_eja_prof=1) & (localizacao_id=2) então conta id
+    let allLibrariesReadingRoom = allCountrySchools.clone();
+    allLibrariesReadingRoom.where('reg_fund_ai_t1=1 OR reg_fund_af_t1=1 OR reg_medio_medio_t1=1 OR ensino_eja_fund=1 OR ensino_eja_medio=1 OR ensino_eja_prof=1 OR esp_eja_fund=1 OR esp_eja_medio=1 OR ensino_esp_exclusiva_eja_prof=1');
+    req.queryIndex.allLibrariesReadingRoom = req.querySet.push(allLibrariesReadingRoom) - 1;
+
+    let haveLibrariesReadingRoom = allLibrariesReadingRoom.clone();
     haveLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = true');
     req.queryIndex.haveLibrariesReadingRoom = req.querySet.push(haveLibrariesReadingRoom) - 1;
 
-    let needLibrariesReadingRoom = allCountrySchools.clone();
+    let needLibrariesReadingRoom = allLibrariesReadingRoom.clone();
     needLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = false');
     req.queryIndex.needLibrariesReadingRoom = req.querySet.push(needLibrariesReadingRoom) - 1;
 
     // Laboratório de informática
+    // Se (situacao_de_funcionamento=1) & (dependencia_adm_id<=3) & (CEBES027P1=1) & 
+    // (ensino_regular=1 | ensino_eja=1 |    educacao_profissional=1) & 
+    // ( reg_fund_ai_t1=1 | reg_fund_af_t1=1 | reg_medio_medio_t1=1 | ensino_eja_fund= 1 |     ensino_eja_medio= 1 | ensino_eja_prof= 1 | esp_eja_fund=1 | 
+    // esp_eja_medio=1 | ensino_esp_exclusiva_eja_prof=1) então conta id
     let allInfLab = allSchools.clone();
-    allInfLab.where('escola.reg_infantil_preescola = 1 OR escola.reg_fund_ai = 1 OR escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado = 1 OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1');
+    allInfLab.where('reg_fund_ai_t1=1 OR reg_fund_af_t1=1 OR reg_medio_medio_t1=1 OR ensino_eja_fund=1 OR ensino_eja_medio=1 OR ensino_eja_prof=1 OR esp_eja_fund=1 OR esp_eja_medio=1 OR ensino_esp_exclusiva_eja_prof=1');
     req.queryIndex.allInfLab = req.querySet.push(allInfLab) - 1;
 
     let haveInfLab = allInfLab.clone();
@@ -399,7 +414,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
 
     // Laboratório de ciências
     let allScienceLab = allSchools.clone();
-    allScienceLab.where('escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado = 1 OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1');
+    allScienceLab.where('reg_fund_af_t1=1 OR reg_medio_medio_t1=1 OR ensino_eja_fund=1 OR ensino_eja_medio=1 OR ensino_eja_prof=1 OR esp_eja_fund=1 OR esp_eja_medio=1 OR ensino_esp_exclusiva_eja_prof=1');
     req.queryIndex.allScienceLab = req.querySet.push(allScienceLab) - 1;
 
     let haveScienceLab = allScienceLab.clone();
@@ -411,8 +426,10 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.needScienceLab = req.querySet.push(needScienceLab) - 1;
 
     // Parque infantil
+    // Se (situacao_de_funcionamento=1) and (ensino_regular=1 OR ensino_eja=1 OR educacao_profissional=1) and 
+    // (local_func_predio_escolar=1) and (dependencia_adm_id<=3) and (reg_infantil_creche_t1=1 or reg_infantil_preescola_t1=1 or reg_fund_ai_t1=1) então conta id
     let allKidsPark = allSchools.clone();
-    allKidsPark.where('escola.reg_infantil_creche = 1 OR escola.reg_infantil_preescola = 1 OR escola.reg_fund_ai = 1');
+    allKidsPark.where('reg_infantil_creche_t1=1 OR reg_infantil_preescola_t1=1 OR reg_fund_ai_t1=1');
     req.queryIndex.allKidsPark = req.querySet.push(allKidsPark) - 1;
 
     let haveKidsPark = allKidsPark.clone();
@@ -425,7 +442,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
 
     // Berçário
     let allCribs = allSchools.clone();
-    allCribs.where('escola.reg_infantil_creche = 1');
+    allCribs.where('escola.reg_infantil_creche_t1 = 1');
     req.queryIndex.allCribs = req.querySet.push(allCribs) - 1;
 
     let haveCribs = allCribs.clone();
@@ -438,7 +455,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
 
     // Quadra Coberta
     let allSportsCourt = allSchools.clone();
-    allSportsCourt.where('escola.reg_fund_ai = 1 OR escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1');
+    allSportsCourt.where('reg_fund_ai_t1=1  or reg_fund_af_t1=1 or  reg_medio_medio_t1=1  or  ensino_eja_fund= 1 or ensino_eja_medio= 1 or ensino_eja_prof= 1 or esp_eja_fund=1 or esp_eja_medio=1 or ensino_esp_exclusiva_eja_prof=1');
     req.queryIndex.allSportsCourt = req.querySet.push(allSportsCourt) - 1;
 
     let haveSportsCourt = allSportsCourt.clone();
@@ -452,7 +469,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     // Cobertura de quadra esportiva
     let allSportsCourtCoverage = allSportsCourt.clone();
     allSportsCourtCoverage.where('escola.quadra_esportes_descoberta = 1');
-    req.queryIndex.allSportsCourtCoverage = req.querySet.push(allSportsCourtCoverage);
+    req.queryIndex.allSportsCourtCoverage = req.querySet.push(allSportsCourtCoverage) -1;
 
     req.queryIndex.haveSportsCourtCoverage = req.queryIndex.allSportsCourtCoverage;
 
@@ -466,7 +483,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.haveCourtyard = req.querySet.push(haveCourtyard) - 1;
 
     let needCourtyard = allSchools.clone();
-    needCourtyard.where('escola.patio = 1');
+    needCourtyard.where('escola.patio = 0');
     req.queryIndex.needCourtyard = req.querySet.push(needCourtyard) - 1;
 
     // Cobertura do Pátio
@@ -479,7 +496,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.needCourtyardCoverage = req.queryIndex.allCourtyardCoverage;
 
     // Sala de direção
-    req.queryIndex.allDirectorRoom = req.queryIndex.allLibraries;
+    req.queryIndex.allDirectorRoom = req.queryIndex.allUrbanSchools;
 
     let haveDirectorRoom = allUrbanSchools.clone();
     haveDirectorRoom.where('escola.sala_diretoria = 1');
@@ -541,11 +558,11 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.haveWarehouse = req.querySet.push(haveWarehouse) - 1;
 
     let needWarehouse = allSchools.clone();
-    needWarehouse.where('escola.almoxarifado = 1');
+    needWarehouse.where('escola.almoxarifado = 0');
     req.queryIndex.needWarehouse = req.querySet.push(needWarehouse) - 1;
 
     // Internet
-    req.queryIndex.allInternet = req.queryIndex.allLibrariesReadingRoom;
+    req.queryIndex.allInternet = req.queryIndex.allCountrySchools;
 
     let haveInternet = allCountrySchools.clone();
     haveInternet.where('escola.internet = 1');
@@ -556,7 +573,9 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.needInternet = req.querySet.push(needInternet) - 1;
 
     // Internet banda larga
-    req.queryIndex.allBroadbandInternet = req.queryIndex.allLibraries;
+    // Se (situacao_de_funcionamento=1) and (ensino_regular=1 OR ensino_eja=1 OR educacao_profissional=1) and (local_func_predio_escolar=1) and 
+    // (dependencia_adm_id<=3) and (localizacao_id=2) então conta id
+    req.queryIndex.allBroadbandInternet = req.queryIndex.allUrbanSchools;
 
     let haveBroadbandInternet = allUrbanSchools.clone();
     haveBroadbandInternet.where('escola.internet_banda_larga = 1');
@@ -578,13 +597,17 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.needInsideBathroom = req.querySet.push(needInsideBathroom) - 1;
 
     // Banheiro adequado para educação infantil dentro do prédio
-    req.queryIndex.allInsideKidsBathroom = req.queryIndex.allKidsPark;
+    // Se (situacao_de_funcionamento=1) and (ensino_regular=1 OR ensino_eja=1 OR educacao_profissional=1) and (local_func_predio_escolar=1) and
+    // (dependencia_adm_id<=3) and (reg_infantil_creche_t1=1 or reg_infantil_preescola_t1=1 or  reg_fund_ai_t1=1) então conta id
+    let allInsideKidsBathroom = allSchools.clone();
+    allInsideKidsBathroom.where('reg_infantil_creche_t1=1 OR reg_infantil_preescola_t1=1 OR reg_fund_ai_t1=1');
+    req.queryIndex.allInsideKidsBathroom = req.querySet.push(allInsideKidsBathroom) - 1;
 
-    let haveInsideKidsBathroom = allKidsPark.clone();
+    let haveInsideKidsBathroom = allInsideKidsBathroom.clone();
     haveInsideKidsBathroom.where('escola.sanitario_ei = 1');
     req.queryIndex.haveInsideKidsBathroom = req.querySet.push(haveInsideKidsBathroom) - 1;
 
-    let needInsideKidsBathroom = allKidsPark.clone();
+    let needInsideKidsBathroom = allInsideKidsBathroom.clone();
     needInsideKidsBathroom.where('escola.sanitario_ei = 0');
     req.queryIndex.needInsideKidsBathroom = req.querySet.push(needInsideKidsBathroom) - 1;
 
@@ -651,7 +674,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.haveSpecialBathroom = req.querySet.push(haveSpecialBathroom) - 1;
 
     let needSpecialBathroom = allSchools.clone();
-    needSpecialBathroom.where('escola.sanitario_pne = 1');
+    needSpecialBathroom.where('escola.sanitario_pne = 0');
     req.queryIndex.needSpecialBathroom = req.querySet.push(needSpecialBathroom) - 1;
 
 
-- 
GitLab


From fc47450a43c6f977bfe14696e17820b808db7780 Mon Sep 17 00:00:00 2001
From: hi15 <hi15@inf.ufpr.br>
Date: Wed, 22 May 2019 11:12:54 -0300
Subject: [PATCH 104/142] Fixed tests

---
 src/test/simulation.js |  1 -
 src/test/user.js       | 57 ------------------------------------------
 2 files changed, 58 deletions(-)
 delete mode 100644 src/test/user.js

diff --git a/src/test/simulation.js b/src/test/simulation.js
index d7a99a97..78633b10 100644
--- a/src/test/simulation.js
+++ b/src/test/simulation.js
@@ -44,7 +44,6 @@ const server = require(`${libs}/app`);
 
 const mongoose = require('../libs/db/mongoose');
 const Simulation = require('../libs/models/simulation');
-const User = require('../libs/models/user');
 
 chai.use(chaiHttp);
 
diff --git a/src/test/user.js b/src/test/user.js
deleted file mode 100644
index ab44a78d..00000000
--- 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')
-    //     });
-    // });
-});
-- 
GitLab


From 051497d4514d1dc32e6e8d943f558a407475effc Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Wed, 22 May 2019 13:53:27 -0300
Subject: [PATCH 105/142] [university_fix]Fix age range filter

---
 src/libs/convert/ageStudentCode.js      | 38 +++++++++++++++++++++++++
 src/libs/middlewares/id2str.js          |  5 +++-
 src/libs/routes/universityEnrollment.js | 21 ++++++++++++++
 3 files changed, 63 insertions(+), 1 deletion(-)
 create mode 100644 src/libs/convert/ageStudentCode.js

diff --git a/src/libs/convert/ageStudentCode.js b/src/libs/convert/ageStudentCode.js
new file mode 100644
index 00000000..450c9361
--- /dev/null
+++ b/src/libs/convert/ageStudentCode.js
@@ -0,0 +1,38 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function ageStudentCode(id) {
+    switch (id) {
+        case 1:
+        return 'Menor que 18 anos';
+        case 2:
+        return 'Entre 18 anos e 24 anos';
+        case 3:
+        return 'Entre 25 anos e 29 anos';
+        case 4:
+        return 'Entre 30 anos e 34 anos';
+        case 5:
+        return 'Entre 35 anos e 39 anos';
+        case 6:
+        return 'Maior que 39 anos';
+        default:
+        return 'Não classificado';
+    }
+};
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 7f9f73fa..c9e21641 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -42,6 +42,7 @@ const contractType = require(`${libs}/convert/contractType`);
 const ethnicGroupPnad = require(`${libs}/convert/ethnicGroupPnad`);
 const ageRange = require(`${libs}/convert/ageRange`);
 const ageRangeAll = require(`${libs}/convert/ageRangeAll`);
+const ageStudentCode = require(`${libs}/convert/ageStudentCode`);
 const fullAgeRange = require(`${libs}/convert/fullAgeRange`);
 const genderPnad = require(`${libs}/convert/genderPnad`);
 const fifthHouseholdIncome = require(`${libs}/convert/fifthHouseholdIncome`);
@@ -145,7 +146,8 @@ const ids = {
     teacher_schooling_id: teacherSchooling,
     ethnic_group_teacher_ies_id: ethnicGroupTeacherIES,
     gender_ies_id: genderIES,
-    deficiency_id: deficiency
+    deficiency_id: deficiency,
+    age_student_code_id: ageStudentCode
 };
 
 function transform(removeId=false) {
@@ -209,6 +211,7 @@ module.exports = {
     ethnicGroupPnad,
     ageRange,
     ageRangeAll,
+    ageStudentCode,
     fullAgeRange,
     genderPnad,
     fifthHouseholdIncome,
diff --git a/src/libs/routes/universityEnrollment.js b/src/libs/routes/universityEnrollment.js
index ddfd8272..9eb452fd 100644
--- a/src/libs/routes/universityEnrollment.js
+++ b/src/libs/routes/universityEnrollment.js
@@ -212,6 +212,17 @@ universityEnrollmentApp.get('/upper_education_mod', function (req, res, next) {
     next();
 }, response('upper_education_mod'));
 
+universityEnrollmentApp.get('/age_student_code', function (req, res, next) {
+    req.result = [];
+    for (var i = 1; i <= 6; ++i) {
+        req.result.push({
+            id: i,
+            name: id2str.ageStudentCode(i)
+        });
+    };
+    next();
+}, response('age_student_code'));
+
 rqf.addField({
     name: 'filter',
     field: false,
@@ -299,6 +310,16 @@ rqf.addField({
         type: 'integer',
         field: 'cod_ies'
     }
+}).addValue({
+    name: 'age_student_code',
+    table: 'aluno_ens_superior',
+    tableField: 'idade_aluno_codigo',
+    resultField: 'age_student_code_id',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'idade_aluno_codigo'
+    }
 }).addValue({
     name: 'upper_adm_dependency',
     table: 'aluno_ens_superior',
-- 
GitLab


From 5da66d88b0c5b01a5420eac2fc8ee455b8e5a772 Mon Sep 17 00:00:00 2001
From: Fernando Erd <fcerd@inf.ufpr.br>
Date: Thu, 23 May 2019 10:23:59 -0300
Subject: [PATCH 106/142] Fix order error

---
 src/libs/routes/enrollment.js | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js
index d40fb5ec..be61a306 100644
--- a/src/libs/routes/enrollment.js
+++ b/src/libs/routes/enrollment.js
@@ -531,7 +531,7 @@ rqf.addField({
   resultField: 'integral_time_id',
   where: {
       relation: '=',
-      type: 'boolean',
+      type: 'integer',
       field: 'tempo_integral'
   }
 }).addValue({
@@ -556,7 +556,7 @@ rqf.addField({
   }
 });
 
-enrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
+enrollmentApp.get('/', rqf.parse(), (req, res, next) => {
     req.sql.field('COUNT(*)', 'total')
     .field('matricula.ano_censo', 'year')
     .from('matricula')
@@ -564,7 +564,7 @@ enrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     .order('matricula.ano_censo')
     .where('matricula.tipo<=3');
     next();
-}, query, addMissing(rqf), id2str.transform(false), response('enrollment'));
+}, rqf.build(), query, id2str.transform(false), addMissing(rqf), response('enrollment'));
 
 enrollmentApp.get('/diagnosis', rqf.parse(), (req, res, next) => {
     req.dims = {};
-- 
GitLab


From e36e0363026b7161fda21609acbab2fbd7e43e8b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Fri, 24 May 2019 09:11:36 -0300
Subject: [PATCH 107/142] Added projection of future years

---
 src/libs/routes/classroomCount.js | 538 +++++++++++++++---------------
 1 file changed, 271 insertions(+), 267 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 6ac9d9f6..6f9cd6d2 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -192,8 +192,7 @@ rqf.addField({
 classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     let classSize = JSON.parse(req.body.class_size) || null;
     let integralTime = JSON.parse(req.body.integral_time) || null;
-    let enrollmentProjection = JSON.parse(req.body.enrollment_projection) || null;
-    req.projection = enrollmentProjection !== null;
+    let enrollmentProjection = (req.body.projections !== undefined) ? JSON.parse(req.body.projections) : null;
 
     if(classSize == null || integralTime == null) {
         res.statusCode = 400;
@@ -201,9 +200,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     }
     req.classSize = classSize;
     req.integralTime = integralTime;
-    if (req.projection) {
-        req.enrollmentProjection = enrollmentProjection.projections;
-    }
+    req.projections = (enrollmentProjection !== null) ? enrollmentProjection : false;
 
     req.dims.state = true;
     req.dims.city = true;
@@ -317,321 +314,328 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
     let enrollmentProjectionNight = [];
     let enrollmentProjectionDay = [];
-    if (req.projection) {
-        for (let i = 0; i < req.enrollmentProjection.length; i++) {
-            if (req.enrollmentProjection[i].periods === 3) {
-                enrollmentProjectionNight.push(req.enrollmentProjection[i]);
+    if (req.projections) {
+        for (let i = 0; i < req.projections.length; i++) {
+            if (req.projections[i].periods === 3) {
+                enrollmentProjectionNight.push(req.projections[i]);
             } else {
-                enrollmentProjectionDay.push(req.enrollmentProjection[i]);
+                enrollmentProjectionDay.push(req.projections[i]);
             }
         }
     }
-    console.log(enrollmentProjectionDay);
+    let qntYears = 1;
+    if (req.projections) {
+        qntYears = enrollmentProjectionDay[0].stagesEnrollments[0].seriesEnrollments[0].enrollments.length;
+    }
+    let result = [];
 
     // Cria estrutura de resposta requisitada:
-    let i = 0;
-    let j = 0;
-    let result = [];
-    let hashSet = new Set();
-    let enrollments = [...req.enrollment];
-    let ei = 0;
-    let eiCityStart = 0;
-    let verifySchoolYear;                                   // Matriz para verificar se o idm já foi inserido no school year.
-    while (i < req.classroom.length) {
-        let classroom = req.classroom[i];
-        // Cria hash única para cada espacialidade, dado um ano
-        let hash = '' + 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: []
-        };
-
-        // Inserimos a localidade no array de locations da sala
-        let location = {
-            location_id: classroom.location_id,
-            location_name: classroom.location_name,
-            total_classroom: (classroom.school_building == 1) ? parseInt(classroom.total, 10) : 0,      // Conta apenas salas de prédios próprios
-            total_classroom_be_built: 0,
-            education_level: []
-        };
-        
-        let currentClassroomObj = null;
-        if( !hashSet.has(hash) ) {
-            if (result[result.length - 1] !== undefined) {      // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id
-                let last_locations = result[result.length - 1].locations
-                for (let i = 0; i < last_locations.length - 1; i++) {
-                    if (last_locations[i].location_id === last_locations[i+1].location_id) {
-                        last_locations[i].total_classroom_be_built += last_locations[i+1].total_classroom_be_built;
-                        last_locations[i].total_classroom += last_locations[i+1].total_classroom;
-                        last_locations.splice(i+1, 1);
+    for(let yearCount = 0; yearCount < qntYears; yearCount++) {
+        let i = 0;
+        let old_i = 0;
+        let j = 0;
+        let hashSet = new Set();
+        let enrollments = [...req.enrollment];
+        let test1 = [1,2,3];
+        let test2 = Array.from(Array(qntYears), () => [...test1]);
+        let ei = 0;
+        let eiCityStart = 0;
+        let verifySchoolYear;                                   // Matriz para verificar se o idm já foi inserido no school year.
+        while (i < req.classroom.length) {
+            let classroom = req.classroom[i];
+            // Cria hash única para cada espacialidade, dado um ano
+            let hash = '' + yearCount + classroom.state_id + classroom.city_id;
+            // Estrutura do objeto do resultado final
+            let obj = {
+                year: classroom.year + yearCount,
+                name: classroom.name,
+                state_id: classroom.state_id,
+                state_name: classroom.state_name,
+                city_id: classroom.city_id,
+                city_name: classroom.city_name,
+                locations: []
+            };
+
+            // Inserimos a localidade no array de locations da sala
+            let location = {
+                location_id: classroom.location_id,
+                location_name: classroom.location_name,
+                total_classroom: (classroom.school_building == 1) ? parseInt(classroom.total, 10) : 0,      // Conta apenas salas de prédios próprios
+                total_classroom_be_built: 0,
+                education_level: []
+            };
+            
+            let currentClassroomObj = null;
+            if( !hashSet.has(hash) ) {
+                // console.log(enrollments[yearCount].length);
+                if (result[result.length - 1] !== undefined) {      // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id
+                    let last_locations = result[result.length - 1].locations
+                    for (let i = 0; i < last_locations.length - 1; i++) {
+                        if (last_locations[i].location_id === last_locations[i+1].location_id) {
+                            last_locations[i].total_classroom_be_built += last_locations[i+1].total_classroom_be_built;
+                            last_locations[i].total_classroom += last_locations[i+1].total_classroom;
+                            last_locations.splice(i+1, 1);
+                        }
+                    }
+                    for (let i = 0; i < last_locations.length; i++) {   // Passamos agora para não deixar to_be_built < 0
+                        last_locations[i].total_classroom_be_built = (last_locations[i].total_classroom_be_built < 0) ? 0 : last_locations[i].total_classroom_be_built;
                     }
                 }
-                for (let i = 0; i < last_locations.length; i++) {   // Passamos agora para não deixar to_be_built < 0
-                    last_locations[i].total_classroom_be_built = (last_locations[i].total_classroom_be_built < 0) ? 0 : last_locations[i].total_classroom_be_built;
-                }
-            }
-            hashSet.add(hash);
-            result.push(obj);
-            currentClassroomObj = obj;
-            eiCityStart = ei;
-            verifySchoolYear = Array.from(Array(2), () => new Array(15));
-        } else { // Se a hash já existe, já temos a cidade nos resultados. Como está ordenado, é o último valor nos resultados
-            currentClassroomObj = result[result.length - 1];
-            ei = eiCityStart;
-        }
-        currentClassroomObj.locations.push(location);
-
-        // Partimos para as etapas de ensino/anos escolares
-        let enrollmentMatch = true;
-        j = 0;
-        let educationLevelSet = new Set();
-        let schoolYearSet = new Set();
-        let enrollment = enrollments[j];
-        while(enrollmentMatch && j < enrollments.length) {
-            enrollment = enrollments[j];
-
-            if(typeof enrollment === 'undefined') {
-                ++j;
-                continue;
+                hashSet.add(hash);
+                result.push(obj);
+                currentClassroomObj = obj;
+                eiCityStart = ei;
+                verifySchoolYear = Array.from(Array(2), () => new Array(15));
+            } else { // Se a hash já existe, já temos a cidade nos resultados. Como está ordenado, é o último valor nos resultados
+                currentClassroomObj = result[result.length - 1];
+                ei = eiCityStart;
             }
+            currentClassroomObj.locations.push(location);
+
+            // Partimos para as etapas de ensino/anos escolares
+            let enrollmentMatch = true;
+            j = 0;
+            let educationLevelSet = new Set();
+            let schoolYearSet = new Set();
+            let enrollment;
+            while(enrollmentMatch && j < enrollments.length) {
+                enrollment = enrollments[j];
+
+                if(typeof enrollment === 'undefined') {
+                    ++j;
+                    continue;
+                }
+
+                if(classroom.city_id !== enrollment.city_id) { // Se as cidades não são iguais, já passamos do range
+                    enrollmentMatch = false;
+                    while (req.idm[ei].city_id !== enrollment.city_id) {
+                        ei++;
+                    }
+                    continue;
+                } 
 
-            if(classroom.city_id !== enrollment.city_id) { // Se as cidades não são iguais, já passamos do range
-                enrollmentMatch = false;
-                while (req.idm[ei].city_id !== enrollment.city_id) {
-                    ei++;
+                if(enrollment.year != classroom.year || enrollment.location_id != classroom.location_id) { // Se ano ou localização são diferentes, passa para o próximo
+                    ++j;
+                    continue;
                 }
-                continue;
-            } 
 
-            if(enrollment.year != classroom.year || enrollment.location_id != classroom.location_id) { // Se ano ou localização são diferentes, passa para o próximo
-                ++j;
-                continue;
-            }
 
+                // Temos uma matrícula com cidade, ano e localidades certos
+                // "Consome" a matrícula (remove do vetor de matrículas)
+                enrollments.splice(j, 1);
 
-            // Temos uma matrícula com cidade, ano e localidades certos
-            // "Consome" a matrícula (remove do vetor de matrículas)
-            enrollments.splice(j, 1);
+                // Cria a etapa de ensino adequada
+                let enrollmentEducationLevel = req.educationSchoolYear[enrollment.school_year_id];
+                // Se não há um número de alunos por turna para a etapa de ensino, ignoramos a entrada
+                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
+                        }
+                    };
 
-            // 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 = [];
                     }
-                };
 
-                if(enrollmentEducationLevel.id == 1) {
-                    educationLevel.classes_school_year = [];
-                }
-
-                // Para manter a ordem da etapa de ensino
-                if (location.education_level.length == 0) {
-                    location.education_level.push(educationLevel);
+                    // Para manter a ordem da etapa de ensino
+                    if (location.education_level.length == 0) {
+                        location.education_level.push(educationLevel);
+                    } else {
+                        let k = location.education_level.length - 1;
+                        let el = location.education_level[k];
+                        while (k >= 0) {
+                            if(educationLevel.education_level_short_id < el.education_level_short_id) {
+                                --k;
+                                if(k>=0) el = location.education_level[k];
+                            } else break;
+                        }
+                        k++;
+                        location.education_level.splice(k, 0, educationLevel);
+                    }
                 } else {
-                    let k = location.education_level.length - 1;
+                    let k = 0;
                     let el = location.education_level[k];
-                    while (k >= 0) {
-                        if(educationLevel.education_level_short_id < el.education_level_short_id) {
-                            --k;
-                            if(k>=0) el = location.education_level[k];
+                    while(k < location.education_level.length) {
+                        if(el.education_level_short_id != enrollmentEducationLevel.id) {
+                            ++k;
+                            if(k<location.education_level.length) el = location.education_level[k];
                         } else break;
                     }
-                    k++;
-                    location.education_level.splice(k, 0, educationLevel);
+                    if(k >= location.education_level.length) --k;
+                    educationLevel = location.education_level[k];
                 }
-            } else {
-                let k = 0;
-                let el = location.education_level[k];
-                while(k < location.education_level.length) {
-                    if(el.education_level_short_id != enrollmentEducationLevel.id) {
-                        ++k;
-                        if(k<location.education_level.length) el = location.education_level[k];
-                    } else break;
-                }
-                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];
+                // 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;
                     }
-                    // educationLevel.classes_school_year.push(school_year);
-                    educationLevel.classes_school_year.splice(k, 0, school_year);
-                    currentSchoolYear = school_year;
                 }
-            }
 
-            // Faz match da tabela de idm com a de enrollment
-            if (educationLevel.education_level_short_id !== 1) {
-                while (req.idm[ei].school_year_id < educationLevel.education_level_short_id) ei++;
-                while (req.idm[ei].school_year_id > educationLevel.education_level_short_id) ei--;
+                // Faz match da tabela de idm com a de enrollment
+                if (educationLevel.education_level_short_id !== 1) {
+                    while (req.idm[ei].school_year_id < educationLevel.education_level_short_id) ei++;
+                    while (req.idm[ei].school_year_id > educationLevel.education_level_short_id) ei--;
 
-                if (req.idm[ei].location_id < location.location_id) {
-                    ei++;
-                }
-                else if(req.idm[ei].location_id > location.location_id) {
-                    ei--;
+                    if (req.idm[ei].location_id < location.location_id) {
+                        ei++;
+                    }
+                    else if(req.idm[ei].location_id > location.location_id) {
+                        ei--;
+                    }
                 }
-            }
-            let enrollmentIdm = req.idm[ei];
+                let enrollmentIdm = req.idm[ei];
 
 
-            let currentIntegralOfferGoal = enrollmentEducationLevel.integralTimeOfferGoal;
-            let currentNumberStudentClass = (enrollment.location_id == 1) ? enrollmentEducationLevel.numberStudentClass.urban : enrollmentEducationLevel.numberStudentClass.country;
-            
-            let currentEnrollmentOfferDay = enrollmentProjectionDay[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
-            let currentEnrollmentOfferNight = enrollmentProjectionNight[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
-            if (req.projection && !verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] && (currentEnrollmentOfferDay.enrollments !== undefined)) {     // Garantimos que será somado apenas uma vez por localização.
-                // Projeção matricula multiplicada pelo indice da cidade.
-                verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] = 1;
-
-                educationLevel.enrollment.total_enrollment_day += (currentEnrollmentOfferDay.enrollments[0].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm;
-                educationLevel.enrollment.total_enrollment_night += (currentEnrollmentOfferNight.enrollments[0].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm;
-            }
-            // Soma os totais de matrícula da etapa de ensino
-            educationLevel.enrollment.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
-            educationLevel.enrollment.total_enrollment_night += (enrollment.period_id == 3 && educationLevel.education_level_short_id > 2) ? enrollment.total : 0;      //Não contamos matrículas noturnos de pré-escola e creche
+                let currentIntegralOfferGoal = enrollmentEducationLevel.integralTimeOfferGoal;
+                let currentNumberStudentClass = (enrollment.location_id == 1) ? enrollmentEducationLevel.numberStudentClass.urban : enrollmentEducationLevel.numberStudentClass.country;
+                
+                let currentEnrollmentOfferDay;
+                let currentEnrollmentOfferNight;
+                if (req.projections) {
+                    currentEnrollmentOfferDay = enrollmentProjectionDay[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
+                    currentEnrollmentOfferNight = enrollmentProjectionNight[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
+                }
+                if (req.projections && !verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] && (currentEnrollmentOfferDay.enrollments !== undefined)) {     // Garantimos que será somado apenas uma vez por localização.
+                    // Projeção matricula multiplicada pelo indice de distribuição de matriculas da localização.
+                    verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] = 1;
 
-            // Calcula o número de turmas parcial
-            // Turmas de período integral
-            educationLevel.enrollment.full_period_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (currentIntegralOfferGoal/100)) / currentNumberStudentClass);
+                    educationLevel.enrollment.total_enrollment_day += Math.ceil((currentEnrollmentOfferDay.enrollments[yearCount].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm);
+                    educationLevel.enrollment.total_enrollment_night += (educationLevel.education_level_short_id > 2) ? Math.ceil((currentEnrollmentOfferNight.enrollments[yearCount].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm) : 0;
+                }
+                // Soma os totais de matrícula da etapa de ensino
+                educationLevel.enrollment.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
+                educationLevel.enrollment.total_enrollment_night += (enrollment.period_id == 3 && educationLevel.education_level_short_id > 2) ? enrollment.total : 0;      //Não contamos matrículas noturnos de pré-escola e creche
 
-            // Turmas diurnas (matrículas diurnas - matrículas integrais)
-            educationLevel.enrollment.day_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (1 - currentIntegralOfferGoal/100)) / currentNumberStudentClass);
+                // Calcula o número de turmas parcial
+                // Turmas de período integral
+                educationLevel.enrollment.full_period_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (currentIntegralOfferGoal/100)) / currentNumberStudentClass);
 
-            // Turmas noturnas
-            educationLevel.enrollment.night_classes = Math.ceil((educationLevel.enrollment.total_enrollment_night / currentNumberStudentClass)) || 0;
+                // Turmas diurnas (matrículas diurnas - matrículas integrais)
+                educationLevel.enrollment.day_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (1 - currentIntegralOfferGoal/100)) / currentNumberStudentClass);
 
-            // Total de salas
-            educationLevel.enrollment.total_classrooms_needed = (educationLevel.enrollment.full_period_classes + educationLevel.enrollment.day_classes/2);
+                // Turmas noturnas
+                educationLevel.enrollment.night_classes = Math.ceil((educationLevel.enrollment.total_enrollment_night / currentNumberStudentClass)) || 0;
 
-            if(educationLevel.enrollment.night_classes > (educationLevel.enrollment.day_classes/2)) educationLevel.enrollment.total_classrooms_needed += (educationLevel.enrollment.night_classes - (educationLevel.enrollment.day_classes/2));
+                // Total de salas
+                educationLevel.enrollment.total_classrooms_needed = (educationLevel.enrollment.full_period_classes + educationLevel.enrollment.day_classes/2);
 
-            educationLevel.enrollment.total_classrooms_needed = Math.ceil(educationLevel.enrollment.total_classrooms_needed);
+                if(educationLevel.enrollment.night_classes > (educationLevel.enrollment.day_classes/2)) educationLevel.enrollment.total_classrooms_needed += (educationLevel.enrollment.night_classes - (educationLevel.enrollment.day_classes/2));
 
-            // Faz os mesmos cálculos para a série escolar
-            if(currentSchoolYear) {
-                // Faz match da enrollment com o idm, no caso de não usar o mod
-                while (req.idm[ei].school_year_id < enrollment.school_year_id) ei++;
-                while (req.idm[ei].school_year_id > enrollment.school_year_id) ei--;
+                educationLevel.enrollment.total_classrooms_needed = Math.ceil(educationLevel.enrollment.total_classrooms_needed);
 
-                if (req.idm[ei].location_id < location.location_id) {
-                    ei++;
-                }
-                else if(req.idm[ei].location_id > location.location_id) {
-                    ei--;
-                }
-                enrollmentIdm = req.idm[ei];
+                // Faz os mesmos cálculos para a série escolar
+                if(currentSchoolYear) {
+                    // Faz match da enrollment com o idm, no caso de não usar o mod
+                    while (req.idm[ei].school_year_id < enrollment.school_year_id) ei++;
+                    while (req.idm[ei].school_year_id > enrollment.school_year_id) ei--;
 
+                    if (req.idm[ei].location_id < location.location_id) {
+                        ei++;
+                    }
+                    else if(req.idm[ei].location_id > location.location_id) {
+                        ei--;
+                    }
+                    enrollmentIdm = req.idm[ei];
 
-                // Totais de matrícula
-                currentSchoolYear.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
-                currentSchoolYear.total_enrollment_night += (enrollment.period_id == 3 && currentSchoolYear.school_year_id > 30) ? enrollment.total : 0;        //Não contamos matrículas noturnos de pré-escola e creche
 
-                if (req.projection && !verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id]) {     // Garantimos que será somado apenas uma vez por localização.
-                    verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] = 1;
+                    // Totais de matrícula
+                    currentSchoolYear.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
 
-                    let currentEnrollmentSchoolYear = currentEnrollmentOfferDay.seriesEnrollments[Math.trunc(currentSchoolYear.school_year_id/10) - 1];
-                    currentSchoolYear.total_enrollment_day += (currentEnrollmentSchoolYear !== undefined) ? (currentEnrollmentSchoolYear.enrollments[0].quantity - currentEnrollmentSchoolYear.currentOffer)*enrollmentIdm.idm : 0;
-                    currentSchoolYear.total_enrollment_night += (currentEnrollmentSchoolYear !== undefined) ? (currentEnrollmentSchoolYear.enrollments[0].quantity - currentEnrollmentSchoolYear.currentOffer)*enrollmentIdm.idm : 0;
-                }
-                
-                // Número de turmas parcial
-                currentSchoolYear.full_period_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (currentIntegralOfferGoal/100)) / currentNumberStudentClass);
+                    if (req.projections && !verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id]) {     // Garantimos que será somado apenas uma vez por localização.
+                        verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] = 1;
 
-                currentSchoolYear.day_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (1 - currentIntegralOfferGoal/100)) / currentNumberStudentClass);
+                        let currentEnrollmentSchoolYear = currentEnrollmentOfferDay.seriesEnrollments[Math.trunc(currentSchoolYear.school_year_id/10) - 1];
+                        currentSchoolYear.total_enrollment_day += (currentEnrollmentSchoolYear !== undefined) ? Math.ceil((currentEnrollmentSchoolYear.enrollments[yearCount].quantity - currentEnrollmentSchoolYear.currentOffer)*enrollmentIdm.idm) : 0;
+                    }
+                    
+                    // Número de turmas parcial
+                    currentSchoolYear.full_period_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (currentIntegralOfferGoal/100)) / currentNumberStudentClass);
 
-                currentSchoolYear.night_classes = Math.ceil((currentSchoolYear.total_enrollment_night / enrollmentEducationLevel.numberStudentClass)) || 0;
+                    currentSchoolYear.day_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (1 - currentIntegralOfferGoal/100)) / currentNumberStudentClass);
 
-                // 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));
+                    // Total de salas
+                    currentSchoolYear.total_classrooms_needed = (currentSchoolYear.full_period_classes + currentSchoolYear.day_classes/2);
 
-                currentSchoolYear.total_classrooms_needed = Math.ceil(currentSchoolYear.total_classrooms_needed);
+                    currentSchoolYear.total_classrooms_needed = Math.ceil(currentSchoolYear.total_classrooms_needed);
 
-                function reducer(key) { return (sum, elem) => sum + elem[key]}
-                educationLevel.enrollment.total_enrollment_day = educationLevel.classes_school_year.reduce(reducer('total_enrollment_day'), 0);
-                educationLevel.enrollment.full_period_classes = educationLevel.classes_school_year.reduce(reducer('full_period_classes'), 0);
-                educationLevel.enrollment.day_classes = educationLevel.classes_school_year.reduce(reducer('day_classes'), 0);
-                educationLevel.enrollment.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);
+                    function reducer(key) { return (sum, elem) => sum + elem[key]}
+                    educationLevel.enrollment.total_enrollment_day = educationLevel.classes_school_year.reduce(reducer('total_enrollment_day'), 0);
+                    educationLevel.enrollment.full_period_classes = educationLevel.classes_school_year.reduce(reducer('full_period_classes'), 0);
+                    educationLevel.enrollment.day_classes = educationLevel.classes_school_year.reduce(reducer('day_classes'), 0);
+                    educationLevel.enrollment.total_classrooms_needed = educationLevel.classes_school_year.reduce(reducer('total_classrooms_needed'), 0);
+                }
+                enrollment = enrollments[j];
             }
-            enrollment = enrollments[j];
-        }
 
-        // Calculamos o total classroom be built para o município usando reduce
-        location.total_classroom_be_built = location.education_level.reduce((total, atual) => {
-            return total + atual.enrollment.total_classrooms_needed;
-        }, 0) - location.total_classroom;
-        ++i;
-    }
+            // Calculamos o total classroom be built para o município usando reduce
+            location.total_classroom_be_built = location.education_level.reduce((total, atual) => {
+                return total + atual.enrollment.total_classrooms_needed;
+            }, 0) - location.total_classroom;
+            ++i;
+        }
 
-    // Tratamento do último resultado, para remover double location, tirar negativo do to_be_built.
-    if (result[result.length - 1] !== undefined) {      // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id
-                let last_locations = result[result.length - 1].locations
-                for (let i = 0; i < last_locations.length - 1; i++) {
-                    if (last_locations[i].location_id === last_locations[i+1].location_id) {
-                        last_locations[i].total_classroom_be_built += last_locations[i+1].total_classroom_be_built;
-                        last_locations[i].total_classroom += last_locations[i+1].total_classroom;
-                        last_locations.splice(i+1, 1);
-                    }
-                }
-                for (let i = 0; i < last_locations.length; i++) {   // Passamos agora para não deixar to_be_built < 0
-                    last_locations[i].total_classroom_be_built = (last_locations[i].total_classroom_be_built < 0) ? 0 : last_locations[i].total_classroom_be_built;
+        // Tratamento do último resultado, para remover double location, tirar negativo do to_be_built.
+        if (result[result.length - 1] !== undefined) {      // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id
+            let last_locations = result[result.length - 1].locations
+            for (let i = 0; i < last_locations.length - 1; i++) {
+                if (last_locations[i].location_id === last_locations[i+1].location_id) {
+                    last_locations[i].total_classroom_be_built += last_locations[i+1].total_classroom_be_built;
+                    last_locations[i].total_classroom += last_locations[i+1].total_classroom;
+                    last_locations.splice(i+1, 1);
                 }
             }
+            for (let i = 0; i < last_locations.length; i++) {   // Passamos agora para não deixar to_be_built < 0
+                last_locations[i].total_classroom_be_built = (last_locations[i].total_classroom_be_built < 0) ? 0 : last_locations[i].total_classroom_be_built;
+            }
+        }
+    }
 
     // Agregar por estado e brasil
     let reduction = null;
-- 
GitLab


From b4607d4a9b737c1f256e148cd4eb2c7dc74db4c1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Fri, 24 May 2019 11:43:41 -0300
Subject: [PATCH 108/142] Fix negative enrollments in cities

---
 src/libs/routes/classroomCount.js | 43 +++++++++++++++++++++----------
 1 file changed, 29 insertions(+), 14 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 6f9cd6d2..9dffd0c6 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -187,6 +187,16 @@ rqf.addField({
         type: 'boolean',
         field: 'local_func_predio_escolar'
     }
+}).addValue({
+    name: 'night_time',
+    table: 'matricula',
+    tableField: 'periodo_noturno',
+    resultField: 'night_time',
+    where: {
+        relation: '=',
+        type: 'boolean',
+        field: 'periodo_noturno'
+    }
 });
 
 classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
@@ -204,7 +214,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
     req.dims.state = true;
     req.dims.city = true;
-    req.dims.period = true;
+    req.dims.night_time = true;
     req.dims.school_year = true;
     req.dims.location = true;
 
@@ -285,7 +295,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                .order('indice_distribuicao_matriculas.indice');
     }
     else {
-        console.log(req.dims);
         req.dims.state = true;
         req.dims.city = true;
         req.dims.school_year = true;
@@ -367,7 +376,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             
             let currentClassroomObj = null;
             if( !hashSet.has(hash) ) {
-                // console.log(enrollments[yearCount].length);
                 if (result[result.length - 1] !== undefined) {      // Após mudar de cidade, passamos pela cidade anterior e juntamos o valor to_be_built de localizações com o mesmo id
                     let last_locations = result[result.length - 1].locations
                     for (let i = 0; i < last_locations.length - 1; i++) {
@@ -535,22 +543,28 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 let currentIntegralOfferGoal = enrollmentEducationLevel.integralTimeOfferGoal;
                 let currentNumberStudentClass = (enrollment.location_id == 1) ? enrollmentEducationLevel.numberStudentClass.urban : enrollmentEducationLevel.numberStudentClass.country;
                 
+                // Soma os totais de matrícula da etapa de ensino
+                educationLevel.enrollment.total_enrollment_day += (!enrollment.night_time) ? enrollment.total : 0;
+                educationLevel.enrollment.total_enrollment_night += (enrollment.night_time && educationLevel.education_level_short_id > 2) ? enrollment.total : 0;      //Não contamos matrículas noturnos de pré-escola e creche
+
                 let currentEnrollmentOfferDay;
                 let currentEnrollmentOfferNight;
                 if (req.projections) {
                     currentEnrollmentOfferDay = enrollmentProjectionDay[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
                     currentEnrollmentOfferNight = enrollmentProjectionNight[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
                 }
-                if (req.projections && !verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] && (currentEnrollmentOfferDay.enrollments !== undefined)) {     // Garantimos que será somado apenas uma vez por localização.
-                    // Projeção matricula multiplicada pelo indice de distribuição de matriculas da localização.
-                    verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] = 1;
+                if (req.projections && (verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] !== enrollment.night_time) && (currentEnrollmentOfferDay.enrollments !== undefined)) {     // Garantimos que será somado apenas uma vez por localização.
+                    // Projeção de matricula multiplicada pelo indice de distribuição de matriculas da localização.
+                    verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] = enrollment.night_time;
 
-                    educationLevel.enrollment.total_enrollment_day += Math.ceil((currentEnrollmentOfferDay.enrollments[yearCount].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm);
-                    educationLevel.enrollment.total_enrollment_night += (educationLevel.education_level_short_id > 2) ? Math.ceil((currentEnrollmentOfferNight.enrollments[yearCount].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm) : 0;
+                    if (!enrollment.night_time) {
+                        educationLevel.enrollment.total_enrollment_day += Math.ceil((currentEnrollmentOfferDay.enrollments[yearCount].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm);
+                        if (educationLevel.enrollment.total_enrollment_day < 0) educationLevel.enrollment.total_enrollment_day = 0;
+                    } else {
+                        educationLevel.enrollment.total_enrollment_night += (educationLevel.education_level_short_id > 2) ? Math.ceil((currentEnrollmentOfferNight.enrollments[yearCount].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm) : 0;
+                        if (educationLevel.enrollment.total_enrollment_night < 0) educationLevel.enrollment.total_enrollment_night = 0;
+                    }
                 }
-                // Soma os totais de matrícula da etapa de ensino
-                educationLevel.enrollment.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
-                educationLevel.enrollment.total_enrollment_night += (enrollment.period_id == 3 && educationLevel.education_level_short_id > 2) ? enrollment.total : 0;      //Não contamos matrículas noturnos de pré-escola e creche
 
                 // Calcula o número de turmas parcial
                 // Turmas de período integral
@@ -585,13 +599,14 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
 
                     // Totais de matrícula
-                    currentSchoolYear.total_enrollment_day += (enrollment.period_id < 3) ? enrollment.total : 0;
+                    currentSchoolYear.total_enrollment_day += (!enrollment.night_time) ? enrollment.total : 0;
 
-                    if (req.projections && !verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id]) {     // Garantimos que será somado apenas uma vez por localização.
-                        verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] = 1;
+                    if (req.projections && !verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] !== enrollment.night_time) {     // Garantimos que será somado apenas uma vez por localização.
+                        verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] = enrollment.night_time;
 
                         let currentEnrollmentSchoolYear = currentEnrollmentOfferDay.seriesEnrollments[Math.trunc(currentSchoolYear.school_year_id/10) - 1];
                         currentSchoolYear.total_enrollment_day += (currentEnrollmentSchoolYear !== undefined) ? Math.ceil((currentEnrollmentSchoolYear.enrollments[yearCount].quantity - currentEnrollmentSchoolYear.currentOffer)*enrollmentIdm.idm) : 0;
+                        if (currentSchoolYear.total_enrollment_day < 0) currentSchoolYear.total_enrollment_day = 0;
                     }
                     
                     // Número de turmas parcial
-- 
GitLab


From 295a69db26d5d21b0974fe7897cd6639186e5523 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 30 May 2019 10:28:43 -0300
Subject: [PATCH 109/142] Change to use an aggregate table to get the
 enrollments

---
 src/libs/middlewares/id2str.js    |  1 +
 src/libs/routes/classroomCount.js | 38 +++++++++++++++----------------
 2 files changed, 20 insertions(+), 19 deletions(-)

diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 0e2b9e9c..257105a6 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -193,6 +193,7 @@ module.exports = {
     educationLevelBasic,
     educationLevelMod,
     educationLevelShort,
+    educationLevelSchoolYear,
     admDependency,
     admDependencyPriv,
     location,
diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index 9dffd0c6..f776ddb9 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -18,6 +18,7 @@ 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();
@@ -214,18 +215,19 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
     req.dims.state = true;
     req.dims.city = true;
-    req.dims.night_time = true;
     req.dims.school_year = true;
     req.dims.location = true;
 
-    req.sql.field('COUNT(*)', 'total')
+    req.sql.field('dia_total', 'total_day')
+    .field('noite_total', 'total_night')
     .field("'Brasil'", 'name')
-    .field('matricula.ano_censo', 'year')
-    .from('matricula')
-    .group('matricula.ano_censo')
-    .order('matricula.ano_censo')
-    .where('matricula.tipo<=3')
-    .where('matricula.dependencia_adm_id < 4');
+    .field('matricula_por_localizacao.ano_censo', 'year')
+    .from('matricula_por_localizacao')
+    .where('matricula_por_localizacao.serie_ano_id < 15')
+    .group('matricula_por_localizacao.ano_censo')
+    .group('matricula_por_localizacao.dia_total')
+    .group('matricula_por_localizacao.noite_total')
+    .order('matricula_por_localizacao.ano_censo')
 
     next();
 }, rqf.build(), query, id2str.transform(), (req, res, next) => {
@@ -233,9 +235,9 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
     // Gera a relação etapa de ensino X ano escolar
     req.educationSchoolYear = {};
-    for(let i = 10; i < 80; ++i) {
-        if(id2str.schoolYear(i) !== id2str.schoolYear(99)) {
-            let educationLevelId = Math.floor(i/10);
+    for(let i = 1; i < 15; ++i) {
+        if(id2str.educationLevelSchoolYear(i) !== id2str.educationLevelSchoolYear(99)) {
+            let educationLevelId = (i > 10) ? Math.floor(i/10) : i;
 
             let classSize = req.classSize.find((el) => {return el.id === educationLevelId || el.id === i});
             let integralTime = req.integralTime.find((el) => {return el.id === educationLevelId});
@@ -251,7 +253,8 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
             };
         }
     }
-
+    delete req.dims;
+    delete req.filter;
     req.resetSql();
     next();
 }, rqf.parse(), (req, res, next) => {
@@ -292,7 +295,6 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                .group('indice_distribuicao_matriculas.ano_censo')
                .group('indice_distribuicao_matriculas.indice')
                .order('indice_distribuicao_matriculas.ano_censo')
-               .order('indice_distribuicao_matriculas.indice');
     }
     else {
         req.dims.state = true;
@@ -341,12 +343,9 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
     // Cria estrutura de resposta requisitada:
     for(let yearCount = 0; yearCount < qntYears; yearCount++) {
         let i = 0;
-        let old_i = 0;
         let j = 0;
         let hashSet = new Set();
         let enrollments = [...req.enrollment];
-        let test1 = [1,2,3];
-        let test2 = Array.from(Array(qntYears), () => [...test1]);
         let ei = 0;
         let eiCityStart = 0;
         let verifySchoolYear;                                   // Matriz para verificar se o idm já foi inserido no school year.
@@ -435,6 +434,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 // 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;
@@ -544,8 +544,8 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                 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.night_time) ? enrollment.total : 0;
-                educationLevel.enrollment.total_enrollment_night += (enrollment.night_time && educationLevel.education_level_short_id > 2) ? enrollment.total : 0;      //Não contamos matrículas noturnos de pré-escola e creche
+                educationLevel.enrollment.total_enrollment_day += enrollment.total_day;
+                educationLevel.enrollment.total_enrollment_night += (educationLevel.education_level_short_id > 2) ? enrollment.total_night : 0;      //Não contamos matrículas noturnos de pré-escola e creche
 
                 let currentEnrollmentOfferDay;
                 let currentEnrollmentOfferNight;
@@ -599,7 +599,7 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
 
 
                     // Totais de matrícula
-                    currentSchoolYear.total_enrollment_day += (!enrollment.night_time) ? enrollment.total : 0;
+                    currentSchoolYear.total_enrollment_day += enrollment.total_day;
 
                     if (req.projections && !verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] !== enrollment.night_time) {     // Garantimos que será somado apenas uma vez por localização.
                         verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] = enrollment.night_time;
-- 
GitLab


From 14aae54cbd3b37bb6a7f1f40a8e9642e36705d9e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Fri, 31 May 2019 08:40:35 -0300
Subject: [PATCH 110/142] Fix idm

---
 src/libs/routes/classroomCount.js | 19 ++++++++-----------
 1 file changed, 8 insertions(+), 11 deletions(-)

diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js
index f776ddb9..fe3e3c31 100644
--- a/src/libs/routes/classroomCount.js
+++ b/src/libs/routes/classroomCount.js
@@ -553,17 +553,14 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                     currentEnrollmentOfferDay = enrollmentProjectionDay[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
                     currentEnrollmentOfferNight = enrollmentProjectionNight[enrollment.location_id - 1].stagesEnrollments[educationLevel.education_level_short_id - 1];
                 }
-                if (req.projections && (verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] !== enrollment.night_time) && (currentEnrollmentOfferDay.enrollments !== undefined)) {     // Garantimos que será somado apenas uma vez por localização.
+                if (req.projections && (!verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id]) && (currentEnrollmentOfferDay.enrollments !== undefined)) {     // Garantimos que será somado apenas uma vez por localização.
                     // Projeção de matricula multiplicada pelo indice de distribuição de matriculas da localização.
-                    verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] = enrollment.night_time;
+                    verifySchoolYear[location.location_id-1][educationLevel.education_level_short_id] = 1;
 
-                    if (!enrollment.night_time) {
-                        educationLevel.enrollment.total_enrollment_day += Math.ceil((currentEnrollmentOfferDay.enrollments[yearCount].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm);
-                        if (educationLevel.enrollment.total_enrollment_day < 0) educationLevel.enrollment.total_enrollment_day = 0;
-                    } else {
-                        educationLevel.enrollment.total_enrollment_night += (educationLevel.education_level_short_id > 2) ? Math.ceil((currentEnrollmentOfferNight.enrollments[yearCount].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm) : 0;
-                        if (educationLevel.enrollment.total_enrollment_night < 0) educationLevel.enrollment.total_enrollment_night = 0;
-                    }
+                    educationLevel.enrollment.total_enrollment_day += Math.ceil((currentEnrollmentOfferDay.enrollments[yearCount].quantity - currentEnrollmentOfferDay.currentOffer)*enrollmentIdm.idm);
+                    if (educationLevel.enrollment.total_enrollment_day < 0) educationLevel.enrollment.total_enrollment_day = 0;
+                    educationLevel.enrollment.total_enrollment_night += (educationLevel.education_level_short_id > 2) ? Math.ceil((currentEnrollmentOfferNight.enrollments[yearCount].quantity - currentEnrollmentOfferNight.currentOffer)*enrollmentIdm.idm) : 0;
+                    if (educationLevel.enrollment.total_enrollment_night < 0) educationLevel.enrollment.total_enrollment_night = 0;
                 }
 
                 // Calcula o número de turmas parcial
@@ -601,8 +598,8 @@ classroomCountApp.post('/', rqf.parse(), (req, res, next) => {
                     // Totais de matrícula
                     currentSchoolYear.total_enrollment_day += enrollment.total_day;
 
-                    if (req.projections && !verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] !== enrollment.night_time) {     // Garantimos que será somado apenas uma vez por localização.
-                        verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] = enrollment.night_time;
+                    if (req.projections && !verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id]) {     // Garantimos que será somado apenas uma vez por localização.
+                        verifySchoolYear[location.location_id-1][currentSchoolYear.school_year_id] = 1;
 
                         let currentEnrollmentSchoolYear = currentEnrollmentOfferDay.seriesEnrollments[Math.trunc(currentSchoolYear.school_year_id/10) - 1];
                         currentSchoolYear.total_enrollment_day += (currentEnrollmentSchoolYear !== undefined) ? Math.ceil((currentEnrollmentSchoolYear.enrollments[yearCount].quantity - currentEnrollmentSchoolYear.currentOffer)*enrollmentIdm.idm) : 0;
-- 
GitLab


From 015539e45448817d16e40f7a23e5098efbc1399b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Mon, 10 Jun 2019 10:21:43 -0300
Subject: [PATCH 111/142] Change transport route to use an aggregate table

---
 src/libs/convert/transport.js  |  48 +++++
 src/libs/middlewares/id2str.js |   7 +-
 src/libs/routes/transport.js   | 340 +++++++++++----------------------
 3 files changed, 160 insertions(+), 235 deletions(-)
 create mode 100644 src/libs/convert/transport.js

diff --git a/src/libs/convert/transport.js b/src/libs/convert/transport.js
new file mode 100644
index 00000000..f5dbeadb
--- /dev/null
+++ b/src/libs/convert/transport.js
@@ -0,0 +1,48 @@
+/*
+Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+
+This file is part of simcaq-node.
+
+simcaq-node is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+simcaq-node is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
+*/
+
+module.exports = function teacherSituation(id) {
+    switch (id) {
+        case 1:
+        return 'public_transport';
+        case 2:
+        return 'van_and_kombi';
+        case 3:
+        return 'micro_bus';
+        case 4:
+        return 'bus';
+        case 5:
+        return 'bike';
+        case 6:
+        return 'animal_traction';
+        case 7:
+        return 'other_vehicle';
+        case 8:
+        return 'waterway_5_Students';
+        case 9:
+        return 'waterway_15_Students';
+        case 10:
+        return 'waterway_35_Students';
+        case 11:
+        return 'waterway_More_Than_35';
+        case 12:
+        return 'subway_and_train';
+    }
+};
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index 51ffccd4..d800505c 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -49,6 +49,7 @@ const fifthHouseholdIncome = require(`${libs}/convert/fifthHouseholdIncome`);
 const extremesHouseholdIncome = require(`${libs}/convert/extremesHouseholdIncome`);
 const educationLevelBasic = require(`${libs}/convert/educationLevelBasic`);
 const useTransport = require(`${libs}/convert/booleanVariable`);
+const transport = require(`${libs}/convert/transport`);
 const useTransportPublic = require(`${libs}/convert/booleanVariable`);
 const transportationManager = require(`${libs}/convert/transportationManager`);
 const specialClass = require(`${libs}/convert/booleanVariable`);
@@ -147,7 +148,8 @@ const ids = {
     ethnic_group_teacher_ies_id: ethnicGroupTeacherIES,
     gender_ies_id: genderIES,
     deficiency_id: deficiency,
-    age_student_code_id: ageStudentCode
+    age_student_code_id: ageStudentCode,
+    transport_id: transport
 };
 
 function transform(removeId=false) {
@@ -243,5 +245,6 @@ module.exports = {
     teacherSchooling,
     ethnicGroupTeacherIES,
     genderIES,
-    deficiency
+    deficiency,
+    transport
 };
diff --git a/src/libs/routes/transport.js b/src/libs/routes/transport.js
index 6435833b..2d55b556 100644
--- a/src/libs/routes/transport.js
+++ b/src/libs/routes/transport.js
@@ -30,8 +30,6 @@ const squel = require('squel');
 
 const query = require(`${libs}/middlewares/query`).query;
 
-const multiQuery = require(`${libs}/middlewares/multiQuery`);
-
 const response = require(`${libs}/middlewares/response`);
 
 const addMissing = require(`${libs}/middlewares/addMissing`);
@@ -49,15 +47,15 @@ let rqf = new ReqQueryFields();
 transportApp.use(cache('15 day'));
 
 transportApp.get('/year_range', (req, res, next) => {
-    req.sql.from('matricula')
-    .field('MIN(matricula.ano_censo)', 'start_year')
-    .field('MAX(matricula.ano_censo)', 'end_year');
+    req.sql.from('transporte')
+    .field('MIN(transporte.ano_censo)', 'start_year')
+    .field('MAX(transporte.ano_censo)', 'end_year');
     next();
 }, query, response('range'));
 
 transportApp.get('/years', (req, res, next) => {
-    req.sql.from('matricula')
-    .field('DISTINCT matricula.ano_censo', 'year');
+    req.sql.from('transporte')
+    .field('DISTINCT transporte.ano_censo', 'year');
     next();
 }, query, response('years'));
 
@@ -168,7 +166,7 @@ rqf.addField({
     join: {
         primary: ['id', 'ano_censo'],
         foreign: ['escola_id', 'ano_censo'],
-        foreignTable: 'matricula'
+        foreignTable: 'transporte'
     }
 }).addValue({
     name: 'region',
@@ -183,7 +181,7 @@ rqf.addField({
     join: {
         primary: 'id',
         foreign: 'regiao_id',
-        foreignTable: 'matricula'
+        foreignTable: 'transporte'
     }
 }).addValue({
     name: 'city',
@@ -194,32 +192,27 @@ rqf.addField({
         relation: '=',
         type: 'integer',
         field: 'municipio_id',
-        table: 'matricula'
+        table: 'transporte'
     },
     join: {
         primary: 'id',
         foreign: 'municipio_id',
-        foreignTable: 'matricula'
+        foreignTable: 'transporte'
     }
 }).addValue({
     name: 'state',
-    table: 'estado',
-    tableField: 'nome',
-    resultField: 'state_name',
+    table: 'transporte',
+    tableField: ['estado_nome', 'estado_id'],
+    resultField: ['state_name', 'state_id'],
     where: {
         relation: '=',
         type: 'integer',
         field: 'estado_id',
-        table: 'matricula'
-    },
-    join: {
-        primary: 'id',
-        foreign: 'estado_id',
-        foreignTable: 'matricula'
+        table: 'transporte'
     }
 }).addValue({
     name: 'rural_location',
-    table: 'matricula',
+    table: 'transporte',
     tableField: 'localidade_area_rural',
     resultField: 'rural_location_id',
     where: {
@@ -229,7 +222,7 @@ rqf.addField({
     }
 }).addValue({
     name: 'location',
-    table: 'matricula',
+    table: 'transporte',
     tableField: 'localizacao_id',
     resultField: 'location_id',
     where: {
@@ -239,7 +232,7 @@ rqf.addField({
     }
 }).addValue({
     name:'adm_dependency',
-    table: 'matricula',
+    table: 'transporte',
     tableField: 'dependencia_adm_id',
     resultField: 'adm_dependency_id',
     where: {
@@ -249,7 +242,7 @@ rqf.addField({
     }
 }).addValue({
     name: 'adm_dependency_detailed',
-    table: 'matricula',
+    table: 'transporte',
     tableField: 'dependencia_adm_priv',
     resultField: 'adm_dependency_detailed_id',
     where: {
@@ -259,7 +252,7 @@ rqf.addField({
     }
 }).addValue({
     name: 'transportation_manager',
-    table: 'matricula',
+    table: 'transporte',
     tableField: 'responsavel_transp',
     resultField: 'transportation_manager_id',
     where: {
@@ -269,7 +262,7 @@ rqf.addField({
     }
 }).addValue({
     name: 'education_level_mod',
-    table: 'matricula',
+    table: 'transporte',
     tableField: 'etapas_mod_ensino_segmento_id',
     resultField: 'education_level_mod_id',
     where: {
@@ -279,7 +272,7 @@ rqf.addField({
     }
 }).addValue({
     name: 'service_type',
-    table: 'matricula',
+    table: 'transporte',
     tableField: 'tipo',
     resultField: 'service_type_id',
     where: {
@@ -289,7 +282,7 @@ rqf.addField({
     }
 }).addValue({
     name: 'min_year',
-    table: 'matricula',
+    table: 'transporte',
     tableField: 'ano_censo',
     resultField: 'year',
     where: {
@@ -299,7 +292,7 @@ rqf.addField({
     }
 }).addValue({
     name: 'max_year',
-    table: 'matricula',
+    table: 'transporte',
     tableField: 'ano_censo',
     resultField: 'year',
     where: {
@@ -307,217 +300,98 @@ rqf.addField({
         type: 'integer',
         field: 'ano_censo'
     }
+}).addValue({
+    name: 'year',
+    table: 'transporte',
+    tableField: 'ano_censo',
+    resultField: 'year',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'ano_censo'
+    }
 });
 
-function matchQueries(queryTotal, queryPartial) {
-    let match = [];
-    queryTotal.forEach((result) => {
-        let newObj = {};
-        let keys = Object.keys(result);
-        keys.forEach((key) => {
-            newObj[key] = result[key];
-        });
-        let index = keys.indexOf('total');
-        if(index > -1) keys.splice(index, 1);
-        let objMatch = null;
-
-        for(let i = 0; i < queryPartial.length; ++i) {
-            let partial = queryPartial[i];
-            let foundMatch = true;
-            for(let j = 0; j < keys.length; ++j) {
-                let key = keys[j];
-                if(partial[key] !== result[key]) {
-                    foundMatch = false;
-                    break;
+transportApp.get('/', rqf.parse(), (req, res, next) => {
+    req.dims.year = true;
+    req.sql
+        .field('sum(transporte.total)', 'total')
+        .field("'Brasil'", 'name')
+        .from('transporte')
+        .where('transporte.transporte_id=0')
+    next();
+}, rqf.build(), query, id2str.transform(), (req, res, next) => {
+    req.total = req.result;
+    console.log('here');
+    req.resetSql();
+    next();
+}, rqf.parse(), (req, res, next) => {
+    req.dims.year = true;
+    req.sql
+        .field('sum(transporte.total)', 'total')
+        .field("'Brasil'", 'name')
+        .from('transporte')
+        .where('transporte.transporte_id=1')
+    next();
+}, rqf.build(), query, id2str.transform(), (req, res, next) => {
+    req.public_total = req.result;
+    console.log('here');
+    req.resetSql();
+    next();
+
+}, rqf.parse(), (req, res, next) => {
+    req.dims.year = true;
+    req.sql
+        .field('sum(transporte.total)', 'total')
+        .field("'Brasil'", 'name')
+        .field('transporte.transporte_id', 'id')
+        .from('transporte')
+        .where('transporte.transporte_id>0')
+        .group('transporte.transporte_id')
+        .order('transporte.transporte_id')
+    next();
+}, rqf.build(), query, id2str.transform(), (req, res, next) => {
+    let transports = req.result;
+    let results = [];
+    let obj = {};
+    let i = 0
+    while (i < transports.length) {
+        let result = [];
+        let j = 0;
+        let transport = transports[i];
+        let totalArray = (transport.id  == 1) ? req.total : req.public_total;
+        let match;
+        obj[id2str.transport(transport.id)] = result;
+        while (j < totalArray.length && i < transports.length) {
+            transport = transports[i];
+            let transportTotal = totalArray[j];
+
+            let currentTransport = {};
+            delete transport.id;
+            match = true;
+            Object.keys(transport).forEach(function(key) {
+                currentTransport[key] = transportTotal[key];
+                if (key != 'total' && transport[key] != transportTotal[key]) {
+                    match = false;
+                    return;
                 }
+            })
+
+            if (match) {
+                currentTransport.partial = (match) ? transport.total : 0;
+                currentTransport.percentage = (match) ? transport.total/transportTotal.total * 100 : 0;
+                result.push(currentTransport);
+                i++;
+                j++;
             }
-            if(foundMatch) {
-                objMatch = partial;
-                break;
-            }
+            else
+                j++;
         }
-
-        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])
     }
+    results.push(obj)
+    req.result = results;
 
-    let public_transport = matchQueries(all_enrollment_match, req.result[req.queryIndex.allEnrollmentTransport]);
-    let van_and_kombi = matchQueries(transport_match, req.result[req.queryIndex.goVansAndKombi]);
-    let micro_bus = matchQueries(transport_match, req.result[req.queryIndex.goMicroBus]);
-    let bus = matchQueries(transport_match, req.result[req.queryIndex.goBus]);
-    let bike = matchQueries(transport_match, req.result[req.queryIndex.goBikes]);
-    let animal_traction = matchQueries(transport_match, req.result[req.queryIndex.goAnimalTraction]);
-    let other_vehicle = matchQueries(transport_match, req.result[req.queryIndex.goOtherVehicle]);
-    let waterway_5_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_5_Students]);
-    let waterway_15_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_15_Students]);
-    let waterway_35_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_35_Students]);
-    let waterway_More_Than_35 = matchQueries(transport_match, req.result[req.queryIndex.goWaterwayMoreThan_35]);
-    let subway_and_train = matchQueries(transport_match, req.result[req.queryIndex.goSubwayAndTrain]);
-
-    req.result = [{
-        public_transport,
-        van_and_kombi,
-        micro_bus,
-        bus,
-        bike,
-        animal_traction,
-        other_vehicle,
-        waterway_5_Students,
-        waterway_15_Students,
-        waterway_35_Students,
-        waterway_More_Than_35,
-        subway_and_train
-    }];
     next();
-}, id2str.multitransform(false), response('transports'));
+}, response('transports'));
 
 module.exports = transportApp;
-- 
GitLab


From 74809066beb9cba1fe61a970185215df2850ad76 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Mon, 10 Jun 2019 10:55:45 -0300
Subject: [PATCH 112/142] [change_variables]Modify existing variables

---
 src/libs/routes/university.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index 826a6b76..af733785 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -275,7 +275,7 @@ rqfCount.addField({
 }).addValue({
     name: 'upper_adm_dependency',
     table: 'ies_ens_superior',
-    tableField: 'cod_categoria_administrativa',
+    tableField: 'par_categoria_administrativa',
     resultField: 'upper_adm_dependency_id',
     where: {
         relation: '=',
@@ -297,7 +297,7 @@ rqfCount.addField({
 }).addValue({
     name: 'capital',
     table: 'ies_ens_superior',
-    tableField: 'capital_ies',
+    tableField: 'tfd_capital_ies',
     resultField: 'capital_id',
     where: {
         relation: '=',
-- 
GitLab


From ddc3b8d121a44a1a06ace9eb4bb045dda883987a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Mon, 10 Jun 2019 11:55:55 -0300
Subject: [PATCH 113/142] Fix transport when missing a type

---
 src/libs/routes/transport.js | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/src/libs/routes/transport.js b/src/libs/routes/transport.js
index 2d55b556..8327c4f6 100644
--- a/src/libs/routes/transport.js
+++ b/src/libs/routes/transport.js
@@ -352,8 +352,13 @@ transportApp.get('/', rqf.parse(), (req, res, next) => {
     next();
 }, rqf.build(), query, id2str.transform(), (req, res, next) => {
     let transports = req.result;
+
     let results = [];
     let obj = {};
+    for (let i = 1; i < 13; i++) {
+        obj[id2str.transport(i)] = [];
+    }
+
     let i = 0
     while (i < transports.length) {
         let result = [];
-- 
GitLab


From e7106ad4bdd338f4c7cae6842c738e9919da9962 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 11 Jun 2019 09:11:10 -0300
Subject: [PATCH 114/142] years restriction open

---
 src/libs/routes/university.js | 1 -
 1 file changed, 1 deletion(-)

diff --git a/src/libs/routes/university.js b/src/libs/routes/university.js
index af733785..959f4adb 100644
--- a/src/libs/routes/university.js
+++ b/src/libs/routes/university.js
@@ -64,7 +64,6 @@ universityApp.get('/upper_adm_dependency', (req, res, next) => {
 universityApp.get('/years', (req, res, next) => {
     req.sql.from('ies_ens_superior')
     .field('DISTINCT ies_ens_superior.ano_censo', 'year')
-    .where('ies_ens_superior.ano_censo = 2017');
     next();
 }, query, response('years'));
 
-- 
GitLab


From a027ab17d5a621f3e63347dec0547c118b9194cc Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Mon, 24 Jun 2019 11:40:35 -0300
Subject: [PATCH 115/142] [course_count]Course count variables modified

---
 src/libs/routes/courseCount.js | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index b80e38eb..6038565b 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -247,12 +247,12 @@ rqf.addField({
 }).addValue({
     name:'upper_adm_dependency',
     table: 'curso_ens_superior',
-    tableField: 'cod_categoria_administrativa',
+    tableField: 'par_categoria_administrativa',
     resultField: 'upper_adm_dependency_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'cod_categoria_administrativa'
+        field: 'par_categoria_administrativa'
     }
 }).addValue({
     name:'academic_organization',
@@ -267,12 +267,12 @@ rqf.addField({
 }).addValue({
     name:'capital',
     table: 'curso_ens_superior',
-    tableField: 'capital_curso',
+    tableField: 'tfd_capital_curso',
     resultField: 'capital_id',
     where: {
         relation: '=',
         type: 'integer',
-        field: 'capital_curso'
+        field: 'tfd_capital_curso'
     }
 }).addValue({
     name:'course',
-- 
GitLab


From dadc030c446902394fd8084355cee1e895ba517d Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 25 Jun 2019 11:06:43 -0300
Subject: [PATCH 116/142] [lon_lat]Added longitute and latitude to indicators

---
 src/libs/routes/city.js  |  4 +++-
 src/libs/routes/state.js | 14 ++++++--------
 2 files changed, 9 insertions(+), 9 deletions(-)

diff --git a/src/libs/routes/city.js b/src/libs/routes/city.js
index 9342f64c..09a27630 100644
--- a/src/libs/routes/city.js
+++ b/src/libs/routes/city.js
@@ -89,7 +89,9 @@ cityApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.sql.from('municipio')
     .field('municipio.nome', 'name')
     .field('municipio.id')
-    .field('municipio.estado_id', 'state_id');
+    .field('municipio.estado_id', 'state_id')
+    .field('municipio.longitude', 'longitude')
+    .field('municipio.latitude', 'latitude');
     next();
 }, query, response('city'));
 
diff --git a/src/libs/routes/state.js b/src/libs/routes/state.js
index cb84a096..8f4f91ed 100644
--- a/src/libs/routes/state.js
+++ b/src/libs/routes/state.js
@@ -86,14 +86,12 @@ rqf.addField({
 
 stateApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.sql.from('estado')
-        .field('estado.id')
-        .group('estado.id')
-        .field('regiao_id', 'region_id')
-        .group('regiao_id')
-        .field('estado.nome', 'name')
-        .group('estado.nome')
-        .field('estado.sigla', 'abbreviation')
-        .group('estado.sigla');
+        .field('estado.id').group('estado.id')
+        .field('regiao_id', 'region_id').group('regiao_id')
+        .field('estado.nome', 'name').group('estado.nome')
+        .field('estado.sigla', 'abbreviation').group('estado.sigla')
+        .field('estado.longitude', 'longitude')
+        .field('estado.latitude', 'latitude');
     next();
 }, query, response('state'));
 
-- 
GitLab


From 30a323337fe70128a408f53ba90b2ae8b53855c6 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 25 Jun 2019 11:16:06 -0300
Subject: [PATCH 117/142] [lon_lat]Fix group

---
 src/libs/routes/state.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/state.js b/src/libs/routes/state.js
index 8f4f91ed..6fab1fc8 100644
--- a/src/libs/routes/state.js
+++ b/src/libs/routes/state.js
@@ -90,8 +90,8 @@ stateApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
         .field('regiao_id', 'region_id').group('regiao_id')
         .field('estado.nome', 'name').group('estado.nome')
         .field('estado.sigla', 'abbreviation').group('estado.sigla')
-        .field('estado.longitude', 'longitude')
-        .field('estado.latitude', 'latitude');
+        .field('estado.longitude', 'longitude').group('estado.longitude')
+        .field('estado.latitude', 'latitude').group('estado.latitude');
     next();
 }, query, response('state'));
 
-- 
GitLab


From 38435268b5b5386efe1666b2fec17c9667230a80 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Tue, 25 Jun 2019 11:46:49 -0300
Subject: [PATCH 118/142] [development]Ferd modification

---
 src/libs/routes/enrollment.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js
index be61a306..39ed82f2 100644
--- a/src/libs/routes/enrollment.js
+++ b/src/libs/routes/enrollment.js
@@ -271,7 +271,7 @@ rqf.addField({
     resultField: 'adm_dependency_id',
     where: {
         relation: '=',
-        type: 'integer',
+        type: 'boolean',
         field: 'dependencia_adm_id'
     }
 }).addValue({
-- 
GitLab


From b02bbc9ee84a2b9cbe79aeff06bde84a369168e9 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Fri, 28 Jun 2019 10:40:00 -0300
Subject: [PATCH 119/142] [course_fix]Fix order

---
 src/libs/routes/courseCount.js | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index 6038565b..62a374c9 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -398,7 +398,7 @@ rqf.addField({
     }
 });
 
-courseCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
+courseCountApp.get('/', rqf.parse(), (req, res, next) => {
     req.sql.from('curso_ens_superior')
         .field('COUNT(curso_ens_superior.cod_curso)', 'total')
         .field("'Brasil'", 'name')
@@ -407,8 +407,7 @@ courseCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
         .order('curso_ens_superior.ano_censo')
         .where('curso_ens_superior.tipo_atributo_ingresso <> 1')
         .where('curso_ens_superior.cod_nivel_academico = 1');
-
     next();
-}, query, addMissing(rqf), id2str.transform(), response('course_count'));
+}, rqf.build(), query, id2str.transform(), addMissing(rqf), response('course_count'));
 
 module.exports = courseCountApp;
-- 
GitLab


From d8db0517c054d95a4d0be2587f7dfd57b5ec7ed7 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Fri, 28 Jun 2019 11:10:07 -0300
Subject: [PATCH 120/142] [course_fix]NULL querry fix

---
 src/libs/routes/courseCount.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/libs/routes/courseCount.js b/src/libs/routes/courseCount.js
index 62a374c9..c59892e7 100644
--- a/src/libs/routes/courseCount.js
+++ b/src/libs/routes/courseCount.js
@@ -405,7 +405,7 @@ courseCountApp.get('/', rqf.parse(), (req, res, next) => {
         .field('curso_ens_superior.ano_censo', 'year')
         .group('curso_ens_superior.ano_censo')
         .order('curso_ens_superior.ano_censo')
-        .where('curso_ens_superior.tipo_atributo_ingresso <> 1')
+        .where('curso_ens_superior.tipo_atributo_ingresso <> 1 OR curso_ens_superior.tipo_atributo_ingresso is NULL')
         .where('curso_ens_superior.cod_nivel_academico = 1');
     next();
 }, rqf.build(), query, id2str.transform(), addMissing(rqf), response('course_count'));
-- 
GitLab


From 563a17cef3325ef976b7901f62c4ed6b3454d748 Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Tue, 2 Jul 2019 11:52:49 -0300
Subject: [PATCH 121/142] try .gitlab-ci.yml

---
 .gitlab-ci.yml | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 39587c79..6fedfdeb 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -11,10 +11,11 @@ variables:
   NODE_ENV: 'test'
 
 before_script:
+  - apt-get install git python2.7
   - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
-
+  - git clone git@gitlab.c3sl.ufpr.br:simcaq/lde-api-regression-test.git
 run_tests:
   stage: test
   script:
@@ -22,5 +23,6 @@ run_tests:
     - sed -i -e 's/false/true/g' config.json
     - gulp build
     - gulp test
+    - python lde-api-regression-test/regression_test.py
   tags:
     - node
-- 
GitLab


From ff51d7916d4f28b8b0774eba945e770243755334 Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Tue, 2 Jul 2019 12:07:26 -0300
Subject: [PATCH 122/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 1 -
 1 file changed, 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 6fedfdeb..d82a6262 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -11,7 +11,6 @@ variables:
   NODE_ENV: 'test'
 
 before_script:
-  - apt-get install git python2.7
   - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
-- 
GitLab


From ef351ac3e82d86bada4cf7fe15fe85e05684fba6 Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Tue, 2 Jul 2019 14:20:53 -0300
Subject: [PATCH 123/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index d82a6262..916b13d0 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -14,7 +14,7 @@ before_script:
   - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
-  - git clone git@gitlab.c3sl.ufpr.br:simcaq/lde-api-regression-test.git
+  - git clone https://gitlab.c3sl.ufpr.br/simcaq/lde-api-regression-test.git
 run_tests:
   stage: test
   script:
-- 
GitLab


From dcfecb3c94c7968433d99c7ad4f79d800beab32a Mon Sep 17 00:00:00 2001
From: hi15 <hi15@inf.ufpr.br>
Date: Tue, 2 Jul 2019 14:52:59 -0300
Subject: [PATCH 124/142] Add submodule of regression test

---
 .gitmodules             | 3 +++
 lde-api-regression-test | 1 +
 2 files changed, 4 insertions(+)
 create mode 100644 .gitmodules
 create mode 160000 lde-api-regression-test

diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 00000000..bbec3a97
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "lde-api-regression-test"]
+	path = lde-api-regression-test
+	url = git@gitlab.c3sl.ufpr.br:simcaq/lde-api-regression-test.git
diff --git a/lde-api-regression-test b/lde-api-regression-test
new file mode 160000
index 00000000..24788fc6
--- /dev/null
+++ b/lde-api-regression-test
@@ -0,0 +1 @@
+Subproject commit 24788fc662e682fc92bb108cb4ef4ac3f8687dd9
-- 
GitLab


From 3d7d77fe60f1f67dc12cbd02d29ee258174eda03 Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Tue, 2 Jul 2019 14:55:25 -0300
Subject: [PATCH 125/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 1 -
 1 file changed, 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 916b13d0..7b6efd62 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -14,7 +14,6 @@ before_script:
   - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
-  - git clone https://gitlab.c3sl.ufpr.br/simcaq/lde-api-regression-test.git
 run_tests:
   stage: test
   script:
-- 
GitLab


From 6e38a353beed38bd4ff435802b5184cf2113a6cf Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Tue, 2 Jul 2019 15:21:33 -0300
Subject: [PATCH 126/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 7b6efd62..a19dcae0 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -17,10 +17,10 @@ before_script:
 run_tests:
   stage: test
   script:
+    - python lde-api-regression-test/regression_test.py
     - ping -W1 -c1 mongo
     - sed -i -e 's/false/true/g' config.json
     - gulp build
     - gulp test
-    - python lde-api-regression-test/regression_test.py
   tags:
     - node
-- 
GitLab


From c60e4860295e818dee541a43a6d88a8f81f2cb2a Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Tue, 2 Jul 2019 15:34:38 -0300
Subject: [PATCH 127/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index a19dcae0..277e1fb5 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,6 +1,7 @@
 image: node:9.2.1
 
 stages:
+  - regression_test_api
   - test
 
 services:
@@ -14,10 +15,16 @@ before_script:
   - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
+  
+run_regression_test:
+  stage: regression_test_api
+  script:
+    - cd lde-api-regression-test
+    - python regression_test.py --compare
+
 run_tests:
   stage: test
   script:
-    - python lde-api-regression-test/regression_test.py
     - ping -W1 -c1 mongo
     - sed -i -e 's/false/true/g' config.json
     - gulp build
-- 
GitLab


From c653f4b960e731b9d67edafb259e327d81ddb718 Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Wed, 3 Jul 2019 14:49:10 -0300
Subject: [PATCH 128/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 277e1fb5..56f127bb 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -20,6 +20,7 @@ run_regression_test:
   stage: regression_test_api
   script:
     - cd lde-api-regression-test
+    - ls
     - python regression_test.py --compare
 
 run_tests:
-- 
GitLab


From 772ba774519355dd5f69faeb8dff5bd5e6f31ff6 Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Wed, 3 Jul 2019 14:51:15 -0300
Subject: [PATCH 129/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 11 +++--------
 1 file changed, 3 insertions(+), 8 deletions(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 56f127bb..f34470bd 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,7 +1,6 @@
 image: node:9.2.1
 
 stages:
-  - regression_test_api
   - test
 
 services:
@@ -15,17 +14,13 @@ before_script:
   - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
-  
-run_regression_test:
-  stage: regression_test_api
-  script:
-    - cd lde-api-regression-test
-    - ls
-    - python regression_test.py --compare
 
 run_tests:
   stage: test
   script:
+    - cd lde-api-regression-test
+    - ls
+    - python regression_test.py --compare
     - ping -W1 -c1 mongo
     - sed -i -e 's/false/true/g' config.json
     - gulp build
-- 
GitLab


From b043f94ff84a00c214889646837c96991d9703ec Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Wed, 3 Jul 2019 15:36:18 -0300
Subject: [PATCH 130/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index f34470bd..ed8cd3f8 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -9,6 +9,7 @@ services:
 variables:
   MONGO_URI: 'mongodb://mongo/app_name'
   NODE_ENV: 'test'
+  GIT_SUBMODULE_STRATEGY: 'normal'
 
 before_script:
   - node -v
@@ -19,7 +20,6 @@ run_tests:
   stage: test
   script:
     - cd lde-api-regression-test
-    - ls
     - python regression_test.py --compare
     - ping -W1 -c1 mongo
     - sed -i -e 's/false/true/g' config.json
-- 
GitLab


From e4580267e7eeb87f994e2355b1fa75a356b39b62 Mon Sep 17 00:00:00 2001
From: Victor Picussa <vp16@inf.ufpr.br>
Date: Thu, 4 Jul 2019 10:02:05 -0300
Subject: [PATCH 131/142] [teacher_fix]Removed not classified query

---
 src/libs/routes/teacher.js | 36 +-----------------------------------
 1 file changed, 1 insertion(+), 35 deletions(-)

diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js
index f503963e..ff712b52 100644
--- a/src/libs/routes/teacher.js
+++ b/src/libs/routes/teacher.js
@@ -97,11 +97,6 @@ teacherApp.get('/education_level_mod', (req, res, next) => {
             name: id2str.educationLevelMod(i)
         });
     }
-
-    req.result.push({
-        id: 99,
-        name: id2str.educationLevelMod(99)
-    });
     next();
 }, response('education_level_mod'));
 
@@ -424,35 +419,6 @@ teacherApp.get('/', rqf.parse(), (req, res, next) => {
     }
 
     next();
-}, rqf.build(), query, addMissing(rqf), (req, res, next) => {
-    req.oldResult = req.result;
-    if(req.hadEducationLevelMod) {
-
-        req.sql = squel.select()
-        .field('COUNT(DISTINCT docente.id_docente)', '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'));
+}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('teacher'));
 
 module.exports = teacherApp;
-- 
GitLab


From 93b8ea659eff94dff3e8d8c348e2fd6eed0b9b56 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Thu, 4 Jul 2019 11:20:00 -0300
Subject: [PATCH 132/142] Fix ferd modifications

---
 src/libs/routes/enrollment.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js
index 39ed82f2..be61a306 100644
--- a/src/libs/routes/enrollment.js
+++ b/src/libs/routes/enrollment.js
@@ -271,7 +271,7 @@ rqf.addField({
     resultField: 'adm_dependency_id',
     where: {
         relation: '=',
-        type: 'boolean',
+        type: 'integer',
         field: 'dependencia_adm_id'
     }
 }).addValue({
-- 
GitLab


From 90c8b41e002fd0ea31bbb04c8c49b7b3ebadafe8 Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Thu, 4 Jul 2019 18:25:03 -0300
Subject: [PATCH 133/142] fix bug in matchQueries

---
 src/libs/routes/schoolInfrastructure.js | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/src/libs/routes/schoolInfrastructure.js b/src/libs/routes/schoolInfrastructure.js
index 27902c97..7bdf6182 100644
--- a/src/libs/routes/schoolInfrastructure.js
+++ b/src/libs/routes/schoolInfrastructure.js
@@ -312,12 +312,12 @@ function matchQueries(queryTotal, queryPartial, queryNeeded, zeroPercentage=fals
             needMatch.total = 0;
         }
 
-        if(partialMatch && needMatch) {
+        if(partialMatch) {
             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;
+            newObj.need_adaptation = needMatch ? needMatch.total : 0;
             match.push(newObj);
         }
     });
@@ -467,6 +467,9 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.queryIndex.needSportsCourt = req.querySet.push(needSportsCourt) - 1;
 
     // Cobertura de quadra esportiva
+    // Se (situacao_de_funcionamento=1) and (ensino_regular=1 OR ensino_eja=1 OR educacao_profissional=1) and (local_func_predio_escolar=1) and 
+    // (dependencia_adm_id<=3) and (reg_fund_ai_t1=1  or reg_fund_af_t1=1 or  reg_medio_medio_t1=1  or  ensino_eja_fund= 1 or ensino_eja_medio= 1 or 
+    // ensino_eja_prof= 1 or esp_eja_fund=1 or esp_eja_medio=1 or ensino_esp_exclusiva_eja_prof=1) and (quadra_esportes_descoberta=1) então conta id
     let allSportsCourtCoverage = allSportsCourt.clone();
     allSportsCourtCoverage.where('escola.quadra_esportes_descoberta = 1');
     req.queryIndex.allSportsCourtCoverage = req.querySet.push(allSportsCourtCoverage) -1;
@@ -680,6 +683,7 @@ infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
 
     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];
-- 
GitLab


From 52c188f4e1f3a4dd2745c650efda81aa7128bf19 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Fri, 5 Jul 2019 09:07:28 -0300
Subject: [PATCH 134/142] Add series not present with 0 to
 enrollment_projection when using state or city filters

---
 src/libs/routes/enrollmentProjection.js | 83 +++++++++++++++++++------
 1 file changed, 64 insertions(+), 19 deletions(-)

diff --git a/src/libs/routes/enrollmentProjection.js b/src/libs/routes/enrollmentProjection.js
index 47eb7b71..8a25fb6c 100644
--- a/src/libs/routes/enrollmentProjection.js
+++ b/src/libs/routes/enrollmentProjection.js
@@ -130,29 +130,74 @@ rqf.addField({
 
 enrollmentProjectionApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
     req.sql.field("'Brasil'", 'name')
-    .field('SUM(projecao_matricula.urbano_dia_total)', 'urban_day_total')
-    .field('SUM(projecao_matricula.urbano_noite_total)', 'urban_night_total')
-    .field('SUM(projecao_matricula.rural_dia_total)', 'rural_day_total')
-    .field('SUM(projecao_matricula.rural_noite_total)', 'rural_night_total')
-    .field('projecao_matricula.etapa_ensino_escola_ano_id', 'education_level_school_year_id')
-    .field('projecao_matricula.ano_censo', 'year')
-    .from('projecao_matricula')
-    .where('projecao_matricula.etapa_ensino_escola_ano_id <> 7 AND projecao_matricula.etapa_ensino_escola_ano_id < 71')
-    .group('projecao_matricula.etapa_ensino_escola_ano_id')
-    .group('projecao_matricula.ano_censo')
-    .order('projecao_matricula.ano_censo')
-    .order('projecao_matricula.etapa_ensino_escola_ano_id');
+        .field('SUM(projecao_matricula.urbano_dia_total)', 'urban_day_total')
+        .field('SUM(projecao_matricula.urbano_noite_total)', 'urban_night_total')
+        .field('SUM(projecao_matricula.rural_dia_total)', 'rural_day_total')
+        .field('SUM(projecao_matricula.rural_noite_total)', 'rural_night_total')
+        .field('projecao_matricula.etapa_ensino_escola_ano_id', 'education_level_school_year_id')
+        .field('projecao_matricula.ano_censo', 'year')
+        .from('projecao_matricula')
+        .where('projecao_matricula.etapa_ensino_escola_ano_id <> 7 AND projecao_matricula.etapa_ensino_escola_ano_id < 71')
+        .group('projecao_matricula.etapa_ensino_escola_ano_id')
+        .group('projecao_matricula.ano_censo')
+        .order('projecao_matricula.ano_censo')
+        .order('projecao_matricula.etapa_ensino_escola_ano_id');
 
     next();
 }, query, id2str.transform(), (req, res, next) => {
 
-    req.result.forEach((r) => {
-        r.urban_day_total = parseInt(r.urban_day_total, 10);
-        r.urban_night_total = ((r.education_level_school_year_id >= 3 && r.education_level_school_year_id < 10) || (r.education_level_school_year_id >= 30)) ? parseInt(r.urban_night_total, 10) : 0;   //Não conta matrículas noturnas da pré-escola e da creche
-        r.rural_day_total = parseInt(r.rural_day_total, 10);
-        r.rural_night_total = ((r.education_level_school_year_id >= 3 && r.education_level_school_year_id < 10) || (r.education_level_school_year_id >= 30)) ? parseInt(r.rural_night_total, 10) : 0;
-    });
-    
+    let result = [];
+    if ('city' in req.filter || 'state' in req.filter) {        // Adciona séries não existentes no banco com 0 nos totais.
+        let i = 0;
+        let j = 1;
+        let base_year = req.result[0].year
+        while (i < req.result.length) {
+            if (j > 71) {       // Caso j passou da última série existente, mudamos de ano.
+                j = 1;
+                base_year++;
+            }
+            if (id2str.educationLevelSchoolYear(j) === id2str.educationLevelSchoolYear(99)) {
+                j++;
+                continue;
+            }
+
+            let atual = req.result[i];
+            if (atual.education_level_school_year_id === j) {   // Série existe.
+                atual.urban_day_total = parseInt(atual.urban_day_total, 10);
+                atual.urban_night_total = ((atual.education_level_school_year_id >= 3 && atual.education_level_school_year_id < 10) || (atual.education_level_school_year_id >= 30)) ? parseInt(atual.urban_night_total, 10) : 0;   //Não conta matrículas noturnas da pré-escola e da creche
+                atual.rural_day_total = parseInt(atual.rural_day_total, 10);
+                atual.rural_night_total = ((atual.education_level_school_year_id >= 3 && atual.education_level_school_year_id < 10) || (atual.education_level_school_year_id >= 30)) ? parseInt(atual.rural_night_total, 10) : 0;
+                result.push(atual);
+
+                i++;
+            }
+            else {      //  Série não existe para a cidade/estado específica, adcionamos 0 ao resultado.
+                let base_result = {
+                    name: req.result[0].name,
+                    urban_day_total: 0,
+                    urban_night_total: 0,
+                    rural_day_total: 0,
+                    rural_night_total: 0,
+                    education_level_school_year_id: j,
+                    year: base_year,
+                    education_level_school_year_name: id2str.educationLevelSchoolYear(j)
+                };
+                result.push(base_result)
+            }
+            j++;
+        }
+        
+        req.result = result;
+    }
+    else {
+        req.result.forEach((r) => {
+            r.urban_day_total = parseInt(r.urban_day_total, 10);
+            r.urban_night_total = ((r.education_level_school_year_id >= 3 && r.education_level_school_year_id < 10) || (r.education_level_school_year_id >= 30)) ? parseInt(r.urban_night_total, 10) : 0;   //Não conta matrículas noturnas da pré-escola e da creche
+            r.rural_day_total = parseInt(r.rural_day_total, 10);
+            r.rural_night_total = ((r.education_level_school_year_id >= 3 && r.education_level_school_year_id < 10) || (r.education_level_school_year_id >= 30)) ? parseInt(r.rural_night_total, 10) : 0;
+        });    
+    }
+
     next();
 }, response('enrollment_projection'));
 
-- 
GitLab


From 659340ee28d3e55712d81d0b97cebaf3895338f1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Frans=20Pondaco=20Winandy?=
 <jvfpw18@inf.ufpr.br>
Date: Fri, 5 Jul 2019 10:16:30 -0300
Subject: [PATCH 135/142] Fix not working with dims

---
 src/libs/routes/enrollmentProjection.js | 109 +++++++++++++++---------
 1 file changed, 67 insertions(+), 42 deletions(-)

diff --git a/src/libs/routes/enrollmentProjection.js b/src/libs/routes/enrollmentProjection.js
index 8a25fb6c..00c75b00 100644
--- a/src/libs/routes/enrollmentProjection.js
+++ b/src/libs/routes/enrollmentProjection.js
@@ -147,57 +147,82 @@ enrollmentProjectionApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
 }, query, id2str.transform(), (req, res, next) => {
 
     let result = [];
-    if ('city' in req.filter || 'state' in req.filter) {        // Adciona séries não existentes no banco com 0 nos totais.
-        let i = 0;
-        let j = 1;
-        let base_year = req.result[0].year
-        while (i < req.result.length) {
-            if (j > 71) {       // Caso j passou da última série existente, mudamos de ano.
-                j = 1;
-                base_year++;
+    let i = 0;
+    let j = 1;
+    let base_year = req.result[0].year;
+
+    let hashSet = new Set();
+    let atual_city_name;
+    let atual_city_id;
+    let atual_state_name;
+    let atual_state_id;
+    while (i < req.result.length || j <= 63) {      // Adciona séries não existentes no banco com 0 nos totais.
+        let atual = req.result[i];
+        if (j > 63) {       // Caso j passou da última série existente, mudamos de dimensão.
+            j = 1;
+
+            if (base_year !== atual.year) {
+                base_year = atual.year;
+                hashSet = new Set();
             }
-            if (id2str.educationLevelSchoolYear(j) === id2str.educationLevelSchoolYear(99)) {
-                j++;
-                continue;
+        }
+        if (id2str.educationLevelSchoolYear(j) === id2str.educationLevelSchoolYear(99) || j === 7) {
+            j++;
+            continue;
+        }
+
+        if (j == 1) {
+            let hash = ""
+            if ('state' in req.dims)
+                hash += atual.state_id;
+            if ('city' in req.dims)
+                hash += atual.city_id;
+
+            if (!hashSet.has(hash)) {
+                hashSet.add(hash);
+                atual_city_id = atual.city_id;
+                atual_city_name = atual.city_name;
+                atual_state_id = atual.state_id;
+                atual_state_name = atual.state_name;
             }
+        }
 
-            let atual = req.result[i];
-            if (atual.education_level_school_year_id === j) {   // Série existe.
-                atual.urban_day_total = parseInt(atual.urban_day_total, 10);
-                atual.urban_night_total = ((atual.education_level_school_year_id >= 3 && atual.education_level_school_year_id < 10) || (atual.education_level_school_year_id >= 30)) ? parseInt(atual.urban_night_total, 10) : 0;   //Não conta matrículas noturnas da pré-escola e da creche
-                atual.rural_day_total = parseInt(atual.rural_day_total, 10);
-                atual.rural_night_total = ((atual.education_level_school_year_id >= 3 && atual.education_level_school_year_id < 10) || (atual.education_level_school_year_id >= 30)) ? parseInt(atual.rural_night_total, 10) : 0;
-                result.push(atual);
+        if (atual !== undefined && atual.education_level_school_year_id === j) {   // Série existe.
+            atual.urban_day_total = parseInt(atual.urban_day_total, 10);
+            atual.urban_night_total = ((atual.education_level_school_year_id >= 3 && atual.education_level_school_year_id < 10) || (atual.education_level_school_year_id >= 30)) ? parseInt(atual.urban_night_total, 10) : 0;   //Não conta matrículas noturnas da pré-escola e da creche
+            atual.rural_day_total = parseInt(atual.rural_day_total, 10);
+            atual.rural_night_total = ((atual.education_level_school_year_id >= 3 && atual.education_level_school_year_id < 10) || (atual.education_level_school_year_id >= 30)) ? parseInt(atual.rural_night_total, 10) : 0;
+            result.push(atual);
 
-                i++;
+            i++;
+        }
+        else {      //  Série não existe, adcionamos 0 ao resultado.
+            let base_result = {
+                name: req.result[0].name,
+                urban_day_total: 0,
+                urban_night_total: 0,
+                rural_day_total: 0,
+                rural_night_total: 0,
+                education_level_school_year_id: j,
+                year: base_year,
+                education_level_school_year_name: id2str.educationLevelSchoolYear(j)
+            };
+
+            if ('city' in req.dims) {           // adciona os campos de cidade e/ou estado
+                base_result.city_id = atual_city_id;
+                base_result.city_name = atual_city_name;
             }
-            else {      //  Série não existe para a cidade/estado específica, adcionamos 0 ao resultado.
-                let base_result = {
-                    name: req.result[0].name,
-                    urban_day_total: 0,
-                    urban_night_total: 0,
-                    rural_day_total: 0,
-                    rural_night_total: 0,
-                    education_level_school_year_id: j,
-                    year: base_year,
-                    education_level_school_year_name: id2str.educationLevelSchoolYear(j)
-                };
-                result.push(base_result)
+            if ('state' in req.dims) {
+                base_result.state_id = atual_state_id;
+                base_result.state_name = atual_state_name;
             }
-            j++;
+
+            result.push(base_result)
         }
-        
-        req.result = result;
-    }
-    else {
-        req.result.forEach((r) => {
-            r.urban_day_total = parseInt(r.urban_day_total, 10);
-            r.urban_night_total = ((r.education_level_school_year_id >= 3 && r.education_level_school_year_id < 10) || (r.education_level_school_year_id >= 30)) ? parseInt(r.urban_night_total, 10) : 0;   //Não conta matrículas noturnas da pré-escola e da creche
-            r.rural_day_total = parseInt(r.rural_day_total, 10);
-            r.rural_night_total = ((r.education_level_school_year_id >= 3 && r.education_level_school_year_id < 10) || (r.education_level_school_year_id >= 30)) ? parseInt(r.rural_night_total, 10) : 0;
-        });    
+        j++;
     }
 
+    req.result = result;
     next();
 }, response('enrollment_projection'));
 
-- 
GitLab


From 8079d11327e31aa20cafbb05adb3cc620eb286f9 Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Fri, 5 Jul 2019 11:47:01 -0300
Subject: [PATCH 136/142] Update with clone .gitlab-ci.yml

---
 .gitlab-ci.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index ed8cd3f8..307b9725 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -9,7 +9,6 @@ services:
 variables:
   MONGO_URI: 'mongodb://mongo/app_name'
   NODE_ENV: 'test'
-  GIT_SUBMODULE_STRATEGY: 'normal'
 
 before_script:
   - node -v
@@ -19,6 +18,7 @@ before_script:
 run_tests:
   stage: test
   script:
+    - git clone https://gitlab.c3sl.ufpr.br/simcaq/lde-api-regression-test.git
     - cd lde-api-regression-test
     - python regression_test.py --compare
     - ping -W1 -c1 mongo
-- 
GitLab


From ac688efa7d159fb77829aeae8ade122e3bbc81e0 Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Fri, 5 Jul 2019 11:53:34 -0300
Subject: [PATCH 137/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 307b9725..8bf33ee6 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -14,12 +14,14 @@ before_script:
   - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
+  - apt install python-pip
 
 run_tests:
   stage: test
   script:
     - git clone https://gitlab.c3sl.ufpr.br/simcaq/lde-api-regression-test.git
     - cd lde-api-regression-test
+    - pip install -r requirements.txt
     - python regression_test.py --compare
     - ping -W1 -c1 mongo
     - sed -i -e 's/false/true/g' config.json
-- 
GitLab


From dca45f14cb43295848f0ec89d4cbdb182bd7ac8e Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Fri, 5 Jul 2019 12:02:43 -0300
Subject: [PATCH 138/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 8bf33ee6..64da93e4 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -14,7 +14,7 @@ before_script:
   - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
-  - apt install python-pip
+  - apt update && apt install python-pip
 
 run_tests:
   stage: test
-- 
GitLab


From 255705f8556deac8adc8df5e470b35af7aa056bd Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Fri, 5 Jul 2019 13:40:42 -0300
Subject: [PATCH 139/142] remove addMissoinf from enrollment

---
 src/libs/middlewares/addMissing.js | 2 +-
 src/libs/routes/enrollment.js      | 6 ++----
 2 files changed, 3 insertions(+), 5 deletions(-)

diff --git a/src/libs/middlewares/addMissing.js b/src/libs/middlewares/addMissing.js
index 034ca80e..c98fa373 100644
--- a/src/libs/middlewares/addMissing.js
+++ b/src/libs/middlewares/addMissing.js
@@ -27,7 +27,7 @@ module.exports = function addMissing(rqf){
         if(req.result.length === 0) return next();
 
         let result = req.result;
-
+        
         let dimsValues = {};
         result.forEach((r) => {
             dims.forEach((dim) => {
diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js
index be61a306..695d624b 100644
--- a/src/libs/routes/enrollment.js
+++ b/src/libs/routes/enrollment.js
@@ -531,7 +531,7 @@ rqf.addField({
   resultField: 'integral_time_id',
   where: {
       relation: '=',
-      type: 'integer',
+      type: 'boolean',
       field: 'tempo_integral'
   }
 }).addValue({
@@ -564,7 +564,7 @@ enrollmentApp.get('/', rqf.parse(), (req, res, next) => {
     .order('matricula.ano_censo')
     .where('matricula.tipo<=3');
     next();
-}, rqf.build(), query, id2str.transform(false), addMissing(rqf), response('enrollment'));
+}, rqf.build(), query, id2str.transform(false), /*addMissing(rqf),*/ response('enrollment'));
 
 enrollmentApp.get('/diagnosis', rqf.parse(), (req, res, next) => {
     req.dims = {};
@@ -817,8 +817,6 @@ enrollmentApp.get('/projection', rqf.parse(), (req, res, next) => {
         }
     }
 
-    console.log(educationSchoolYear);
-
     let result = [];
     let educationLevelSet = new Set();
     let schoolYearSet = new Set();
-- 
GitLab


From d94d324cc0805a46eba1f58571989a155bdb9672 Mon Sep 17 00:00:00 2001
From: pdg16 <pdg16@inf.ufpr.br>
Date: Mon, 8 Jul 2019 10:59:40 -0300
Subject: [PATCH 140/142] fix match queries

---
 src/libs/routes/schoolInfrastructure.js | 15 ++++++---------
 1 file changed, 6 insertions(+), 9 deletions(-)

diff --git a/src/libs/routes/schoolInfrastructure.js b/src/libs/routes/schoolInfrastructure.js
index 7bdf6182..30780daf 100644
--- a/src/libs/routes/schoolInfrastructure.js
+++ b/src/libs/routes/schoolInfrastructure.js
@@ -285,7 +285,6 @@ function matchQueries(queryTotal, queryPartial, queryNeeded, zeroPercentage=fals
                 break;
             }
         }
-
         if(queryPartial.length == 0) {
             partialMatch = JSON.parse(JSON.stringify(result));
             partialMatch.total = 0;
@@ -312,14 +311,12 @@ function matchQueries(queryTotal, queryPartial, queryNeeded, zeroPercentage=fals
             needMatch.total = 0;
         }
 
-        if(partialMatch) {
-            newObj.percentage = (partialMatch.total / result.total) * 100;
-            if(zeroPercentage) newObj.percentage = 0;
-            newObj.partial = partialMatch.total;
-            newObj.total = result.total;
-            newObj.need_adaptation = needMatch ? needMatch.total : 0;
-            match.push(newObj);
-        }
+        newObj.percentage = ( ( partialMatch ? partialMatch.total : 0) / result.total) * 100;
+		if(zeroPercentage) newObj.percentage = 0;
+		newObj.partial = ( partialMatch ? partialMatch.total : 0);
+		newObj.total = result.total;
+		newObj.need_adaptation = needMatch ? needMatch.total : 0;
+		match.push(newObj);
     });
 
     return match;
-- 
GitLab


From 023cce722196f3717110f917ecdf62b64893748d Mon Sep 17 00:00:00 2001
From: Hamer Iboshi <hi15@inf.ufpr.br>
Date: Mon, 8 Jul 2019 14:16:39 -0300
Subject: [PATCH 141/142] Update .gitlab-ci.yml

---
 .gitlab-ci.yml | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 64da93e4..7e420329 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -14,7 +14,9 @@ before_script:
   - node -v
   - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint
   - npm install
-  - apt update && apt install python-pip
+  - apt update && apt install curl
+  - curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
+  - python get-pip.py
 
 run_tests:
   stage: test
-- 
GitLab


From 820daecf1fe700864750373194ca63d87f6086a2 Mon Sep 17 00:00:00 2001
From: hi15 <hi15@inf.ufpr.br>
Date: Mon, 8 Jul 2019 14:24:46 -0300
Subject: [PATCH 142/142] Remove from local repository submodule of regression
 tests

---
 .gitmodules             | 3 ---
 lde-api-regression-test | 1 -
 2 files changed, 4 deletions(-)
 delete mode 100644 .gitmodules
 delete mode 160000 lde-api-regression-test

diff --git a/.gitmodules b/.gitmodules
deleted file mode 100644
index bbec3a97..00000000
--- a/.gitmodules
+++ /dev/null
@@ -1,3 +0,0 @@
-[submodule "lde-api-regression-test"]
-	path = lde-api-regression-test
-	url = git@gitlab.c3sl.ufpr.br:simcaq/lde-api-regression-test.git
diff --git a/lde-api-regression-test b/lde-api-regression-test
deleted file mode 160000
index 24788fc6..00000000
--- a/lde-api-regression-test
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 24788fc662e682fc92bb108cb4ef4ac3f8687dd9
-- 
GitLab