Skip to content

Commit

Permalink
Merge pull request #28 from sombriks/develop
Browse files Browse the repository at this point in the history
teste
  • Loading branch information
sombriks committed Jun 9, 2024
2 parents bac6d50 + bcaa057 commit 886bc0d
Show file tree
Hide file tree
Showing 8 changed files with 197 additions and 122 deletions.
16 changes: 11 additions & 5 deletions service-node-koa/app/config/db/knexfile.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const _cfg = {
min: 2,
max: 10,
afterCreate: (conn, cb) =>
conn.run('PRAGMA foreign_keys = ON', cb)
conn.run('PRAGMA foreign_keys = ON', cb) // does not work with postgres
},
migrations: {
directory: `${__dirname}/migrations`,
Expand All @@ -29,17 +29,23 @@ module.exports = {
connection: {
filename: ':memory:'
}
// client: 'pg',
// connection: process.env.PG_CONNECTION_URL
},
staging: {
..._cfg,
client: 'pg',
connection: process.env.PG_CONNECTION_URL
connection: process.env.PG_CONNECTION_URL,
pool: {
..._cfg.pool,
afterCreate: undefined
}
},
production: {
..._cfg,
client: 'pg',
connection: process.env.PG_CONNECTION_URL
connection: process.env.PG_CONNECTION_URL,
pool: {
..._cfg.pool,
afterCreate: undefined
}
}
}
47 changes: 30 additions & 17 deletions service-node-koa/app/controllers/movimentacao.mjs
Original file line number Diff line number Diff line change
@@ -1,51 +1,51 @@
import {
downloadMovimentacoes,
downloadMovimentacoes, findCategoria, findConta,
findMovimentacao,
insertMovimentacao,
listMovimentacaoByConta,
listMovimentacaoByUsuario,
removeMovimentacao,
removeMovimentacao, transferencia,
updateMovimentacao,
uploadMovimentacoes
} from '../services/index.mjs'

export const listMovimentacaoRequest = async ctx => {
const {usuario_id} = ctx.request.params
const { usuario_id } = ctx.request.params
// TODO validar
const params = {...ctx.request.query, usuario_id}
const params = { ...ctx.request.query, usuario_id }
if (ctx.request.query.conta_id) ctx.body = await listMovimentacaoByConta(params)
else ctx.body = await listMovimentacaoByUsuario(params)
}

export const findMovimentacaoRequest = async ctx => {
const {/*usuario_id, conta_id,*/ id} = ctx.request.params
const {/*usuario_id, conta_id,*/ id } = ctx.request.params
ctx.body = await findMovimentacao(id)
}

export const insertMovimentacaoRequest = async ctx => {
const {conta_id} = ctx.request.params
const { conta_id } = ctx.request.params
const novaMovimentacao = ctx.request.body
novaMovimentacao.conta_id = conta_id
ctx.body = await insertMovimentacao(novaMovimentacao)
}

export const updateMovimentacaoRequest = async ctx => {
const {conta_id, id} = ctx.request.params
const { conta_id, id } = ctx.request.params
const movimentacao = ctx.request.body
movimentacao.alteracao = new Date()
movimentacao.conta_id = conta_id
movimentacao.id = id
ctx.body = await updateMovimentacao({id, movimentacao})
ctx.body = await updateMovimentacao({ id, movimentacao })
}

export const removeMovimentacaoRequest = async ctx => {
const {id} = ctx.request.params
const { id } = ctx.request.params
ctx.body = await removeMovimentacao(id)
}

