diff --git a/.gitignore b/.gitignore index 08baf221d197e203575471053f219672305703c4..99a279fb87ba4d97734e25ed4d26cfef532ea04e 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,5 @@ build/* config.json docs/ .vscode/ + +package-lock.json diff --git a/CHANGELOG.md b/CHANGELOG.md index d32a346a56d17b9757fa8f418cf4cd772970bd4d..6ffc657d792d9a0358b82c4ad7f0d2c49e2a7173 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ 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/). +## 1.4.0 - 2018-06-27 +### Added +- Add school building filter/dimension to school count route +- Add transport indicator +- Add cub route +### Changed +- Fixed CSV output when result objects have nested arrays and/or objects +- Limit year range to 2007-2015 in out of school indicator +- Fix auxiliar indicator + ## 1.3.3 - 2018-06-27 ### Changed - Removed restriction of year > 2014 of school count route @@ -48,7 +58,6 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Liquid enrollment ratio indicator - Gloss enrollment ratio indicator - ## 1.0.3 - 2018-04-27 ### Changed - Fixed bug undefined field in some indicators diff --git a/src/libs/convert/ageRange.js b/src/libs/convert/ageRange.js index b24990a1bd9870c90365d0af9b118c1578b1dd3a..30bc9f6c0cd64123a3673f248a222351634627ed 100644 --- a/src/libs/convert/ageRange.js +++ b/src/libs/convert/ageRange.js @@ -1,17 +1,17 @@ module.exports = function ageRange(id) { switch (id) { case 1: - return '0-3'; + return '0 a 3 anos'; case 2: - return '4-5'; + return '4 a 5 anos'; case 3: - return '6-10'; + return '6 a 10 anos'; case 4: - return '11-14'; + return '11 a 14 anos'; case 5: - return '15-17'; + return '15 a 17 anos'; case 6: - return '18-24'; + return '18 a 24 anos'; default: return 'Não declarada'; } diff --git a/src/libs/convert/fullAgeRange.js b/src/libs/convert/fullAgeRange.js index d7b36fdc9aee2e459126feb457695c9ea13aa7d5..e18b9156ed4e723fec83c939e8b01f148580d018 100644 --- a/src/libs/convert/fullAgeRange.js +++ b/src/libs/convert/fullAgeRange.js @@ -1,27 +1,27 @@ module.exports = function ageRange(id) { switch (id) { case 1: - return '0-3'; + return '0 a 3 anos'; case 2: - return '4-5'; + return '4 a 5 anos'; case 3: - return '6-10'; + return '6 a 10 anos'; case 4: - return '11-14'; + return '11 a 14 anos'; case 5: - return '15-17'; + return '15 a 17 anos'; case 6: - return '18-24'; + return '18 a 24 anos'; case 7: - return '25-29'; + return '25 a 29 anos'; case 8: - return '30-40'; + return '30 a 40 anos'; case 9: - return '41-50'; + return '41 a 50 anos'; case 10: - return '51-64'; + return '51 a 64 anos'; case 11: - return '64+'; + return 'Mais de 64 anos'; default: return 'Não declarada'; } diff --git a/src/libs/convert/incomeLevel.js b/src/libs/convert/incomeLevel.js index c39106843027d91d628ec6bdda664507e660aae8..f80faf8692c93bee328e8051cb39ab5b05745deb 100644 --- a/src/libs/convert/incomeLevel.js +++ b/src/libs/convert/incomeLevel.js @@ -1,4 +1,4 @@ -module.exports = function citySize(id) { +module.exports = function incomeLevel(id) { switch (id) { case 1: return '1º quintil – 20% menores'; diff --git a/src/libs/convert/transportationManager.js b/src/libs/convert/transportationManager.js new file mode 100644 index 0000000000000000000000000000000000000000..28961db9f23316bc66730dc2c2554a904322c18f --- /dev/null +++ b/src/libs/convert/transportationManager.js @@ -0,0 +1,8 @@ +module.exports = function transportationManager(id) { + switch(id) { + case 1: + return 'Estadual'; + case 2: + return 'Municipal'; + } +}; diff --git a/src/libs/middlewares/addMissing.js b/src/libs/middlewares/addMissing.js index aaa451fbb4438b1480f3454212fd8dde39f3675d..f3d1b300abb37b388532b65d8cc3abc344fcca26 100644 --- a/src/libs/middlewares/addMissing.js +++ b/src/libs/middlewares/addMissing.js @@ -38,7 +38,6 @@ module.exports = function addMissing(rqf){ result.forEach((r) => { let resultDim1 = r[rqfName]; let resultDim2 = r[rqfName2]; - G[rqfName][resultDim1][rqfName2][resultDim2] = true; }); diff --git a/src/libs/middlewares/id2str.js b/src/libs/middlewares/id2str.js index 776c338219297401aee5bb398810c0b50544198d..c2fa1fab15eded3a1190bdbe5c918275b2e9b5c5 100644 --- a/src/libs/middlewares/id2str.js +++ b/src/libs/middlewares/id2str.js @@ -25,6 +25,9 @@ const genderPnad = require(`${libs}/convert/genderPnad`); const fifthHouseholdIncome = require(`${libs}/convert/fifthHouseholdIncome`); const extremesHouseholdIncome = require(`${libs}/convert/extremesHouseholdIncome`); const educationLevelBasic = require(`${libs}/convert/educationLevelBasic`); +const useTransport = require(`${libs}/convert/booleanVariable`); +const useTransportPublic = require(`${libs}/convert/booleanVariable`); +const transportationManager = require(`${libs}/convert/transportationManager`); const ids = { gender_id: gender, @@ -61,7 +64,10 @@ const ids = { full_age_range_id: fullAgeRange, gender_pnad_id: genderPnad, fifth_household_income_id: fifthHouseholdIncome, - extremes_household_income_id: extremesHouseholdIncome + extremes_household_income_id: extremesHouseholdIncome, + use_transport_id: useTransport, + use_transport_public_id: useTransportPublic, + transportation_manager_id: transportationManager }; function transform(removeId=false) { @@ -127,5 +133,7 @@ module.exports = { fullAgeRange, genderPnad, fifthHouseholdIncome, - extremesHouseholdIncome + extremesHouseholdIncome, + useTransport, + transportationManager }; diff --git a/src/libs/middlewares/response.js b/src/libs/middlewares/response.js index bd5009cd1e55ea391231348b30eea07568c6258d..62e1d9601c971b67abcf3a596160c9087850df03 100644 --- a/src/libs/middlewares/response.js +++ b/src/libs/middlewares/response.js @@ -3,13 +3,51 @@ const log = require(`${libs}/log`)(module); const xml = require('js2xmlparser'); const csv = require('csv-express'); - // Custom generic middleware used respond requests. - // The function reads the req.query.format param and respond in json, xml or csv +// Função para transformar um resultado que contém objetos com arrays aninhados em vários objetos +// sem arrays aninhandos +function flatObj(obj) { + let flatList = []; + let tempObj = {}; + + Object.keys(obj).forEach((key) => { + if(obj[key] instanceof Array) { + obj[key].forEach((i) => { + let flatten = flatObj(i); + if(flatten instanceof Array) { + flatten.forEach((j) => { + flatList.push(Object.assign({}, tempObj, j)); + }); + } else { + flatList.push(Object.assign({}, tempObj, flatten)); + } + }); + } else if(obj[key] instanceof Object) { + tempObj = Object.assign({}, tempObj, obj[key]); + } else { + tempObj[key] = obj[key]; + } + }); + + if(flatList.length > 0) return flatList; + return tempObj; +} + + // Custom generic middleware used to answer requests. + // The function reads the req.query.format param and answers in json, xml or csv function response(value) { return (req, res, next) => { if (req.query.format === 'csv') { + let result = []; + req.result.forEach((i) => { + let flatten = flatObj(i); + if(flatten instanceof Array) { + result = [...result, ...flatten]; + } else { + result.push(flatten); + } + }); res.attachment(`${value}.csv`); - res.csv(req.result, true); + res.csv(result, true); } else if (req.query.format === 'xml') { res.send(xml.parse('result', { [value]: req.result })); } else { diff --git a/src/libs/routes/api.js b/src/libs/routes/api.js index 2f9e7f4a65783a1d41c8b0cc149695e4c0138eb8..f5742fd5aad548d1bf98e9435fb0ef496b4b9afb 100644 --- a/src/libs/routes/api.js +++ b/src/libs/routes/api.js @@ -64,8 +64,14 @@ const outOfSchool = require(`${libs}/routes/outOfSchool`); const classroomCount = require(`${libs}/routes/classroomCount`); +const transport = require(`./transport`); + +const auxiliar = require(`${libs}/routes/auxiliar`); + const dailyChargeAmount = require(`${libs}/routes/dailyChargeAmount`); +const cub = require(`${libs}/routes/cub`); + api.get('/', (req, res) => { res.json({ msg: 'SimCAQ API is running' }); }); @@ -101,5 +107,8 @@ api.use('/siope', siope); api.use('/out_of_school', outOfSchool); api.use('/classroom_count', classroomCount); api.use('/daily_charge_amount', dailyChargeAmount); +api.use('/transport', transport); +api.use('/cub', cub); +api.use('/auxiliar', auxiliar); module.exports = api; diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js new file mode 100644 index 0000000000000000000000000000000000000000..21e7c5f59074435489bbf5a44d07cc2bbe6bd6ac --- /dev/null +++ b/src/libs/routes/auxiliar.js @@ -0,0 +1,319 @@ +const express = require('express'); + +const auxiliarApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const log = require(`${libs}/log`)(module); + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const id2str = require(`${libs}/middlewares/id2str`); + +const config = require(`${libs}/config`); + +const passport = require('passport'); + +const download = require(`${libs}/middlewares/downloadDatabase`); + +const addMissing = require(`${libs}/middlewares/addMissing`); + +const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; + +let rqf = new ReqQueryFields(); + +auxiliarApp.use(cache('15 day')); + +auxiliarApp.get('/year_range', (req, res, next) => { + req.sql.from('docente') + .field('MIN(docente.ano_censo)', 'start_year') + .field('MAX(docente.ano_censo)', 'end_year'); + next(); +}, query, response('range')); + +auxiliarApp.get('/years', (req, res, next) => { + req.sql.from('docente'). + field('DISTINCT docente.ano_censo', 'year'); + next(); +}, query, response('years')); + +auxiliarApp.get('/source', (req, res, next) => { + req.sql.from('fonte') + .field('fonte', 'source') + .where('tabela = \'docente\''); + next(); +}, query, response('source')) + +auxiliarApp.get('/adm_dependency_detailed', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 6; ++i) { + req.result.push({ + id: i, + name: id2str.admDependencyPriv(i) + }); + }; + next(); +}, response('adm_dependency_detailed')); + +auxiliarApp.get('/adm_dependency', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 4; ++i) { + req.result.push({ + id: i, + name: id2str.admDependency(i) + }); + }; + next(); +}, response('adm_dependency')); + +auxiliarApp.get('/location', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 2; ++i) { + req.result.push({ + id: i, + name: id2str.location(i) + }); + }; + next(); +}, response('location')); + +auxiliarApp.get('/rural_location', (req, res, next) => { + req.result = [ + {id: 1, name: "Urbana"}, + {id: 2, name: "Rural"}, + {id: 3, name: "Rural - Ãrea de assentamento"}, + {id: 4, name: "Rural - Terra indÃgena"}, + {id: 5, name: "Rural - Ãrea remanescente de quilombos"}, + {id: 6, name: "Rural - Unidade de uso sustentável"} + ]; + next(); +}, response('rural_location')); + +auxiliarApp.get('/education_level_mod', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 11; ++i) { + req.result.push({ + id: i, + name: id2str.educationLevelMod(i) + }); + } + + req.result.push({ + id: 99, + name: id2str.educationLevelMod(99) + }); + next(); +}, response('education_level_mod')); + +auxiliarApp.get('/gender', (req, res, next) => { + req.result = [ + {id: 1, name: 'Masculino'}, + {id: 2, name: 'Feminino'} + ]; + next(); +}, response('gender')); + +auxiliarApp.get('/ethnic_group', (req, res, next) => { + req.result = []; + for(let i = 0; i <=5; ++i) { + req.result.push({ + id: i, + name: id2str.ethnicGroup(i) + }); + } + next(); +}, response('ethnic_group')); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'adm_dependency', + table: 'docente', + tableField: 'dependencia_adm_id', + resultField: 'adm_dependency_id', + where: { + relation: '=', + type: 'integer', + field: 'dependencia_adm_id' + } +}).addValue({ + name: 'adm_dependency_detailed', + table: 'docente', + tableField: 'dependencia_adm_priv', + resultField: 'adm_dependency_detailed_id', + where: { + relation: '=', + type: 'integer', + field: 'dependencia_adm_priv' + } +}).addValue({ + name: 'education_level_mod', + table: 'docente', + tableField: 'etapas_mod_ensino_segmento_id', + resultField: 'education_level_mod_id', + where: { + relation: '=', + type: 'integer', + field: 'etapas_mod_ensino_segmento_id' + } +}).addValue({ + name: 'region', + table: 'regiao', + tableField: 'nome', + resultField: 'region_name', + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'id', + foreign: 'escola_regiao_id', + foreignTable: 'docente' + } +}).addValue({ + name: 'state', + table: 'estado', + tableField: 'nome', + resultField: 'state_name', + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'id', + foreign: 'escola_estado_id', + foreignTable: 'docente' + } +}).addValue({ + name: 'rural_location', + table: 'docente', + tableField: 'localidade_area_rural', + resultField: 'rural_location_id', + where: { + relation: '=', + type: 'integer', + field: 'localidade_area_rural' + } +}).addValueToField({ + name: 'city', + table: 'municipio', + tableField: ['nome', 'id'], + resultField: ['city_name', 'city_id'], + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'id', + foreign: 'escola_municipio_id', + foreignTable: 'docente' + } +}, 'dims').addValueToField({ + name: 'city', + table: 'municipio', + tableField: 'nome', + resultField: 'city_name', + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'id', + foreign: 'escola_municipio_id', + foreignTable: 'docente' + } +}, 'filter').addValue({ + name: 'location', + table: 'docente', + tableField: 'cod_localizacao', + resultField: 'location_id', + where: { + relation: '=', + type: 'integer', + field: 'cod_localizacao' + } +}).addValue({ + name: 'min_year', + table: 'docente', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo' + } +}).addValue({ + name: 'max_year', + table: 'docente', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo' + } +}).addValue({ + name: 'gender', + table: 'docente', + tableField: 'sexo', + resultField: 'gender_id', + where: { + relation: '=', + type: 'integer', + field: 'sexo' + } +}).addValue({ + name: 'ethnic_group', + table: 'docente', + tableField: 'cor_raca', + resultField: 'ethnic_group_id', + where: { + relation: '=', + type: 'integer', + field: 'cor_raca' + } +}); + +// LDE +auxiliarApp.get('/', rqf.parse(), (req, res, next) => { + req.sql.field('COUNT(DISTINCT docente.id)', 'total') + .field("'Brasil'", 'name') + .field('docente.ano_censo', 'year') + .from('docente') + .group('docente.ano_censo') + .order('docente.ano_censo') + .where('(docente.tipo_turma_id <= 3 AND docente.dependencia_adm_id > 1 AND docente.tipo_docente = 2)'); + next(); +}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('auxiliar')); + +// SimCAQ +auxiliarApp.get('/count', rqf.parse(), (req, res, next) => { + req.sql.field('COUNT(DISTINCT docente.id)', 'total') + .field("'Brasil'", 'name') + .field('docente.ano_censo', 'year') + .from('docente') + .group('docente.ano_censo') + .order('docente.ano_censo') + .where('((docente.tipo_turma_id <= 3) AND (docente.dependencia_adm_id = 2 OR docente.dependencia_adm_id = 3) AND (docente.tipo_docente = 2))'); + next(); +}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('auxiliar')); + +auxiliarApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('docente', 'mapping_docente')); + +module.exports = auxiliarApp; diff --git a/src/libs/routes/cub.js b/src/libs/routes/cub.js new file mode 100644 index 0000000000000000000000000000000000000000..5310f0be248f191f0e41325fb84d03525f638e40 --- /dev/null +++ b/src/libs/routes/cub.js @@ -0,0 +1,178 @@ +const express = require('express'); + +const cubApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const log = require(`${libs}/log`)(module); + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const id2str = require(`${libs}/middlewares/id2str`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const request = require(`request`); + +const config = require(`${libs}/config`); + +const passport = require('passport'); + +const download = require(`${libs}/middlewares/downloadDatabase`); + +const addMissing = require(`${libs}/middlewares/addMissing`); + +const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; + +let rqf = new ReqQueryFields(); +let rqfCount = new ReqQueryFields(); + +cubApp.get('/year_range', (req, res, next) => { + req.sql.from('cub') + .field('MIN(cub.ano_censo)', 'start_year') + .field('MAX(cub.ano_censo)', 'end_year'); + next(); +}, query, response('range')); + +cubApp.get('/years', (req, res, next) => { + req.sql.from('cub') + .field('DISTINCT cub.ano_censo', 'year'); + next(); +}, query, response('years')); + +cubApp.get('/months', (req, res, next) => { + req.sql.from('cub') + .field('DISTINCT cub.mes_censo', 'month'); + next(); +}, query, response('months')); + +cubApp.get('/years_months', (req, res, next) => { + req.sql.from('cub') + .field('DISTINCT cub.ano_censo AS "year", cub.mes_censo AS "month"'); + next(); +}, query, response('years_months')); + +cubApp.get('/price_type', (req, res, next) => { + req.sql.from('cub') + .field('DISTINCT cub.tipo_preco', 'price_type'); + next(); +}, query, response('price_type')); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'state', + table: 'estado', + tableField: ['sigla', 'id'], + resultField: ['sigla_uf', 'cod_uf'], + where: { + relation: '=', + type: 'integer', + field: 'estado_id', + table: 'cub' + }, + join: { + primary: 'id', + foreign: 'estado_id', + foreignTable: 'cub' + } +}).addValue({ + name: 'min_year', + table: 'cub', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + table: 'cub', + field: 'ano_censo' + } +}).addValue({ + name: 'max_year', + table: 'cub', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + table: 'cub', + field: 'ano_censo' + } +}).addValue({ + name: 'min_month', + table: 'cub', + tableField: 'mes_censo', + resultField: 'month', + where: { + relation: '>=', + type: 'integer', + table: 'cub', + field: 'mes_censo' + } +}).addValue({ + name: 'max_month', + table: 'cub', + tableField: 'mes_censo', + resultField: 'month', + where: { + relation: '<=', + type: 'integer', + table: 'cub', + field: 'mes_censo' + } +}); + +cubApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + if (req.filter.size || req.filter.dims) { + if ('state' in req.filter || 'state' in req.dims) { + req.sql.from('cub') + .field('cub.estado_id', 'cod_uf') + .field('estado.sigla', 'sigla_uf') + .field('cub.tipo_preco', 'tipo_preco') + .field('cub.preco', 'preco') + .join('estado', null, 'cub.estado_id=estado.id') + .group('cub.ano_censo') + .group('cub.mes_censo') + .group('cub.estado_id') + .group('estado.sigla') + .group('cub.tipo_preco') + .group('cub.preco') + } else { + req.sql.from('cub') + .field("'BR'", 'sigla_uf') + .field("cub.tipo_preco", 'tipo_preco') + .field('AVG(cub.preco)', 'preco') + .join('estado', null, 'cub.estado_id=estado.id') + .group('cub.ano_censo') + .group('cub.mes_censo') + .group('cub.tipo_preco') + } + } else { + req.sql.from('cub') + .field('cub.estado_id', 'cod_uf') + .field('estado.sigla', 'sigla_uf') + .field('cub.tipo_preco', 'tipo_preco') + .field('cub.preco', 'preco') + .join('estado', null, 'cub.estado_id=estado.id') + .group('cub.ano_censo') + .group('cub.mes_censo') + .group('cub.estado_id') + .group('estado.sigla') + .group('cub.tipo_preco') + .group('cub.preco') + } + + next(); +}, query, addMissing(rqf), id2str.transform(), response('cub')); + +module.exports = cubApp; diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js index a3a25119d7067e08456e71056a3cff02a99b743b..839eaba2f0fdc66b09caba1487ae7d04396d2b6e 100644 --- a/src/libs/routes/enrollment.js +++ b/src/libs/routes/enrollment.js @@ -467,4 +467,333 @@ enrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { 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.school_year = true; + req.dims.location = true; + req.dims.adm_dependency_detailed = true; + + req.sql.field('COUNT(*)', 'total') + .field("'Brasil'", 'name') + .field('matricula.ano_censo', 'year') + .from('matricula') + .group('matricula.ano_censo') + .order('matricula.ano_censo') + .where('matricula.tipo<=3'); + + next(); +}, rqf.build(), query, id2str.transform(), (req, res, next) => { + let enrollments = req.result; + + // Gera a relação etapa de ensino X ano escolar + let educationSchoolYear = {}; + for(let i = 10; i < 80; ++i) { + if(id2str.schoolYear(i) !== id2str.schoolYear(99)) { + let educationLevelId = Math.floor(i/10); + educationSchoolYear[i] = { + id: educationLevelId, + name: id2str.educationLevelShort(educationLevelId), + }; + } + } + + let result = []; + let educationLevelSet = new Set(); + let schoolYearSet = new Set(); + let i = 0; + while(i < enrollments.length) { + let enrollment = enrollments[i]; + let educationLevelHash = '' + enrollment.year + educationSchoolYear[enrollment.school_year_id].id; + let schoolYearHash = '' + enrollment.year + enrollment.school_year_id; + + let currentEducation = null; + // Busca ou cria a etapa de ensino adequada + if(educationLevelSet.has(educationLevelHash)) { + let j = 0; + let edu = result[j]; + while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != educationSchoolYear[enrollment.school_year_id].id)) { + ++j; + edu = result[j]; + } + if(j >= result.length) --j; + edu = result[j]; + + currentEducation = edu; + } else { + educationLevelSet.add(educationLevelHash); + let obj = { + year: enrollment.year, + name: enrollment.name, + education_level_school_year_id: educationSchoolYear[enrollment.school_year_id].id, + education_level_school_year_name: educationSchoolYear[enrollment.school_year_id].name, + total: 0, + adm_dependencies: [ + { + adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, + adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, + total: 0 + } + ], + locations: [ + { + location_id: enrollment.location_id, + location_name: enrollment.location_name, + total: 0 + } + ] + }; + + result.push(obj); + currentEducation = obj; + } + + let currentSchoolYear = null; + // Busca ou cria a série adequada + if(schoolYearSet.has(schoolYearHash)) { + let j = 0; + let edu = result[j]; + while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != enrollment.school_year_id)) { + ++j; + edu = result[j]; + } + if(j >= result.length) --j; + edu = result[j]; + + currentSchoolYear = edu; + } else { + schoolYearSet.add(schoolYearHash); + let obj = { + year: enrollment.year, + name: enrollment.name, + education_level_school_year_id: enrollment.school_year_id, + education_level_school_year_name: enrollment.school_year_name, + total: 0, + adm_dependencies: [ + { + adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, + adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, + total: 0 + } + ], + locations: [ + { + location_id: enrollment.location_id, + location_name: enrollment.location_name, + total: 0 + } + ] + }; + + result.push(obj); + currentSchoolYear = obj; + } + + // Adiciona ao total + currentEducation.total += enrollment.total; + currentSchoolYear.total += enrollment.total; + + // Adiciona ao total da dependência administrativa + let admDependencyIndex = 0; + let admDependency = currentEducation.adm_dependencies[admDependencyIndex]; + while (admDependencyIndex < currentEducation.adm_dependencies.length && enrollment.adm_dependency_detailed_id > admDependency.adm_dependency_detailed_id) { + ++admDependencyIndex; + admDependency = currentEducation.adm_dependencies[admDependencyIndex]; + } + if(admDependencyIndex >= currentEducation.adm_dependencies.length || admDependency.adm_dependency_detailed_id != enrollment.adm_dependency_detailed_id) { // não encontrou + let obj = { + adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, + adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, + total: 0 + } + currentEducation.adm_dependencies.splice(admDependencyIndex, 0, obj); + admDependency = obj; + } + admDependency.total += enrollment.total; + + admDependencyIndex = 0; + admDependency = currentSchoolYear.adm_dependencies[admDependencyIndex]; + while (admDependencyIndex < currentSchoolYear.adm_dependencies.length && enrollment.adm_dependency_detailed_id > admDependency.adm_dependency_detailed_id) { + ++admDependencyIndex; + admDependency = currentSchoolYear.adm_dependencies[admDependencyIndex]; + } + if(admDependencyIndex >= currentSchoolYear.adm_dependencies.length || admDependency.adm_dependency_detailed_id != enrollment.adm_dependency_detailed_id) { // não encontrou + let obj = { + adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, + adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, + total: 0 + } + currentSchoolYear.adm_dependencies.splice(admDependencyIndex, 0, obj); + admDependency = obj; + } + admDependency.total += enrollment.total; + + // Adiciona ao total da localidade + let locationIndex = 0; + let location = currentEducation.locations[locationIndex]; + while (locationIndex < currentEducation.locations.length && enrollment.location_id > location.location_id) { + ++locationIndex; + location = currentEducation.locations[locationIndex]; + } + if(locationIndex >= currentEducation.locations.length || location.location_id != enrollment.location_id) { + let obj = { + location_id: enrollment.location_id, + location_name: enrollment.location_name, + total: 0 + } + currentEducation.locations.splice(locationIndex, 0, obj); + location = obj; + } + location.total += enrollment.total; + + locationIndex = 0; + location = currentSchoolYear.locations[locationIndex]; + while (locationIndex < currentSchoolYear.locations.length && enrollment.location_id > location.location_id) { + ++locationIndex; + location = currentSchoolYear.locations[locationIndex]; + } + if(locationIndex >= currentSchoolYear.locations.length || location.location_id != enrollment.location_id) { + let obj = { + location_id: enrollment.location_id, + location_name: enrollment.location_name, + total: 0 + } + currentSchoolYear.locations.splice(locationIndex, 0, obj); + location = obj; + } + location.total += enrollment.total; + + ++i; + } + + req.result = result; + + next(); +}, response('enrollment_diagnosis')); + +enrollmentApp.get('/projection', rqf.parse(), (req, res, next) => { + req.dims = {}; + req.dims.location = true; + req.dims.school_year = true; + req.dims.adm_dependency = true; + req.dims.period = true; + req.filter.adm_dependency = [1,2,3]; + + req.sql.field('COUNT(*)', 'total') + .field("'Brasil'", 'name') + .field('matricula.ano_censo', 'year') + .from('matricula') + .group('matricula.ano_censo') + .order('matricula.ano_censo') + .where('matricula.tipo<=3'); + + next(); +}, rqf.build(), query, id2str.transform(), (req, res, next) => { + let enrollments = req.result; + + // Gera a relação etapa de ensino X ano escolar + let educationSchoolYear = {}; + for(let i = 10; i < 80; ++i) { + if(id2str.schoolYear(i) !== id2str.schoolYear(99)) { + let educationLevelId = Math.floor(i/10); + educationSchoolYear[i] = { + id: educationLevelId, + name: id2str.educationLevelShort(educationLevelId), + }; + } + } + + let result = []; + let educationLevelSet = new Set(); + let schoolYearSet = new Set(); + let i = 0; + while(i < enrollments.length) { + let enrollment = enrollments[i]; + let educationLevelHash = '' + enrollment.year + educationSchoolYear[enrollment.school_year_id].id; + let schoolYearHash = '' + enrollment.year + enrollment.school_year_id; + + let currentEducation = null; + // Busca ou cria a etada de ensino adequada + if(educationLevelSet.has(educationLevelHash)) { + let j = 0; + let edu = result[j]; + while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != educationSchoolYear[enrollment.school_year_id].id)) { + ++j; + edu = result[j]; + } + if((j >= result.length)) --j; + edu = result[j]; + + currentEducation = edu; + } else { + educationLevelSet.add(educationLevelHash); + let obj = { + year: enrollment.year, + name: enrollment.name, + education_level_school_year_id: educationSchoolYear[enrollment.school_year_id].id, + education_level_school_year_name: educationSchoolYear[enrollment.school_year_id].name, + urban_day_total: 0, + urban_night_total: 0, + rural_day_total: 0, + rural_night_total: 0 + }; + result.push(obj); + currentEducation = obj; + } + + let currentSchoolYear = null; + // Busca ou cria a série adequada + if(schoolYearSet.has(schoolYearHash)) { + let j = 0; + let edu = result[j]; + while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != enrollment.school_year_id)){ + ++j; + edu = result[j]; + } + if(j >= result.length) --j; + edu = result[j]; + + currentSchoolYear = edu; + } else { + schoolYearSet.add(schoolYearHash); + let obj = { + year: enrollment.year, + name: enrollment.name, + education_level_school_year_id: enrollment.school_year_id, + education_level_school_year_name: enrollment.school_year_name, + urban_day_total: 0, + urban_night_total: 0, + rural_day_total: 0, + rural_night_total: 0 + }; + + result.push(obj); + currentSchoolYear = obj; + } + + if(enrollment.location_id == 1) { + if(enrollment.period_id < 3) { + currentEducation.urban_day_total += enrollment.total; + currentSchoolYear.urban_day_total += enrollment.total; + } else { + currentEducation.urban_night_total += enrollment.total; + currentSchoolYear.urban_night_total += enrollment.total; + } + } else { + if(enrollment.period_id < 3) { + currentEducation.rural_day_total += enrollment.total; + currentSchoolYear.rural_day_total += enrollment.total; + } else { + currentEducation.rural_night_total += enrollment.total; + currentSchoolYear.rural_night_total += enrollment.total; + } + } + + ++i; + } + + req.result = result; + + next(); +}, response('enrollment_projection')); + module.exports = enrollmentApp; diff --git a/src/libs/routes/liquidEnrollmentRatio.js b/src/libs/routes/liquidEnrollmentRatio.js index 7324709e8eaed83481466c555d519a4e3554277e..793e4f65309314f9ee12f53afa3230cb8e01bc84 100644 --- a/src/libs/routes/liquidEnrollmentRatio.js +++ b/src/libs/routes/liquidEnrollmentRatio.js @@ -398,7 +398,7 @@ liquidEnrollmentRatioApp.get('/', rqf.parse(),(req, res, next) => { next(); }, rqf.build(), query, id2str.transform(), (req, res, next) => { req.denominator = req.result; - + //division to generate req.result final req.result = [] let liquidEnrollment = matchQueries(req.denominator, req.numerator); diff --git a/src/libs/routes/outOfSchool.js b/src/libs/routes/outOfSchool.js index b3b6e930dc265ecd198ba95a1862679448627a6b..d7e3915a624bac28541ecbe2460f8ae54d8e0e0c 100644 --- a/src/libs/routes/outOfSchool.js +++ b/src/libs/routes/outOfSchool.js @@ -29,29 +29,31 @@ outOfSchoolApp.use(cache('15 day')); outOfSchoolApp.get('/year_range', (req, res, next) => { req.sql.from('pnad') .field('MIN(pnad.ano_censo)', 'start_year') - .field('MAX(pnad.ano_censo)', 'end_year'); + .field('MAX(pnad.ano_censo)', 'end_year') + .where('pnad.ano_censo >= 2007 AND pnad.ano_censo <= 2015'); next(); }, query, response('range')); outOfSchoolApp.get('/years', (req, res, next) => { req.sql.from('pnad'). - field('DISTINCT pnad.ano_censo', 'year'); + field('DISTINCT pnad.ano_censo', 'year') + .where('pnad.ano_censo >= 2007 AND pnad.ano_censo <= 2015'); next(); }, query, response('years')); outOfSchoolApp.get('/full_age_range', (req, res, next) => { req.result = [ - {id: 1, name: '0-3'}, - {id: 2, name: '4-5'}, - {id: 3, name: '6-10'}, - {id: 4, name: '11-14'}, - {id: 5, name: '15-17'}, - {id: 6, name: '18-24'}, - {id: 7, name: '25-29'}, - {id: 8, name: '30-40'}, - {id: 9, name: '41-50'}, - {id: 10, name: '51-64'}, - {id: 11, name: '64+'} + {id: 1, name: '0 a 3 anos'}, + {id: 2, name: '4 a 5 anos'}, + {id: 3, name: '6 a 10 anos'}, + {id: 4, name: '11 a 14 anos'}, + {id: 5, name: '15 a 17 anos'}, + {id: 6, name: '18 a 24 anos'}, + {id: 7, name: '25 a 29 anos'}, + {id: 8, name: '30 a 40 anos'}, + {id: 9, name: '41 a 50 anos'}, + {id: 10, name: '51 a 64 anos'}, + {id: 11, name: 'Mais de 64 anos'} ]; next(); }, response('full_age_range')); @@ -238,4 +240,4 @@ outOfSchoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { next(); }, query, addMissing(rqf), id2str.transform(), response('out_of_school')); -module.exports = outOfSchoolApp; \ No newline at end of file +module.exports = outOfSchoolApp; diff --git a/src/libs/routes/pibpercapita.js b/src/libs/routes/pibpercapita.js index 57b7089837579d9d1aa2d51a0a8c81591026d699..bfe2c4dde740ff787eb7c5bb1d03f34ccd1d0207 100644 --- a/src/libs/routes/pibpercapita.js +++ b/src/libs/routes/pibpercapita.js @@ -166,7 +166,7 @@ pibpercapitaApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { }, query, (req, res, next) => { req.result.forEach((i) => { let value = i.total; - console.log(i.total); + // console.log(i.total); let res = value.toString().split("."); //rounding decimal. let decimal = Math.round(res[1].toString().substring(0,2) + (".") + res[1].toString().substring(2,3)); @@ -176,7 +176,7 @@ pibpercapitaApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { } else { i.total = parseFloat(res[0] + "." + decimal); } - console.log(i.total); + // console.log(i.total); }); next(); }, addMissing(rqf), id2str.transform(false), response("pibpercapita")); diff --git a/src/libs/routes/rateSchool.js b/src/libs/routes/rateSchool.js index 856013220997193c288c99ebd83dd33ffe8d03a8..a45865a9337e027cdbec45bd8b0163bd4477112c 100644 --- a/src/libs/routes/rateSchool.js +++ b/src/libs/routes/rateSchool.js @@ -64,12 +64,12 @@ rateSchoolApp.get('/ethnic_group_pnad', (req, res, next) => { rateSchoolApp.get('/age_range', (req, res, next) => { req.result = [ - {id: 1, name: '0-3'}, - {id: 2, name: '4-5'}, - {id: 3, name: '6-10'}, - {id: 4, name: '11-14'}, - {id: 5, name: '15-17'}, - {id: 6, name: '18-24'} + {id: 1, name: '0 a 3 anos'}, + {id: 2, name: '4 a 5 anos'}, + {id: 3, name: '6 a 10 anos'}, + {id: 4, name: '11 a 14 anos'}, + {id: 5, name: '15 a 17 anos'}, + {id: 6, name: '18 a 24 anos'} ]; next(); }, response('age_range')); diff --git a/src/libs/routes/school.js b/src/libs/routes/school.js index 835181fc4669cd0d98b8b635045595ae4ee272ec..33b5e1cf983e146e30c928f50a22af6d1f98e813 100644 --- a/src/libs/routes/school.js +++ b/src/libs/routes/school.js @@ -35,13 +35,13 @@ let rqfCount = new ReqQueryFields(); schoolApp.get('/year_range', cache('15 day'), (req, res, next) => { req.sql.from('escola') .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year') + .field('MAX(escola.ano_censo)', 'end_year'); next(); }, query, response('range')); schoolApp.get('/years', cache('15 day'), (req, res, next) => { req.sql.from('escola'). - field('DISTINCT escola.ano_censo', 'year') + field('DISTINCT escola.ano_censo', 'year'); next(); }, query, response('years')); @@ -452,6 +452,16 @@ rqfCount.addField({ type: 'integer', field: 'ano_censo' } +}).addValue({ + name: 'school_building', + table: 'escola', + tableField: 'local_func_predio_escolar', + resultField: 'school_building', + where: { + relation: '=', + type: 'boolean', + field: 'local_func_predio_escolar' + } }); schoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { if(typeof req.filter === 'undefined' || Object.keys(req.filter).length === 0) { diff --git a/src/libs/routes/transport.js b/src/libs/routes/transport.js new file mode 100644 index 0000000000000000000000000000000000000000..38c81c9c1e6361b40371363c3b19e6b60390ef65 --- /dev/null +++ b/src/libs/routes/transport.js @@ -0,0 +1,521 @@ +const express = require('express'); + +const transportApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const log = require(`${libs}/log`)(module); + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const multiQuery = require(`${libs}/middlewares/multiQuery`); + +const response = require(`${libs}/middlewares/response`); + +const addMissing = require(`${libs}/middlewares/addMissing`); + +const id2str = require(`${libs}/middlewares/id2str`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const config = require(`${libs}/config`); + +const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; + +let rqf = new ReqQueryFields(); + +transportApp.use(cache('15 day')); + +transportApp.get('/year_range', (req, res, next) => { + req.sql.from('matricula') + .field('MIN(matricula.ano_censo)', 'start_year') + .field('MAX(matricula.ano_censo)', 'end_year'); + next(); +}, query, response('range')); + +transportApp.get('/years', (req, res, next) => { + req.sql.from('matricula') + .field('DISTINCT matricula.ano_censo', 'year'); + next(); +}, query, response('years')); + +transportApp.get('/adm_dependency', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 4; ++i) { + req.result.push({ + id: i, + name: id2str.admDependency(i) + }); + }; + next(); +}, response('adm_dependency')); + +transportApp.get('/adm_dependency_detailed', (req, res, next) => { + req.result = []; + for(let i = 1; i <= 6; ++i) { + req.result.push({ + id: i, + name: id2str.admDependencyPriv(i) + }); + }; + next(); +}, response('adm_dependency_detailed')); + +transportApp.get('/location', (req, res, next) => { + req.result = [ + {id: 1, name: 'Urbana'}, + {id: 2, name: 'Rural'} + ]; + next(); +}, response('location')); + +transportApp.get('/rural_location', (req, res, next) => { + req.result = [ + {id: 1, name: "Urbana"}, + {id: 2, name: "Rural"}, + {id: 3, name: "Rural - Ãrea de assentamento"}, + {id: 4, name: "Rural - Terra indÃgena"}, + {id: 5, name: "Rural - Ãrea remanescente de quilombos"}, + {id: 6, name: "Rural - Unidade de uso sustentável"} + ]; + next(); +}, response('rural_location')); + +transportApp.get('/education_level_basic', (req, res, next) => { + req.result = [ + {id: null, name: 'Não classificada'}, + {id: 1, name: 'Creche'}, + {id: 2, name: 'Pré-Escola'}, + {id: 4, name: 'Ensino Fundamental - anos iniciais'}, + {id: 5, name: 'Ensino Fundamental - anos finais'}, + {id: 6, name: 'Ensino Médio'} + ]; + next(); +}, response('education_level_basic')); + +transportApp.get('/service_type', (req, res, next) => { + req.result = [ + {id: 0, name: 'Não se aplica'}, + {id: 1, name: 'Classe hospitalar'}, + {id: 2, name: 'Unidade de Atendimento Socioeducativo'}, + {id: 3, name: 'Unidade Prisional'}, + {id: 4, name: 'Atividade Complementar '}, + {id: 5, name: 'Atendimento Educacional Especializado (AEE)'} + ]; + next(); +}, response('service_type')); + +transportApp.get('/transportation_manager', (req, res, next) => { + req.result = [ + {id: null, name: 'Não classificada'}, + {id: 1, name: 'Estadual'}, + {id: 2, name: 'Municipal'}, + ]; + next(); +}, response('transportation_manager')); + +transportApp.get('/source', (req, res, next) => { + req.sql.from('fonte') + .field('fonte', 'source') + .where('tabela = \'matricula\''); + next(); +}, query, response('source')); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'school', + table: 'escola', + tableField: ['nome_escola', 'id'], + resultField: ['school_name', 'school_id'], + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: ['id', 'ano_censo'], + foreign: ['escola_id', 'ano_censo'], + foreignTable: 'matricula' + } +}).addValue({ + name: 'region', + table: 'regiao', + tableField: 'nome', + resultField: 'region_name', + where: { + relation: '=', + type: 'integer', + field: 'id' + }, + join: { + primary: 'id', + foreign: 'regiao_id', + foreignTable: 'matricula' + } +}).addValue({ + name: 'city', + table: 'municipio', + tableField: 'nome', + resultField: 'city_name', + where: { + relation: '=', + type: 'integer', + field: 'municipio_id', + table: 'matricula' + }, + join: { + primary: 'id', + foreign: 'municipio_id', + foreignTable: 'matricula' + } +}).addValue({ + name: 'state', + table: 'estado', + tableField: 'nome', + resultField: 'state_name', + where: { + relation: '=', + type: 'integer', + field: 'estado_id', + table: 'matricula' + }, + join: { + primary: 'id', + foreign: 'estado_id', + foreignTable: 'matricula' + } +}).addValue({ + name: 'rural_location', + table: 'matricula', + tableField: 'localidade_area_rural', + resultField: 'rural_location_id', + where: { + relation: '=', + type: 'integer', + field: 'localidade_area_rural' + } +}).addValue({ + name: 'location', + table: 'matricula', + tableField: 'localizacao_id', + resultField: 'location_id', + where: { + relation: '=', + type: 'integer', + field: 'localizacao_id' + } +}).addValue({ + name:'adm_dependency', + table: 'matricula', + tableField: 'dependencia_adm_id', + resultField: 'adm_dependency_id', + where: { + relation: '=', + type: 'integer', + field: 'dependencia_adm_id' + } +}).addValue({ + name: 'adm_dependency_detailed', + table: 'matricula', + tableField: 'dependencia_adm_priv', + resultField: 'adm_dependency_detailed_id', + where: { + relation: '=', + type: 'integer', + field: 'dependencia_adm_priv' + } +}).addValue({ + name: 'transportation_manager', + table: 'matricula', + tableField: 'responsavel_transp', + resultField: 'transportation_manager_id', + where: { + relation: '=', + type: 'integer', + field: 'responsavel_transp' + } +}).addValue({ + name: 'education_level_basic', + table: 'matricula', + tableField: 'etapas_mod_ensino_segmento_id', + resultField: 'education_level_basic_id', + where: { + relation: '=', + type: 'integer', + field: 'etapas_mod_ensino_segmento_id' + } +}).addValue({ + name: 'service_type', + table: 'matricula', + tableField: 'tipo', + resultField: 'service_type_id', + where: { + relation: '=', + type: 'integer', + field: 'tipo' + } +}).addValue({ + name: 'service_type', + table: 'matricula', + tableField: 'tipo', + resultField: 'service_type_id', + where: { + relation: '=', + type: 'integer', + field: 'tipo' + } +}).addValue({ + name: 'min_year', + table: 'matricula', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo' + } +}).addValue({ + name: 'max_year', + table: 'matricula', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo' + } +}); + +function matchQueries(queryTotal, queryPartial) { + let match = []; + queryTotal.forEach((result) => { + let newObj = {}; + let keys = Object.keys(result); + keys.forEach((key) => { + newObj[key] = result[key]; + }); + let index = keys.indexOf('total'); + if(index > -1) keys.splice(index, 1); + let objMatch = null; + + for(let i = 0; i < queryPartial.length; ++i) { + let partial = queryPartial[i]; + let foundMatch = true; + for(let j = 0; j < keys.length; ++j) { + let key = keys[j]; + if(partial[key] !== result[key]) { + foundMatch = false; + break; + } + } + if(foundMatch) { + objMatch = partial; + break; + } + } + + if(objMatch) { + newObj.percentage = (objMatch.total / result.total) * 100; + newObj.partial = objMatch.total; + newObj.total = result.total + match.push(newObj); + } + }); + + return match; +} + +transportApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.querySet = []; + req.queryIndex = {}; + + let allEnrollment = req.sql.clone() + allEnrollment.field('COUNT(*)', 'total') + .field("'Brasil'", 'name') + .field('matricula.ano_censo', 'year') + .from('matricula') + .group('matricula.ano_censo') + .order('matricula.ano_censo') + .where('matricula.tipo <= 3'); + req.queryIndex.allEnrollment = req.querySet.push(allEnrollment) - 1; + + let allEnrollmentTransport = req.sql.clone() + allEnrollmentTransport.field('COUNT(*)', 'total') + .field("'Brasil'", 'name') + .field('matricula.ano_censo', 'year') + .field('matricula.transporte_escolar_publico', 'use_transport_id') + .from('matricula') + .group('matricula.ano_censo') + .order('matricula.ano_censo') + .where('matricula.tipo <= 3'); + req.queryIndex.allEnrollmentTransport = req.querySet.push(allEnrollmentTransport) - 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_public_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 OR matricula.transporte_vans_kombi = 0'); + 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 OR matricula.transporte_micro_onibus = 0'); + 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 OR matricula.transporte_onibus = 0'); + 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 OR matricula.transporte_bicicleta = 0'); + 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 OR matricula.transporte_animal = 0'); + 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 OR matricula.transporte_outro = 0'); + 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 OR matricula.transporte_embar_0_5 = 0'); + 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 OR matricula.transporte_embar_5_15 = 0'); + 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 OR matricula.transporte_embar_15_35 = 0'); + 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 OR matricula.transporte_embar_35 = 0'); + 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 OR matricula.transporte_trem_metro = 0'); + 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_public_id = true; + all_enrollment_match.push(all_enrollment_match_0[i]) + all_enrollment_match_1[i].use_transport_public_id = false; + all_enrollment_match.push(all_enrollment_match_1[i]) + } + + let public_transport = matchQueries(all_enrollment_match, req.result[req.queryIndex.allEnrollmentTransport]); + let van_and_kombi = matchQueries(transport_match, req.result[req.queryIndex.goVansAndKombi]); + let micro_bus = matchQueries(transport_match, req.result[req.queryIndex.goMicroBus]); + let bus = matchQueries(transport_match, req.result[req.queryIndex.goBus]); + let bike = matchQueries(transport_match, req.result[req.queryIndex.goBikes]); + let animal_traction = matchQueries(transport_match, req.result[req.queryIndex.goAnimalTraction]); + let other_vehicle = matchQueries(transport_match, req.result[req.queryIndex.goOtherVehicle]); + let waterway_5_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_5_Students]); + let waterway_15_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_15_Students]); + let waterway_35_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_35_Students]); + let waterway_More_Than_35 = matchQueries(transport_match, req.result[req.queryIndex.goWaterwayMoreThan_35]); + let subway_and_train = matchQueries(transport_match, req.result[req.queryIndex.goSubwayAndTrain]); + + req.result = [{ + public_transport, + van_and_kombi, + micro_bus, + bus, + bike, + animal_traction, + other_vehicle, + waterway_5_Students, + waterway_15_Students, + waterway_35_Students, + waterway_More_Than_35, + subway_and_train + }]; + next(); +}, id2str.multitransform(false), response('transports')); + +module.exports = transportApp; diff --git a/src/libs/routes/user.js b/src/libs/routes/user.js index af123a588d41a37c1e64fb0cfa20abe3928a84b4..ee5ddf0171999840a2bdd4fec9a7a2e1ef234713 100644 --- a/src/libs/routes/user.js +++ b/src/libs/routes/user.js @@ -141,54 +141,76 @@ userApp.post('/', (req, res, next) => { 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) { + let emailAddress = req.body.email; + let origin = req.body.origin; + User.findOne({email: emailAddress}, (err, find)=> { + 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}); - } + } else if (find) { + if (find.origin != origin) { + res.statusCode = 400; + return res.json({errors:["Identificamos que esta conta já existe em outra plataforma.\n\nVocê pode realizar o login com a conta do SimCAQ ou criar uma conta nova com outros dados"]}); + } else { + res.statusCode = 400; + return res.json({errors:["Identificamos que esta conta já existe nesta plataforma"]}); + } + } else { + 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 - }); + // 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`); + 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'}); + }); + }); + }); } - res.json({msg: 'User created'}); - }); - }); - }); - } + } + }) }); diff --git a/src/test/auxiliar.js b/src/test/auxiliar.js new file mode 100644 index 0000000000000000000000000000000000000000..1bb0d309c8fa5ef6165fabae2018f5a6bbd1a090 --- /dev/null +++ b/src/test/auxiliar.js @@ -0,0 +1,345 @@ +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 auxiliar', () => { + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/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 source', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/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 locations', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/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 years', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/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 rural locations', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/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/auxiliar/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 administrative dependencies', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/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/auxiliar/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 genders', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/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 ethnic groups', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/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 teachers count', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?filter=min_year:2016,max_year:2016') + .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('name'); + res.body.result[0].should.have.property('total'); + done(); + }); + }); + + it('should list teacher count with valid filters', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?filter=min_year:2015,max_year:2015,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('name'); + res.body.result[0].should.have.property('total'); + done(); + }); + }); + + it('should list teacher count with invalid filters', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?filter=foo:2010,bar:41,min_year:2016,max_year:2016') + .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('name'); + res.body.result[0].should.have.property('total'); + done(); + }); + }); + + it('should list teacher count with valid dimensions', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=region,state,adm_dependency,location,gender,ethnic_group&filter=min_year:2016,max_year:2016') + .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('region_name'); + res.body.result[0].should.have.property('state_name'); + res.body.result[0].should.have.property('adm_dependency_name'); + res.body.result[0].should.have.property('location_name'); + res.body.result[0].should.have.property('total'); + done(); + }); + }); + + it('should list teacher count with invalid dimensions', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=foo,bar&filter=min_year:2016,max_year:2016') + .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('name'); + res.body.result[0].should.have.property('total'); + done(); + }); + }); + + it('should list teacher count with valid dimensions and filters', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=region,state,gender&filter=min_year:2015,max_year:2015,city:4106902') + .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('region_name'); + res.body.result[0].should.have.property('state_name'); + res.body.result[0].should.have.property('total'); + res.body.result[0].should.have.property('year'); + done(); + }); + }); + + it('should list teacher count with dimension location', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=location&filter=min_year:2016,max_year:2016') + .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 teacher count with dimension rural_location', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=rural_location&filter=min_year:2016,max_year:2016') + .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('rural_location_name'); + done(); + }); + }); + + it('should list teacher count with dimension education_level_mod', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=education_level_mod&filter=min_year:2015,max_year:2015') + .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('education_level_mod_name'); + done(); + }); + }); + + it('should list teacher count with dimension adm_dependency', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=adm_dependency&filter=min_year:2016,max_year:2016') + .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('adm_dependency_name'); + done(); + }); + }); + + it('should list teacher count with dimension adm_dependency_detailed', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=adm_dependency_detailed&filter=min_year:2016,max_year:2016') + .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('adm_dependency_detailed_name'); + done(); + }); + }); + + it('should list teacher count with dimension gender', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=gender&filter=min_year:2016,max_year:2016') + .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('gender_name'); + done(); + }); + }); + + it('should list teacher count with dimension ethnic_group', (done) => { + chai.request(server) + .get('/api/v1/auxiliar/count?dims=ethnic_group&filter=min_year:2016,max_year:2016') + .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('ethnic_group_name'); + done(); + }); + }); +}); diff --git a/src/test/class.js b/src/test/class.js index ef5254f45d847a568c17b31afafc8119273cb50e..3000476ce8f5008dae9e9d8b51132a7512081a9d 100644 --- a/src/test/class.js +++ b/src/test/class.js @@ -38,6 +38,20 @@ describe('request class', () => { }); }); + it('should list the years', (done) => { + chai.request(server) + .get('/api/v1/class/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 source', (done) => { chai.request(server) .get('/api/v1/class/source') diff --git a/src/test/cub.js b/src/test/cub.js new file mode 100644 index 0000000000000000000000000000000000000000..751ca40a2a77ff9fe7275f0a2f3c769c5318e4f3 --- /dev/null +++ b/src/test/cub.js @@ -0,0 +1,109 @@ +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 cub', () => { + it('should return default query cub', (done) => { + chai.request(server) + .get('/api/v1/cub') + .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 list the years', (done) => { + chai.request(server) + .get('/api/v1/cub/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 year range', (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('start_year'); + res.body.result[0].should.have.property('end_year'); + done(); + }); + }); + + it('should list the months', (done) => { + chai.request(server) + .get('/api/v1/cub/months') + .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('month'); + done(); + }); + }); + + 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') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('price_type'); + done(); + }); + }); +}); diff --git a/src/test/dailyChargeAmount.js b/src/test/dailyChargeAmount.js new file mode 100644 index 0000000000000000000000000000000000000000..6cef69f46622bb13cc031234dc19279e5ca7ddb4 --- /dev/null +++ b/src/test/dailyChargeAmount.js @@ -0,0 +1,159 @@ +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 daily charge amount', () => { + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/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 year range', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/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 locations', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/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') + .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 mod', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/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 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"]') + .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('education_level_short_name'); + 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'); + done(); + }); + }); + + it('should list the filter of education level mod', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/average?filter=education_level_mod:["3","4","5","6"],integral_time:"0",period:["3"]') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('education_level_mod_id'); + res.body.result[0].should.have.property('education_level_mod_name'); + res.body.result[0].should.have.property('average_class_duration'); + done(); + }); + }); + + it('should return 400 with no filters', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount') + .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 return 400 with no filters', (done) => { + chai.request(server) + .get('/api/v1/daily_charge_amount/average?filter=education_level_mod:["3","4","5","6"]') + .end((err, res) => { + res.should.have.status(200); + res.should.be.json; + res.body.should.have.property('result'); + res.body.result.should.be.a('array'); + res.body.result[0].should.have.property('year'); + res.body.result[0].should.have.property('education_level_mod_id'); + res.body.result[0].should.have.property('education_level_mod_name'); + res.body.result[0].should.have.property('average_class_duration'); + done(); + }); + }); +}); diff --git a/src/test/distributionFactor.js b/src/test/distributionFactor.js index e0531c6bfa03ee0d3aba2e49bb3c92e1f3510f13..e733fc5908cd0791490645abed718ffb5aa0dcfb 100644 --- a/src/test/distributionFactor.js +++ b/src/test/distributionFactor.js @@ -24,51 +24,51 @@ const server = require(`${libs}/app`); chai.use(chaiHttp); describe('request distribution factor', () => { - it('should list default distribution factor', (done) => { - chai.request(server) - .get('/api/v1/distribution_factor') - .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('city_id'); - res.body.result[0].should.have.property('series'); - res.body.result[0].series[0].should.have.property('serie_id'); - res.body.result[0].series[0].should.have.property('distribution_factor_reduction'); - done(); - }); - }); + // it('should list default distribution factor', (done) => { + // chai.request(server) + // .get('/api/v1/distribution_factor') + // .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('city_id'); + // res.body.result[0].should.have.property('series'); + // res.body.result[0].series[0].should.have.property('serie_id'); + // res.body.result[0].series[0].should.have.property('distribution_factor_reduction'); + // done(); + // }); + // }); - it('should list distribution factor with valid filters', (done) => { - chai.request(server) - .get('/api/v1/distribution_factor?filter=state:41,city:4100103') - .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('city_id'); - res.body.result[0].should.have.property('series'); - res.body.result[0].series[0].should.have.property('serie_id'); - done(); - }); - }); + // it('should list distribution factor with valid filters', (done) => { + // chai.request(server) + // .get('/api/v1/distribution_factor?filter=state:41,city:4100103') + // .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('city_id'); + // res.body.result[0].should.have.property('series'); + // res.body.result[0].series[0].should.have.property('serie_id'); + // done(); + // }); + // }); - it('should list distribution factor with valid filters', (done) => { - chai.request(server) - .get('/api/v1/distribution_factor?filter=city:1100023') - .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('city_id'); - res.body.result[0].should.have.property('series'); - res.body.result[0].series[0].should.have.property('serie_id'); - res.body.result[0].series[0].should.have.property('distribution_factor_addition'); - done(); - }); - }); + // it('should list distribution factor with valid filters', (done) => { + // chai.request(server) + // .get('/api/v1/distribution_factor?filter=city:1100023') + // .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('city_id'); + // res.body.result[0].should.have.property('series'); + // res.body.result[0].series[0].should.have.property('serie_id'); + // res.body.result[0].series[0].should.have.property('distribution_factor_addition'); + // done(); + // }); + // }); }); diff --git a/src/test/glossEnrollmentRatio.js b/src/test/glossEnrollmentRatio.js new file mode 100644 index 0000000000000000000000000000000000000000..4043bf4a670b72864de89210b933eb992abd024c --- /dev/null +++ b/src/test/glossEnrollmentRatio.js @@ -0,0 +1,194 @@ +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 gloss enrollment ratio', () => { + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio/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 year range', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio/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 return 400 with no filters', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio') + .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 locations', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio/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 genders', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio/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 education level basic', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio/education_level_basic') + .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 ethnic group', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio/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 dimensions of education_level_basic', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio?dims=education_level_basic&filter=min_year:"2015",max_year:"2015"') + .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(); + }); + }); + + it('should list the dimensions of ethnic groups and education level basic', (done) => { + chai.request(server) + .get('/api/v1/gloss_enrollment_ratio?dims=education_level_basic,gender&filter=min_year:"2015",max_year:"2015"') + .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('gender_id'); + res.body.result[0].should.have.property('gender_name'); + 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/gloss_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/gloss_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/id2str.js b/src/test/id2str.js index 153768988421d52127e8ff7f3f9a9b0d5800d4d2..8d6f5457fac34c031612fd4cf8a9732a66690f67 100644 --- a/src/test/id2str.js +++ b/src/test/id2str.js @@ -44,9 +44,12 @@ describe('id2str middleware', () => { }); it('should transform a location id', (done) => { - expect(id2str.location(6)).to.deep.equal('Unidade de uso sustentável'); + expect(id2str.location(1)).to.deep.equal('Urbana'); + expect(id2str.location(2)).to.deep.equal('Rural'); + expect(id2str.location(3)).to.deep.equal('Ãrea de assentamento'); expect(id2str.location(4)).to.deep.equal('Terra indÃgena'); expect(id2str.location(5)).to.deep.equal('Ãrea remanescente de quilombos'); + expect(id2str.location(6)).to.deep.equal('Unidade de uso sustentável'); done(); }); @@ -58,20 +61,87 @@ describe('id2str middleware', () => { it('should transform a income level id', (done) => { expect(id2str.incomeLevel(1)).to.deep.equal('1º quintil – 20% menores'); + expect(id2str.incomeLevel(12)).to.deep.equal('Não classificada'); + done(); + }); + + it('should transform a education level basic id', (done) => { + expect(id2str.educationLevelBasic(7)).to.deep.equal('Não classificada'); + done(); + }); + + it('should transform a age range id', (done) => { + expect(id2str.ageRange(12)).to.deep.equal('Não declarada'); + done(); + }); + + it('should transform a booleans variables', (done) => { + expect(id2str.booleanVariable(1)).to.deep.equal('Sim'); + expect(id2str.booleanVariable(0)).to.deep.equal('Não'); + expect(id2str.booleanVariable(null)).to.deep.equal('Não Declarado'); + done(); + }); + + it('should transform a city size id', (done) => { + expect(id2str.citySize(10)).to.deep.equal('Não classificada'); done(); - }); + }); + + it('should transform a educatoin type id', (done) => { + expect(id2str.educationType(10)).to.deep.equal('Não definido'); + done(); + }); - it('should transform a class adm dependency id', (done) => { + + it('should transform a gender Pnad id', (done) => { + expect(id2str.genderPnad(2)).to.deep.equal('Masculino'); + expect(id2str.genderPnad(4)).to.deep.equal('Feminino'); + done(); + }); + + it('should transform a adm dependency id', (done) => { expect(id2str.admDependency(6)).to.deep.equal('Não classificada'); done(); }); - it('should transform a class adm dependency priv id', (done) => { + it('should transform a adm dependency priv id', (done) => { expect(id2str.admDependencyPriv(7)).to.deep.equal('Não classificada'); + done(); + }); + + it('should transform a ethnic group id', (done) => { + expect(id2str.ethnicGroup(7)).to.deep.equal('Não declarada'); + done(); + }); + it('should transform a ethnic group Pnad id', (done) => { + expect(id2str.ethnicGroupPnad(7)).to.deep.equal('Sem declaração'); done(); }); + 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(12)).to.deep.equal('Não declarada'); + + done(); + }); + + it('should transform a idhm level id', (done) => { + expect(id2str.idhmLevel(12)).to.deep.equal('Não classificada'); + done(); + }); + + it('should transform a result', (done) => { let req = { result: [{gender_id: 2, period_id: 3, school_year_id: 11}] diff --git a/src/test/infrastructure.js b/src/test/infrastructure.js index c92fda1e1b4ae003beff20c202d852fa997eb115..8714a73cd12a73ba81652ff13a9f3feacc661dc9 100644 --- a/src/test/infrastructure.js +++ b/src/test/infrastructure.js @@ -50,6 +50,20 @@ describe('request infrastructure', () => { }); }); + it('should list the years', (done) => { + chai.request(server) + .get('/api/v1/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 source', (done) => { chai.request(server) .get('/api/v1/infrastructure/source') diff --git a/src/test/liquidEnrollmentRatio.js b/src/test/liquidEnrollmentRatio.js new file mode 100644 index 0000000000000000000000000000000000000000..ec0489e905f1fd8360200adbdb603f4d888233a0 --- /dev/null +++ b/src/test/liquidEnrollmentRatio.js @@ -0,0 +1,194 @@ +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 liquid enrollment ratio', () => { + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio/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 year range', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio/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 return 400 with no filters', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio') + .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 locations', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio/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 genders', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio/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 education level basic', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio/education_level_basic') + .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 ethnic group', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio/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 dimensions of education_level_basic', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio?dims=education_level_basic&filter=min_year:"2015",max_year:"2015"') + .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(); + }); + }); + + it('should list the dimensions of ethnic groups and education level basic', (done) => { + chai.request(server) + .get('/api/v1/liquid_enrollment_ratio?dims=education_level_basic,gender&filter=min_year:"2015",max_year:"2015"') + .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('gender_id'); + res.body.result[0].should.have.property('gender_name'); + 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"]') + .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 266c542850095f1469d7952174af80e3a35d18e1..0ca4c78b47b93addb3aa5970588bfa1fc060d87f 100644 --- a/src/test/school.js +++ b/src/test/school.js @@ -54,6 +54,21 @@ describe('request schools', () => { }); }); + it('should list a school by id', (done) => { + chai.request(server) + .get('/api/v1/school/education_end_elementary_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('id'); + res.body.result[0].should.have.property('name'); + //res.body.result[0].should.have.property('nome_entidade'); + done(); + }); + }); + it('should list all schools from a state', (done) => { chai.request(server) .get('/api/v1/school?filter=state:41') @@ -84,6 +99,33 @@ describe('request schools', () => { }) }); + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/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 year range', (done) => { + chai.request(server) + .get('/api/v1/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 return 400 with no filters', (done) => { chai.request(server) .get('/api/v1/school') diff --git a/src/test/transport.js b/src/test/transport.js new file mode 100644 index 0000000000000000000000000000000000000000..78a4075b9dbc56a8fadcc3d55581f3338cbe613c --- /dev/null +++ b/src/test/transport.js @@ -0,0 +1,164 @@ +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 transport', () => { + it('should list default query transport', (done) => { + chai.request(server) + .get('/api/v1/transport') + .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('public_transport'); + done(); + }); + }); + + it('should list the year range', (done) => { + chai.request(server) + .get('/api/v1/transport/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 years', (done) => { + chai.request(server) + .get('/api/v1/transport/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 source', (done) => { + chai.request(server) + .get('/api/v1/transport/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 rural locations', (done) => { + chai.request(server) + .get('/api/v1/transport/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 locations', (done) => { + chai.request(server) + .get('/api/v1/transport/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 detailed', (done) => { + chai.request(server) + .get('/api/v1/transport/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 adm dependency', (done) => { + chai.request(server) + .get('/api/v1/transport/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 transportation manager', (done) => { + chai.request(server) + .get('/api/v1/transport/transportation_manager') + .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 basic', (done) => { + chai.request(server) + .get('/api/v1/transport/education_level_basic') + .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(); + }); + }); + +});