Skip to content

Commit

Permalink
Adicionando poetry e atualizando layout da pagina
Browse files Browse the repository at this point in the history
  • Loading branch information
joaoallmeida committed Sep 10, 2024
1 parent 83cc468 commit 5a936f1
Show file tree
Hide file tree
Showing 7 changed files with 1,408 additions and 37 deletions.
12 changes: 10 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
FROM python:3.10.12-slim

# Configure Poetry
ENV POETRY_HOME=/opt/poetry
ENV POETRY_VENV=/opt/poetry-venv
ENV POETRY_CACHE_DIR=/opt/.cache
ENV PATH="${PATH}:${POETRY_VENV}/bin"

RUN apt-get update
RUN apt-get install -y --no-install-recommends \
libatlas-base-dev \
Expand All @@ -10,9 +16,11 @@ RUN apt-get install -y --no-install-recommends \

WORKDIR /app
COPY /app /app
COPY requirements.txt .
COPY pyproject.toml .

RUN pip install --upgrade pip setuptools wheel && pip install poetry
RUN poetry install

RUN pip install --upgrade pip setuptools wheel && pip install -r requirements.txt

EXPOSE 5000
CMD ["uwsgi", "--ini", "./wsgi.ini"]
25 changes: 14 additions & 11 deletions app/calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@
import traceback

class Calculator:
def __init__(self, codes:list, choice:str, value:float) -> None:
self.codes = [x.strip() for x in codes]
def __init__(self, form_data:list, choice:str) -> None:
self.data = form_data
self.choice = choice
self.value = value
self.currentYear = datetime.now().year

def calculator(self) -> Dict:
Expand All @@ -26,18 +25,20 @@ def calculator(self) -> Dict:
if self.__check_exists__(df):
for _ , row in df.iterrows():

val = [list(val.values())[0] for val in self.data if row['TICKER'] in val][0]

if self.choice == 'quotas':
cotes = self.value
value_invested = val
else:
cotes = ( (self.value / len(df.index)) / row['PRECO'])
value_invested = (val/row['PRECO'])

values = {
"fundo": row['TICKER'],
"preco": row['PRECO'],
"cotas": round(cotes),
"cotas": round(value_invested),
"ult_dividendo": row['ULTIMO DIVIDENDO'],
"investimento": (row['PRECO'] * cotes),
"dividendo": (cotes * row['ULTIMO DIVIDENDO']),
"investimento": (row['PRECO'] * value_invested),
"dividendo": (value_invested * row['ULTIMO DIVIDENDO']),
"totalInvestir": (row['PRECO'] * 1000 / row['ULTIMO DIVIDENDO']),
"totalCotas": round((1000 / row['ULTIMO DIVIDENDO'])),
"report": self.__get_report__(row['TICKER'])
Expand Down Expand Up @@ -71,13 +72,15 @@ def __get_data__(self) -> pd.DataFrame:
}

try:
codes = [list(item.keys())[0] for item in self.data]

response = requests.get( url, headers=headers)
content = response.content
response.raise_for_status()

df = pd.read_csv(io.StringIO(content.decode('utf-8')), sep=';')

df = df[df['TICKER'].isin(self.codes)]
df = df[df['TICKER'].isin(codes)]
df['PRECO'] = df['PRECO'].apply(lambda x: float(x.replace(".", "").replace(",", ".")))
df['DY'] = df['DY'].apply(lambda x: float(x.replace(".", "").replace(",", ".")))
df['ULTIMO DIVIDENDO'] = df['ULTIMO DIVIDENDO'].apply(lambda x: float(str(x).replace(".", "").replace(",", ".")))
Expand All @@ -94,7 +97,6 @@ def __get_report__(self, code:str) -> str:
paramGetDetail = encodeParam({'typeFund':7,'identifierFund':code.replace('11','')})
urlGetDetail = f"https://sistemaswebb3-listados.b3.com.br/fundsProxy/fundsCall/GetDetailFundSIG/{paramGetDetail}"


responseDetail = requests.get(urlGetDetail, headers=header, verify=False)
details = responseDetail.json()['detailFund']

Expand Down Expand Up @@ -145,7 +147,8 @@ def __get_report__(self, code:str) -> str:

def __check_exists__(self, df:pd.DataFrame) -> bool:
check = False
for code in self.codes:
codes = [list(item.keys())[0] for item in self.data]
for code in codes:
if code not in df['TICKER'].values:
flash(f"Fundo imobiliário {code} não encontrado.", "warning")
else:
Expand Down
35 changes: 32 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,41 @@ def calc():
* Valor a investir
"""
if request.method == "POST":
# Collect all the dynamically generated fields
form_data = []
data_found_aux = {}
data_value_aux = {}

# Loop through form data to capture dynamic fields
for key in request.form:

if key.startswith('found'):
try:
index = key.split('_')[1]
except IndexError:
index = 1

found = request.form[key]
data_found_aux[index] = found.upper()

if key.startswith('value_invested'):
try:
index = key.split('_')[2]
except IndexError:
index = 1

value_invested = request.form[key]
data_value_aux[index] = float(value_invested.replace(',',''))

for index in data_found_aux:
if index in data_value_aux:
form_data.append({
data_found_aux[index]:data_value_aux[index]
})

founds = request.form.get('found').upper().split(',')
value_invested = float(str(request.form.get('value_invested',type=str)).replace(',',''))
choice = request.form.get('choice')

calc = Calculator(founds,choice,value_invested)
calc = Calculator(form_data,choice)
data = calc.calculator()

return render_template('index.html', data=data)
Expand Down
48 changes: 40 additions & 8 deletions app/static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,27 @@ body {
color: #eeeeee;
border-color: #35dd89;
}

.btn-plus-found {
color: #3578dd;
border-color: #3578dd;
}
.btn-plus-found:hover {
background-color: #3578dd;
color: #eeeeee;
border-color: #3578dd;
}

.btn-danger-custom {
color: #DC3545;
border-color: #DC3545;
}
.btn-danger-custom:hover {
background-color: #DC3545;
color: #eeeeee;
border-color: #DC3545;
}

.btn-outline-secondary {
color: #dd7835;
border-color: #dd7835;
Expand Down Expand Up @@ -68,46 +89,57 @@ input[type='text']::placeholder{
body{
margin: auto;
}

.btn-outline-primary {
margin: 14px;
}

.btn-outline-secondary {
margin: 14px;
}

.btn-plus {
flex: 0 0 auto;
width: 50%;
}

.border-custom {
border: none;
}

.response-row {
display: flex;
flex-direction: column;
align-content: flex-start;
}

}

/* Media query for smaller mobile screens */
@media screen and (max-width: 480px) {
body{
margin: auto;
}

.btn-outline-primary {
margin: 10px;
}

.btn-outline-secondary {
margin: 10px;
}


.btn-plus {
flex: 0 0 auto;
width: 50%;
}

.w-50, .w-75 {
width: 100% !important;
}

.border-custom {
border: none;
}

}
}
96 changes: 83 additions & 13 deletions app/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,82 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="../static/style.css">
<link rel="icon" href="https://img.icons8.com/color/48/cash.png">
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('#value_invested').mask("#,##0.00", {reverse: true});
<script>
let fieldCount = 1;

// Function to add dynamic fields
function addFields() {
fieldCount++;

// Create new row div for the dynamic form fields
const newRow = document.createElement('div');
newRow.className = 'row g-2 justify-content-center';
newRow.id = `row_${fieldCount}`; // Give a unique ID for the row

// First column for 'Código Fundo'
const col1 = document.createElement('div');
col1.className = 'col-auto';
const input1 = document.createElement('input');
input1.type = 'text';
input1.className = 'form-control text-uppercase';
input1.placeholder = `Código Fundo ${fieldCount}`;
input1.name = `found_${fieldCount}`;
input1.required = true;
col1.appendChild(input1);

// Second column for 'Value Invested'
const col2 = document.createElement('div');
col2.className = 'col-auto btn-plus';
const input2 = document.createElement('input');
input2.type = 'text';
input2.className = 'form-control value_invested';
input2.placeholder = '0,00';
input2.name = `value_invested_${fieldCount}`;
col2.appendChild(input2);

// Third column for 'Remove' button
const col3 = document.createElement('div');
col3.className = 'col-auto';
const removeBtn = document.createElement('button');
removeBtn.type = 'button';
removeBtn.className = 'btn btn-danger-custom remove-field';
removeBtn.textContent = '-';
removeBtn.onclick = function() {
removeField(newRow.id); // Call the removeField function on click
};
col3.appendChild(removeBtn);

// Append columns to the new row
newRow.appendChild(col1);
newRow.appendChild(col2);
newRow.appendChild(col3);

// Append the new row to the field container
document.getElementById('fieldContainer').appendChild(newRow);

// Apply mask to newly added fields
$('.value_invested').mask("#,##0.00", {reverse: true});
}

// Function to remove the dynamic field
function removeField(rowId) {
document.getElementById(rowId).remove();
}

// Initial masking for the default fields
$(document).ready(function() {
$('.value_invested').mask("#,##0.00", {reverse: true});

// Add remove functionality to initial fields
$('.remove-field').on('click', function() {
$(this).closest('.row').remove();
});
});
</script>
</head>
Expand Down Expand Up @@ -43,17 +109,21 @@
<h1 class="text-white mb-5"> Calculadora de Rendimentos FIIs</h1>
</div>

<div class="container text-center ">
<form action="{{ url_for('calc')}}" method="post">
<div class="container-sm text-center ">
<form id="dynamicForm" action="{{ url_for('calc')}}" method="post">

<div class="row g-3 justify-content-center">
<div class="col-md-3">
<input type="text" class="form-control text-uppercase" placeholder="Código Fundo" name="found" required multiple>
<div class="row g-2 justify-content-center" id="fieldContainer">
<div class="col-auto" >
<input type="text" class="form-control text-uppercase" placeholder="Código Fundo 1" name="found" required multiple>
</div>
<div class="col-md-3">
<input type="text" id="value_invested" name="value_invested" class="form-control" placeholder="0,00">
<div class="col-auto btn-plus">
<input type="text" name="value_invested" class="form-control value_invested" placeholder="0,00">
</div>
</div>
<div class="col-auto">
<button type="button" class="btn btn-plus-found" onclick="addFields()">+</button>
</div>
</div>


<div class="row justify-content-center ">
<div class="col-sm-2 col-6">
Expand Down
Loading

0 comments on commit 5a936f1

Please sign in to comment.