export const uploadMovimentacoesRequest = async ctx => {
const {usuario_id: id} = ctx.request.params
const {file} = ctx.request.body
const { usuario_id: id } = ctx.request.params
const { file } = ctx.request.body
ctx.logger.info(`prepare to import data for user #${id}`)
if (!file) throw new Error('csv file not found')
const lines = file.split(/[\r\n]/).filter(l => l.length > 0)
Expand All @@ -54,17 +54,30 @@ export const uploadMovimentacoesRequest = async ctx => {
const header = lines.shift()
if (header.split(/[,;]/).length < 7) throw new Error('Incorrect column count')
ctx.logger.info('Proper column count. Start processing...')
const result = await uploadMovimentacoes({id, header, lines})
ctx.body = {message: 'processed', result}
const result = await uploadMovimentacoes({ id, header, lines })
ctx.body = { message: 'processed', result }
}

export const downloadMovimentacoesRequest = async ctx => {
const {usuario_id: id} = ctx.request.params
const {conta_id, data_inicio, data_fim} = ctx.request.query
const { usuario_id: id } = ctx.request.params
const { conta_id, data_inicio, data_fim } = ctx.request.query
if (!conta_id) throw new Error('account not found')
if (!data_inicio || !data_fim) throw new Error('must provide date interval (data_inicio/data_fim)')
// if (!data_inicio.match(/\d{4}-\d{2}-\d{2}/)) throw new Error("invalid date format for data_inicio")
// if (!data_fim.match(/\d{4}-\d{2}-\d{2}/)) throw new Error("invalid date format for data_fim")
const csv = await downloadMovimentacoes({id, conta_id, data_inicio, data_fim})
ctx.body = {csv}
const csv = await downloadMovimentacoes({ id, conta_id, data_inicio, data_fim })
ctx.body = { csv }
}

export const transferenciaRequest = async ctx => {
const { usuario_id, conta_id: conta_origem_id, conta_destino_id } = ctx.request.params
const { valor, vencimento, categoria: categoria_id } = ctx.request.body
const origem = await findConta({ id: conta_origem_id, usuario_id })
const destino = await findConta({ id: conta_destino_id, usuario_id })
const categoria = await findCategoria({ id: categoria_id, usuario_id })
if (!origem) return ctx.throw(400, 'conta origem não encontrada')
if (!destino) return ctx.throw(400, 'conta destino não encontrada')
if (!categoria) return ctx.throw(400, 'categoria não encontrada')
const result = await transferencia({ origem, destino, categoria, valor, vencimento })
ctx.body = result
}
131 changes: 66 additions & 65 deletions service-node-koa/app/main.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Koa from "koa";
import cors from "@koa/cors";
import Router from "@koa/router";
import bodyParser from "koa-bodyparser";
import Koa from 'koa'
import cors from '@koa/cors'
import Router from '@koa/router'
import bodyParser from 'koa-bodyparser'

import {
delCategoriaRequest,
Expand All @@ -22,7 +22,7 @@ import {
listMovimentacaoRequest,
listPlanejamentoRequest,
listRecorrenciaRequest,
removeMovimentacaoRequest,
removeMovimentacaoRequest, transferenciaRequest,
updateCategoriaRequest,
updateContaRequest,
updateMovimentacaoRequest,
Expand All @@ -31,87 +31,88 @@ import {
userLoginRequest,
userSignupRequest
} from './controllers/index.mjs'
import {listModelocategoria, listTipoConta, listTipoMovimentacao, listTipoRecorrencia} from "./services/index.mjs";
import {contaOwnedBy, ifAuthenticated} from "./config/security/index.mjs";
import { listModelocategoria, listTipoConta, listTipoMovimentacao, listTipoRecorrencia } from './services/index.mjs'
import { contaOwnedBy, ifAuthenticated } from './config/security/index.mjs'

import ApiBuilder from "koa-api-builder";
import {errHandler} from './config/default-error-handler.mjs'
import {cabin} from "./config/base-logging.mjs";
import ApiBuilder from 'koa-api-builder'
import { errHandler } from './config/default-error-handler.mjs'
import { cabin } from './config/base-logging.mjs'

export const app = new Koa();
const router = new Router();
export const app = new Koa()
const router = new Router()

app.use(cabin.middleware).use(errHandler).use(cors()).use(bodyParser());
app.use(cabin.middleware).use(errHandler).use(cors()).use(bodyParser())

new ApiBuilder({router}).path(b => {
b.get("/status", async ctx => ctx.body = "ONLINE");
b.get("/tipo-conta", async ctx => ctx.body = await listTipoConta());
b.get("/modelocategoria", async ctx => ctx.body = await listModelocategoria());
b.get("/tipo-recorrencia", async ctx => ctx.body = await listTipoRecorrencia());
b.get("/tipo-movimentacao", async ctx => ctx.body = await listTipoMovimentacao());
new ApiBuilder({ router }).path(b => {
b.get('/status', async ctx => ctx.body = 'ONLINE')
b.get('/tipo-conta', async ctx => ctx.body = await listTipoConta())
b.get('/modelocategoria', async ctx => ctx.body = await listModelocategoria())
b.get('/tipo-recorrencia', async ctx => ctx.body = await listTipoRecorrencia())
b.get('/tipo-movimentacao', async ctx => ctx.body = await listTipoMovimentacao())

b.post("/login", userLoginRequest);
b.post("/signup", userSignupRequest);
b.post('/login', userLoginRequest)
b.post('/signup', userSignupRequest)

b.path("/:usuario_id", ifAuthenticated, b => {
b.del("/removeAccount", delUsuarioRequest);
b.path('/:usuario_id', ifAuthenticated, b => {
b.del('/removeAccount', delUsuarioRequest)

b.path("/categoria", b => {
b.get(listCategoriasRequest);
b.post(insertCategoriaRequest);
b.path("/:id", b => {
b.get(findCategoriaRequest);
b.put(updateCategoriaRequest);
b.del(delCategoriaRequest);
b.path('/categoria', b => {
b.get(listCategoriasRequest)
b.post(insertCategoriaRequest)
b.path('/:id', b => {
b.get(findCategoriaRequest)
b.put(updateCategoriaRequest)
b.del(delCategoriaRequest)
})
});
})

b.path("/conta", b => {
b.get(listContasRequest);
b.post(insertContaRequest);
b.path("/:id", b => {
b.get(findContaRequest);
b.put(updateContaRequest);
b.del(delContaRequest);
});
});
b.path('/conta', b => {
b.get(listContasRequest)
b.post(insertContaRequest)
b.path('/:id', b => {
b.get(findContaRequest)
b.put(updateContaRequest)
b.del(delContaRequest)
})
})

b.path("/movimentacao", b => {
b.get(listMovimentacaoRequest);
b.get("/download", downloadMovimentacoesRequest);
b.post("/upload", uploadMovimentacoesRequest);
b.path("/:conta_id", contaOwnedBy, b => {
b.post(insertMovimentacaoRequest);
b.path("/:id", b => {
b.get(findMovimentacaoRequest);
b.put(updateMovimentacaoRequest);
b.del(removeMovimentacaoRequest);
});
});
});
b.path('/movimentacao', b => {
b.get(listMovimentacaoRequest)
b.get('/download', downloadMovimentacoesRequest)
b.post('/upload', uploadMovimentacoesRequest)
b.path('/:conta_id', contaOwnedBy, b => {
b.post(insertMovimentacaoRequest)
b.post('/transferir/:conta_destino_id', transferenciaRequest)
b.path('/:id', b => {
b.get(findMovimentacaoRequest)
b.put(updateMovimentacaoRequest)
b.del(removeMovimentacaoRequest)
})
})
})

b.path("/planejamento", b => {
b.path('/planejamento', b => {
b.get(listPlanejamentoRequest)
b.post(insertPlanejamentoRequest)
b.path("/:id", b => {
b.path('/:id', b => {
b.del(delPlanejamentoRequest)
b.put(updatePlanejamentoRequest)
});
});
})
})

b.path("/recorrencia", b => {
b.path('/recorrencia', b => {
b.get(listRecorrenciaRequest)
b.post(insertRecorrenciaRequest)
b.path("/:id", b => {
b.path('/:id', b => {
b.get(findRecorrenciaRequest)
b.put(updateRecorrenciaRequest)
b.del(delRecorrenciaRequest)
b.get("/lancamentos", geraLancamentosRequest)
b.get('/lancamentos', geraLancamentosRequest)
})
});
})

b.get("/dashboard", getDashboardRequest)
});
}).build();
b.get('/dashboard', getDashboardRequest)
})
}).build()

app.use(router.routes()).use(router.allowedMethods());
app.use(router.routes()).use(router.allowedMethods())
31 changes: 30 additions & 1 deletion service-node-koa/app/services/movimentacao.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export const listMovimentacaoByUsuario = async (params) => {
knex('conta').where({ usuario_id }).select('id'))
}


export const listMovimentacaoByConta = async (params) => {
const {
conta_id = -1
Expand Down Expand Up @@ -117,6 +116,36 @@ export const removeMovimentacao = async (id = -1) =>
.where({ id })
.del()

export const transferencia = async ({ origem, destino, categoria, valor, vencimento }) => {
const saida = {
descricao: `${origem.descricao} => ${destino.descricao}`,
valor,
criacao: new Date().toISOString(),
alteracao: new Date().toISOString(),
vencimento: new Date(vencimento).toISOString(),
efetivada: new Date(vencimento).toISOString(),
conta_id: origem.id,
categoria_id: categoria.id,
tipo_movimentacao_id: 2 // saída
}
const entrada = {
descricao: `${destino.descricao} <= ${origem.descricao}`,
valor,
criacao: new Date().toISOString(),
alteracao: new Date().toISOString(),
vencimento: new Date(vencimento).toISOString(),
efetivada: new Date(vencimento).toISOString(),
conta_id: destino.id,
categoria_id: categoria.id,
tipo_movimentacao_id: 1 // entrada
}

const [{ idEntrada }] = await insertMovimentacao(entrada)
const [{ idSaida }] = await insertMovimentacao(saida)

return { idEntrada, idSaida }
}

export const uploadMovimentacoes = async ({ id, header, lines }) => {
const headerMap = { tipo: -1, conta: -1, categoria: -1, vencimento: -1, efetivada: -1, valor: -1, 'descrição': -1 }
header.toLowerCase().replace(/"/g, '').split(/[,;]/).forEach((h, i) => {
Expand Down
Loading

0 comments on commit 886bc0d

Please sign in to comment.