Skip to content
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

Development/CayoNakasato #54

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
SECRET_KEY=
POSTGRES_DB=
POSTGRES_USER=
POSTGRES_PASSWORD=
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
venv
__pycache__
.env
db.sqlite3
.vscode

134 changes: 49 additions & 85 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,88 +1,52 @@
# Back End Test Project <img src="https://coderockr.com/assets/images/coderockr.svg" align="right" height="50px" />
# Tenha controle de seus investimentos

##### Projeto no qual você pode guardar seus investimentos ou de outras pessoas e vê-los crescendo com a quantia que colocou com os juros compostos, você também pode retirá-los, o que ocasionará no retiro total da quantia e tendo ainda um histórico de investimentos em cada conta!

## Tecnologias Utilizadas

#### Neste projeto foram usados as seguintes tecnologias:

```
- Python
- Django
- Django Rest Framework
- PostgreSQL
```
## Pré Requisitos:
-Python
-Pip
-PostgreSQL
#### Assim que clonar o repositório entre na pasta com :
- cd backend-test-nomedousuário
- code .

## Abra o terminal para instalar as dependências no ambiente virtual(venv):
#### Para utilizar o venv se estiver utilizando Linux use o comando:

source venv/bin/activate

#### Para utilizar o venv se estiver utilizando bash use o comando:

source venv/Scripts/activate
#### Para utilizar o venv se estiver utilizando PowerShell use o comando:

venv/Scripts/activate

### Para instalar as dependências use o comando:
pip install -r requirements.txt

##### Dentro do arquivo requirements.txt está todos as denpendências que o projeto necessita para o código rodar normalmente.

## Após instalar pode se iniciar o projeto com
### Rodando as migrations com
python manage.py migrate
### Após rodar as migrations pode iniciar o projeto com:
python manage.py runserver
# Para acessar a documentação, após iniciar o servidor, possui a rota
Nesta rota acessando pelo localhost:****/api/docs terá acesso a documentação da api!
```
/api/docs
````

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.

## Scope

In this challenge you should build an API for an application that stores and manages investments, it should have the following features:

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][].
2. If an investment was already withdrawn then the balance must reflect the gains of that investment
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.

__NOTE:__ the implementation of an interface will not be evaluated.

### Gain Calculation

The investment will pay 0.52% every month in the same day of the investment creation.

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
Empty file added investments/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions investments/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions investments/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class InvestmentsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "investments"
8 changes: 8 additions & 0 deletions investments/baker_recipes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from model_bakery.recipe import Recipe
from investments.models import Investment

new_investment = Recipe(
Investment,
amount= 100,
created_at= "2022-10-06"
)
69 changes: 69 additions & 0 deletions investments/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Generated by Django 4.1.3 on 2022-12-06 21:57

from django.db import migrations, models
import investments.models
import uuid


class Migration(migrations.Migration):

initial = True

dependencies = []

operations = [
migrations.CreateModel(
name="Investment",
fields=[
(
"id",
models.UUIDField(
default=uuid.uuid4,
editable=False,
primary_key=True,
serialize=False,
),
),
(
"initial_amount",
models.DecimalField(decimal_places=2, max_digits=15, null=True),
),
(
"amount",
models.DecimalField(
decimal_places=2,
max_digits=10,
validators=[investments.models.validate_amount],
),
),
(
"created_at",
models.DateField(validators=[investments.models.validate_date]),
),
(
"gains",
models.DecimalField(
decimal_places=2, default=0, max_digits=5, null=True
),
),
(
"withdrawn_date",
models.DateField(
null=True,
validators=[investments.models.validate_withdrawn_date],
),
),
(
"withdrew_amount",
models.DecimalField(decimal_places=2, max_digits=15, null=True),
),
(
"expected_balance",
models.DecimalField(
decimal_places=2, default=0, max_digits=15, null=True
),
),
("isActive", models.BooleanField(default=True)),
],
),
]
27 changes: 27 additions & 0 deletions investments/migrations/0002_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Generated by Django 4.1.3 on 2022-12-06 21:57

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
("investments", "0001_initial"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.AddField(
model_name="investment",
name="owner",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="investments",
to=settings.AUTH_USER_MODEL,
),
),
]
Empty file.
103 changes: 103 additions & 0 deletions investments/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
from django.db import models
from django.core.exceptions import ValidationError
from datetime import date
import ipdb
import uuid
from rest_framework.exceptions import APIException
from rest_framework.views import status

class CustomValidation(APIException):
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
default_detail = "A server error occured."

def __init__(self, detail, status_code):
if status_code is not None:self.status_code=status_code
if detail is not None:
self.detail={"detail": detail}

def validate_amount(value):
if value < 0 :
raise ValidationError(
(f'{value} is a invalid number, please only positive numbers!')
)

def validate_date(date_req):
today = date.today()

day = str(today).split("-")[2]
month = str(today).split("-")[1]

if int(day) > 31:
raise ValidationError(
(f'{day} is a invalid day, please insert a valid day!')
)

if int(month) > 12:
raise ValidationError(
(f'{month} is a invalid month, please insert a valid month!')
)

today_formated = today.strftime("%d/%m/%Y")

formated_date = date_req.strftime("%d/%m/%Y")

if today_formated.split('/')[2] < formated_date.split('/')[2]:
raise CustomValidation("Invalid Date!", 400)

if today_formated.split('/')[2] == formated_date.split('/')[2]:
if today_formated.split('/')[1] < formated_date.split('/')[1]:
raise CustomValidation("Invalid Date!", 400)


if today_formated.split('/')[2] == formated_date.split('/')[2]:
if today_formated.split('/')[1] == formated_date.split('/')[1]:
if today_formated.split('/')[0] < formated_date.split('/')[0]:
raise CustomValidation("Invalid Date!", 400)

def validate_withdrawn_date(date_req):
today = date.today()

if int(str(today).split("-")[2]) > 31:
ipdb.set_trace()
raise CustomValidation("Invalid Date!",400)

if int(str(today).split("-")[1]) > 12:
ipdb.set_trace()

raise CustomValidation("Invalid Date!",400)

today_formated = str(today)

formated_date = str(date_req)

if today_formated.split('-')[0] < formated_date.split('-')[0]:
raise CustomValidation("Invalid Date!",400)

if today_formated.split('-')[0] == formated_date.split('-')[0]:
if today_formated.split('-')[1] < formated_date.split('-')[1]:
raise CustomValidation("Invalid Date!",400)


if today_formated.split('-')[0] == formated_date.split('-')[0]:
if today_formated.split('-')[1] == formated_date.split('-')[1]:
if today_formated.split('-')[2] < formated_date.split('-')[2]:
raise CustomValidation("Invalid Date!",400)


class Investment(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
initial_amount = models.DecimalField(decimal_places=2,max_digits=15, null=True)
amount = models.DecimalField(decimal_places=2,max_digits=10,validators=[validate_amount])
created_at = models.DateField(validators=[validate_date])
gains = models.DecimalField(decimal_places=2,max_digits=5, null=True, default=0)
withdrawn_date = models.DateField(null=True, validators=[validate_withdrawn_date])
withdrew_amount = models.DecimalField(decimal_places=2,max_digits=15, null=True)
expected_balance = models.DecimalField(decimal_places=2,max_digits=15, null=True, default=0)
isActive = models.BooleanField(default=True)

owner = models.ForeignKey(
"users.User",
on_delete=models.CASCADE,
related_name="investments"
)

Loading