Skip to content

Development #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
91 changes: 11 additions & 80 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,88 +1,19 @@
# Back End Test Project <img src="https://coderockr.com/assets/images/coderockr.svg" align="right" height="50px" />
# Investiment API

You should see this challenge as an opportunity to create an application following modern development best practices (given the stack of your choice), but also feel free to use your own architecture preferences (coding standards, code organization, third-party libraries, etc). It’s perfectly fine to use vanilla code or any framework or libraries.
## Descrição do Projeto
Criação de uma API com NodeJS para o cadastro e gerenciamento de investimentos e um portal com ReactJS para interação com a API.

## Scope
Para instalação local e realização de testes do sistema primeiro voce deve clonar esse repositório: `git clone https://github.com/juancarlossilva-MS/backend-test.git`.

In this challenge you should build an API for an application that stores and manages investments, it should have the following features:
**Nota: O Banco de Dados utilizado neste projeto é o MongoDB, portanto, para utilização da aplicação é necessário que o servidor mongodb esteja configurado e em funcionamento**

1. __Creation__ of an investment with an owner, a creation date and an amount.
1. The creation date of an investment can be today or a date in the past.
2. An investment should not be or become negative.
2. __View__ of an investment with its initial amount and expected balance.
1. Expected balance should be the sum of the invested amount and the [gains][].
3. __Withdrawal__ of a investment.
1. The withdraw will always be the sum of the initial amount and its gains,
partial withdrawn is not supported.
2. Withdrawals can happen in the past or today, but can't happen before the investment creation or the future.
3. [Taxes][taxes] need to be applied to the withdrawals before showing the
final value.
4. __List__ of a person's investments
1. This list should have pagination.
Após a clonagem do repositório acessar a pasta `cd backend-test`. Note que o projeto está dividido em Front e Back.
Acesse a pasta Front `cd back` e execute o comando `npm install`.

__NOTE:__ the implementation of an interface will not be evaluated.
Após instalar as dependencias necessárias execute o comando `node server` e a API que realizará o gerenciamento dos investimentos, bem como sua inserção no BD já estará disponível na url `http://localhost:8080/api`.

### Gain Calculation
Volte a pasta principal `cd ..` e acesse a pasta `cd front` e execute o comando `npm install`.

The investment will pay 0.52% every month in the same day of the investment creation.
Após instalar as dependencias necessárias execute o comando `npm run start` e o portal para visualizar e utilizar a API bem como executar os testes já estará disponível na url `http://localhost:3000`.

Given that the gain is paid every month, it should be treated as [compound gain][], which means that every new period (month) the amount gained will become part of the investment balance for the next payment.

### Taxation

When money is withdrawn, tax is triggered. Taxes apply only to the profit/gain portion of the money withdrawn. For example, if the initial investment was 1000.00, the current balance is 1200.00, then the taxes will be applied to the 200.00.

The tax percentage changes according to the age of the investment:
* If it is less than one year old, the percentage will be 22.5% (tax = 45.00).
* If it is between one and two years old, the percentage will be 18.5% (tax = 37.00).
* If older than two years, the percentage will be 15% (tax = 30.00).

## Requirements
1. Create project using any technology of your preference. It’s perfectly OK to use vanilla code or any framework or libraries;
2. Although you can use as many dependencies as you want, you should manage them wisely;
3. It is not necessary to send the notification emails, however, the code required for that would be welcome;
4. The API must be documented in some way.

