0
I am doing a school job that consists of implementing a web app (mobile responsive site first) to store in the Local Storage API spent by the user. Minimum resources:
- Add an expense: description, value, date, category (food, clothing, transport, leisure, etc.);
- Edit an expense;
- Remove an expense;
- View registered expenses;
- Pie chart of expenses by category;
- Bar chart of expenses per day of the month.
I was able to make the first 5 resources, but the last one I’m having trouble adding up the expenses per day, because instead of adding it up it’s only getting the last recorded expense of a date. If anyone can help me, I’d appreciate it.
Follow the codes in Jsfiddle: https://jsfiddle.net/n2Lwg0jt/
$(function(){
var operacao = "A"; //"A"=Adição; "E"=Edição
var indice_selecionado = -1;
var tbClientes = localStorage.getItem("tbClientes");// Recupera os dados armazenados
var datas;
tbClientes = JSON.parse(tbClientes); // Converte string para objeto
if(tbClientes == null) // Caso não haja conteúdo, iniciamos um vetor vazio
tbClientes = [];
$("gasto").on("change",function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
function Adicionar(){
var data = $("#data").val();
let split = data.split('-');
let formated = split[2]+"/"+split[1]+"/"+split[0];
var cliente = JSON.stringify({
Descrição: $("#descricao").text(),
Gasto: $("#gasto").val(),
Data: formated,
Categoria: $("#categoria").val()
});
tbClientes.push(cliente);
localStorage.setItem("tbClientes", JSON.stringify(tbClientes));
alert("Registro adicionado.");
return true;
}
function Editar(){
tbClientes[indice_selecionado] = JSON.stringify({
Descrição: $("#descricao").val(),
Gasto: $("#gasto").val(),
Data: $("#data").val(),
Categoria: $("#categoria").val()
});
localStorage.setItem("tbClientes", JSON.stringify(tbClientes));
alert("Informações editadas.")
operacao = "A";
return true;
}
function Listar(){
$("#tblListar").html("");
$("#tblListar").html(
"<thead>"+
" <tr>"+
" <th scope='col'>Descrição</th>"+
" <th scope='col'>Gasto</th>"+
" <th scope='col'>Data</th>"+
" <th scope='col'>Categoria</th>"+
" <th scope='col'></th>"+
" </tr>"+
"</thead>"+
"<tbody>"+
"</tbody>"
);
var soma=0,soma1=0,soma2=0,soma3=0,soma4=0,soma5=0,soma6=0,soma7=0, somaData=[];
var listaData=[], novaArr=[];
for(var i in tbClientes){
var cli = JSON.parse(tbClientes[i]);
$("#tblListar tbody").append("<tr>"+
" <td>"+cli.Descricao+"</td>" +
" <td>"+cli.Gasto+"</td>" +
" <td>"+cli.Data+"</td>" +
" <td>"+cli.Categoria+"</td>" +
" <td><img src='edit.png' alt='"+i+"' class='btnEditar'/><img src='delete.png' alt='"+i+"' class='btnExcluir'/></td>" +
"</tr>");
if(cli.Categoria=="Sem categoria")
soma+= parseFloat(cli.Gasto);
if(cli.Categoria=="Transferência")
soma1+= parseFloat(cli.Gasto);
if(cli.Categoria=="Alimentação")
soma2+= parseFloat(cli.Gasto);
if(cli.Categoria=="Casa")
soma3+= parseFloat(cli.Gasto);
if(cli.Categoria=="Receita")
soma4+= parseFloat(cli.Gasto);
if(cli.Categoria=="Saude")
soma5+= parseFloat(cli.Gasto);
if(cli.Categoria=="Transporte")
soma6+= parseFloat(cli.Gasto);
if(cli.Categoria=="Vestuário")
soma7+= parseFloat(cli.Gasto);
listaData.push(cli.Data);
novaArr = listaData.filter((este, i) => listaData.indexOf(este) === i);
for(var j in novaArr){
if(cli.Data == novaArr[j]){
somaData[j] = 0;
somaData[j]+= somaData[j]+ parseFloat(cli.Gasto);
}
}
}
let segundoGrafico = document.getElementById('segundoGrafico').getContext('2d');
let chart2 = new Chart(segundoGrafico, {
type: 'bar',
data: {
labels: novaArr,
datasets: [{
label: 'Gastos por Dia',
data: somaData,
backgroundColor: ["#ff2200"]
}]
},
options: {
title: {
display: true,
text: 'Grafico de Gastos por Dia'
}
}
});
let primeiroGrafico = document.getElementById('primeiroGrafico').getContext('2d');
let chart = new Chart(primeiroGrafico, {
type: 'pie',
data: {
labels: ['Sem categoria', 'Transferência', 'Alimentação', 'Casa', 'Receita', 'Saude', 'Transporte', 'Vestuário'],
datasets: [{
label: 'Gastos por Categoria',
data: [soma, soma1, soma2, soma3, soma4, soma5, soma6, soma7],
backgroundColor: ["#ff2200","#088A08","#0404B4","#6E6E6E","#FFFF00","#3B0B0B","#58D3F7","#74DF00"]
}]
},
options: {
title: {
display: true,
text: 'Grafico de Gastos por Categoria'
}
}
});
}
function Excluir(){
tbClientes.splice(indice_selecionado, 1);
localStorage.setItem("tbClientes", JSON.stringify(tbClientes));
alert("Registro excluído.");
}
Listar();
$("#frmCadastro").on("submit",function(){
if(operacao == "A")
return Adicionar();
else
return Editar();
});
$("#tblListar").on("click", ".btnEditar", function(){
operacao = "E";
indice_selecionado = parseInt($(this).attr("alt"));
var cli = JSON.parse(tbClientes[indice_selecionado]);
$("#descricao").text(cli.Descricao);
$("#gasto").val(cli.Gasto);
$("#data").val(cli.Data);
$("#categoria").val(cli.Categoria);
});
$("#tblListar").on("click", ".btnExcluir", function(){
indice_selecionado = parseInt($(this).attr("alt"));
Excluir();
Listar();
});
});
img{
height: 30px;
width: 30px;
}
canvas{
max-height: 100% !important;
max-width: 100% !important;
}
@media (max-width: 320px) {
.menu {
width:calc(200% - 15px);
font-size: 12px;
}
canvas{
max-height: 100% !important;
max-width: 100% !important;
}
}
<!DOCTYPE html>
<html>
<head>
<title>API Web Storage</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="stylesheet" type="text/css" href="Trabalho.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="menu">
<nav class="navbar-expand">
<div class="nav nav-tabs" id="nav-tab" role="tablist">
<a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Home</a>
<a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false">Gastos por categoria</a>
<a class="nav-item nav-link" id="nav-contact-tab" data-toggle="tab" href="#nav-contact" role="tab" aria-controls="nav-contact" aria-selected="false">Gastos por dia</a>
</div>
</nav>
</div>
<div class="tab-content container-fluid" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
<form id="frmCadastro">
<div class="form-group">
<label for="descricao">Descrição:</label>
<input type="text" id="descricao" class="form-control">
</div>
<div class="form-group">
<label for="gasto">Gasto:</label>
<input type="number" step="0.010" id="gasto" class="form-control">
</div>
<div class="form-group">
<label for="data">Data:</label>
<input type="date" id="data" class="form-control" value="dd/MM/yyyy">
</div>
<div class="form-group">
<label for="categoria">Categoria:</label>
<select id="categoria" class="form-control">
<option value="Sem categoria" id="1">Sem categoria</option>
<option value="Transferência" id="2">Transferência</option>
<option value="Alimentação" id="3">Alimentação</option>
<option value="Casa" id="4">Casa</option>
<option value="Receita" id="5">Receita</option>
<option value="Saude" id="6">Saude</option>
<option value="Transporte" id="7">Transporte</option>
<option value="Vestuario" id="8">Vestuário</option>
</select>
</div>
<input type="submit" value="Salvar" id="btnSalvar" class="btn btn-primary mb-2">
</form>
<div class="table-responsive tabela">
<table class="table" id="tblListar"></table>
</div>
</div>
<div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
<canvas id="primeiroGrafico" width="500" height="550"></canvas>
</div>
<div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">
<canvas id="segundoGrafico" width="500" height="550"></canvas>
</div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" language="javascript" src="Trabalho.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
</body>
</html>
Better create a Jsfiddle, because running here is giving error and it is difficult to help.
– iamdlm
@iamdlm updated the topic with the link in Jsfiddle.
– matheus william