Skip to content

Commit

Permalink
Merge pull request #28 from analytics-ufcg/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
JoaquimCMH authored Oct 1, 2020
2 parents 756b52e + 3cc3e32 commit 5a494e5
Show file tree
Hide file tree
Showing 13 changed files with 270 additions and 117 deletions.
2 changes: 2 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const app = express();
const licitacoesRoute = require('./routes/licitacoes.routes');
const regioesRoute = require('./routes/regioes.routes');
const contratosRoute = require('./routes/contratos.routes');
const previsoesRoute = require('./routes/previsoes.routes');

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
Expand All @@ -22,6 +23,7 @@ app.use(cors());
app.use('/api/', licitacoesRoute);
app.use('/api/', regioesRoute);
app.use('/api/', contratosRoute);
app.use('/api/', previsoesRoute);

module.exports = app;

Expand Down
15 changes: 14 additions & 1 deletion src/config/credentials.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,18 @@ module.exports = {
encrypt: false,
enableArithAbort: true
}
} //, AL_DB {...}
},
MC_DB: {
username: process.env.POSTGRES_MCDB_USER,
host: process.env.POSTGRES_MCDB_HOST,
database: process.env.POSTGRES_MCDB_DB,
password: process.env.POSTGRES_MCDB_PASSWORD,
port: process.env.POSTGRES_MCDB_PORT,
dialect: 'postgres',
options: {
trustedConnection: true,
encrypt: false,
enableArithAbort: true
}
}
}
17 changes: 11 additions & 6 deletions src/config/db.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,30 @@

const { Sequelize } = require('sequelize');
const { AL_DB } = require("./credentials");
const { MC_DB } = require("./credentials");

/** Adiciona as configurações específicas de um banco. Caso seja necessário mudar
o BD basta alterar o parâmetro do Sequelize.
*/
const sequelize = new Sequelize(AL_DB)
const sequelize_aldb = new Sequelize(AL_DB)
const sequelize_mcdb = new Sequelize(MC_DB)


run(sequelize_aldb, AL_DB).catch(error => console.log(error.stack));
run(sequelize_mcdb, MC_DB).catch(error => console.log(error.stack));

