Compare previous period by category

This commit is contained in:
JKuijperM 2026-01-22 18:50:36 +01:00
parent b74cfbac9e
commit 2a692534d0
2 changed files with 71 additions and 1 deletions

View File

@ -144,6 +144,39 @@
</tbody>
</table>
{% if compare_enabled %}
<h3>Comparativa por categoría</h3>
<table>
<thead>
<tr>
<th>Categoría</th>
<th>Actual</th>
<th>Anterior</th>
<th>Diferencia</th>
</tr>
</thead>
<tbody>
{% for row in category_comparison %}
<tr>
<td>{{ row.category }}</td>
<td>{{ row.current }}</td>
<td>{{ row.previous }}</td>
<td>
{% if row.difference > 0 %}
▲ {{ row.difference }}
{% elif row.difference < 0 %}
▼ {{ row.difference }}
{% else %}
=
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
<hr>
<!-- ========================= -->

View File

@ -207,6 +207,7 @@ def dashboard(request):
previous_total = None
difference = None
percentage = None
category_comparison = None
if compare_enabled:
previous_expenses = Expense.objects.filter(owner=request.user)
@ -240,6 +241,41 @@ def dashboard(request):
if previous_total:
percentage = (difference / previous_total) * 100
# ------------------
# Previous expenses by category
# ------------------
previous_by_category = (
previous_expenses
.values('category__name')
.annotate(total=Sum('amount'))
)
current_map = {
row['category__name']: row['total']
for row in by_category
}
previous_map = {
row['category__name']: row['total']
for row in previous_by_category
}
all_categories = set(current_map.keys()) | set(previous_map.keys())
category_comparison = []
for category in all_categories:
current_total = current_map.get(category, 0)
previous_total_cat = previous_map.get(category, 0)
difference = current_total - previous_total_cat
category_comparison.append({
'category': category,
'current': current_total,
'previous': previous_total_cat,
'difference': difference,
})
# Send the data to the dashboard
return render(request, 'expenses/dashboard.html', {
@ -258,4 +294,5 @@ def dashboard(request):
'kpi_previous_total': previous_total,
'kpi_difference': difference,
'kpi_percentage': percentage,
'category_comparison': category_comparison,
})