From 3e7a27ed0b1d0417bd987f4f6d6726377da60fd2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Risso?= <joaovictor.risso@gmail.com>
Date: Wed, 9 Nov 2016 11:32:10 -0200
Subject: [PATCH] Implement route to list enrollments per school level for a
 given city
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: João Victor Risso <joaovictor.risso@gmail.com>
---
 src/libs/routes/location.js | 72 +++++++++++++++++++++++++++++++++++++
 src/test/location.js        | 29 +++++++++++++++
 2 files changed, 101 insertions(+)

diff --git a/src/libs/routes/location.js b/src/libs/routes/location.js
index c10d77b9..0dd66531 100644
--- a/src/libs/routes/location.js
+++ b/src/libs/routes/location.js
@@ -1196,4 +1196,76 @@ locationApp.get('/educational/school_level/state/:id', (req, res, next) => {
     });
 }, response('location'));
 
+locationApp.get('/educational/school_level/city/:id', (req, res, next) => {
+    const cityId = parseInt(req.params.id, 10);
+
+    const enrollmentsPerSchoolLevelYearQry = squel.select()
+        .field('MAX(turma.ano_censo)', 'census_year')
+        .from('turma');
+
+    const enrollmentsPerSchoolLevelQry = squel.select()
+        .field('COALESCE(SUM(turma.num_matriculas), 0)', 'total')
+        .field('turma.ano_censo', 'census_year')
+        .field('turma.serie_ano', 'school_year')
+        .field('etapa_ensino.desc_etapa', 'school_level')
+        .from('turma')
+        .from('etapa_ensino')
+        .from('municipio')
+        .where(`turma.fk_municipio_id = ${cityId}`)
+        .where('turma.fk_municipio_id = municipio.pk_cod_ibge')
+        .where(`turma.ano_censo IN (${enrollmentsPerSchoolLevelYearQry.toString()})`)
+        .where('turma.fk_etapa_ensino_id = etapa_ensino.pk_etapa_ensino_id')
+        .where('turma.fk_tipo_turma_id <= 3')
+        .group('municipio.nome')
+        .group('etapa_ensino.desc_etapa')
+        .group('turma.serie_ano')
+        .group('turma.ano_censo')
+        .order('municipio.nome')
+        .order('etapa_ensino.desc_etapa')
+        .order('turma.serie_ano')
+        .order('turma.ano_censo');
+
+    const queryLabels = [ 'enrollment_per_school_level', 'enrollment_census_year' ];
+    const querySet = [ enrollmentsPerSchoolLevelQry, enrollmentsPerSchoolLevelYearQry ];
+    // wait until all queries finish or one of them fail
+    Promise.all(dbExecAll(querySet, enrollmentsPerSchoolLevelYearQry)).then((queryResults) => {
+        const result = queryResults[0];
+        const censusYear = queryResults[1][0]['census_year'];
+
+        let school_levels = {};
+        for(let i = 0; i < result.length; ++i) {
+            const school_year  = schoolYearIdToStr(result[i].school_year);
+            const school_level = result[i].school_level;
+            const census_year = result[i].census_year;
+            if (typeof school_levels[school_level] === 'undefined') {
+                school_levels[school_level] = {};
+            }
+            school_levels[school_level][school_year] = parseInt(result[i].total, 10);
+        }
+
+        let response = [];
+        for(let level in school_levels) {
+            if (school_levels.hasOwnProperty(level)) {
+                let sclevel = {};
+                sclevel["degree"] = level;
+                sclevel["census_year"] = parseInt(censusYear, 10);
+                sclevel["table"] = [];
+                for(let school_year in school_levels[level]) {
+                    if (school_levels[level].hasOwnProperty(school_year)) {
+                        let enrollment = { 'title' : school_year,
+                                           'value' : school_levels[level][school_year] };
+                        sclevel["table"].push(enrollment);
+                    }
+                }
+                response.push(sclevel);
+            }
+        }
+        req.result = response;
+        next();
+    }).catch((error) => {
+        log.error(`[SQL query error] ${error}`);
+        next(error);
+    });
+}, response('location'));
+
 module.exports = locationApp;
diff --git a/src/test/location.js b/src/test/location.js
index 12d6e6c9..42761a8d 100644
--- a/src/test/location.js
+++ b/src/test/location.js
@@ -533,4 +533,33 @@ describe('test location', () => {
                 done();
             });
     }).timeout(testTimeout);
+
+    it('should return the correct format of enrollments per school level for a city', (done) => {
+        chai.request(server)
+            .get('/api/v1/location/educational/school_level/state/4106902')
+            .end((err, res) => {
+                res.should.have.status(200);
+                // test response format
+                res.should.be.json;
+                // test for result attribute in the response
+                res.body.should.have.property('result');
+                res.body.result.should.be.a('array');
+                // test response attributes for school
+                res.body.result.forEach((row) => {
+                    row.should.be.a('object');
+                    row.should.have.property('degree');
+                    row.should.have.property('census_year');
+                    row.should.have.property('table');
+                    row.table.should.be.a('array');
+                    row.table.forEach((tableRow) => {
+                        tableRow.should.be.a('object');
+                        tableRow.should.have.property('title');
+                        tableRow.should.have.property('value');
+                        tableRow.title.should.be.a('String');
+                        tableRow.value.should.be.a('Number');
+                    });
+                });
+                done();
+            });
+    }).timeout(testTimeout);
 });
-- 
GitLab