From a443dd6acceb8ac3d55218302e291b7214a5f68f Mon Sep 17 00:00:00 2001
From: edsaibert <es23@inf.ufpr.br>
Date: Mon, 10 Feb 2025 11:50:55 -0300
Subject: [PATCH] problemas com uf reg e municipio

---
 src/libs/convert/modalityShiftSuperior.js     |  30 +++
 src/libs/middlewares/aggregateData.js         |   3 +-
 src/libs/middlewares/id2str.js                |   7 +-
 .../routes_v1/superiorEnrollmentAggregate.js  | 172 +++++++++++++++---
 4 files changed, 182 insertions(+), 30 deletions(-)
 create mode 100644 src/libs/convert/modalityShiftSuperior.js

diff --git a/src/libs/convert/modalityShiftSuperior.js b/src/libs/convert/modalityShiftSuperior.js
new file mode 100644
index 00000000..64595063
--- /dev/null
+++ b/src/libs/convert/modalityShiftSuperior.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 shift(id) {
+    switch(id) {
+        case 1:
+            return 'Diurno';
+        case 2:
+            return 'Noturno';
+        default:
+            return 'Não especificado';
+    }
+}
\ No newline at end of file
diff --git a/src/libs/middlewares/aggregateData.js b/src/libs/middlewares/aggregateData.js
index 98234532..96272ddc 100644
--- a/src/libs/middlewares/aggregateData.js
+++ b/src/libs/middlewares/aggregateData.js
@@ -37,7 +37,8 @@ const convert = {
     education_degree_entity: "educationDegreeEntity",
     government_agreement: "governmentAgreement",
     school_type: "schoolType",
-    age_range_cescu: "ageRangeCescu"
+    age_range_cescu: "ageRangeCescu",
+    modality_shift_superior: "modalityShiftSuperior"
 }
 
 function aggregateData(req, res, next) {
diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js
index d4b3896b..c5edb2ae 100644
--- a/src/libs/middlewares/id2str.js
+++ b/src/libs/middlewares/id2str.js
@@ -127,6 +127,7 @@ const ageRangeEntity = require(`${libs}/convert/ageRangeEntity`);
 const postGraduationEntity = require(`${libs}/convert/postGraduationEntity`);
 const totalDoc = require(`${libs}/convert/totalDoc`);
 const educationDegreeEntity = require(`${libs}/convert/educationDegreeEntity`);
+const modalityShiftSuperior = require(`${libs}/convert/modalityShiftSuperior`);
 
 const ids = {
     gender_id: gender,
@@ -246,7 +247,8 @@ const ids = {
     post_graduation_entity: postGraduationEntity,
     special_education_entity: specialEducationEntity,
     total_doc: totalDoc,
-    education_degree_entity: educationDegreeEntity
+    education_degree_entity: educationDegreeEntity,
+    modality_shift_superior_id: modalityShiftSuperior,
 };
 
 function transform(removeId=false) {
@@ -389,5 +391,6 @@ module.exports = {
     postGraduationEntity,
     specialEducationEntity,
     totalDoc,
-    educationDegreeEntity
+    educationDegreeEntity,
+    modalityShiftSuperior,
 };
diff --git a/src/libs/routes_v1/superiorEnrollmentAggregate.js b/src/libs/routes_v1/superiorEnrollmentAggregate.js
index ed02530e..e2c47728 100644
--- a/src/libs/routes_v1/superiorEnrollmentAggregate.js
+++ b/src/libs/routes_v1/superiorEnrollmentAggregate.js
@@ -30,6 +30,8 @@ const log = require(`${libs}/log`)(module);
 
 const squel = require('squel');
 
+const multiQuery = require(`${libs}/middlewares/multiQuery`);
+
 const query = require(`${libs}/middlewares/query`).query;
 
 const response = require(`${libs}/middlewares/response`);
@@ -327,61 +329,177 @@ rqf.addField({
         field: 'qtd_aluno_deficiente'
     }
 }).addValue({
-
+    name: 'academic_level',
+    table: 'curso_superior_agregado',
+    tableField: 'tp_grau_acad',
+    resultField: 'academic_level',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'tp_grau_acad'
+    }
+}).addValue({
+    name: 'ies_name',
+    table: 'ies_ens_superior',
+    tableField: 'nome_ies',
+    resultField: 'ies_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'cod_ies'
+    },
+    join: {
+        primary: ['cod_ies', 'ano_censo'],
+        foreign: ['cod_ies', 'ano_censo'],
+        foreignTable: 'curso_superior_agregado'
+    }
+}).addValue({
+    name: 'modality',
+    table: 'curso_superior_agregado',
+    tableField: 'tp_modal_ens',
+    resultField: 'modality',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'tp_modal_ens'
+    }
+}).addValue({
+    name: 'academic_organization',
+    table: 'curso_superior_agregado',
+    tableField: 'tp_org_acad',
+    resultField: 'academic_organization',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'tp_org_acad'
+    }
 });
 
+function matchQueries(queryPartial, queryTotal) {
+    let match = [];
+    queryTotal.forEach((result) => {
+        let newObj = {};
+        let keys = Object.keys(result);
+        keys.forEach((key) => {
+            newObj[key] = result[key];
+        });
+        let index = keys.indexOf('cod');
+        if(index > -1) keys.splice(index, 1);
+        let objMatch = null;
+
+        for(let i = 0; i < queryPartial.length; ++i) {
+            let partial = queryPartial[i];
+            let foundMatch = true;
+            for(let j = 0; j < keys.length; ++j) {
+                let key = keys[j];
+                if(partial[key] !== result[key]) {
+                    foundMatch = false;
+                    break;
+                }
+            }
+            if(foundMatch) {
+                objMatch = partial;
+                break;
+            }
+        }
+
+        if(objMatch) {
+            newObj.denominator = result.cod;
+            newObj.partial = objMatch.cod;
+            // newObj.total = (objMatch.total / result.total) * 100;
+            match.push(newObj);
+        }
+    });
+
+    return match;
+}        
+
 superiorEnrollmentAggregateApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
