Merge branch 'main' into export

This commit is contained in:
Herculino Trotta
2025-02-19 13:41:04 -03:00
committed by GitHub
9 changed files with 337 additions and 233 deletions

View File

@@ -9,6 +9,7 @@ from apps.common.widgets.datepicker import (
AirDatePickerInput, AirDatePickerInput,
) )
from apps.transactions.models import TransactionCategory from apps.transactions.models import TransactionCategory
from apps.common.widgets.tom_select import TomSelect
class SingleMonthForm(forms.Form): class SingleMonthForm(forms.Form):
@@ -115,7 +116,9 @@ class CategoryForm(forms.Form):
category = forms.ModelChoiceField( category = forms.ModelChoiceField(
required=False, required=False,
label=_("Category"), label=_("Category"),
empty_label=_("Uncategorized"),
queryset=TransactionCategory.objects.filter(active=True), queryset=TransactionCategory.objects.filter(active=True),
widget=TomSelect(clear_button=True),
) )
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):

View File

@@ -3,7 +3,7 @@ from django.db.models.functions import Coalesce
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
def get_category_sums_by_account(queryset, category): def get_category_sums_by_account(queryset, category=None):
""" """
Returns income/expense sums per account for a specific category. Returns income/expense sums per account for a specific category.
""" """
@@ -11,10 +11,11 @@ def get_category_sums_by_account(queryset, category):
queryset.filter(category=category) queryset.filter(category=category)
.values("account__name") .values("account__name")
.annotate( .annotate(
income=Coalesce( current_income=Coalesce(
Sum( Sum(
Case( Case(
When(type="IN", then="amount"), When(type="IN", then="amount"),
When(is_paid=True, then="amount"),
default=Value(0), default=Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30), output_field=DecimalField(max_digits=42, decimal_places=30),
) )
@@ -22,10 +23,35 @@ def get_category_sums_by_account(queryset, category):
Value(0), Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30), output_field=DecimalField(max_digits=42, decimal_places=30),
), ),
expense=Coalesce( current_expense=Coalesce(
Sum( Sum(
Case( Case(
When(type="EX", then=-F("amount")), When(type="EX", then=-F("amount")),
When(is_paid=True, then="amount"),
default=Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30),
)
),
Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30),
),
projected_income=Coalesce(
Sum(
Case(
When(type="IN", then="amount"),
When(is_paid=False, then="amount"),
default=Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30),
)
),
Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30),
),
projected_expense=Coalesce(
Sum(
Case(
When(type="EX", then=-F("amount")),
When(is_paid=False, then="amount"),
default=Value(0), default=Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30), output_field=DecimalField(max_digits=42, decimal_places=30),
) )
@@ -41,18 +67,26 @@ def get_category_sums_by_account(queryset, category):
"labels": [item["account__name"] for item in sums], "labels": [item["account__name"] for item in sums],
"datasets": [ "datasets": [
{ {
"label": _("Income"), "label": _("Current Income"),
"data": [float(item["income"]) for item in sums], "data": [float(item["current_income"]) for item in sums],
}, },
{ {
"label": _("Expenses"), "label": _("Current Expenses"),
"data": [float(item["expense"]) for item in sums], "data": [float(item["current_expense"]) for item in sums],
},
{
"label": _("Projected Income"),
"data": [float(item["projected_income"]) for item in sums],
},
{
"label": _("Projected Expenses"),
"data": [float(item["projected_expense"]) for item in sums],
}, },
], ],
} }
def get_category_sums_by_currency(queryset, category): def get_category_sums_by_currency(queryset, category=None):
""" """
Returns income/expense sums per currency for a specific category. Returns income/expense sums per currency for a specific category.
""" """
@@ -60,10 +94,11 @@ def get_category_sums_by_currency(queryset, category):
queryset.filter(category=category) queryset.filter(category=category)
.values("account__currency__name") .values("account__currency__name")
.annotate( .annotate(
income=Coalesce( current_income=Coalesce(
Sum( Sum(
Case( Case(
When(type="IN", then="amount"), When(type="IN", then="amount"),
When(is_paid=True, then="amount"),
default=Value(0), default=Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30), output_field=DecimalField(max_digits=42, decimal_places=30),
) )
@@ -71,10 +106,35 @@ def get_category_sums_by_currency(queryset, category):
Value(0), Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30), output_field=DecimalField(max_digits=42, decimal_places=30),
), ),
expense=Coalesce( current_expense=Coalesce(
Sum( Sum(
Case( Case(
When(type="EX", then=-F("amount")), When(type="EX", then=-F("amount")),
When(is_paid=True, then="amount"),
default=Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30),
)
),
Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30),
),
projected_income=Coalesce(
Sum(
Case(
When(type="IN", then="amount"),
When(is_paid=False, then="amount"),
default=Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30),
)
),
Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30),
),
projected_expense=Coalesce(
Sum(
Case(
When(type="EX", then=-F("amount")),
When(is_paid=False, then="amount"),
default=Value(0), default=Value(0),
output_field=DecimalField(max_digits=42, decimal_places=30), output_field=DecimalField(max_digits=42, decimal_places=30),
) )
@@ -90,12 +150,20 @@ def get_category_sums_by_currency(queryset, category):
"labels": [item["account__currency__name"] for item in sums], "labels": [item["account__currency__name"] for item in sums],
"datasets": [ "datasets": [
{ {
"label": _("Income"), "label": _("Current Income"),
"data": [float(item["income"]) for item in sums], "data": [float(item["current_income"]) for item in sums],
}, },
{ {
"label": _("Expenses"), "label": _("Current Expenses"),
"data": [float(item["expense"]) for item in sums], "data": [float(item["current_expense"]) for item in sums],
},
{
"label": _("Projected Income"),
"data": [float(item["projected_income"]) for item in sums],
},
{
"label": _("Projected Expenses"),
"data": [float(item["projected_expense"]) for item in sums],
}, },
], ],
} }