## Deliverables
The project source code and dependencies should be made available in GitHub. Here are the steps you should follow:
1. Fork this repository to your GitHub account (create an account if you don't have one, you will need it working with us).
2. Create a "development" branch and commit the code to it. Do not push the code to the main branch.
3. Include a README file that describes:
- Special build instructions, if any
- List of third-party libraries used and short description of why/how they were used
- A link to the API documentation.
4. Once the work is complete, create a pull request from "development" into "main" and send us the link.
5. Avoid using huge commits hiding your progress. Feel free to work on a branch and use `git rebase` to adjust your commits before submitting the final version.

## Coding Standards
When working on the project be as clean and consistent as possible.

## Project Deadline
Ideally you'd finish the test project in 5 days. It shouldn't take you longer than a entire week.

## Quality Assurance
Use the following checklist to ensure high quality of the project.

### General
- First of all, the application should run without errors.
- Are all requirements set above met?
- Is coding style consistent?
- The API is well documented?
- The API has unit tests?

## Submission
1. A link to the Github repository.
2. Briefly describe how you decided on the tools that you used.

## Have Fun Coding 🤘
- This challenge description is intentionally vague in some aspects, but if you need assistance feel free to ask for help.
- If any of the seems out of your current level, you may skip it, but remember to tell us about it in the pull request.

## Credits

This coding challenge was inspired on [kinvoapp/kinvo-back-end-test](https://github.com/kinvoapp/kinvo-back-end-test/blob/2f17d713de739e309d17a1a74a82c3fd0e66d128/README.md)

[gains]: #gain-calculation
[taxes]: #taxation
[interest]: #interest-calculation
[compound gain]: https://www.investopedia.com/terms/g/gain.asp
A documentação dessa API encontra-se no Link: <a href="https://docs.google.com/document/d/18T5PQTHv9a6EwR2i42Wd5vMkkBE_WWjr1wq-zQSeTpU/edit?usp=sharing">https://docs.google.com/document/d/18T5PQTHv9a6EwR2i42Wd5vMkkBE_WWjr1wq-zQSeTpU/edit?usp=sharing</a>
4 changes: 4 additions & 0 deletions back/app/config/db.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
url: "mongodb://localhost:27017/backend_test",
database: "backend_test",
};
160 changes: 160 additions & 0 deletions back/app/controllers/invest.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
const db = require("../models");
const Invest = db.invest;

exports.create = (req,res) => {
if(!req.body.owner ) {
res.status(400).send({ message: "Content can not be empty!" });
return;
}
if(req.body.valueInitalInvest < 0 ) {
res.status(400).send({ message: "The initial value of investiment can't be negative!" });
return;
}

dataAtual = new Date(new Date().getTime());

if(new Date(req.body.dateInvest) > dataAtual)
{
res.status(400).send({ message: "Can't set future date of investiment!"});
return;
}

const invest = new Invest({
owner: req.body.owner,
valueInitalInvest: req.body.valueInitalInvest,
dateInvest: new Date(req.body.dateInvest),
withdrawn:req.body.withdrawn,
valueWithdrawn:0,
dateWithdrawn:null
});
invest
.save(invest)
.then(data => {
res.status(201).send(data);
})
.catch(err => {
console.log("error"+err)
res.status(500).send({
message:
err.message || "Some error occurred while creating."
});
});
}
exports.findAll = (req,res) => {
owner = req.query.owner;
pg = req.query.pg;

var end = 5;
var init = pg ? ((pg-1)*5) : 0;
var condition = owner ? { owner: { $eq: owner} } : {};

Invest.find(condition).limit(end).skip(init)
.then(data => {
res.send(data);
})
.catch(err => {
console.log(err)
res.status(500).send({
message:
err.message || "Some error occurred while retrieving."
});
});

}
exports.withdrawal = (req,res) => {
var idInvest = req.body.id_invest;
var dataWithdrawn = new Date(req.body.dataWithdrawn.substr(0,10));
var dateInvest = req.body.dateInvest
var valueWithdrawn = req.body.valueWithdrawn;

var d = new Date();
d.setHours(0,0,0,0);
var di = new Date(dateInvest)
di.setHours(0,0,0,0);

var dataAtual = new Date(d.getTime() + (3600000*(-3)))
var dataI = new Date(di.getTime() + (3600000*(-3)))

if( dataWithdrawn > dataAtual || dataWithdrawn < dataI){
res.status(400).send({ message: "Data de retirada do investimento inválida"});
}
Invest.updateOne(
{_id:idInvest},
{ $set: {
withdrawn: true,
valueWithdrawn:valueWithdrawn,
dateWithdrawn:dataWithdrawn
}
}).then((data)=>{
res.status(201).send({data});
})

}
exports.findOne = (req,res) => {
id = req.params.id
dataWithdrawn = req.query.dataWithdrawn

Invest.findById(id)
.then(data => {
if (!data)
res.status(404).send({ message: "Not found Investiment with id " + id });
else {
var d = new Date(data.dateInvest)
d.setHours(0,0,0,0);

if(dataWithdrawn == "null" || dataWithdrawn == undefined){
var di = new Date();
di.setHours(0,0,0,0);
data2 = new Date(di.getTime() + (3600000*(-3)))

}else{
data2 = new Date(dataWithdrawn.substr(0,30))
}
var di = new Date();
di.setHours(0,0,0,0);

data1 = new Date(d.getTime() + (3600000*(-3)))
now = new Date(di.getTime() + (3600000*(-3)))

if( data2 > now || data2 < data1){
res.status(400).send({ message: "Data de retirada do investimento inválida! Obs: a data deve ser maior que a data de lançamento e menor ou igual ao dia de hoje."});
return;
}
var total = (data2.getFullYear() - data1.getFullYear())*12 + (data2.getMonth() - data1.getMonth());
if((data2.getDate() - data1.getDate()) < 0 ){
total--;
}

let result = data.valueInitalInvest;
for(i=0;i<total;i++){
result += (result * 0.0052);
}

lucroBruto = result - data.valueInitalInvest;
lucro = result - data.valueInitalInvest;
let imposto;
if(total < 12){
lucro -= (lucro * 0.225);
imposto = "22,5%"
}
if(total >= 12 && total <= 24){
lucro -= (lucro * 0.185);
imposto = "18,5%"
}
if(total > 24){
lucro -= (lucro * 0.15);
imposto = "15%"
}


res.status(201).send({lucroBruto:lucroBruto.toFixed(2),imposto:imposto,total:total,result:parseFloat((data.valueInitalInvest + lucro).toFixed(2))});
}
})
.catch(err => {
console.log("error"+err)
res
.status(500)
.send({ message: "Error retrieving Investiment with id=" + id });
});

}
Loading