// Testa se a conexão foi estabelecida
run().catch(error => console.log(error.stack));
async function run() {
async function run(conexao, config) {
try {
await sequelize.authenticate();
console.log('Conexão estabelecida com o banco de dados ', AL_DB.database);
await conexao.authenticate();
console.log('Conexão estabelecida com o banco de dados ', config.database);
} catch (error) {
console.error('Não foi possível conectar-se ao banco de dados:', error);
}
}

module.exports = {
sequelize
sequelize_aldb, sequelize_mcdb
}


Expand Down
111 changes: 55 additions & 56 deletions src/controllers/contratos.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@

const models = require("../models/index.model");
const Contrato = models.contrato;
const Previsao = models.previsao;
const Pagamento = models.pagamento;
const Empenho = models.empenho;

const Op = models.Sequelize.Op;
const sequelize = models.sequelize;
const sequelize = models.sequelize_aldb;

const BAD_REQUEST = 400;
const SUCCESS = 200;
Expand All @@ -18,33 +19,46 @@ const SUCCESS = 200;
exports.getContratosPorMunicipio = (req, res) => {
const cd_municipio = req.query.cd_municipio

Contrato.findAll({
include: [
{
model: Previsao,
as: "previsaoContrato"
}
],
where: {
Contrato.findAll({
attributes: {
include: [[sequelize.fn('SUM', sequelize.col('pagamentosContrato.vl_pagamento')), 'totalPago']]
},
include: {
model: Pagamento,
attributes: [],
as: "pagamentosContrato",
required: false
},
group: ['contrato.id_contrato'],
where: {
cd_municipio: cd_municipio,
id_licitacao: { [Op.ne]: null
id_licitacao: {
[Op.ne]: null
}
}
}})
.then(contratos => res.status(SUCCESS).json(contratos))
.catch(err => res.status(BAD_REQUEST).json({ err }));
})
.then(contratos => res.status(SUCCESS).json(contratos))
.catch(err => res.status(BAD_REQUEST).json({ err }));
};

// Recupera o contrato pelo ID
exports.getContratoById = (req, res) => {
const id = req.params.id

Contrato.findOne({
include: [
{
model: Previsao,
as: "previsaoContrato"
}
],
include: [{
model: Pagamento,
attributes: ['dt_pagamento', 'vl_pagamento'],
as: "pagamentosContrato",
required: false
},
{
model: Empenho,
attributes: ['dt_empenho','vl_empenho'],
as: "empenhosContrato",
required: false
},
],
where: {
id_contrato: id
}
Expand All @@ -66,61 +80,46 @@ exports.getContratosByLicitacao = (req, res) => {
.catch(err => res.status(BAD_REQUEST).json({ err }));
}

// Retorna todas os contratos, ordenados pelo Risco
exports.getContratosPorRisco = (req, res) => {

Contrato.findAll({
include: [
{
model: Previsao,
as: "previsaoContrato",
where: {
id_contrato: { [Op.ne]: null }
}
}
],

exports.getContratosVigentes = (req, res) => {

Contrato.findAll({
where: {
id_licitacao: { [Op.ne]: null },
where: sequelize.where( sequelize.col('pr_vigencia'), '>=', sequelize.literal('CURRENT_TIMESTAMP'))
},
order: [
[
{model: Previsao, as: 'previsaoContrato'},
'vig_prob_1',
'DESC'
]
]
where: sequelize.where( sequelize.col('pr_vigencia'), '>=', sequelize.literal('CURRENT_TIMESTAMP'))
}
})
.then(contratos => res.status(SUCCESS).json(contratos))
.catch(err => res.status(BAD_REQUEST).json({ err }));
};
.then(contratos => res.json(contratos))
.catch(err => res.status(BAD_REQUEST).json({ err }));
}


exports.getContratosByQuery = (req, res) => {

const termos = req.query.termo.replace(/[&|!<()\\:',]/gi, '').replace( /\s+/g, ' ').trim().split(' ').join(' & ');
const termos = req.query.termo.replace(/[&|!<()\\:',]/gi, '').replace(/\s+/g, ' ').trim().split(' ').join(' & ');

let query = `SELECT \
id_contrato, \
de_obs, \
de_ugestora, \
vl_total_contrato, \
dt_ano, \
(\
SELECT \
vig_prob_1 \
FROM \
previsao \
WHERE \
p_search.id_contrato = previsao.id_contrato\
) \
nu_licitacao, \
nu_contrato \
FROM \
( \
SELECT \
*, \
to_tsvector( \
contrato.language::regconfig, \
contrato.de_obs \
) AS document \
) ||
to_tsvector( \
contrato.nu_licitacao \
) ||
to_tsvector( \
contrato.nu_contrato \
) AS document \
FROM \
contrato \
) p_search \
Expand All @@ -132,7 +131,7 @@ exports.getContratosByQuery = (req, res) => {
to_tsquery('portuguese', '${termos}') \
) DESC; `

models.sequelize.query(query, {
sequelize.query(query, {
model: Contrato,
mapToModel: true
}).then(Contrato => res.status(SUCCESS).json(Contrato))
Expand Down
21 changes: 11 additions & 10 deletions src/controllers/licitacoes.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,20 @@ const Participante = models.participante;
const Previsao = models.previsao;

const Op = models.Sequelize.Op;
const sequelize = models.sequelize_aldb;

const BAD_REQUEST = 400;
const SUCCESS = 200;

// Retorna todas as licitações não vazias de um município
// Retorna todas as licitações não vazias de um município
exports.getLicitacoesPorMunicipio = (req, res) => {
const cd_municipio = req.query.cd_municipio

Licitacao.findAll({ where: {
cd_municipio: cd_municipio,
nu_licitacao: { [Op.ne]: '000000000'}
nu_licitacao: { [Op.ne]: '000000000'}
},

})
.then(licitacoes => res.status(SUCCESS).json(licitacoes))
.catch(err => res.status(BAD_REQUEST).json({ err }));
Expand All @@ -38,19 +39,19 @@ exports.getLicitacaoById = (req, res) => {
{
model: Contrato,
as: "contratosLicitacao",
include: [
{
model: Previsao,
as: "previsaoContrato"
}
]
include: [{
model: Pagamento,
as: "pagamentosContrato",
required: false
}]
},
{
model: Participante,
as: "participantesLicitacao",
where: {
nu_cpfcnpj: { [Op.ne]: '00000000000000'}
}
},
required: false
}
],
where: {
Expand Down
21 changes: 21 additions & 0 deletions src/controllers/previsoes.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Arquivo: controllers/previsao.controller.js
* Descrição: arquivo responsável por recuperar informações relacionadas as previsoes contratuais.
*/

const models = require("../models/index.model");
const { previsao } = require("../models/index.model");
const Previsao = models.previsao;

const sequelize = models.sequelize_mcdb;

const BAD_REQUEST = 400;
const SUCCESS = 200;

// Retorna todos os riscos calculados
exports.getRiscos = (req, res) => {

Previsao.findAll()
.then(previsao => res.status(SUCCESS).json(previsao))
.catch(err => res.status(BAD_REQUEST).json({ err }));
};
12 changes: 9 additions & 3 deletions src/models/contrato.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,19 @@ module.exports = (sequelize, type) => {
}

);

Contrato.associate = function (models) {
Contrato.hasOne(models.previsao, {
Contrato.hasMany(models.pagamento, {
foreignKey: "id_contrato",
sourceKey: "id_contrato",
as: "pagamentosContrato"
});

Contrato.hasMany(models.empenho, {
foreignKey: "id_contrato",
sourceKey: "id_contrato",
as: "previsaoContrato"
as: "empenhosContrato"
});
}

return Contrato;
};
57 changes: 57 additions & 0 deletions src/models/empenho.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Arquivo: models/empenho.model.js
* Descrição: arquivo com o modelo de empenho.
*/

module.exports = (sequelize, type) => {
Empenho = sequelize.define(
"empenho",
{
id_empenho: {
type: type.STRING,
primaryKey: true
},
id_licitacao: type.STRING,
id_contrato: type.STRING,
cd_municipio: type.STRING,
cd_u_gestora: type.INTEGER,
dt_ano: type.INTEGER,
cd_unid_orcamentaria: type.STRING,
cd_funcao: type.STRING,
cd_subfuncao: type.STRING,
cd_programa: type.STRING,
cd_acao: type.STRING,
cd_classificacao: type.STRING,
cd_cat_economica: type.STRING,
cd_nat_despesa: type.STRING,
cd_modalidade: type.STRING,
cd_elemento: type.STRING,
cd_sub_elemento: type.STRING,
tp_licitacao: type.STRING,
nu_licitacao: type.STRING,
nu_empenho: type.STRING,
tp_empenho: type.STRING,
dt_empenho: type.STRING,
vl_empenho: type.INTEGER,
cd_credor: type.STRING,
no_credor: type.STRING,
tp_credor: type.STRING,
de_historico1: type.STRING,
de_historico2: type.STRING,
de_historico: type.STRING,
tp_meta: type.STRING,
nu_obra: type.STRING,
dt_mes_ano: type.STRING,
dt_mes_ano_referencia: type.STRING,
tp_fonte_recursos: type.STRING,
nu_cpf: type.STRING,
cd_sub_elemento_2: type.STRING
},
{
freezeTableName: true,
timestamps: false
}

);
return Empenho;
};
Loading

0 comments on commit 5a494e5

Please sign in to comment.