Merge pull request #201

feat(insights): add Emergency Fund simulator
This commit is contained in:
Herculino Trotta
2025-03-04 02:52:52 -03:00
committed by GitHub
5 changed files with 146 additions and 1 deletions

View File

@@ -44,4 +44,9 @@ urlpatterns = [
views.latest_transactions,
name="insights_latest_transactions",
),
path(
"insights/emergency-fund/",
views.emergency_fund,
name="insights_emergency_fund",
),
]

View File

@@ -1,8 +1,10 @@
import decimal
import json
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from django.contrib.auth.decorators import login_required
from django.db.models import Sum, Avg, F
from django.shortcuts import render
from django.utils import timezone
from django.views.decorators.http import require_http_methods
@@ -27,6 +29,7 @@ from apps.insights.utils.sankey import (
from apps.insights.utils.transactions import get_transactions
from apps.transactions.models import TransactionCategory, Transaction
from apps.insights.utils.category_overview import get_categories_totals
from apps.transactions.utils.calculations import calculate_currency_totals
@login_required
@@ -209,3 +212,55 @@ def late_transactions(request):
"insights/fragments/late_transactions.html",
{"transactions": transactions},
)
@only_htmx
@login_required
@require_http_methods(["GET"])
def emergency_fund(request):
transactions_currency_queryset = Transaction.objects.filter(
is_paid=True, account__is_archived=False, account__is_asset=False
).order_by(
"account__currency__name",
)
currency_net_worth = calculate_currency_totals(
transactions_queryset=transactions_currency_queryset, ignore_empty=False
)
end_date = (timezone.now() - relativedelta(months=1)).replace(day=1)
start_date = (end_date - relativedelta(months=12)).replace(day=1)
# Step 1: Calculate total expense for each month and currency
monthly_expenses = (
Transaction.objects.filter(
type=Transaction.Type.EXPENSE,
is_paid=True,
account__is_asset=False,
reference_date__gte=start_date,
reference_date__lte=end_date,
category__mute=False,
)
.values("reference_date", "account__currency")
.annotate(monthly_total=Sum("amount"))
)
# Step 2: Calculate averages by currency using Python
currency_totals = defaultdict(list)
for expense in monthly_expenses:
currency_id = expense["account__currency"]
currency_totals[currency_id].append(expense["monthly_total"])
for currency_id, totals in currency_totals.items():
avg = currency_net_worth[currency_id]["average"] = sum(totals) / len(totals)
if currency_net_worth[currency_id]["total_current"] < 0:
currency_net_worth[currency_id]["months"] = 0
else:
currency_net_worth[currency_id]["months"] = int(
currency_net_worth[currency_id]["total_current"] / avg
)
return render(
request,
"insights/fragments/emergency_fund.html",
{"data": currency_net_worth},
)

View File

@@ -1,8 +1,12 @@
{% load currency_display %}
{% if not divless %}
<div class="{% if text_end %}text-end{% elif text_start %}text-start{% endif %}">
<span class="amount{% if color == 'grey' or color == "gray" %} tw-text-gray-500{% elif color == 'green' %} tw-text-green-400{% elif color == 'red' %} tw-text-red-400{% endif %}"
{% endif %}
<span class="amount{% if color == 'grey' or color == "gray" %} tw-text-gray-500{% elif color == 'green' %} tw-text-green-400{% elif color == 'red' %} tw-text-red-400{% endif %} {{ custom_class }}"
data-original-value="{% currency_display amount=amount prefix=prefix suffix=suffix decimal_places=decimal_places %}"
data-amount="{{ amount|floatformat:"-40u" }}">
</span><span>{{ slot }}</span>
{% if not divless %}
</div>
{% endif %}

View File

@@ -0,0 +1,75 @@
{% load i18n %}
<div hx-get="{% url 'insights_emergency_fund' %}" hx-trigger="updated from:window" class="show-loading"
hx-swap="outerHTML">
<div class="accordion" id="emergency-fund-accordion">
{% for id, data in data.items %}
{% if data.average %}
<div class="accordion-item">
<h2 class="accordion-header">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
data-bs-target="#flush-collapse-{{ id }}" aria-expanded="false"
aria-controls="flush-collapse-{{ id }}">
<span>
<span class="tw-text-gray-300">{% trans "You've spent an average of" %}</span>
<c-amount.display
:amount="data.average"
:prefix="data.currency.prefix"
:suffix="data.currency.suffix"
:decimal_places="data.currency.decimal_places"
custom_class="tw-text-3xl"
divless></c-amount.display>
<span class="tw-text-gray-300">{% trans 'on the last 12 months, at this rate you could go by' %}</span>
<span class="tw-text-3xl">{{ data.months }}</span>
<span class="tw-text-gray-300">{% trans 'months without any income.' %}</span>
</span>
</button>
</h2>
<div id="flush-collapse-{{ id }}" class="accordion-collapse collapse"
data-bs-parent="#emergency-fund-accordion">
<div class="accordion-body">
<div class="d-flex justify-content-between align-items-baseline mt-2">
<div class="text-end font-monospace">
<div class="tw-text-gray-400">{% translate 'average expenses' %}</div>
</div>
<div class="dotted-line flex-grow-1"></div>
<div class="text-end font-monospace">
<c-amount.display
:amount="data.average"
:prefix="data.currency.prefix"
:suffix="data.currency.suffix"
:decimal_places="data.currency.decimal_places"
color="red"></c-amount.display>
</div>
</div>
<div class="d-flex justify-content-between align-items-baseline mt-2">
<div class="text-end font-monospace">
<div class="tw-text-gray-400">{% translate 'liquid total' %}</div>
</div>
<div class="dotted-line flex-grow-1"></div>
<div class="text-end font-monospace">
<c-amount.display
:amount="data.total_current"
:prefix="data.currency.prefix"
:suffix="data.currency.suffix"
:decimal_places="data.currency.decimal_places"
color="{% if data.total_current > 0 %}green{% elif data.total_current < 0 %}red{% endif %}"></c-amount.display>
</div>
</div>
<div class="d-flex justify-content-between align-items-baseline mt-2">
<div class="text-end font-monospace">
<div class="tw-text-gray-400">{% translate 'months left' %}</div>
</div>
<div class="dotted-line flex-grow-1"></div>
<div class="text-end font-monospace">
<span>{{ data.months }}</span>
</div>
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>

View File

@@ -114,6 +114,12 @@
hx-indicator="#tab-content"
hx-target="#tab-content">{% trans 'Latest Transactions' %}
</button>
<button class="nav-link" id="v-pills-tab" data-bs-toggle="pill" data-bs-target="#v-pills-content"
type="button" role="tab" aria-controls="v-pills-content" aria-selected="false"
hx-get="{% url 'insights_emergency_fund' %}"
hx-indicator="#tab-content"
hx-target="#tab-content">{% trans 'Emergency Fund' %}
</button>
</div>
</div>
</div>