diff --git a/ SMPPIR-API Specification.yaml b/ SMPPIR-API Specification.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a79e649100bfa66cc0c7613a45bed5f1430818d8 --- /dev/null +++ b/ SMPPIR-API Specification.yaml @@ -0,0 +1,2973 @@ +# Specification of SMPPIR API using OpenAPI 3.0 +# For the specification of OpenAPI 3.0, please refer to: https://swagger.io/docs/specification/about/ +openapi: "3.0.0" +info: + version: 1.0.0 + title: SMPPIR - API + description: 'This API provides access to quotas data based in [INEP - Census of higher education](http://portal.inep.gov.br/web/guest/microdados), [PNAD - People information](http://www.ibge.gov.br/home/estatistica/pesquisas/pesquisa_resultados.php?id_pesquisa=40), [FIES](http://www.fnde.gov.br/dadosabertos/dataset/fundo-de-financiamento-estudantil-fies), [PROUNI](http://dadosabertos.mec.gov.br/prouni)' + +servers: + - url: http://seppirdev.c3sl.ufpr.br:4000/api/v1 + +tags: + - name: INEP + description: "Contains queries made with data from the INEP database listed above. This section's concern is the undergraduation students" + externalDocs: + url: http://portal.inep.gov.br/web/guest/microdados + - name: FIES + description: "Contains queries made with data from the FIES database listed above. This section's concern is the loan for undergraduation students" + externalDocs: + url: http://www.fnde.gov.br/dadosabertos/dataset/fundo-de-financiamento-estudantil-fies + - name: PNAD + description: "Contains queries made with data from the PNAD database listed above. This section's concern is the educational level of the population between 18 and 24 years old" + externalDocs: + url: http://www.ibge.gov.br/home/estatistica/pesquisas/pesquisa_resultados.php?id_pesquisa=40 + - name: PROUNI + description: "Contains queries made with data from the PROUNI database listed above. This section's concern is the federal scholarship" + externalDocs: + url: http://www.ibge.gov.br/home/estatistica/pesquisas/pesquisa_resultados.php?id_pesquisa=40 +# - name: IBGE - Census +# description: "Contains queries made with data from IBGE Census" +# externalDocs: +#url: https://ww2.ibge.gov.br/home/estatistica/populacao/censo2010/resultados_gerais_amostra/resultados_gerais_amostra_tab_uf_microdados.shtm + - name: CadÚnico + description: "Contains queries made with data from CadÚnico" + externalDocs: + url: https://aplicacoes.mds.gov.br/sagi/portal/index.php?grupo=212 + - name: EXTRA + description: "Contains data from auxiliary extra routes" + externalDocs: + url: https://ww2.ibge.gov.br/home/estatistica/populacao/censo2010/resultados_gerais_amostra/resultados_gerais_amostra_tab_uf_microdados.shtm + +paths: + /admission: + get: + summary: Return the number of quotasholder that entered in a federal institution. This route uses the INEP database listed above + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: shift,gender,ethnic + schema: + type: array + items: + type: string + enum: + - shift + - gender + - ethnic + - course + - institution + - institution_cod + - year + - min_year + - max_year + - cod_offer_location + - name_offer_location + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: shift:["Integral","Noturno"],gender:"Feminino" + schema: + type: array + items: + type: object + properties: + shift: + type: array + items: + type: string + gender: + type: array + items: + type: string + ethnic: + type: array + items: + type: string + course: + type: array + items: + type: string + institution: + type: array + items: + type: string + institution_code: + type: array + items: + type: integer + year: + type: array + items: + type: integer + min_year: + type: integer + max_year: + type: integer + cod_offer_location: + type: array + items: + type: integer + name_offer_location: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/BasicInepReturn' + '404': + description: no data found + /evader: + get: + summary: Return the number of quotasholder that had been studying in a federal institution and drop out. This route uses the INEP database listed above + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: shift,gender,ethnic + schema: + type: array + items: + type: string + enum: + - shift + - gender + - ethnic + - course + - institution + - institution_cod + - year + - min_year + - max_year + - cod_offer_location + - name_offer_location + - region + - uf + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: shift:["Integral","Noturno"],gender:"Feminino" + schema: + type: array + items: + type: object + properties: + shift: + type: array + items: + type: string + gender: + type: array + items: + type: string + ethnic: + type: array + items: + type: string + course: + type: array + items: + type: string + institution: + type: array + items: + type: string + institution_code: + type: array + items: + type: integer + year: + type: array + items: + type: integer + min_year: + type: integer + max_year: + type: integer + cod_offer_location: + type: array + items: + type: integer + name_offer_location: + type: array + items: + type: string + region: + type: array + items: + type: string + uf: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/BasicInepReturnWithLocationInfo' + '404': + description: no data found + /extracurricular_activities: + get: + summary: Return the number of quotasholder that studie in a federal institution and do any type of extracurricular activity (Intership, Teacher's Assistant, etc.). This route uses the INEP database listed above + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: shift,gender,ethnic + schema: + type: array + items: + type: string + enum: + - shift + - gender + - ethnic + - course + - institution + - institution_cod + - year + - min_year + - max_year + - cod_offer_location + - name_offer_location + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: shift:["Integral","Noturno"],gender:"Feminino" + schema: + type: array + items: + type: object + properties: + shift: + type: array + items: + type: string + gender: + type: array + items: + type: string + ethnic: + type: array + items: + type: string + course: + type: array + items: + type: string + institution: + type: array + items: + type: string + institution_code: + type: array + items: + type: integer + year: + type: array + items: + type: integer + min_year: + type: integer + max_year: + type: integer + cod_offer_location: + type: array + items: + type: integer + name_offer_location: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/BasicInepReturn' + '404': + description: no data found + /fies: + get: + summary: Return the number of students that got a loan from FIES. This route uses the FIES database listed above + tags: + - FIES + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: gender,ethnic + schema: + type: array + items: + type: string + enum: + - gender + - ethnic + - course + - institution + - institution_cod + - offer_location + - loan + - loan_type + - uf + - region + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: gender:"Feminino",ethnic:["Branco","Pardo"] + schema: + type: array + items: + type: object + properties: + gender: + type: array + items: + type: string + enum: ['Masculino', 'Feminino'] + ethnic: + type: array + items: + type: string + enum: ['Amarelo', 'Branco', 'Negro', 'Pardo', 'Índio'] + course: + type: array + items: + type: string + institution: + type: array + items: + type: string + institution_cod: + type: array + items: + type: integer + offer_location: + type: array + items: + type: string + loan: + type: array + items: + type: integer + enum: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 ] + loan_type: + type: array + items: + type: string + enum: ["F", "N", "S"] + year: + type: array + items: + type: integer + min_year: + type: integer + max_year: + type: integer + region: + type: array + items: + type: string + enum: [ 'Norte', 'Nordeste', 'Centro-Oeste', 'Sul', 'Sudeste' ] + uf: + type: array + items: + type: string + enum: [ 'AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO' ] + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/FiesReturn' + '404': + description: no data found + /graduate: + get: + summary: Return the number of quotasholder that had been studying in a federal institution and finished their studies + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: shift,gender,ethnic + schema: + type: array + items: + type: string + enum: + - shift + - gender + - ethnic + - course + - institution + - institution_cod + - year + - min_year + - max_year + - cod_offer_location + - name_offer_location + - region + - uf + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: shift:["Integral","Noturno"],gender:"Feminino" + schema: + type: array + items: + type: object + properties: + shift: + type: array + items: + type: string + gender: + type: array + items: + type: string + ethnic: + type: array + items: + type: string + course: + type: array + items: + type: string + institution: + type: array + items: + type: string + institution_code: + type: array + items: + type: integer + year: + type: array + items: + type: integer + min_year: + type: integer + max_year: + type: integer + cod_offer_location: + type: array + items: + type: integer + name_offer_location: + type: array + items: + type: string + region: + type: array + items: + type: string + uf: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/BasicInepReturnWithLocationInfo' + '404': + description: no data found + + /course: + get: + summary: Return the available courses made available by the IFES(Instituto Federal de Educação Superior). This route uses the INEP database listed above + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,uf + schema: + type: array + items: + type: string + enum: + - year + - min_year + - max_year + - uf + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: year:"2015", uf:"PR" + schema: + type: array + items: + type: object + properties: + year: + type: number + min_year: + type: number + max_year: + type: number + uf: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/course' + '404': + description: no data found + + /courseFIES: + get: + summary: Return the available courses made available by the IFES(Instituto Federal de Educação Superior). This route uses the FIES database listed above + tags: + - FIES + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,uf + schema: + type: array + items: + type: string + enum: + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: year:"2015" + schema: + type: array + items: + type: object + properties: + year: + type: number + min_year: + type: number + max_year: + type: number + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/coursePROUNI' + '404': + description: no data found + + /coursePROUNI: + get: + summary: Return the available courses made available by the IFES(Instituto Federal de Educação Superior). This route uses the PROUNI database listed above + tags: + - PROUNI + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,uf + schema: + type: array + items: + type: string + enum: + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: year:"2015" + schema: + type: array + items: + type: object + properties: + year: + type: number + min_year: + type: number + max_year: + type: number + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/courseFIES' + '404': + description: no data found + + /institution: + get: + summary: Return the exiting IFES(Instituto Federal de Educação Superior) that are public. This route uses the INEP database listed above + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,uf + schema: + type: array + items: + type: string + enum: + - year + - min_year + - max_year + - uf + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: year:"2015", uf:"PR" + schema: + type: array + items: + type: object + properties: + year: + type: number + min_year: + type: number + max_year: + type: number + uf: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/institution' + '404': + description: no data found + + /institutionFIES: + get: + summary: Return the exiting IFES(Instituto Federal de Educação Superior) that are public. This route uses the FIES database listed above + tags: + - FIES + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,uf + schema: + type: array + items: + type: string + enum: + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: year:"2015" + schema: + type: array + items: + type: object + properties: + year: + type: number + min_year: + type: number + max_year: + type: number + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/institutionFIES' + '404': + description: no data found + + /institutionPROUNI: + get: + summary: Return the exiting IFES(Instituto Federal de Educação Superior) that are public. This route uses the PROUNI database listed above + tags: + - PROUNI + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,uf + schema: + type: array + items: + type: string + enum: + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: year:"2015" + schema: + type: array + items: + type: object + properties: + year: + type: number + min_year: + type: number + max_year: + type: number + + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/institutionPROUNI' + '404': + description: no data found + + /ibge_code: + get: + summary: Return the name and code of a city as well as the code for the state the city is in. This route uses the IBGE database listed above. + tags: + - EXTRA + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,uf + schema: + type: array + items: + type: string + enum: + - city_name + - city_code + - state + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: city_name:"Curitiba", state:"17" + schema: + type: array + items: + type: object + properties: + city_name: + type: string + city_code: + type: number + state: + type: number + + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ibge_code' + '404': + description: no data found + + /institutionPrivate: + get: + summary: Return the existing IFES(Instituto Federal de Educação Superior) that are private. This route uses the INEP database listed above + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,uf + schema: + type: array + items: + type: string + enum: + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: year:"2015" + schema: + type: array + items: + type: object + properties: + year: + type: number + min_year: + type: number + max_year: + type: number + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/institutionPrivate' + '404': + description: no data found + + /vacancy: + get: + summary: Return the number of quotasholder spots that are open to students in a federal institution + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: shift,gender,ethnic + schema: + type: array + items: + type: string + enum: + - region + - uf + - cod_ies + - campus + - course + - shift + - name_ies + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: shift:["Integral","Noturno"],gender:"Feminino" + schema: + type: array + items: + type: object + properties: + shift: + type: array + items: + type: string + gender: + type: array + items: + type: string + ethnic: + type: array + items: + type: string + course: + type: array + items: + type: string + institution: + type: array + items: + type: string + institution_code: + type: array + items: + type: integer + year: + type: array + items: + type: integer + min_year: + type: integer + max_year: + type: integer + cod_offer_location: + type: array + items: + type: integer + name_offer_location: + type: array + items: + type: string + region: + type: array + items: + type: string + uf: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/vacancy' + '404': + description: no data found + + /pnad: + get: + summary: Return the number of people obtained by IBGE in the PNAD research. This route uses the PNAD database listed above + tags: + - PNAD + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: level_of_education,type_of_school + schema: + type: array + items: + type: string + enum: + - ethnic + - type_of_school + - type_of_public_school + - level_of_education + - uf + - region + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: level_of_education:["2","6"],type_of_school:"4" + schema: + type: array + items: + type: object + properties: + ethnic: + type: "array" + items: + type: "string" + enum: ['0', '2', '4', '6', '8', '9'] + type_of_school: + type: "array" + items: + type: "string" + enum: ['2', '4'] + type_of_public_school: + type: "array" + items: + type: "string" + enum: ['2','4','6'] + level_of_education: + type: "array" + items: + type: "string" + enum: ['1','2','3','4','5','6','10','11'] + uf: + type: "array" + items: + type: "string" + enum: ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"] + region: + type: "array" + items: + type: "string" + enum: ['Norte', 'Nordeste', 'Centro-Oeste', 'Sul', 'Sudeste'] + year: + type: "array" + items: + type: "integer" + min_year: + type: "integer" + max_year: + type: "integer" + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/PnadReturn' + '404': + description: no data found + /prouni: + get: + summary: Return the number of people that received a scholarship from PROUNI. This route uses the PROUNI database listed above + tags: + - PROUNI + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: shift,gender + schema: + type: array + items: + type: string + enum: + - shift + - gender + - ethnic + - course + - institution + - scholarship + - uf + - region + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: shift:["Integral","Curso a distância"],gender:"Feminino" + schema: + type: array + items: + type: object + properties: + shift: + type: "string" + enum: ["Curso a distância", "Integral", "Matutino", "Noturno", "Vespertino"] + gender: + type: "string" + enum: ["Masculino", "Feminino"] + ethnic: + type: "string" + enum: ["Amarela", "Branca", "Indígena", "Não Informada", "Parda", "Preta"] + course: + type: "string" + institution: + type: "string" + scholarship: + type: "string" + enum: ["BOLSA INTEGRAL", "BOLSA PARCIAL 50%"] + uf: + type: "array" + items: + type: "string" + enum: ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"] + region: + type: "array" + items: + type: "string" + enum: ['Norte', 'Nordeste', 'Centro-Oeste', 'Sul', 'Sudeste'] + year: + type: "array" + items: + type: "integer" + min_year: + type: "integer" + max_year: + type: "integer" + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ProuniReturn' + '404': + description: no data found + /social_support: + get: + summary: Return the number of quotasholder that had been studying in a federal institution and had some sort of social support + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: shift,gender,ethnic + schema: + type: array + items: + type: string + enum: + - shift + - gender + - ethnic + - course + - institution + - institution_cod + - food_support + - support + - work_support + - courseware_support + - housing_support + - transport_support + - year + - min_year + - max_year + - cod_offer_location + - name_offer_location + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: shift:["Integral","Noturno"],gender:"Feminino" + schema: + type: array + items: + type: object + properties: + shift: + type: array + items: + type: string + gender: + type: array + items: + type: string + ethnic: + type: array + items: + type: string + course: + type: array + items: + type: string + institution: + type: array + items: + type: string + institution_code: + type: array + items: + type: integer + food_support: + type: array + items: + type: string + support: + type: array + items: + type: string + work_support: + type: array + items: + type: string + courseware_support: + type: array + items: + type: string + housing_support: + type: array + items: + type: string + transport_support: + type: array + items: + type: string + year: + type: array + items: + type: integer + min_year: + type: integer + max_year: + type: integer + cod_offer_location: + type: array + items: + type: integer + name_offer_location: + type: array + items: + type: string + + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/SocialSupportReturn' + '404': + description: no data found + /student_loans: + get: + summary: Return the number of quotasholder that had been studying in a federal institution and contracted some sort of loan + tags: + - INEP + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: shift,gender,ethnic + schema: + type: array + items: + type: string + enum: + - cod_offer_location + - name_offer_location + - shift + - gender + - ethnic + - course + - institution + - institution_cod + - refund_fies + - refund_state + - refund_city + - refund_edu_inst + - refund_org + - refund_others + - no_refund_prouni_integral + - no_refund_prouni_partial + - no_refund_state + - no_refund_city + - no_refund_edu_inst + - no_refund_org + - no_refund_others + - year + - min_year + - max_year + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: shift:["Integral","Noturno"],gender:"Feminino" + schema: + type: array + items: + type: object + properties: + shift: + type: array + items: + type: string + gender: + type: array + items: + type: string + ethnic: + type: array + items: + type: string + course: + type: array + items: + type: string + institution: + type: array + items: + type: string + institution_code: + type: array + items: + type: integer + refund_fies: + type: array + items: + type: string + refund_state: + type: array + items: + type: string + refund_city: + type: array + items: + type: string + refund_edu_inst: + type: array + items: + type: string + refund_org: + type: array + items: + type: string + refund_others: + type: array + items: + type: string + no_refund_prouni_integral: + type: array + items: + type: string + no_refund_prouni_partial: + type: array + items: + type: string + no_refund_state: + type: array + items: + type: string + no_refund_city: + type: array + items: + type: string + no_refund_edu_inst: + type: array + items: + type: string + no_refund_org: + type: array + items: + type: string + no_refund_others: + type: array + items: + type: string + year: + type: array + items: + type: integer + min_year: + type: integer + max_year: + type: integer + cod_offer_location: + type: array + items: + type: integer + name_offer_location: + type: array + items: + type: string + region: + type: array + items: + type: string + uf: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/InepLoanReturn' + '404': + description: no data found + +# /ibge_census: +# get: +# summary: Return the number of people obtained by IBGE in the last census. This route uses the IBGE data listed above +# tags: +# - IBGE - Census +# parameters: +# - name: dims +# in: query +# description: Group data using a metric parameter +# allowReserved: true +# required: false +# explode: false +# style: form +# example: ethnic,gender +# schema: +# type: array +# items: +# type: string +# enum: +# - ethnic +# - gender +# - religion +# - income_range +# - age +# - age_greater_than +# - age_lesser_than +# - highest_education +# - school_daycare +# - work_status +# - education_level +# - ocupation_position_and_category +# - home_status +# - work_condition +# - mensal_home_income_range +# - relation_homeowner +# - name: filter +# in: query +# description: Filter data +# allowReserved: true +# required: false +# explode: false +# style: form +# example: ethnic:["2","6"],gender:"1" +# schema: +# type: array +# items: +# type: object +# properties: +# ethnic: +# type: "array" +# items: +# type: "string" +# enum: ['1', '2', '3', '4', '5', '9'] +# gender: +# type: "array" +# items: +# type: "string" +# enum: ['1', '2'] +# religion: +# type: "array" +# items: +# type: "string" +# enum: ['0', '1', '2', '110', '111', '112', '120', '130', '140', '149', '199', '210', '219', '220', '221', '222', '223', '224', '225', '229', '230', '231', '232', '239', '240', '241', '242', '243', '244', '245', '249', '250', '251', '259', '260', '261', '262', '269', '270', '279', '280', '289', '300', '310', '311', '312', '319', '320', '329', '330', '339', '340', '349', '350', '359', '360', '369', '370', '379', '380', '389', '390', '399', '400', '401', '409', '420', '429', '430', '439', '440', '449', '450', '451', '452', '453', '454', '455', '460', '469', '470', '479', '480', '489', '490', '492', '499', '510', '519', '520', '529', '530', '590', '599', '610', '619', '620', '629', '630', '639', '640', '641', '649', '710', '711', '719', '740', '741', '749', '750', '751', '752', '753', '754', '755', '759', '760', '761', '762', '763', '764', '765', '766', '790', '791', '792', '793', '799', '810', '811', '819', '820', '821', '829', '830', '831', '832', '834', '839', '850', '890', '891', '892', '893', '894', '895', '896', '990', '999', ] +# income_range: +# type: "array" +# items: +# type: "number" +# age: +# type: "array" +# items: +# type: "integer" +# age_greater_than: +# type: "array" +# items: +# type: "integer" +# age_lesser_than: +# type: "array" +# items: +# type: "integer" +# highest_education: +# type: "array" +# items: +# type: "string" +# enum: [null, '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14'] +# school_daycare: +# type: "array" +# items: +# type: "string" +# enum: ['1', '2','3', '4'] +# work_status: +# type: "array" +# items: +# type: "string" +# enum: [null, '1', '2'] +# education_level: +# type: "array" +# items: +# type: "string" +# enum: ['1', '2', '3', '4', '5'] +# ocupation_position_and_category: +# type: "array" +# items: +# type: "string" +# enum: ['1', '2'] +# home_status: +# type: "array" +# items: +# type: "string" +# enum: ['1', '2'] +# work_condition: +# type: "array" +# items: +# type: "string" +# enum: [null, '1', '2'] +# mensal_home_income_range: +# type: "array" +# items: +# type: "number" +# relation_homeowner: +# type: "array" +# items: +# type: "string" +# enum: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'] +# +# responses: +# '200': +# description: successful operation +# content: +# application/json: +# schema: +# $ref: '#/components/schemas/IBGECensusReturn' +# '404': +# description: no data found + +# /cad_unico: +# get: +# summary: Return the number of people and families from that belongs to 'terreiro communities' obtained by CadÚnico. This route uses the IBGE data listed above +# tags: +# - CadÚnico +# parameters: +# - name: dims +# in: query +# description: Group data using a metric parameter +# allowReserved: true +# required: false +# explode: false +# style: form +# example: year,home_type +# schema: +# type: array +# items: +# type: string +# enum: +# - year +# - per_capita_income +# - home_type +# - home_location +# - education_families +# - education_families_level +# - education_families_conclude +# - name: filter +# in: query +# description: Filter data +# allowReserved: true +# required: false +# explode: false +# style: form +# example: ethnic:["2","6"],gender:"1" +# schema: +# type: array +# items: +# type: object +# properties: +# year: +# type: "array" +# items: +# type: "string" +# enum: ['2012', '2013', '2014', '2015', '2016'] +# per_capita_income: +# type: "array" +# items: +# type: "string" +# home_type: +# type: "array" +# items: +# type: "string" +# enum: [null, '1','2','3'] +# home_location: +# type: 'array' +# items: +# type: "number" +# education_families_conclude: +# type: "array" +# items: +# type: "string" +# enum: [null, '1', '2'] +# education_families: +# type: 'array' +# items: +# type: "string" +# enum: [null, '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15'] +# education_families_level: +# type: 'array' +# items: +# type: "string" +# enum: [null,'1','2','3','4','5','6','7','8','9','10'] + +# responses: +# '200': +# description: successful operation +# content: +# application/json: +# schema: +# $ref: '#/components/schemas/CadUnicoReturn' +# '404': +# description: no data found + + /african_culture: + get: + summary: Return the type of house and location of the houses that belongs to 'terreiro communities' obtained by CadÚnico. This route uses the IBGE data listed above + tags: + - CadÚnico + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,home_type + schema: + type: array + items: + type: string + enum: + - year + - cod_local_home + - home_type + - home_location + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: ethnic:["2","6"],gender:"1" + schema: + type: array + items: + type: object + properties: + year: + type: "array" + items: + type: "string" + enum: ['2012', '2013', '2014', '2015', '2016','2017'] + cod_local_home: + type: "array" + items: + type: "string" + enum: ['1','2'] + home_type: + type: "array" + items: + type: "string" + enum: ['1','2','3'] + home_location: + type: "array" + items: + type: "string" + enum: ['1301902','1303809', '1304237','1500107','1502806','1503705','1503903','1504604','1504901','1505205'] + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/AfricanCulture' + '404': + description: no data found + + /african_rights: + get: + summary: Return the education level and number of families that belongs to 'terreiro communities' obtained by CadÚnico. This route uses the IBGE data listed above + tags: + - CadÚnico + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,home_type + schema: + type: array + items: + type: string + enum: + - year + - education_families_conclude + - education_families_level + - education_families + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: ethnic:["2","6"],gender:"1" + schema: + type: array + items: + type: object + properties: + year: + type: "array" + items: + type: "string" + enum: ['2012', '2013', '2014', '2015', '2016','2017'] + education_families_conclude: + type: "array" + items: + type: "string" + enum: ['1','2','null'] + education_families_level: + type: "array" + items: + type: "string" + enum: ['1','2','3','4','5','6','7','8','9','null'] + education_families: + type: "array" + items: + type: "string" + enum: ['3','4','5','6','7','8','9','12','13','null'] + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/AfricanRights' + '404': + description: no data found + + /african_sustentability: + get: + summary: Return the average per capita income from families that belongs to 'terreiro communities' obtained by CadÚnico. This route uses the IBGE data listed above + tags: + - CadÚnico + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,home_type + schema: + type: array + items: + type: string + enum: + - year + - family_type + - per_capita_income + + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: ethnic:["2","6"],gender:"1" + schema: + type: array + items: + type: object + properties: + year: + type: "array" + items: + type: "string" + enum: ['2012', '2013', '2014', '2015', '2016','2017'] + vlr_renda_media_fam: + type: "array" + items: + type: "number" + minimum: 0 + maximum: 3000 + + + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/AfricanSustentability' + '404': + description: no data found + + /eixo_2: + get: + summary: Return the infraestructure and life quality information about quilombola families obtained by CadÚnico. This route uses the CadUnico data listed above + tags: + - CadÚnico + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,home_type + schema: + type: array + items: + type: string + enum: + - year + - family_type + - cod_local_home + - cod_home_lighting + - cod_home_trash_destiny + - cod_home_watter_supply + - cod_sanitary_dump + - home_type + - home_location + - uf + - region + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: ethnic:["2","6"],gender:"1" + schema: + type: array + items: + type: object + properties: + year: + type: "array" + items: + type: "string" + enum: ['2012', '2013', '2014', '2015', '2016','2017'] + family_type: + type: "array" + items: + type: "string" + enum: ['201','202','203','204','205','301','302','303','304','305','306','101','0','null'] + cod_local_home: + type: "array" + items: + type: "string" + enum: ['1','2,','NA','null'] + cod_home_lighting: + type: "array" + items: + type: "string" + enum: ['1','2','3','4','5','6','NA','null'] + cod_home_trash_destiny: + type: "array" + items: + type: "string" + enum: ['1','2','3','4','5','6','null','NA'] + cod_home_watter_supply: + type: "array" + items: + type: "string" + enum: ['1','2','3','4','null','NA'] + home_type: + type: "array" + items: + type: "string" + enum: ['1', '2', '3', 'null'] + uf: + type: "array" + items: + type: "string" + enum: ['RS', 'BA', 'PA', 'PR', 'GO', 'MA', 'AL','SE', 'MG', 'PE', 'PI','RN', 'ES', 'PB', 'CE', 'SP', 'SC', 'MS', 'MT', 'AM', 'AP', 'RO', 'TO', 'RJ', 'AC','DF','RR'] + region: + type: "array" + items: + type: "string" + enum: ['norte','nordeste','sul','centro-oeste','sudeste'] + cod_escoa_sanitario_domic_fam: + type: "array" + items: + type: "string" + enum: ['1','2','3','4','5','6','null','NA'] + + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Eixo2' + '404': + description: no data found + + /eixo_3: + get: + summary: Return the local development and productive inclusion about quilombola families obtained by CadÚnico. This route uses the CadUnico data listed above + tags: + - CadÚnico + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,home_type + schema: + type: array + items: + type: string + enum: + - year + - family_type + - cod_home_bolsa_familia + - cod_agriculture_job + - per_capita_income + - home_location + - uf + - region + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: ethnic:["2","6"],gender:"1" + schema: + type: array + items: + type: object + properties: + year: + type: "array" + items: + type: "string" + enum: ['2012', '2013', '2014', '2015', '2016','2017'] + family_type: + type: "array" + items: + type: "string" + enum: ['201','202','203','204','205','301','302','303','304','305','306','101','0','null'] + cod_home_bolsa_familia: + type: "array" + items: + type: "string" + enum: ['0','1','null'] + cod_agriculture_job: + type: "array" + items: + type: "string" + enum: ['0','1','null','NA'] + per_capita_income: + type: "array" + items: + type: "string" + minimum: 0 + maximum: 2800 + home_location: + type: "array" + items: + type: "string" + minimum: 1100015 + maximum: 5300108 + uf: + type: "array" + items: + type: "string" + enum: ['RS', 'BA', 'PA', 'PR', 'GO', 'MA', 'AL','SE', 'MG', 'PE', 'PI','RN', 'ES', 'PB', 'CE', 'SP', 'SC', 'MS', 'MT', 'AM', 'AP', 'RO', 'TO', 'RJ', 'AC','DF','RR'] + region: + type: "array" + items: + type: "string" + enum: ['norte','nordeste','sul','centro-oeste','sudeste'] + + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Eixo3' + '404': + description: no data found + + /eixo_4: + get: + summary: Return the rights and citizenship information about quilombola families obtained by CadÚnico. This route uses the CadUnico data listed above + tags: + - CadÚnico + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,home_type + schema: + type: array + items: + type: string + enum: + - year + - cod_local_home + - age + - education_families_conclude + - education_families_level + - education_families + - uf + - region + - gender + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: ethnic:["2","6"],gender:"1" + schema: + type: array + items: + type: object + properties: + year: + type: "array" + items: + type: "string" + enum: ['2012', '2013', '2014', '2015', '2016','2017'] + age: + type: "array" + items: + type: "string" + minimum: 0 + maximum: 128 + education_families_conclude: + type: "array" + items: + type: "string" + enum: ['1','2','null'] + education_families_level: + type: "array" + items: + type: "string" + enum: ['1','1','3','4','5','6','7','8','9','10'] + education_families: + type: "array" + items: + type: "string" + enum: ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','null'] + uf: + type: "array" + items: + type: "string" + enum: ['RS', 'BA', 'PA', 'PR', 'GO', 'MA', 'AL','SE', 'MG', 'PE', 'PI','RN', 'ES', 'PB', 'CE', 'SP', 'SC', 'MS', 'MT', 'AM', 'AP', 'RO', 'TO', 'RJ', 'AC','DF','RR'] + region: + type: "array" + items: + type: "string" + enum: ['norte','nordeste','sul','centro-oeste','sudeste'] + gender: + type: "array" + items: + type: "string" + enum: ['1','2','null'] + + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Eixo4' + '404': + description: no data found + + /quilombola_metrics: + get: + summary: Return the useful metrics for quilombola families obtained by CadÚnico, like the maximum, minimum and average income they have, per year. This route uses the CadUnico data listed above + tags: + - CadÚnico + parameters: + - name: dims + in: query + description: Group data using a metric parameter + allowReserved: true + required: false + explode: false + style: form + example: year,home_type + schema: + type: array + items: + type: string + enum: + - year + + - name: filter + in: query + description: Filter data + allowReserved: true + required: false + explode: false + style: form + example: year:"2016" + schema: + type: array + items: + type: object + properties: + year: + type: "array" + items: + type: "string" + enum: ['2012', '2013', '2014', '2015', '2016','2017'] + + + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/metrics' + '404': + description: no data found + +components: + schemas: + + Eixo2: + type: object + required: ['total'] + description: | + This model represents the return possibilities in quilombola_eixo_2 queries + properties: + total: + type: "number" + ano_pesquisa: + type: "number" + ind_parc_mds_fam: + type: "number" + cod_local_domic_fam: + type: "number" + cod_iluminacao_domic_fam: + type: "number" + cod_destino_lixo_domic_fam: + type: "number" + cod_abaste_agua_domic_fam: + type: "number" + cod_especie_domic_fam: + type: "number" + uf: + type: "string" + region: + type: "string" + cod_escoa_sanitario_domic_fam: + type: "number" + Eixo3: + type: object + required: ['total'] + description: | + This model represents the return possibilities in quilombola_eixo_3 queries + properties: + total: + type: "number" + ano_pesquisa: + type: "number" + ind_parc_mds_fam: + type: "number" + marc_pbf: + type: "number" + ind_familia_quilombola_fam: + type: "number" + cod_agricultura_trab_memb: + type: "number" + vlr_renda_media_fam: + type: "number" + cd_ibge: + type: "number" + uf: + type: "string" + region: + type: "string" + cod_escoa_sanitario_domic_fam: + type: "number" + + Eixo4: + type: object + required: ['total'] + description: | + This model represents the return possibilities in quilombola_eixo_3 queries + properties: + total: + type: "number" + ano_pesquisa: + type: "number" + idade: + type: "number" + cod_concluiu_frequentou_memb: + type: "string" + cod_ano_serie_frequentou_memb: + type: "string" + cod_curso_frequentou_pessoa_memb: + type: "string" + uf: + type: "string" + region: + type: "string" + genero: + type: "string" + + metrics: + type: object + required: ['total'] + description: | + This model represents the return possibilities in quilombola_metrics queries + properties: + ano_pesquisa: + type: "number" + + AfricanSustentability: + type: object + required: ['total'] + description: | + This model represents the return possibilities in african_rights queries + properties: + total: + type: "number" + ano_pesquisa: + type: "number" + vlr_renda_media_fam: + type: "number" + + + AfricanRights: + type: object + required: ['total'] + description: | + This model represents the return possibilities in african_rights queries + properties: + total: + type: "number" + ano_pesquisa: + type: "number" + cod_concluiu_frequentou_memb: + type: "string" + cod_ano_serie_frequentou_memb: + type: "string" + cod_curso_frequentou_pessoa_memb: + type: "string" + + AfricanCulture: + type: object + required: ['total'] + description: | + This model represents the return possibilities in african_culture queries + properties: + total: + type: "number" + ano_pesquisa: + type: "number" + cod_local_domic_fam: + type: "string" + cod_especie_domic_fam: + type: "string" + cd_ibge: + type: "string" + +# CadUnicoReturn: +# type: object +# required: ['total'] +# description: | +# This model represents the return possibilities in CadUnico queries +# properties: +# total: +# type: "number" +# ano_pesquisa: +# type: "number" +# vlr_renda_media_fam: +# type: "number" +# cod_especie_domic_fam: +# type: "string" +# cd_ibge: +# type: "string" +# cod_concluiu_frequentou_memb: +# type: "string" +# cod_ano_serie_frequentou_memb: +# type: "string" +# cod_curso_frequentou_pessoa_memb: +# type: "string" + + course: + type: object + required: ['total'] + description: | + This model represents the return possibilities in course queries + properties: + total: + type: "number" + year: + type: "number" + uf: + type: "string" + courseFIES: + type: object + required: ['total'] + description: | + This model represents the return possibilities in courseFIES queries + properties: + total: + type: "number" + year: + type: "number" + uf: + type: "string" + coursePROUNI: + type: object + required: ['total'] + description: | + This model represents the return possibilities in course queries + properties: + total: + type: "number" + year: + type: "number" + uf: + type: "string" + institution: + type: object + required: ['total'] + description: | + This model represents the return possibilities in institution queries + properties: + total: + type: "number" + year: + type: "number" + uf: + type: "string" + + institutionFIES: + type: object + required: ['total'] + description: | + This model represents the return possibilities in institutionFIES queries + properties: + total: + type: "number" + year: + type: "number" + + institutionPROUNI: + type: object + required: ['total'] + description: | + This model represents the return possibilities in institutionPROUNI queries + properties: + total: + type: "number" + year: + type: "number" + + + institutionPrivate: + type: object + required: ['total'] + description: | + This model represents the return possibilities in institution queries + properties: + total: + type: "number" + year: + type: "number" + uf: + type: "string" + + ibge_code: + type: object + required: ['total'] + description: | + This model represents the return possibilities in ibge_code queries + properties: + no_cidade: + type: "string" + co_cidade: + type: "number" + sgl_estado: + type: "string" + +# IBGECensusReturn: +# type: object +# required: ['total'] +# description: | +# This model represents the return possibilities in IBGE Census queries +# properties: +# total: +# type: "number" +# co_cor_raca: +# type: "string" +## co_sexo: +# type: "string" +# co_religiao: +# type: "string" +# nu_sal_min_todos_trabalhos: +# type: "number" +# nu_idade_calculada_anos: +# type: "number" +# co_curso_mais_elevado_freq: +# type: "string" + # co_freq_escola_creche: +# type: "string" +# co_condicao_atividade_semana_ref: +# type: "string" +# co_nivel_instrucao: +# type: "string" +# co_posicao_na_ocupacao_e_categoria_do_emprego: +# type: "string" +# co_situacao_dom: +# type: "string" +# co_condicao_ocupacao_semana_ref: +# type: "string" +# vl_rendimneto_mensal_domicilio_sal_min_per_capita: +# type: "number" +# co_relacao_responsavel_dom: +# type: "string" + + BasicInepReturn: + type: object + required: ['result'] + description: | + This model represents the return possibilities in INEP queries when location information is not needed. + Note that there will always exists the total and no_ano_pesquisa keys. + All the other keys are optional and appear if the dims paramter is used. + properties: + result: + type: array + items: + type: object + required: ['total', 'no_ano_pesquisa'] + properties: + total: + type: "number" + no_ano_pesquisa: + type: "integer" + format: "int32" + ds_turno_aluno: + type: "string" + enum: ['Integral', 'Matutino', 'Noturno', 'Não aplicável', 'Vespertino'] + ds_sexo_aluno: + type: "string" + enum: ['Masculino', 'Feminino'] + ds_cor_raca_aluno: + type: "string" + enum: ['Aluno não quis declarar cor/raça', 'Amarela', 'Branca', 'Indígena', 'Parda', 'Preta'] + no_curso: + type: "string" + no_ies: + type: "string" + co_ies: + type: "integer" + co_local_oferta: + type: "integer" + no_local_oferta: + type: "string" + BasicInepReturnWithLocationInfo: + type: object + required: ['result'] + description: | + This model represents the return possibilities in INEP queries when location information is needed. + Note that there will always exists the total and no_ano_pesquisa keys. + All the other keys are optional and appear if the dims paramter is used. + properties: + result: + type: array + items: + type: object + required: ['total', 'no_ano_pesquisa'] + properties: + total: + type: "number" + no_ano_pesquisa: + type: "integer" + format: "int32" + ds_turno_aluno: + type: "string" + enum: ['Integral', 'Matutino', 'Noturno', 'Não aplicável', 'Vespertino'] + ds_sexo_aluno: + type: "string" + enum: ['Masculino', 'Feminino'] + ds_cor_raca_aluno: + type: "string" + enum: ['Aluno não quis declarar cor/raça', 'Amarela', 'Branca', 'Indígena', 'Parda', 'Preta'] + no_curso: + type: "string" + no_ies: + type: "string" + co_ies: + type: "integer" + co_local_oferta: + type: "integer" + no_local_oferta: + type: "string" + region: + type: "string" + enum: ['Norte', 'Nordeste', 'Centro-Oeste', 'Sul', 'Sudeste'] + uf: + type: "string" + enum: ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"] + + vacancy: + type: object + required: ['total'] + description: | + This model represents the return possibilities in vacancy queries + properties: + total: + type: "number" + uf: + type: "string" + region: + type: "string" + year: + type: "number" + cod_ies: + type: "integer" + campus: + type: "string" + curso: + type: "string" + turno: + type: "string" + nome_ies: + type: "string" + cod_especie_domic_fam: + type: "number" + total_vagas_ampla_concorrencia_nao_pcd: + type: "number" + total_vagas_ampla_concorrencia_pcd: + type: "number" + total_vagas_cotas_renda_baixa_ppi_nao_pcd: + type: "number" + total_vagas_cotas_renda_baixa_ppi_pcd: + type: "number" + total_vagas_cotas_renda_baixa_outros_nao_pcd: + type: "number" + total_vagas_cotas_renda_baixa_outros_pcd: + type: "number" + total_vagas_cotas_renda_alta_ppi_nao_pcd: + type: "number" + total_vagas_cotas_renda_alta_ppi_pcd: + type: "number" + total_vagas_cotas_renda_alta_outros_nao_pcd: + type: "number" + total_vagas_cotas_renda_alta_outros_pcd: + type: "number" + total_total_pcd: + type: "number" + + + + FiesReturn: + type: object + required: ['result'] + description: | + This model represents the return possibilities in FIES queries. + Note that there will always exists the total and nu_ano keys. + All the other keys are optional and appear if the dims paramter is used. + properties: + result: + type: array + items: + type: object + required: ['total', 'nu_ano'] + properties: + total: + type: "number" + nu_ano: + type: "integer" + format: "int32" + ds_sexo: + type: "string" + enum: ['Masculino', 'Feminino'] + ds_raca_cor: + type: "string" + enum: ['Amarelo','Branco','Negro','Pardo','Índio'] + ds_curso: + type: "string" + no_ies: + type: "string" + co_ies: + type: "integer" + no_campus: + type: "string" + nu_percent_solicitado_financ: + type: integer + enum: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 ] + tp_fianca: + type: "string" + enum: ["F", "N", "S"] + description: | + Meanings of each letter: + + F - Fundo de Garantia de Operações de Crédito Educativo – FGEDUC + + N - Normal/Convencional + + S - Solidária + region: + type: "string" + enum: ['Norte', 'Nordeste', 'Centro-Oeste', 'Sul', 'Sudeste'] + uf: + type: "string" + enum: ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"] + PnadReturn: + type: object + required: ['result'] + description: | + This model represents the return possibilities in PNAD queries. + Note that there will always exists the total and nu_ano_referencia keys. + All the other keys are optional and appear if the dims paramter is used. + properties: + result: + type: array + items: + type: object + required: ['total', 'nu_ano_referencia'] + properties: + total: + type: "number" + nu_ano_referencia: + type: "integer" + format: "int32" + co_cor_raca: + type: "string" + enum: ['0', '2', '4', '6', '8', '9'] + co_rede_ensino: + type: "string" + enum: ['2', '4'] + co_area_rede_publica_ensino: + type: "string" + enum: ['2','4','6'] + co_curso: + type: "string" + enum: ['1','2','3','4','5','6','10','11'] + uf: + type: "string" + enum: ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"] + region: + type: "string" + enum: ['Norte', 'Nordeste', 'Centro-Oeste', 'Sul', 'Sudeste'] + ProuniReturn: + type: object + required: ['result'] + description: | + This model represents the return possibilities in PROUNI queries. + Note that there will always exists the total and ano_concessao_bolsa keys. + All the other keys are optional and appear if the dims paramter is used. + properties: + result: + type: array + items: + type: object + required: ['total', 'ano_concessao_bolsa'] + properties: + total: + type: "number" + ano_concessao_bolsa: + type: "integer" + format: "int32" + nome_turno_curso_bolsa: + # shift + type: "string" + enum: ['Curso a distância', 'Integral', 'Matutino', 'Noturno', 'Vespertino'] + sexo_beneficiario_bolsa: + # gender + type: "string" + enum: ["Masculino", "Feminino"] + raca_beneficiario_bolsa: + # ethnic + type: "string" + enum: ['Amarela', 'Branca', 'Indígena', 'Não Informada', 'Parda', 'Preta'] + nome_curso_bolsa: + # course + type: "string" + nome_ies_bolsa: + # institution + type: "string" + tipo_bolsa: + # scholarship + type: "string" + enum: ["BOLSA INTEGRAL", "BOLSA PARCIAL 50%"] + sigla_uf_beneficiario_bolsa: + # uf + type: "string" + enum: ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"] + regiao_beneficiario_bolsa: + # region + type: "string" + enum: ['Norte', 'Nordeste', 'Centro-Oeste', 'Sul', 'Sudeste'] + SocialSupportReturn: + type: object + required: ['result'] + description: | + This model represents the return possibilities in INEP queries when location information is not needed. + Note that there will always exists the total and no_ano_pesquisa keys. + All the other keys are optional and appear if the dims paramter is used. + properties: + result: + type: array + items: + type: object + required: ['total', 'no_ano_pesquisa'] + properties: + total: + type: "number" + no_ano_pesquisa: + type: "integer" + format: "int32" + ds_turno_aluno: + type: "string" + enum: ['Integral', 'Matutino', 'Noturno', 'Não aplicável', 'Vespertino'] + ds_sexo_aluno: + type: "string" + enum: ['Masculino', 'Feminino'] + ds_cor_raca_aluno: + type: "string" + enum: ['Aluno não quis declarar cor/raça', 'Amarela', 'Branca', 'Indígena', 'Parda', 'Preta'] + no_curso: + type: "string" + no_ies: + type: "string" + co_ies: + type: "integer" + co_local_oferta: + type: "integer" + no_local_oferta: + type: "string" + in_apoio_alimentacao: + type: "string" + enum: ["0", "1"] + in_apoio_bolsa_pemanencia: + type: "string" + enum: ["0", "1"] + in_apoio_bolsa_trabalho: + type: "string" + enum: ["0", "1"] + in_apoio_material_didatico: + type: "string" + enum: ["0", "1"] + in_apoio_moradia: + type: "string" + enum: ["0", "1"] + in_apoio_transporte: + type: "string" + enum: ["0", "1"] + InepLoanReturn: + type: object + required: ['result'] + description: | + This model represents the return possibilities in INEP queries when location information is not needed. + Note that there will always exists the total and no_ano_pesquisa keys. + All the other keys are optional and appear if the dims paramter is used. + properties: + result: + type: array + items: + type: object + required: ['total', 'no_ano_pesquisa'] + properties: + total: + type: "number" + no_ano_pesquisa: + type: "integer" + format: "int32" + ds_turno_aluno: + type: "string" + enum: ['Integral', 'Matutino', 'Noturno', 'Não aplicável', 'Vespertino'] + ds_sexo_aluno: + type: "string" + enum: ['Masculino', 'Feminino'] + ds_cor_raca_aluno: + type: "string" + enum: ['Aluno não quis declarar cor/raça', 'Amarela', 'Branca', 'Indígena', 'Parda', 'Preta'] + no_curso: + type: "string" + no_ies: + type: "string" + co_ies: + type: "integer" + refund_fies: + type: "string" + enum: ["0", "1"] + refund_state: + type: "string" + enum: ["0", "1"] + refund_city: + type: "string" + enum: ["0", "1"] + refund_edu_inst: + type: "string" + enum: ["0", "1"] + refund_org: + type: "string" + enum: ["0", "1"] + refund_others: + type: "string" + enum: ["0", "1"] + no_refund_prouni_integral: + type: "string" + enum: ["0", "1"] + no_refund_prouni_partial: + type: "string" + enum: ["0", "1"] + no_refund_state: + type: "string" + enum: ["0", "1"] + no_refund_city: + type: "string" + enum: ["0", "1"] + no_refund_edu_inst: + type: "string" + enum: ["0", "1"] + no_refund_org: + type: "string" + enum: ["0", "1"] + no_refund_others: + type: "string" + enum: ["0", "1"] + co_local_oferta: + type: "integer" + no_local_oferta: + type: "string" \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml deleted file mode 100644 index 2cfd1adfd30e95fcc86afa8f389450e666b68f85..0000000000000000000000000000000000000000 --- a/.gitlab-ci.yml +++ /dev/null @@ -1,24 +0,0 @@ -stages: - - test - -services: - - mongo:latest - -variables: - MONGO_URI: 'mongodb://mongo/app_name' - NODE_ENV: 'test' - -before_script: - - npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint - - npm install - -run_tests: - stage: test - script: - - ping -W1 -c1 mongo - - mv config.json.example config.json - - sed -i -e 's/false/true/g' config.json - - gulp build - - gulp test - tags: - - node diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d3dbb013cec3a98716cbe86e5644659c987e7c8..ad2d90ae546c79c8e7cbba04bfc4125f841bb2dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 2019-07-03 +### Changed +- Remove mongoose dependency so it can be used in SMPPIR + ## 1.9.0 - 2018-11-24 ## Changed - Fix school infrastructure results when partial or needed schools query return empty diff --git a/Consultas_SQL/Atv-Extra/Atividade_extra.sql b/Consultas_SQL/Atv-Extra/Atividade_extra.sql new file mode 100644 index 0000000000000000000000000000000000000000..f20f7d92bf0ec1fde93bf0ee92fb3a040e868986 --- /dev/null +++ b/Consultas_SQL/Atv-Extra/Atividade_extra.sql @@ -0,0 +1,15 @@ +SELECT + aluno_ens_superior.ano_censo, + COUNT(*) AS total +FROM + aluno_ens_superior +WHERE + (reserva_vagas = 1) AND + (bolsa_extensao = 1) AND + (cod_categoria_administrativa IN (1)) AND + (cod_organizacao_academica IN (1, 4, 5)) +GROUP BY + aluno_ens_superior.ano_censo +ORDER BY + aluno_ens_superior.ano_censo ASC +; diff --git a/Consultas_SQL/Atv-Extra/Atividade_extra_sem_order.sql b/Consultas_SQL/Atv-Extra/Atividade_extra_sem_order.sql new file mode 100644 index 0000000000000000000000000000000000000000..cbb91d2f65f9c6edeffad7aa2b4972cbdb21388d --- /dev/null +++ b/Consultas_SQL/Atv-Extra/Atividade_extra_sem_order.sql @@ -0,0 +1,13 @@ +SELECT + aluno_ens_superior.ano_censo, + COUNT(*) AS total +FROM + aluno_ens_superior +WHERE + (reserva_vagas = 1) AND + (bolsa_extensao = 1) AND + (cod_categoria_administrativa IN (1)) AND + (cod_organizacao_academica IN (1, 4, 5)) +GROUP BY + aluno_ens_superior.ano_censo +; diff --git a/Consultas_SQL/Atv-Extra/Atividade_extra_sem_order_troca_count.sql b/Consultas_SQL/Atv-Extra/Atividade_extra_sem_order_troca_count.sql new file mode 100644 index 0000000000000000000000000000000000000000..9df0b448bbc3bbf326dfc153d9ef3cdc8daa758a --- /dev/null +++ b/Consultas_SQL/Atv-Extra/Atividade_extra_sem_order_troca_count.sql @@ -0,0 +1,13 @@ +SELECT + aluno_ens_superior.ano_censo, + COUNT(cod_aluno) AS total +FROM + aluno_ens_superior +WHERE + (reserva_vagas = 1) AND + (bolsa_extensao = 1) AND + (cod_categoria_administrativa IN (1)) AND + (cod_organizacao_academica IN (1, 4, 5)) +GROUP BY + aluno_ens_superior.ano_censo +; diff --git a/Consultas_SQL/Atv-Extra/Atividade_extra_trocando_count.sql b/Consultas_SQL/Atv-Extra/Atividade_extra_trocando_count.sql new file mode 100644 index 0000000000000000000000000000000000000000..8d81f475e95cd686b8fc607498d8519bbe3c8e97 --- /dev/null +++ b/Consultas_SQL/Atv-Extra/Atividade_extra_trocando_count.sql @@ -0,0 +1,15 @@ +SELECT + aluno_ens_superior.ano_censo, + COUNT(cod_aluno) AS total +FROM + aluno_ens_superior +WHERE + (reserva_vagas = 1) AND + (bolsa_extensao = 1) AND + (cod_categoria_administrativa IN (1)) AND + (cod_organizacao_academica IN (1, 4, 5)) +GROUP BY + aluno_ens_superior.ano_censo +ORDER BY + aluno_ens_superior.ano_censo ASC +; diff --git a/Consultas_SQL/Evasores/Evasores.sql b/Consultas_SQL/Evasores/Evasores.sql new file mode 100644 index 0000000000000000000000000000000000000000..12f6a4def5add8145798238b08ec01ec021ae4cf --- /dev/null +++ b/Consultas_SQL/Evasores/Evasores.sql @@ -0,0 +1,19 @@ +SELECT + aluno_ens_superior.ano_censo, + COUNT(*) AS total +FROM + aluno_ens_superior + INNER JOIN + ies_ens_superior + ON (aluno_ens_superior.cod_ies = ies_ens_superior.cod_ies) +WHERE + (aluno_ens_superior.cod_aluno_situacao IN (4,5,7)) AND + (aluno_ens_superior.reserva_vagas = 1) AND + (aluno_ens_superior.cod_categoria_administrativa IN (1)) AND + (aluno_ens_superior.cod_organizacao_academica IN (1, 4, 5)) AND + (aluno_ens_superior.ano_censo = ies_ens_superior.ano_censo) +GROUP BY + aluno_ens_superior.ano_censo +ORDER BY + aluno_ens_superior.ano_censo ASC +; diff --git a/Consultas_SQL/Evasores/Evasores_sem_order.sql b/Consultas_SQL/Evasores/Evasores_sem_order.sql new file mode 100644 index 0000000000000000000000000000000000000000..d7a2d6cfc4068fd64aee9a44860db6dc77f4ea5e --- /dev/null +++ b/Consultas_SQL/Evasores/Evasores_sem_order.sql @@ -0,0 +1,17 @@ +SELECT + aluno_ens_superior.ano_censo, + COUNT(*) AS total +FROM + aluno_ens_superior + INNER JOIN + ies_ens_superior + ON (aluno_ens_superior.cod_ies = ies_ens_superior.cod_ies) +WHERE + (aluno_ens_superior.cod_aluno_situacao IN (4,5,7)) AND + (aluno_ens_superior.reserva_vagas = 1) AND + (aluno_ens_superior.cod_categoria_administrativa IN (1)) AND + (aluno_ens_superior.cod_organizacao_academica IN (1, 4, 5)) AND + (aluno_ens_superior.ano_censo = ies_ens_superior.ano_censo) +GROUP BY + aluno_ens_superior.ano_censo +; diff --git a/Consultas_SQL/Evasores/Evasores_sem_order_troca_count.sql b/Consultas_SQL/Evasores/Evasores_sem_order_troca_count.sql new file mode 100644 index 0000000000000000000000000000000000000000..73f8a48a95bfd9bf3d5c0825fc985cc8248ded88 --- /dev/null +++ b/Consultas_SQL/Evasores/Evasores_sem_order_troca_count.sql @@ -0,0 +1,17 @@ +SELECT + aluno_ens_superior.ano_censo, + COUNT(cod_aluno) AS total +FROM + aluno_ens_superior + INNER JOIN + ies_ens_superior + ON (aluno_ens_superior.cod_ies = ies_ens_superior.cod_ies) +WHERE + (aluno_ens_superior.cod_aluno_situacao IN (4,5,7)) AND + (aluno_ens_superior.reserva_vagas = 1) AND + (aluno_ens_superior.cod_categoria_administrativa IN (1)) AND + (aluno_ens_superior.cod_organizacao_academica IN (1, 4, 5)) AND + (aluno_ens_superior.ano_censo = ies_ens_superior.ano_censo) +GROUP BY + aluno_ens_superior.ano_censo +; diff --git a/Consultas_SQL/Evasores/Evasores_trocando_count.sql b/Consultas_SQL/Evasores/Evasores_trocando_count.sql new file mode 100644 index 0000000000000000000000000000000000000000..9c5621e2351cf208cf65364e4f080a8a011b5a0c --- /dev/null +++ b/Consultas_SQL/Evasores/Evasores_trocando_count.sql @@ -0,0 +1,19 @@ +SELECT + aluno_ens_superior.ano_censo, + COUNT(cod_aluno) AS total +FROM + aluno_ens_superior + INNER JOIN + ies_ens_superior + ON (aluno_ens_superior.cod_ies = ies_ens_superior.cod_ies) +WHERE + (aluno_ens_superior.cod_aluno_situacao IN (4,5,7)) AND + (aluno_ens_superior.reserva_vagas = 1) AND + (aluno_ens_superior.cod_categoria_administrativa IN (1)) AND + (aluno_ens_superior.cod_organizacao_academica IN (1, 4, 5)) AND + (aluno_ens_superior.ano_censo = ies_ens_superior.ano_censo) +GROUP BY + aluno_ens_superior.ano_censo +ORDER BY + aluno_ens_superior.ano_censo ASC +; diff --git a/Consultas_SQL/FIES/fies.sql b/Consultas_SQL/FIES/fies.sql new file mode 100644 index 0000000000000000000000000000000000000000..dd0cf8d3624e0e50855eb3860c00354ec4718716 --- /dev/null +++ b/Consultas_SQL/FIES/fies.sql @@ -0,0 +1,12 @@ +SELECT + ano_censo, + COUNT(*) AS total +FROM + fies +WHERE + (ano_censo > 2011) +GROUP BY + ano_censo +ORDER BY + ano_censo ASC +; diff --git a/Consultas_SQL/FIES/fies_sem_order.sql b/Consultas_SQL/FIES/fies_sem_order.sql new file mode 100644 index 0000000000000000000000000000000000000000..db1c031979d5ba5f4eefcd53d0efd7738f880aec --- /dev/null +++ b/Consultas_SQL/FIES/fies_sem_order.sql @@ -0,0 +1,10 @@ +SELECT + ano_censo, + COUNT(*) AS total +FROM + fies +WHERE + (ano_censo > 2011) +GROUP BY + ano_censo +; diff --git a/Consultas_SQL/FIES/fies_sem_order_troca_count.sql b/Consultas_SQL/FIES/fies_sem_order_troca_count.sql new file mode 100644 index 0000000000000000000000000000000000000000..742bae09a22deea4978d7c52f13376a9f64486f9 --- /dev/null +++ b/Consultas_SQL/FIES/fies_sem_order_troca_count.sql @@ -0,0 +1,11 @@ +SELECT + ano_censo, + COUNT(sigla_uf) AS total +FROM + fies +WHERE + (ano_censo > 2011) +GROUP BY + ano_censo + +; diff --git a/Consultas_SQL/FIES/fies_trocando_count.sql b/Consultas_SQL/FIES/fies_trocando_count.sql new file mode 100644 index 0000000000000000000000000000000000000000..0620bf5852b544c6c20de9ebb75003a41df4542b --- /dev/null +++ b/Consultas_SQL/FIES/fies_trocando_count.sql @@ -0,0 +1,13 @@ +SELECT + ano_censo, + COUNT(sigla_uf) AS total +FROM + fies +WHERE + (ano_censo > 2011) +GROUP BY + ano_censo +ORDER BY + ano_censo ASC; + +; diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8574cf989b6988b633b48dc1c45bdfb3006b7f88 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM node:9.5.0-stretch + +RUN apt-get -y update -qq && apt-get install -y -qq apt-utils + +RUN npm install --global gulp gulp-cli babel babel-cli babel-core babel-register mocha gulp-mocha gulp-eslint istanbul + +RUN mkdir API + +COPY . ./API + +WORKDIR ./API + +RUN npm install + +RUN gulp build + +EXPOSE 4000 + +CMD gulp + +# sudo docker build --tag api-smppir . + +# sudo docker run --rm -p 4000:4000 --net="host" --name api-smppir api-smppir \ No newline at end of file diff --git a/FIES_ORIGINAL.txt b/FIES_ORIGINAL.txt new file mode 100644 index 0000000000000000000000000000000000000000..2d85e3e07400b1a6948d32d36a696822334d8b77 --- /dev/null +++ b/FIES_ORIGINAL.txt @@ -0,0 +1,150 @@ ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,993s +user 0m0,004s +sys 0m0,007s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,905s +user 0m0,004s +sys 0m0,008s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,906s +user 0m0,012s +sys 0m0,000s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,964s +user 0m0,004s +sys 0m0,008s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,972s +user 0m0,006s +sys 0m0,006s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,955s +user 0m0,007s +sys 0m0,012s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m2,205s +user 0m0,005s +sys 0m0,006s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,781s +user 0m0,003s +sys 0m0,008s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,930s +user 0m0,012s +sys 0m0,000s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m2,097s +user 0m0,003s +sys 0m0,009s diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..9e419e042146a2ce2e354202d4f7d8e4a3d66f31 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,674 @@ +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. \ No newline at end of file diff --git a/Resultados/ATV_EXTRA_ORIGINAL.txt b/Resultados/ATV_EXTRA_ORIGINAL.txt new file mode 100644 index 0000000000000000000000000000000000000000..502b0a382483dc36997658f1bddfa76866d71f5b --- /dev/null +++ b/Resultados/ATV_EXTRA_ORIGINAL.txt @@ -0,0 +1,160 @@ ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,465s +user 0m0,021s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,406s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,278s +user 0m0,008s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,425s +user 0m0,004s +sys 0m0,009s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,440s +user 0m0,013s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,359s +user 0m0,004s +sys 0m0,009s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,392s +user 0m0,001s +sys 0m0,012s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,100s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,617s +user 0m0,005s +sys 0m0,009s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,350s +user 0m0,006s +sys 0m0,014s diff --git a/Resultados/ATV_EXTRA_SEM_ORDER.txt b/Resultados/ATV_EXTRA_SEM_ORDER.txt new file mode 100644 index 0000000000000000000000000000000000000000..cdce053e78fc94af7774a827885b911865073921 --- /dev/null +++ b/Resultados/ATV_EXTRA_SEM_ORDER.txt @@ -0,0 +1,160 @@ ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,362s +user 0m0,013s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,217s +user 0m0,010s +sys 0m0,003s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,450s +user 0m0,013s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,425s +user 0m0,021s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,508s +user 0m0,002s +sys 0m0,010s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,400s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,222s +user 0m0,008s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,278s +user 0m0,004s +sys 0m0,009s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,800s +user 0m0,010s +sys 0m0,010s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m4,483s +user 0m0,009s +sys 0m0,004s diff --git a/Resultados/ATV_EXTRA_SEM_ORDER_TROCA_COUNT.txt b/Resultados/ATV_EXTRA_SEM_ORDER_TROCA_COUNT.txt new file mode 100644 index 0000000000000000000000000000000000000000..17481c54e9cf00440402fb8e7defddc502382f65 --- /dev/null +++ b/Resultados/ATV_EXTRA_SEM_ORDER_TROCA_COUNT.txt @@ -0,0 +1,160 @@ ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,195s +user 0m0,006s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,116s +user 0m0,007s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,013s +user 0m0,009s +sys 0m0,003s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,128s +user 0m0,004s +sys 0m0,010s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,207s +user 0m0,013s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,314s +user 0m0,009s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m7,836s +user 0m0,007s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,048s +user 0m0,004s +sys 0m0,007s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m7,773s +user 0m0,020s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,208s +user 0m0,009s +sys 0m0,004s diff --git a/Resultados/ATV_EXTRA_TROCA_COUNT.txt b/Resultados/ATV_EXTRA_TROCA_COUNT.txt new file mode 100644 index 0000000000000000000000000000000000000000..ea3d3cfc4d95a2792720bb36f6531662248faf59 --- /dev/null +++ b/Resultados/ATV_EXTRA_TROCA_COUNT.txt @@ -0,0 +1,160 @@ ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m7,963s +user 0m0,003s +sys 0m0,010s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m7,714s +user 0m0,012s +sys 0m0,001s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,113s +user 0m0,007s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,039s +user 0m0,014s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,361s +user 0m0,009s +sys 0m0,004s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,158s +user 0m0,008s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m7,719s +user 0m0,010s +sys 0m0,003s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,122s +user 0m0,006s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,072s +user 0m0,008s +sys 0m0,013s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 723 | +| 2011 | 1080 | +| 2012 | 1508 | +| 2013 | 1783 | +| 2014 | 3150 | +| 2015 | 4157 | +| 2016 | 6412 | ++-----------+-------+ +7 tuples + +real 0m8,242s +user 0m0,011s +sys 0m0,010s diff --git a/Resultados/EVASOR_ORIGINAL.txt b/Resultados/EVASOR_ORIGINAL.txt new file mode 100644 index 0000000000000000000000000000000000000000..c695c61d980642ab983d00e8d3fb9d37666b3943 --- /dev/null +++ b/Resultados/EVASOR_ORIGINAL.txt @@ -0,0 +1,160 @@ ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,365s +user 0m0,014s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,084s +user 0m0,010s +sys 0m0,003s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,484s +user 0m0,000s +sys 0m0,013s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,350s +user 0m0,013s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m7,966s +user 0m0,013s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,184s +user 0m0,009s +sys 0m0,012s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,528s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,325s +user 0m0,012s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,273s +user 0m0,004s +sys 0m0,010s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,375s +user 0m0,005s +sys 0m0,008s diff --git a/Resultados/EVASOR_SEM_ORDER.txt b/Resultados/EVASOR_SEM_ORDER.txt new file mode 100644 index 0000000000000000000000000000000000000000..4081237b3e39486e3d933096cd150edb712a0ff7 --- /dev/null +++ b/Resultados/EVASOR_SEM_ORDER.txt @@ -0,0 +1,160 @@ ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m7,990s +user 0m0,009s +sys 0m0,004s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,242s +user 0m0,003s +sys 0m0,011s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,764s +user 0m0,010s +sys 0m0,003s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,048s +user 0m0,016s +sys 0m0,005s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,258s +user 0m0,013s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,308s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m7,783s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m7,975s +user 0m0,007s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,292s +user 0m0,010s +sys 0m0,003s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m8,374s +user 0m0,007s +sys 0m0,007s diff --git a/Resultados/EVASOR_SEM_ORDER_TROCA_COUNT.txt b/Resultados/EVASOR_SEM_ORDER_TROCA_COUNT.txt new file mode 100644 index 0000000000000000000000000000000000000000..6fc384438229b9cfebd449aca8bffdec9bcbb50f --- /dev/null +++ b/Resultados/EVASOR_SEM_ORDER_TROCA_COUNT.txt @@ -0,0 +1,160 @@ ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,012s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m11,942s +user 0m0,000s +sys 0m0,012s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,011s +user 0m0,012s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,489s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m11,955s +user 0m0,012s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,217s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,489s +user 0m0,007s +sys 0m0,013s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m11,895s +user 0m0,007s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,556s +user 0m0,006s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,239s +user 0m0,007s +sys 0m0,006s diff --git a/Resultados/EVASOR_TROCA_COUNT.txt b/Resultados/EVASOR_TROCA_COUNT.txt new file mode 100644 index 0000000000000000000000000000000000000000..9c6135bcbe1d3fb89fd06f4a3787120f20a4fb98 --- /dev/null +++ b/Resultados/EVASOR_TROCA_COUNT.txt @@ -0,0 +1,160 @@ ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,290s +user 0m0,005s +sys 0m0,008s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m11,613s +user 0m0,006s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m11,739s +user 0m0,007s +sys 0m0,006s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,155s +user 0m0,011s +sys 0m0,010s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m11,917s +user 0m0,008s +sys 0m0,005s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,192s +user 0m0,005s +sys 0m0,009s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,024s +user 0m0,009s +sys 0m0,004s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,541s +user 0m0,013s +sys 0m0,000s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,083s +user 0m0,011s +sys 0m0,003s ++-----------+-------+ +| ano_censo | total | ++===========+=======+ +| 2010 | 6708 | +| 2011 | 8700 | +| 2012 | 13593 | +| 2013 | 16366 | +| 2014 | 24563 | +| 2015 | 33678 | +| 2016 | 43813 | ++-----------+-------+ +7 tuples + +real 0m12,239s +user 0m0,005s +sys 0m0,008s diff --git a/Resultados/FIES_ORIGINAL.txt b/Resultados/FIES_ORIGINAL.txt new file mode 100644 index 0000000000000000000000000000000000000000..c7504e471ecf0c3e9409e1c3a2969fb4417251e1 --- /dev/null +++ b/Resultados/FIES_ORIGINAL.txt @@ -0,0 +1,150 @@ ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,973s +user 0m0,009s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,904s +user 0m0,004s +sys 0m0,007s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,890s +user 0m0,007s +sys 0m0,005s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,939s +user 0m0,005s +sys 0m0,008s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,924s +user 0m0,006s +sys 0m0,006s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,980s +user 0m0,004s +sys 0m0,008s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,849s +user 0m0,012s +sys 0m0,000s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,915s +user 0m0,004s +sys 0m0,010s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,948s +user 0m0,012s +sys 0m0,008s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,857s +user 0m0,008s +sys 0m0,004s diff --git a/Resultados/FIES_SEM_ORDER.txt b/Resultados/FIES_SEM_ORDER.txt new file mode 100644 index 0000000000000000000000000000000000000000..849d93ea56e79c47b7869601e8924e5147e5fd81 --- /dev/null +++ b/Resultados/FIES_SEM_ORDER.txt @@ -0,0 +1,150 @@ ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,977s +user 0m0,003s +sys 0m0,010s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m2,247s +user 0m0,014s +sys 0m0,005s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,924s +user 0m0,011s +sys 0m0,001s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,939s +user 0m0,007s +sys 0m0,006s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,992s +user 0m0,009s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,946s +user 0m0,016s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,905s +user 0m0,008s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,958s +user 0m0,004s +sys 0m0,008s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,999s +user 0m0,003s +sys 0m0,009s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m2,033s +user 0m0,012s +sys 0m0,000s diff --git a/Resultados/FIES_SEM_ORDER_TROCA_COUNT.txt b/Resultados/FIES_SEM_ORDER_TROCA_COUNT.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c20b21acf16976440f789c820b0808e6919d2e8 --- /dev/null +++ b/Resultados/FIES_SEM_ORDER_TROCA_COUNT.txt @@ -0,0 +1,150 @@ ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,943s +user 0m0,006s +sys 0m0,006s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,855s +user 0m0,008s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,849s +user 0m0,016s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,941s +user 0m0,012s +sys 0m0,000s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,963s +user 0m0,004s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,963s +user 0m0,003s +sys 0m0,009s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,896s +user 0m0,006s +sys 0m0,006s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,947s +user 0m0,011s +sys 0m0,000s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,949s +user 0m0,009s +sys 0m0,011s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,932s +user 0m0,012s +sys 0m0,008s diff --git a/Resultados/FIES_TROCA_COUNT.txt b/Resultados/FIES_TROCA_COUNT.txt new file mode 100644 index 0000000000000000000000000000000000000000..8a97321de0084a7c8aab356f171664a7c3b53af7 --- /dev/null +++ b/Resultados/FIES_TROCA_COUNT.txt @@ -0,0 +1,150 @@ ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,910s +user 0m0,009s +sys 0m0,003s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,910s +user 0m0,012s +sys 0m0,000s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,938s +user 0m0,006s +sys 0m0,006s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m2,107s +user 0m0,008s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m2,213s +user 0m0,008s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,962s +user 0m0,006s +sys 0m0,006s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,996s +user 0m0,016s +sys 0m0,004s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,896s +user 0m0,011s +sys 0m0,000s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,996s +user 0m0,001s +sys 0m0,006s ++-----------+----------+ +| ano_censo | total | ++===========+==========+ +| 2012 | 5700370 | +| 2013 | 10779401 | +| 2014 | 16114623 | +| 2015 | 14457435 | +| 2016 | 17050881 | +| 2017 | 13783936 | ++-----------+----------+ +6 tuples + +real 0m1,868s +user 0m0,004s +sys 0m0,007s diff --git a/config.json.example b/config.json.example index e3d309200d160d47b17dbe57f23dee11cdbccd23..bf1d212cb45a55ad2c1a23f6fb05df8d2fced569 100644 --- a/config.json.example +++ b/config.json.example @@ -16,12 +16,6 @@ "url": "http://simcaqdb3.c3sl.ufpr.br:3000", "download": "https://simcaqdev.c3sl.ufpr.br/download/" }, - "mongodb" : { - "uri": "mongodb://localhost/dev_users" - }, - "monq": { - "uri": "mongodb://localhost/dev_monq" - }, "default": { "api": { "version" : "v1" @@ -61,13 +55,6 @@ "url": "http://simcaqdb3.c3sl.ufpr.br:3000", "download": "https://simcaqdev.c3sl.ufpr.br/download/" }, - "mongodb" : { - "uri": "mongodb://localhost/test_users", - "secret": "SimCAQC3SL" - }, - "monq": { - "uri": "mongodb://localhost/test_monq" - }, "default": { "api": { "version" : "v1" @@ -107,13 +94,6 @@ "url": "http://simcaqdb3.c3sl.ufpr.br:7000", "download": "https://simcaq.c3sl.ufpr.br/download/" }, - "mongodb" : { - "uri": "mongodb://localhost/users", - "secret": "SimCAQC3SL" - }, - "monq": { - "uri": "mongodb://localhost/monq" - }, "default": { "api": { "version" : "v1" diff --git a/fies.sql b/fies.sql new file mode 100644 index 0000000000000000000000000000000000000000..2c1136027ebd5833d9e7311111bc14211d99d46f --- /dev/null +++ b/fies.sql @@ -0,0 +1,15 @@ +SELECT + ano_censo, + COUNT(*) AS total + +FROM + fies + +WHERE + (ano_censo > 2011) + +GROUP BY + ano_censo + +ORDER BY + ano_censo ASC; diff --git a/fies_no_order.sql b/fies_no_order.sql new file mode 100644 index 0000000000000000000000000000000000000000..2c1136027ebd5833d9e7311111bc14211d99d46f --- /dev/null +++ b/fies_no_order.sql @@ -0,0 +1,15 @@ +SELECT + ano_censo, + COUNT(*) AS total + +FROM + fies + +WHERE + (ano_censo > 2011) + +GROUP BY + ano_censo + +ORDER BY + ano_censo ASC; diff --git a/package.json b/package.json index bb9438bfbcf40e8adfddb2dd27896bbe557a4dc5..f603817a79d175c397ddb03a822a8537dd0d30a2 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,6 @@ "method-override": "^2.3.10", "mocha": "^3.5.3", "monetdb-pool": "0.0.8", - "mongoose": "^4.13.17", "nconf": "^0.8.5", "node-uuid": "^1.4.8", "nodemailer": "^4.6.8", diff --git a/result.txt b/result.txt new file mode 100644 index 0000000000000000000000000000000000000000..30fc3485419bde598f2e0eb86dc4cf1254e79677 --- /dev/null +++ b/result.txt @@ -0,0 +1 @@ +------------TESTING ATV_EXTRA_TROCA_COUNT------------- diff --git a/runAllTests.sh b/runAllTests.sh new file mode 100755 index 0000000000000000000000000000000000000000..3b9f2d11ea36a4584b6fb6113b116558c6ec77b5 --- /dev/null +++ b/runAllTests.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +echo "Testing FIES" +./testScript.sh Consultas_SQL/FIES/fies.sql FIES_ORIGINAL +./testScript.sh Consultas_SQL/FIES/fies_sem_order.sql FIES_SEM_ORDER +./testScript.sh Consultas_SQL/FIES/fies_sem_order_troca_count.sql FIES_SEM_ORDER_TROCA_COUNT +./testScript.sh Consultas_SQL/FIES/fies_trocando_count.sql FIES_TROCA_COUNT + +echo "Testing Evasores" +./testScript.sh Consultas_SQL/Evasores/Evasores.sql EVASOR_ORIGINAL +./testScript.sh Consultas_SQL/Evasores/Evasores_sem_order.sql EVASOR_SEM_ORDER +./testScript.sh Consultas_SQL/Evasores/Evasores_sem_order_troca_count.sql EVASOR_SEM_ORDER_TROCA_COUNT +./testScript.sh Consultas_SQL/Evasores/Evasores_trocando_count.sql EVASOR_TROCA_COUNT + +echo "Testing Atv-Extra" +./testScript.sh Consultas_SQL/Atv-Extra/Atividade_extra.sql ATV_EXTRA_ORIGINAL +./testScript.sh Consultas_SQL/Atv-Extra/Atividade_extra_sem_order.sql ATV_EXTRA_SEM_ORDER +./testScript.sh Consultas_SQL/Atv-Extra/Atividade_extra_sem_order_troca_count.sql ATV_EXTRA_SEM_ORDER_TROCA_COUNT +./testScript.sh Consultas_SQL/Atv-Extra/Atividade_extra_trocando_count.sql ATV_EXTRA_TROCA_COUNT diff --git a/src/libs/app.js b/src/libs/app.js index 5a1097988e77bf77b555095c51a5a9ef350a7aa3..496b619b2762364bb2058eb4c846376e56f7bc80 100644 --- a/src/libs/app.js +++ b/src/libs/app.js @@ -36,13 +36,6 @@ const app = express(); const api = require('./routes/api'); -const passport = require('passport'); - -const mongoose = require(`${libs}/db/mongoose`); - -const db = mongoose(); - -require(`${libs}/middlewares/passport`); app.use(bodyParser.json({limit: '50mb'})); app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' })); @@ -78,8 +71,6 @@ app.use((req, res, next) => { next(); }); -app.use(passport.initialize()); -app.use(passport.session()); app.use((req, res, next) => { res.setHeader('Last-Modified', (new Date()).toUTCString()); diff --git a/src/libs/db/mongoose.js b/src/libs/db/mongoose.js deleted file mode 100644 index e1927339fa242dfee3998f5fe04d96517d399bb9..0000000000000000000000000000000000000000 --- a/src/libs/db/mongoose.js +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const libs = `${process.cwd()}/libs`; - -const config = require(`${libs}/config`); - -const log = require(`${libs}/log`)(module); - -const mongoose = require('mongoose'); - -mongoose.Promise = global.Promise; - -module.exports = () => { - // Get mongodb URI (ip and port) in config file - const mongoUri = process.env.MONGO_URI || config.mongodb.uri; - log.info(`Connecting to MongoDB on URI ${mongoUri}`); - // Connection singleton - const db = mongoose.connect(mongoUri); - - mongoose.connection.once('open', () => { log.info("MongoDB connected"); }); - - return db; -}; diff --git a/src/libs/middlewares/downloadDatabase.js b/src/libs/middlewares/downloadDatabase.js deleted file mode 100644 index ee1529228d1293939e260ea0d047260556f0ef63..0000000000000000000000000000000000000000 --- a/src/libs/middlewares/downloadDatabase.js +++ /dev/null @@ -1,108 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const execute = require(`${libs}/middlewares/query`).execute; - -const request = require(`request`); - -const config = require(`${libs}/config`); - -const Download = require(`${libs}/models/download`); - -module.exports = function download(table, mappingTable) { - return (req, res, next) => { - // First, query the mapping - execute(`SELECT target_name, name FROM ${mappingTable}`, undefined, (err, result) => { - if(err) { - log.error(err.stack); - next(new Error('Request could not be satisfied due to a database error.')); - } else { - let header = ''; - req.sql.from(table); - result.forEach((field) => { - req.sql.field(`CASE ${table}.${field.name} WHEN true THEN 1 WHEN false THEN 0 ELSE ${table}.${field.name} END AS ${field.target_name}`); - // req.sql.field(table + '.' + field.name, field.target_name); - if(header === '') header += field.target_name; - else header = header + ';' + field.target_name; - }); - - let form = { - query: req.sql.toString(), - table: req.sql.tableFrom, - name: req.sql.tableFrom, - username: req.user.name, - email: req.user.email, - header - }; - - request.post(config.cdn.url + '/api/v1/file', {form}, (err, response, body) => { - if(err) { - log.error(err); - return res.json({error: err}); - } - - Download.findOne({query: req.sql.toString()}, (err, download) => { - if(download) { - download.updatedAt = Date.now(); - if(download.userId != req.user._id) { - let dl = new Download({ - userId: req.user._id, - table, - name: req.query.name, - mappingTable, - query: req.sql.toString(), - status: 'Enviando', - expired: false - }); - console.log(dl); - dl.save((err) => { - if(err) log.error(err); - }); - } - } else { - download = new Download({ - userId: req.user._id, - table, - name: req.query.name, - mappingTable, - query: req.sql.toString(), - query: req.sql.toString(), - status: 'Enviando', - expired: false - }); - console.log(download); - } - - download.save((err) => { - if(err) { - log.error(err); - } - res.json({msg: 'Wait for download email', waitForIt: true}); - }); - }); - }); - } - }); - } -}; \ No newline at end of file diff --git a/src/libs/middlewares/oauth2.js b/src/libs/middlewares/oauth2.js deleted file mode 100644 index e7f7b446ed037cdb0c4843084bf9626556c19c97..0000000000000000000000000000000000000000 --- a/src/libs/middlewares/oauth2.js +++ /dev/null @@ -1,141 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const oauth2orize = require('oauth2orize'); -const passport = require('passport'); -const crypto = require('crypto'); - -const libs = `${process.cwd()}/libs`; - -const config = require(`${libs}/config`); -const log = require(`${libs}/log`)(module); - -const db = require(`${libs}/db/mongoose`); -const User = require(`${libs}/models/user`); -const AccessToken = require(`${libs}/models/accessToken`); -const RefreshToken = require(`${libs}/models/refreshToken`); - -// create OAuth 2.0 server -let aserver = oauth2orize.createServer() - -// Generic error handler -let errFn = (cb, err) => { - if (err) { - return cb(err) - } -} - -// Destroys any old tokens and generates a new access and refresh token -let generateTokens = (data, done) => { - // curries in `done` callback so we don't need to pass it - let errorHandler = errFn.bind(undefined, done); - let refreshToken; - let refreshTokenValue; - let token; - let tokenValue; - - RefreshToken.remove(data, errorHandler); - AccessToken.remove(data, errorHandler); - - tokenValue = crypto.randomBytes(32).toString('hex'); - refreshTokenValue = crypto.randomBytes(32).toString('hex'); - - data.token = tokenValue; - token = new AccessToken(data); - - data.token = refreshTokenValue; - refreshToken = new RefreshToken(data); - - refreshToken.save(errorHandler); - - token.save((err) => { - if (err) { - log.error(err); - return done(err); - } - done(null, tokenValue, refreshTokenValue, { - 'expires_in': config.security.tokenLife - }); - }) -}; - -// Exchange username & password for access token. -aserver.exchange(oauth2orize.exchange.password((client, username, password, scope, done) => { - User.findOne({ email: username }, (err, user) => { - if (err) { - return done(err); - } - - if (!user || !user.checkPassword(password)) { - return done(null, false); - } - - var model = { - userId: user._id, - clientId: client._id - }; - log.info(`Gerando token para usuário ${user.name}`); - generateTokens(model, done); - }) - -})); - -// Exchange refreshToken for access token. -aserver.exchange(oauth2orize.exchange.refreshToken((client, refreshToken, scope, done) =>{ - RefreshToken.findOne({ token: refreshToken, clientId: client._id }, (err, token) => { - if (err) { - return done(err); - } - - if (!token) { - return done(null, false); - } - - User.findById(token.userId, (err, user) => { - if (err) { - log.error(err); - return done(err); - } - if (!user) { - return done(null, false); - } - - var model = { - userId: user._id, - clientId: client._id - }; - - generateTokens(model, done); - }) - }) -})) - -// token endpoint -// -// `token` middleware handles client requests to exchange authorization grants -// for access tokens. Based on the grant type being exchanged, the above -// exchange middleware will be invoked to handle the request. Clients must -// authenticate when making requests to this endpoint. - -exports.token = [ - passport.authenticate(['oauth2-client-password'], { session: false }), - aserver.token(), - aserver.errorHandler() -]; diff --git a/src/libs/middlewares/passport.js b/src/libs/middlewares/passport.js deleted file mode 100644 index ea4fd95c1945786946ea5e82128d7bfbb37850c6..0000000000000000000000000000000000000000 --- a/src/libs/middlewares/passport.js +++ /dev/null @@ -1,87 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const passport = require('passport'); -const ClientPasswordStrategy = require('passport-oauth2-client-password'); -const BearerStrategy = require('passport-http-bearer').Strategy; - -const libs = `${process.cwd()}/libs`; -const config = require(`${libs}/config`); - -const User = require(`${libs}/models/user`); -const Client = require(`${libs}/models/client`); -const AccessToken = require(`${libs}/models/accessToken`); -const RefreshToken = require(`${libs}/models/refreshToken`); -const email = require(`${libs}/middlewares/email`); - -passport.use(new ClientPasswordStrategy( (clientId, clientSecret, done) => { - Client.findOne({ _id: clientId }, (err, client) => { - if (err) { - return done(err); - } - - if (!client) { - return done(null, false); - } - - if (client.clientSecret !== clientSecret) { - return done(null, false); - } - - return done(null, client); - }) - } -)); - -passport.use(new BearerStrategy( (accessToken, done) => { - AccessToken.findOne({ token: accessToken }, (err, token) => { - if (err) { - return done(err); - } - - if (!token) { - return done(null, false); - } - - if( Math.round((Date.now()-token.created)/1000) > config.security.tokenLife) { - AccessToken.remove({ token: accessToken }, (err) => { - if (err) { - return done(err); - } - }); - - return done(null, false, { msg: 'Token expired' }); - } - - User.findById(token.userId, function(err, usuario) { - if (err) { - return done(err); - } - - if (!usuario) { - return done(null, false, { msg: 'Unknown user' }); - } - - var info = { scope: '*' }; - done(null, usuario, info); - }) - }) - } -)); diff --git a/src/libs/middlewares/reqQueryFields.js b/src/libs/middlewares/reqQueryFields.js index 8ac231fc2f0f98e83c5dedd5e466400655f7ad51..424ef59b7137cb87a43871943aac95018e6f790e 100644 --- a/src/libs/middlewares/reqQueryFields.js +++ b/src/libs/middlewares/reqQueryFields.js @@ -27,7 +27,7 @@ const _ = require('lodash'); function parseWhereValue(type, value) { if(type === 'integer') return parseInt(value, 10); if(type === 'double') return parseFloat(value); - if(type === 'string') return '%'+value+'%'; + if(type === 'string') return value; if(type === 'boolean') { if(value === null || typeof value === 'boolean') { return value; diff --git a/src/libs/models/accessToken.js b/src/libs/models/accessToken.js deleted file mode 100644 index b9c2a60ac4ce29ce45a944c2c23aa189db02cf72..0000000000000000000000000000000000000000 --- a/src/libs/models/accessToken.js +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const User = require(`${libs}/models/user`); -const Client = require(`${libs}/models/client`); - -let AccessToken = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - clientId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'Client' - }, - token: { - type: String, - unique: true, - required: true - }, - createdAt: { - type: Date, - default: Date.now - } -}); - -module.exports = mongoose.model('AccessToken', AccessToken); diff --git a/src/libs/models/client.js b/src/libs/models/client.js deleted file mode 100644 index 2ddae28075d6d2d35eba0798ad425b00580ebd12..0000000000000000000000000000000000000000 --- a/src/libs/models/client.js +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; - -let Client = new Schema({ - name: { - type: String, - unique: true, - required: true - }, - clientSecret: { - type: String, - required: true, - unique: true - } -}); - -module.exports = mongoose.model('Client', Client); diff --git a/src/libs/models/download.js b/src/libs/models/download.js deleted file mode 100644 index 21fdf683c38dfcce176bd44b5ae456e6b0e80a3c..0000000000000000000000000000000000000000 --- a/src/libs/models/download.js +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); - -let Download = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - table: { - type: String, - required: true - }, - name: { - type: String, - required: true - }, - mappingTable: { - type: String, - required: true - }, - query: { - type: String, - required: true - }, - createdAt: { - type: Date, - required: true, - default: Date.now - }, - updatedAt: { - type: Date, - required: true, - default: Date.now - }, - status: { - type: String - }, - size: { - type: Number - }, - expired: { - type: Boolean - }, - link: { - type: String - } -}); - -module.exports = mongoose.model('Download', Download); diff --git a/src/libs/models/pqr.js b/src/libs/models/pqr.js deleted file mode 100644 index d8c71c6df182297dbddbb5f4a4a12eb0cf951cb2..0000000000000000000000000000000000000000 --- a/src/libs/models/pqr.js +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const mongoose = require('mongoose') - -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); - -const Schema = mongoose.Schema; - -let PQRSchema = new Schema({ - content: { - type: String, - required: true, - } -}); - -module.exports = mongoose.model('PQR', PQRSchema); diff --git a/src/libs/models/refreshToken.js b/src/libs/models/refreshToken.js deleted file mode 100644 index 3a37ae96d69c08b698ebd6ab924ddb602d07722e..0000000000000000000000000000000000000000 --- a/src/libs/models/refreshToken.js +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const User = require(`${libs}/models/user`); -const Client = require(`${libs}/models/client`); - -let RefreshToken = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - clientId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'Client' - }, - token: { - type: String, - unique: true, - required: true - }, - createdAt: { - type: Date, - default: Date.now - } -}); - -module.exports = mongoose.model('RefreshToken', RefreshToken); - diff --git a/src/libs/models/resetToken.js b/src/libs/models/resetToken.js deleted file mode 100644 index d983436b9181a7f55aafd5eefcfc3f028038a345..0000000000000000000000000000000000000000 --- a/src/libs/models/resetToken.js +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); -const uuid = require('node-uuid'); - -let ResetToken = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - token: { - type: String, - required: true - }, - reset: { - type: Boolean, - required: true, - default: false - }, - createdAt: { - type: Date, - required: true, - default: Date.now - } -}); - -ResetToken.methods.createResetToken = function (done) { - let resetToken = this; - let token = uuid.v4(); - resetToken.set('token', token); - resetToken.reset = false; - resetToken.save(function(err) { - if (err) - return done(err); - return done(null, token); - }) -} -ResetToken.methods.hasExpired = function () { - var now = new Date(); - return (now - this.createdAt) > 86400; //Expire if token is 1 day old -}; - -module.exports = mongoose.model('ResetToken', ResetToken); diff --git a/src/libs/models/simulation.js b/src/libs/models/simulation.js deleted file mode 100644 index a4a6cc3cd5b2c26aa28f68953b82d85243cd0144..0000000000000000000000000000000000000000 --- a/src/libs/models/simulation.js +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const mongoose = require('mongoose') - -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); - -const Schema = mongoose.Schema; - -let SimulationSchema = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - content: { - type: String, - required: true, - }, - name: { - type: String - }, - createdAt: { - type: Date, - required: true, - default: Date.now - }, - updatedAt: { - type: Date, - required: true, - default: Date.now - } -}); - -module.exports = mongoose.model('Simulation', SimulationSchema); diff --git a/src/libs/models/user.js b/src/libs/models/user.js deleted file mode 100644 index 7dc642e3cd6c81301677f89f27b8852751596cbc..0000000000000000000000000000000000000000 --- a/src/libs/models/user.js +++ /dev/null @@ -1,139 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const mongoose = require('mongoose'); -const crypto = require('crypto') -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const Schema = mongoose.Schema; - -// set up a mongoose model -var UserSchema = new Schema({ - email: { - type: String, - unique: true, - required: [true, 'O campo Email é obrigatório.'] - }, - hashedPassword: { - type: String, - required: [true, 'O campo Senha é obrigatório.'] - }, - salt: { - type: String, - required: true - }, - name: { - type: String, - required: [true, 'O campo Nome é obrigatório.'] - }, - nickname: { - type: String, - required: [true, 'O campo Apelido é obrigatório.'] - }, - cpf:{ - type: String, - unique: true, - required: [true, 'O campo CPF é obrigatório.'] - }, - cep:{ - type: String, - required: [true, 'O campo CEP é obrigatório.'] - }, - schooling: { - type: String, - required: [true, 'O campo Formação é obrigatório.'] - }, - course: { - type: String, - }, - complement: { - type: String, - }, - address: { - type: String, - }, - phone: { - type: String, - }, - segment: { - type: String, - required: [true, 'O campo Segmento é obrigatório.'] - }, - role: { - type: String, - required: [true, 'O campo Função é obrigatório.'] - }, - institutionName: { - type: String, - required: [true, 'O campo Instituição em que trabalha ou estuda é obrigatório.'] - }, - state: { - type: String, - required: [true, 'O campo Estado é obrigatório.'] - }, - city: { - type: String, - required: [true, 'O campo Cidade é obrigatório.'] - }, - receiveEmails: { - type: Boolean - }, - createdAt: { - type: Date, - default: Date.now - }, - origin: { - type: String, - enum: ['LDE', 'SimCAQ'], - required: [true, 'O campo origem é obrigatória e aceita apenas os valores "LDE" ou "SimCAQ"'] - }, - verified: { - type: Boolean, - default: false - }, - citesegment: { - type: String - }, - citerole: { - type: String - }, - admin: { - type: Boolean, - default: false - } -}); - -UserSchema.methods.encryptPassword = function(password) { - return crypto.pbkdf2Sync(password+'', this.salt, 10000, 512, 'sha512'); -}; - -UserSchema.virtual('password').set(function(password) { - this._plainPassword = password+''; - this.salt = crypto.randomBytes(128).toString('hex'); - this.hashedPassword = this.encryptPassword(password).toString('hex'); -}).get(function() { - return this._plainPassword; -}); - -UserSchema.methods.checkPassword = function(password) { - return this.encryptPassword(password).toString('hex') === this.hashedPassword; -} - -module.exports = mongoose.model('User', UserSchema); diff --git a/src/libs/models/verificationToken.js b/src/libs/models/verificationToken.js deleted file mode 100644 index 1047e4d0795165041b0b06d2c86c2884ed3f7481..0000000000000000000000000000000000000000 --- a/src/libs/models/verificationToken.js +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; -const libs = `${process.cwd()}/libs`; -const log = require(`${libs}/log`)(module); -const User = require(`${libs}/models/user`); -const uuid = require('node-uuid'); - -let VerificationToken = new Schema({ - userId: { - type: Schema.Types.ObjectId, - required: true, - ref: 'User' - }, - token: { - type: String, - required: true - }, - verified: { - type: Boolean, - required: true, - default: false - }, - createdAt: { - type: Date, - required: true, - default: Date.now - } -}); - -VerificationToken.methods.createVerificationToken = function(done) { - let verificationToken = this; - let token = uuid.v4(); - verificationToken.set('token', token); - verificationToken.verified = false; - verificationToken.save(function(err) { - if (err) return done(err); - return done(null, token); - }) -} - -module.exports = mongoose.model('VerificationToken', VerificationToken); diff --git a/src/libs/routes/SMPPIR/admission.js b/src/libs/routes/SMPPIR/admission.js new file mode 100644 index 0000000000000000000000000000000000000000..80245eb274aa0e164455fbbc3e09a63dec7b4160 --- /dev/null +++ b/src/libs/routes/SMPPIR/admission.js @@ -0,0 +1,156 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const admissionApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'shift', + table: 'admission_ag', + tableField: 'turno_aluno', + resultField: 'ds_turno_aluno', + where: { + relation: '=', + type: 'string', + field: 'turno_aluno', + }, +}) +.addValue({ + name: 'gender', + table: 'admission_ag', + tableField: 'descricao_genero_aluno', + resultField: 'ds_sexo_aluno', + where: { + relation: '=', + type: 'string', + field: 'descricao_genero_aluno', + }, +}) +.addValue({ + name: 'ethnic', + table: 'admission_ag', + tableField: 'cor_raca_aluno', + resultField: 'ds_cor_raca_aluno', + where: { + relation: '=', + type: 'string', + field: 'cor_raca_aluno', + }, +}) +.addValue({ + name: 'course', + table: 'admission_ag', + tableField: 'nome_curso', + resultField: 'no_curso', + where: { + relation: '=', + type: 'string', + field: 'nome_curso', + }, +}) +.addValue({ + name: 'institution', + table: 'admission_ag', + tableField: 'nome_ies', + resultField: 'no_ies', + where: { + relation: '=', + type: 'string', + field: 'nome_ies', + }, +}) +.addValue({ + name: 'institution_cod', + table: 'admission_ag', + tableField: 'cod_ies', + resultField: 'co_ies', + where: { + relation: '=', + type: 'integer', + field: 'cod_ies', + }, +}) +.addValue({ + name: 'year', + table: 'admission_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'min_year', + table: 'admission_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'admission_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +admissionApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('admission_ag.ano_censo as no_ano_pesquisa') + .field('SUM(total) AS total') + .from('admission_ag') + .group('admission_ag.ano_censo') + .order('admission_ag.ano_censo'); + next(); +}, query, response('admission')); + +module.exports = admissionApp; diff --git a/src/libs/routes/SMPPIR/african_culture.js b/src/libs/routes/SMPPIR/african_culture.js new file mode 100644 index 0000000000000000000000000000000000000000..6268fc7c99763f684e4cf180833f7d9b1638fed0 --- /dev/null +++ b/src/libs/routes/SMPPIR/african_culture.js @@ -0,0 +1,141 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const cad_unico = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'african_culture_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +.addValue({ + name: 'family_type', + table: 'african_culture_ag', + tableField: 'ind_tipo_familia', + resultField: 'ind_parc_mds_fam', + where: { + relation: '=', + type: 'string', + field: 'ind_tipo_familia', + }, +}) + +.addValue({ + name:'cod_local_home', + table:'african_culture_ag', + tableField:'cod_local_domicilio', + resultField:'cod_local_domic_fam', + where: { + relation:'=', + type:'string', + field:'cod_local_domicilio', + }, +}) + +.addValue({ + name: 'home_type', + table: 'african_culture_ag', + tableField: 'cod_especie_domicilio', + resultField: 'cod_especie_domic_fam', + where: { + relation: '=', + type: 'string', + field: 'cod_especie_domicilio', + }, +}) + +.addValue({ + name: 'home_location', + table: 'african_culture_ag', + tableField: 'codigo_ibge', + resultField: 'cd_ibge', + where: { + relation: '=', + type: 'string', + field: 'codigo_ibge', + }, +}) + +.addValue({ + name: 'uf', + table: 'african_culture_ag', + tableField: 'sigla_estado', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_estado', + }, +}) +.addValue({ + name: 'region', + table: 'african_culture_ag', + tableField : 'nome_regiao', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao', + }, +}) + +; + + +cad_unico.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('SUM(total) AS Total') + .from('african_culture_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = cad_unico; diff --git a/src/libs/routes/SMPPIR/african_rights.js b/src/libs/routes/SMPPIR/african_rights.js new file mode 100644 index 0000000000000000000000000000000000000000..27b5de8ade40006aeed5d29aeeb44cb79cef1fc6 --- /dev/null +++ b/src/libs/routes/SMPPIR/african_rights.js @@ -0,0 +1,141 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const cad_unico = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'african_rights_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +.addValue({ + name: 'family_type', + table: 'african_rights_ag', + tableField: 'ind_tipo_familia', + resultField: 'ind_parc_mds_fam', + where: { + relation: '=', + type: 'string', + field: 'ind_tipo_familia', + }, +}) + +.addValue({ + name: 'education_families_conclude', + table: 'african_rights_ag', + tableField: 'concluiu_frequentou', + resultField: 'cod_concluiu_frequentou_memb', + where: { + relation: '=', + type: 'string', + field: 'concluiu_frequentou', + }, +}) + +.addValue({ + name: 'education_families_level', + table: 'african_rights_ag', + tableField: 'ano_serie_frequentou', + resultField: 'cod_ano_serie_frequentou_memb', + where: { + relation: '=', + type: 'string', + field: 'ano_serie_frequentou', + }, +}) + +.addValue({ + name: 'education_families', + table: 'african_rights_ag', + tableField: 'curso_frequentou', + resultField: 'cod_curso_frequentou_pessoa_memb', + where: { + relation: '=', + type: 'string', + field: 'curso_frequentou', + }, +}) + +.addValue({ + name: 'uf', + table: 'african_rights_ag', + tableField: 'sigla_estado', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_estado', + }, +}) +.addValue({ + name: 'region', + table: 'african_rights_ag', + tableField : 'nome_regiao', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao', + }, +}) + +; + + +cad_unico.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('SUM(total) AS Total') + .from('african_rights_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = cad_unico; diff --git a/src/libs/routes/SMPPIR/african_sustentability.js b/src/libs/routes/SMPPIR/african_sustentability.js new file mode 100644 index 0000000000000000000000000000000000000000..3bd006f36e41509f5a9246c59fce219ce32881df --- /dev/null +++ b/src/libs/routes/SMPPIR/african_sustentability.js @@ -0,0 +1,117 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const cad_unico = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'african_sustentability_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +.addValue({ + name: 'family_type', + table: 'african_sustentability_ag', + tableField: 'ind_tipo_familia', + resultField: 'ind_parc_mds_fam', + where: { + relation: '=', + type: 'string', + field: 'ind_tipo_familia', + }, +}) + +.addValue({ + name: 'per_capita_income', + table: 'african_sustentability_ag', + tableField: 'renda_media', + resultField: 'vlr_renda_media_fam', + where: { + relation: '=', + type: 'float', + field: 'renda_media', + }, +}) + +.addValue({ + name: 'uf', + table: 'african_sustentability_ag', + tableField: 'sigla_estado', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_estado', + }, +}) +.addValue({ + name: 'region', + table: 'african_sustentability_ag', + tableField : 'nome_regiao', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao', + }, +}) + +; + + +cad_unico.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('SUM(total) AS Total') + .from('african_sustentability_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = cad_unico; diff --git a/src/libs/routes/SMPPIR/ciganos_culture.js b/src/libs/routes/SMPPIR/ciganos_culture.js new file mode 100644 index 0000000000000000000000000000000000000000..f368aa0fc6c90ae4ac41a085e8371d2575beae9f --- /dev/null +++ b/src/libs/routes/SMPPIR/ciganos_culture.js @@ -0,0 +1,141 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const cad_unico = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'ciganos_culture_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +.addValue({ + name: 'family_type', + table: 'ciganos_culture_ag', + tableField: 'ind_tipo_familia', + resultField: 'ind_parc_mds_fam', + where: { + relation: '=', + type: 'string', + field: 'ind_tipo_familia', + }, +}) + +.addValue({ + name:'cod_local_home', + table:'ciganos_culture_ag', + tableField:'cod_local_domicilio', + resultField:'cod_local_domic_fam', + where: { + relation:'=', + type:'string', + field:'cod_local_domicilio', + }, +}) + +.addValue({ + name: 'home_type', + table: 'ciganos_culture_ag', + tableField: 'cod_especie_domicilio', + resultField: 'cod_especie_domic_fam', + where: { + relation: '=', + type: 'string', + field: 'cod_especie_domicilio', + }, +}) + +.addValue({ + name: 'home_location', + table: 'ciganos_culture_ag', + tableField: 'codigo_ibge', + resultField: 'cd_ibge', + where: { + relation: '=', + type: 'string', + field: 'codigo_ibge', + }, +}) + +.addValue({ + name: 'uf', + table: 'ciganos_culture_ag', + tableField: 'sigla_estado', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_estado', + }, +}) +.addValue({ + name: 'region', + table: 'ciganos_culture_ag', + tableField : 'nome_regiao', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao', + }, +}) + +; + + +cad_unico.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('SUM(total) AS Total') + .from('ciganos_culture_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = cad_unico; diff --git a/src/libs/routes/SMPPIR/ciganos_rights.js b/src/libs/routes/SMPPIR/ciganos_rights.js new file mode 100644 index 0000000000000000000000000000000000000000..537ceee36ffff043baff540059e65e1741f4e5cc --- /dev/null +++ b/src/libs/routes/SMPPIR/ciganos_rights.js @@ -0,0 +1,141 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const cad_unico = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'ciganos_rights_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +.addValue({ + name: 'family_type', + table: 'ciganos_rights_ag', + tableField: 'ind_tipo_familia', + resultField: 'ind_parc_mds_fam', + where: { + relation: '=', + type: 'string', + field: 'ind_tipo_familia', + }, +}) + +.addValue({ + name: 'education_families_conclude', + table: 'ciganos_rights_ag', + tableField: 'concluiu_frequentou', + resultField: 'cod_concluiu_frequentou_memb', + where: { + relation: '=', + type: 'string', + field: 'concluiu_frequentou', + }, +}) + +.addValue({ + name: 'education_families_level', + table: 'ciganos_rights_ag', + tableField: 'ano_serie_frequentou', + resultField: 'cod_ano_serie_frequentou_memb', + where: { + relation: '=', + type: 'string', + field: 'ano_serie_frequentou', + }, +}) + +.addValue({ + name: 'education_families', + table: 'ciganos_rights_ag', + tableField: 'curso_frequentou', + resultField: 'cod_curso_frequentou_pessoa_memb', + where: { + relation: '=', + type: 'string', + field: 'curso_frequentou', + }, +}) + +.addValue({ + name: 'uf', + table: 'ciganos_rights_ag', + tableField: 'sigla_estado', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_estado', + }, +}) +.addValue({ + name: 'region', + table: 'ciganos_rights_ag', + tableField : 'nome_regiao', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao', + }, +}) + +; + + +cad_unico.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('SUM(total) AS Total') + .from('ciganos_rights_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = cad_unico; diff --git a/src/libs/routes/SMPPIR/ciganos_sustentability.js b/src/libs/routes/SMPPIR/ciganos_sustentability.js new file mode 100644 index 0000000000000000000000000000000000000000..89b28cf7f9b0b77c363999afb0a69419c8603f6d --- /dev/null +++ b/src/libs/routes/SMPPIR/ciganos_sustentability.js @@ -0,0 +1,117 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const cad_unico = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'ciganos_sustentability_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +.addValue({ + name: 'family_type', + table: 'ciganos_sustentability_ag', + tableField: 'ind_tipo_familia', + resultField: 'ind_parc_mds_fam', + where: { + relation: '=', + type: 'string', + field: 'ind_tipo_familia', + }, +}) + +.addValue({ + name: 'per_capita_income', + table: 'ciganos_sustentability_ag', + tableField: 'renda_media', + resultField: 'vlr_renda_media_fam', + where: { + relation: '=', + type: 'float', + field: 'renda_media', + }, +}) + +.addValue({ + name: 'uf', + table: 'ciganos_sustentability_ag', + tableField: 'sigla_estado', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_estado', + }, +}) +.addValue({ + name: 'region', + table: 'ciganos_sustentability_ag', + tableField : 'nome_regiao', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao', + }, +}) + +; + + +cad_unico.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('SUM(total) AS Total') + .from('ciganos_sustentability_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = cad_unico; diff --git a/src/libs/routes/SMPPIR/course.js b/src/libs/routes/SMPPIR/course.js new file mode 100644 index 0000000000000000000000000000000000000000..482ecaca78494672770c5db0b1c3d12e68fcae86 --- /dev/null +++ b/src/libs/routes/SMPPIR/course.js @@ -0,0 +1,88 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const course = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}).addValue({ + name: 'year', + table: 'course_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}).addValue({ + name: 'min_year', + table: 'course_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'course_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +course.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('course_ag.nome_curso AS no_curso') + .from('course_ag') + .group('course_ag.nome_curso') + .order('course_ag.nome_curso'); + next(); +}, query, response('social_support')); + +module.exports = course; diff --git a/src/libs/routes/SMPPIR/courseFIES.js b/src/libs/routes/SMPPIR/courseFIES.js new file mode 100644 index 0000000000000000000000000000000000000000..a6bf0c3c400bee9243459887c9711ad81992d61c --- /dev/null +++ b/src/libs/routes/SMPPIR/courseFIES.js @@ -0,0 +1,88 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const institution = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}).addValue({ + name: 'year', + table: 'course_fies_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}).addValue({ + name: 'min_year', + table: 'course_fies_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'course_fies_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +institution.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('course_fies_ag.curso as DS_curso') + .from('course_fies_ag') + .group('course_fies_ag.curso') + .order('course_fies_ag.curso'); + next(); +}, query, response('courseFIES')); + +module.exports = institution; diff --git a/src/libs/routes/SMPPIR/coursePROUNI.js b/src/libs/routes/SMPPIR/coursePROUNI.js new file mode 100644 index 0000000000000000000000000000000000000000..96152d4be74ccd6d38b0962ab9422bd3e24ae0a6 --- /dev/null +++ b/src/libs/routes/SMPPIR/coursePROUNI.js @@ -0,0 +1,88 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const institution = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}).addValue({ + name: 'year', + table: 'course_prouni_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}).addValue({ + name: 'min_year', + table: 'course_prouni_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'course_prouni_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +institution.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('course_prouni_ag.nome_curso as nome_curso_bolsa') + .from('course_prouni_ag') + .group('course_prouni_ag.nome_curso') + .order('nome_curso'); + next(); +}, query, response('coursePROUNI')); + +module.exports = institution; diff --git a/src/libs/routes/SMPPIR/eixo_2.js b/src/libs/routes/SMPPIR/eixo_2.js new file mode 100644 index 0000000000000000000000000000000000000000..9b1a15f2b506be35a111df4af7353b181658dc26 --- /dev/null +++ b/src/libs/routes/SMPPIR/eixo_2.js @@ -0,0 +1,205 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const cad_unico = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'quilombola_eixo_2_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +.addValue({ + name: 'family_type', + table: 'quilombola_eixo_2_ag', + tableField: 'ind_tipo_familia', + resultField: 'ind_parc_mds_fam', + where: { + relation: '=', + type: 'string', + field: 'ind_tipo_familia', + }, +}) + +.addValue({ + name:'cod_local_home', + table:'quilombola_eixo_2_ag', + tableField:'cod_local_domicilio', + resultField:'cod_local_domic_fam', + where: { + relation:'=', + type:'string', + field:'cod_local_domicilio', + }, +}) + +.addValue({ + name:'cod_home_lighting', + table:'quilombola_eixo_2_ag', + tableField:'cod_iluminacao_domicilio', + resultField:'cod_iluminacao_domic_fam', + where: { + relation:'=', + type:'string', + field:'cod_iluminacao_domicilio', + }, +}) + +.addValue({ + name:'cod_home_trash_destiny', + table:'quilombola_eixo_2_ag', + tableField:'cod_destino_lixo_domicilio', + resultField:'cod_destino_lixo_domic_fam', + where: { + relation:'=', + type:'string', + field:'cod_destino_lixo_domicilio', + }, +}) + +.addValue({ + name:'cod_home_watter_supply', + table:'quilombola_eixo_2_ag', + tableField:'cod_abastecimento_agua_domicilio', + resultField:'cod_abaste_agua_domic_fam', + where: { + relation:'=', + type:'string', + field:'cod_abastecimento_agua_domicilio', + }, +}) + + +.addValue({ + name:'quilombola_family', + table:'quilombola_eixo_2_ag', + tableField:'ind_familia_quilombola', + resultField:'ind_familia_quilombola_fam', + where: { + relation:'=', + type:'string', + field:'ind_familia_quilombola', + }, +}) + + + +.addValue({ + name: 'home_type', + table: 'quilombola_eixo_2_ag', + tableField: 'cod_especie_domicilio', + resultField: 'cod_especie_domic_fam', + where: { + relation: '=', + type: 'string', + field: 'cod_especie_domicilio', + }, +}) + +.addValue({ + name: 'home_location', + table: 'quilombola_eixo_2_ag', + tableField: 'codigo_ibge', + resultField: 'cd_ibge', + where: { + relation: '=', + type: 'string', + field: 'codigo_ibge', + }, +}) + + +.addValue({ + name: 'uf', + table: 'quilombola_eixo_2_ag', + tableField: 'sigla_estado', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_estado', + }, +}) +.addValue({ + name: 'region', + table: 'quilombola_eixo_2_ag', + tableField : 'nome_regiao', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao', + }, +}) + +.addValue({ + name:'cod_sanitary_dump', + table:'quilombola_eixo_2_ag', + tableField:'cod_escoa_sanitario_domicilio', + resultField:'cod_escoa_sanitario_domic_fam', + where: { + relation:'=', + type:'string', + field:'cod_escoa_sanitario_domic_fam', + }, +}) + +; + + +cad_unico.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('SUM(total) AS Total') + .from('quilombola_eixo_2_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = cad_unico; diff --git a/src/libs/routes/SMPPIR/eixo_3.js b/src/libs/routes/SMPPIR/eixo_3.js new file mode 100644 index 0000000000000000000000000000000000000000..0a6edb94d27fb552eb211b6291f919f19beef7eb --- /dev/null +++ b/src/libs/routes/SMPPIR/eixo_3.js @@ -0,0 +1,167 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const cad_unico_count = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'quilombola_eixo_3_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +.addValue({ + name: 'family_type', + table: 'quilombola_eixo_3_ag', + tableField: 'ind_tipo_familia', + resultField: 'ind_parc_mds_fam', + where: { + relation: '=', + type: 'string', + field: 'ind_tipo_familia', + }, +}) + + +.addValue({ + name:'cod_home_bolsa_familia', + table:'quilombola_eixo_3_ag', + tableField:'marca_programa_bolsa_familia', + resultField:'marc_pbf', + where: { + relation:'=', + type:'string', + field:'marca_programa_bolsa_familia', + }, +}) + +.addValue({ + name:'quilombola_family', + table:'quilombola_eixo_3_ag', + tableField:'ind_familia_quilombola', + resultField:'ind_familia_quilombola_fam', + where: { + relation:'=', + type:'string', + field:'ind_familia_quilombola', + }, +}) + +.addValue({ + name:'cod_agriculture_job', + table:'quilombola_eixo_3_ag', + tableField:'atividade_extrativista', + resultField:'cod_agricultura_trab_memb', + where: { + relation:'=', + type:'string', + field:'atividade_extrativista', + }, +}) + + +.addValue({ + name: 'per_capita_income', + table: 'quilombola_eixo_3_ag', + tableField: 'renda_media', + resultField: 'vlr_renda_media_fam', + where: { + relation: '=', + type: 'float', + field: 'renda_media', + }, +}) + +.addValue({ + name: 'home_location', + table: 'quilombola_eixo_3_ag', + tableField: 'codigo_ibge', + resultField: 'cd_ibge', + where: { + relation: '=', + type: 'string', + field: 'codigo_ibge', + }, +}) + +.addValue({ + name: 'uf', + table: 'quilombola_eixo_3_ag', + tableField: 'sigla_estado', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_estado', + }, +}) +.addValue({ + name: 'region', + table: 'quilombola_eixo_3_ag', + tableField : 'nome_regiao', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao', + }, +}) + +; + + +cad_unico_count.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('SUM(total) AS Total') + .from('quilombola_eixo_3_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = cad_unico_count; diff --git a/src/libs/routes/SMPPIR/eixo_4.js b/src/libs/routes/SMPPIR/eixo_4.js new file mode 100644 index 0000000000000000000000000000000000000000..3e9c8539fc2c202e9e72a1ab419c7f0bf2b39228 --- /dev/null +++ b/src/libs/routes/SMPPIR/eixo_4.js @@ -0,0 +1,177 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const cad_unico = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'quilombola_eixo_4_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +.addValue({ + name:'cod_local_home', + table:'quilombola_eixo_4_ag', + tableField:'cod_local_domicilio', + resultField:'cod_local_domic_fam', + where: { + relation:'=', + type:'string', + field:'cod_local_domicilio', + }, +}) + +.addValue({ + name:'quilombola_family', + table:'quilombola_eixo_4_ag', + tableField:'ind_familia_quilombola', + resultField:'ind_familia_quilombola_fam', + where: { + relation:'=', + type:'string', + field:'ind_familia_quilombola', + }, +}) + +.addValue({ + name:'age', + table:'quilombola_eixo_4_ag', + tableField:'idade', + resultField:'idade', + where: { + relation:'=', + type:'string', + field:'idade', + }, +}) + + +.addValue({ + name: 'education_families_conclude', + table: 'quilombola_eixo_4_ag', + tableField: 'concluiu_frequentou', + resultField: 'cod_concluiu_frequentou_memb', + where: { + relation: '=', + type: 'string', + field: 'concluiu_frequentou', + }, +}) +.addValue({ + name: 'education_families_level', + table: 'quilombola_eixo_4_ag', + tableField: 'ano_serie_frequentou', + resultField: 'cod_ano_serie_frequentou_memb', + where: { + relation: '=', + type: 'string', + field: 'ano_serie_frequentou', + }, +}) +.addValue({ + name: 'education_families', + table: 'quilombola_eixo_4_ag', + tableField: 'curso_frequentou', + resultField: 'cod_curso_frequentou_pessoa_memb', + where: { + relation: '=', + type: 'string', + field: 'curso_frequentou', + }, +}) +.addValue({ + name: 'uf', + table: 'quilombola_eixo_4_ag', + tableField: 'sigla_estado', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_estado', + }, +}) + +.addValue({ + name: 'region', + table: 'quilombola_eixo_4_ag', + tableField : 'nome_regiao', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao', + }, +}) + +.addValue({ + name:'gender', + table:'quilombola_eixo_4_ag', + tableField:'genero', + resultField:'genero', + where: { + relation:'=', + type:'string', + field:'genero', + }, +}) + + +; + + +cad_unico.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('SUM(total) AS Total') + .from('quilombola_eixo_4_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = cad_unico; diff --git a/src/libs/routes/SMPPIR/evader.js b/src/libs/routes/SMPPIR/evader.js new file mode 100644 index 0000000000000000000000000000000000000000..d16d8328a1ee0ea7b0fcf83ac751595af7c9dacf --- /dev/null +++ b/src/libs/routes/SMPPIR/evader.js @@ -0,0 +1,179 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const evaderApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'shift', + table: 'evader_ag', + tableField: 'turno_aluno', + resultField: 'ds_turno_aluno', + where: { + relation: '=', + type: 'string', + field: 'turno_aluno', + }, +}) +.addValue({ + name: 'gender', + table: 'evader_ag', + tableField: 'descricao_genero_aluno', + resultField: 'ds_sexo_aluno', + where: { + relation: '=', + type: 'string', + field: 'descricao_genero_aluno', + }, +}) +.addValue({ + name: 'ethnic', + table: 'evader_ag', + tableField: 'cor_raca_aluno', + resultField: 'ds_cor_raca_aluno', + where: { + relation: '=', + type: 'string', + field: 'cor_raca_aluno', + }, +}) +.addValue({ + name: 'course', + table: 'evader_ag', + tableField: 'nome_curso', + resultField: 'no_curso', + where: { + relation: '=', + type: 'string', + field: 'nome_curso', + }, +}) +.addValue({ + name: 'institution', + table: 'evader_ag', + tableField: 'nome_ies', + resultField: 'no_ies', + where: { + relation: '=', + type: 'string', + field: 'nome_ies', + }, +}) +.addValue({ + name: 'institution_cod', + table: 'evader_ag', + tableField: 'cod_ies', + resultField: 'co_ies', + where: { + relation: '=', + type: 'integer', + field: 'cod_ies', + }, +}) +.addValue({ + name: 'year', + table: 'evader_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'min_year', + table: 'evader_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'evader_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'region', + table: 'evader_ag', + tableField: 'nome_regiao_ies', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao_ies', + }, +}) +.addValue({ + name: 'uf', + table: 'evader_ag', + tableField: 'sigla_uf_ies', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_uf_ies', + }, +}); + +evaderApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('evader_ag.ano_censo as no_ano_pesquisa') + .field('SUM(total) AS total') + .from('evader_ag') + .group('evader_ag.ano_censo') + .order('evader_ag.ano_censo'); + next(); +}, query, response('evader')); + +module.exports = evaderApp; diff --git a/src/libs/routes/SMPPIR/extracurricular_activities.js b/src/libs/routes/SMPPIR/extracurricular_activities.js new file mode 100644 index 0000000000000000000000000000000000000000..2a9c892dac1b879cfd84d2a34f44d11f390ba64b --- /dev/null +++ b/src/libs/routes/SMPPIR/extracurricular_activities.js @@ -0,0 +1,124 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const extracurricular_activitiesApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'shift', + table: 'extracurricular_activities_ag', + tableField: 'turno_aluno', + resultField: 'ds_turno_aluno', + where: { + relation: '=', + type: 'string', + field: 'turno_aluno', + }, +}) +.addValue({ + name: 'gender', + table: 'extracurricular_activities_ag', + tableField: 'descricao_genero_aluno', + resultField: 'ds_sexo_aluno', + where: { + relation: '=', + type: 'string', + field: 'descricao_genero_aluno', + }, +}) +.addValue({ + name: 'ethnic', + table: 'extracurricular_activities_ag', + tableField: 'cor_raca_aluno', + resultField: 'ds_cor_raca_aluno', + where: { + relation: '=', + type: 'string', + field: 'cor_raca_aluno', + }, +}) +.addValue({ + name: 'course', + table: 'extracurricular_activities_ag', + tableField: 'nome_curso', + resultField: 'no_curso', + where: { + relation: '=', + type: 'string', + field: 'nome_curso', + }, +}) +.addValue({ + name: 'institution_cod', + table: 'extracurricular_activities_ag', + tableField: 'cod_ies', + resultField: 'co_ies', + where: { + relation: '=', + type: 'integer', + field: 'cod_ies', + }, +}) +.addValue({ + name: 'institution', + table: 'extracurricular_activities_ag', + tableField: 'nome_ies', + resultField: 'no_ies', + where: { + relation: '=', + type: 'string', + field: 'nome_ies', + }, +}); + +extracurricular_activitiesApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('extracurricular_activities_ag.ano_censo as no_ano_pesquisa') + .field('SUM(total) AS total') + .from('extracurricular_activities_ag') + .group('extracurricular_activities_ag.ano_censo') + .order('extracurricular_activities_ag.ano_censo'); + next(); +}, query, response('extracurricular_activities')); + +module.exports = extracurricular_activitiesApp; diff --git a/src/libs/routes/SMPPIR/fies.js b/src/libs/routes/SMPPIR/fies.js new file mode 100644 index 0000000000000000000000000000000000000000..a2844786461bd902c824c32e34d75bfd21ddc7c5 --- /dev/null +++ b/src/libs/routes/SMPPIR/fies.js @@ -0,0 +1,211 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const fiesApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'gender', + table: 'fies_ag', + tableField: 'genero', + resultField: 'ds_sexo', + where: { + relation: '=', + type: 'string', + field: 'genero', + }, +}) +.addValue({ + name: 'ethnic', + table: 'fies_ag', + tableField: 'raca_cor', + resultField: 'ds_raca_cor', + where: { + relation: '=', + type: 'string', + field: 'raca_cor', + }, +}) +.addValue({ + name: 'course', + table: 'fies_ag', + tableField: 'curso', + resultField: 'ds_curso', + where: { + relation: '=', + type: 'string', + field: 'curso', + }, +}) +.addValue({ + name: 'institution', + table: 'fies_ag', + tableField: 'nome_ies', + resultField: 'no_ies', + where: { + relation: '=', + type: 'string', + field: 'nome_ies', + }, +}) +.addValue({ + name: 'institution_cod', + table: 'fies_ag', + tableField: 'codigo_ies', + resultField: 'co_ies', + where: { + relation: '=', + type: 'integer', + field: 'codigo_ies', + }, +}) +.addValue({ + name: 'offer_location', + table: 'fies_ag', + tableField: 'campus', + resultField: 'no_campus', + where: { + relation: '=', + type: 'string', + field: 'campus', + }, +}) +.addValue({ + name: 'offer_location_cod', + table: 'fies_ag', + tableField: 'codigo_campus', + resultField: 'co_campus', + where: { + relation: '=', + type: 'integer', + field: 'codigo_campus', + }, +}) +.addValue({ + name: 'loan', + table: 'fies_ag', + tableField: 'percentual_solicitado_financiamento', + resultField: 'nu_percent_solicitado_financ', + where: { + relation: '=', + type: 'string', + field: 'percentual_solicitado_financiamento', + }, +}) +.addValue({ + name: 'loan_type', + table: 'fies_ag', + tableField: 'tipo_fianca', + resultField: 'tp_fianca', + where: { + relation: '=', + type: 'string', + field: 'tipo_fianca', + }, +}) +.addValue({ + name: 'uf', + table: 'fies_ag', + tableField: 'sigla_uf', + resultField: 'sg_uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_uf', + }, +}) +.addValue({ + name: 'region', + table: 'fies_ag', + tableField: 'regiao_id', + where: { + relation: '=', + type: 'integer', + field: 'regiao_id', + }, +}) +.addValue({ + name: 'year', + table: 'fies_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'min_year', + table: 'fies_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'fies_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +fiesApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('ano_censo as nu_ano') + .field('COUNT(*) AS total') + .from('fies_ag') + .group('ano_censo') + .order('ano_censo'); + next(); +}, query, response('fies')); + +module.exports = fiesApp; diff --git a/src/libs/routes/SMPPIR/graduate.js b/src/libs/routes/SMPPIR/graduate.js new file mode 100644 index 0000000000000000000000000000000000000000..c2b6ec58cd7993a2e396688a081086440aea7245 --- /dev/null +++ b/src/libs/routes/SMPPIR/graduate.js @@ -0,0 +1,179 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const graduateApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'shift', + table: 'graduate_ag', + tableField: 'turno_aluno', + resultField: 'ds_turno_aluno', + where: { + relation: '=', + type: 'string', + field: 'turno_aluno', + }, +}) +.addValue({ + name: 'gender', + table: 'graduate_ag', + tableField: 'descricao_genero_aluno', + resultField: 'ds_sexo_aluno', + where: { + relation: '=', + type: 'string', + field: 'descricao_genero_aluno', + }, +}) +.addValue({ + name: 'ethnic', + table: 'graduate_ag', + tableField: 'cor_raca_aluno', + resultField: 'ds_cor_raca_aluno', + where: { + relation: '=', + type: 'string', + field: 'cor_raca_aluno', + }, +}) +.addValue({ + name: 'course', + table: 'graduate_ag', + tableField: 'nome_curso', + resultField: 'no_curso', + where: { + relation: '=', + type: 'string', + field: 'nome_curso', + }, +}) +.addValue({ + name: 'institution', + table: 'graduate_ag', + tableField: 'nome_ies', + resultField: 'no_ies', + where: { + relation: '=', + type: 'string', + field: 'nome_ies', + }, +}) +.addValue({ + name: 'institution_cod', + table: 'graduate_ag', + tableField: 'cod_ies', + resultField: 'co_ies', + where: { + relation: '=', + type: 'integer', + field: 'cod_ies', + }, +}) +.addValue({ + name: 'year', + table: 'graduate_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'min_year', + table: 'graduate_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'graduate_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'region', + table: 'graduate_ag', + tableField: 'nome_regiao_ies', + resultField: 'region', + where: { + relation: '=', + type: 'string', + field: 'nome_regiao_ies', + }, +}) +.addValue({ + name: 'uf', + table: 'graduate_ag', + tableField: 'sigla_uf_ies', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_uf_ies', + }, +}); + +graduateApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('graduate_ag.ano_censo as no_ano_pesquisa') + .field('SUM(total) AS total') + .from('graduate_ag') + .group('graduate_ag.ano_censo') + .order('graduate_ag.ano_censo'); + next(); +}, query, response('graduate')); + +module.exports = graduateApp; diff --git a/src/libs/routes/SMPPIR/ibge_census.js b/src/libs/routes/SMPPIR/ibge_census.js new file mode 100644 index 0000000000000000000000000000000000000000..100d81956a6ff3fff852be0de5aac80d8ecd19ec --- /dev/null +++ b/src/libs/routes/SMPPIR/ibge_census.js @@ -0,0 +1,228 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const ibge_census = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +let rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'ethnic', + table: 'pessoa_censo', + tableField: 'co_cor_raca', + resultField: 'co_cor_raca', + where: { + relation: '=', + type: 'integer', + field: 'co_cor_raca' + } +}).addValue({ + name: 'gender', + table: 'pessoa_censo', + tableField: 'co_sexo', + resultField: 'co_sexo', + where: { + relation: '=', + type: 'integer', + field: 'co_sexo' + } +}).addValue({ + name: 'religion', + table: 'pessoa_censo', + tableField: 'co_religiao', + resultField: 'co_religiao', + where: { + relation: '=', + type: 'integer', + field: 'co_religiao' + } +}).addValue({ + name: 'income_range', + table: 'pessoa_censo', + tableField: 'nu_sal_min_todos_trabalhos', + resultField: 'nu_sal_min_todos_trabalhos', + where: { + relation: '=', + type: 'double', + field: 'nu_sal_min_todos_trabalhos' + } +}).addValue({ + name: 'age', + table: 'pessoa_censo', + tableField: 'nu_idade_calculada_anos', + resultField: 'nu_idade_calculada_anos', + where: { + relation: '=', + type: 'integer', + field: 'nu_idade_calculada_anos' + } +}).addValue({ + name: 'age_greater_than', + table: 'pessoa_censo', + tableField: 'nu_idade_calculada_anos', + resultField: 'nu_idade_calculada_anos', + where: { + relation: '>=', + type: 'integer', + field: 'nu_idade_calculada_anos' + } +}).addValue({ + name: 'age_lesser_than', + table: 'pessoa_censo', + tableField: 'nu_idade_calculada_anos', + resultField: 'nu_idade_calculada_anos', + where: { + relation: '<=', + type: 'integer', + field: 'nu_idade_calculada_anos' + } +}).addValue({ + name: 'highest_education', + table: 'pessoa_censo', + tableField: 'co_curso_mais_elevado_freq', + resultField: 'co_curso_mais_elevado_freq', + where: { + relation: '=', + type: 'string', + field: 'co_curso_mais_elevado_freq' + } +}).addValue({ + name: 'school_daycare', + table: 'pessoa_censo', + tableField: 'co_freq_escola_creche', + resultField: 'co_freq_escola_creche', + where: { + relation: '=', + type: 'integer', + field: 'co_freq_escola_creche' + } +}).addValue({ + name: 'work_status', + table: 'pessoa_censo', + tableField: 'co_condicao_atividade_semana_ref', + resultField: 'co_condicao_atividade_semana_ref', + where: { + relation: '=', + type: 'integer', + field: 'co_condicao_atividade_semana_ref' + } +}).addValue({ + name: 'education_level', + table: 'pessoa_censo', + tableField: 'co_nivel_instrucao', + resultField: 'co_nivel_instrucao', + where: { + relation: '=', + type: 'integer', + field: 'co_nivel_instrucao' + } +}).addValue({ + name: 'ocupation_position_and_category', + table: 'pessoa_censo', + tableField: 'co_posicao_na_ocupacao_e_categoria_do_emprego', + resultField: 'co_posicao_na_ocupacao_e_categoria_do_emprego', + where: { + relation: '=', + type: 'integer', + field: 'co_posicao_na_ocupacao_e_categoria_do_emprego' + } +}).addValue({ + name: 'home_status', + table: 'domicilio_censo', + tableField: 'co_situacao_dom', + resultField: 'co_situacao_dom', + where: { + relation: '=', + type: 'integer', + field: 'co_situacao_dom' + }, + join: { + primary: ['co_controle','co_uf'], + foreign: ['co_controle','co_uf'], + foreignTable: 'pessoa_censo' + } +}).addValue({ + name: 'work_condition', + table: 'pessoa_censo', + tableField: 'co_condicao_ocupacao_semana_ref', + resultField: 'co_condicao_ocupacao_semana_ref', + where: { + relation: '=', + type: 'integer', + field: 'co_condicao_ocupacao_semana_ref' + } +}).addValue({ + name: 'mensal_home_income_range', + table: 'domicilio_censo', + tableField: 'vl_rendimneto_mensal_domicilio_sal_min_per_capita', + resultField: 'vl_rendimneto_mensal_domicilio_sal_min_per_capita', + where: { + relation: '=', + type: 'integer', + field: 'vl_rendimneto_mensal_domicilio_sal_min_per_capita' + }, + join: { + primary: ['co_controle','co_uf'], + foreign: ['co_controle','co_uf'], + foreignTable: 'pessoa_censo' + } +}).addValue({ + name: 'relation_homeowner', + table: 'pessoa_censo', + tableField: 'co_relacao_responsavel_dom', + resultField: 'co_relacao_responsavel_dom', + where: { + relation: '=', + type: 'integer', + field: 'co_relacao_responsavel_dom' + } +}) + +; + + +ibge_census.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field("COUNT(*) AS Total") + .from("pessoa_censo") + next(); +}, query, response('ibge_census')); + +module.exports = ibge_census; diff --git a/src/libs/routes/SMPPIR/ibge_code.js b/src/libs/routes/SMPPIR/ibge_code.js new file mode 100644 index 0000000000000000000000000000000000000000..b50c16a99c66a8619fcb3d662c7f2e809bb1b61d --- /dev/null +++ b/src/libs/routes/SMPPIR/ibge_code.js @@ -0,0 +1,89 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const pnadApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}).addValue({ + name: 'city_name', + table: 'municipio', + tableField: 'nome', + resultField: 'no_cidade', + where: { + relation: '=', + type: 'string', + field: 'nome', + }, +}).addValue({ + name: 'city_code', + table: 'municipio', + tableField: 'id', + resultField: 'co_cidade', + where: { + relation: '=', + type: 'integer', + field: 'id', + }, +}) +.addValue({ + name: 'state', + table: 'municipio', + tableField: 'estado_id', + resultField: 'sgl_estado', + where: { + relation: '=', + type: 'integer', + field: 'estado_id', + }, +}); + +pnadApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('id as co_cidade') + .field('nome as no_cidade') + .field('estado_id as sgl_estado') + .from('municipio'); + + next(); +}, query, response('pnad')); + +module.exports = pnadApp; diff --git a/src/libs/routes/SMPPIR/institution.js b/src/libs/routes/SMPPIR/institution.js new file mode 100644 index 0000000000000000000000000000000000000000..5387c738587f75371a2e0773c79b5f02852fc053 --- /dev/null +++ b/src/libs/routes/SMPPIR/institution.js @@ -0,0 +1,101 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const institution = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}).addValue({ + name: 'year', + table: 'institution_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}).addValue({ + name: 'min_year', + table: 'institution_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'institution_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'uf', + table: 'institution_ag', + tableField: 'sigla_uf_ies', + resultField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'sigla_uf_ies', + }, +}); + +institution.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('nome_ies AS no_ies') + .field('cod_ies AS co_ies') + .from('institution_ag') + .group('nome_ies') + .group('cod_ies') + .order('nome_ies'); + next(); +}, query, response('institution')); + +module.exports = institution; diff --git a/src/libs/routes/SMPPIR/institutionFIES.js b/src/libs/routes/SMPPIR/institutionFIES.js new file mode 100644 index 0000000000000000000000000000000000000000..f60189abf034bfee4c7de4fa5455a28417ce9a4b --- /dev/null +++ b/src/libs/routes/SMPPIR/institutionFIES.js @@ -0,0 +1,90 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const institution = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}).addValue({ + name: 'year', + table: 'institution_fies_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}).addValue({ + name: 'min_year', + table: 'institution_fies_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'institution_fies_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +institution.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('institution_fies_ag.codigo_ies as co_ies') + .field('institution_fies_ag.nome_ies as no_ies') + .from('institution_fies_ag') + .group('institution_fies_ag.codigo_ies') + .group('institution_fies_ag.nome_ies') + .order('institution_fies_ag.codigo_ies'); + next(); +}, query, response('institutionFIES')); + +module.exports = institution; diff --git a/src/libs/routes/SMPPIR/institutionPROUNI.js b/src/libs/routes/SMPPIR/institutionPROUNI.js new file mode 100644 index 0000000000000000000000000000000000000000..5048bb0d130829cc3a9fec1b2d0aa1e2f395c40f --- /dev/null +++ b/src/libs/routes/SMPPIR/institutionPROUNI.js @@ -0,0 +1,88 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const institution = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}).addValue({ + name: 'year', + table: 'institution_prouni_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}).addValue({ + name: 'min_year', + table: 'institution_prouni_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'institution_prouni_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +institution.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('institution_prouni_ag.nome_ies as nome_ies_bolsa') + .from('institution_prouni_ag') + .group('institution_prouni_ag.nome_ies') + .order('institution_prouni_ag.nome_ies'); + next(); +}, query, response('institutionPROUNI')); + +module.exports = institution; diff --git a/src/libs/routes/SMPPIR/institutionPrivate.js b/src/libs/routes/SMPPIR/institutionPrivate.js new file mode 100644 index 0000000000000000000000000000000000000000..15e85b94d3d7bcfeb1f4425b65280df24dc19484 --- /dev/null +++ b/src/libs/routes/SMPPIR/institutionPrivate.js @@ -0,0 +1,89 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const institution = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}).addValue({ + name: 'year', + table: 'institution_private_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}).addValue({ + name: 'min_year', + table: 'institution_private_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'institution_private_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +institution.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('nome_ies as no_ies') + .field('cod_ies as co_ies') + .from('institution_private_ag') + .group('nome_ies') + .group('cod_ies') + .order('nome_ies'); + next(); +}, query, response('institution')); +module.exports = institution; diff --git a/src/libs/routes/SMPPIR/pnad.js b/src/libs/routes/SMPPIR/pnad.js new file mode 100644 index 0000000000000000000000000000000000000000..153792b2b38ec5c898fe67f78fb335ae83b73665 --- /dev/null +++ b/src/libs/routes/SMPPIR/pnad.js @@ -0,0 +1,157 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const pnadApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'ethnic', + table: 'pnad_ag', + tableField: 'cor_raca_original', + resultField: 'co_cor_raca', + where: { + relation: '=', + type: 'string', + field: 'cor_raca_original', + }, +}) +.addValue({ + name: 'type_of_school', + table: 'pnad_ag', + tableField: 'rede_ensino', + resultField: 'cod_rede_ensino', + where: { + relation: '=', + type: 'string', + field: 'rede_ensino', + }, +}) +.addValue({ + name: 'type_of_public_school', + table: 'pnad_ag', + tableField: 'area_rede_publica_ensino', + resultField: 'co_area_rede_publica_ensino', + where: { + relation: '=', + type: 'string', + field: 'area_rede_publica_ensino', + }, +}) +.addValue({ + name: 'level_of_education', + table: 'pnad_ag', + tableField: 'curso_que_frequenta', + resultField: 'co_curso', + where: { + relation: '=', + type: 'string', + field: 'curso_que_frequenta', + }, +}) +.addValue({ + name: 'uf', + table: 'pnad_ag', + tableField: 'sigla', + resultField: 'sgl_uf', + where: { + relation: '=', + type: 'string', + field: 'sigla', + }, +}) +.addValue({ + name: 'region', + table: 'pnad_ag', + tableField: 'regiao_id', + resultField: 'no_regiao', + where: { + relation: '=', + type: 'integer', + field: 'regiao_id', + }, +}) +.addValue({ + name: 'year', + table: 'pnad_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'min_year', + table: 'pnad_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'pnad_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +pnadApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('ano_censo as nu_ano_referencia') + .field('SUM(total) AS total') + .from('pnad_ag') + .group('ano_censo') + .order('ano_censo'); + next(); +}, query, response('pnad')); + +module.exports = pnadApp; diff --git a/src/libs/routes/SMPPIR/prouni.js b/src/libs/routes/SMPPIR/prouni.js new file mode 100644 index 0000000000000000000000000000000000000000..8a223c1c568ee777c7c4a27c932f15c5ba30812a --- /dev/null +++ b/src/libs/routes/SMPPIR/prouni.js @@ -0,0 +1,179 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const prouniApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'shift', + table: 'prouni_ag', + tableField: 'nome_turno_curso', + resultField: 'nome_turno_curso_bolsa', + where: { + relation: '=', + type: 'string', + field: 'nome_turno_curso', + }, +}) +.addValue({ + name: 'gender', + table: 'prouni_ag', + tableField: 'genero_beneficiario', + resultField: 'sexo_beneficiario_bolsa', + where: { + relation: '=', + type: 'string', + field: 'genero_beneficiario', + }, +}) +.addValue({ + name: 'ethnic', + table: 'prouni_ag', + tableField: 'raca_beneficiario', + resultField: 'raca_beneficiario_bolsa', + where: { + relation: '=', + type: 'string', + field: 'raca_beneficiario', + }, +}) +.addValue({ + name: 'course', + table: 'prouni_ag', + tableField: 'nome_curso', + resultField: 'nome_curso_bolsa', + where: { + relation: '=', + type: 'string', + field: 'nome_curso', + }, +}) +.addValue({ + name: 'institution', + table: 'prouni_ag', + tableField: 'nome_ies', + resultField: 'nome_ies_bolsa', + where: { + relation: '=', + type: 'string', + field: 'nome_ies', + }, +}) +.addValue({ + name: 'scholarship', + table: 'prouni_ag', + tableField: 'tipo', + resultField: 'tipo_bolsa', + where: { + relation: '=', + type: 'string', + field: 'tipo', + }, +}) +.addValue({ + name: 'uf', + table: 'prouni_ag', + tableField: 'sigla_uf_beneficiario', + resultField: 'sigla_uf_beneficiario_bolsa', + where: { + relation: '=', + type: 'string', + field: 'sigla_uf_beneficiario', + }, +}) +.addValue({ + name: 'region', + table: 'prouni_ag', + tableField: 'regiao_beneficiario', + resultField: 'regiao_beneficiario_bolsa', + where: { + relation: '=', + type: 'string', + field: 'regiao_beneficiario', + }, +}) +.addValue({ + name: 'year', + table: 'prouni_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'min_year', + table: 'prouni_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'prouni_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +prouniApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('ano_censo as ano_concessao_bolsa') + .field('SUM(total) AS total') + .from('prouni_ag') + .group('ano_censo') + .order('ano_censo'); + next(); +}, query, response('prouni')); + +module.exports = prouniApp; diff --git a/src/libs/routes/SMPPIR/quilombola_metrics.js b/src/libs/routes/SMPPIR/quilombola_metrics.js new file mode 100644 index 0000000000000000000000000000000000000000..5438e0adf49e3b2e82a6c62008d549e8c4648a07 --- /dev/null +++ b/src/libs/routes/SMPPIR/quilombola_metrics.js @@ -0,0 +1,70 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const quilombola_metrics = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'year', + table: 'cad_unico_quilombola_metrics_ag', + tableField: 'ano_censo', + resultField: 'ano_pesquisa', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) + +; + + +quilombola_metrics.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + console.log(req.sql.toString()); + req.sql.field('*') + .from('cad_unico_quilombola_metrics_ag'); + next(); +}, query, response('cad_unico')); + +module.exports = quilombola_metrics; diff --git a/src/libs/routes/SMPPIR/social_support.js b/src/libs/routes/SMPPIR/social_support.js new file mode 100644 index 0000000000000000000000000000000000000000..4a5752646203a012d2c2fc92fb7b0190a2c3835b --- /dev/null +++ b/src/libs/routes/SMPPIR/social_support.js @@ -0,0 +1,223 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const social_supportApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'shift', + table: 'social_support_ag', + tableField: 'turno_aluno', + resultField: 'ds_turno_aluno', + where: { + relation: '=', + type: 'string', + field: 'turno_aluno', + }, +}) +.addValue({ + name: 'gender', + table: 'social_support_ag', + tableField: 'descricao_genero_aluno', + resultField: 'ds_sexo_aluno', + where: { + relation: '=', + type: 'string', + field: 'descricao_genero_aluno', + }, +}) +.addValue({ + name: 'ethnic', + table: 'social_support_ag', + tableField: 'cor_raca_aluno', + resultField: 'ds_cor_raca_aluno', + where: { + relation: '=', + type: 'string', + field: 'cor_raca_aluno', + }, +}) +.addValue({ + name: 'course', + table: 'social_support_ag', + tableField: 'nome_curso', + resultField: 'no_curso', + where: { + relation: '=', + type: 'string', + field: 'nome_curso', + }, +}) +.addValue({ + name: 'institution_cod', + table: 'social_support_ag', + tableField: 'cod_ies', + resultField: 'co_ies', + where: { + relation: '=', + type: 'integer', + field: 'cod_ies', + }, +}) +.addValue({ + name: 'institution', + table: 'social_support_ag', + tableField: 'nome_ies', + resultField: 'no_ies', + where: { + relation: '=', + type: 'string', + field: 'nome_ies', + }, +}) +.addValue({ + name: 'food_support', + table: 'social_support_ag', + tableField: 'apoio_alimentacao', + resultField: 'in_apoio_alimentacao', + where: { + relation: '=', + type: 'string', + field: 'apoio_alimentacao', + }, +}) +.addValue({ + name: 'support', + table: 'social_support_ag', + tableField: 'apoio_bolsa_permanencia', + resultField: 'in_apoio_bolsa_permanencia', + where: { + relation: '=', + type: 'string', + field: 'apoio_bolsa_permanencia', + }, +}) +.addValue({ + name: 'work_support', + table: 'social_support_ag', + tableField: 'apoio_bolsa_trabalho', + resultField: 'in_apoio_bolsa_trabalho', + where: { + relation: '=', + type: 'string', + field: 'apoio_bolsa_trabalho', + }, +}) +.addValue({ + name: 'courseware_support', + table: 'social_support_ag', + tableField: 'apoio_material_didatico', + resultField: 'in_apoio_material_didatico', + where: { + relation: '=', + type: 'string', + field: 'apoio_material_didatico', + }, +}) +.addValue({ + name: 'housing_support', + table: 'social_support_ag', + tableField: 'apoio_moradia', + resultField: 'in_apoio_moradia', + where: { + relation: '=', + type: 'string', + field: 'apoio_moradia', + }, +}) +.addValue({ + name: 'transport_support', + table: 'social_support_ag', + tableField: 'apoio_transporte', + resultField: 'in_apoio_transporte', + where: { + relation: '=', + type: 'string', + field: 'apoio_transporte', + }, +}) +.addValue({ + name: 'year', + table: 'social_support_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'min_year', + table: 'social_support_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'social_support_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +social_supportApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('social_support_ag.ano_censo as no_ano_pesquisa') + .field('SUM(total) AS total') + .from('social_support_ag') + .group('social_support_ag.ano_censo') + .order('social_support_ag.ano_censo'); + next(); +}, query, response('social_support')); + +module.exports = social_supportApp; diff --git a/src/libs/routes/SMPPIR/student_loans.js b/src/libs/routes/SMPPIR/student_loans.js new file mode 100644 index 0000000000000000000000000000000000000000..faf9b5564d8a6e63c8045beba73736e5100bd1ac --- /dev/null +++ b/src/libs/routes/SMPPIR/student_loans.js @@ -0,0 +1,300 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const student_loansApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +const rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true, +}).addField({ + name: 'dims', + field: true, + where: false, +}) +.addValue({ + name: 'shift', + table: 'student_loans_ag', + tableField: 'turno_aluno', + resultField: 'ds_turno_aluno', + where: { + relation: '=', + type: 'string', + field: 'turno_aluno', + }, +}) +.addValue({ + name: 'gender', + table: 'student_loans_ag', + tableField: 'descricao_genero_aluno', + resultField: 'ds_sexo_aluno', + where: { + relation: '=', + type: 'string', + field: 'descricao_genero_aluno', + }, +}) +.addValue({ + name: 'ethnic', + table: 'student_loans_ag', + tableField: 'cor_raca_aluno', + resultField: 'ds_cor_raca_aluno', + where: { + relation: '=', + type: 'string', + field: 'cor_raca_aluno', + }, +}) +.addValue({ + name: 'course', + table: 'student_loans_ag', + tableField: 'nome_curso', + resultField: 'no_curso', + where: { + relation: '=', + type: 'string', + field: 'nome_curso', + }, +}) +.addValue({ + name: 'institution_cod', + table: 'student_loans_ag', + tableField: 'cod_ies', + resultField: 'co_ies', + where: { + relation: '=', + type: 'integer', + field: 'cod_ies', + }, +}) +.addValue({ + name: 'institution', + table: 'student_loans_ag', + tableField: 'nome_ies', + resultField: 'no_ies', + where: { + relation: '=', + type: 'string', + field: 'nome_ies', + }, +}) +.addValue({ + name: 'refund_fies', + table: 'student_loans_ag', + tableField: 'financiamento_reembolsavel_fies', + resultField: 'in_fin_reemb_fies', + where: { + relation: '=', + type: 'string', + field: 'financiamento_reembolsavel_fies', + }, +}) +.addValue({ + name: 'refund_state', + table: 'student_loans_ag', + tableField: 'financiamento_reembolsavel_estadual', + resultField: 'in_fin_reemb_estadual', + where: { + relation: '=', + type: 'string', + field: 'financiamento_reembolsavel_estadual', + }, +}) +.addValue({ + name: 'refund_city', + table: 'student_loans_ag', + tableField: 'financiamento_reembolsavel_municipal', + resultField: 'in_fin_reemb_municipal', + where: { + relation: '=', + type: 'string', + field: 'financiamento_reembolsavel_municipal', + }, +}) +.addValue({ + name: 'refund_edu_inst', + table: 'student_loans_ag', + tableField: 'financiamento_reembolsavel_prog_ies', + resultField: 'in_fin_reemb_prog_ies', + where: { + relation: '=', + type: 'string', + field: 'financiamento_reembolsavel_prog_ies', + }, +}) +.addValue({ + name: 'refund_org', + table: 'student_loans_ag', + tableField: 'financiamento_reembolsavel_entidade_externa', + resultField: 'in_fin_reemb_ent_externa', + where: { + relation: '=', + type: 'string', + field: 'financiamento_reembolsavel_entidade_externa', + }, +}) +.addValue({ + name: 'refund_others', + table: 'student_loans_ag', + tableField: 'financiamento_reembolsavel_outra', + resultField: 'in_fin_reemb_outra', + where: { + relation: '=', + type: 'string', + field: 'financiamento_reembolsavel_outra', + }, +}) +.addValue({ + name: 'no_refund_prouni_integral', + table: 'student_loans_ag', + tableField: 'financiamento_naoreembolsavel_prouni_integral', + resultField: 'in_fin_naoreemb_prouni_integr', + where: { + relation: '=', + type: 'string', + field: 'financiamento_naoreembolsavel_prouni_integral', + }, +}) +.addValue({ + name: 'no_refund_prouni_partial', + table: 'student_loans_ag', + tableField: 'financiamento_naoreembolsavel_prouni_parcial', + resultField: 'in_fin_naoreemb_prouni_parcial', + where: { + relation: '=', + type: 'string', + field: 'financiamento_naoreembolsavel_prouni_parcial', + }, +}) +.addValue({ + name: 'no_refund_state', + table: 'student_loans_ag', + tableField: 'financiamento_naoreembolsavel_estadual', + resultField: 'in_fin_naoreemb_estadual', + where: { + relation: '=', + type: 'string', + field: 'financiamento_naoreembolsavel_estadual', + }, +}) +.addValue({ + name: 'no_refund_city', + table: 'student_loans_ag', + tableField: 'financiamento_naoreembolsavel_municipal', + resultField: 'in_fin_naoreemb_municipal', + where: { + relation: '=', + type: 'string', + field: 'financiamento_naoreembolsavel_municipal', + }, +}) +.addValue({ + name: 'no_refund_edu_inst', + table: 'student_loans_ag', + tableField: 'financiamento_naoreembolsavel_prog_ies', + resultField: 'in_fin_naoreemb_prog_ies', + where: { + relation: '=', + type: 'string', + field: 'financiamento_naoreembolsavel_prog_ies', + }, +}) +.addValue({ + name: 'no_refund_org', + table: 'student_loans_ag', + tableField: 'financiamento_naoreembolsavel_entidade_externa', + resultField: 'in_fin_naoreemb_ent_externa', + where: { + relation: '=', + type: 'string', + field: 'financiamento_naoreembolsavel_entidade_externa', + }, +}) +.addValue({ + name: 'no_refund_others', + table: 'student_loans_ag', + tableField: 'financiamento_naoreembolsavel_outra', + resultField: 'in_fin_naoreemb_outra', + where: { + relation: '=', + type: 'string', + field: 'financiamento_naoreembolsavel_outra', + }, +}) +.addValue({ + name: 'year', + table: 'student_loans_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'min_year', + table: 'student_loans_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo', + }, +}) +.addValue({ + name: 'max_year', + table: 'student_loans_ag', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo', + }, +}); + +student_loansApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field('student_loans_ag.ano_censo as no_ano_pesquisa') + .field('SUM(total) AS total') + .from('student_loans_ag') + .group('student_loans_ag.ano_censo') + .order('student_loans_ag.ano_censo'); + next(); +}, query, response('student_loans')); + +module.exports = student_loansApp; diff --git a/src/libs/routes/SMPPIR/vacancy.js b/src/libs/routes/SMPPIR/vacancy.js new file mode 100644 index 0000000000000000000000000000000000000000..0844430a770afb0fe0ff72a9c0b192df63ba9628 --- /dev/null +++ b/src/libs/routes/SMPPIR/vacancy.js @@ -0,0 +1,158 @@ +/* +Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR + +This file is part of SMPPIR-Node. + +SMPPIR-Node is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +SMPPIR-Node is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with SMPPIR-Node. If not, see <https://www.gnu.org/licenses/>. +*/ + + + +const express = require('express'); + +const vacancyApp = express.Router(); + +const libs = `${process.cwd()}/libs`; + +const squel = require('squel'); + +const query = require(`${libs}/middlewares/query`).query; + +const response = require(`${libs}/middlewares/response`); + +const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); + +let rqf = new ReqQueryFields(); + +rqf.addField({ + name: 'filter', + field: false, + where: true +}).addField({ + name: 'dims', + field: true, + where: false +}).addValue({ + name: 'uf', + table: 'vagas_ofertadas', + tableField: 'uf', + where: { + relation: '=', + type: 'string', + field: 'uf' + } +}).addValue({ + name: 'region', + table: 'vagas_ofertadas', + tableField: 'regiao', + where: { + relation: '=', + type: 'string', + field: 'regiao' + } +}).addValue({ + name: 'cod_ies', + table: 'vagas_ofertadas', + tableField: 'cod_ies', + where: { + relation: '=', + type: 'integer', + field: 'cod_ies' + } +}).addValue({ + name: 'campus', + table: 'vagas_ofertadas', + tableField: 'campus', + where: { + relation: '=', + type: 'string', + field: 'campus' + } +}).addValue({ + name: 'course', + table: 'vagas_ofertadas', + tableField: 'curso', + where: { + relation: '=', + type: 'string', + field: 'curso' + } +}).addValue({ + name: 'shift', + table: 'vagas_ofertadas', + tableField: 'turno', + where: { + relation: '=', + type: 'string', + field: 'turno' + } +}).addValue({ + name: 'name_ies', + table: 'vagas_ofertadas', + tableField: 'nome_ies', + where: { + relation: '=', + type: 'string', + field: 'nome_ies' + } +}).addValue({ + name: 'year', + table: 'vagas_ofertadas', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '=', + type: 'integer', + field: 'ano_censo' + } +}).addValue({ + name: 'min_year', + table: 'vagas_ofertadas', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '>=', + type: 'integer', + field: 'ano_censo' + } +}).addValue({ + name: 'max_year', + table: 'vagas_ofertadas', + tableField: 'ano_censo', + resultField: 'year', + where: { + relation: '<=', + type: 'integer', + field: 'ano_censo' + } +}); + +vacancyApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { + req.sql.field("SUM (CASE WHEN vagas_ofertadas.vagas_ampla_concorrencia_nao_pcd > 0 THEN vagas_ofertadas.vagas_ampla_concorrencia_nao_pcd ELSE 0 END) AS total_vagas_ampla_concorrencia_nao_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.vagas_ampla_concorrencia_pcd > 0 THEN vagas_ofertadas.vagas_ampla_concorrencia_pcd ELSE 0 END) AS total_vagas_ampla_concorrencia_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.vagas_cotas_renda_baixa_ppi_nao_pcd > 0 THEN vagas_ofertadas.vagas_cotas_renda_baixa_ppi_nao_pcd ELSE 0 END) AS total_vagas_cotas_renda_baixa_ppi_nao_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.vagas_cotas_renda_baixa_ppi_pcd > 0 THEN vagas_ofertadas.vagas_cotas_renda_baixa_ppi_pcd ELSE 0 END) AS total_vagas_cotas_renda_baixa_ppi_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.vagas_cotas_renda_baixa_outros_nao_pcd > 0 THEN vagas_ofertadas.vagas_cotas_renda_baixa_outros_nao_pcd ELSE 0 END) AS total_vagas_cotas_renda_baixa_outros_nao_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.vagas_cotas_renda_baixa_outros_pcd > 0 THEN vagas_ofertadas.vagas_cotas_renda_baixa_outros_pcd ELSE 0 END) AS total_vagas_cotas_renda_baixa_outros_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.vagas_cotas_renda_alta_ppi_nao_pcd > 0 THEN vagas_ofertadas.vagas_cotas_renda_alta_ppi_nao_pcd ELSE 0 END) AS total_vagas_cotas_renda_alta_ppi_nao_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.vagas_cotas_renda_alta_ppi_pcd > 0 THEN vagas_ofertadas.vagas_cotas_renda_alta_ppi_pcd ELSE 0 END) AS total_vagas_cotas_renda_alta_ppi_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.vagas_cotas_renda_alta_outros_nao_pcd > 0 THEN vagas_ofertadas.vagas_cotas_renda_alta_outros_nao_pcd ELSE 0 END) AS total_vagas_cotas_renda_alta_outros_nao_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.vagas_cotas_renda_alta_outros_pcd > 0 THEN vagas_ofertadas.vagas_cotas_renda_alta_outros_pcd ELSE 0 END) AS total_vagas_cotas_renda_alta_outros_pcd") + .field("SUM (CASE WHEN vagas_ofertadas.total_pcd > 0 THEN vagas_ofertadas.total_pcd ELSE 0 END) AS total_total_pcd") + .from("vagas_ofertadas") + next(); +}, query, response('evader')); + +module.exports = vacancyApp; \ No newline at end of file diff --git a/src/libs/routes/api.js b/src/libs/routes/api.js index 5141ec78f74d19f1c0e7fb5031f355a90e249d04..fd1bae834c25b56b570ed709cf30a70a6add8a43 100644 --- a/src/libs/routes/api.js +++ b/src/libs/routes/api.js @@ -26,131 +26,104 @@ const libs = `${process.cwd()}/libs`; const config = require(`${libs}/config`); -const classes = require('./class'); -const enrollment = require('./enrollment'); +// SMPPIR Routes -const state = require('./state'); +const evader = require(`${libs}/routes/SMPPIR/evader`); -const region = require('./region'); +const graduate = require(`${libs}/routes/SMPPIR/graduate`); -const city = require('./city'); +const prouni = require(`${libs}/routes/SMPPIR/prouni`); -const school = require('./school'); +const fies = require(`${libs}/routes/SMPPIR/fies`); -const simulation = require('./simulation'); +const pnad = require(`${libs}/routes/SMPPIR/pnad`); -const user = require('./user'); +const social_support = require(`${libs}/routes/SMPPIR/social_support`); -const classroom = require('./classroom'); +const admission = require(`${libs}/routes/SMPPIR/admission`); -const teacher = require('./teacher'); +const student_loans = require(`${libs}/routes/SMPPIR/student_loans`); -const idhme = require('./idhme'); +const extracurricular_activities = require(`${libs}/routes/SMPPIR/extracurricular_activities`); -const pibpercapita = require('./pibpercapita') +const institution = require(`${libs}/routes/SMPPIR/institution`); -const population = require('./population') +const institutionPROUNI = require(`${libs}/routes/SMPPIR/institutionPROUNI`); -const rateSchool = require('./rateSchool') +const institutionFIES = require(`${libs}/routes/SMPPIR/institutionFIES`); -const glossEnrollmentRatio = require('./glossEnrollmentRatio') +const institutionPrivate = require(`${libs}/routes/SMPPIR/institutionPrivate`); -const liquidEnrollmentRatio = require('./liquidEnrollmentRatio') +const coursePROUNI = require(`${libs}/routes/SMPPIR/coursePROUNI`); -const idhm = require('./idhm'); +const courseFIES = require(`${libs}/routes/SMPPIR/courseFIES`); -const idhmr = require('./idhmr'); +const course = require(`${libs}/routes/SMPPIR/course`); -const idhml = require('./idhml'); +const ibge_census = require(`${libs}/routes/SMPPIR/ibge_census`); -const oauth2 = require(`${libs}/middlewares/oauth2`); +const ibge_code = require(`${libs}/routes/SMPPIR/ibge_code`); -const verifyToken = require(`${libs}/routes/verifyToken`); +const vacancies = require(`${libs}/routes/SMPPIR/vacancy`); -const resetToken = require(`${libs}/routes/resetToken`); +const eixo_2 = require(`${libs}/routes/SMPPIR/eixo_2`) -const educationYears = require(`${libs}/routes/educationYears`); +const eixo_3 = require(`${libs}/routes/SMPPIR/eixo_3`) -const downloads = require(`${libs}/routes/downloads`); +const eixo_4 = require(`${libs}/routes/SMPPIR/eixo_4`) -const infrastructure = require(`${libs}/routes/infrastructure`); +const african_rights = require(`${libs}/routes/SMPPIR/african_rights`) -const schoolInfrastructure = require(`${libs}/routes/schoolInfrastructure`); +const african_culture = require(`${libs}/routes/SMPPIR/african_culture`) -const distributionFactor = require(`${libs}/routes/distributionFactor`); +const african_sustentability = require(`${libs}/routes/SMPPIR/african_sustentability`) -const siope = require(`${libs}/routes/siope`); +const quilombola_metrics = require(`${libs}/routes/SMPPIR/quilombola_metrics`) -const verifyTeacher = require(`${libs}/routes/portalMec`); +const ciganos_rights = require(`${libs}/routes/SMPPIR/ciganos_rights`) -const outOfSchool = require(`${libs}/routes/outOfSchool`); +const ciganos_culture = require(`${libs}/routes/SMPPIR/ciganos_culture`) -const classroomCount = require(`${libs}/routes/classroomCount`); +const ciganos_sustentability = require(`${libs}/routes/SMPPIR/ciganos_sustentability`) -const transport = require(`./transport`); - -const auxiliar = require(`${libs}/routes/auxiliar`); - -const dailyChargeAmount = require(`${libs}/routes/dailyChargeAmount`); - -const cub = require(`${libs}/routes/cub`); - -const classCount = require(`${libs}/routes/classCount`); - -const portalMecInep = require(`${libs}/routes/portalMecInep`); - -const enrollmentProjection = require(`${libs}/routes/enrollmentProjection`); - -const employees = require(`${libs}/routes/employees`); - -const financial = require(`${libs}/routes/financial`); api.get('/', (req, res) => { - res.json({ msg: 'SimCAQ API is running' }); + res.json({ msg: 'SMPPIR API is running' }); }); // mount API routes -api.use('/user', user); -api.use('/simulation', simulation); -api.use('/class', classes); -api.use('/enrollment', enrollment); -api.use('/state', state); -api.use('/region', region); -api.use('/city', city); -api.use('/school', school); -api.use('/classroom', classroom); -api.use('/teacher', teacher); -api.use('/idhmr', idhmr); -api.use('/idhm', idhm); -api.use('/idhme', idhme); -api.use('/pibpercapita', pibpercapita); -api.use('/population', population); -api.use('/rate_school', rateSchool); -api.use('/gloss_enrollment_ratio', glossEnrollmentRatio); -api.use('/liquid_enrollment_ratio', liquidEnrollmentRatio); -api.use('/idhml', idhml); -api.use('/auth/token', oauth2.token); -api.use('/verify', verifyToken); -api.use('/reset', resetToken); -api.use('/education_years', educationYears); -api.use('/downloads', downloads); -api.use('/infrastructure', infrastructure); -api.use('/school_infrastructure', schoolInfrastructure); -api.use('/distribution_factor', distributionFactor); -api.use('/siope', siope); -api.use('/out_of_school', outOfSchool); -api.use('/classroom_count', classroomCount); -api.use('/daily_charge_amount', dailyChargeAmount); -api.use('/transport', transport); -api.use('/cub', cub); -api.use('/auxiliar', auxiliar); -api.use('/verify_teacher', verifyTeacher); -api.use('/class_count', classCount); -api.use('/portal_mec_inep', portalMecInep); -api.use('/enrollment_projection', enrollmentProjection); -api.use('/employees', employees); -api.use('/financial', financial); - - -module.exports = api; +// SMPPIR Routes + +api.use('/evader', evader); +api.use('/graduate', graduate); +api.use('/prouni', prouni); +api.use('/fies', fies); +api.use('/pnad', pnad); +api.use('/social_support', social_support); +api.use('/student_loans', student_loans); +api.use('/admission', admission); +api.use('/extracurricular_activities', extracurricular_activities); +api.use('/institution', institution); +api.use('/institutionprouni', institutionPROUNI); +api.use('/institutionstudent_loans', institutionPrivate); +api.use('/institutionfies', institutionFIES); +api.use('/course', course); +api.use('/courseprouni', coursePROUNI); +api.use('/coursefies', courseFIES); +api.use('/ibge_census', ibge_census); +api.use('/ibge_code', ibge_code); +api.use('/vacancy', vacancies); +api.use('/eixo_2', eixo_2); +api.use('/eixo_3', eixo_3); +api.use('/eixo_4', eixo_4); +api.use('/african_rights', african_rights); +api.use('/african_culture', african_culture); +api.use('/african_sustentability', african_sustentability); +api.use(`/quilombola_metrics`,quilombola_metrics) +api.use('/ciganos_rights', ciganos_rights); +api.use('/ciganos_culture', ciganos_culture); +api.use('/ciganos_sustentability', ciganos_sustentability); + + +module.exports = api; \ No newline at end of file diff --git a/src/libs/routes/auxiliar.js b/src/libs/routes/auxiliar.js deleted file mode 100644 index 74e05c77be3b38ca81619635a19bb37b6aa9db9e..0000000000000000000000000000000000000000 --- a/src/libs/routes/auxiliar.js +++ /dev/null @@ -1,369 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const auxiliarApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -auxiliarApp.use(cache('15 day')); - -auxiliarApp.get('/year_range', (req, res, next) => { - req.sql.from('docente') - .field('MIN(docente.ano_censo)', 'start_year') - .field('MAX(docente.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -auxiliarApp.get('/years', (req, res, next) => { - req.sql.from('docente'). - field('DISTINCT docente.ano_censo', 'year'); - next(); -}, query, response('years')); - -auxiliarApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'docente\''); - next(); -}, query, response('source')) - -auxiliarApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -auxiliarApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -auxiliarApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -auxiliarApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -auxiliarApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 11; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -auxiliarApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -auxiliarApp.get('/ethnic_group', (req, res, next) => { - req.result = []; - for(let i = 0; i <=5; ++i) { - req.result.push({ - id: i, - name: id2str.ethnicGroup(i) - }); - } - next(); -}, response('ethnic_group')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: 'docente', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'docente', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'education_level_mod', - table: 'docente', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_regiao_id', - foreignTable: 'docente' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_estado_id', - foreignTable: 'docente' - } -}).addValue({ - name: 'rural_location', - table: 'docente', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_municipio_id', - foreignTable: 'docente' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_municipio_id', - foreignTable: 'docente' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'docente' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'docente' - } -}, 'filter').addValue({ - name: 'location', - table: 'docente', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'min_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'gender', - table: 'docente', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'ethnic_group', - table: 'docente', - tableField: 'cor_raca', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca' - } -}); - -// LDE -auxiliarApp.get('/', rqf.parse(), (req, res, next) => { - req.sql.field('COUNT(DISTINCT docente.id)', 'total') - .field("'Brasil'", 'name') - .field('docente.ano_censo', 'year') - .from('docente') - .group('docente.ano_censo') - .order('docente.ano_censo') - .where('(docente.tipo_turma_id <= 3 AND docente.tipo_docente = 2)'); - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('auxiliar')); - -// SimCAQ -auxiliarApp.get('/count', rqf.parse(), (req, res, next) => { - req.sql.field('COUNT(DISTINCT docente.id)', 'total') - .field("'Brasil'", 'name') - .field('docente.ano_censo', 'year') - .from('docente') - .group('docente.ano_censo') - .order('docente.ano_censo') - .where('(docente.tipo_turma_id <= 3 AND docente.dependencia_adm_id <= 3 AND docente.tipo_docente = 2)'); - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('auxiliar')); - -auxiliarApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('docente', 'mapping_docente')); - -module.exports = auxiliarApp; diff --git a/src/libs/routes/city.js b/src/libs/routes/city.js deleted file mode 100644 index 9342f64c92dbd1d1f1b3187606f7cd81fa00aa5d..0000000000000000000000000000000000000000 --- a/src/libs/routes/city.js +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const cityApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -cityApp.use(cache('15 day')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addValue({ - name: 'id', - table: 'municipio', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'municipio' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'municipio' - } -}).addField({ - name: 'search', - field: false, - where: true -}).addValueToField({ - name: 'name', - table: 'municipio', - tableField: 'nome', - where: { - relation: 'LIKE', - type: 'string', - field: 'nome' - } -}, 'search');; - -// Return all cities -cityApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.from('municipio') - .field('municipio.nome', 'name') - .field('municipio.id') - .field('municipio.estado_id', 'state_id'); - next(); -}, query, response('city')); - -module.exports = cityApp; diff --git a/src/libs/routes/class.js b/src/libs/routes/class.js deleted file mode 100644 index 9819a23ba4483c6b1c72c3a3a32f2c75da97f245..0000000000000000000000000000000000000000 --- a/src/libs/routes/class.js +++ /dev/null @@ -1,394 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const classApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const passport = require('passport'); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqfCount = new ReqQueryFields(); - -classApp.use(cache('15 day')); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -classApp.get('/year_range', (req, res, next) => { - req.sql.from('turma') - .field('MIN(turma.ano_censo)', 'start_year') - .field('MAX(turma.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -classApp.get('/years', (req, res, next) => { - req.sql.from('turma') - .field('DISTINCT turma.ano_censo', 'year'); - next(); -}, query, response('years')); - -classApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'turma\''); - next(); -}, query, response('source')); - -classApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -classApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -// Returns all adm dependencies -classApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -classApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -// Returns all periods avaible -classApp.get('/period', (req, res, next) => { - req.result = []; - for(let i=1; i <= 3; ++i) { - req.result.push({ - id: i, - name: id2str.period(i) - }); - } - req.result.push({ - id: 99, - name: id2str.period(99) - }); - next(); -}, response('period')); - -// Returns integral-time avaible -classApp.get('/integral_time', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Disponível'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('integral_time')); - -// Returns all educational levels avaible -classApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <=11; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -classApp.get('/education_level_short', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Ensino Fundamental - anos iniciais'}, - {id: 4, name: 'Ensino Fundamental - anos finais'}, - {id: 5, name: 'Ensino Médio'}, - {id: 6, name: 'EJA'}, - {id: 7, name: 'EE exclusiva'} - ]; - next(); -}, response('education_level_short')); - -rqfCount.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}, 'filter').addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'min_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name:'adm_dependency', - table: 'turma', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'location', - table: 'turma', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'turma', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name:'education_level_mod', - table: 'turma', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'education_level_short', - table: 'turma', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'turma', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name:'period', - table: 'turma', - tableField: 'turma_turno_id', - resultField: 'period_id', - where: { - relation: '=', - type: 'integer', - field: 'turma_turno_id' - } -}).addValue({ - name:'integral_time', - table: 'turma', - tableField: 'tempo_integral', - resultField: 'integral_time_id', - where: { - relation: '=', - type: 'boolean', - field: 'tempo_integral' - } -}).addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'turma' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'turma' - } -}, 'filter'); - - -classApp.get('/', rqfCount.parse(), rqfCount.build(), (req, res, next) => { - req.sql.field('COUNT(turma.id)', 'total') - .field("'Brasil'", 'name') - .field('turma.ano_censo', 'year') - .from('turma') - .group('turma.ano_censo') - .order('turma.ano_censo') - .where('turma.tipo_turma_id = 0 OR turma.tipo_turma_id = 1 OR turma.tipo_turma_id = 2 OR turma.tipo_turma_id = 3'); - next(); -}, query, addMissing(rqfCount), id2str.transform(), response('class')); - -classApp.get('/download', passport.authenticate('bearer', { session: false }), rqfCount.parse(), rqfCount.build(), download('turma', 'mapping_turma')); - -module.exports = classApp; diff --git a/src/libs/routes/classCount.js b/src/libs/routes/classCount.js deleted file mode 100644 index c7fa1d036eaa9f1b66988c52a14c1a8645f41ed1..0000000000000000000000000000000000000000 --- a/src/libs/routes/classCount.js +++ /dev/null @@ -1,434 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const classCountApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}, 'filter') -.addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'min_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name:'adm_dependency', - table: 'turma', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'location', - table: 'turma', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'turma', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name:'education_level_mod', - table: 'turma', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name:'education_level_short', - table: 'turma', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'turma', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'turma' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'turma' - } -}, 'filter'); - -classCountApp.get('/year_range', (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -classCountApp.get('/years', (req, res, next) => { - req.sql.from('escola') - .field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -classCountApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -classCountApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -classCountApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -classCountApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -classCountApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 10; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -classCountApp.get('/education_level_short', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 7; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelShort(i) - }); - } - req.result.push({ - id: 99, - name: id2str.educationLevelShort(99) - }); - next(); -}, response('education_level_short')); - -classCountApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'turma\''); - next(); -}, query, response('source')); - -// Se a dimensão obrigatória do LDE (etapa de ensino) possui alguma etapa sem nenhum valor, então é criado um objeto -// com média 0.0 e é inserido no resultado. Usada para não quebrar a sequência de etapas na tabela do LDE. -function addNullFields(result) { - const firstYear = result[0].year; - var obj = result.filter(res => res.year == firstYear); - var prevFirstDimId = obj[0]; - obj.forEach((d) => { - if((d["education_level_mod_id"] > prevFirstDimId["education_level_mod_id"]) && (prevFirstDimId["education_level_mod_id"] != 10) && - (d["education_level_mod_id"] != prevFirstDimId["education_level_mod_id"] + 1)) { - let newObj = {}; - Object.keys(prevFirstDimId).forEach((key) => { - newObj[key] = prevFirstDimId[key]; - }); - newObj.education_level_mod_id = d["education_level_mod_id"] - 1; - newObj.education_level_mod_name = id2str.educationLevelMod(d["education_level_mod_id"] - 1); - newObj.average = 0.0; - result.splice(result.indexOf(prevFirstDimId) + 1, 0, newObj); - } - prevFirstDimId = d; - }); -} - -// SimCAQ -classCountApp.get('/count', rqf.parse(), (req, res, next) => { - req.sql.field("'Brasil'", 'name') - .field('turma.ano_censo', 'year') - .field('AVG(turma.num_matricula)', 'average') - .field('MEDIAN(turma.num_matricula)', 'median') - .field('STDDEV_POP(turma.num_matricula)', 'stddev') - .field('QUANTILE(turma.num_matricula, 0.25)', 'first_qt') - .field('QUANTILE(turma.num_matricula, 0.75)', 'third_qt') - .from('turma') - .group('turma.ano_censo') - .order('turma.ano_censo') - .where('turma.tipo_turma_id = 0 AND turma.dependencia_adm_id <= 3 AND ((turma.etapa_resumida >= 1 AND turma.etapa_resumida <= 7) OR turma.etapa_resumida = 99)'); - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('class_count')); - -// LDE -classCountApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - // Faz a consulta do número de alunos pelas dimensões - if(("education_level_mod" in req.dims) || ("education_level_mod" in req.filter) || ("education_level_short" in req.dims)) { - req.sql.field("'Brasil'", 'name') - .field('turma.ano_censo', 'year') - .field('AVG(turma.num_matricula)', 'average') - .field('MEDIAN(turma.num_matricula)', 'median') - .field('STDDEV_POP(turma.num_matricula)', 'stddev') - .field('QUANTILE(turma.num_matricula, 0.25)', 'first_qt') - .field('QUANTILE(turma.num_matricula, 0.75)', 'third_qt') - .from('turma') - .group('turma.ano_censo') - .order('turma.ano_censo') - .where('turma.tipo_turma_id = 0 AND turma.etapas_mod_ensino_segmento_id >= 1 AND turma.etapas_mod_ensino_segmento_id <= 10'); - next(); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.partial = []; - - // Caso tenha apenas uma dimensão, o indicador possuirá uma linha de total - if((req.dims) && (req.dims.size == 1)) { - req.partial = req.result; - - // A linha de total deverá conter o valor total do ano que está no banco de dados, então usa o mesmo filtro de anos da consulta anterior - let yearFilter = {}; - if("min_year" in req.filter) - yearFilter.min_year = req.filter.min_year; - if("max_year" in req.filter) - yearFilter.max_year = req.filter.max_year; - - // Faz a consulta sem dimensões, do total do(s) ano(s) escolhido(s) - req.resetSql(); - req.dims = {}; - req.filter = yearFilter; - req.sql.field("'Brasil'", 'name') - .field('turma.ano_censo', 'year') - .field('AVG(turma.num_matricula)', 'average') - .field('MEDIAN(turma.num_matricula)', 'median') - .field('STDDEV_POP(turma.num_matricula)', 'stddev') - .field('QUANTILE(turma.num_matricula, 0.25)', 'first_qt') - .field('QUANTILE(turma.num_matricula, 0.75)', 'third_qt') - .from('turma') - .group('turma.ano_censo') - .order('turma.ano_censo') - .where('turma.tipo_turma_id = 0 AND turma.etapas_mod_ensino_segmento_id >= 1 AND turma.etapas_mod_ensino_segmento_id <= 10'); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), (req, res, next) => { - // Se tem apenas uma dimensão - if(req.partial.length > 0) { - const yearClassCount = req.result; - req.result = req.partial; - - // Como a linha de total deve aparecer em um caso específico, ela é adicionada junto com a dimensão obrigatória - yearClassCount.forEach((result) => { - let obj = {}; - obj = result; - obj.education_level_mod_name = "Total"; - req.result.push(obj); - }) - } - // Caso tenha mais de uma dimensão, retorna a consulta só pelas dimensões, sem linha de total - else - addNullFields(req.result); - - next(); -}, response('class_count')); - -module.exports = classCountApp; diff --git a/src/libs/routes/classroom.js b/src/libs/routes/classroom.js deleted file mode 100644 index a445e9412d7edc8337186e4cc6b448eaaded7961..0000000000000000000000000000000000000000 --- a/src/libs/routes/classroom.js +++ /dev/null @@ -1,253 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const classroomApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -let rqfCount = new ReqQueryFields(); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -classroomApp.get('/year_range', (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -classroomApp.get('/years', (req, res, next) => { - req.sql.from('escola') - .field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -classroomApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'escola\''); - next(); -}, query, response('source')); - -classroomApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -classroomApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -classroomApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}, 'filter').addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'filter').addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'min_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'adm_dependency', - table: 'escola', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'escola', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'location', - table: 'escola', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}); - -classroomApp.get('/', cache('15 day'), rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.from('escola') - .field('SUM(escola.num_salas)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .order('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1 AND escola.local_func_predio_escolar = 1'); - next(); -}, query, addMissing(rqf), id2str.transform(), response('classroom')); - -module.exports = classroomApp; diff --git a/src/libs/routes/classroomCount.js b/src/libs/routes/classroomCount.js deleted file mode 100644 index 7489ddcbef1ee1422d77f10d4c95555dacb0e4cf..0000000000000000000000000000000000000000 --- a/src/libs/routes/classroomCount.js +++ /dev/null @@ -1,653 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const classroomCountApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'filter').addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}, 'filter').addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'id', - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}, 'dims').addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'school_year', - table: '@', - tableField: 'serie_ano_id', - resultField: 'school_year_id', - where: { - relation: '=', - type: 'integer', - field: 'serie_ano_id' - } -}).addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'period', - table: '@', - tableField: 'turma_turno_id', - resultField: 'period_id', - where: { - relation: '=', - type: 'integer', - field: 'turma_turno_id' - } -}); - -classroomCountApp.post('/', rqf.parse(), (req, res, next) => { - let classSize = JSON.parse(req.body.class_size) || null; - let integralTime = JSON.parse(req.body.integral_time) || null; - - if(classSize == null || integralTime == null) { - res.statusCode = 400; - return res.json({err: {message: "There was an error processing class_size or integral_time. Check your JSON sintax and be sure you're sending both paramenters."}}); - } - req.classSize = classSize; - req.integralTime = integralTime; - - req.dims.state = true; - req.dims.city = true; - req.dims.period = true; - req.dims.school_year = true; - req.dims.location = true; - - req.sql.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .from('matricula') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo<=3') - .where('matricula.dependencia_adm_id < 4'); - - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.enrollment = req.result; - - // Gera a relação etapa de ensino X ano escolar - req.educationSchoolYear = {}; - for(let i = 10; i < 80; ++i) { - if(id2str.schoolYear(i) !== id2str.schoolYear(99)) { - let educationLevelId = Math.floor(i/10); - - let classSize = req.classSize.find((el) => {return el.id === educationLevelId || el.id === i}); - let integralTime = req.integralTime.find((el) => {return el.id === educationLevelId}); - - let numberStudentClass = (typeof classSize !== 'undefined') ? classSize.numberStudentClass : null; - let offerGoal = (typeof integralTime !== 'undefined') ? integralTime.offerGoal : null; - - req.educationSchoolYear[i] = { - id: educationLevelId, - name: id2str.educationLevelShort(educationLevelId), - numberStudentClass, - offerGoal - }; - } - } - - req.resetSql(); - next(); -}, rqf.parse(), (req, res, next) => { - - req.dims.state = true; - req.dims.city = true; - req.dims.location = true; - - req.sql.field('SUM(escola.num_salas)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .from('escola') - .group('escola.ano_censo') - .order('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1 AND escola.local_func_predio_escolar = 1') - .where('escola.dependencia_adm_id < 4'); - - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - delete req.dims; - delete req.filter; - next(); -}, rqf.parse(), rqf.build(), (req, res, next) => { - req.classroom = req.result; - let classroom = []; - - // req.result = [{classroom: req.classroom, enrollment: req.enrollment}]; return next(); - - // Cria estrutura de resposta requisitada: - let i = 0; - let j = 0; - let result = []; - let hashSet = new Set(); - let enrollments = [...req.enrollment]; - let leftovers = []; - while (i < req.classroom.length) { - let classroom = req.classroom[i]; - // Cria hash única para cada espacialidade, dado um ano - let hash = '' + classroom.year + classroom.state_id + classroom.city_id; - // Estrutura do objeto do resultado final - let obj = { - year: classroom.year, - name: classroom.name, - state_id: classroom.state_id, - state_name: classroom.state_name, - city_id: classroom.city_id, - city_name: classroom.city_name, - locations: [] - }; - - let currentClassroomObj = null; - if( !hashSet.has(hash) ) { - hashSet.add(hash); - result.push(obj); - currentClassroomObj = obj; - } else { // Se a hash já existe, já temos a cidade nos resultados. Como está ordenado, é o último valor nos resultados - currentClassroomObj = result[result.length - 1]; - } - - // Inserimos a localidade no array de locations da sala - let location = { - location_id: classroom.location_id, - location_name: classroom.location_name, - total_classroom: parseInt(classroom.total, 10), - total_classroom_be_built: 0, - education_level: [] - }; - currentClassroomObj.locations.push(location); - - // Partimos para as etapas de ensino/anos escolares - - let enrollmentMatch = true; - j = 0; - let educationLevelSet = new Set(); - let schoolYearSet = new Set(); - let enrollment = enrollments[j]; - - while(enrollmentMatch && j < enrollments.length) { - enrollment = enrollments[j]; - - // Remove se o período é nulo (não dá pra usar no cálculo) - if(enrollment.period_id == null) { - enrollments.splice(j, 1); - continue; - } - - if(typeof enrollment === 'undefined') { - ++j; - continue; - } - - if(classroom.city_name < enrollment.city_name) { // Se as cidades não são iguais, já passamos do range - enrollmentMatch = false; - continue; - } else if(classroom.city_name > enrollment.city_name) { - let enrollmentHash = '' + enrollment.year + enrollment.state_id + enrollment.city_id; - if(hashSet.has(enrollmentHash)) { - leftovers.push(enrollments.splice(j, 1)); // Para inspeção, adiciona os que "sobram" no array de sobras - } else { - ++j; - } - continue; - } - - if(enrollment.year != classroom.year || enrollment.location_id != classroom.location_id) { // Se ano ou localização são diferentes, passa para o próximo - ++j; - continue; - } - - - // Temos uma matrícula com cidade, ano e localidades certos - // "Consome" a matrícula (remove do vetor de matrículas) - enrollments.splice(j, 1); - - // Cria a etapa de ensino adequada - let enrollmentEducationLevel = req.educationSchoolYear[enrollment.school_year_id]; - // Se não há um número de alunos por turna para a etapa de ensino, ignoramos a entrada - if(enrollmentEducationLevel.numberStudentClass == null) continue; - - let educationLevel = null; - if(!educationLevelSet.has(enrollmentEducationLevel.id)) { - educationLevelSet.add(enrollmentEducationLevel.id); - - educationLevel = { - education_level_short_id: enrollmentEducationLevel.id, - education_level_short_name: enrollmentEducationLevel.name, - enrollment: { - total_enrollment_day: 0, - total_enrollment_night: 0, - full_period_classes: 0, - day_classes: 0, - night_classes: 0, - total_classrooms_needed: 0 - } - }; - - if(enrollmentEducationLevel.id == 1) { - educationLevel.classes_school_year = []; - } - - // Para manter a ordem da etapa de ensino - if (location.education_level.length == 0) { - location.education_level.push(educationLevel); - } else { - let k = location.education_level.length - 1; - let el = location.education_level[k]; - while (k >= 0) { - if(educationLevel.education_level_short_id < el.education_level_short_id) { - --k; - if(k>=0) el = location.education_level[k]; - } else break; - } - k++; - location.education_level.splice(k, 0, educationLevel); - } - } else { - let k = 0; - let el = location.education_level[k]; - while(k < location.education_level.length) { - if(el.education_level_short_id != enrollmentEducationLevel.id) { - ++k; - if(k<location.education_level.length) el = location.education_level[k]; - } else break; - } - if(k >= location.education_level.length) --k; - educationLevel = location.education_level[k]; - } - - // Adiciona as séries da creche - let currentSchoolYear = null; - if(enrollmentEducationLevel.id == 1){ - let schoolYearHash = '' + enrollment.year + enrollment.city_id + enrollment.location_id + enrollment.school_year_id; - if(schoolYearSet.has(schoolYearHash)) { // Busca a série escolar - let k = 0; - let el = educationLevel.classes_school_year[k]; - while(k < educationLevel.classes_school_year.length) { - if(el.school_year_id != enrollment.school_year_id) { - ++k; - if(k < educationLevel.classes_school_year.length) el = educationLevel.classes_school_year[k]; - } else break; - } - if(k >= educationLevel.classes_school_year.length) --k; - currentSchoolYear = educationLevel.classes_school_year[k]; - } else { // Adiciona uma nova série escolar - let school_year = { - school_year_id: enrollment.school_year_id, - school_year_name: enrollment.school_year_name, - total_enrollment_day: 0, - total_enrollment_night: 0, - full_period_classes: 0, - day_classes: 0, - night_classes: 0, - total_classrooms_needed: 0 - } - schoolYearSet.add(schoolYearHash); - // Busca a posição para inserir - let k = 0; - let el = educationLevel.classes_school_year[k]; - while((typeof el !== 'undefined') && school_year.school_year_id > el.school_year_id) { - el = educationLevel.classes_school_year[++k]; - } - // educationLevel.classes_school_year.push(school_year); - educationLevel.classes_school_year.splice(k, 0, school_year); - currentSchoolYear = school_year; - } - } - - let currentOfferGoal = enrollmentEducationLevel.offerGoal; - let currentNumberStudentClass = (enrollment.location_id == 1) ? enrollmentEducationLevel.numberStudentClass.urban : enrollmentEducationLevel.numberStudentClass.country; - - // Soma os totais de matrícula da etapa de ensino - educationLevel.enrollment.total_enrollment_day += (enrollment.period_id < 3 && enrollment.period_id != null) ? enrollment.total : 0; - educationLevel.enrollment.total_enrollment_night += (enrollment.period_id == 3) ? enrollment.total : 0; - - // Calcula o número de turmas parcial - // Turmas de período integral - educationLevel.enrollment.full_period_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (currentOfferGoal/100)) / currentNumberStudentClass); - - // Turmas diurnas (matrículas diurnas - matrículas integrais) - educationLevel.enrollment.day_classes = Math.ceil((educationLevel.enrollment.total_enrollment_day * (1 - currentOfferGoal/100)) / currentNumberStudentClass); - - // Turmas noturnas - educationLevel.enrollment.night_classes = Math.ceil((educationLevel.enrollment.total_enrollment_night / currentNumberStudentClass)) || 0; - - // Total de salas - educationLevel.enrollment.total_classrooms_needed = (educationLevel.enrollment.full_period_classes + educationLevel.enrollment.day_classes/2); - - if(educationLevel.enrollment.night_classes > (educationLevel.enrollment.day_classes/2)) educationLevel.enrollment.total_classrooms_needed += (educationLevel.enrollment.night_classes - (educationLevel.enrollment.day_classes/2)); - - educationLevel.enrollment.total_classrooms_needed = Math.ceil(educationLevel.enrollment.total_classrooms_needed); - - // Faz os mesmos cálculos para a série escolar - if(currentSchoolYear) { - // Totais de matrícula - currentSchoolYear.total_enrollment_day += (enrollment.period_id < 3 && enrollment.period_id != null) ? enrollment.total : 0; - currentSchoolYear.total_enrollment_night += (enrollment.period_id == 3) ? enrollment.total : 0; - - // Número de turmas parcial - currentSchoolYear.full_period_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (currentOfferGoal/100)) / currentNumberStudentClass); - - currentSchoolYear.day_classes = Math.ceil((currentSchoolYear.total_enrollment_day * (1 - currentOfferGoal/100)) / currentNumberStudentClass); - - currentSchoolYear.night_classes = Math.ceil((currentSchoolYear.total_enrollment_night / enrollmentEducationLevel.numberStudentClass)) || 0; - - // Total de salas - currentSchoolYear.total_classrooms_needed = (currentSchoolYear.full_period_classes + currentSchoolYear.day_classes/2); - - if(currentSchoolYear.night_classes > (currentSchoolYear.day_classes/2)) currentSchoolYear.total_classrooms_needed += (currentSchoolYear.night_classes - (currentSchoolYear.day_classes/2)); - - currentSchoolYear.total_classrooms_needed = Math.ceil(currentSchoolYear.total_classrooms_needed); - - function reducer(key) { return (sum, elem) => sum + elem[key]} - educationLevel.enrollment.full_period_classes = educationLevel.classes_school_year.reduce(reducer('full_period_classes'), 0); - educationLevel.enrollment.day_classes = educationLevel.classes_school_year.reduce(reducer('day_classes'), 0); - educationLevel.enrollment.night_classes = educationLevel.classes_school_year.reduce(reducer('night_classes'), 0); - educationLevel.enrollment.total_classrooms_needed = educationLevel.classes_school_year.reduce(reducer('total_classrooms_needed'), 0); - } - - enrollment = enrollments[j]; - } - - // Calculamos o total classroom be built para o município usando reduce - location.total_classroom_be_built = location.education_level.reduce((total, atual) => { - return total + atual.enrollment.total_classrooms_needed; - }, 0) - location.total_classroom; - - if(location.total_classroom_be_built < 0) location.total_classroom_be_built = 0; - - ++i; - } - - // Agregar por estado e brasil - let reduction = null; - if(req.dims.state || !req.dims.city) { // Se um dos dois acontecer, sabemos que devemos agregar - let i = 0; - reduction = []; - let reductionSet = new Set(); - while (i < result.length) { - let city = result[i]; - let obj = { - year: city.year, - name: city.name - } - - if(req.dims.state) { - obj.state_id = city.state_id; - obj.state_name = city.state_name; - } - - obj.locations = []; - - let hash = '' + city.year; - if(req.dims.state) hash += '' + city.state_id; - - let currentObj = null; - if(!reductionSet.has(hash)) { - reductionSet.add(hash); - reduction.push(obj); - currentObj = obj; - } else { // Está ordenado, podemos pegar o último - currentObj = reduction[reduction.length - 1]; - } - - // Fazer "merge" do array locations da cidade com o da agregação - if(currentObj.locations.length == 0) { - // Pode ser que a cidade atual tenha menos localidades que o total (só urbana ou só rural) - currentObj.locations = [...city.locations]; - } else { - let j = 0; - let k = 0; - let cityLocation = null; - let currentLocation = null; - while((typeof cityLocation !== 'undefined') && (typeof currentLocation !== 'undefined')) { - cityLocation = city.locations[j]; - currentLocation = currentObj.locations[k]; - if(cityLocation.location_id < currentLocation.location_id) { - ++j; - cityLocation = city.locations[j]; - continue; - } else if(cityLocation.location_id > currentLocation.location_id) { - ++k; - currentLocation = currentObj.locations[k]; - // Se a localidade da cidade é maior que a localidade do objeto atual E o vetor de localidades do objeto atual - // acaba, então esta localidade falta no objeto atual, pois as localidades estão ordenadas - if(typeof currentLocation == 'undefined' && typeof cityLocation !== 'undefined') { - currentObj.locations[k] = cityLocation; - currentLocation = currentObj.locations[k]; - } - continue; - } - - // Faz "merge" do array education_level - // Se a localidade atual não tem o vetor - if(currentLocation.education_level.length == 0) { - currentLocation.education_level = [...cityLocation.education_level]; - } else { // Caso já tenha, atualiza os valores - let l = 0; - while(l < cityLocation.education_level.length) { - let cityEducation = cityLocation.education_level[l]; - let m = 0; - let currentEducation = currentLocation.education_level[m]; - while(m < currentLocation.education_level.length && cityEducation.education_level_short_id > currentEducation.education_level_short_id) { - ++m; - currentEducation = currentLocation.education_level[m]; - } - if(m >= currentLocation.education_level.length) --m; - currentEducation = currentLocation.education_level[m]; - - if(currentEducation.education_level_short_id == cityEducation.education_level_short_id) { - currentEducation.enrollment.total_enrollment_day += cityEducation.enrollment.total_enrollment_day; - currentEducation.enrollment.total_enrollment_night += cityEducation.enrollment.total_enrollment_night; - currentEducation.enrollment.full_period_classes += cityEducation.enrollment.full_period_classes; - currentEducation.enrollment.day_classes += cityEducation.enrollment.day_classes; - currentEducation.enrollment.night_classes += cityEducation.enrollment.night_classes; - currentEducation.enrollment.total_classrooms_needed += cityEducation.enrollment.total_classrooms_needed; - // Insere as séries escolares, se existirem - if((typeof cityEducation.classes_school_year !== 'undefined') && (typeof currentEducation.classes_school_year !== 'undefined')) { - let n = 0; - let o = 0; - let currentClass = currentEducation.classes_school_year[n]; - let cityClass = cityEducation.classes_school_year[o]; - while((typeof cityClass !== 'undefined') && (typeof currentClass !== 'undefined')) { - currentClass = currentEducation.classes_school_year[n]; - cityClass = cityEducation.classes_school_year[o]; - - // Se a série escolar é menor que a atual, ela não está no vetor, pois o vetor está ordenado e tem range limitado - if(cityClass.school_year_id < currentClass.school_year_id) { - currentEducation.classes_school_year.splice(n, 0, cityClass); - currentClass = currentEducation.classes_school_year[n]; - cityClass = cityEducation.classes_school_year[++o]; - continue; - } else if(cityClass.school_year_id > currentClass.school_year_id) { - currentClass = currentEducation.classes_school_year[++n]; - // Se o ano escolar da cidade é maior que do objeto atual E o vetor de ano escolar do objeto atual - // acaba, então este ano escolar falta no objeto atual, pois os anos escolares estão ordenados - if((typeof currentClass == 'undefined') && (typeof cityClass !== 'undefined')) { - currentEducation.classes_school_year[n] = cityClass; - currentClass = currentEducation.classes_school_year[n]; - } - continue; - } - - currentClass.total_enrollment_day += cityClass.total_enrollment_day; - currentClass.total_enrollment_night += cityClass.total_enrollment_night; - currentClass.full_period_classes += cityClass.full_period_classes; - currentClass.day_classes += cityClass.day_classes; - currentClass.night_classes += cityClass.night_classes; - currentClass.total_classrooms_needed += cityClass.total_classrooms_needed; - - cityClass = cityEducation.classes_school_year[++o]; - } - - } - } else { - if(currentEducation.education_level_short_id < cityEducation.education_level_short_id) { - currentLocation.education_level.splice(++m, 0, cityEducation); - } else { - currentLocation.education_level.splice(m, 0, cityEducation); - } - } - ++l; - } - } - - currentLocation.total_classroom += cityLocation.total_classroom; - currentLocation.total_classroom_be_built += cityLocation.total_classroom_be_built; - - ++j; - cityLocation = city.locations[j]; - } - } - ++i; - } - } - - req.result = reduction || result; - - next(); -}, response('classroom_count')); - -module.exports = classroomCountApp; diff --git a/src/libs/routes/cub.js b/src/libs/routes/cub.js deleted file mode 100644 index b6bb034cb579e9df82ac6180220aa463bc8b8432..0000000000000000000000000000000000000000 --- a/src/libs/routes/cub.js +++ /dev/null @@ -1,198 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const cubApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const request = require(`request`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); -let rqfCount = new ReqQueryFields(); - -cubApp.get('/year_range', (req, res, next) => { - req.sql.from('cub') - .field('MIN(cub.ano_censo)', 'start_year') - .field('MAX(cub.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -cubApp.get('/years', (req, res, next) => { - req.sql.from('cub') - .field('DISTINCT cub.ano_censo', 'year'); - next(); -}, query, response('years')); - -cubApp.get('/months', (req, res, next) => { - req.sql.from('cub') - .field('DISTINCT cub.mes_censo', 'month'); - next(); -}, query, response('months')); - -cubApp.get('/years_months', (req, res, next) => { - req.sql.from('cub') - .field('DISTINCT cub.ano_censo AS "year", cub.mes_censo AS "month"'); - next(); -}, query, response('years_months')); - -cubApp.get('/price_type', (req, res, next) => { - req.sql.from('cub') - .field('DISTINCT cub.tipo_preco', 'price_type'); - next(); -}, query, response('price_type')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'state', - table: 'estado', - tableField: ['sigla', 'id'], - resultField: ['sigla_uf', 'cod_uf'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'cub' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'cub' - } -}).addValue({ - name: 'min_year', - table: 'cub', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'cub', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'cub', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'cub', - field: 'ano_censo' - } -}).addValue({ - name: 'min_month', - table: 'cub', - tableField: 'mes_censo', - resultField: 'month', - where: { - relation: '>=', - type: 'integer', - table: 'cub', - field: 'mes_censo' - } -}).addValue({ - name: 'max_month', - table: 'cub', - tableField: 'mes_censo', - resultField: 'month', - where: { - relation: '<=', - type: 'integer', - table: 'cub', - field: 'mes_censo' - } -}); - -cubApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - if (req.filter.size || req.filter.dims) { - if ('state' in req.filter || 'state' in req.dims) { - req.sql.from('cub') - .field('cub.estado_id', 'cod_uf') - .field('estado.sigla', 'sigla_uf') - .field('cub.tipo_preco', 'tipo_preco') - .field('cub.preco', 'preco') - .join('estado', null, 'cub.estado_id=estado.id') - .group('cub.ano_censo') - .group('cub.mes_censo') - .group('cub.estado_id') - .group('estado.sigla') - .group('cub.tipo_preco') - .group('cub.preco') - } else { - req.sql.from('cub') - .field("'BR'", 'sigla_uf') - .field("cub.tipo_preco", 'tipo_preco') - .field('AVG(cub.preco)', 'preco') - .join('estado', null, 'cub.estado_id=estado.id') - .group('cub.ano_censo') - .group('cub.mes_censo') - .group('cub.tipo_preco') - } - } else { - req.sql.from('cub') - .field('cub.estado_id', 'cod_uf') - .field('estado.sigla', 'sigla_uf') - .field('cub.tipo_preco', 'tipo_preco') - .field('cub.preco', 'preco') - .join('estado', null, 'cub.estado_id=estado.id') - .group('cub.ano_censo') - .group('cub.mes_censo') - .group('cub.estado_id') - .group('estado.sigla') - .group('cub.tipo_preco') - .group('cub.preco') - } - - next(); -}, query, addMissing(rqf), id2str.transform(), response('cub')); - -module.exports = cubApp; diff --git a/src/libs/routes/dailyChargeAmount.js b/src/libs/routes/dailyChargeAmount.js deleted file mode 100644 index 3588a5475a763e88fb92a07a9d52cb557e0cd508..0000000000000000000000000000000000000000 --- a/src/libs/routes/dailyChargeAmount.js +++ /dev/null @@ -1,474 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const dailyChargeAmountApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const request = require(`request`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); -let rqfCount = new ReqQueryFields(); - -dailyChargeAmountApp.get('/year_range', (req, res, next) => { - req.sql.from('turma') - .field('MIN(turma.ano_censo)', 'start_year') - .field('MAX(turma.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -dailyChargeAmountApp.get('/years', (req, res, next) => { - req.sql.from('turma') - .field('DISTINCT turma.ano_censo', 'year'); - next(); -}, query, response('years')); - -dailyChargeAmountApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'turma\''); - next(); -}, query, response('source')); - -dailyChargeAmountApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -dailyChargeAmountApp.get('/adm_dependency_detailed', cache('15 day'), (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -dailyChargeAmountApp.get('/location', cache('15 day'), (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -dailyChargeAmountApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -dailyChargeAmountApp.get('/education_level_short', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Ensino Fundamental - anos iniciais'}, - {id: 4, name: 'Ensino Fundamental - anos finais'}, - {id: 5, name: 'Ensino Médio'}, - {id: 6, name: 'EJA'}, - {id: 7, name: 'EE exclusiva'} - ]; - next(); -}, response('education_level_short')); - -dailyChargeAmountApp.get('/average/education_level_mod', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Educação Infantil Unificada'}, - {id: 4, name: 'Ensino Fundamental - anos iniciais'}, - {id: 5, name: 'Ensino Fundamental - anos finais'}, - {id: 6, name: 'Ensino Médio'}, - {id: 7, name: 'Turma Multisseriadas e Multietapas'}, - {id: 8, name: 'EJA - Ensino Fundamental'}, - {id: 9, name: 'EJA - Ensino Médio'}, - {id: 10, name: 'Educação Profissional'} - ]; - next(); -}, response('education_level_mod')); - -dailyChargeAmountApp.get('/period', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 3; ++i) { - req.result.push({ - id: i, - name: id2str.period(i) - }); - }; - req.result.push({ - id: 99, - name: id2str.period(99) - }); - next(); -}, response('period')); - -dailyChargeAmountApp.get('/integral_time', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Disponível'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('integral_time')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'turma' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'turma' - } -}).addValue({ - name: 'min_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'turma', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'turma', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'turma', - field: 'ano_censo' - } -}).addValue({ - name: 'location', - table: 'turma', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'adm_dependency', - table: 'turma', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'turma', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'rural_location', - table: 'turma', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'education_level_mod', - table: 'turma', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - dontGroup: true, - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'period', - table: 'turma', - tableField: 'turma_turno_id', - resultField: 'period_id', - where: { - relation: '=', - type: 'integer', - field: 'turma_turno_id' - } -}).addValue({ - name: 'integral_time', - table: 'turma', - tableField: 'tempo_integral', - resultField: 'integral_time_id', - where: { - relation: '=', - type: 'boolean', - field: 'tempo_integral' - } -}).addValue({ - name: 'education_level_short', - table: 'turma', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}); - -dailyChargeAmountApp.get('/', rqf.parse(), (req, res, next) => { - var status = 0; - if ('integral_time' in req.filter) { - if (req.filter['integral_time'] == '0' - && ('period' in req.filter)) { - if (req.filter['period'].length == 1 - && req.filter['period'][0] == '3') { - status = 1; - } else if (req.filter['period'].length <= 2 - && (req.filter['period'].includes('1') - || req.filter['period'].includes('2')) - && (!req.filter['period'].includes('3'))) { - status = 1; - } - } else if (req.filter['integral_time'] == '1') { - status = 1; - } - } - - if (status) { - req.sql.from('turma') - .field('turma.ano_censo', 'year') - .field('turma.etapa_resumida', 'education_level_short_id') - .field('AVG(turma.duracao_turma)/60.0', 'average_class_duration') - .field('MEDIAN(turma.duracao_turma)/60.0', 'median_class_duration') - .field('STDDEV_SAMP(turma.duracao_turma)/60.0', 'std_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.25)/60.0', 'fstqt_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.75)/60.0', 'thdqt_class_duration') - .group('turma.ano_censo') - .group('turma.etapa_resumida') - .order('turma.ano_censo') - .order('turma.etapa_resumida') - .where('turma.tipo_turma_id <= 3 and turma.dependencia_adm_id <= 3') - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); - -}, rqf.build(), query, addMissing(rqf), (req, res, next) => { - - function sliced(object) { - return object['education_level_short_id'] > 3; - } - - if ('period' in req.filter || 'period' in req.dims) { - req.filter['period'].forEach((element) => { - if (element == '3') - req.result = req.result.filter(sliced); - }); - } - - next(); -}, id2str.transform(), response('turma')); - -dailyChargeAmountApp.get('/average', rqf.parse(), rqf.build(), (req, res, next) => { - var status = 0; - if (('education_level_mod' in req.filter || 'education_level_mod' in req.dims) - && ('integral_time' in req.filter)) { - if (req.filter['integral_time'] == '0' - && ('period' in req.filter)) { - if (req.filter['period'].length == 1 - && req.filter['period'][0] == '3') { - status = 1; - } else if (req.filter['period'].length <= 2 - && (req.filter['period'].includes('1') - || req.filter['period'].includes('2')) - && (!req.filter['period'].includes('3'))) { - status = 1; - } - } else if (req.filter['integral_time'] == '1') { - status = 1; - } - } - - if (status) { - let baseQ = req.sql.clone(); - - let tableR = baseQ.clone(); - tableR.from('turma') - .field('duracao_turma') - .field('etapas_mod_ensino_segmento_id') - .field('ROW_NUMBER() OVER(PARTITION BY etapas_mod_ensino_segmento_id ORDER BY duracao_turma)', 'rowno') - .where('tipo_turma_id <= 3') - - let tableG = baseQ.clone(); - tableG.from('turma') - .field('1+COUNT(*)', 'counter') - .field('etapas_mod_ensino_segmento_id') - .where('tipo_turma_id <= 3') - .group('etapas_mod_ensino_segmento_id') - - let joinRG = squel.select(); - joinRG.from(tableR, 'R') - .field('R.etapas_mod_ensino_segmento_id') - .field('AVG(1.0*R.duracao_turma)/60', 'median_value') - .join(tableG, 'G', 'R.etapas_mod_ensino_segmento_id = G.etapas_mod_ensino_segmento_id AND R.rowNo BETWEEN G.counter/2 AND G.counter/2+G.counter%2') - .group('R.etapas_mod_ensino_segmento_id') - - req.sql - .from('turma') - .from(joinRG, 'm') - .field('turma.ano_censo', 'year') - .field('turma.etapas_mod_ensino_segmento_id', 'education_level_mod_id') - .field('AVG(turma.duracao_turma)/60.0', 'average_class_duration') - .field('AVG(m.median_value)', 'median_class_duration') - .field('STDDEV_SAMP(turma.duracao_turma)/60.0', 'std_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.25)/60.0', 'fstqt_class_duration') - .field('QUANTILE(turma.duracao_turma, 0.75)/60.0', 'thdqt_class_duration') - .group('turma.ano_censo') - .group('turma.etapas_mod_ensino_segmento_id') - .order('turma.ano_censo') - .order('turma.etapas_mod_ensino_segmento_id') - .where('turma.tipo_turma_id <= 3 and m.etapas_mod_ensino_segmento_id = turma.etapas_mod_ensino_segmento_id') - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); -}, query, addMissing(rqf), id2str.transform(), response('turma')); - -module.exports = dailyChargeAmountApp; diff --git a/src/libs/routes/distributionFactor.js b/src/libs/routes/distributionFactor.js deleted file mode 100644 index 99e1a77a9e9dea2fc2b49551d2b9d9760ec680fa..0000000000000000000000000000000000000000 --- a/src/libs/routes/distributionFactor.js +++ /dev/null @@ -1,210 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const distributionApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -distributionApp.use(cache('15 day')); - -rqf.addField({ - name: 'dims', - field: true, - where: false -}).addField({ - name: 'filter', - field: false, - where: true -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'fatores_matricula' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'fatores_matricula' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'fatores_matricula' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'fatores_matricula' - } -}, 'filter').addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'fatores_matricula' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'fatores_matricula' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'fatores_matricula' - } -}) - -// Return all cities -distributionApp.get('/', rqf.parse(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - let relation = req.sql.clone(); - relation.from('relacao_fatores_matricula').field('*'); - req.queryIndex.relation = req.querySet.push(relation) - 1; - - req.sql.from('fatores_matricula') - .field('fatores_matricula.municipio_id', 'municipio_id') - .field('fatores_matricula."mais_CRE_0"') - .field('fatores_matricula."mais_CRE_1"') - .field('fatores_matricula."mais_CRE_2"') - .field('fatores_matricula."mais_CRE_3"') - .field('fatores_matricula."mais_PRE"') - .field('fatores_matricula."mais_EFAI"') - .field('fatores_matricula."mais_EFAF"') - .field('fatores_matricula."mais_EM"') - .field('fatores_matricula."mais_EJA"') - .field('fatores_matricula."menos_CRE_0"') - .field('fatores_matricula."menos_CRE_1"') - .field('fatores_matricula."menos_CRE_2"') - .field('fatores_matricula."menos_CRE_3"') - .field('fatores_matricula."menos_PRE"') - .field('fatores_matricula."menos_EFAI"') - .field('fatores_matricula."menos_EFAF"') - .field('fatores_matricula."menos_EM"') - .field('fatores_matricula."menos_EJA"') - .group('fatores_matricula.municipio_id') - .group('fatores_matricula."mais_CRE_0"') - .group('fatores_matricula."mais_CRE_1"') - .group('fatores_matricula."mais_CRE_2"') - .group('fatores_matricula."mais_CRE_3"') - .group('fatores_matricula."mais_PRE"') - .group('fatores_matricula."mais_EFAI"') - .group('fatores_matricula."mais_EFAF"') - .group('fatores_matricula."mais_EM"') - .group('fatores_matricula."mais_EJA"') - .group('fatores_matricula."menos_CRE_0"') - .group('fatores_matricula."menos_CRE_1"') - .group('fatores_matricula."menos_CRE_2"') - .group('fatores_matricula."menos_CRE_3"') - .group('fatores_matricula."menos_PRE"') - .group('fatores_matricula."menos_EFAI"') - .group('fatores_matricula."menos_EFAF"') - .group('fatores_matricula."menos_EM"') - .group('fatores_matricula."menos_EJA"'); - - if(typeof req.dims.state !== 'undefined' || typeof req.filter.state !== 'undefined') { - req.sql.where('fatores_matricula.nivel = \'UF\''); - } else { - req.sql.where('fatores_matricula.nivel = \'BR\''); - } - - next(); -}, rqf.build(), query, (req, res, next) => { - req.enrollmentFactor = req.result; - next(); -}, multiQuery, (req, res, next) => { - let relation = req.result[req.queryIndex.relation]; - let result = []; - let first = true; - req.enrollmentFactor.forEach((city) => { - // if(first) console.log(city); - let obj = { - level: city.nivel, - region_id: city.regiao_id, - region_name: city.region_name, - state_id: city.state_id, - state_name: city.state_name, - city_id: city.municipio_id, - city_name: city.city_name, - series: [] - }; - // if(first) console.log(obj); - first = false; - relation.forEach((serie) => { - obj.series.push({ - serie_id: serie.id, - distribution_factor_addition: city[serie.fator_adicao], - distribution_factor_reduction: city[serie.fator_reducao] - }); - }); - result.push(obj); - }); - req.result = result; - next(); -}, response('ditributionFactor')); - -module.exports = distributionApp; diff --git a/src/libs/routes/downloads.js b/src/libs/routes/downloads.js deleted file mode 100644 index 9f01479dc051b04daef6c683742d0b2762eae5ef..0000000000000000000000000000000000000000 --- a/src/libs/routes/downloads.js +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const downloadApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const Download = require(`${libs}/models/download`); - -const User = require(`${libs}/models/user`); - -const passport = require('passport'); - -const request = require(`request`); - -const config = require(`${libs}/config`); - -downloadApp.get('/', passport.authenticate('bearer', {session: false}), (req, res, next) => { - request.get(config.cdn.url + '/api/v1/file', (err, response, body) => { - let cdn = JSON.parse(body); - Download.find({userId: req.user._id}, (err, downloads) => { - if (err) { - log.error(err); - return next(err); - } - - if(!downloads) { - res.statusCode = 404; - return res.json({msg: 'Nenhum download encontrado'}); - } else { - downloads.forEach((dl) => { - for(let i = 0; i < cdn.length; ++i) { - if(cdn[i].query == dl.query) { - dl.status = cdn[i].expired ? 'Expirado' : 'Enviado'; - dl.size = cdn[i].size; - dl.expired = cdn[i].expired; - dl.updatedAt = cdn[i].lastAccess; - dl.link = config.cdn.download + '/' + cdn[i]._id; - - dl.save((err) => { - if(err) log.error(err); - }); - return; - } - } - }); - } - res.json(downloads); - }); - }); -}); - -module.exports = downloadApp; diff --git a/src/libs/routes/educationYears.js b/src/libs/routes/educationYears.js deleted file mode 100644 index b8173d060e8f29183ccc65926815dc3594a2ce24..0000000000000000000000000000000000000000 --- a/src/libs/routes/educationYears.js +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const educationYearsApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const response = require(`${libs}/middlewares/response`); - -const config = require(`${libs}/config`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -educationYearsApp.use(cache('15 day')); - -educationYearsApp.get('/', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 7; ++i) { - let edLvlShort = { - id: i, - name: id2str.educationLevelShort(i), - schoolYears: [] - }; - - for(let j = i*10; j <= (i*10 + 9); ++j) { - - let schoolYear = { - id: j, - name: id2str.schoolYear(j) - }; - - if(schoolYear.name !== id2str.schoolYear(99)) { - edLvlShort.schoolYears.push(schoolYear); - } - } - if(edLvlShort.name !== id2str.schoolYear(99)) { - req.result.push(edLvlShort); - } - } - next(); -}, response('educationYears')); - -module.exports = educationYearsApp; diff --git a/src/libs/routes/employees.js b/src/libs/routes/employees.js deleted file mode 100644 index 9aedbcb1de07e1e769806e57483981cb9530981a..0000000000000000000000000000000000000000 --- a/src/libs/routes/employees.js +++ /dev/null @@ -1,537 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const employeesApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqfTeacher = new ReqQueryFields(); - -let rqfSchool = new ReqQueryFields(); - - -employeesApp.use(cache('15 day')); - -// Returns a tuple of start and ending years of the complete enrollments dataset. -employeesApp.get('/year_range', (req, res, next) => { - req.sql.from('docente') - .field('MIN(docente.ano_censo)', 'start_year') - .field('MAX(docente.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -employeesApp.get('/years', (req, res, next) => { - req.sql.from('docente'). - field('DISTINCT docente.ano_censo', 'year'); - next(); -}, query, response('years')); - -employeesApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'docente\''); - next(); -}, query, response('source')); - -employeesApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -employeesApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -employeesApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -employeesApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -rqfSchool.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: '@', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: '@', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, -}, 'filter').addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: '@', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - -rqfTeacher.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: '@', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: '@', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: '@' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id','ano_censo'], - foreign: ['escola_id','ano_censo'], - foreignTable: '@' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id','ano_censo'], - foreign: ['escola_id','ano_censo'], - foreignTable: '@' - } -}, 'filter').addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: '@', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryTotal.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - let objMatch = null; - - for(let i = 0; i < queryPartial.length; ++i) { - let partial = queryPartial[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(partial[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - objMatch = partial; - break; - } - } - - if(objMatch) { - newObj.total = result.total - objMatch.total; - newObj.total_employees = result.total; - newObj.total_teachers = objMatch.total - match.push(newObj); - } - }); - - return match; -} - -employeesApp.get('/', rqfSchool.parse(), (req, res, next) => { - req.allEmployees = {} - req.allTeacher = {} - - if ("school" in req.filter) { - req.sql.field('SUM(escola.num_funcionarios)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .from('escola') - .group('escola.ano_censo') - .order('escola.ano_censo') - .where('(escola.situacao_de_funcionamento = 1) AND (escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1) AND (dependencia_adm_id = 2 OR dependencia_adm_id = 3 OR dependencia_adm_id = 4) AND (escola.id=' + req.filter.school + ')'); - delete req.filter.school; - next(); - } else { - req.sql.field('SUM(escola.num_funcionarios)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .from('escola') - .group('escola.ano_censo') - .order('escola.ano_censo') - .where('(escola.situacao_de_funcionamento = 1) AND (escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1) AND (dependencia_adm_id = 2 OR dependencia_adm_id = 3 OR dependencia_adm_id = 4)'); - next(); - } -}, rqfSchool.build(), query, rqfSchool.parse(), id2str.transform(), (req, res, next) => { - - req.allEmployees = req.result; - req.resetSql(); - - if ("school" in req.filter) { - req.sql.field('SUM(docente_por_escola.total_professores)', 'total') - .field("'Brasil'", 'name') - .field('docente_por_escola.ano_censo', 'year') - .from('docente_por_escola') - .join('escola', null, 'docente_por_escola.escola_id=escola.id AND docente_por_escola.ano_censo=escola.ano_censo') - .group('docente_por_escola.ano_censo') - .order('docente_por_escola.ano_censo') - .where('(docente_por_escola.dependencia_adm_id > 1) AND (docente_por_escola.escola_id=' + req.filter.school + ')'); - } else if ("school" in req.dims) { - req.sql.field('SUM(docente_por_escola.total_professores)', 'total') - .field("'Brasil'", 'name') - .field('docente_por_escola.ano_censo', 'year') - .field('escola.nome_escola', 'school_name') - .from('docente_por_escola') - .join('escola', null, 'docente_por_escola.escola_id=escola.id AND docente_por_escola.ano_censo=escola.ano_censo') - .group('docente_por_escola.ano_censo') - .order('docente_por_escola.ano_censo') - .where('(docente_por_escola.dependencia_adm_id > 1)'); - } else { - req.sql.field('SUM(docente_por_escola.total_professores)', 'total') - .field("'Brasil'", 'name') - .field('docente_por_escola.ano_censo', 'year') - .from('docente_por_escola') - .group('docente_por_escola.ano_censo') - .order('docente_por_escola.ano_censo') - .where('(docente_por_escola.dependencia_adm_id > 1)'); - } - next(); - -}, rqfSchool.build(), query, id2str.transform(), (req, res, next) => { - - req.allTeacher = req.result; - let aux_employees = matchQueries(req.allEmployees, req.allTeacher); - req.result = aux_employees; - next(); -}, response('employees')); - -module.exports = employeesApp; diff --git a/src/libs/routes/enrollment.js b/src/libs/routes/enrollment.js deleted file mode 100644 index 65110003de781c01472300fe233dc03898c79d96..0000000000000000000000000000000000000000 --- a/src/libs/routes/enrollment.js +++ /dev/null @@ -1,934 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const enrollmentApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -enrollmentApp.use(cache('15 day')); - -let rqf = new ReqQueryFields(); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -enrollmentApp.get('/year_range', (req, res, next) => { - req.sql.from('matricula') - .field('MIN(matricula.ano_censo)', 'start_year') - .field('MAX(matricula.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -enrollmentApp.get('/years', (req, res, next) => { - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, response('years')); - -enrollmentApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'matricula\''); - next(); -}, query, response('source')); - -enrollmentApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -enrollmentApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -// Returns all school years available -enrollmentApp.get('/school_year', (req, res, next) => { - req.result = []; - for(let i = 11; i <= 71; ++i) { - let obj = { - id: i, - name: id2str.schoolYear(i) - }; - - if(obj.name !== id2str.schoolYear(99)) { - req.result.push(obj); - } - } - req.result.push({ - id: 99, - name: id2str.schoolYear(99) - }); - next(); -}, response('school_year')); - -// Returns all school years available -enrollmentApp.get('/education_level', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 74; ++i) { - let obj = { - id: i, - name: id2str.educationLevel(i) - }; - - if(obj.name !== id2str.educationLevel(99)) { - req.result.push(obj); - } - } - req.result.push({ - id: 99, - name: id2str.educationLevel(99) - }); - next(); -}, response('education_level')); - -// Returns all school years available -enrollmentApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 10; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -enrollmentApp.get('/education_level_short', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Ensino Fundamental - anos iniciais'}, - {id: 4, name: 'Ensino Fundamental - anos finais'}, - {id: 5, name: 'Ensino Médio'}, - {id: 6, name: 'EJA'}, - {id: 7, name: 'EE exclusiva'} - ]; - next(); -}, response('education_level_short')); - -// Returns all adm dependencies -enrollmentApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -enrollmentApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -// Return genders -enrollmentApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -// Return ethnic group -enrollmentApp.get('/ethnic_group', (req, res, next) => { - req.result = []; - for(let i = 1; i <=5; ++i) { - req.result.push({ - id: i, - name: id2str.ethnicGroup(i) - }); - } - next(); -}, response('ethnic_group')); - -enrollmentApp.get('/period', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 3; ++i) { - req.result.push({ - id: i, - name: id2str.period(i) - }); - } - req.result.push({ - id: 99, - name: id2str.period(99) - }); - next(); -}, response('period')); - -// Returns integral-time avaible -enrollmentApp.get('/integral_time', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Disponível'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('integral_time')); - -enrollmentApp.get('/special_class', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('special_class')); - -enrollmentApp.get('/age_range_all', (req, res, next) => { - req.result = [ - {id: 1, name: '0 a 3 anos'}, - {id: 2, name: '4 a 5 anos'}, - {id: 3, name: '6 a 10 anos'}, - {id: 4, name: '11 a 14 anos'}, - {id: 5, name: '15 a 17 anos'}, - {id: 6, name: '18 a 24 anos'}, - {id: 7, name: '25 a 29 anos'}, - {id: 8, name: '30 a 40 anos'}, - {id: 9, name: '41 a 50 anos'}, - {id: 10, name: '51 a 64 anos'}, - {id: 11, name: 'Mais que 64 anos'} - ]; - next(); -}, response('age_range_all')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: 'matricula', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'matricula', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'school_year', - table: 'matricula', - tableField: 'serie_ano_id', - resultField: 'school_year_id', - where: { - relation: '=', - type: 'integer', - field: 'serie_ano_id' - } -}).addValue({ - name: 'education_level', - table: 'matricula', - tableField: 'etapa_ensino_id', - resultField: 'education_level_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_ensino_id' - } -}).addValue({ - name: 'education_level_mod', - table: 'matricula', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'education_level_short', - table: 'matricula', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'matricula' - } -}).addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'matricula' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'matricula' - } -}, 'filter').addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'matricula' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'matricula' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'matricula' - } -}, 'dims').addValueToField({ - name: 'locale_id', - table: 'matricula', - tableField: 'localizacao_id', - resultField: 'locale_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}, 'dims').addValueToField({ - name: 'school_id', - table: 'escola', - tableField: 'id', - resultField: 'school_id', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'matricula' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'matricula' - } -}, 'filter').addValue({ - name: 'location', - table: 'matricula', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'matricula', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'min_year', - table: 'matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'gender', - table: 'matricula', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'ethnic_group', - table: 'matricula', - tableField: 'cor_raca_id', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca_id' - } -}).addValue({ - name: 'period', - table: 'matricula', - tableField: 'turma_turno_id', - resultField: 'period_id', - where: { - relation: '=', - type: 'integer', - field: 'turma_turno_id' - } -}).addValue({ - name:'integral_time', - table: 'matricula', - tableField: 'tempo_integral', - resultField: 'integral_time_id', - where: { - relation: '=', - type: 'boolean', - field: 'tempo_integral' - } -}).addValue({ - name:'age_range_all', - table: 'matricula', - tableField: 'faixa_etaria_31_03', - resultField: 'age_range_all_id', - where: { - relation: '=', - type: 'integer', - field: 'faixa_etaria_31_03' - } -}).addValue({ - name:'special_class', - table: 'matricula', - tableField: 'exclusiva_especial', - resultField: 'special_class_id', - where: { - relation: '=', - type: 'boolean', - field: 'exclusiva_especial' - } -}); - -enrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.field('COUNT(*)', 'total') - .field('matricula.ano_censo', 'year') - .from('matricula') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo<=3'); - next(); -}, query, addMissing(rqf), id2str.transform(false), response('enrollment')); - -enrollmentApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('matricula', 'mapping_matricula')); - -enrollmentApp.get('/diagnosis', rqf.parse(), (req, res, next) => { - req.dims = {}; - req.dims.state = true; - req.dims.city = true; - req.dims.school_year = true; - req.dims.location = true; - req.dims.adm_dependency_detailed = true; - - req.sql.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .from('matricula') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo<=3'); - - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - let enrollments = req.result; - - // Gera a relação etapa de ensino X ano escolar - let educationSchoolYear = {}; - for(let i = 10; i < 80; ++i) { - if(id2str.schoolYear(i) !== id2str.schoolYear(99)) { - let educationLevelId = Math.floor(i/10); - educationSchoolYear[i] = { - id: educationLevelId, - name: id2str.educationLevelShort(educationLevelId), - }; - } - } - - let result = []; - let educationLevelSet = new Set(); - let schoolYearSet = new Set(); - let i = 0; - while(i < enrollments.length) { - let enrollment = enrollments[i]; - if(!educationSchoolYear[enrollment.school_year_id]) { - ++i; - continue; - } - let educationLevelHash = '' + enrollment.year + educationSchoolYear[enrollment.school_year_id].id + enrollment.city_id; - let schoolYearHash = '' + enrollment.year + enrollment.school_year_id + enrollment.city_id; - - let currentEducation = null; - // Busca ou cria a etapa de ensino adequada - if(educationLevelSet.has(educationLevelHash)) { - let j = 0; - let edu = result[j]; - while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != educationSchoolYear[enrollment.school_year_id].id)) { - ++j; - edu = result[j]; - } - if(j >= result.length) --j; - edu = result[j]; - - currentEducation = edu; - } else { - educationLevelSet.add(educationLevelHash); - let obj = { - year: enrollment.year, - name: enrollment.name, - state_id: enrollment.state_id, - state_name: enrollment.state_name, - city_id: enrollment.city_id, - city_name: enrollment.city_name, - education_level_school_year_id: educationSchoolYear[enrollment.school_year_id].id, - education_level_school_year_name: educationSchoolYear[enrollment.school_year_id].name, - total: 0, - adm_dependencies: [ - { - adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, - adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, - total: 0 - } - ], - locations: [ - { - location_id: enrollment.location_id, - location_name: enrollment.location_name, - total: 0 - } - ] - }; - - result.push(obj); - currentEducation = obj; - } - - let currentSchoolYear = null; - // Busca ou cria a série adequada - if(schoolYearSet.has(schoolYearHash)) { - let j = 0; - let edu = result[j]; - while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != enrollment.school_year_id)) { - ++j; - edu = result[j]; - } - if(j >= result.length) --j; - edu = result[j]; - - currentSchoolYear = edu; - } else { - schoolYearSet.add(schoolYearHash); - let obj = { - year: enrollment.year, - name: enrollment.name, - state_id: enrollment.state_id, - state_name: enrollment.state_name, - city_id: enrollment.city_id, - city_name: enrollment.city_name, - education_level_school_year_id: enrollment.school_year_id, - education_level_school_year_name: enrollment.school_year_name, - total: 0, - adm_dependencies: [ - { - adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, - adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, - total: 0 - } - ], - locations: [ - { - location_id: enrollment.location_id, - location_name: enrollment.location_name, - total: 0 - } - ] - }; - - result.push(obj); - currentSchoolYear = obj; - } - - // Adiciona ao total - currentEducation.total += enrollment.total; - currentSchoolYear.total += enrollment.total; - - // Adiciona ao total da dependência administrativa - let admDependencyIndex = 0; - let admDependency = currentEducation.adm_dependencies[admDependencyIndex]; - while (admDependencyIndex < currentEducation.adm_dependencies.length && enrollment.adm_dependency_detailed_id > admDependency.adm_dependency_detailed_id) { - ++admDependencyIndex; - admDependency = currentEducation.adm_dependencies[admDependencyIndex]; - } - if(admDependencyIndex >= currentEducation.adm_dependencies.length || admDependency.adm_dependency_detailed_id != enrollment.adm_dependency_detailed_id) { // não encontrou - let obj = { - adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, - adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, - total: 0 - } - currentEducation.adm_dependencies.splice(admDependencyIndex, 0, obj); - admDependency = obj; - } - admDependency.total += enrollment.total; - - admDependencyIndex = 0; - admDependency = currentSchoolYear.adm_dependencies[admDependencyIndex]; - while (admDependencyIndex < currentSchoolYear.adm_dependencies.length && enrollment.adm_dependency_detailed_id > admDependency.adm_dependency_detailed_id) { - ++admDependencyIndex; - admDependency = currentSchoolYear.adm_dependencies[admDependencyIndex]; - } - if(admDependencyIndex >= currentSchoolYear.adm_dependencies.length || admDependency.adm_dependency_detailed_id != enrollment.adm_dependency_detailed_id) { // não encontrou - let obj = { - adm_dependency_detailed_id: enrollment.adm_dependency_detailed_id, - adm_dependency_detailed_name: enrollment.adm_dependency_detailed_name, - total: 0 - } - currentSchoolYear.adm_dependencies.splice(admDependencyIndex, 0, obj); - admDependency = obj; - } - admDependency.total += enrollment.total; - - // Adiciona ao total da localidade - let locationIndex = 0; - let location = currentEducation.locations[locationIndex]; - while (locationIndex < currentEducation.locations.length && enrollment.location_id > location.location_id) { - ++locationIndex; - location = currentEducation.locations[locationIndex]; - } - if(locationIndex >= currentEducation.locations.length || location.location_id != enrollment.location_id) { - let obj = { - location_id: enrollment.location_id, - location_name: enrollment.location_name, - total: 0 - } - currentEducation.locations.splice(locationIndex, 0, obj); - location = obj; - } - location.total += enrollment.total; - - locationIndex = 0; - location = currentSchoolYear.locations[locationIndex]; - while (locationIndex < currentSchoolYear.locations.length && enrollment.location_id > location.location_id) { - ++locationIndex; - location = currentSchoolYear.locations[locationIndex]; - } - if(locationIndex >= currentSchoolYear.locations.length || location.location_id != enrollment.location_id) { - let obj = { - location_id: enrollment.location_id, - location_name: enrollment.location_name, - total: 0 - } - currentSchoolYear.locations.splice(locationIndex, 0, obj); - location = obj; - } - location.total += enrollment.total; - - ++i; - } - - req.result = result; - - next(); -}, response('enrollment_diagnosis')); - -enrollmentApp.get('/projection', rqf.parse(), (req, res, next) => { - req.dims = {}; - req.dims.state = true; - req.dims.city = true; - req.dims.location = true; - req.dims.school_year = true; - req.dims.adm_dependency = true; - req.dims.period = true; - req.filter.adm_dependency = [1,2,3]; - - req.sql.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .from('matricula') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo<=3'); - - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - let enrollments = req.result; - - // Gera a relação etapa de ensino X ano escolar - let educationSchoolYear = {}; - for(let i = 10; i < 80; ++i) { - if(id2str.schoolYear(i) !== id2str.schoolYear(99)) { - let educationLevelId = Math.floor(i/10); - educationSchoolYear[i] = { - id: educationLevelId, - name: id2str.educationLevelShort(educationLevelId), - }; - } - } - - console.log(educationSchoolYear); - - let result = []; - let educationLevelSet = new Set(); - let schoolYearSet = new Set(); - let i = 0; - while(i < enrollments.length) { - let enrollment = enrollments[i]; - if(!educationSchoolYear[enrollment.school_year_id]) { - ++i; - continue; - } - let educationLevelHash = '' + enrollment.year + educationSchoolYear[enrollment.school_year_id].id + enrollment.city_id; - let schoolYearHash = '' + enrollment.year + enrollment.school_year_id + enrollment.city_id; - - let currentEducation = null; - // Busca ou cria a etapa de ensino adequada - if(educationLevelSet.has(educationLevelHash)) { - let j = 0; - let edu = result[j]; - while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != educationSchoolYear[enrollment.school_year_id].id)) { - ++j; - edu = result[j]; - } - if((j >= result.length)) --j; - edu = result[j]; - - currentEducation = edu; - } else { - educationLevelSet.add(educationLevelHash); - let obj = { - year: enrollment.year, - name: enrollment.name, - state_id: enrollment.state_id, - state_name: enrollment.state_name, - city_id: enrollment.city_id, - city_name: enrollment.city_name, - education_level_school_year_id: educationSchoolYear[enrollment.school_year_id].id, - education_level_school_year_name: educationSchoolYear[enrollment.school_year_id].name, - urban_day_total: 0, - urban_night_total: 0, - rural_day_total: 0, - rural_night_total: 0 - }; - result.push(obj); - currentEducation = obj; - } - - let currentSchoolYear = null; - // Busca ou cria a série adequada - if(schoolYearSet.has(schoolYearHash)) { - let j = 0; - let edu = result[j]; - while(j < result.length && (edu.year != enrollment.year || edu.education_level_school_year_id != enrollment.school_year_id)){ - ++j; - edu = result[j]; - } - if(j >= result.length) --j; - edu = result[j]; - - currentSchoolYear = edu; - } else { - schoolYearSet.add(schoolYearHash); - let obj = { - year: enrollment.year, - name: enrollment.name, - state_id: enrollment.state_id, - state_name: enrollment.state_name, - city_id: enrollment.city_id, - city_name: enrollment.city_name, - education_level_school_year_id: enrollment.school_year_id, - education_level_school_year_name: enrollment.school_year_name, - urban_day_total: 0, - urban_night_total: 0, - rural_day_total: 0, - rural_night_total: 0 - }; - - result.push(obj); - currentSchoolYear = obj; - } - - if(enrollment.location_id == 1) { - if(enrollment.period_id < 3) { - currentEducation.urban_day_total += enrollment.total; - currentSchoolYear.urban_day_total += enrollment.total; - } else { - currentEducation.urban_night_total += enrollment.total; - currentSchoolYear.urban_night_total += enrollment.total; - } - } else { - if(enrollment.period_id < 3) { - currentEducation.rural_day_total += enrollment.total; - currentSchoolYear.rural_day_total += enrollment.total; - } else { - currentEducation.rural_night_total += enrollment.total; - currentSchoolYear.rural_night_total += enrollment.total; - } - } - - ++i; - } - - req.result = result; - - next(); -}, response('enrollment_projection')); - -module.exports = enrollmentApp; diff --git a/src/libs/routes/enrollmentProjection.js b/src/libs/routes/enrollmentProjection.js deleted file mode 100644 index 7ff2ab2379de73e63ff83f28399019accb7adb3a..0000000000000000000000000000000000000000 --- a/src/libs/routes/enrollmentProjection.js +++ /dev/null @@ -1,159 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const enrollmentProjectionApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -let rqf = new ReqQueryFields(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'projecao_matricula' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'projecao_matricula' - } -}, 'filter').addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'projecao_matricula' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'projecao_matricula' - } -}, 'filter').addValue({ - name: 'min_year', - table: 'projecao_matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'projecao_matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - -enrollmentProjectionApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.field("'Brasil'", 'name') - .field('SUM(projecao_matricula.urbano_dia_total)', 'urban_day_total') - .field('SUM(projecao_matricula.urbano_noite_total)', 'urban_night_total') - .field('SUM(projecao_matricula.rural_dia_total)', 'rural_day_total') - .field('SUM(projecao_matricula.rural_noite_total)', 'rural_night_total') - .field('projecao_matricula.etapa_ensino_escola_ano_id', 'education_level_school_year_id') - .field('projecao_matricula.ano_censo', 'year') - .from('projecao_matricula') - .where('projecao_matricula.etapa_ensino_escola_ano_id <> 7 AND projecao_matricula.etapa_ensino_escola_ano_id < 71') - .group('projecao_matricula.etapa_ensino_escola_ano_id') - .group('projecao_matricula.ano_censo') - .order('projecao_matricula.ano_censo') - .order('projecao_matricula.etapa_ensino_escola_ano_id'); - - next(); -}, query, id2str.transform(), (req, res, next) => { - - req.result.forEach((r) => { - r.urban_day_total = parseInt(r.urban_day_total, 10); - r.urban_night_total = parseInt(r.urban_night_total, 10); - r.rural_day_total = parseInt(r.rural_day_total, 10); - r.rural_night_total = parseInt(r.rural_night_total, 10); - }); - - next(); -}, response('enrollment_projection')); - -module.exports = enrollmentProjectionApp; \ No newline at end of file diff --git a/src/libs/routes/financial.js b/src/libs/routes/financial.js deleted file mode 100644 index bfe272058ce1d385bce3934b49a094140c496f1e..0000000000000000000000000000000000000000 --- a/src/libs/routes/financial.js +++ /dev/null @@ -1,186 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const financialApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -financialApp.get('/year_range', (req, res, next) => { - req.sql.from('indicadores_financeiros') - .field('MIN(indicadores_financeiros.ano_censo)', 'start_year') - .field('MAX(indicadores_financeiros.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -financialApp.get('/years', (req, res, next) => { - req.sql.from('indicadores_financeiros') - .field('DISTINCT indicadores_financeiros.ano_censo', 'year'); - next(); -}, query, response('years')); - -financialApp.get('/sphere_adm', (req, res, next) => { - req.result = [ - {id: 1, name: "1"}, - {id: 2, name: "2"} - ] - next(); -}, response('sphere_adm')); - -financialApp.get('/financial_data', (req, res, next) => { - req.sql.from('indicadores_financeiros') - .field('DISTINCT indicadores_financeiros.dados_financeiros', 'financial_data'); - next(); -}, query, response('financial_data')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'state', - table: 'estado', - tableField: ['sigla', 'id'], - resultField: ['sigla_uf', 'cod_uf'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'indicadores_financeiros' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'indicadores_financeiros' - } -}).addValue({ - name: 'min_year', - table: 'indicadores_financeiros', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'indicadores_financeiros', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'indicadores_financeiros', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'indicadores_financeiros', - field: 'ano_censo' - } -}).addValue({ - name: 'sphere_adm', - table: 'indicadores_financeiros', - tableField: 'esfera_adm', - resultField: 'sphere_adm_id', - where: { - relation: '=', - type: 'integer', - field: 'esfera_adm' - } -}).addValue({ - name: 'city', - table: 'indicadores_financeiros', - tableField: 'municipio_id', - resultField: 'city_id', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id' - } -}).addValue({ - name: 'financial_data', - table: 'indicadores_financeiros', - tableField: 'dados_financeiros', - resultField: 'financial_data_id', - where: { - relation: '=', - type: 'integer', - field: 'dados_financeiros' - } -}); - -financialApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - if ("state" in req.filter) { - req.sql.from('indicadores_financeiros') - .field('indicadores_financeiros.estado_id', 'state_id') - .field('indicadores_financeiros.ano_censo', 'year') - .field('estado.sigla', 'state_abbreviation') - .field('indicadores_financeiros.valor', 'valor') - .field('indicadores_financeiros.esfera_adm', 'sphere_adm_id') - .field('indicadores_financeiros.dados_financeiros', 'financial_data_id') - .group('indicadores_financeiros.ano_censo') - .group('indicadores_financeiros.estado_id') - .group('estado.sigla') - .group('indicadores_financeiros.valor') - .group('indicadores_financeiros.dados_financeiros') - .group('indicadores_financeiros.esfera_adm') - } else { - req.sql.from('indicadores_financeiros') - .field('indicadores_financeiros.estado_id', 'state_id') - .field('indicadores_financeiros.ano_censo', 'year') - .field('estado.sigla', 'state_abbreviation') - .field('indicadores_financeiros.valor', 'valor') - .field('indicadores_financeiros.esfera_adm', 'sphere_adm_id') - .field('indicadores_financeiros.dados_financeiros', 'financial_data_id') - .join('estado', null, 'indicadores_financeiros.estado_id=estado.id') - .group('indicadores_financeiros.ano_censo') - .group('indicadores_financeiros.estado_id') - .group('estado.sigla') - .group('indicadores_financeiros.valor') - .group('indicadores_financeiros.dados_financeiros') - .group('indicadores_financeiros.esfera_adm') - } - next(); -}, query, addMissing(rqf), id2str.transform(), response('financial')); - -module.exports = financialApp; diff --git a/src/libs/routes/glossEnrollmentRatio.js b/src/libs/routes/glossEnrollmentRatio.js deleted file mode 100644 index 7183715a1778fbe4ee9ee9d058ba1b3d6d897189..0000000000000000000000000000000000000000 --- a/src/libs/routes/glossEnrollmentRatio.js +++ /dev/null @@ -1,404 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const glossEnrollmentRatioApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const passport = require('passport'); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -glossEnrollmentRatioApp.use(cache('15 day')); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -glossEnrollmentRatioApp.get('/year_range', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let distinct_years = []; - let new_result = []; - for (let i = 0; i < req.oldResult.length; i++) { - for (let j = 0; j < req.result.length; j++) { - if(req.oldResult[i].year == req.result[j].year) { - distinct_years.push(req.oldResult[i]); - } - } - } - new_result.push({start_year: distinct_years[distinct_years.length -1].year, end_year: distinct_years[0].year}); - req.result = new_result; - next(); -}, response('range')); - -glossEnrollmentRatioApp.get('/years', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let new_result = [] - for (let i = 0; i < req.oldResult.length; i++) { - for (let j = 0; j < req.result.length; j++) { - if(req.oldResult[i].year == req.result[j].year) { - new_result.push(req.oldResult[i]); - } - } - } - req.result = new_result; - next(); -}, response('years')); - -glossEnrollmentRatioApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'pnad\''); - next(); -}, query, response('source')); - -glossEnrollmentRatioApp.get('/education_level_basic', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 4, name: 'Ensino Fundamental - anos iniciais'}, - {id: 5, name: 'Ensino Fundamental - anos finais'}, - {id: 6, name: 'Ensino Médio'} - ]; - next(); -}, response('education_level_basic')); - -glossEnrollmentRatioApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -glossEnrollmentRatioApp.get('/ethnic_group', (req, res, next) => { - req.result = [ - {id: 0, name: 'Sem declaração'}, - {id: 1, name: 'Branca'}, - {id: 2, name: 'Preta'}, - {id: 3, name: 'Parda'}, - {id: 4, name: 'Amarela'}, - {id: 5, name: 'Indígena'} - ]; - next(); -}, response('ethnic_group')); - -glossEnrollmentRatioApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValue({ - name: 'ethnic_group', - table: '@', - tableField: 'cor_raca_id', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca_id' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'gender', - table: '@', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'education_level_basic', - table: 'matricula', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_basic_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}); - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryPartial.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - // console.log('NEW OBJ'); - // console.log(newObj); - // remove total - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - // remove education_level_basic_id - index = keys.indexOf('education_level_basic_id'); - if(index > -1) keys.splice(index, 1); - // remove education_level_basic_name - index = keys.indexOf('education_level_basic_name'); - if(index > -1) keys.splice(index, 1); - let objMatch = null; - - for(let i = 0; i < queryTotal.length; ++i) { - let total = queryTotal[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(total[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - objMatch = total; - break; - } - } - - if(objMatch) { - // console.log('MATCH!!!!'); - // console.log(objMatch); - newObj.total = (result.total / objMatch.total) * 100; - newObj.partial = result.total; - newObj.denominator = objMatch.total - match.push(newObj); - } - }); - // console.log('TAMANHOS'); - // console.log(queryTotal.length); - // console.log(queryPartial.length); - // console.log(match.length); - return match; -} - -glossEnrollmentRatioApp.get('/', rqf.parse(),(req, res, next) => { - req.numerator = {}; - req.denominator = {}; - let glossEnrollmentRatioApp = {}; - - req.sql.from('matricula') - .field('count(*)', 'total') - .field('matricula.ano_censo', 'year') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3') - - if ( "education_level_basic" in req.dims ) { - req.sql.field('matricula.etapas_mod_ensino_segmento_id', 'age_range') - req.sql.where('matricula.etapas_mod_ensino_segmento_id = 1 OR matricula.etapas_mod_ensino_segmento_id = 2 OR matricula.etapas_mod_ensino_segmento_id = 4 OR matricula.etapas_mod_ensino_segmento_id = 5 OR matricula.etapas_mod_ensino_segmento_id = 6') - req.sql.group('matricula.etapas_mod_ensino_segmento_id', 'age_range'); - } - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.numerator = req.result; - req.resetSql(); - req.sql.field('sum(peso)', 'total') - .field('pnad.ano_censo','year') - .from('pnad') - .group('pnad.ano_censo') - .order('pnad.ano_censo') - - function convert(result) { - if (result == 1) { - return 'pnad.faixa_etaria_31_03 = 1' - } else if (result == 2) { - return 'pnad.faixa_etaria_31_03 = 2' - } else if (result == 4) { - return 'pnad.faixa_etaria_31_03 = 3' - } else if (result == 5) { - return 'pnad.faixa_etaria_31_03 = 4' - } else if (result == 6) { - return 'pnad.faixa_etaria_31_03 = 5' - } - } - - //remove education_level_basic how filter and add faixa_etaria_31_03 in filter - if ("education_level_basic" in req.filter) { - if (Array.isArray(req.filter.education_level_basic)) { - var string_query = ''; - for(let i = 0; i < req.filter.education_level_basic.length - 1; i++) { - string_query = string_query + convert(req.filter.education_level_basic[i]) + ' OR '; - } - string_query = string_query + convert(req.filter.education_level_basic[req.filter.education_level_basic.length - 1]); - req.sql.where(string_query); - req.sql.field('pnad.faixa_etaria_31_03','age_range') - req.sql.group('pnad.faixa_etaria_31_03', 'age_range') - } - } else if ( "education_level_basic" in req.dims ) { - req.sql.field('pnad.faixa_etaria_31_03','age_range') - req.sql.where('pnad.faixa_etaria_31_03 = 1 OR pnad.faixa_etaria_31_03 = 2 OR pnad.faixa_etaria_31_03 = 3 OR pnad.faixa_etaria_31_03 = 4 OR pnad.faixa_etaria_31_03 = 5') - req.sql.group('pnad.faixa_etaria_31_03', 'age_range'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); -}, rqf.parse(), (req, res, next) => { - if ("education_level_basic" in req.filter) { - delete req.filter.education_level_basic; - } - if ("education_level_basic" in req.dims) { - delete req.dims.education_level_basic; - } - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.denominator = req.result; - //change age range in denominator to match with numerator result - for(let i = 0; i < req.denominator.length; i++) { - if (req.denominator[i].age_range > 2) { - req.denominator[i].age_range = req.denominator[i].age_range + 1; - } - } - // log.debug("Numerador"); - // log.debug(req.numerator); - // log.debug("Denominador"); - // log.debug(req.denominator); - req.result = [] - let glossEnrollment = matchQueries(req.denominator, req.numerator); - req.result = glossEnrollment; - - next(); -}, response('glossEnrollmentRatio')); - -module.exports = glossEnrollmentRatioApp; diff --git a/src/libs/routes/idhm.js b/src/libs/routes/idhm.js deleted file mode 100644 index f21d2154506e28acbe9aa5dfb388d74debc2d164..0000000000000000000000000000000000000000 --- a/src/libs/routes/idhm.js +++ /dev/null @@ -1,212 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const idhmApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -idhmApp.use(cache('15 day')); - -idhmApp.get('/year_range', (req, res, next) => { - req.sql.from('adh_idh') - .field('MIN(adh_idh.ano_censo)', 'start_year') - .field('MAX(adh_idh.ano_censo)', 'end_year'); - next(); -}, query, (req, res, next) => { - req.sql.from('adh_idh_uf') - .field('MIN(adh_idh_uf.ano_censo)', 'start_year') - .field('MAX(adh_idh_uf.ano_censo)', 'end_year'); - req.old_result = req.result; - next(); -}, query, (req, res, next) => { - if (req.old_result[0].start_year < req.result[0].start_year) { - req.result[0].start_year = req.old_result[0].start_year; - } - if (req.old_result[0].end_year > req.result[0].end_year) { - req.result[0].end_year = req.old_result[0].old_result; - } - next(); -}, query, response('range')); - -idhmApp.get('/years', (req, res, next) => { - req.sql.from('adh_idh') - .field('DISTINCT adh_idh.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('adh_idh_uf') - .field('DISTINCT adh_idh_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -idhmApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'adh_idh\''); - next(); -}, query, response('source')); - -idhmApp.get('/IDHM_level', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Muito Baixa'}, - {id: 2, name: 'Baixo'}, - {id: 3, name: 'Médio'}, - {id: 4, name: 'Alto'}, - {id: 5, name: 'Muito Alto'} - ]; - next(); -}, response('IDHM_level')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'adh_idh' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'adh_idh' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'idhm_level', - table: '@', - tableField: 'idhm_nivel', - resultField: 'idhm_level_id', - where: { - relation: '=', - type: 'integer', - table: '@', - field: 'idhm_nivel' - } -}); - - -idhmApp.get('/', rqf.parse(), (req, res, next) => { - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('adh_idh') - .field('adh_idh.idhm', 'total') - .field('adh_idh.ano_censo', 'year') - .field('adh_idh.municipio_id', 'city_id') - .field('adh_idh.estado_id', 'state_id') - .group('adh_idh.idhm') - .group('adh_idh.ano_censo') - .group('adh_idh.municipio_id') - .group('adh_idh.estado_id') - } else if (("state" in req.filter) || ("state" in req.dims)) { - req.sql.from('adh_idh_uf') - .field('adh_idh_uf.idhm', 'total') - .field('adh_idh_uf.ano_censo', 'year') - .field('adh_idh_uf.estado_id', 'state_id') - .group('adh_idh_uf.idhm') - .group('adh_idh_uf.ano_censo') - .group('adh_idh_uf.estado_id') - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('idhm')); - -module.exports = idhmApp; diff --git a/src/libs/routes/idhme.js b/src/libs/routes/idhme.js deleted file mode 100644 index 25d9e682039f17f6c9059cab30802b1a3c929ba2..0000000000000000000000000000000000000000 --- a/src/libs/routes/idhme.js +++ /dev/null @@ -1,185 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const idhmeApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -idhmeApp.use(cache('15 day')); - -idhmeApp.get('/year_range', (req, res, next) => { - req.sql.from('adh_idh') - .field('MIN(adh_idh.ano_censo)', 'start_year') - .field('MAX(adh_idh.ano_censo)', 'end_year'); - next(); -}, query, (req, res, next) => { - req.sql.from('adh_idh_uf') - .field('MIN(adh_idh_uf.ano_censo)', 'start_year') - .field('MAX(adh_idh_uf.ano_censo)', 'end_year'); - req.old_result = req.result; - next(); -}, query, (req, res, next) => { - if (req.old_result[0].start_year < req.result[0].start_year) { - req.result[0].start_year = req.old_result[0].start_year; - } - if (req.old_result[0].end_year > req.result[0].end_year) { - req.result[0].end_year = req.old_result[0].old_result; - } - next(); -}, query, response('range')); - -idhmeApp.get('/years', (req, res, next) => { - req.sql.from('adh_idh') - .field('DISTINCT adh_idh.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('adh_idh_uf') - .field('DISTINCT adh_idh_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -idhmeApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'adh_idh\''); - next(); -}, query, response('source')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'adh_idh' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'adh_idh' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}); - -idhmeApp.get('/', rqf.parse(), (req, res, next) => { - - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('adh_idh') - .field('adh_idh.idhm_e', 'total') - .field('adh_idh.ano_censo', 'year') - .field('adh_idh.municipio_id', 'city_id') - .group('adh_idh.idhm_e') - .group('adh_idh.ano_censo') - .group('adh_idh.municipio_id'); - } else if (("state" in req.filter) || ("state" in req.dims)) { - req.sql.from('adh_idh_uf') - .field('adh_idh_uf.idhm_e', 'total') - .field('adh_idh_uf.ano_censo', 'year') - .field('adh_idh_uf.estado_id', 'state_id') - .group('adh_idh_uf.idhm_e') - .group('adh_idh_uf.ano_censo') - .group('adh_idh_uf.estado_id'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('idhme')); - -module.exports = idhmeApp; diff --git a/src/libs/routes/idhml.js b/src/libs/routes/idhml.js deleted file mode 100644 index aa811d8f0a4dee6febcede55f33468c75b49f338..0000000000000000000000000000000000000000 --- a/src/libs/routes/idhml.js +++ /dev/null @@ -1,185 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const idhmlApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -idhmlApp.use(cache('15 day')); - -idhmlApp.get('/year_range', (req, res, next) => { - req.sql.from('adh_idh') - .field('MIN(adh_idh.ano_censo)', 'start_year') - .field('MAX(adh_idh.ano_censo)', 'end_year'); - next(); -}, query, (req, res, next) => { - req.sql.from('adh_idh_uf') - .field('MIN(adh_idh_uf.ano_censo)', 'start_year') - .field('MAX(adh_idh_uf.ano_censo)', 'end_year'); - req.old_result = req.result; - next(); -}, query, (req, res, next) => { - if (req.old_result[0].start_year < req.result[0].start_year) { - req.result[0].start_year = req.old_result[0].start_year; - } - if (req.old_result[0].end_year > req.result[0].end_year) { - req.result[0].end_year = req.old_result[0].old_result; - } - next(); -}, query, response('range')); - -idhmlApp.get('/years', (req, res, next) => { - req.sql.from('adh_idh') - .field('DISTINCT adh_idh.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('adh_idh_uf') - .field('DISTINCT adh_idh_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -idhmlApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'adh_idh\''); - next(); -}, query, response('source')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'adh_idh' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'adh_idh' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}); - -idhmlApp.get('/', rqf.parse(), (req, res, next) => { - - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('adh_idh') - .field('adh_idh.idhm_l', 'total') - .field('adh_idh.ano_censo', 'year') - .field('adh_idh.municipio_id', 'city_id') - .group('adh_idh.idhm_l') - .group('adh_idh.ano_censo') - .group('adh_idh.municipio_id'); - } else if (("state" in req.filter) || ("state" in req.dims)) { - req.sql.from('adh_idh_uf') - .field('adh_idh_uf.idhm_l', 'total') - .field('adh_idh_uf.ano_censo', 'year') - .field('adh_idh_uf.estado_id', 'state_id') - .group('adh_idh_uf.idhm_l') - .group('adh_idh_uf.ano_censo') - .group('adh_idh_uf.estado_id'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('idhme')); - -module.exports = idhmlApp; diff --git a/src/libs/routes/idhmr.js b/src/libs/routes/idhmr.js deleted file mode 100644 index d140cc541e3e36f85334a68c8a3815a40c057196..0000000000000000000000000000000000000000 --- a/src/libs/routes/idhmr.js +++ /dev/null @@ -1,188 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const idhmrApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -idhmrApp.use(cache('15 day')); - -idhmrApp.get('/year_range', (req, res, next) => { - req.sql.from('adh_idh') - .field('MIN(adh_idh.ano_censo)', 'start_year') - .field('MAX(adh_idh.ano_censo)', 'end_year'); - next(); -}, query, (req, res, next) => { - req.sql.from('adh_idh_uf') - .field('MIN(adh_idh_uf.ano_censo)', 'start_year') - .field('MAX(adh_idh_uf.ano_censo)', 'end_year'); - req.old_result = req.result; - next(); -}, query, (req, res, next) => { - if (req.old_result[0].start_year < req.result[0].start_year) { - req.result[0].start_year = req.old_result[0].start_year; - } - if (req.old_result[0].end_year > req.result[0].end_year) { - req.result[0].end_year = req.old_result[0].old_result; - } - next(); -}, query, response('range')); - -idhmrApp.get('/years', (req, res, next) => { - req.sql.from('adh_idh') - .field('DISTINCT adh_idh.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('adh_idh_uf') - .field('DISTINCT adh_idh_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -idhmrApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'adh_idh\''); - next(); -}, query, response('source')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'adh_idh' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'adh_idh' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}); - -idhmrApp.get('/', rqf.parse(), (req, res, next) => { - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('adh_idh') - .field('adh_idh.idhm_r', 'total') - .field('adh_idh.ano_censo', 'year') - .field('adh_idh.municipio_id', 'city_id') - .field('adh_idh.estado_id', 'state_id') - .group('adh_idh.idhm_r') - .group('adh_idh.ano_censo') - .group('adh_idh.municipio_id') - .group('adh_idh.estado_id') - } else if (("state" in req.filter) || ("state" in req.dims)) { - req.sql.from('adh_idh_uf') - .field('adh_idh_uf.idhm_r', 'total') - .field('adh_idh_uf.ano_censo', 'year') - .field('adh_idh_uf.estado_id', 'state_id') - .group('adh_idh_uf.idhm_r') - .group('adh_idh_uf.ano_censo') - .group('adh_idh_uf.estado_id') - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - next(); -}, rqf.build(), query, addMissing(rqf), id2str.transform(), response('idhmr')); - -module.exports = idhmrApp; diff --git a/src/libs/routes/infrastructure.js b/src/libs/routes/infrastructure.js deleted file mode 100644 index 8630cb947e57d07f48c75f1f6194a3be62f6d98e..0000000000000000000000000000000000000000 --- a/src/libs/routes/infrastructure.js +++ /dev/null @@ -1,585 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const infrastructureApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -infrastructureApp.use(cache('15 day')); - -infrastructureApp.get('/year_range', (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -infrastructureApp.get('/years', (req, res, next) => { - req.sql.from('escola') - .field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -infrastructureApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'escola\''); - next(); -}, query, response('source')); - -infrastructureApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -infrastructureApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -infrastructureApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -infrastructureApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'id', - resultField: 'city_id', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'filter').addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'id', - resultField: 'state_id', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}, 'filter').addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'location', - table: 'escola', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'escola', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'adm_dependency', - table: 'escola', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'escola', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'min_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryTotal.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - let objMatch = null; - - for(let i = 0; i < queryPartial.length; ++i) { - let partial = queryPartial[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(partial[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - objMatch = partial; - break; - } - } - - if(objMatch) { - newObj.percentage = (objMatch.total / result.total) * 100; - newObj.partial = objMatch.total; - newObj.total = result.total - match.push(newObj); - } - }); - - return match; -} - -infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - // Local de funcionamento - let allSchools = req.sql.clone(); - allSchools.from('escola').field('COUNT(escola.id)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1') - .order('escola.ano_censo'); - req.queryIndex.allSchools = req.querySet.push(allSchools) - 1; - - let schoolPlace = allSchools.clone(); - schoolPlace.where('escola.func_predio_escolar = 1 AND escola.func_salas_empresa = 0 AND escola.func_templo_igreja = 0 AND escola.func_casa_professor = 0 AND escola.func_galpao = 0 AND escola.biblioteca = 1'); - req.queryIndex.schoolPlace = req.querySet.push(schoolPlace) - 1; - - // Bibliotecas - let allLibraries = allSchools.clone(); - allLibraries.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 1'); - req.queryIndex.allLibraries = req.querySet.push(allLibraries) - 1; - - let haveLibraries = allLibraries.clone(); - haveLibraries.where('escola.biblioteca = 1'); - req.queryIndex.haveLibraries = req.querySet.push(haveLibraries) - 1; - - // Bibliotecas/Sala de leitura - let allLibrariesReadingRoom = allSchools.clone(); - allLibrariesReadingRoom.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 2'); - req.queryIndex.allLibrariesReadingRoom = req.querySet.push(allLibrariesReadingRoom) - 1; - - let haveLibrariesReadingRoom = allLibrariesReadingRoom.clone(); - haveLibrariesReadingRoom.where('escola.sala_leitura = 1'); - req.queryIndex.haveLibrariesReadingRoom = req.querySet.push(haveLibrariesReadingRoom) - 1; - - // Laboratório de informática - let allInfLab = allSchools.clone(); - allInfLab.where('escola.func_predio_escolar = 1') - .where('escola.reg_fund_ai = 1 OR escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado = 1 OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1'); - req.queryIndex.allInfLab = req.querySet.push(allInfLab) - 1; - - let haveInfLab = allInfLab.clone(); - haveInfLab.where('escola.lab_informatica = 1'); - req.queryIndex.haveInfLab = req.querySet.push(haveInfLab) - 1; - - // Laboratório de ciências - let allScienceLab = allInfLab.clone(); - req.queryIndex.allScienceLab = req.querySet.push(allScienceLab) - 1; - - let haveScienceLab = allScienceLab.clone(); - haveScienceLab.where('escola.lab_ciencias = 1'); - req.queryIndex.haveScienceLab = req.querySet.push(haveScienceLab) - 1; - - // Parque infantil - let allKidsPark = allSchools.clone(); - allKidsPark.where('escola.func_predio_escolar = 1') - .where('escola.reg_infantil_creche = 1 OR escola.reg_infantil_preescola = 1 OR escola.reg_fund_ai = 1 OR escola.esp_infantil_creche = 1 OR escola.esp_exclusiva_creche = 1 OR escola.reg_esp_exclusiva_fund_ai = 1'); - req.queryIndex.allKidsPark = req.querySet.push(allKidsPark) - 1; - - let haveKidsPark = allKidsPark.clone(); - haveKidsPark.where('escola.parque_infantil = 1'); - req.queryIndex.haveKidsPark = req.querySet.push(haveKidsPark) - 1; - - // Berçário - let allCribs = allSchools.clone(); - allCribs.where('escola.func_predio_escolar = 1') - .where('escola.reg_infantil_creche = 1 OR escola.esp_infantil_creche = 1'); - req.queryIndex.allCribs = req.querySet.push(allCribs) - 1; - - let haveCribs = allCribs.clone(); - haveCribs.where('escola.bercario = 1'); - req.queryIndex.haveCribs = req.querySet.push(haveCribs) - 1; - - // Quadra - let allSportsCourt = allScienceLab.clone(); - allSportsCourt.where('escola.localizacao_id = 1'); - req.queryIndex.allSportsCourt = req.querySet.push(allSportsCourt) - 1; - - let haveSportsCourt = allSportsCourt.clone(); - haveSportsCourt.where('escola.quadra_esportes = 1'); - req.queryIndex.haveSportsCourt = req.querySet.push(haveSportsCourt) - 1; - - // Quadra coberta - req.queryIndex.allCoveredSportsCourt = req.queryIndex.allSportsCourt; - - let haveCoveredSportsCourt = allSportsCourt.clone(); - haveCoveredSportsCourt.where('escola.quadra_esportes_coberta = 1'); - req.queryIndex.haveCoveredSportsCourt = req.querySet.push(haveCoveredSportsCourt) - 1; - - // Quadra Descoberta - let allUncoveredSportsCourt = allSportsCourt.clone(); - allUncoveredSportsCourt.where('escola.quadra_esportes_coberta = 0'); - req.queryIndex.allUncoveredSportsCourt = req.querySet.push(allUncoveredSportsCourt) - 1; - - let haveUncoveredSportsCourt = allUncoveredSportsCourt.clone(); - haveUncoveredSportsCourt.where('escola.quadra_esportes_descoberta = 1'); - req.queryIndex.haveUncoveredSportsCourt = req.querySet.push(haveUncoveredSportsCourt) - 1; - - // Sala de direção - let allDirectorRoom = allSchools.clone(); - allDirectorRoom.where('escola.func_predio_escolar = 1 AND escola.localizacao_id = 1'); - req.queryIndex.allDirectorRoom = req.querySet.push(allDirectorRoom) - 1; - - let haveDirectorRoom = allDirectorRoom.clone(); - haveDirectorRoom.where('escola.sala_diretoria = 1'); - req.queryIndex.haveDirectorRoom = req.querySet.push(haveDirectorRoom) - 1; - - // Secretaria - let allSecretary = allSchools.clone(); - allSecretary.where('escola.func_predio_escolar = 1'); - req.queryIndex.allSecretary = req.querySet.push(allSecretary) - 1; - - let haveSecretary = allSecretary.clone(); - haveSecretary.where('escola.secretaria = 1'); - req.queryIndex.haveSecretary = req.querySet.push(haveSecretary) - 1; - - // Sala de professores - req.queryIndex.allTeacherRoom = req.queryIndex.allSecretary; - - let haveTeacherRoom = allSecretary.clone(); - haveTeacherRoom.where('escola.sala_professor = 1'); - req.queryIndex.haveTeacherRoom = req.querySet.push(haveTeacherRoom) - 1; - - // Cozinha - req.queryIndex.allKitchen = req.queryIndex.allSecretary; - - let haveKitchen = allSecretary.clone(); - haveKitchen.where('escola.cozinha = 1'); - req.queryIndex.haveKitchen = req.querySet.push(haveKitchen) - 1; - - // Despensa - req.queryIndex.allStoreroom = req.queryIndex.allSecretary; - - let haveStoreroom = allSecretary.clone(); - haveStoreroom.where('escola.despensa = 1'); - req.queryIndex.haveStoreroom = req.querySet.push(haveStoreroom) - 1; - - // Almoxarifado - req.queryIndex.allWarehouse = req.queryIndex.allSecretary; - - let haveWarehouse = allSecretary.clone(); - haveWarehouse.where('escola.almoxarifado = 1'); - req.queryIndex.haveWarehouse = req.querySet.push(haveWarehouse) - 1; - - // Internet - req.queryIndex.allInternet = req.queryIndex.allLibrariesReadingRoom; - - let haveInternet = allLibrariesReadingRoom.clone(); - haveInternet.where('escola.internet = 1'); - req.queryIndex.haveInternet = req.querySet.push(haveInternet) - 1; - - // Internet banda larga - req.queryIndex.allBroadbandInternet = req.queryIndex.allLibraries; - - let haveBroadbandInternet = allLibraries.clone(); - haveBroadbandInternet.where('escola.internet_banda_larga = 1'); - req.queryIndex.haveBroadbandInternet = req.querySet.push(haveBroadbandInternet) - 1; - - // Banheiro dentro do prédio - req.queryIndex.allInsideBathroom = req.queryIndex.allSecretary; - - let haveInsideBathroom = allSecretary.clone(); - haveInsideBathroom.where('escola.sanitario_dentro_predio = 1'); - req.queryIndex.haveInsideBathroom = req.querySet.push(haveInsideBathroom) - 1; - - // Banheiro adequado para educação infantil dentro do prédio - req.queryIndex.allInsideKidsBathroom = req.queryIndex.allKidsPark; - - let haveInsideKidsBathroom = allKidsPark.clone(); - haveInsideKidsBathroom.where('escola.sanitario_ei = 1'); - req.queryIndex.haveInsideKidsBathroom = req.querySet.push(haveInsideKidsBathroom) - 1; - - // Fornecimento de energia - req.queryIndex.allEletricEnergy = req.queryIndex.allSecretary; - - let haveEletricEnergy = allSecretary.clone(); - haveEletricEnergy.where('escola.fornecimento_energia = 1'); - req.queryIndex.haveEletricEnergy = req.querySet.push(haveEletricEnergy) - 1; - - // Abastecimento de água - req.queryIndex.allWaterSupply = req.queryIndex.allSecretary; - - let haveWaterSupply = allSecretary.clone(); - haveWaterSupply.where('escola.fornecimento_agua = 1'); - req.queryIndex.haveWaterSupply = req.querySet.push(haveWaterSupply) - 1; - - // Água filtrada - req.queryIndex.allFilteredWater = req.queryIndex.allSecretary; - - let haveFilteredWater = allSecretary.clone(); - haveFilteredWater.where('escola.agua_filtrada = 1'); - req.queryIndex.haveFilteredWater = req.querySet.push(haveFilteredWater) - 1; - - // Coleta de esgoto - req.queryIndex.allSewage = req.queryIndex.allSecretary; - - let haveSewage = allSecretary.clone(); - haveSewage.where('escola.esgoto_sanitario = 1'); - req.queryIndex.haveSewage = req.querySet.push(haveSewage) - 1; - - // Sala de recursos multifuncionais para Atendimento Educacional Especializado - req.queryIndex.allMultifunctionRoom = req.queryIndex.allSecretary; - - let haveMultifunctionRoom = allSecretary.clone(); - haveMultifunctionRoom.where('escola.sala_atendimento_especial = 1'); - req.queryIndex.haveMultifunctionRoom = req.querySet.push(haveMultifunctionRoom) - 1; - - // Banheiros adaptados para pessoas com deficiências - req.queryIndex.allSpecialBathroom = req.queryIndex.allSecretary; - - let haveSpecialBathroom = allSecretary.clone(); - haveSpecialBathroom.where('escola.sanitario_pne = 1'); - req.queryIndex.haveSpecialBathroom = req.querySet.push(haveSpecialBathroom) - 1; - - // Dependências adaptada para pessoas com deficiências - req.queryIndex.allAdaptedBuilding = req.queryIndex.allSecretary; - - let haveAdaptedBuilding = allSecretary.clone(); - haveAdaptedBuilding.where('escola.dependencias_pne = 1'); - req.queryIndex.haveAdaptedBuilding = req.querySet.push(haveAdaptedBuilding) - 1; - - next(); -}, multiQuery, (req, res, next) => { - // Faz o matching entre os resultados - let school_place = matchQueries(req.result[req.queryIndex.allSchools], req.result[req.queryIndex.schoolPlace]); - let libraries = matchQueries(req.result[req.queryIndex.allLibraries], req.result[req.queryIndex.haveLibraries]); - let libraries_reading_room = matchQueries(req.result[req.queryIndex.allLibrariesReadingRoom], req.result[req.queryIndex.haveLibrariesReadingRoom]); - let computer_lab = matchQueries(req.result[req.queryIndex.allInfLab], req.result[req.queryIndex.haveInfLab]); - let science_lab = matchQueries(req.result[req.queryIndex.allScienceLab], req.result[req.queryIndex.haveScienceLab]); - let kids_park = matchQueries(req.result[req.queryIndex.allKidsPark], req.result[req.queryIndex.haveKidsPark]); - let nursery = matchQueries(req.result[req.queryIndex.allCribs], req.result[req.queryIndex.haveCribs]); - let sports_court = matchQueries(req.result[req.queryIndex.allSportsCourt], req.result[req.queryIndex.haveSportsCourt]); - let covered_sports_court = matchQueries(req.result[req.queryIndex.allCoveredSportsCourt], req.result[req.queryIndex.haveCoveredSportsCourt]); - let uncovered_sports_court = matchQueries(req.result[req.queryIndex.allUncoveredSportsCourt], req.result[req.queryIndex.haveUncoveredSportsCourt]); - let director_room = matchQueries(req.result[req.queryIndex.allDirectorRoom], req.result[req.queryIndex.haveDirectorRoom]); - let secretary = matchQueries(req.result[req.queryIndex.allSecretary], req.result[req.queryIndex.haveSecretary]); - let teacher_room = matchQueries(req.result[req.queryIndex.allTeacherRoom], req.result[req.queryIndex.haveTeacherRoom]); - let kitchen = matchQueries(req.result[req.queryIndex.allKitchen], req.result[req.queryIndex.haveKitchen]); - let storeroom = matchQueries(req.result[req.queryIndex.allStoreroom], req.result[req.queryIndex.haveStoreroom]); - let warehouse = matchQueries(req.result[req.queryIndex.allWarehouse], req.result[req.queryIndex.haveWarehouse]); - let internet = matchQueries(req.result[req.queryIndex.allInternet], req.result[req.queryIndex.haveInternet]); - let broadband_internet = matchQueries(req.result[req.queryIndex.allBroadbandInternet], req.result[req.queryIndex.haveBroadbandInternet]); - let inside_bathroom = matchQueries(req.result[req.queryIndex.allInsideBathroom], req.result[req.queryIndex.haveInsideBathroom]); - let inside_kids_bathroom = matchQueries(req.result[req.queryIndex.allInsideKidsBathroom], req.result[req.queryIndex.haveInsideKidsBathroom]); - let eletric_energy = matchQueries(req.result[req.queryIndex.allEletricEnergy], req.result[req.queryIndex.haveEletricEnergy]); - let water_supply = matchQueries(req.result[req.queryIndex.allWaterSupply], req.result[req.queryIndex.haveWaterSupply]); - let filtered_water = matchQueries(req.result[req.queryIndex.allFilteredWater], req.result[req.queryIndex.haveFilteredWater]); - let sewage_treatment = matchQueries(req.result[req.queryIndex.allSewage], req.result[req.queryIndex.haveSewage]); - let special_multifunction_room = matchQueries(req.result[req.queryIndex.allMultifunctionRoom], req.result[req.queryIndex.haveMultifunctionRoom]); - let special_bathroom = matchQueries(req.result[req.queryIndex.allSpecialBathroom], req.result[req.queryIndex.haveSpecialBathroom]); - let adapted_building = matchQueries(req.result[req.queryIndex.allAdaptedBuilding], req.result[req.queryIndex.haveAdaptedBuilding]); - - req.result = [{ - school_place, - libraries, - libraries_reading_room, - computer_lab, - science_lab, - kids_park, - nursery, - sports_court, - covered_sports_court, - uncovered_sports_court, - director_room, - secretary, - teacher_room, - kitchen, - storeroom, - warehouse, - internet, - broadband_internet, - inside_bathroom, - inside_kids_bathroom, - eletric_energy, - water_supply, - filtered_water, - sewage_treatment, - special_multifunction_room, - special_bathroom, - adapted_building - }]; - - next(); -}, id2str.multitransform(false), response('infrastructure')); - -module.exports = infrastructureApp; diff --git a/src/libs/routes/liquidEnrollmentRatio.js b/src/libs/routes/liquidEnrollmentRatio.js deleted file mode 100644 index fd06c5281c870eb8ae208a7312e234e3501940c7..0000000000000000000000000000000000000000 --- a/src/libs/routes/liquidEnrollmentRatio.js +++ /dev/null @@ -1,429 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const liquidEnrollmentRatioApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const passport = require('passport'); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -liquidEnrollmentRatioApp.use(cache('15 day')); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -liquidEnrollmentRatioApp.get('/year_range', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let distinct_years = []; - let new_result = []; - for (let i = 0; i < req.oldResult.length; i++) { - for (let j = 0; j < req.result.length; j++) { - if(req.oldResult[i].year == req.result[j].year) { - distinct_years.push(req.oldResult[i]); - } - } - } - new_result.push({start_year: distinct_years[distinct_years.length -1].year, end_year: distinct_years[0].year}); - req.result = new_result; - next(); -}, response('range')); - -liquidEnrollmentRatioApp.get('/years', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let new_result = [] - for (let i = 0; i < req.oldResult.length; i++) { - for (let j = 0; j < req.result.length; j++) { - if(req.oldResult[i].year == req.result[j].year) { - new_result.push(req.oldResult[i]); - } - } - } - req.result = new_result; - next(); -}, response('years')); - -liquidEnrollmentRatioApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'pnad\''); - next(); -}, query, response('source')); - -liquidEnrollmentRatioApp.get('/education_level_basic', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 4, name: 'Ensino Fundamental - anos iniciais'}, - {id: 5, name: 'Ensino Fundamental - anos finais'}, - {id: 6, name: 'Ensino Médio'} - ]; - next(); -}, response('education_level_basic')); - -liquidEnrollmentRatioApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -liquidEnrollmentRatioApp.get('/ethnic_group', (req, res, next) => { - req.result = [ - {id: 0, name: 'Sem declaração'}, - {id: 1, name: 'Branca'}, - {id: 2, name: 'Preta'}, - {id: 3, name: 'Parda'}, - {id: 4, name: 'Amarela'}, - {id: 5, name: 'Indígena'} - ]; - next(); -}, response('ethnic_group')); - -liquidEnrollmentRatioApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: '@' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValue({ - name: 'ethnic_group', - table: '@', - tableField: 'cor_raca_id', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca_id' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'gender', - table: '@', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'location', - table: '@', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'education_level_basic', - table: 'matricula', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_basic_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}); - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryPartial.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - // console.log('NEW OBJ'); - // console.log(newObj); - // remove total - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - // remove education_level_basic_id - index = keys.indexOf('education_level_basic_id'); - if(index > -1) keys.splice(index, 1); - // remove education_level_basic_name - index = keys.indexOf('education_level_basic_name'); - if(index > -1) keys.splice(index, 1); - let objMatch = null; - - for(let i = 0; i < queryTotal.length; ++i) { - let total = queryTotal[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(total[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - objMatch = total; - break; - } - } - - if(objMatch) { - // console.log('MATCH!!!!'); - // console.log(objMatch); - newObj.total = (result.total / objMatch.total) * 100; - newObj.partial = result.total; - newObj.denominator = objMatch.total - match.push(newObj); - } - }); - // console.log('TAMANHOS'); - // console.log(queryTotal.length); - // console.log(queryPartial.length); - // console.log(match.length); - return match; -} - - -liquidEnrollmentRatioApp.get('/', rqf.parse(),(req, res, next) => { - req.numerator = {}; - req.denominator = {}; - let liquidEnrollmentRatioApp = {}; - - req.sql.from('matricula') - .field('count(*)', 'total') - .field('matricula.ano_censo', 'year') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3') - - function ConvertMatricula(result) { - if (result == 1) { - return '(matricula.faixa_etaria_31_03 = 1 AND matricula.etapas_mod_ensino_segmento_id = 1)' - } else if (result == 2) { - return '(matricula.faixa_etaria_31_03 = 2 AND matricula.etapas_mod_ensino_segmento_id = 2)' - } else if (result == 4) { - return '(matricula.faixa_etaria_31_03 = 3 AND matricula.etapas_mod_ensino_segmento_id = 4)' - } else if (result == 5) { - return '(matricula.faixa_etaria_31_03 = 4 AND matricula.etapas_mod_ensino_segmento_id = 5)' - } else if (result == 6) { - return '(matricula.faixa_etaria_31_03 = 5 AND matricula.etapas_mod_ensino_segmento_id = 6)' - } - } - if ("education_level_basic" in req.filter) { - if (Array.isArray(req.filter.education_level_basic)) { - var string_query_enrollment = ''; - for(let i = 0; i < req.filter.education_level_basic.length - 1; i++) { - string_query_enrollment = string_query_enrollment + ConvertMatricula(req.filter.education_level_basic[i]) + ' OR '; - - } - string_query_enrollment = string_query_enrollment + ConvertMatricula(req.filter.education_level_basic[req.filter.education_level_basic.length - 1]); - delete req.filter.education_level_basic; - req.sql.where(string_query_enrollment); - req.sql.field('matricula.faixa_etaria_31_03', 'age_range') - req.sql.group('matricula.faixa_etaria_31_03', 'age_range'); - } - } else if ( "education_level_basic" in req.dims ) { - req.sql.field('matricula.faixa_etaria_31_03', 'age_range') - req.sql.where('(matricula.etapas_mod_ensino_segmento_id = 1 AND matricula.faixa_etaria_31_03 = 1) OR (matricula.etapas_mod_ensino_segmento_id = 2 AND matricula.faixa_etaria_31_03 = 2) OR (matricula.etapas_mod_ensino_segmento_id = 4 AND matricula.faixa_etaria_31_03 = 3) OR (matricula.etapas_mod_ensino_segmento_id = 5 AND matricula.faixa_etaria_31_03 = 4) OR (matricula.etapas_mod_ensino_segmento_id = 6 AND matricula.faixa_etaria_31_03 = 5)'); - req.sql.group('matricula.faixa_etaria_31_03', 'age_range'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.numerator = req.result; - req.resetSql(); - req.sql.field('sum(peso)', 'total') - .field('pnad.ano_censo','year') - .from('pnad') - .group('pnad.ano_censo') - .order('pnad.ano_censo') - - function convertPnad(result) { - if (result == 1) { - return 'pnad.faixa_etaria_31_03 = 1' - } else if (result == 2) { - return 'pnad.faixa_etaria_31_03 = 2' - } else if (result == 4) { - return 'pnad.faixa_etaria_31_03 = 3' - } else if (result == 5) { - return 'pnad.faixa_etaria_31_03 = 4' - } else if (result == 6) { - return 'pnad.faixa_etaria_31_03 = 5' - } - } - - //remove education_level_basic how filter and add faixa_etaria_31_03 in filter - if ("education_level_basic" in req.filter) { - if (Array.isArray(req.filter.education_level_basic)) { - var string_query = ''; - for(let i = 0; i < req.filter.education_level_basic.length - 1; i++) { - string_query = string_query + convertPnad(req.filter.education_level_basic[i]) + ' OR '; - } - string_query = string_query + convertPnad(req.filter.education_level_basic[req.filter.education_level_basic.length - 1]); - req.sql.where(string_query); - } - req.sql.field('pnad.faixa_etaria_31_03', 'age_range') - req.sql.group('pnad.faixa_etaria_31_03', 'age_range'); - } else if ( "education_level_basic" in req.dims ) { - req.sql.field('pnad.faixa_etaria_31_03','age_range') - req.sql.where('pnad.faixa_etaria_31_03 = 1 OR pnad.faixa_etaria_31_03 = 2 OR pnad.faixa_etaria_31_03 = 3 OR pnad.faixa_etaria_31_03 = 4 OR pnad.faixa_etaria_31_03 = 5') - req.sql.group('pnad.faixa_etaria_31_03', 'age_range'); - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - - next(); -}, rqf.parse(), (req, res, next) => { - if ("education_level_basic" in req.filter) { - delete req.filter.education_level_basic; - } - if ("education_level_basic" in req.dims) { - delete req.dims.education_level_basic; - } - next(); -}, rqf.build(), query, id2str.transform(), (req, res, next) => { - req.denominator = req.result; - - //division to generate req.result final - req.result = [] - let liquidEnrollment = matchQueries(req.denominator, req.numerator); - req.result = liquidEnrollment; - next(); -}, response('liquidEnrollmentRatio')); - -module.exports = liquidEnrollmentRatioApp; diff --git a/src/libs/routes/outOfSchool.js b/src/libs/routes/outOfSchool.js deleted file mode 100644 index 16c5660f482cb1457c05ee81273d1847c1e55c81..0000000000000000000000000000000000000000 --- a/src/libs/routes/outOfSchool.js +++ /dev/null @@ -1,335 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const outOfSchoolApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -outOfSchoolApp.use(cache('15 day')); - -outOfSchoolApp.get('/year_range', (req, res, next) => { - req.sql.from('pnad') - .field('MIN(pnad.ano_censo)', 'start_year') - .field('MAX(pnad.ano_censo)', 'end_year') - .where('pnad.ano_censo >= 2007 AND pnad.ano_censo <= 2015'); - next(); -}, query, response('range')); - -outOfSchoolApp.get('/years', (req, res, next) => { - req.sql.from('pnad'). - field('DISTINCT pnad.ano_censo', 'year') - .where('pnad.ano_censo >= 2007 AND pnad.ano_censo <= 2015'); - next(); -}, query, response('years')); - -outOfSchoolApp.get('/full_age_range', (req, res, next) => { - req.result = [ - {id: 1, name: '0 a 3 anos'}, - {id: 2, name: '4 a 5 anos'}, - {id: 3, name: '6 a 10 anos'}, - {id: 4, name: '11 a 14 anos'}, - {id: 5, name: '15 a 17 anos'}, - {id: 6, name: '18 a 24 anos'}, - {id: 7, name: '25 a 29 anos'}, - {id: 8, name: '30 a 40 anos'}, - {id: 9, name: '41 a 50 anos'}, - {id: 10, name: '51 a 64 anos'}, - {id: 11, name: 'Mais de 64 anos'} - ]; - next(); -}, response('full_age_range')); - -outOfSchoolApp.get('/ethnic_group', (req, res, next) => { - req.result = [ - {id: 0, name: 'Sem declaração'}, - {id: 1, name: 'Branca'}, - {id: 2, name: 'Preta'}, - {id: 3, name: 'Parda'}, - {id: 4, name: 'Amarela'}, - {id: 5, name: 'Indígena'} - ]; - next(); -}, response('ethnic_group')); - -outOfSchoolApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -outOfSchoolApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -outOfSchoolApp.get('/fifth_household_income', (req, res, next) => { - req.result = [ - {id: 1, name: '20% menores'}, - {id: 2, name: '2o quinto'}, - {id: 3, name: '3o quinto'}, - {id: 4, name: '4o quinto'}, - {id: 5, name: '20% maiores'}, - {id: -1, name: 'Sem declaração'} - ]; - next(); -},response('fifth_household_income')); - -outOfSchoolApp.get('/extremes_household_income', (req, res, next) => { - req.result = [ - {id: 1, name: '10% menores'}, - {id: 2, name: '10% maiores'}, - {id: -1, name: 'Sem declaração'} - ]; - next(); -}, response('extremes_household_income')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'pnad' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'pnad' - } -}).addValue({ - name: 'ethnic_group', - table: 'pnad', - tableField: 'cor_raca_id', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca_id' - } -}).addValue({ - name: 'min_year', - table: 'pnad', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'pnad', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'pnad', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'pnad', - field: 'ano_censo' - } -}).addValue({ - name: 'full_age_range', - table: 'pnad', - tableField: 'faixa_etaria_31_03', - resultField: 'full_age_range_id', - where: { - relation: '=', - type: 'integer', - field: 'faixa_etaria_31_03' - } -}).addValue({ - name: 'gender', - table: 'pnad', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'location', - table: 'pnad', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'extremes_household_income', - table: 'pnad', - tableField: 'extremos_nivel_rendimento', - resultField: 'extremes_household_income_id', - where: { - relation: '=', - type: 'integer', - field: 'extremos_nivel_rendimento' - } -}).addValue({ - name: 'fifth_household_income', - table: 'pnad', - tableField: 'quintil_nivel_rendimento', - resultField: 'fifth_household_income_id', - where: { - relation: '=', - type: 'integer', - field: 'quintil_nivel_rendimento' - } -}); - -outOfSchoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.from('pnad') - .field('SUM(pnad.peso)', 'total') - .field('pnad.ano_censo', 'year') - .where('pnad.escolaridade_familiar >= 1 AND pnad.escolaridade_familiar <= 4 AND pnad.frequenta_escola_creche = 4') - .group('pnad.ano_censo') - .order('pnad.ano_censo'); - - next(); -}, query, addMissing(rqf), id2str.transform(), response('out_of_school')); - -// Versão para o SimCAQ -let simcaqRqf = new ReqQueryFields(); - -simcaqRqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'state', - table: 'populacao_fora_da_escola', - tableField: 'unidade_federativa', - resultField: 'state_id', - where: { - relation: '=', - type: 'integer', - field: 'unidade_federativa' - } -}).addValue({ - name: 'pfe', - table: 'populacao_fora_da_escola', - tableField: 'codigo_pfe', - resultField: 'pfe_id', - where: { - relation: '=', - type: 'integer', - field: 'codigo_pfe' - } -}).addValue({ - name: 'min_year', - table: 'populacao_fora_da_escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'populacao_fora_da_escola', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'populacao_fora_da_escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'populacao_fora_da_escola', - field: 'ano_censo' - } -}); - -outOfSchoolApp.get('/simcaq', simcaqRqf.parse(), simcaqRqf.build(), (req, res, next) => { - req.sql.from('populacao_fora_da_escola') - .field('SUM(populacao_fora_da_escola.pop_fora_escola)', 'total') - .field("'Brasil'", 'name') - .field('populacao_fora_da_escola.ano_censo') - .group('populacao_fora_da_escola.ano_censo') - .order('populacao_fora_da_escola.ano_censo'); - - next(); -}, query, (req, res, next) => { - req.result.forEach((i) => { - i.total = parseInt(i.total); - console.log(i.total); - }); - next(); -}, addMissing(simcaqRqf), id2str.transform(), response('out_of_school')); - -module.exports = outOfSchoolApp; diff --git a/src/libs/routes/pibpercapita.js b/src/libs/routes/pibpercapita.js deleted file mode 100644 index 3cb91c5b17f7bba08022b5ad485b34fd06e8ce5f..0000000000000000000000000000000000000000 --- a/src/libs/routes/pibpercapita.js +++ /dev/null @@ -1,211 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const pibpercapitaApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -pibpercapitaApp.use(cache('15 day')); - -pibpercapitaApp.get('/year_range', (req, res, next) => { - req.sql.from('ibge_pib') - .field('MIN(ibge_pib.ano_censo)', 'start_year') - .field('MAX(ibge_pib.ano_censo)', 'end_year') - .where('ibge_pib.ano_censo > 2013'); - next(); -}, query, response('range')); - -pibpercapitaApp.get('/years', (req, res, next) => { - req.sql.from('ibge_pib'). - field('DISTINCT ibge_pib.ano_censo', 'year') - .where('ibge_pib.ano_censo > 2013'); - next(); -}, query, response('years')); - -pibpercapitaApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'ibge_pib\''); - next(); -}, query, response('source')); - -pibpercapitaApp.get('/income_level', (req, res, next) => { - req.result = [ - {id: 1, name: "1º quintil – 20% menores"}, - {id: 2, name: "2º quintil"}, - {id: 3, name: "3º quintil"}, - {id: 4, name: "4º quintil"}, - {id: 5, name: "5º quintil – 20% maiores"}, - ]; - next(); -}, response('income_level')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'ibge_pib' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'ibge_pib' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'ibge_pib' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'ibge_pib' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'regiao_id', - table: 'ibge_pib' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'ibge_pib' - } -}).addValue({ - name: 'min_year', - table: 'ibge_pib', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'ibge_pib', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'income_level', - table: 'ibge_pib', - tableField: 'nivel_renda_per_capita', - resultField: 'income_level_id', - where: { - relation: '=', - type: 'integer', - field: 'nivel_renda_per_capita' - } -}); - -pibpercapitaApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - if (("city" in req.dims) || ("city" in req.filter)) { - req.sql.from('ibge_pib') - .field('ibge_pib.pib_per_capita', 'total') - .field('ibge_pib.ano_censo', 'year') - .group('ibge_pib.ano_censo') - .group('ibge_pib.pib_per_capita') - .order('ibge_pib.ano_censo') - console.log("CiTy") - } else { - req.sql.from('ibge_pib') - .field('SUM(ibge_pib.pib)/SUM(ibge_pib.populacao)', 'total') - .field('ibge_pib.ano_censo', 'year') - .group('ibge_pib.ano_censo') - .order('ibge_pib.ano_censo') - } - next(); -}, query, (req, res, next) => { - req.result.forEach((i) => { - let value = parseFloat(i.total); - let isnum = /^\d+$/.test(value); - if (isnum == true) { - value = value.toFixed(2) - } - // console.log(i.total); - - let res = value.toString().split("."); - //rounding decimal. - let decimal = Math.round(res[1].toString().substring(0,2) + (".") + res[1].toString().substring(2,3)); - //case 0 after comma - if (res[1].toString().substring(0,1) == 0) { - i.total = parseFloat(res[0] + "." + "0" + decimal); - } else { - i.total = parseFloat(res[0] + "." + decimal); - } - // console.log(i.total); - }); - next(); - }, addMissing(rqf), id2str.transform(false), response("pibpercapita")); - - -module.exports = pibpercapitaApp; diff --git a/src/libs/routes/population.js b/src/libs/routes/population.js deleted file mode 100644 index ed644e9ee94259de5a484a9a43e951afb8d23043..0000000000000000000000000000000000000000 --- a/src/libs/routes/population.js +++ /dev/null @@ -1,173 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const populationApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -populationApp.use(cache('15 day')); - -populationApp.get('/year_range', (req, res, next) => { - req.sql.from('ibge_populacao') - .field('MIN(ibge_populacao.ano_censo)', 'start_year') - .field('MAX(ibge_populacao.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -populationApp.get('/years', (req, res, next) => { - req.sql.from('ibge_populacao'). - field('DISTINCT ibge_populacao.ano_censo', 'year'); - next(); -}, query, response('years')); - -populationApp.get('/city_size', (req, res, next) => { - req.result = [ - {id: 1, name: "0 - 5000"}, - {id: 2, name: "5001 - 10000"}, - {id: 3, name: "10001 - 20000"}, - {id: 4, name: "20001 - 50000"}, - {id: 5, name: "50001 - 100000"}, - {id: 6, name: "100001 - 500000"}, - {id: 7, name: "mais que 500000"} - ]; - next(); -}, response('city_size')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'ibge_populacao' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'ibge_populacao' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'ibge_populacao' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'ibge_populacao' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'regiao_id', - table: 'ibge_populacao' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'ibge_populacao' - } -}).addValue({ - name: 'min_year', - table: 'ibge_populacao', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'ibge_populacao', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'city_size', - table: 'ibge_populacao', - tableField: 'porte', - resultField: 'city_size_id', - where: { - relation: '=', - type: 'integer', - field: 'porte' - } -}); - -populationApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.from('ibge_populacao') - .field('SUM(ibge_populacao.populacao)', 'total') - .field('ibge_populacao.ano_censo', 'year') - .group('ibge_populacao.ano_censo') - .order('ibge_populacao.ano_censo') - - next(); -}, query, addMissing(rqf), id2str.transform(false), response('population')); - -module.exports = populationApp; diff --git a/src/libs/routes/portalMec.js b/src/libs/routes/portalMec.js deleted file mode 100644 index 29a1be6b39fae2f62351e000bf3e80dd11df1fb0..0000000000000000000000000000000000000000 --- a/src/libs/routes/portalMec.js +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const portalMecApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'day', - table: 'docente', - tableField: 'nasc_dia', - resultField: 'born_day_id', - where: { - relation: '=', - type: 'integer', - table: 'docente', - field: 'nasc_dia' - } -}).addValue({ - name: 'month', - table: 'docente', - tableField: 'nasc_mes_id', - resultField: 'born_month', - where: { - relation: '=', - type: 'integer', - table: 'docente', - field: 'nasc_mes' - } -}).addValue({ - name: 'year', - table: 'docente', - tableField: 'nasc_ano_id', - resultField: 'born_year', - where: { - relation: '=', - type: 'integer', - table: 'docente', - field: 'nasc_ano' - } -}).addValue({ - name: 'teacher', - table: 'docente', - tableField: 'id', - resultField: 'teacher_id', - where: { - relation: '=', - type: 'integer', - table: 'docente', - field: 'id' - } -}).addValue({ - name: 'min_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'docente', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'docente', - field: 'ano_censo' - } -}); - -portalMecApp.get('/', rqf.parse(), (req, res, next) => { - - req.sql.field('docente.id') - .field('docente.ano_censo', 'year') - .field('docente.cod_quimica', 'Química') - .field('docente.cod_fisica', 'Física') - .field('docente.cod_matematica', 'Matemática') - .field('docente.cod_biologia', 'Biologia') - .field('docente.cod_ciencias', 'Ciências') - .field('docente.cod_literat_port', 'Língua/ Literatura Portuguesa') - .field('docente.cod_literat_ing', 'Língua/ Literatura estrangeira - Inglês') - .field('docente.cod_literat_esp', 'Língua/ Literatura estrangeira - Espanhol') - .field('docente.cod_literat_frances', 'Língua/ Literatura estrangeira - Francês') - .field('docente.literat_outra', 'Língua/ Literatura estrangeira - Outra') - .field('docente.cod_literat_indigena', 'Língua/ Literatura estrangeira - Língua Indígena') - .field('docente.cod_artes', 'Artes (Educação Artística, Teatro, Dança, Música, Artes Plásticas e outras)') - .field('docente.cod_ed_fisica', 'Educação Física') - .field('docente.cod_hist', 'História') - .field('docente.cod_geo', 'Geografia') - .field('docente.cod_filos', 'Filosofia') - .field('docente.cod_ensino_religioso', 'Ensino Religioso') - .field('docente.cod_estudos_sociais', 'Estudos Sociais') - .field('docente.cod_sociologia', 'Sociologia') - .field('docente.cod_inf_comp', 'Informática/ Computação') - .field('docente.cod_profissionalizante', 'Disciplinas profissionalizantes') - .field('docente.cod_disc_atendimento_especiais', 'Disciplinas voltadas ao atendimento às necessidades educacionais específicas dos alunos que são público alvo da educação especial e às práticas educacionais inclusivas') - .field('docente.cod_disc_diversidade_socio_cult', 'Disciplinas voltadas à diversidade sociocultural (Disciplinas pedagógicas)') - .field('docente.cod_libras', 'Libras') - .field('docente.cod_disciplina_pedag', 'Disciplinas pedagógicas') - .field('docente.cod_outras_disciplina', 'Outras disciplinas') - .from('docente') - next(); - -}, rqf.build(), query, response('portalMec')); - -module.exports = portalMecApp; diff --git a/src/libs/routes/portalMecInep.js b/src/libs/routes/portalMecInep.js deleted file mode 100644 index f8108ce46b77928357fa5cdd8232e11a9de9d414..0000000000000000000000000000000000000000 --- a/src/libs/routes/portalMecInep.js +++ /dev/null @@ -1,80 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const portalMecInepApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'school_cod', - table: 'escola', - tableField: 'id', - resultField: 'school_cod_id', - where: { - relation: '=', - type: 'integer', - table: 'escola', - field: 'id' - } -}); - -portalMecInepApp.get('/', rqf.parse(), (req, res, next) => { - - req.sql.field('DISTINCT escola.id', 'id') - .field('escola.nome_escola', 'name') - .from('escola') - .join('estado', null, 'estado.id=escola.estado_id') - .field('estado.nome', 'state_name') - .join('municipio', null, 'municipio.id=escola.municipio_id') - .field('municipio.nome', 'city_name') - - next(); - -}, rqf.build(), query, response('portalMec_inep')); - -module.exports = portalMecInepApp; diff --git a/src/libs/routes/rateSchool.js b/src/libs/routes/rateSchool.js deleted file mode 100644 index a8e9253e38a7241721a61c262ede57c0d1d0562c..0000000000000000000000000000000000000000 --- a/src/libs/routes/rateSchool.js +++ /dev/null @@ -1,343 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const rateSchoolApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const passport = require('passport'); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -rateSchoolApp.use(cache('15 day')); - -let rqf = new ReqQueryFields(); - -// Complete range of the enrollments dataset. -// Returns a tuple of start and ending years of the complete enrollments dataset. -rateSchoolApp.get('/year_range', (req, res, next) => { - req.sql.from('pnad') - .field('MIN(pnad.ano_censo)', 'start_year') - .field('MAX(pnad.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -rateSchoolApp.get('/years', (req, res, next) => { - req.sql.from('pnad') - .field('DISTINCT pnad.ano_censo', 'year'); - next(); -}, query, response('years')); - -rateSchoolApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'pnad\''); - next(); -}, query, response('source')); - -rateSchoolApp.get('/ethnic_group_pnad', (req, res, next) => { - req.result = [ - {id: 0, name: 'Indígena'}, - {id: 1, name: 'Branca e amarela'}, - {id: 2, name: 'Preta e parda'}, - {id: 9, name: 'Sem declaração'} - ]; - next(); -}, response('ethnic_group_pnad')); - -rateSchoolApp.get('/age_range', (req, res, next) => { - req.result = [ - {id: 1, name: '0 a 3 anos'}, - {id: 2, name: '4 a 5 anos'}, - {id: 3, name: '6 a 10 anos'}, - {id: 4, name: '11 a 14 anos'}, - {id: 5, name: '15 a 17 anos'}, - {id: 6, name: '18 a 24 anos'} - ]; - next(); -}, response('age_range')); - -rateSchoolApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - -rateSchoolApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -rateSchoolApp.get('/fifth_household_income', (req, res, next) => { - req.result = [ - {id: 1, name: '20% menores'}, - {id: 2, name: '2o quinto'}, - {id: 3, name: '3o quinto'}, - {id: 4, name: '4o quinto'}, - {id: 5, name: '20% maiores'}, - {id: -1, name: 'Sem declaração'} - ]; - next(); -},response('fifth_household_income')); - -rateSchoolApp.get('/extremes_household_income', (req, res, next) => { - req.result = [ - {id: 1, name: '10% menores'}, - {id: 2, name: '10% maiores'}, - {id: -1, name: 'Sem declaração'} - ]; - next(); -}, response('extremes_household_income')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'pnad' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'pnad' - } -}).addValue({ - name: 'ethnic_group_pnad', - table: 'pnad', - tableField: 'cor_raca', - resultField: 'ethnic_group_pnad_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca' - } -}).addValue({ - name: 'min_year', - table: 'pnad', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: 'pnad', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'pnad', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: 'pnad', - field: 'ano_censo' - } -}).addValue({ - name: 'age_range', - table: 'pnad', - tableField: 'faixa_etaria_31_03', - resultField: 'age_range_id', - where: { - relation: '=', - type: 'integer', - field: 'faixa_etaria_31_03' - } -}).addValue({ - name: 'gender', - table: 'pnad', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'location', - table: 'pnad', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'extremes_household_income', - table: 'pnad', - tableField: 'extremos_nivel_rendimento', - resultField: 'extremes_household_income_id', - where: { - relation: '=', - type: 'integer', - field: 'extremos_nivel_rendimento' - } -}).addValue({ - name: 'fifth_household_income', - table: 'pnad', - tableField: 'quintil_nivel_rendimento', - resultField: 'fifth_household_income_id', - where: { - relation: '=', - type: 'integer', - field: 'quintil_nivel_rendimento' - } -}); - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryTotal.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - // console.log('NEW OBJ'); - // console.log(newObj); - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - let objMatch = null; - - for(let i = 0; i < queryPartial.length; ++i) { - let partial = queryPartial[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(partial[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - objMatch = partial; - break; - } - } - - if(objMatch) { - // console.log(objMatch); - newObj.denominator = result.total; - newObj.partial = objMatch.total; - newObj.total = (objMatch.total / result.total) * 100; - match.push(newObj); - } - }); - - return match; -} - -rateSchoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - log.debug(req.sql.toParam()); - if ("age_range" in req.filter || "age_range" in req.dims) { - let freq_total = req.sql.clone(); - freq_total.field('sum(pnad.peso)', 'total') - .field('pnad.ano_censo','year') - .from('pnad') - .group('pnad.ano_censo') - .order('pnad.ano_censo') - .where('pnad.faixa_etaria_31_03 < 7') - req.queryIndex.freq_total = req.querySet.push(freq_total) - 1; - - let freq_nursery = req.sql.clone(); - freq_nursery.field('sum(pnad.peso)', 'total') - .field('pnad.ano_censo','year') - .from('pnad') - .group('pnad.ano_censo') - .order('pnad.ano_censo') - .where('pnad.frequenta_escola_creche = 2') - .where('pnad.faixa_etaria_31_03 < 7') - req.queryIndex.freq_nursery = req.querySet.push(freq_nursery) - 1; - } - next(); -}, multiQuery, (req, res, next) => { - if ("age_range" in req.filter || "age_range" in req.dims) { - log.debug(req.result[req.queryIndex.freq_total]); - log.debug(req.result[req.queryIndex.freq_nursery]) - let school_attendance_rate = matchQueries(req.result[req.queryIndex.freq_total], req.result[req.queryIndex.freq_nursery]); - req.result = school_attendance_rate; - } else { - res.status(400); - next({ - status: 400, - message: 'Wrong/No filter specified' - }); - } - log.debug(req.result) - next(); -}, id2str.transform(false), response('rateSchool')); - -rateSchoolApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('pnad', 'mapping_pnad')); - -module.exports = rateSchoolApp; diff --git a/src/libs/routes/region.js b/src/libs/routes/region.js deleted file mode 100644 index f36760f3ba4f45ad56c98a95463ab370f5a6261a..0000000000000000000000000000000000000000 --- a/src/libs/routes/region.js +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const regionApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -regionApp.use(cache('15 day')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addValue({ - name: 'id', - table: '@', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id', - table: '@' - } -}).addField({ - name: 'search', - field: false, - where: true -}).addValueToField({ - name: 'name', - table: '@', - tableField: 'nome', - where: { - relation: 'LIKE', - type: 'string', - field: 'nome', - table: '@' - } -}, 'search'); - -regionApp.get('/', rqf.parse(), (req, res, next) => { - req.sql.from('regiao') - .field('id') - .field('nome', 'name'); - next(); -}, rqf.build(), query, response('region')); - -module.exports = regionApp; diff --git a/src/libs/routes/resetToken.js b/src/libs/routes/resetToken.js deleted file mode 100644 index 5fa96b018c68f827e9ea203d5a652e04b0329704..0000000000000000000000000000000000000000 --- a/src/libs/routes/resetToken.js +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const resetTokenApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const ResetToken = require(`${libs}/models/resetToken`); - -const User = require(`${libs}/models/user`); - -resetTokenApp.get('/:token', (req, res, next) => { - let token = req.params.token; - ResetToken.findOne({token: token}, (err, rToken) => { - if(err) { - log.error(err); - return next(err); - } - if(!rToken) { - // TODO: generate new reset token - res.statusCode = 404; - return next({msg: 'Token not found', status:404}); - } - if (rToken.hasExpired()) { - res.statusCode = 410; - ResetToken.remove({token: token}, (err) => { - if(err) { - log.error(err); - next(err); - } - }) - return next({msg: 'Token expired', status: 410}); - } - User.findById(rToken.userId, (err, user) => { - if(err) { - log.error(err); - next(err); - } - let u = user.toObject(); - delete u.salt; - delete u.hashedPassword; - res.json({user: u}); - }); - }); -}); -resetTokenApp.post('/:token', (req, res, next) => { - let token = req.params.token; - ResetToken.findOne({token: token}, (err, rToken) => { - if(err) { - log.error(err); - return next(err); - } - if(!rToken) { - res.statusCode = 404; - return next({msg: 'Token not found', status:404}); - } - User.findById(rToken.userId, (err, user) => { - if(err) { - log.error(err); - next(err); - } - user.password = req.body.password; - user.save((err) => { - if(err) { - log.error(err); - next(err); - } - ResetToken.remove({token: token}, (err) => { - if(err) { - log.error(err); - next(err); - } - }) - res.json({msg: "Senha alterada com sucesso"}); - }) - }); - }); -}) - -module.exports = resetTokenApp; diff --git a/src/libs/routes/school.js b/src/libs/routes/school.js deleted file mode 100644 index 13abdfa8b8ee17f10af1f3c946f903f9353eef9c..0000000000000000000000000000000000000000 --- a/src/libs/routes/school.js +++ /dev/null @@ -1,570 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const schoolApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const request = require(`request`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); -let rqfCount = new ReqQueryFields(); - -// Return location -schoolApp.get('/year_range', cache('15 day'), (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -schoolApp.get('/years', cache('15 day'), (req, res, next) => { - req.sql.from('escola'). - field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -schoolApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'escola\''); - next(); -}, query, response('source')); - -schoolApp.get('/location', cache('15 day'), (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -schoolApp.get('/rural_location', cache('15 day'), (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -schoolApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -schoolApp.get('/adm_dependency_detailed', cache('15 day'), (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -schoolApp.get('/government_agreement', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('government_agreement')); - -schoolApp.get('/agreement', cache('15 day'), (req, res, next) => { - req.result = [ - {id: 1, name: 'Municipal'}, - {id: 2, name: 'Estadual'}, - {id: 3, name: 'Estadual e Municipal'} - ]; - next(); -}, response('agreement')); - -schoolApp.get('/education_day_care_child', (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_day_care_child')); - -schoolApp.get('/education_preschool_child', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_preschool_child')); - -schoolApp.get('/education_begin_elementary_school', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_begin_elementary_school')); - -schoolApp.get('/education_end_elementary_school', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_end_elementary_school')); - -schoolApp.get('/education_middle_school', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_middle_school')); - -schoolApp.get('/education_professional', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_professional')); - -schoolApp.get('/education_eja', cache('15 day'), (req, res, next) => { - req.result = [ - {id: null, name: 'Não Declarado'}, - {id: 0, name: 'Não'}, - {id: 1, name: 'Sim'} - ]; - next(); -}, response('education_eja')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addValue({ - name: 'id', - table: 'escola', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '=', - type: 'integer', - field: 'ano_censo', - table: 'escola' - } -}).addField({ - name: 'search', - field: true, - where: true -}).addValueToField({ - name: 'city_name', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - dontGroup: true, - where: { - relation: 'LIKE', - type: 'string', - field: 'nome' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'search') -.addValueToField({ - name: 'state_name', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - dontGroup: true, - where: { - relation: 'LIKE', - type: 'string', - field: 'sigla' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}, 'search'); - -rqfCount.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'id', - table: 'escola', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'filter').addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '=', - type: 'integer', - field: 'ano_censo', - table: 'escola' - } -}).addValue({ - name: 'location', - table: 'escola', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'escola', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'adm_dependency', - table: 'escola', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'escola', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'government_agreement', - table: 'escola', - tableField: 'conveniada_pp', - resultField: 'government_agreement_id', - where: { - relation: '=', - type: 'boolean', - field: 'conveniada_pp' - } -}).addValue({ - name: 'agreement', - table: 'escola', - tableField: 'tipo_convenio_pp', - resultField: 'agreement_id', - where: { - relation: '=', - type: 'integer', - field: 'tipo_convenio_pp' - } -}).addValue({ - name: 'education_day_care_child', - table: 'escola', - tableField: 'reg_infantil_creche_t1', - resultField: 'education_day_care_child_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_infantil_creche_t1' - } -}).addValue({ - name: 'education_preschool_child', - table: 'escola', - tableField: 'reg_infantil_preescola_t1', - resultField: 'education_preschool_child_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_infantil_preescola_t1' - } -}).addValue({ - name: 'education_begin_elementary_school', - table: 'escola', - tableField: 'reg_fund_ai_t1', - resultField: 'education_begin_elementary_school_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_fund_ai_t1' - } -}).addValue({ - name: 'education_end_elementary_school', - table: 'escola', - tableField: 'reg_fund_af_t1', - resultField: 'education_end_elementary_school_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_fund_af_t1' - } -}).addValue({ - name: 'education_middle_school', - table: 'escola', - tableField: 'reg_medio_medio_t1', - resultField: 'education_middle_school_id', - where: { - relation: '=', - type: 'boolean', - field: 'reg_medio_medio_t1' - } -}).addValue({ - name: 'education_professional', - table: 'escola', - tableField: 'educacao_profissional', - resultField: 'education_professional_id', - where: { - relation: '=', - type: 'boolean', - field: 'educacao_profissional' - } -}).addValue({ - name: 'education_eja', - table: 'escola', - tableField: 'ensino_eja', - resultField: 'education_eja_id', - where: { - relation: '=', - type: 'boolean', - field: 'ensino_eja' - } -}).addValue({ - name: 'min_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'school_building', - table: 'escola', - tableField: 'local_func_predio_escolar', - resultField: 'school_building', - where: { - relation: '=', - type: 'boolean', - field: 'local_func_predio_escolar' - } -}); -schoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - - req.sql.from('escola') - .field('escola.id') - .field('escola.ano_censo', 'year') - .field('escola.nome_escola', 'name') - .field('escola.estado_id', 'state_id') - .field('escola.municipio_id', 'city_id'); - next(); -}, query, response('school')); - -schoolApp.get('/count', cache('15 day'), rqfCount.parse(), rqfCount.build(), (req, res, next) => { - - req.sql.from('escola') - .field('COUNT(escola.id)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .order('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1 AND (escola.ensino_regular = 1 OR escola.ensino_eja=1 or escola.educacao_profissional=1)'); - next(); -}, query, addMissing(rqfCount), id2str.transform(), response('school')); - -schoolApp.get('/count/download', passport.authenticate('bearer', { session: false }), rqfCount.parse(), rqfCount.build(), download('escola', 'mapping_escola')); - -module.exports = schoolApp; diff --git a/src/libs/routes/schoolInfrastructure.js b/src/libs/routes/schoolInfrastructure.js deleted file mode 100644 index f805e8827768eec1c4c6122c25da4be2672d43ce..0000000000000000000000000000000000000000 --- a/src/libs/routes/schoolInfrastructure.js +++ /dev/null @@ -1,728 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const infrastructureApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -infrastructureApp.use(cache('15 day')); - -infrastructureApp.get('/year_range', (req, res, next) => { - req.sql.from('escola') - .field('MIN(escola.ano_censo)', 'start_year') - .field('MAX(escola.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -infrastructureApp.get('/years', (req, res, next) => { - req.sql.from('escola') - .field('DISTINCT escola.ano_censo', 'year'); - next(); -}, query, response('years')); - -infrastructureApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'escola\''); - next(); -}, query, response('source')); - -infrastructureApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -infrastructureApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -infrastructureApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -infrastructureApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'id', - resultField: 'city_id', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'escola' - } -}, 'filter').addValueToField({ - name: 'state', - table: 'estado', - tableField: ['nome', 'id'], - resultField: ['state_name', 'state_id'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}, 'dims').addValueToField({ - name: 'state', - table: 'estado', - tableField: 'id', - resultField: 'state_id', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'escola' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'escola' - } -}, 'filter').addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'escola' - } -}).addValue({ - name: 'location', - table: 'escola', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'escola', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'adm_dependency', - table: 'escola', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'escola', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'min_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'escola', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - -function matchQueries(queryTotal, queryPartial, queryNeeded, zeroPercentage=false) { - let match = []; - queryTotal.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - let partialMatch = null; - let needMatch = null; - - for(let i = 0; i < queryPartial.length; ++i) { - let partial = queryPartial[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(partial[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - partialMatch = partial; - break; - } - } - - if(queryPartial.length == 0) { - partialMatch = JSON.parse(JSON.stringify(result)); - partialMatch.total = 0; - } - - for(let i = 0; i < queryNeeded.length; ++i) { - let needed = queryNeeded[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(needed[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - needMatch = needed; - break; - } - } - - if(queryNeeded.length == 0) { - needMatch = JSON.parse(JSON.stringify(result)); - needMatch.total = 0; - } - - if(partialMatch && needMatch) { - newObj.percentage = (partialMatch.total / result.total) * 100; - if(zeroPercentage) newObj.percentage = 0; - newObj.partial = partialMatch.total; - newObj.total = result.total; - newObj.need_adaptation = needMatch.total; - match.push(newObj); - } - }); - - return match; -} - -infrastructureApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - // Local de funcionamento - let allSchools = req.sql.clone(); - allSchools.from('escola').field('COUNT(escola.id)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1') - .where('escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1') - .where('escola.local_func_predio_escolar = 1') - .where('escola.dependencia_adm_id <= 3') - .order('escola.ano_censo'); - req.queryIndex.allSchools = req.querySet.push(allSchools) - 1; - - let allUrbanSchools = allSchools.clone(); - allUrbanSchools.where('escola.localizacao_id = 1'); - req.queryIndex.allUrbanSchools = req.querySet.push(allUrbanSchools) - 1; - - let allCountrySchools = allSchools.clone(); - allCountrySchools.where('escola.localizacao_id = 2'); - req.queryIndex.allCountrySchools = req.querySet.push(allCountrySchools) - 1; - - let allSchoolsNotSchoolBuilding = req.sql.clone(); - allSchoolsNotSchoolBuilding.from('escola').field('COUNT(escola.id)', 'total') - .field("'Brasil'", 'name') - .field('escola.ano_censo', 'year') - .group('escola.ano_censo') - .where('escola.situacao_de_funcionamento = 1') - .where('escola.ensino_regular = 1 OR escola.ensino_eja = 1 OR escola.educacao_profissional = 1') - .where('escola.local_func_predio_escolar = 0') - .where('escola.dependencia_adm_id <= 3') - .order('escola.ano_censo'); - req.queryIndex.allSchoolsNotSchoolBuilding = req.querySet.push(allSchoolsNotSchoolBuilding) - 1; - - // Bibliotecas - req.queryIndex.allLibraries = req.queryIndex.allUrbanSchools; - - let haveLibraries = allUrbanSchools.clone(); - haveLibraries.where('escola.biblioteca = 1'); - req.queryIndex.haveLibraries = req.querySet.push(haveLibraries) - 1; - - let needLibraries = allUrbanSchools.clone(); - needLibraries.where('escola.biblioteca = 0'); - req.queryIndex.needLibraries = req.querySet.push(needLibraries) - 1; - - // Bibliotecas/Sala de leitura - req.queryIndex.allLibrariesReadingRoom = req.queryIndex.allCountrySchools; - - let haveLibrariesReadingRoom = allCountrySchools.clone(); - haveLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = true'); - req.queryIndex.haveLibrariesReadingRoom = req.querySet.push(haveLibrariesReadingRoom) - 1; - - let needLibrariesReadingRoom = allCountrySchools.clone(); - needLibrariesReadingRoom.where('escola.biblioteca_sala_leitura = false'); - req.queryIndex.needLibrariesReadingRoom = req.querySet.push(needLibrariesReadingRoom) - 1; - - // Laboratório de informática - let allInfLab = allSchools.clone(); - allInfLab.where('escola.reg_infantil_preescola = 1 OR escola.reg_fund_ai = 1 OR escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado = 1 OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1'); - req.queryIndex.allInfLab = req.querySet.push(allInfLab) - 1; - - let haveInfLab = allInfLab.clone(); - haveInfLab.where('escola.lab_informatica = 1'); - req.queryIndex.haveInfLab = req.querySet.push(haveInfLab) - 1; - - let needInfLab = allInfLab.clone(); - needInfLab.where('escola.lab_informatica = 0'); - req.queryIndex.needInfLab = req.querySet.push(needInfLab) - 1; - - // Laboratório de ciências - let allScienceLab = allSchools.clone(); - allScienceLab.where('escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado = 1 OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1'); - req.queryIndex.allScienceLab = req.querySet.push(allScienceLab) - 1; - - let haveScienceLab = allScienceLab.clone(); - haveScienceLab.where('escola.lab_ciencias = true'); - req.queryIndex.haveScienceLab = req.querySet.push(haveScienceLab) - 1; - - let needScienceLab = allScienceLab.clone(); - needScienceLab.where('escola.lab_ciencias = false'); - req.queryIndex.needScienceLab = req.querySet.push(needScienceLab) - 1; - - // Parque infantil - let allKidsPark = allSchools.clone(); - allKidsPark.where('escola.reg_infantil_creche = 1 OR escola.reg_infantil_preescola = 1 OR escola.reg_fund_ai = 1'); - req.queryIndex.allKidsPark = req.querySet.push(allKidsPark) - 1; - - let haveKidsPark = allKidsPark.clone(); - haveKidsPark.where('escola.parque_infantil = 1'); - req.queryIndex.haveKidsPark = req.querySet.push(haveKidsPark) - 1; - - let needKidsPark = allKidsPark.clone(); - needKidsPark.where('escola.parque_infantil = 0'); - req.queryIndex.needKidsPark = req.querySet.push(needKidsPark) - 1; - - // Berçário - let allCribs = allSchools.clone(); - allCribs.where('escola.reg_infantil_creche = 1'); - req.queryIndex.allCribs = req.querySet.push(allCribs) - 1; - - let haveCribs = allCribs.clone(); - haveCribs.where('escola.bercario = 1'); - req.queryIndex.haveCribs = req.querySet.push(haveCribs) - 1; - - let needCribs = allCribs.clone(); - needCribs.where('escola.bercario = 0'); - req.queryIndex.needCribs = req.querySet.push(needCribs) - 1; - - // Quadra Coberta - let allSportsCourt = allSchools.clone(); - allSportsCourt.where('escola.reg_fund_ai = 1 OR escola.reg_fund_af = 1 OR escola.reg_medio_medio = 1 OR escola.reg_medio_integrado OR escola.reg_medio_normal = 1 OR escola.ensino_eja_fund = 1 OR escola.ensino_eja_medio = 1 OR escola.ensino_eja_prof = 1'); - req.queryIndex.allSportsCourt = req.querySet.push(allSportsCourt) - 1; - - let haveSportsCourt = allSportsCourt.clone(); - haveSportsCourt.where('escola.quadra_esportes = 1'); - req.queryIndex.haveSportsCourt = req.querySet.push(haveSportsCourt) - 1; - - let needSportsCourt = allSportsCourt.clone(); - needSportsCourt.where('escola.quadra_esportes = 0'); - req.queryIndex.needSportsCourt = req.querySet.push(needSportsCourt) - 1; - - // Cobertura de quadra esportiva - let allSportsCourtCoverage = allSportsCourt.clone(); - allSportsCourtCoverage.where('escola.quadra_esportes_descoberta = 1'); - req.queryIndex.allSportsCourtCoverage = req.querySet.push(allSportsCourtCoverage); - - req.queryIndex.haveSportsCourtCoverage = req.queryIndex.allSportsCourtCoverage; - - req.queryIndex.needSportsCourtCoverage = req.queryIndex.allSportsCourtCoverage; - - // Pátio - req.queryIndex.allCourtyard = req.queryIndex.allSchools; - - let haveCourtyard = allSchools.clone(); - haveCourtyard.where('escola.patio = 2 OR escola.patio = 1'); - req.queryIndex.haveCourtyard = req.querySet.push(haveCourtyard) - 1; - - let needCourtyard = allSchools.clone(); - needCourtyard.where('escola.patio = 1'); - req.queryIndex.needCourtyard = req.querySet.push(needCourtyard) - 1; - - // Cobertura do Pátio - let allCourtyardCoverage = allSchools.clone(); - allCourtyardCoverage.where('escola.patio = 1'); - req.queryIndex.allCourtyardCoverage = req.querySet.push(allCourtyardCoverage) - 1; - - req.queryIndex.haveCourtyardCoverage = req.queryIndex.allCourtyardCoverage; - - req.queryIndex.needCourtyardCoverage = req.queryIndex.allCourtyardCoverage; - - // Sala de direção - req.queryIndex.allDirectorRoom = req.queryIndex.allLibraries; - - let haveDirectorRoom = allUrbanSchools.clone(); - haveDirectorRoom.where('escola.sala_diretoria = 1'); - req.queryIndex.haveDirectorRoom = req.querySet.push(haveDirectorRoom) - 1; - - let needDirectorRoom = allUrbanSchools.clone(); - needDirectorRoom.where('escola.sala_diretoria = 0'); - req.queryIndex.needDirectorRoom = req.querySet.push(needDirectorRoom) - 1; - - // Secretaria - req.queryIndex.allSecretary = req.queryIndex.allSchools; - - let haveSecretary = allSchools.clone(); - haveSecretary.where('escola.secretaria = 1'); - req.queryIndex.haveSecretary = req.querySet.push(haveSecretary) - 1; - - let needSecretary = allSchools.clone(); - needSecretary.where('escola.secretaria = 0'); - req.queryIndex.needSecretary = req.querySet.push(needSecretary) - 1; - - // Sala de professores - req.queryIndex.allTeacherRoom = req.queryIndex.allSchools; - - let haveTeacherRoom = allSchools.clone(); - haveTeacherRoom.where('escola.sala_professor = 1'); - req.queryIndex.haveTeacherRoom = req.querySet.push(haveTeacherRoom) - 1; - - let needTeacherRoom = allSchools.clone(); - needTeacherRoom.where('escola.sala_professor = 0'); - req.queryIndex.needTeacherRoom = req.querySet.push(needTeacherRoom) - 1; - - // Cozinha - req.queryIndex.allKitchen = req.queryIndex.allSchools; - - let haveKitchen = allSchools.clone(); - haveKitchen.where('escola.cozinha = 1'); - req.queryIndex.haveKitchen = req.querySet.push(haveKitchen) - 1; - - let needKitchen = allSchools.clone(); - needKitchen.where('escola.cozinha = 0'); - req.queryIndex.needKitchen = req.querySet.push(needKitchen) - 1; - - // Despensa - req.queryIndex.allStoreroom = req.queryIndex.allSchools; - - let haveStoreroom = allSchools.clone(); - haveStoreroom.where('escola.despensa = 1'); - req.queryIndex.haveStoreroom = req.querySet.push(haveStoreroom) - 1; - - let needStoreroom = allSchools.clone(); - needStoreroom.where('escola.despensa = 0'); - req.queryIndex.needStoreroom = req.querySet.push(needStoreroom) - 1; - - // Almoxarifado - req.queryIndex.allWarehouse = req.queryIndex.allSchools; - - let haveWarehouse = allSchools.clone(); - haveWarehouse.where('escola.almoxarifado = 1'); - req.queryIndex.haveWarehouse = req.querySet.push(haveWarehouse) - 1; - - let needWarehouse = allSchools.clone(); - needWarehouse.where('escola.almoxarifado = 1'); - req.queryIndex.needWarehouse = req.querySet.push(needWarehouse) - 1; - - // Internet - req.queryIndex.allInternet = req.queryIndex.allLibrariesReadingRoom; - - let haveInternet = allCountrySchools.clone(); - haveInternet.where('escola.internet = 1'); - req.queryIndex.haveInternet = req.querySet.push(haveInternet) - 1; - - let needInternet = allCountrySchools.clone(); - needInternet.where('escola.internet = 0'); - req.queryIndex.needInternet = req.querySet.push(needInternet) - 1; - - // Internet banda larga - req.queryIndex.allBroadbandInternet = req.queryIndex.allLibraries; - - let haveBroadbandInternet = allUrbanSchools.clone(); - haveBroadbandInternet.where('escola.internet_banda_larga = 1'); - req.queryIndex.haveBroadbandInternet = req.querySet.push(haveBroadbandInternet) - 1; - - let needBroadbandInternet = allUrbanSchools.clone(); - needBroadbandInternet.where('escola.internet_banda_larga = 0'); - req.queryIndex.needBroadbandInternet = req.querySet.push(needBroadbandInternet) - 1; - - // Sanitário dentro do prédio - req.queryIndex.allInsideBathroom = req.queryIndex.allSchools; - - let haveInsideBathroom = allSchools.clone(); - haveInsideBathroom.where('escola.sanitario_dentro_predio = 1'); - req.queryIndex.haveInsideBathroom = req.querySet.push(haveInsideBathroom) - 1; - - let needInsideBathroom = allSchools.clone(); - needInsideBathroom.where('escola.sanitario_dentro_predio = 0'); - req.queryIndex.needInsideBathroom = req.querySet.push(needInsideBathroom) - 1; - - // Banheiro adequado para educação infantil dentro do prédio - req.queryIndex.allInsideKidsBathroom = req.queryIndex.allKidsPark; - - let haveInsideKidsBathroom = allKidsPark.clone(); - haveInsideKidsBathroom.where('escola.sanitario_ei = 1'); - req.queryIndex.haveInsideKidsBathroom = req.querySet.push(haveInsideKidsBathroom) - 1; - - let needInsideKidsBathroom = allKidsPark.clone(); - needInsideKidsBathroom.where('escola.sanitario_ei = 0'); - req.queryIndex.needInsideKidsBathroom = req.querySet.push(needInsideKidsBathroom) - 1; - - // Fornecimento de energia - req.queryIndex.allEletricPower = req.queryIndex.allSchools; - - let haveEletricPower = allSchools.clone(); - haveEletricPower.where('escola.fornecimento_energia = 1'); - req.queryIndex.haveEletricPower = req.querySet.push(haveEletricPower) - 1; - - let needEletricPower = allSchools.clone(); - needEletricPower.where('escola.fornecimento_energia = 0'); - req.queryIndex.needEletricPower = req.querySet.push(needEletricPower) - 1; - - // Abastecimento de água - req.queryIndex.allWaterSupply = req.queryIndex.allSchools; - - let haveWaterSupply = allSchools.clone(); - haveWaterSupply.where('escola.fornecimento_agua = 1'); - req.queryIndex.haveWaterSupply = req.querySet.push(haveWaterSupply) - 1; - - let needWaterSupply = allSchools.clone(); - needWaterSupply.where('escola.fornecimento_agua = 0'); - req.queryIndex.needWaterSupply = req.querySet.push(needWaterSupply) - 1; - - // Água filtrada - req.queryIndex.allFilteredWater = req.queryIndex.allSchools; - - let haveFilteredWater = allSchools.clone(); - haveFilteredWater.where('escola.agua_filtrada = 1'); - req.queryIndex.haveFilteredWater = req.querySet.push(haveFilteredWater) - 1; - - let needFilteredWater = allSchools.clone(); - needFilteredWater.where('escola.agua_filtrada = 0'); - req.queryIndex.needFilteredWater = req.querySet.push(needFilteredWater) - 1; - - // Coleta de esgoto - req.queryIndex.allSewage = req.queryIndex.allSchools; - - let haveSewage = allSchools.clone(); - haveSewage.where('escola.esgoto_sanitario = 1'); - req.queryIndex.haveSewage = req.querySet.push(haveSewage) - 1; - - let needSewage = allSchools.clone(); - needSewage.where('escola.esgoto_sanitario = 0'); - req.queryIndex.needSewage = req.querySet.push(needSewage) - 1; - - // Dependências adaptada para pessoas com deficiências - req.queryIndex.allAdaptedBuilding = req.queryIndex.allSchools; - - let haveAdaptedBuilding = allSchools.clone(); - haveAdaptedBuilding.where('escola.dependencias_pne = 1'); - req.queryIndex.haveAdaptedBuilding = req.querySet.push(haveAdaptedBuilding) - 1; - - let needAdaptedBuilding = allSchools.clone(); - needAdaptedBuilding.where('escola.dependencias_pne = 0'); - req.queryIndex.needAdaptedBuilding = req.querySet.push(needAdaptedBuilding) - 1; - - // Banheiros adaptados para pessoas com deficiências - req.queryIndex.allSpecialBathroom = req.queryIndex.allSchools; - - let haveSpecialBathroom = allSchools.clone(); - haveSpecialBathroom.where('escola.sanitario_pne = 1'); - req.queryIndex.haveSpecialBathroom = req.querySet.push(haveSpecialBathroom) - 1; - - let needSpecialBathroom = allSchools.clone(); - needSpecialBathroom.where('escola.sanitario_pne = 1'); - req.queryIndex.needSpecialBathroom = req.querySet.push(needSpecialBathroom) - 1; - - - next(); -}, multiQuery, (req, res, next) => { - let schools_in_school_buildings = req.result[req.queryIndex.allSchools]; - let urban_schools_in_school_buildings = req.result[req.queryIndex.allUrbanSchools]; - let country_schools_in_school_buildings = req.result[req.queryIndex.allCountrySchools]; - let schools_not_in_school_buildings = req.result[req.queryIndex.allSchoolsNotSchoolBuilding]; - // Faz o matching entre os resultados - let libraries = matchQueries(req.result[req.queryIndex.allLibraries], req.result[req.queryIndex.haveLibraries], req.result[req.queryIndex.needLibraries]); - let libraries_reading_room = matchQueries(req.result[req.queryIndex.allLibrariesReadingRoom], req.result[req.queryIndex.haveLibrariesReadingRoom], req.result[req.queryIndex.needLibrariesReadingRoom]); - let computer_lab = matchQueries(req.result[req.queryIndex.allInfLab], req.result[req.queryIndex.haveInfLab], req.result[req.queryIndex.needInfLab]); - let science_lab = matchQueries(req.result[req.queryIndex.allScienceLab], req.result[req.queryIndex.haveScienceLab], req.result[req.queryIndex.needScienceLab]); - let kids_park = matchQueries(req.result[req.queryIndex.allKidsPark], req.result[req.queryIndex.haveKidsPark], req.result[req.queryIndex.needKidsPark]); - let nursery = matchQueries(req.result[req.queryIndex.allCribs], req.result[req.queryIndex.haveCribs], req.result[req.queryIndex.needCribs]); - let sports_court = matchQueries(req.result[req.queryIndex.allSportsCourt], req.result[req.queryIndex.haveSportsCourt], req.result[req.queryIndex.needSportsCourt]); - let sports_court_coverage = matchQueries(req.result[req.queryIndex.allSportsCourtCoverage], req.result[req.queryIndex.haveSportsCourtCoverage], req.result[req.queryIndex.needSportsCourtCoverage], true); - let courtyard = matchQueries(req.result[req.queryIndex.allCourtyard], req.result[req.queryIndex.haveCourtyard], req.result[req.queryIndex.needCourtyard]); - let courtyard_coverage = matchQueries(req.result[req.queryIndex.allCourtyardCoverage], req.result[req.queryIndex.haveCourtyardCoverage], req.result[req.queryIndex.needCourtyardCoverage], true); - let director_room = matchQueries(req.result[req.queryIndex.allDirectorRoom], req.result[req.queryIndex.haveDirectorRoom], req.result[req.queryIndex.needDirectorRoom]); - let secretary = matchQueries(req.result[req.queryIndex.allSecretary], req.result[req.queryIndex.haveSecretary], req.result[req.queryIndex.needSecretary]); - let teacher_room = matchQueries(req.result[req.queryIndex.allTeacherRoom], req.result[req.queryIndex.haveTeacherRoom], req.result[req.queryIndex.needTeacherRoom]); - let kitchen = matchQueries(req.result[req.queryIndex.allKitchen], req.result[req.queryIndex.haveKitchen], req.result[req.queryIndex.needKitchen]); - let storeroom = matchQueries(req.result[req.queryIndex.allStoreroom], req.result[req.queryIndex.haveStoreroom], req.result[req.queryIndex.needStoreroom]); - let warehouse = matchQueries(req.result[req.queryIndex.allWarehouse], req.result[req.queryIndex.haveWarehouse], req.result[req.queryIndex.needWarehouse]); - let internet = matchQueries(req.result[req.queryIndex.allInternet], req.result[req.queryIndex.haveInternet], req.result[req.queryIndex.needInternet]); - let broadband_internet = matchQueries(req.result[req.queryIndex.allBroadbandInternet], req.result[req.queryIndex.haveBroadbandInternet], req.result[req.queryIndex.needBroadbandInternet]); - let inside_bathroom = matchQueries(req.result[req.queryIndex.allInsideBathroom], req.result[req.queryIndex.haveInsideBathroom], req.result[req.queryIndex.needInsideBathroom]); - let inside_kids_bathroom = matchQueries(req.result[req.queryIndex.allInsideKidsBathroom], req.result[req.queryIndex.haveInsideKidsBathroom], req.result[req.queryIndex.needInsideKidsBathroom]); - let eletrical_power = matchQueries(req.result[req.queryIndex.allEletricPower], req.result[req.queryIndex.haveEletricPower], req.result[req.queryIndex.needEletricPower]); - let water_supply = matchQueries(req.result[req.queryIndex.allWaterSupply], req.result[req.queryIndex.haveWaterSupply], req.result[req.queryIndex.needWaterSupply]); - let filtered_water = matchQueries(req.result[req.queryIndex.allFilteredWater], req.result[req.queryIndex.haveFilteredWater], req.result[req.queryIndex.needFilteredWater]); - let sewage = matchQueries(req.result[req.queryIndex.allSewage], req.result[req.queryIndex.haveSewage], req.result[req.queryIndex.needSewage]); - let adapted_building = matchQueries(req.result[req.queryIndex.allAdaptedBuilding], req.result[req.queryIndex.haveAdaptedBuilding], req.result[req.queryIndex.needAdaptedBuilding]); - let adapted_bathroom = matchQueries(req.result[req.queryIndex.allSpecialBathroom], req.result[req.queryIndex.haveSpecialBathroom], req.result[req.queryIndex.needSpecialBathroom]); - - req.result = [{ - schools_in_school_buildings, - urban_schools_in_school_buildings, - country_schools_in_school_buildings, - schools_not_in_school_buildings, - libraries, - libraries_reading_room, - computer_lab, - science_lab, - kids_park, - nursery, - sports_court, - sports_court_coverage, - courtyard, - courtyard_coverage, - director_room, - secretary, - teacher_room, - kitchen, - storeroom, - warehouse, - internet, - broadband_internet, - inside_bathroom, - inside_kids_bathroom, - eletric_energy: eletrical_power, - water_supply, - filtered_water, - sewage_treatment: sewage, - adapted_building, - special_bathroom: adapted_bathroom - }]; - - next(); -}, id2str.multitransform(false), response('infrastructure')); - -module.exports = infrastructureApp; diff --git a/src/libs/routes/simulation.js b/src/libs/routes/simulation.js deleted file mode 100644 index 8003b54dcdf7eea11d98e051de865c919b896744..0000000000000000000000000000000000000000 --- a/src/libs/routes/simulation.js +++ /dev/null @@ -1,187 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const simulationApp = express(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const Simulation = require(`${libs}/models/simulation`); - -const PQR = require(`${libs}/models/pqr`); - -const passport = require('passport'); - -simulationApp.get('/time', (req, res, next) => { - const maxTime = parseInt(req.query.max_time, 10); - if(isNaN(maxTime)) { - res.status(400); - next({ - status: 400, - message: 'Invalid value for mandatory parameter max_time' - }); - } - res.json({ - result: Array.apply(null, {length: maxTime}).map(Number.call, Number).map((i)=>i+1) - }); -}); - -simulationApp.get('/pqr', (req, res) => { - PQR.findOne((err, pqr) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json(pqr); - }); -}); - -simulationApp.put('/pqr', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - - PQR.findOne((err, pqr) => { - if(err) { - log.error(err) - return next({err}); - } - - if(!user.admin) { - log.info(`Usuário ${user.email} tentou alterar o PQR, mas não tem privilégio`); - res.statusCode = 401; - return next({err: { msg: 'Unauthorized'}}); - } - pqr.content = req.body.content || pqr.content; - pqr.save((err) => { - if(err) { - log.error(err); - return next({err}); - } - res.json({msg: 'PQR updated'}) - }); - }); -}); - -simulationApp.get('/', passport.authenticate('bearer', { session: false }), (req, res) => { - let user = req.user.toObject(); - let query = Simulation.find({userId: user._id}).select('userId name createdAt updatedAt'); - query.exec((err, simulations) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json(simulations); - }); - - // Simulation.find({userId: user._id}, (err, simulations) => { - // if(err) { - // log.error(err); - // return next({err}); - // } - - // res.json(simulations); - // }); -}); - -simulationApp.post('/', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - - let simulation = new Simulation({ - userId: user._id, - content: req.body.content, - name: req.body.name - }); - - simulation.save((err) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json({msg: 'Simulation created', simulation}); - }) -}); - -simulationApp.get('/:id', passport.authenticate('bearer', { session: false }), (req, res) => { - let user = req.user.toObject(); - - Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json(simulation); - }); -}); - -simulationApp.put('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - - Simulation.findOne({_id: req.params.id, userId: user._id}, (err, simulation) => { - if(err) { - log.error(err); - return next({err}); - } - - if(!simulation) { - res.statusCode = 404; - return next({err: { msg: 'Simulation not found'}}); - } - - simulation.content = req.body.content || simulation.content; - simulation.name = req.body.name || simulation.name; - simulation.updatedAt = Date.now(); - - simulation.save((err) => { - if(err) { - log.error(err); - return next(err); - } - - res.json(simulation); - }); - }); -}); - -simulationApp.delete('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - - Simulation.remove({_id: req.params.id, userId: user._id}, (err, simulation) => { - if(err) { - log.error(err); - return next({err}); - } - - res.json({msg: 'Simulation removed'}); - }); -}); - -module.exports = simulationApp; diff --git a/src/libs/routes/siope.js b/src/libs/routes/siope.js deleted file mode 100644 index 615e2225477a1631df2b862f3e75276632a183b0..0000000000000000000000000000000000000000 --- a/src/libs/routes/siope.js +++ /dev/null @@ -1,186 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const siopeApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -siopeApp.use(cache('15 day')); - -siopeApp.get('/years', (req, res, next) => { - req.sql.from('siope_mun') - .field('DISTINCT siope_mun.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - req.oldResult = req.result; - - req.sql = squel.select(); - - req.sql.from('siope_uf') - .field('DISTINCT siope_uf.ano_censo', 'year'); - next(); -}, query, (req, res, next) => { - let result = Object.assign(req.oldResult, req.result); - req.result = result; - next(); -}, response('years')); - -rqf.addField({ - name: 'filter', - field: true, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'siope_mun' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'siope_mun' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: ['id','nome','sigla'], - resultField: ['state_id','state_name','state_abbreviation'], - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: '@' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: '@' - } -}).addValue({ - name: 'min_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: '@', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - table: '@', - field: 'ano_censo' - } -}); - - - -siopeApp.get('/', rqf.parse(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - let siopeUf = req.sql.clone(); - siopeUf.from('siope_uf') - .field('siope_uf.ano_censo', 'year') - .field('siope_uf.estado_id', 'state_id') - .field('siope_uf.fundeb', 'fundeb') - .field('siope_uf.total_impostos', 'impostos') - .field('siope_uf.total_mde', 'MDE') - .group('siope_uf.ano_censo') - .group('siope_uf.estado_id') - .group('siope_uf.fundeb') - .group('siope_uf.total_impostos') - .group('siope_uf.total_mde') - .order('siope_uf.ano_censo'); - req.queryIndex.siopeUf = req.querySet.push(siopeUf) - 1; - - let siopeMun = req.sql.clone(); - siopeMun.from('siope_mun') - .field('siope_mun.ano_censo', 'year') - .field('siope_mun.estado_id', 'state_id') - .field('siope_mun.municipio_id', 'city_id') - .field('siope_mun.fundeb', 'fundeb') - .field('siope_mun.total_impostos', 'impostos') - .field('siope_mun.total_mde', 'MDE') - .group('siope_mun.ano_censo') - .group('siope_mun.estado_id') - .group('siope_mun.municipio_id') - .group('siope_mun.fundeb') - .group('siope_mun.total_impostos') - .group('siope_mun.total_mde') - .order('siope_mun.ano_censo'); - req.queryIndex.siopeMun = req.querySet.push(siopeMun) - 1; - - next(); -}, rqf.multibuild(), multiQuery, (req, res, next) => { - - let result = [] - - req.result[req.queryIndex.siopeUf].forEach((item) => { - result.push(item) - }); - req.result[req.queryIndex.siopeMun].forEach((item) => { - result.push(item) - }); - - req.result = result; - next(); - -}, response('siope')); - -module.exports = siopeApp; diff --git a/src/libs/routes/spatial.js b/src/libs/routes/spatial.js deleted file mode 100644 index dd7fe97a5b21eb49997866353ce3dc4e7513844b..0000000000000000000000000000000000000000 --- a/src/libs/routes/spatial.js +++ /dev/null @@ -1,373 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const log = require(`${libs}/log`)(module); - -const query = require(`${libs}/middlewares/query`).query; - -const sqlQuery = require(`${libs}/db/query_exec`); - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const spatialApp = express(); - -let rqf = new ReqQueryFields(); - -function processResultSet(querySet, querySetLabels = ["result"], singleResult = false) { - const resultMap = new Map(); - let resultIdx = 0; - // loop relies on the fact that Promise.all maintains the order of the original iterable - for(let result of querySet) { - const resultLbl = querySetLabels[resultIdx]; - resultMap[resultLbl] = []; - if (singleResult) { - resultMap[resultLbl] = result[0]; - } else { - for(let row of result) { - resultMap[resultLbl].push(row); - } - } - resultIdx++; - } - return resultMap; -} - -function dbExecAll(querySet = []) { - // Issue all queries concurrently to the database, for every query object in the iterable - // NOTE: Array.map() returns a copy of the original array with each object 'mapped'. - return querySet.map((qry) => { return sqlQuery(qry.toString()); }); -} - -rqf.addField({ - name: 'filter', - field: true, - where: true -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'estado_id' - } -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'municipio_id' - } -}).addValue({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}); - -spatialApp.get('/sociodemographic', rqf.parse(), rqf.build(), (req, res, next) => { - const populationYearQry = squel.select() - .field('MAX(ibge_populacao.ano_censo)') - .from('ibge_populacao'); - - const populationQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('SUM(populacao)', 'population') - .field('ibge_populacao.ano_censo', 'census_year') - .from('ibge_populacao') - .where(`ibge_populacao.ano_censo IN (${populationYearQry.toString()})`) - .group('ibge_populacao.ano_censo'); - - const pibYearQry = squel.select() - .field('MAX(ibge_pib.ano_censo)') - .from('ibge_pib'); - - const pibQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('AVG(ibge_pib.pib_per_capita)', 'gdp_per_capita') - .field('ibge_pib.ano_censo', 'census_year') - .from('ibge_pib') - .where(`ibge_pib.ano_censo IN (${pibYearQry.toString()})`) - .group('ibge_pib.ano_censo'); - - const idhYearQry = squel.select() - .field('MAX(adh_idh.ano_censo)') - .from('adh_idh'); - - const idhQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('AVG(idhm)', 'idhm') - .field('adh_idh.ano_censo', 'census_year') - .from('adh_idh') - .where(`adh_idh.ano_censo IN (${idhYearQry.toString()})`) - .group('adh_idh.ano_censo'); - - const analfabYearQry = squel.select() - .field('MAX(adh_analfabetismo.ano_censo)') - .from('adh_analfabetismo'); - - const analfabQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('AVG(t_analf15m)', 'analfabetism') - .field('adh_analfabetismo.ano_censo', 'census_year') - .from('adh_analfabetismo') - .where(`adh_analfabetismo.ano_censo IN (${analfabYearQry.toString()})`) - .group('adh_analfabetismo.ano_censo'); - - const giniYearQry = squel.select() - .field('MAX(adh_gini.ano_censo)') - .from('adh_gini'); - - const giniQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('AVG(gini)', 'gini') - .field('adh_gini.ano_censo', 'census_year') - .from('adh_gini') - .where(`adh_gini.ano_censo IN (${giniYearQry.toString()})`) - .group('adh_gini.ano_censo'); - - // map query objects to their respective response labels - const queryLabels = [ "population", "gdp", "idh", "analfab", "gini" ]; - const querySet = [ populationQry, pibQry, idhQry, analfabQry, giniQry ]; - // wait until all queries finish or one of them fail - Promise.all(dbExecAll(querySet)).then((queryResults) => { - req.result = processResultSet(queryResults, queryLabels, true); - next(); - }).catch((error) => { - log.error(`[SQL query error] ${error}`); - next(error); - }); -}, response('spatial')); - -spatialApp.get('/educational', rqf.parse(), rqf.build(), (req, res, next) => { - const censusYearQry = squel.select() - .field('MAX(escola.ano_censo)', 'ano_censo') - .from('escola') - .toString(); - - const totalSchoolsQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('\'Total\'', 'location_name') - .field('COUNT(DISTINCT(escola.id))', 'total') - .field('escola.ano_censo', 'census_year') - .from('turma') - .from('escola') - .where('escola.ano_censo=turma.ano_censo AND escola.id=turma.escola_id') - .where(`escola.ano_censo IN (${censusYearQry})`) - .where('turma.tipo_turma_id = 0') - .group('escola.ano_censo'); - - const schoolsPerLocationQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COUNT(DISTINCT(escola.id))', 'total') - .field('escola.ano_censo', 'census_year') - .field('localizacao.descricao', 'location_name') - .from('localizacao') - .from('turma') - .from('escola') - .where('escola.localizacao_id=localizacao.id') - .where('escola.ano_censo=turma.ano_censo AND escola.id=turma.escola_id') - .where(`escola.ano_censo IN (${censusYearQry})`) - .where('turma.tipo_turma_id = 0') - .group('escola.localizacao_id') - .group('escola.ano_censo') - .group('localizacao.descricao') - .order('localizacao.descricao'); - - const schoolsPerAdmDependencyQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COUNT(DISTINCT(escola.id))', 'total') - .field('escola.ano_censo', 'census_year') - .field('dependencia_adm.nome', 'adm_dependency_name') - .from('dependencia_adm') - .from('escola') - .where('escola.dependencia_adm_id=dependencia_adm.id') - .where(`escola.ano_censo IN (${censusYearQry})`) - .group('escola.ano_censo') - .group('dependencia_adm.nome') - .order('escola.ano_censo') - .order('dependencia_adm.nome'); - - const enrollmentsQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COALESCE(SUM(uc201.matriculas), 0)', 'total') - .field('uc201.ano_censo', 'census_year') - .from('uc201') - .group('uc201.ano_censo'); - - const enrollmentsPerAdmDepQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COALESCE(SUM(uc201.matriculas), 0)', 'total') - .field('uc201.ano_censo', 'census_year') - .field('dependencia_adm.nome', 'adm_dependency_name') - .from('dependencia_adm') - .from('uc201') - .where('uc201.dependencia_adm_id=dependencia_adm.id') - .group('dependencia_adm.nome') - .group('uc201.ano_censo'); - - const enrollmentsPerSchoolLevelQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COALESCE(SUM(uc201.matriculas), 0)', 'total') - .field('uc201.ano_censo', 'census_year') - .field('etapa_ensino.desc_etapa', 'school_level_name') - .field('dependencia_adm.nome', 'adm_dependency_name') - .from('etapa_ensino') - .from('dependencia_adm') - .from('uc201') - .where('uc201.etapas_mod_ensino_segmento_id=etapa_ensino.id') - .where('uc201.dependencia_adm_id=dependencia_adm.id') - .group('etapa_ensino.desc_etapa') - .group('dependencia_adm.nome') - .group('uc201.ano_censo'); - - const enrollmentsPerLocationQry = req.sql.clone() - .field('\'Brasil\'', 'name') - .field('COALESCE(SUM(uc201.matriculas), 0)', 'total') - .field('uc201.ano_censo', 'census_year') - .field('localizacao.descricao', 'location_name') - .from('localizacao') - .from('uc201') - .where('uc201.localizacao=localizacao.id') - .group('localizacao.descricao') - .group('uc201.ano_censo'); - - const queryLabels = [ "school", "school_per_location", "school_per_adm_dependency", "enrollment", "enrollment_per_adm_dep", - "enrollment_per_school_level", "enrollment_per_location" ]; - const querySet = [ totalSchoolsQry, schoolsPerLocationQry, schoolsPerAdmDependencyQry, enrollmentsQry, - enrollmentsPerAdmDepQry, enrollmentsPerSchoolLevelQry, enrollmentsPerLocationQry]; - // wait until all queries finish or one of them fail - Promise.all(dbExecAll(querySet)).then((queryResults) => { - req.result = processResultSet(queryResults, queryLabels); - next(); - }).catch((error) => { - log.error(`[SQL query error] ${error}`); - next(error); - }); -}, response('spatial')); - -spatialApp.get('/educational/school_level', rqf.parse(), rqf.build(), (req, res, next) => { - const enrollmentsPerSchoolLevelYearQry = squel.select() - .field('MAX(matricula.ano_censo)', 'census_year') - .from('matricula'); - - const enrollmentsPerSchoolLevelQry = req.sql.clone() - .field('COALESCE(COUNT(matricula.id), 0)', 'total') - .field('matricula.ano_censo', 'census_year') - .field('matricula.serie_ano_id', 'school_year') - .field('etapa_ensino.desc_etapa', 'school_level') - .from('etapa_ensino') - .from('matricula') - .where(`matricula.ano_censo IN (${enrollmentsPerSchoolLevelYearQry.toString()})`) - .where('matricula.etapa_ensino_id = etapa_ensino.id') - .where('matricula.tipo <= 3') - .group('etapa_ensino.desc_etapa') - .group('etapa_ensino.id') - .group('matricula.serie_ano_id') - .group('matricula.ano_censo') - .order('etapa_ensino.id') - .order('matricula.serie_ano_id') - .order('matricula.ano_censo'); - - const queryLabels = [ 'enrollment_per_school_level', 'enrollment_census_year' ]; - const querySet = [ enrollmentsPerSchoolLevelQry, enrollmentsPerSchoolLevelYearQry ]; - // wait until all queries finish or one of them fail - Promise.all(dbExecAll(querySet, enrollmentsPerSchoolLevelYearQry)).then((queryResults) => { - const result = queryResults[0]; - const censusYear = queryResults[1][0]['census_year']; - - let school_levels = {}; - for(let i = 0; i < result.length; ++i) { - const school_year = id2str.schoolYear(result[i].school_year); - const school_level = result[i].school_level; - const census_year = result[i].census_year; - if (typeof school_levels[school_level] === 'undefined') { - school_levels[school_level] = {}; - } - school_levels[school_level][school_year] = parseInt(result[i].total, 10); - } - - let response = []; - for(let level in school_levels) { - if (school_levels.hasOwnProperty(level)) { - let sclevel = {}; - sclevel["degree"] = level; - sclevel["census_year"] = parseInt(censusYear, 10); - sclevel["table"] = []; - for(let school_year in school_levels[level]) { - if (school_levels[level].hasOwnProperty(school_year)) { - let enrollment = { 'title' : school_year, - 'value' : school_levels[level][school_year] }; - sclevel["table"].push(enrollment); - } - } - response.push(sclevel); - } - } - req.result = response; - next(); - }).catch((error) => { - log.error(`[SQL query error] ${error}`); - next(error); - }); -}, response('spatial')); - -module.exports = spatialApp; diff --git a/src/libs/routes/state.js b/src/libs/routes/state.js deleted file mode 100644 index cb84a09662e886ffcc3b28a3d602d9192b5d1c14..0000000000000000000000000000000000000000 --- a/src/libs/routes/state.js +++ /dev/null @@ -1,100 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const stateApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -stateApp.use(cache('15 day')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addValue({ - name: 'id', - table: 'estado', - tableField: 'id', - where: { - relation: '=', - type: 'integer', - field: 'id' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'regiao_id', - table: 'estado' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'estado' - } -}).addField({ - name: 'search', - field: false, - where: true -}).addValueToField({ - name: 'name', - table: 'estado', - tableField: 'nome', - where: { - relation: 'LIKE', - type: 'string', - field: 'nome' - } -}, 'search'); - -stateApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.sql.from('estado') - .field('estado.id') - .group('estado.id') - .field('regiao_id', 'region_id') - .group('regiao_id') - .field('estado.nome', 'name') - .group('estado.nome') - .field('estado.sigla', 'abbreviation') - .group('estado.sigla'); - next(); -}, query, response('state')); - -module.exports = stateApp; diff --git a/src/libs/routes/teacher.js b/src/libs/routes/teacher.js deleted file mode 100644 index b9a862269ab4cfa76f2ac8d576b227bbd1be10bd..0000000000000000000000000000000000000000 --- a/src/libs/routes/teacher.js +++ /dev/null @@ -1,464 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const teacherApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const response = require(`${libs}/middlewares/response`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const config = require(`${libs}/config`); - -const passport = require('passport'); - -const download = require(`${libs}/middlewares/downloadDatabase`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -teacherApp.use(cache('15 day')); - -// Returns a tuple of start and ending years of the complete enrollments dataset. -teacherApp.get('/year_range', (req, res, next) => { - req.sql.from('docente') - .field('MIN(docente.ano_censo)', 'start_year') - .field('MAX(docente.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -teacherApp.get('/years', (req, res, next) => { - req.sql.from('docente'). - field('DISTINCT docente.ano_censo', 'year'); - next(); -}, query, response('years')); - -teacherApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'docente\''); - next(); -}, query, response('source')); - -teacherApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -teacherApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -teacherApp.get('/education_level_mod', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 11; ++i) { - req.result.push({ - id: i, - name: id2str.educationLevelMod(i) - }); - } - - req.result.push({ - id: 99, - name: id2str.educationLevelMod(99) - }); - next(); -}, response('education_level_mod')); - -teacherApp.get('/education_level_short', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 3, name: 'Ensino Fundamental - anos iniciais'}, - {id: 4, name: 'Ensino Fundamental - anos finais'}, - {id: 5, name: 'Ensino Médio'}, - {id: 6, name: 'EJA'}, - {id: 7, name: 'EE exclusiva'} - ]; - next(); -}, response('education_level_short')); - -teacherApp.get('/location', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 2; ++i) { - req.result.push({ - id: i, - name: id2str.location(i) - }); - }; - next(); -}, response('location')); - -teacherApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -teacherApp.get('/education_type', (req, res, next) => { - req.sql.from('docente') - .field('DISTINCT nivel_tipo_formacao', 'id') - .order('id'); - next(); -}, query, (req, res, next) => { - req.result.forEach((result) => { - result.name = id2str.educationType(result.id); - }); - next(); -}, response('education_type')); - -teacherApp.get('/gender', (req, res, next) => { - req.result = [ - {id: 1, name: 'Masculino'}, - {id: 2, name: 'Feminino'} - ]; - next(); -}, response('gender')); - - -teacherApp.get('/contract_type', (req, res, next) => { - req.result = [ - {id: 1, name: 'Concursado/Efetivo/Estável'}, - {id: 2, name: 'Contrato temporário'}, - {id: 3, name: 'Contrato terceirizado'}, - {id: 4, name: 'Contrato CLT'} - ]; - next(); -}, response('contract_type')); - -teacherApp.get('/ethnic_group', (req, res, next) => { - req.result = []; - for(let i = 0; i <=5; ++i) { - req.result.push({ - id: i, - name: id2str.ethnicGroup(i) - }); - } - next(); -}, response('ethnic_group')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'adm_dependency', - table: 'docente', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'docente', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'contract_type', - table: 'docente', - tableField: 'tipo_contratacao', - resultField: 'contract_type_id', - where: { - relation: '=', - type: 'integer', - field: 'tipo_contratacao' - } -}).addValue({ - name: 'education_level_mod', - table: 'docente', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'education_level_short', - table: 'docente', - tableField: 'etapa_resumida', - resultField: 'education_level_short_id', - where: { - relation: '=', - type: 'integer', - field: 'etapa_resumida' - } -}).addValue({ - name: 'education_type', - table: 'docente', - tableField: 'nivel_tipo_formacao', - resultField: 'education_type_id', - where: { - relation: '=', - type: 'integer', - field: 'nivel_tipo_formacao' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_regiao_id', - foreignTable: 'docente' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_estado_id', - foreignTable: 'docente' - } -}).addValueToField({ - name: 'city', - table: 'municipio', - tableField: ['nome', 'id'], - resultField: ['city_name', 'city_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_municipio_id', - foreignTable: 'docente' - } -}, 'dims').addValueToField({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'escola_municipio_id', - foreignTable: 'docente' - } -}, 'filter').addValueToField({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'docente' - } -}, 'dims').addValueToField({ - name: 'school', - table: 'escola', - tableField: 'nome_escola', - resultField: 'school_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'docente' - } -}, 'filter').addValue({ - name: 'location', - table: 'docente', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name: 'rural_location', - table: 'docente', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'min_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'docente', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'gender', - table: 'docente', - tableField: 'sexo', - resultField: 'gender_id', - where: { - relation: '=', - type: 'integer', - field: 'sexo' - } -}).addValue({ - name: 'ethnic_group', - table: 'docente', - tableField: 'cor_raca', - resultField: 'ethnic_group_id', - where: { - relation: '=', - type: 'integer', - field: 'cor_raca' - } -}); - -teacherApp.get('/', rqf.parse(), (req, res, next) => { - req.sql.field('COUNT(DISTINCT docente.id)', 'total') - .field("'Brasil'", 'name') - .field('docente.ano_censo', 'year') - .from('docente') - .join('turma', null, 'docente.turma_id=turma.id AND docente.ano_censo=turma.ano_censo') - .group('docente.ano_censo') - .order('docente.ano_censo') - .where('(docente.tipo_docente = 1 OR docente.tipo_docente = 5) AND (turma.tipo_turma_id <= 3)'); - - if("education_level_mod" in req.dims) { - delete req.dims.education_level_mod; - req.hadEducationLevelMod = true; - req.sql.field('docente.etapas_mod_ensino_segmento_id', 'education_level_mod_id') - .where('docente.etapas_mod_ensino_segmento_id < 11') - .group('docente.etapas_mod_ensino_segmento_id') - .order('docente.etapas_mod_ensino_segmento_id'); - } - - next(); -}, rqf.build(), query, addMissing(rqf), (req, res, next) => { - req.oldResult = req.result; - if(req.hadEducationLevelMod) { - - req.sql = squel.select() - .field('COUNT(DISTINCT docente.id)', 'total') - .field("'Brasil'", 'name') - .field('docente.ano_censo', 'year') - .from('docente') - .join('turma', null, 'docente.turma_id=turma.id AND docente.ano_censo=turma.ano_censo') - .group('docente.ano_censo') - .order('docente.ano_censo') - .where('(docente.tipo_docente = 1 OR docente.tipo_docente = 5) AND (turma.tipo_turma_id <= 3)') - .where('docente.profissionalizante = 1'); - - rqf.build()(req, res, () => {}); - query(req, res, next); - } else { - next(); - } -}, (req, res, next) => { - if(req.hadEducationLevelMod) { - req.result.forEach((result) => { - result.education_level_mod_id = 11; - req.oldResult.push(result); - }); - } - req.result = req.oldResult; - next(); -}, id2str.transform(), response('teacher')); - -teacherApp.get('/download', passport.authenticate('bearer', { session: false }), rqf.parse(), rqf.build(), download('docente', 'mapping_docente')); - -module.exports = teacherApp; diff --git a/src/libs/routes/transport.js b/src/libs/routes/transport.js deleted file mode 100644 index 6435833b591e75e3af451aeb4cce420904fb2449..0000000000000000000000000000000000000000 --- a/src/libs/routes/transport.js +++ /dev/null @@ -1,523 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const transportApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const squel = require('squel'); - -const query = require(`${libs}/middlewares/query`).query; - -const multiQuery = require(`${libs}/middlewares/multiQuery`); - -const response = require(`${libs}/middlewares/response`); - -const addMissing = require(`${libs}/middlewares/addMissing`); - -const id2str = require(`${libs}/middlewares/id2str`); - -const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`); - -const config = require(`${libs}/config`); - -const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware; - -let rqf = new ReqQueryFields(); - -transportApp.use(cache('15 day')); - -transportApp.get('/year_range', (req, res, next) => { - req.sql.from('matricula') - .field('MIN(matricula.ano_censo)', 'start_year') - .field('MAX(matricula.ano_censo)', 'end_year'); - next(); -}, query, response('range')); - -transportApp.get('/years', (req, res, next) => { - req.sql.from('matricula') - .field('DISTINCT matricula.ano_censo', 'year'); - next(); -}, query, response('years')); - -transportApp.get('/adm_dependency', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 4; ++i) { - req.result.push({ - id: i, - name: id2str.admDependency(i) - }); - }; - next(); -}, response('adm_dependency')); - -transportApp.get('/adm_dependency_detailed', (req, res, next) => { - req.result = []; - for(let i = 1; i <= 6; ++i) { - req.result.push({ - id: i, - name: id2str.admDependencyPriv(i) - }); - }; - next(); -}, response('adm_dependency_detailed')); - -transportApp.get('/location', (req, res, next) => { - req.result = [ - {id: 1, name: 'Urbana'}, - {id: 2, name: 'Rural'} - ]; - next(); -}, response('location')); - -transportApp.get('/rural_location', (req, res, next) => { - req.result = [ - {id: 1, name: "Urbana"}, - {id: 2, name: "Rural"}, - {id: 3, name: "Rural - Área de assentamento"}, - {id: 4, name: "Rural - Terra indígena"}, - {id: 5, name: "Rural - Área remanescente de quilombos"}, - {id: 6, name: "Rural - Unidade de uso sustentável"} - ]; - next(); -}, response('rural_location')); - -transportApp.get('/education_level_mod', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Creche'}, - {id: 2, name: 'Pré-Escola'}, - {id: 4, name: 'Ensino Fundamental - anos iniciais'}, - {id: 5, name: 'Ensino Fundamental - anos finais'}, - {id: 6, name: 'Ensino Médio'}, - {id: 7, name: 'Turmas multiseriadas e multietapas'}, - {id: 8, name: 'EJA - Ensino Fundamental'}, - {id: 9, name: 'EJA - Ensino Médio'}, - {id: 10, name: 'Educação Profissional'} - ]; - next(); -}, response('education_level_mod')); - -transportApp.get('/service_type', (req, res, next) => { - req.result = [ - {id: 0, name: 'Não se aplica'}, - {id: 1, name: 'Classe hospitalar'}, - {id: 2, name: 'Unidade de Atendimento Socioeducativo'}, - {id: 3, name: 'Unidade Prisional'}, - {id: 4, name: 'Atividade Complementar '}, - {id: 5, name: 'Atendimento Educacional Especializado (AEE)'} - ]; - next(); -}, response('service_type')); - -transportApp.get('/transportation_manager', (req, res, next) => { - req.result = [ - {id: null, name: 'Não classificada'}, - {id: 1, name: 'Estadual'}, - {id: 2, name: 'Municipal'}, - ]; - next(); -}, response('transportation_manager')); - -transportApp.get('/source', (req, res, next) => { - req.sql.from('fonte') - .field('fonte', 'source') - .where('tabela = \'matricula\''); - next(); -}, query, response('source')); - -rqf.addField({ - name: 'filter', - field: false, - where: true -}).addField({ - name: 'dims', - field: true, - where: false -}).addValue({ - name: 'school', - table: 'escola', - tableField: ['nome_escola', 'id'], - resultField: ['school_name', 'school_id'], - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: ['id', 'ano_censo'], - foreign: ['escola_id', 'ano_censo'], - foreignTable: 'matricula' - } -}).addValue({ - name: 'region', - table: 'regiao', - tableField: 'nome', - resultField: 'region_name', - where: { - relation: '=', - type: 'integer', - field: 'id' - }, - join: { - primary: 'id', - foreign: 'regiao_id', - foreignTable: 'matricula' - } -}).addValue({ - name: 'city', - table: 'municipio', - tableField: 'nome', - resultField: 'city_name', - where: { - relation: '=', - type: 'integer', - field: 'municipio_id', - table: 'matricula' - }, - join: { - primary: 'id', - foreign: 'municipio_id', - foreignTable: 'matricula' - } -}).addValue({ - name: 'state', - table: 'estado', - tableField: 'nome', - resultField: 'state_name', - where: { - relation: '=', - type: 'integer', - field: 'estado_id', - table: 'matricula' - }, - join: { - primary: 'id', - foreign: 'estado_id', - foreignTable: 'matricula' - } -}).addValue({ - name: 'rural_location', - table: 'matricula', - tableField: 'localidade_area_rural', - resultField: 'rural_location_id', - where: { - relation: '=', - type: 'integer', - field: 'localidade_area_rural' - } -}).addValue({ - name: 'location', - table: 'matricula', - tableField: 'localizacao_id', - resultField: 'location_id', - where: { - relation: '=', - type: 'integer', - field: 'localizacao_id' - } -}).addValue({ - name:'adm_dependency', - table: 'matricula', - tableField: 'dependencia_adm_id', - resultField: 'adm_dependency_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_id' - } -}).addValue({ - name: 'adm_dependency_detailed', - table: 'matricula', - tableField: 'dependencia_adm_priv', - resultField: 'adm_dependency_detailed_id', - where: { - relation: '=', - type: 'integer', - field: 'dependencia_adm_priv' - } -}).addValue({ - name: 'transportation_manager', - table: 'matricula', - tableField: 'responsavel_transp', - resultField: 'transportation_manager_id', - where: { - relation: '=', - type: 'integer', - field: 'responsavel_transp' - } -}).addValue({ - name: 'education_level_mod', - table: 'matricula', - tableField: 'etapas_mod_ensino_segmento_id', - resultField: 'education_level_mod_id', - where: { - relation: '=', - type: 'integer', - field: 'etapas_mod_ensino_segmento_id' - } -}).addValue({ - name: 'service_type', - table: 'matricula', - tableField: 'tipo', - resultField: 'service_type_id', - where: { - relation: '=', - type: 'integer', - field: 'tipo' - } -}).addValue({ - name: 'min_year', - table: 'matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '>=', - type: 'integer', - field: 'ano_censo' - } -}).addValue({ - name: 'max_year', - table: 'matricula', - tableField: 'ano_censo', - resultField: 'year', - where: { - relation: '<=', - type: 'integer', - field: 'ano_censo' - } -}); - -function matchQueries(queryTotal, queryPartial) { - let match = []; - queryTotal.forEach((result) => { - let newObj = {}; - let keys = Object.keys(result); - keys.forEach((key) => { - newObj[key] = result[key]; - }); - let index = keys.indexOf('total'); - if(index > -1) keys.splice(index, 1); - let objMatch = null; - - for(let i = 0; i < queryPartial.length; ++i) { - let partial = queryPartial[i]; - let foundMatch = true; - for(let j = 0; j < keys.length; ++j) { - let key = keys[j]; - if(partial[key] !== result[key]) { - foundMatch = false; - break; - } - } - if(foundMatch) { - objMatch = partial; - break; - } - } - - if(objMatch) { - newObj.percentage = (objMatch.total / result.total) * 100; - newObj.partial = objMatch.total; - newObj.total = result.total - match.push(newObj); - } - }); - - return match; -} - -transportApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => { - req.querySet = []; - req.queryIndex = {}; - - let allEnrollment = req.sql.clone() - allEnrollment.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .from('matricula') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3'); - req.queryIndex.allEnrollment = req.querySet.push(allEnrollment) - 1; - - let allEnrollmentTransport = req.sql.clone() - allEnrollmentTransport.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .field('matricula.transporte_escolar_publico', 'use_transport_id') - .from('matricula') - .group('matricula.ano_censo') - .group('matricula.transporte_escolar_publico') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3'); - req.queryIndex.allEnrollmentTransport = req.querySet.push(allEnrollmentTransport) - 1; - - let allTransports = req.sql.clone() - allTransports.field('COUNT(*)', 'total') - .field("'Brasil'", 'name') - .field('matricula.ano_censo', 'year') - .from('matricula') - .group('matricula.ano_censo') - .order('matricula.ano_censo') - .where('matricula.tipo <= 3 AND matricula.transporte_escolar_publico = 1'); - req.queryIndex.allTransports = req.querySet.push(allTransports) - 1; - - // Vans e Kombi - let goVansAndKombi = allTransports.clone(); - goVansAndKombi.field('matricula.transporte_vans_kombi','use_transport_id') - goVansAndKombi.where('matricula.transporte_vans_kombi = 1'); - goVansAndKombi.group('matricula.transporte_vans_kombi'); - req.queryIndex.goVansAndKombi = req.querySet.push(goVansAndKombi) - 1; - - // Micro - let goMicroBus = allTransports.clone(); - goMicroBus.field('matricula.transporte_micro_onibus', 'use_transport_id') - goMicroBus.where('matricula.transporte_micro_onibus = 1'); - goMicroBus.group('matricula.transporte_micro_onibus'); - req.queryIndex.goMicroBus = req.querySet.push(goMicroBus) - 1; - - - // Ônibus - let goBus = allTransports.clone(); - goBus.field("matricula.transporte_onibus", 'use_transport_id') - goBus.where('matricula.transporte_onibus = 1'); - goBus.group('matricula.transporte_onibus') - req.queryIndex.goBus = req.querySet.push(goBus) - 1; - - // Bicicleta - let goBikes = allTransports.clone(); - goBikes.field('matricula.transporte_bicicleta', 'use_transport_id') - goBikes.where('matricula.transporte_bicicleta = 1'); - goBikes.group('matricula.transporte_bicicleta') - req.queryIndex.goBikes = req.querySet.push(goBikes) - 1; - - // Tração Animal - let goAnimalTraction = allTransports.clone(); - goAnimalTraction.field('matricula.transporte_animal', 'use_transport_id') - goAnimalTraction.where('matricula.transporte_animal = 1'); - goAnimalTraction.group('matricula.transporte_animal') - req.queryIndex.goAnimalTraction = req.querySet.push(goAnimalTraction) - 1; - - // Outro Veículo - let goOtherVehicle = allTransports.clone(); - goOtherVehicle.field('matricula.transporte_outro', 'use_transport_id') - goOtherVehicle.where('matricula.transporte_outro = 1'); - goOtherVehicle.group('matricula.transporte_outro') - req.queryIndex.goOtherVehicle = req.querySet.push(goOtherVehicle) - 1; - - // Aquaviário/ Embarcação (capacidade até 5 alunos) - let goWaterway_5_Students = allTransports.clone(); - goWaterway_5_Students.field('matricula.transporte_embar_0_5','use_transport_id') - goWaterway_5_Students.where('matricula.transporte_embar_0_5 = 1'); - goWaterway_5_Students.group('matricula.transporte_embar_0_5') - req.queryIndex.goWaterway_5_Students = req.querySet.push(goWaterway_5_Students) - 1; - - // Aquaviário/ Embarcação (capacidade de 5 até 15 alunos) - let goWaterway_15_Students = allTransports.clone(); - goWaterway_15_Students.field('matricula.transporte_embar_5_15', 'use_transport_id') - goWaterway_15_Students.where('matricula.transporte_embar_5_15 = 1'); - goWaterway_15_Students.group('matricula.transporte_embar_5_15') - req.queryIndex.goWaterway_15_Students = req.querySet.push(goWaterway_15_Students) - 1; - - // Aquaviário/ Embarcação (capacidade de 15 até 35 alunos)r - let goWaterway_35_Students = allTransports.clone(); - goWaterway_35_Students.field('matricula.transporte_embar_15_35', 'use_transport_id') - goWaterway_35_Students.where('matricula.transporte_embar_15_35 = 1'); - goWaterway_35_Students.group('matricula.transporte_embar_15_35') - req.queryIndex.goWaterway_35_Students = req.querySet.push(goWaterway_35_Students) - 1; - - // Aquaviário/ Embarcação (capacidade mais 35 alunos) - let goWaterwayMoreThan_35 = allTransports.clone(); - goWaterwayMoreThan_35.field('matricula.transporte_embar_35', 'use_transport_id') - goWaterwayMoreThan_35.where('matricula.transporte_embar_35 = 1'); - goWaterwayMoreThan_35.group('matricula.transporte_embar_35') - req.queryIndex.goWaterwayMoreThan_35 = req.querySet.push(goWaterwayMoreThan_35) - 1; - - // Trêm / Metrô - let goSubwayAndTrain = allTransports.clone(); - goSubwayAndTrain.field('matricula.transporte_trem_metro', 'use_transport_id') - goSubwayAndTrain.where('matricula.transporte_trem_metro = 1'); - goSubwayAndTrain.group('matricula.transporte_trem_metro') - req.queryIndex.goSubwayAndTrain = req.querySet.push(goSubwayAndTrain) - 1; - - next(); -}, multiQuery, (req, res, next) => { - let transport_match = []; - let transport_match_0 = JSON.parse(JSON.stringify(req.result[req.queryIndex.allTransports])); - let transport_match_1 = JSON.parse(JSON.stringify(req.result[req.queryIndex.allTransports])); - - let all_enrollment_match = []; - let all_enrollment_match_0 = JSON.parse(JSON.stringify(req.result[req.queryIndex.allEnrollment])); - let all_enrollment_match_1 = JSON.parse(JSON.stringify(req.result[req.queryIndex.allEnrollment])); - - //modifica adicionando use_transport_id=false, com os mesmos valores - //do transport_id=true, usado para dar o match e fazer a divisão. - for (let i = 0; i < transport_match_0.length; i++) { - transport_match_0[i].use_transport_id = true; - transport_match.push(transport_match_0[i]) - // transport_match_1[i].use_transport_id = false; - // transport_match.push(transport_match_1[i]) - } - - //modifica adicionando use_transport_id=false, com os mesmos valores - //do transport_id=true, usado para dar o match e fazer a divisão. - for (let i = 0; i < all_enrollment_match_0.length; i++) { - all_enrollment_match_0[i].use_transport_id = true; - all_enrollment_match.push(all_enrollment_match_0[i]) - // all_enrollment_match_1[i].use_transport_id = false; - // all_enrollment_match.push(all_enrollment_match_1[i]) - } - - let public_transport = matchQueries(all_enrollment_match, req.result[req.queryIndex.allEnrollmentTransport]); - let van_and_kombi = matchQueries(transport_match, req.result[req.queryIndex.goVansAndKombi]); - let micro_bus = matchQueries(transport_match, req.result[req.queryIndex.goMicroBus]); - let bus = matchQueries(transport_match, req.result[req.queryIndex.goBus]); - let bike = matchQueries(transport_match, req.result[req.queryIndex.goBikes]); - let animal_traction = matchQueries(transport_match, req.result[req.queryIndex.goAnimalTraction]); - let other_vehicle = matchQueries(transport_match, req.result[req.queryIndex.goOtherVehicle]); - let waterway_5_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_5_Students]); - let waterway_15_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_15_Students]); - let waterway_35_Students = matchQueries(transport_match, req.result[req.queryIndex.goWaterway_35_Students]); - let waterway_More_Than_35 = matchQueries(transport_match, req.result[req.queryIndex.goWaterwayMoreThan_35]); - let subway_and_train = matchQueries(transport_match, req.result[req.queryIndex.goSubwayAndTrain]); - - req.result = [{ - public_transport, - van_and_kombi, - micro_bus, - bus, - bike, - animal_traction, - other_vehicle, - waterway_5_Students, - waterway_15_Students, - waterway_35_Students, - waterway_More_Than_35, - subway_and_train - }]; - next(); -}, id2str.multitransform(false), response('transports')); - -module.exports = transportApp; diff --git a/src/libs/routes/user.js b/src/libs/routes/user.js deleted file mode 100644 index f32f41ab602dfe3c0c119dcb89b5cfff02edb0ad..0000000000000000000000000000000000000000 --- a/src/libs/routes/user.js +++ /dev/null @@ -1,328 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const userApp = express(); - -const libs = `${process.cwd()}/libs`; - -const config = require(`${libs}/config`); - -const log = require(`${libs}/log`)(module); - -const User = require(`${libs}/models/user`); - -const VerificationToken = require(`${libs}/models/verificationToken`); - -const ResetToken = require(`${libs}/models/resetToken`); - -const response = require(`${libs}/middlewares/response`); - -const email = require(`${libs}/middlewares/email`); - -const passport = require('passport'); - -function emailSyntax(email) { - const regex = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; - return regex.test(email); -} - -userApp.get('/schooling', (req, res, next) => { - req.result = [ - 'Não estudou', - 'Ensino Fundamental Incompleto', - 'Ensino Fundamental Completo', - 'Ensino Médio', - 'Graduação', - 'Mestrado', - 'Doutorado' - ]; - next(); -}, response('schooling')); - -userApp.get('/segment', (req, res, next) => { - req.result = [ - 'Gestores e equipe gestora das secretarias e ministério da Educação', - 'Gestores dos órgãos de planejamento e finanças (das três esferas de governo)', - 'Agentes do poder legislativo', - 'Agentes dos conselhos de educação', - 'Profissionais da educação', - 'Sindicato', - 'Sociedade civil interessada no financiamento da Educação Básica de qualidade', - 'Comunidade acadêmica', - 'Imprensa', - 'Outro [citar segmento]' - ]; - next(); -}, response('segment')); - -userApp.get('/role', (req, res, next) => { - req.result = [ - {"Gestores e equipe gestora das secretarias e ministério da Educação" : ["Dirigente municipal, estadual e federal", "Secretário do MEC", "Servidor da área de planejamento educacional", "Membro de associação de gestores (Ex. Undime, Consed, etc)", "Outro [citar função]"]}, - {"Gestores dos órgãos de planejamento e finanças (das três esferas de governo)" : ["Equipe gestora dos órgãos de planejamento", "Equipe gestora dos órgãos de finanças", "Outro [citar função]"]}, - {"Agentes do poder legislativo" : ["Parlamentar", "Assessor/a parlamentar", "Auditor/a dos tribunais de conta", "Conselheiro/a de tribunais de conta.", "Outro [citar função]"]}, - {"Agentes dos conselhos de educação" : ["Conselheiro/a municipais, estaduais e federais", "Conselheiro/a do Fundeb", "Outro [citar função]"]}, - {"Profissionais da educação" : ["Professor/a da Educação Básica", "Profissional da educação não-docente", "Outro [citar função]"]}, - {"Sindicato" : ["Agente de sindicatos"]}, - {"Sociedade civil interessada no financiamento da Educação Básica de qualidade" : ["Membro de fóruns educacionais", "Membro de ONGs e demais entidades sem fins lucrativos", "Estudante da educação básica e membro de entidades estudantis", "Pais e membros de entidades de pais", "Outro [citar função]"]}, - {"Comunidade acadêmica" : ["Pesquisador/a", "Estudantes de graduação e pós-graduação", "Representantes de entidades de pesquisa (Ex.: ANPED, ANPAE e FINEDUCA)", "Outro [citar função]"]}, - {"Imprensa" : ["Jornalista", "Outro [citar função]"]}, - {"Outro [citar segmento]" : []} - ] - next(); -}, response('role')); - -userApp.get('/', passport.authenticate('bearer', {session: false}), (req, res, next) => { - User.find((err, users) => { - if(err) { - log.error(err); - return next(err); - } - - let result = []; - users.forEach((user) => { - let u = user.toObject(); - delete u.hashedPassword; - delete u.salt; - result.push(u); - }); - req.result = result; - next(); - }); -}, response('users')); - -userApp.get('/me', passport.authenticate('bearer', { session: false }), (req, res, next) => { - let user = req.user.toObject(); - delete user.hashedPassword; - delete user.salt; - req.result = user; - next(); -}, response('user')); - -userApp.get('/:id', (req, res, next) => { - User.findById(req.params.id, (err, user) => { - if(err) { - log.error(err); - return next(err); - } - if(!user) { - req.statusCode = 404; - next({msg: 'User not found'}); - } else { - let u = user.toObject; - delete u.hashedPassword; - delete u.salt; - req.result = u; - next(); - } - }); -}, response('user')); - -userApp.post('/', (req, res, next) => { - let user = new User({ - email: req.body.email, - password: req.body.password, - name: req.body.name, - nickname: req.body.nickname, - cpf: req.body.cpf, - cep: req.body.cep, - complement: req.body.complement, - address: req.body.address, - phone: req.body.phone, - schooling: req.body.schooling, - course: req.body.course, - segment: req.body.segment, - role: req.body.role, - institutionName: req.body.institutionName, - state: req.body.state, - city: req.body.city, - receiveEmails: false || req.body.receiveEmails, - origin: req.body.origin, - citesegment: req.body.citesegment, - citerole: req.body.citerole, - admin: false - }); - - if (typeof req.body.password === 'undefined' || !req.body.password) { - res.statusCode = 400; - return res.json({errors: ["O campo senha é obrigatório"]}); - } else { - user.save((err) => { - if(err) { - log.error(err); - let errors = []; - for(let errName in err.errors) { - errors.push(err.errors[errName].message); - } - log.error(errors); - res.statusCode = 400; - return res.json({err, errors}); - } - - // Create verification token - let verificationToken = new VerificationToken({ - userId: user._id - }); - - verificationToken.createVerificationToken((err, token) => { - if(err) { - log.error(err); - return next(err); - } - let url = config.default.lde.url + '/verify'; - let text = `Olá, ${user.name}, seja bem vindo/a ao Laboratório de Dados Educacionais.\n\nClique neste link para confirmar sua conta: ${url}/${token}`; - // Send confirmation email - let mailOptions = { - to: `"${user.name} <${user.email}>"`, - subject: "Confirme seu cadastro - Laboratório de Dados Educacionais", - text - } - email(mailOptions, (err, info) => { - if(err) { - log.error(err); - res.json({msg: 'User created'}); - } - if(info) { - log.info(`Message ${info.messageId} sent: ${info.response}`); - log.info(`Usuário ${user.email} foi criado`); - } - res.json({msg: 'User created'}); - }); - }); - }); - } - -}); - -userApp.put('/:id', passport.authenticate('bearer', { session: false }), (req, res, next) => { - console.log(req.params.id); - console.log(req.user._id); - User.findById(req.params.id, (err, user) => { - if (err) { - log.error(err); - return next({err}); - } - - if(!user) { - res.statusCode = 404; - return next({err: { - message: 'Usuário não encontrado' - }}); - } - - console.log(req.body); - - user.email = req.body.email || user.email; - user.name = req.body.name || user.name; - user.nickname = req.body.nickname || user.nickname || user.name; - user.cep = req.body.cep || user.cep; - user.complement = req.body.complement || user.complement; - user.address = req.body.address || user.address; - user.phone = req.body.phone || user.phone; - user.schooling = req.body.schooling || user.schooling; - user.course = req.body.course || user.course; - user.segment = req.body.segment || user.segment; - user.role = req.body.role || user.role; - user.institutionName = req.body.institutionName || user.institutionName; - user.state = req.body.state || user.state; - user.city = req.body.city || user.city; - user.receiveEmails = req.body.receiveEmails || user.receiveEmails; - user.citesegment = req.body.citesegment || user.citesegment; - user.citerole = req.body.citerole || user.citerole; - - // console.log(user.checkPassword(req.body.password)); - if ((req.body.password) && (req.body.newpassword)) { - if (req.body.password != req.body.newpassword) { - if (user.checkPassword(req.body.password)) { - user.password = req.body.newpassword; - } else { - res.statusCode = 500; - return res.json({error: { - message: 'A senha atual está incorreta' - }}); - } - } else { - res.statusCode = 500; - return res.json({error: { - message: 'A nova senha é a mesma da senha atual' - }}); - } - } - - user.save(err => { - if(err) { - log.error(err); - return next({message: 'Erro ao atualizar usuário'}); - } - let u = user.toObject(); - delete u.hashedPassword; - delete u.salt; - res.json({user: u}); - }) - }) -}); - -userApp.get('/reset/password', (req, res, next) => { - let emailAddress = req.query.email; - User.findOne({email: emailAddress}, (err, user)=> { - if(err) { - log.error(err); - let errors = []; - for(let errName in err.errors) { - errors.push(err.errors[errName].message); - } - res.statusCode = 400; - return res.json({err, errors}); - } - if (!user) { - res.statusCode = 404; - res.json({msg: "O usuário não está cadastrado"}); - } - else { - let resetToken = new ResetToken({ - userId: user._id - }); - resetToken.createResetToken((err, token) => { - if (err) { - log.error(err); - return next(err); - } - let url = config.default.lde.url + '/reset-password'; - let text = `Olá, ${user.name}.\n\nRecebemos uma solicitação para redefinir sua senha do Laboratório de Dados Educacionais. Clique neste link para redefinir a sua senha: ${url}/${token}`; - let mailOptions = { - to: `"${user.name} <${user.email}>"`, - subject: "Redefinição de Senha - Laboratório de Dados Educacionais", - text - } - email(mailOptions, (err, info) => { - if(err) { - log.error(err); - res.json({msg: 'Undelivered Reset Password Mail'}); - } - log.info(`Message ${info.messageId} sent: ${info.response}`); - res.json({msg: 'Reset Password Mail Successfully Delivered'}); - }); - }) - } - }) -}) - -module.exports = userApp; diff --git a/src/libs/routes/verifyToken.js b/src/libs/routes/verifyToken.js deleted file mode 100644 index a2a278c549c6ef095cab09ee243a48772e11ea5b..0000000000000000000000000000000000000000 --- a/src/libs/routes/verifyToken.js +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -const express = require('express'); - -const verifyTokenApp = express.Router(); - -const libs = `${process.cwd()}/libs`; - -const log = require(`${libs}/log`)(module); - -const VerificationToken = require(`${libs}/models/verificationToken`); - -const User = require(`${libs}/models/user`); - -verifyTokenApp.get('/:token', (req, res, next) => { - let token = req.params.token; - VerificationToken.findOne({token: token}, (err, vToken) => { - if(err) { - log.error(err); - return next(err); - } - if(!vToken) { - // TODO: generate new verification token - res.statusCode = 404; - return next({msg: 'Token not found', status:404}); - } - User.findById(vToken.userId, (err, user) => { - if(err) { - log.error(err); - next(err); - } - user.verified = true; - user.save((err) => { - if(err) { - log.error(err); - next(err); - } - }); - let u = user.toObject(); - delete u.salt; - delete u.hashedPassword; - vToken.verified = true; - vToken.save((err) => { - if(err) { - log.error(err); - next(err); - } - }); - res.json({msg: 'User verified', user: u}); - }); - }); -}); - -module.exports = verifyTokenApp; diff --git a/src/test/simulation.js b/src/test/simulation.js deleted file mode 100644 index d7a99a970a7f0b5f886c0d20b9df28a0291e35ce..0000000000000000000000000000000000000000 --- a/src/test/simulation.js +++ /dev/null @@ -1,453 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -process.env.NODE_ENV = 'test'; - -const chai = require('chai'); - -const dirtyChai = require('dirty-chai'); - -chai.use(dirtyChai); - -const chaiXml = require('chai-xml'); - -chai.use(chaiXml); - -const chaiHttp = require('chai-http'); - -const assert = chai.assert; - -const expect = chai.expect; - -const should = chai.should(); // actually call the function - -const libs = `${process.cwd()}/libs`; - -const server = require(`${libs}/app`); - -const mongoose = require('../libs/db/mongoose'); -const Simulation = require('../libs/models/simulation'); -const User = require('../libs/models/user'); - -chai.use(chaiHttp); - -describe('Requires a simulation', () => { - let newSimulation; - - beforeEach(() => { - Simulation.remove({}, (err) => { - console.log('Test collection purged'); - }); - }); - - // it('should create a new simulation', (done) => { - // chai.request(server) - // .post('/api/v1/simulation') - // .set('content-type', 'application/x-www-form-urlencoded') - // .set('x-apicache-bypass', 'true') - // .send({ name: 'test_entry' }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.name.should.equal('test_entry'); - // done(); - // }); - // }); - // }); - // it('should not create a nameless simulation', (done) => { - // chai.request(server) - // .post('/api/v1/simulation') - // .set('content-type', 'application/x-www-form-urlencoded') - // .set('x-apicache-bypass', 'true') - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.not.have.property('id'); - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // Simulation.findById(res.body.id, (err, simulation) => { - // expect(simulation).to.not.exist; - // done(); - // }); - // }); - // }); - // it('should find an existing simulation', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .get(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('_id'); - // res.body._id.should.be.a('string'); - // res.body.should.have.property('name'); - // res.body._id.should.be.a('string'); - // done(); - // }); - // }); - // }); - // it('should not find an unexisting simulation', (done) => { - // newSimulation = new Simulation(); - // let id = newSimulation._id; - // chai.request(server) - // .get(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // it('should update an existing simulation\'s location', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ location: 5 }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.name.should.equal('test'); - // simulation.should.have.property('location'); - // simulation.location.should.be.a('number'); - // simulation.location.should.equal(5); - // done(); - // }); - // }); - // }); - // }); - // it('should update multiple fields on a single request', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // name: 'new_name', - // location: 5, - // time: 3, - // failure_rate: [0.1, 0.2, 0.3], - // goals_care: [0.3, 0.2, 0.1], - // goals_inclusion: [0.8, 0.9, 1] - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.name.should.equal('new_name'); - // simulation.should.have.property('location'); - // simulation.location.should.be.a('number'); - // simulation.location.should.equal(5); - // simulation.should.have.property('time'); - // simulation.time.should.be.a('number'); - // simulation.time.should.equal(3); - // simulation.should.have.property('failure_rate'); - // simulation.failure_rate.should.be.a('array'); - // simulation.failure_rate.length.should.equal(3); - // simulation.should.have.property('goals_care'); - // simulation.goals_care.should.be.a('array'); - // simulation.goals_care.length.should.equal(3); - // simulation.should.have.property('goals_inclusion'); - // simulation.goals_inclusion.should.be.a('array'); - // simulation.goals_inclusion.length.should.equal(3); - // done(); - // }); - // }); - // }); - // }); - // it('should not update an unexisting simulation', (done) => { - // newSimulation = new Simulation(); - // let id = newSimulation._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ location: 5 }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // it('should update an existing simulation\'s time', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ time: 5 }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.should.have.property('time'); - // simulation.time.should.be.a('number'); - // simulation.time.should.equal(5); - // done(); - // }); - // }); - // }); - // }); - // it('should not change results for empty post requests', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should not update in case of invalid field', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // name: 'other_name', - // totally_not_valid_value_for_an_entry: 'not hacking this api', - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // Simulation.findById(id, (err, simulation) => { - // simulation.name.should.equal('test'); - // done(); - // }); - // }); - // }); - // }); - // it('should include consistent enrollment tables', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "[[100, 150, 200, 250, 300]]", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('id'); - // res.body.id.should.be.a('string'); - // Simulation.findById(res.body.id, (err, simulation) => { - // simulation.should.have.property('name'); - // simulation.name.should.be.a('string'); - // simulation.should.have.property('time'); - // simulation.time.should.be.a('number'); - // simulation.time.should.equal(5); - // done(); - // }); - // }); - // }); - // }); - // it('should not accept an invalid time', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: "I'm an inocent time entry, don't mind me", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // }); - // done(); - // }); - // }); - // it('should not accept enrollments table different than provided time', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "[[1,2,3]]", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should not include arrays of non arrays as enrollments', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "[\"Tomato\"]", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should not accept non array enrollments', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "Am I still wanted here?", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should not accept an enrollment with anything other than a number', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .post(`/api/v1/simulation/${id}`) - // .send({ - // time: 5, - // enrollments: "[[1,2,\"malicious payload\",4,5]]", - // }) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - // }); - // it('should delete an entry', (done) => { - // newSimulation = new Simulation(); - // newSimulation.name = 'test'; - // newSimulation.save((err, sim) => { - // let id = sim._id; - // chai.request(server) - // .delete(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(true); - // done(); - // }); - // }); - // }); - // it('should not delete an unexisting entry', (done) => { - // let sim = new Simulation(); - // let id = sim._id; - // chai.request(server) - // .delete(`/api/v1/simulation/${id}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('success'); - // res.body.success.should.equal(false); - // done(); - // }); - // }); - - // it('should returns an array in simulation/time', (done) => { - // let max_time = 10; - // chai.request(server) - // .get(`/api/v1/simulation/time?max_time=${max_time}`) - // .end((err, res) => { - // res.should.have.status(200); - // res.should.be.json; - // res.body.should.have.property('result'); - // res.body.result.should.be.array; - // done(); - // }); - // }); - - // it('should return an error when no max_time is specified in simulation/time', (done) => { - // chai.request(server) - // .get(`/api/v1/simulation/time`) - // .end((err, res) => { - // res.should.have.status(400); - // res.should.be.json; - // res.body.should.have.property('error'); - // res.body.error.should.equal('Invalid value for mandatory parameter max_time'); - // done(); - // }); - // }); -}); diff --git a/src/test/user.js b/src/test/user.js deleted file mode 100644 index ab44a78ddcd71b20d7c9944d6bf5cea7cd359f9d..0000000000000000000000000000000000000000 --- a/src/test/user.js +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR - -This file is part of simcaq-node. - -simcaq-node is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -simcaq-node is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with simcaq-node. If not, see <https://www.gnu.org/licenses/>. -*/ - -process.env.NODE_ENV = 'test'; - -const chai = require('chai'); - -const dirtyChai = require('dirty-chai'); - -chai.use(dirtyChai); - -const chaiXml = require('chai-xml'); - -chai.use(chaiXml); - -const chaiHttp = require('chai-http'); - -const assert = chai.assert; - -const expect = chai.expect; - -const should = chai.should(); // actually call the function - -const libs = `${process.cwd()}/libs`; - -const server = require(`${libs}/app`); - -const mongoose = require('../libs/db/mongoose'); -//const Simulation = require('../libs/models/simulation'); -const User = require('../libs/models/user'); - -chai.use(chaiHttp); - -describe('Saves a user', () => { - // beforeEach(() => { - // User.remove({}, (err) => { - // console.log('Test collection purged') - // }); - // }); -}); diff --git a/start_monet.sh b/start_monet.sh new file mode 100755 index 0000000000000000000000000000000000000000..d159d28ab988d3a84d79fc4a4b05140dfedc3617 --- /dev/null +++ b/start_monet.sh @@ -0,0 +1,3 @@ +monetdbd start ~/my-dbfarm/ + +monetdb start test3 \ No newline at end of file diff --git a/stop_monet.sh b/stop_monet.sh new file mode 100755 index 0000000000000000000000000000000000000000..696c71b73175ba5435eed33ebd3373a77d7e6e76 --- /dev/null +++ b/stop_monet.sh @@ -0,0 +1,5 @@ +monetdb stop test3 + +monetdbd stop ~/my-dbfarm/ + +sudo bash -c "echo 1 > /proc/sys/vm/drop_caches" \ No newline at end of file diff --git a/testScript.sh b/testScript.sh new file mode 100755 index 0000000000000000000000000000000000000000..bccd5b616ad1818a00e769bf48499128cf48d86f --- /dev/null +++ b/testScript.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +sql=$1 +test=$2 + + +echo "------------TESTING ${test}-------------" > result.txt +for i in {1..10} +do + ./stop_monet.sh + ./start_monet.sh + (time mclient -d test3 ${sql}) >> Resultados/${test}.txt 2>&1 +done +