Prepared view to calculate the previous data
This commit is contained in:
parent
60a64b056a
commit
fb6e0f379e
@ -81,6 +81,12 @@
|
||||
<!-- Chart -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<label>
|
||||
<input type="checkbox" name="compare" value="1"
|
||||
{% if compare %}checked{% endif %}>
|
||||
Comparar con periodo anterior
|
||||
</label>
|
||||
|
||||
<canvas id="expensesChart"></canvas>
|
||||
|
||||
<script>
|
||||
@ -101,5 +107,8 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<hr>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@ -1,7 +1,7 @@
|
||||
from datetime import date
|
||||
from re import M
|
||||
from .models import Expense
|
||||
from .forms import ExpenseForm
|
||||
# from dateutli.relativedelta import relativedelta
|
||||
|
||||
from django.db.models import Sum
|
||||
from django.contrib.auth import login
|
||||
@ -117,6 +117,8 @@ def dashboard(request):
|
||||
selected_year = year or current_year
|
||||
selected_month = month
|
||||
|
||||
compare = request.GET.get("compare") == "1"
|
||||
|
||||
# ------------------
|
||||
# Queryset base
|
||||
# -----------------
|
||||
@ -188,10 +190,61 @@ def dashboard(request):
|
||||
.order_by('year')
|
||||
)
|
||||
|
||||
# Prepare data fot ploting in chart
|
||||
# ------------------
|
||||
# Chart
|
||||
# -----------------
|
||||
chart_labels = months
|
||||
chart_totals = [row['total'] for row in by_month]
|
||||
|
||||
# ------------------
|
||||
# Compare period
|
||||
# -----------------
|
||||
|
||||
previous_expenses = expenses
|
||||
|
||||
if month and year:
|
||||
if month == 1:
|
||||
prev_year = year - 1
|
||||
prev_month = 12
|
||||
else:
|
||||
prev_year = year
|
||||
prev_month = month - 1
|
||||
previous_expenses = previous_expenses.filter(
|
||||
date__year=prev_year,
|
||||
date__month=prev_month
|
||||
)
|
||||
elif year and month is None:
|
||||
prev_year = year - 1
|
||||
previous_expenses = previous_expenses.filter(
|
||||
date__year=prev_year
|
||||
)
|
||||
else:
|
||||
today = date.today()
|
||||
year = today.year
|
||||
month = today.month
|
||||
|
||||
if month == 1:
|
||||
prev_year = year - 1
|
||||
prev_month = 12
|
||||
else:
|
||||
prev_year = year
|
||||
prev_month = month - 1
|
||||
|
||||
previous_expenses = previous_expenses.filter(
|
||||
date__year=prev_year,
|
||||
date__month=prev_month
|
||||
)
|
||||
|
||||
previous_total = (
|
||||
previous_expenses.aggregate(total=Sum('amount'))['total'] or 0
|
||||
)
|
||||
|
||||
difference = total_amount - previous_total
|
||||
precentage = (
|
||||
(difference / previous_total) * 100 if previous_total else None
|
||||
)
|
||||
|
||||
|
||||
# Send the data to the dashboard
|
||||
return render(request, 'expenses/dashboard.html', {
|
||||
'by_category': by_category,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user