View File

@@ -126,7 +126,7 @@ def category_sum_by_account(request):
# Generate data # Generate data
account_data = get_category_sums_by_account(transactions, category) account_data = get_category_sums_by_account(transactions, category)
else: else:
account_data = None account_data = get_category_sums_by_account(transactions, category=None)
return render( return render(
request, request,
@@ -150,7 +150,7 @@ def category_sum_by_currency(request):
# Generate data # Generate data
currency_data = get_category_sums_by_currency(transactions, category) currency_data = get_category_sums_by_currency(transactions, category)
else: else:
currency_data = None currency_data = get_category_sums_by_currency(transactions, category=None)
return render( return render(
request, request,

View File

@@ -1,7 +1,7 @@
{% load markdown %} {% load markdown %}
{% load i18n %} {% load i18n %}
<div class="transaction"> <div class="transaction {% if transaction.type == "EX" %}expense{% else %}income{% endif %}">
<div class="d-flex my-1 {% if transaction.type == "EX" %}expense{% else %}income{% endif %}"> <div class="d-flex my-1">
{% if not disable_selection %} {% if not disable_selection %}
<label class="px-3 d-flex align-items-center justify-content-center"> <label class="px-3 d-flex align-items-center justify-content-center">
<input class="form-check-input" type="checkbox" name="transactions" value="{{ transaction.id }}" <input class="form-check-input" type="checkbox" name="transactions" value="{{ transaction.id }}"

View File

@@ -27,7 +27,7 @@
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li> <li>
<div class="dropdown-item px-3 tw-cursor-pointer" <div class="dropdown-item px-3 tw-cursor-pointer"
_="on click set <#transactions-list input[type='checkbox']/>'s checked to true then call me.blur() then trigger change"> _="on click set <#transactions-list .transaction:not([style*='display: none']) input[type='checkbox']/>'s checked to true then call me.blur() then trigger change">
<i class="fa-regular fa-square-check tw-text-green-400 me-3"></i>{% translate 'Select All' %} <i class="fa-regular fa-square-check tw-text-green-400 me-3"></i>{% translate 'Select All' %}
</div> </div>
</li> </li>

View File

@@ -1,83 +1,100 @@
{% load i18n %} {% load i18n %}
{% if account_data.labels %} {% if account_data.labels %}
<div class="chart-container" style="position: relative; height:400px; width:100%" _="init call setupAccountChart() end"> <div class="chart-container" style="position: relative; height:400px; width:100%"
<canvas id="accountChart"></canvas> _="init call setupAccountChart() end">
</div> <canvas id="accountChart"></canvas>
</div>
<script> <script>
// Get the data from your Django view (passed as JSON) // Get the data from your Django view (passed as JSON)
var accountData = {{ account_data|safe }}; var accountData = {{ account_data|safe }};
function setupAccountChart() { function setupAccountChart() {
var chartOptions = { var chartOptions = {
indexAxis: 'y', // This makes the chart horizontal indexAxis: 'y', // This makes the chart horizontal
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
scales: { scales: {
x: { x: {
stacked: true, // Enable stacking on the x-axis stacked: true, // Enable stacking on the x-axis
title: { title: {
display: false, display: false,
}, },
}, },
y: { y: {
stacked: true, // Enable stacking on the y-axis stacked: true, // Enable stacking on the y-axis
title: { title: {
display: false, display: false,
}, },
} }
}, },
plugins: { plugins: {
legend: { legend: {
display: false, display: false,
}, },
tooltip: { tooltip: {
callbacks: { callbacks: {
label: function (context) { label: function (context) {
if (context.parsed.x !== null) { if (context.parsed.x !== null) {
return new Intl.NumberFormat(undefined).format(Math.abs(context.parsed.x)); // Using abs for display return `${context.dataset.label}: ${new Intl.NumberFormat(undefined, {
} minimumFractionDigits: 0,
return ""; maximumFractionDigits: 30,
}, roundingMode: 'trunc'
} }).format(Math.abs(context.parsed.x))}`;
} }
} return "";
}; },
}
}
}
};
new Chart( new Chart(
document.getElementById('accountChart'), document.getElementById('accountChart'),
{ {
type: 'bar', type: 'bar',
data: { data: {
labels: accountData.labels, labels: accountData.labels,
datasets: [ datasets: [
{ {
label: "{% trans 'Income' %}", label: "{% trans 'Current Income' %}",
data: accountData.datasets[0].data, data: accountData.datasets[0].data,
backgroundColor: '#4dde80', backgroundColor: '#4dde80',
stack: 'stack0' stack: 'stack0'
}, },
{ {
label: "{% trans 'Expenses' %}", label: "{% trans 'Current Expenses' %}",
data: accountData.datasets[1].data, data: accountData.datasets[1].data,
backgroundColor: '#f87171', backgroundColor: '#f87171',
stack: 'stack0' stack: 'stack0'
} },
] {
}, label: "{% trans 'Projected Income' %}",
options: { data: accountData.datasets[2].data,
...chartOptions, backgroundColor: '#4dde8080', // Added transparency
plugins: { stack: 'stack0'
...chartOptions.plugins, },
title: { {
display: false, label: "{% trans 'Projected Expenses' %}",
} data: accountData.datasets[3].data,
} backgroundColor: '#f8717180', // Added transparency
} stack: 'stack0'
} }
); ]
} },
</script> options: {
...chartOptions,
plugins: {
...chartOptions.plugins,
title: {
display: false,
}
}
}
}
);
}
</script>
{% else %} {% else %}
<c-msg.empty title="{% translate "No information to display" %}"></c-msg.empty> <c-msg.empty title="{% translate "No information to display" %}"></c-msg.empty>
{% endif %} {% endif %}

View File

@@ -1,84 +1,92 @@
{% load i18n %} {% load i18n %}
{% if currency_data.labels %} {% if currency_data.labels %}
<div class="chart-container" style="position: relative; height:400px; width:100%" <div class="chart-container" style="position: relative; height:400px; width:100%"
_="init call setupCurrencyChart() end"> _="init call setupCurrencyChart() end">
<canvas id="currencyChart"></canvas> <canvas id="currencyChart"></canvas>
</div> </div>
<script> <script>
// Get the data from your Django view (passed as JSON) // Get the data from your Django view (passed as JSON)
var currencyData = {{ currency_data|safe }}; var currencyData = {{ currency_data|safe }};
function setupCurrencyChart() { function setupCurrencyChart() {
var chartOptions = { var chartOptions = {
indexAxis: 'y', // This makes the chart horizontal indexAxis: 'y',
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
scales: { scales: {
x: { x: {
stacked: true, // Enable stacking on the x-axis stacked: true,
title: { title: {
display: false, display: false,
}, },
}, },
y: { y: {
stacked: true, // Enable stacking on the y-axis stacked: true,
title: { title: {
display: false, display: false,
}, },
} }
}, },
plugins: { plugins: {
legend: { legend: {
display: false, display: false,
}, },
tooltip: { tooltip: {
callbacks: { callbacks: {
label: function (context) { label: function (context) {
if (context.parsed.x !== null) { if (context.parsed.x !== null) {
return new Intl.NumberFormat(undefined).format(Math.abs(context.parsed.x)); // Using abs for display return `${context.dataset.label}: ${new Intl.NumberFormat(undefined, {
} minimumFractionDigits: 0,
return ""; maximumFractionDigits: 30,
}, roundingMode: 'trunc'
} }).format(Math.abs(context.parsed.x))}`;
} }
} return "";
}; },
}
}
}
};
new Chart( new Chart(
document.getElementById('currencyChart'), document.getElementById('currencyChart'),
{ {
type: 'bar', type: 'bar',
data: { data: {
labels: currencyData.labels, labels: currencyData.labels,
datasets: [ datasets: [
{ {
label: "{% trans 'Income' %}", label: "{% trans 'Current Income' %}",
data: currencyData.datasets[0].data, data: currencyData.datasets[0].data,
backgroundColor: '#4dde80', backgroundColor: '#4dde80',
stack: 'stack0' stack: 'stack0'
}, },
{ {
label: "{% trans 'Expenses' %}", label: "{% trans 'Current Expenses' %}",
data: currencyData.datasets[1].data, data: currencyData.datasets[1].data,
backgroundColor: '#f87171', backgroundColor: '#f87171',
stack: 'stack0' stack: 'stack0'
} },
] {
}, label: "{% trans 'Projected Income' %}",
options: { data: currencyData.datasets[2].data,
...chartOptions, backgroundColor: '#4dde8080', // Added transparency
plugins: { stack: 'stack0'
...chartOptions.plugins, },
title: { {
display: false, label: "{% trans 'Projected Expenses' %}",
} data: currencyData.datasets[3].data,
} backgroundColor: '#f8717180', // Added transparency
} stack: 'stack0'
} }
); ]
} },
</script> options: chartOptions
}
);
}
</script>
{% else %} {% else %}
<c-msg.empty title="{% translate "No information to display" %}"></c-msg.empty> <c-msg.empty title="{% translate "No information to display" %}"></c-msg.empty>
{% endif %} {% endif %}

View File

@@ -2,7 +2,8 @@
{% load crispy_forms_tags %} {% load crispy_forms_tags %}
<form _="install init_tom_select <form _="install init_tom_select
on change trigger updated" id="category-form"> on change trigger updated
init trigger updated" id="category-form">
{% crispy category_form %} {% crispy category_form %}
</form> </form>
@@ -15,7 +16,6 @@
<div class="card-body"> <div class="card-body">
<div id="account-card" class="show-loading" hx-get="{% url 'category_sum_by_account' %}" <div id="account-card" class="show-loading" hx-get="{% url 'category_sum_by_account' %}"
hx-trigger="updated from:window" hx-include="#category-form, #picker-form, #picker-type"> hx-trigger="updated from:window" hx-include="#category-form, #picker-form, #picker-type">
<c-msg.empty title="{% translate "No information to display" %}"></c-msg.empty>
</div> </div>
</div> </div>
</div> </div>
@@ -28,7 +28,6 @@
<div class="card-body"> <div class="card-body">
<div id="currency-card" class="show-loading" hx-get="{% url 'category_sum_by_currency' %}" <div id="currency-card" class="show-loading" hx-get="{% url 'category_sum_by_currency' %}"
hx-trigger="updated from:window" hx-include="#category-form, #picker-form, #picker-type"> hx-trigger="updated from:window" hx-include="#category-form, #picker-form, #picker-type">
<c-msg.empty title="{% translate "No information to display" %}"></c-msg.empty>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -4,11 +4,12 @@
{% block content %} {% block content %}
<div class="container-fluid"> <div class="container-fluid">
<div class="row my-3"> <div class="row my-3 h-100">
<div class="col-lg-2 col-md-3 mb-3 mb-md-0"> <div class="col-lg-2 col-md-3 mb-3 mb-md-0">
<div class=""> <div class="position-sticky tw-top-3">
<div class="mb-2 w-100 d-lg-inline-flex d-grid gap-2 flex-wrap justify-content-lg-center" role="group" <div class="">
_="on change <div class="mb-2 w-100 d-lg-inline-flex d-grid gap-2 flex-wrap justify-content-lg-center" role="group"
_="on change
set type to event.target.value set type to event.target.value
add .tw-hidden to <#picker-form > div:not(.tw-hidden)/> add .tw-hidden to <#picker-form > div:not(.tw-hidden)/>
@@ -28,65 +29,73 @@
remove .tw-hidden from #date-range-form remove .tw-hidden from #date-range-form
end end
then trigger updated" then trigger updated"
id="picker-type"> id="picker-type">
<input type="radio" class="btn-check" name="type" value="month" id="monthradio" autocomplete="off" checked> <input type="radio" class="btn-check" name="type" value="month" id="monthradio" autocomplete="off"
<label class="btn btn-sm btn-outline-primary flex-grow-1" for="monthradio">{% translate 'Month' %}</label> checked>
<label class="btn btn-sm btn-outline-primary flex-grow-1" for="monthradio">{% translate 'Month' %}</label>
<input type="radio" class="btn-check" name="type" value="year" id="yearradio" autocomplete="off"> <input type="radio" class="btn-check" name="type" value="year" id="yearradio" autocomplete="off">
<label class="btn btn-sm btn-outline-primary flex-grow-1" for="yearradio">{% translate 'Year' %}</label> <label class="btn btn-sm btn-outline-primary flex-grow-1" for="yearradio">{% translate 'Year' %}</label>
<input type="radio" class="btn-check" name="type" value="month-range" id="monthrangeradio" autocomplete="off"> <input type="radio" class="btn-check" name="type" value="month-range" id="monthrangeradio"
<label class="btn btn-sm btn-outline-primary flex-grow-1" for="monthrangeradio">{% translate 'Month Range' %}</label> autocomplete="off">
<label class="btn btn-sm btn-outline-primary flex-grow-1"
for="monthrangeradio">{% translate 'Month Range' %}</label>
<input type="radio" class="btn-check" name="type" value="year-range" id="yearrangeradio" autocomplete="off"> <input type="radio" class="btn-check" name="type" value="year-range" id="yearrangeradio"
<label class="btn btn-sm btn-outline-primary flex-grow-1" for="yearrangeradio">{% translate 'Year Range' %}</label> autocomplete="off">
<label class="btn btn-sm btn-outline-primary flex-grow-1"
for="yearrangeradio">{% translate 'Year Range' %}</label>
<input type="radio" class="btn-check" name="type" value="date-range" id="daterangeradio" autocomplete="off"> <input type="radio" class="btn-check" name="type" value="date-range" id="daterangeradio"
<label class="btn btn-sm btn-outline-primary flex-grow-1" for="daterangeradio">{% translate 'Date Range' %}</label> autocomplete="off">
</div> <label class="btn btn-sm btn-outline-primary flex-grow-1"
<form id="picker-form" for="daterangeradio">{% translate 'Date Range' %}</label>
_="install init_datepicker </div>
<form id="picker-form"
_="install init_datepicker
on change trigger updated"> on change trigger updated">
<div id="month-form" class=""> <div id="month-form" class="">
{% crispy month_form %} {% crispy month_form %}
</div> </div>
<div id="year-form" class="tw-hidden"> <div id="year-form" class="tw-hidden">
{% crispy year_form %} {% crispy year_form %}
</div> </div>
<div id="month-range-form" class="tw-hidden"> <div id="month-range-form" class="tw-hidden">
{% crispy month_range_form %} {% crispy month_range_form %}
</div> </div>
<div id="year-range-form" class="tw-hidden"> <div id="year-range-form" class="tw-hidden">
{% crispy year_range_form %} {% crispy year_range_form %}
</div> </div>
<div id="date-range-form" class="tw-hidden"> <div id="date-range-form" class="tw-hidden">
{% crispy date_range_form %} {% crispy date_range_form %}
</div> </div>
</form> </form>
</div> </div>
<hr class="mt-0"> <hr class="mt-0">
<div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist" <div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist"
aria-orientation="vertical"> aria-orientation="vertical">
<button class="nav-link" id="v-pills-tab" data-bs-toggle="pill" data-bs-target="#v-pills-content" <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" type="button" role="tab" aria-controls="v-pills-content" aria-selected="false"
hx-get="{% url 'insights_sankey_by_account' %}" hx-include="#picker-form, #picker-type" hx-get="{% url 'insights_sankey_by_account' %}" hx-include="#picker-form, #picker-type"
hx-indicator="#tab-content" hx-indicator="#tab-content"
hx-target="#tab-content">{% trans 'Account Flow' %} hx-target="#tab-content">{% trans 'Account Flow' %}
</button> </button>
<button class="nav-link" id="v-pills-tab" data-bs-toggle="pill" data-bs-target="#v-pills-content" <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" type="button" role="tab" aria-controls="v-pills-content" aria-selected="false"
hx-get="{% url 'insights_sankey_by_currency' %}" hx-get="{% url 'insights_sankey_by_currency' %}"
hx-include="#picker-form, #picker-type" hx-include="#picker-form, #picker-type"
hx-indicator="#tab-content" hx-indicator="#tab-content"
hx-target="#tab-content">{% trans 'Currency Flow' %} hx-target="#tab-content">{% trans 'Currency Flow' %}
</button> </button>
<button class="nav-link" id="v-pills-tab" data-bs-toggle="pill" data-bs-target="#v-pills-content" <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" type="button" role="tab" aria-controls="v-pills-content" aria-selected="false"
hx-get="{% url 'category_explorer_index' %}" hx-get="{% url 'category_explorer_index' %}"
hx-include="#picker-form, #picker-type" hx-include="#picker-form, #picker-type"
hx-indicator="#tab-content" hx-indicator="#tab-content"
hx-target="#tab-content">{% trans 'Category Explorer' %} hx-target="#tab-content">{% trans 'Category Explorer' %}
</button> </button>
</div>
</div> </div>
</div> </div>
<div class="col-md-9 col-lg-10"> <div class="col-md-9 col-lg-10">