Files
WYGIWYH/app/apps/accounts/forms.py
T
Asish Kumar d3f29f5ad1 feat(currencies): make displaying exchanged amounts optional
Currencies and accounts get a "Show exchanged amounts" switch, on by
default. Turning it off hides the amounts converted to the exchange
currency without removing the exchange currency, so consolidated totals
on the Net Worth page keep working.

The switch belongs to whichever one provides the exchange currency:

- Transactions (including both legs of combined transfers) use the
  account's switch when the account has its own exchange currency, and
  the currency's switch otherwise, matching how the exchanged amount is
  picked.
- Account cards and Net Worth account rows follow the account.
- Currency cards, the monthly summary and daily allowance, Net Worth
  currency rows and the month-by-month and year-by-year insights follow
  the currency.

Currency totals still convert hidden currencies, because the
consolidated totals are built from those values; the setting only
leaves them out of the displayed data. The API keeps returning
exchanged_amount for transactions, and the account serializer exposes
the new field (currencies already serialize all fields).

Closes #486
2026-11-11 15:26:04 +05:30

319 lines
10 KiB
Python

import calendar
from apps.accounts.models import Account, AccountGroup, InvestmentClass
from apps.common.middleware.thread_local import get_current_user
from apps.common.fields.forms.dynamic_select import (
DynamicModelChoiceField,
DynamicModelMultipleChoiceField,
)
from apps.common.widgets.crispy.daisyui import Switch
from apps.common.widgets.crispy.submit import NoClassSubmit
from apps.common.widgets.datepicker import AirDatePickerInput, AirMonthYearPickerInput
from apps.common.widgets.decimal import ArbitraryDecimalDisplayNumberInput
from apps.common.widgets.tom_select import TomSelect, TomSelectMultiple
from apps.currencies.models import Currency
from apps.transactions.models import (
TransactionCategory,
TransactionEntity,
TransactionTag,
)
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import HTML, Column, Div, Field, Layout, Row
from django import forms
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
class AccountGroupForm(forms.ModelForm):
class Meta:
model = AccountGroup
fields = ["name"]
labels = {"name": _("Group name")}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.form_method = "post"
self.helper.layout = Layout(
"name",
)
if self.instance and self.instance.pk:
self.helper.layout.append(
FormActions(
NoClassSubmit("submit", _("Update"), css_class="btn btn-primary"),
),
)
else:
self.helper.layout.append(
FormActions(
NoClassSubmit("submit", _("Add"), css_class="btn btn-primary"),
),
)
class InvestmentClassForm(forms.ModelForm):
class Meta:
model = InvestmentClass
fields = ["name", "target"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.form_method = "post"
self.helper.layout = Layout(
"name",
"target",
FormActions(
NoClassSubmit(
"submit",
_("Update") if self.instance.pk else _("Add"),
css_class="btn btn-primary",
),
),
)
class AccountForm(forms.ModelForm):
group = DynamicModelChoiceField(
create_field="name",
label=_("Group"),
model=AccountGroup,
required=False,
)
investment_class = DynamicModelChoiceField(
create_field="name",
label=_("Asset class"),
model=InvestmentClass,
required=False,
help_text=Account._meta.get_field("investment_class").help_text,
)
class Meta:
model = Account
fields = [
"name",
"group",
"currency",
"exchange_currency",
"show_exchanged_amounts",
"is_asset",
"is_archived",
"is_investment",
"investment_class",
"income_entities",
"income_categories",
"income_tags",
]
widgets = {
"currency": TomSelect(),
"exchange_currency": TomSelect(),
"income_entities": TomSelectMultiple(),
"income_categories": TomSelectMultiple(),
"income_tags": TomSelectMultiple(),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["group"].queryset = AccountGroup.objects.all()
self.fields["investment_class"].queryset = InvestmentClass.all_objects.filter(
Q(owner=get_current_user())
| Q(owner=None)
# Keep a class from the account's owner when it's shared with us
| Q(accounts=self.instance.id or 0)
).distinct()
selectable = Q(active=True)
if self.instance.id:
selectable |= Q(investment_accounts=self.instance.id)
for name, model in (
("income_entities", TransactionEntity),
("income_categories", TransactionCategory),
("income_tags", TransactionTag),
):
self.fields[name].queryset = model.objects.filter(selectable).distinct()
if self.instance.id:
qs = Currency.objects.filter(
Q(is_archived=False) | Q(accounts=self.instance.id)
).distinct()
self.fields["currency"].queryset = qs
self.fields["exchange_currency"].queryset = qs
else:
qs = Currency.objects.filter(Q(is_archived=False))
self.fields["currency"].queryset = qs
self.fields["exchange_currency"].queryset = qs
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.form_method = "post"
self.helper.layout = Layout(
"name",
"group",
Switch("is_asset"),
Switch("is_archived"),
"currency",
"exchange_currency",
Switch("show_exchanged_amounts"),
Switch("is_investment"),
# Only relevant for investments: shown while the switch above is on
Div(
"investment_class",
"income_entities",
"income_categories",
"income_tags",
css_id="investment_income",
css_class="" if self.instance.is_investment else "hidden",
),
HTML(
'<div class="hidden" _="on change from closest <form/> '
"if #id_is_investment.checked remove .hidden from #investment_income "
'else add .hidden to #investment_income end"></div>'
),
)
if self.instance and self.instance.pk:
self.helper.layout.append(
FormActions(
NoClassSubmit("submit", _("Update"), css_class="btn btn-primary"),
),
)
else:
self.helper.layout.append(
FormActions(
NoClassSubmit("submit", _("Add"), css_class="btn btn-primary"),
),
)
class AccountBalanceForm(forms.Form):
account_id = forms.IntegerField(widget=forms.HiddenInput())
new_balance = forms.DecimalField(
max_digits=42, decimal_places=30, required=False, label=_("New balance")
)
category = DynamicModelChoiceField(
create_field="name",
model=TransactionCategory,
required=False,
label=_("Category"),
)
tags = DynamicModelMultipleChoiceField(
model=TransactionTag,
to_field_name="name",
create_field="name",
required=False,
label=_("Tags"),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.currency_suffix = self.initial.get("suffix", "")
self.currency_prefix = self.initial.get("prefix", "")
self.currency_decimal_places = self.initial.get("decimal_places", 2)
self.account_name = self.initial.get("account_name", "")
self.account_group = self.initial.get("account_group", None)
self.current_balance = self.initial.get("current_balance", 0)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
"new_balance",
Row(
Column("category"),
Column("tags"),
),
Field("account_id"),
)
self.fields["new_balance"].widget = ArbitraryDecimalDisplayNumberInput(
decimal_places=self.currency_decimal_places
)
self.fields["category"].queryset = TransactionCategory.objects.filter(
active=True
)
self.fields["tags"].queryset = TransactionTag.objects.filter(active=True)
class ReconciliationCutoffForm(forms.Form):
"""Which transactions the reconciliation balance is computed against."""
MODE_CURRENT = "current"
MODE_DATE = "date"
MODE_MONTH = "month"
mode = forms.ChoiceField(
choices=[
(MODE_CURRENT, _("All paid transactions")),
(MODE_DATE, _("Up to date")),
(MODE_MONTH, _("Up to reference month")),
],
required=False,
initial=MODE_CURRENT,
label=_("Balance against"),
)
date = forms.DateField(
required=False,
label=_("Date"),
widget=AirDatePickerInput(clear_button=False),
)
month = forms.DateField(
required=False,
label=_("Reference month"),
widget=AirMonthYearPickerInput(clear_button=False),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, prefix="cutoff", **kwargs)
today = timezone.localdate(timezone.now())
self.today = today
self.fields["date"].initial = today
self.fields["month"].initial = today.replace(day=1)
def _value(self, name):
# Bound but invalid/empty values fall back to the field's initial.
if self.is_bound and self.is_valid() and self.cleaned_data.get(name):
return self.cleaned_data[name]
return self.fields[name].initial
@property
def selected_mode(self):
return self._value("mode")
def balance_filters(self) -> dict:
"""Extra kwargs for get_account_balance."""
if self.selected_mode == self.MODE_DATE:
return {"date_lte": self._value("date")}
if self.selected_mode == self.MODE_MONTH:
return {"reference_date_lte": self._value("month")}
return {}
def adjustment_dates(self):
"""(date, reference_date) for the reconciliation transaction.
Dated at the cutoff so a later reconcile with the same or later cutoff
includes it, and an earlier one doesn't.
"""
if self.selected_mode == self.MODE_DATE:
cutoff = self._value("date")
return cutoff, cutoff.replace(day=1)
if self.selected_mode == self.MODE_MONTH:
month = self._value("month")
last_day = month.replace(
day=calendar.monthrange(month.year, month.month)[1]
)
return min(self.today, last_day), month
return self.today, self.today.replace(day=1)
AccountBalanceFormSet = forms.formset_factory(AccountBalanceForm, extra=0)