+    req.querySet = [];
+
+    let basic = req.sql.clone();
+    let curso = req.sql.clone();
+    let ies = req.sql.clone();
+
+    basic.field('curso_superior_agregado.ano_censo', 'year');
+
     if (req.query.dims && req.query.dims.includes("ethnic_group")){
-        req.sql.field('ano_censo', 'year')
-        .field('sum(qtd_mat_branca)', 'total_branca')
+        basic.field.field('sum(qtd_mat_branca)', 'total_branca')
         .field('sum(qtd_mat_preta)', 'total_preta')
         .field('sum(qtd_mat_parda)', 'total_parda')
         .field('sum(qtd_mat_amarela)', 'total_amarela')
         .field('sum(qtd_mat_indigena)', 'total_indigena')
-        .field('sum(qtd_mat_cor_nao_declarada)', 'total_nd')
-        .from('curso_superior_agregado')
-        .where('tp_nivel_acad = 1')
-        .group('ano_censo')
-        .order('ano_censo');
+        .field('sum(qtd_mat_cor_nao_declarada)', 'total_nd');
     }
     else if (req.query.dims && req.query.dims.includes("school_type")){
-        req.sql.field('ano_censo', 'year')
-        .field('sum(qtd_mat_proces_publica)', 'total_publica')
+        basic.field('sum(qtd_mat_proces_publica)', 'total_publica')
         .field('sum(qtd_mat_proces_privada)', 'total_privada')
-        .field('sum(qtd_mat_proces_nao_informada)', 'total_nao_informada')
-        .from('curso_superior_agregado')
-        .where('tp_nivel_acad = 1')
-        .group('ano_censo')
-        .order('ano_censo');
+        .field('sum(qtd_mat_proces_nao_informada)', 'total_nao_informada');
     }
     else if (req.query.dims && req.query.dims.includes("age_range_cescu")){
-        req.sql.field('ano_censo', 'year')
-        .field('sum(qtd_mat_0_17)', 'total_0_17')
+        basic.field('sum(qtd_mat_0_17)', 'total_0_17')
         .field('sum(qtd_mat_18_24)', 'total_18_24')
         .field('sum(qtd_mat_25_29)', 'total_25_29')
         .field('sum(qtd_mat_30_34)', 'total_30_34')
         .field('sum(qtd_mat_35_39)', 'total_35_39')
         .field('sum(qtd_mat_40_49)', 'total_40_49')
         .field('sum(qtd_mat_50_59)', 'total_50_59')
-        .field('sum(qtd_mat_60_mais)', 'total_60_mais')
-        .from('curso_superior_agregado')
+        .field('sum(qtd_mat_60_mais)', 'total_60_mais');
+    }
+    else if (req.query.dims && req.query.dims.includes("gender")){
+        basic.field('sum(qtd_mat_fem)', 'total_fem')
+        .field('sum(qtd_mat_masc)', 'total_masc');
+    }
+    else if (req.query.dims && req.query.dims.includes("modality_shift_superior")){
+        basic.field('sum(qtd_mat_diurno)', 'total_diurno')
+        .field('sum(qtd_mat_noturno)', 'total_noturno');
+    }
+    else if (req.query.dims && req.query.dims.includes("region")){
+        curso.field('qtd_matriculas', 'enrollment')
+        curso.field('cod_reg', 'cod')
+        curso.field('nome_reg', 'cod_name')
         .where('tp_nivel_acad = 1')
+        .from('curso_superior_agregado')
         .group('ano_censo')
         .order('ano_censo');
-    }
-    else {
-        req.sql.field('ano_censo', 'Ano')
-        .field('SUM(qtd_matriculas)', 'Número de Matrículas')
-        .from('curso_superior_agregado')
+
+        ies.field('nome_regiao_ies', 'cod_name')
         .where('tp_nivel_acad = 1')
+        .from('ies_ens_superior')
+        .where('ano_censo > 2019')
         .group('ano_censo')
         .order('ano_censo');
     }
+    else {
+        basic.field('SUM(qtd_matriculas)', 'enrollment');
+    }
+    
+    basic.from('curso_superior_agregado')
+    .from('ies_ens_superior')
+    // .join('ies_ens_superior', null, 'ies_ens_superior.ano_censo = curso_superior_agregado.ano_censo')
+    .where('tp_nivel_acad = 1') 
+    .group('curso_superior_agregado.ano_censo') 
+    .order('curso_superior_agregado.ano_censo');
 
-    console.log(req.sql.toString());
-    console.log(req.query.dims);
+    // console.log(req.sql.toString());
+    // // console.log(req.query.dims);
+    // console.log(req.sql.result);
+
+    req.querySet.push(basic);
+    req.querySet.push(curso);
+    req.querySet.push(ies);
 
     next();
-}, query, aggregateData, id2str.transform(false), response('superior_enrollment_aggregate'));
+}, multiQuery, query, aggregateData, id2str.transform(false), response('superior_enrollment_aggregate'), (req, res, next) => {
+    
+    if (req.result[1] || req.result[2]){
+        let newObj = matchQueries(req.result[1], req.result[2]);
+        req.result = newObj;     
+    }
+    else {
+        req.result = req.result[0];
+    }
+    next();
+});
 
 module.exports = superiorEnrollmentAggregateApp;
-- 
GitLab