Merge remote-tracking branch 'origin/main' into feat/filter-preset-relative-dates

# Conflicts:
#	app/apps/transactions/filters.py
This commit is contained in:
Herculino Trotta committed 2026-11-14 11:29:15 -03:00
commit 262ac3fbb6
66 files changed
+9076 -5646

No files matched your search

+5
View File
@@ -517,6 +517,11 @@ SPECTACULAR_SETTINGS = {
"DESCRIPTION": "A no-frills expense tracker",
"VERSION": "1.0.0",
"SERVE_INCLUDE_SCHEMA": False,
# Several models have a "type" field with different choices
"ENUM_NAME_OVERRIDES": {
"TransactionTypeEnum": "apps.transactions.models.Transaction.Type",
"TemplateTypeEnum": "apps.transactions.models.QuickTransaction.Type",
},
# OTHER SETTINGS
}
+3
View File
@@ -4,3 +4,6 @@ from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "apps.api"
def ready(self):
import apps.api.schema # noqa: F401 registers the API token scheme for the docs
+2 -1
View File
@@ -10,7 +10,8 @@ from apps.transactions.models import (
@extend_schema_field(
{
"oneOf": [{"type": "string"}, {"type": "integer"}, {"type": "null"}],
"oneOf": [{"type": "string"}, {"type": "integer"}],
"nullable": True,
"description": "TransactionCategory ID or name. If the name doesn't exist, a new one will be created. Can be null if no category is assigned.",
}
)
+20
View File
@@ -0,0 +1,20 @@
from drf_spectacular.extensions import OpenApiAuthenticationExtension
from apps.users.models import APIToken
class APITokenAuthenticationScheme(OpenApiAuthenticationExtension):
"""Describes APITokenAuthentication in the API docs."""
target_class = "apps.api.authentication.APITokenAuthentication"
name = "apiToken"
def get_security_definition(self, auto_schema):
return {
"type": "apiKey",
"in": "header",
"name": "Authorization",
"description": (
f"A personal API token, sent as `Token {APIToken.TOKEN_PREFIX}…`."
),
}
+105 -26
View File
@@ -1,5 +1,6 @@
from decimal import Decimal
from django.db import transaction as db_transaction
from django.utils.translation import gettext_lazy as _
from drf_spectacular import openapi
from drf_spectacular.types import OpenApiTypes
@@ -22,10 +23,85 @@ from apps.transactions.models import (
InstallmentPlan,
TransactionEntity,
RecurringTransaction,
SubTransaction,
)
from apps.common.middleware.thread_local import get_current_user
class SubTransactionSerializer(serializers.ModelSerializer):
class Meta:
model = SubTransaction
fields = ["id", "name", "amount"]
read_only_fields = ["id"]
class SubTransactionsMixin:
"""`sub_transactions`, when sent, replaces the parts; a non-empty list sets
the amount to their sum. Declare the field on the serializer itself."""
sub_amount_field = "amount"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[self.sub_amount_field].required = False
def is_transfer(self, data):
return False
def validate(self, data):
field = self.sub_amount_field
subs = data.get("sub_transactions")
has_parts = self.instance is not None and self.instance.sub_transactions.exists()
if self.is_transfer(data):
if subs:
raise serializers.ValidationError(
{"sub_transactions": _("Transfers can't have sub-transactions.")}
)
if has_parts:
data["sub_transactions"] = []
elif subs:
data[field] = sum(sub["amount"] for sub in subs)
elif subs is None and field in data and has_parts:
raise serializers.ValidationError(
{
field: _(
"The amount is the sum of the sub-transactions; "
"send sub_transactions instead."
)
}
)
if not self.partial and data.get(field) is None:
raise serializers.ValidationError({field: _("This field is required.")})
return super().validate(data)
@staticmethod
def set_sub_transactions(instance, subs):
if subs is None:
return
instance.sub_transactions.all().delete()
for sub in subs:
instance.sub_transactions.create(**sub)
def create(self, validated_data):
subs = validated_data.pop("sub_transactions", None)
with db_transaction.atomic():
instance = super().create(validated_data)
self.set_sub_transactions(instance, subs)
self.after_save(instance, created=True)
return instance
def update(self, instance, validated_data):
subs = validated_data.pop("sub_transactions", None)
with db_transaction.atomic():
instance = super().update(instance, validated_data)
self.set_sub_transactions(instance, subs)
self.after_save(instance, created=False)
return instance
def after_save(self, instance, created):
"""Runs once the parts are saved, e.g. to generate transactions from them."""
class TransactionCategorySerializer(serializers.ModelSerializer):
permission_classes = [IsAuthenticated]
@@ -62,7 +138,9 @@ class TransactionEntitySerializer(serializers.ModelSerializer):
]
class InstallmentPlanSerializer(serializers.ModelSerializer):
class InstallmentPlanSerializer(SubTransactionsMixin, serializers.ModelSerializer):
sub_amount_field = "installment_amount"
sub_transactions = SubTransactionSerializer(many=True, required=False)
category: str | int = TransactionCategoryField(required=False)
tags: str | int = TransactionTagField(required=False)
entities: str | int = TransactionEntityField(required=False)
@@ -84,6 +162,7 @@ class InstallmentPlanSerializer(serializers.ModelSerializer):
"end_date",
"recurrence",
"installment_amount",
"sub_transactions",
"category",
"tags",
"entities",
@@ -91,18 +170,15 @@ class InstallmentPlanSerializer(serializers.ModelSerializer):
]
read_only_fields = ["installment_total_number", "end_date"]
def create(self, validated_data):
instance = super().create(validated_data)
instance.create_transactions()
return instance
def update(self, instance, validated_data):
instance = super().update(instance, validated_data)
instance.update_transactions()
return instance
def after_save(self, instance, created):
if created:
instance.create_transactions()
else:
instance.update_transactions()
class RecurringTransactionSerializer(serializers.ModelSerializer):
class RecurringTransactionSerializer(SubTransactionsMixin, serializers.ModelSerializer):
sub_transactions = SubTransactionSerializer(many=True, required=False)
category: str | int = TransactionCategoryField(required=False)
tags: str | int = TransactionTagField(required=False)
entities: str | int = TransactionEntityField(required=False)
@@ -115,6 +191,7 @@ class RecurringTransactionSerializer(serializers.ModelSerializer):
"account",
"type",
"amount",
"sub_transactions",
"to_account",
"to_amount",
"description",
@@ -142,19 +219,20 @@ class RecurringTransactionSerializer(serializers.ModelSerializer):
)
return super().validate(attrs)
def create(self, validated_data):
instance = super().create(validated_data)
instance.create_upcoming_transactions()
return instance
def is_transfer(self, data):
type_ = data.get("type", getattr(self.instance, "type", None))
return type_ == RecurringTransaction.Type.TRANSFER
def update(self, instance, validated_data):
instance = super().update(instance, validated_data)
instance.update_unpaid_transactions()
instance.generate_upcoming_transactions()
return instance
def after_save(self, instance, created):
if created:
instance.create_upcoming_transactions()
else:
instance.update_unpaid_transactions()
instance.generate_upcoming_transactions()
class TransactionSerializer(serializers.ModelSerializer):
class TransactionSerializer(SubTransactionsMixin, serializers.ModelSerializer):
sub_transactions = SubTransactionSerializer(many=True, required=False)
category: str | int = TransactionCategoryField(required=False)
tags: str | int = TransactionTagField(required=False)
entities: str | int = TransactionEntityField(required=False)
@@ -194,6 +272,9 @@ class TransactionSerializer(serializers.ModelSerializer):
self.fields["account_id"].queryset = Account.objects.all()
def is_transfer(self, data):
return bool(self.instance and self.instance.linked_transaction_id)
def validate(self, data):
if not self.partial:
if "date" in data and "reference_date" not in data:
@@ -204,12 +285,12 @@ class TransactionSerializer(serializers.ModelSerializer):
raise serializers.ValidationError(
_("Either 'date' or 'reference_date' must be provided.")
)
return data
return super().validate(data)
def create(self, validated_data):
tags = validated_data.pop("tags", [])
entities = validated_data.pop("entities", [])
transaction = Transaction.objects.create(**validated_data)
transaction = super().create(validated_data)
transaction.tags.set(tags)
transaction.entities.set(entities)
return transaction
@@ -217,9 +298,7 @@ class TransactionSerializer(serializers.ModelSerializer):
def update(self, instance, validated_data):
tags = validated_data.pop("tags", None)
entities = validated_data.pop("entities", None)
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
instance = super().update(instance, validated_data)
if tags is not None:
instance.tags.set(tags)
+11
View File
@@ -0,0 +1,11 @@
import tempfile
from django.core.management import call_command
from django.test import SimpleTestCase
class SchemaTests(SimpleTestCase):
def test_schema_is_valid_without_warnings(self):
"""Keeps /api/docs/ complete: drf-spectacular warns when it can't describe something."""
with tempfile.NamedTemporaryFile(suffix=".yml") as schema:
call_command("spectacular", "--validate", "--fail-on-warn", "--file", schema.name)
+3 -3
View File
@@ -52,7 +52,7 @@ class TransactionViewSet(viewsets.ModelViewSet):
ordering = ["-id"]
def get_queryset(self):
return Transaction.objects.all()
return Transaction.objects.prefetch_related("sub_transactions")
def perform_create(self, serializer):
instance = serializer.save()
@@ -145,7 +145,7 @@ class InstallmentPlanViewSet(viewsets.ModelViewSet):
ordering = ["-id"]
def get_queryset(self):
return InstallmentPlan.objects.all()
return InstallmentPlan.objects.prefetch_related("sub_transactions")
class RecurringTransactionViewSet(viewsets.ModelViewSet):
@@ -175,4 +175,4 @@ class RecurringTransactionViewSet(viewsets.ModelViewSet):
ordering = ["-id"]
def get_queryset(self):
return RecurringTransaction.objects.all()
return RecurringTransaction.objects.prefetch_related("sub_transactions")
+1 -1
View File
@@ -66,7 +66,7 @@ def calendar_list(request, month: int, year: int):
@require_http_methods(["GET"])
def calendar_transactions_list(request, day: int, month: int, year: int):
date = datetime.date(year=year, month=month, day=day)
transactions = Transaction.objects.filter(date=date).collapse_transfers().order_by(
transactions = Transaction.objects.filter(date=date).collapse_transfers().prefetch_related("sub_transactions").order_by(
"date",
"-type",
"-is_paid",
+4 -2
View File
@@ -40,9 +40,11 @@ class SharedObjectForm(forms.Form):
label=_("Visibility"),
widget=TomSelect(clear_button=False),
help_text=_(
"Private: Only shown for the owner and shared users. Only editable by the owner."
"Private: Only shown for the owner and shared users."
"<br/>"
"Public: Shown for all users. Only editable by the owner."
"Public: Shown for all users."
"<br/>"
"Only the owner can edit, share or delete it."
),
)
@@ -118,6 +118,12 @@ class Command(BaseCommand):
out.save()
return out, inc
def split(self, owner, *parts):
"""Breaks `owner` into named parts; call before it generates transactions."""
for name, amount in parts:
owner.sub_transactions.create(name=name, amount=Decimal(amount))
return owner
def rate(self, series, months):
return series[months + HISTORY_MONTHS]
@@ -278,6 +284,7 @@ class Command(BaseCommand):
notes="12 interest-free installments on the credit card.",
)
laptop.entities.set([self.ents["BuyMore"]])
self.split(laptop, ("Laptop", "99.90"), ("Extended warranty", "8.35"))
laptop.create_transactions()
dental = InstallmentPlan.objects.create(
account=checking, type=EX, description="Dental treatment",
@@ -289,7 +296,8 @@ class Command(BaseCommand):
# Recurring transactions
def recurring(account, amount, description, category, start, entity=None,
recurrence=RecurringTransaction.RecurrenceType.MONTH, paused=False):
recurrence=RecurringTransaction.RecurrenceType.MONTH, paused=False,
parts=()):
r = RecurringTransaction.objects.create(
account=account, type=EX, amount=amount, description=description,
category=self.cats[category], start_date=start, recurrence_type=recurrence,
@@ -297,6 +305,7 @@ class Command(BaseCommand):
)
if entity:
r.entities.set([self.ents[entity]])
self.split(r, *parts)
if not paused:
r.create_upcoming_transactions()
return r
@@ -304,7 +313,8 @@ class Command(BaseCommand):
recurring(card, Decimal("15.99"), "StreamFlix", "Subscriptions",
self.day(-HISTORY_MONTHS, 3), "StreamFlix")
recurring(checking, Decimal("59.99"), "Internet", "Utilities",
self.day(-HISTORY_MONTHS, 15), "FiberNet")
self.day(-HISTORY_MONTHS, 15), "FiberNet",
parts=[("Internet plan", "49.99"), ("Router rental", "10.00")])
recurring(checking, Decimal("39.90"), "Gym membership", "Health",
self.day(-HISTORY_MONTHS, 2), "Iron Gym")
recurring(card, Decimal("14.99"), "Domain renewal", "Subscriptions",
@@ -458,8 +468,9 @@ class Command(BaseCommand):
self.transfer(stock_acc, checking, Decimal("3"), self.day(-2, 21), "Sell AAPL",
to_amount=q(3 * self.rate(aapl_usd, -2)), mute=False,
category="Investments")
self.tx(retirement, EX, Decimal("45.00"), self.day(-6, 30), "Annual management fee",
"Fees")
fee = self.tx(retirement, EX, Decimal("45.00"), self.day(-6, 30),
"Annual management fee", "Fees")
self.split(fee, ("Management fee", "40.00"), ("Custody fee", "5.00"))
for m, spent in ((-9, 1500), (-3, 800)):
self.transfer(checking, gold_acc, Decimal(spent), self.day(m, 12), "Buy gold",
to_amount=q(Decimal(spent) / self.rate(gold_usd, m)), mute=False,
@@ -489,6 +500,11 @@ class Command(BaseCommand):
notes="Very old transactions are no problem.")
self.transfer(old_bank, checking, Decimal("1200.00"), self.day(-HISTORY_MONTHS, 3),
"Closing old bank account", category="Transfers")
# One receipt, split into what was bought
shop = self.tx(card, EX, Decimal("87.35"), self.day(-1, 24), "Big grocery shop",
"Groceries", ["essentials", "home"], ["Fresh Market"])
self.split(shop, ("Produce", "24.80"), ("Meat & fish", "38.15"),
("Household supplies", "16.40"), ("Snacks", "8.00"))
# Balance reconciliation: the wallet had less cash than recorded
self.tx(cash, EX, Decimal("12.40"), self.day(-2, 28), "Balance reconciliation")
@@ -511,6 +527,7 @@ class Command(BaseCommand):
description="Lunch", category=self.cats["Dining"],
)
lunch.tags.set([self.tags["work"]])
self.split(lunch, ("Meal", "11.90"), ("Tip", "2.00"))
# Rules run on transactions you create or edit
ride = TransactionRule.objects.create(
+9 -1
View File
@@ -2,12 +2,20 @@ import functools
import inspect
import procrastinate
from django.db import close_old_connections
from django.db import close_old_connections as _close_old_connections
from django.db import connection
_CONNECTION_CLEANUP_WRAPPED = "_wygiwyh_connection_cleanup_wrapped"
def close_old_connections():
# Rule dry runs call tasks directly inside a transaction they roll back;
# closing its connection there would break it. Worker jobs never run in one.
if not connection.in_atomic_block:
_close_old_connections()
def _wrap_task_with_django_connection_cleanup(task):
if getattr(task.func, _CONNECTION_CLEANUP_WRAPPED, False):
return
+21 -1
View File
@@ -10,7 +10,12 @@ from apps.accounts.models import Account
from apps.common.middleware.thread_local import delete_current_user, write_current_user
from apps.dca.models import DCAStrategy
from apps.investments.services import get_holding_performance
from apps.transactions.models import Transaction
from apps.transactions.models import (
InstallmentPlan,
QuickTransaction,
RecurringTransaction,
Transaction,
)
@override_settings(
@@ -73,6 +78,21 @@ class LoadDemoDataTests(TestCase):
self.assertNotEqual(apple.realized, 0) # partial sale
self.assertTrue(perfs["Retirement Fund"].results) # gains and losses
def test_sub_transactions_add_up(self):
self.load(date(2031, 7, 14))
owners = [
*Transaction.all_objects.filter(sub_transactions__isnull=False).distinct(),
*RecurringTransaction.all_objects.filter(sub_transactions__isnull=False).distinct(),
*QuickTransaction.objects.filter(sub_transactions__isnull=False).distinct(),
]
plans = InstallmentPlan.all_objects.filter(sub_transactions__isnull=False).distinct()
self.assertTrue(plans)
self.assertGreater(len(owners), len(plans))
for owner in [*owners, *plans]:
with self.subTest(owner=str(owner)):
amount = getattr(owner, "installment_amount", None) or owner.amount
self.assertEqual(sum(s.amount for s in owner.sub_transactions.all()), amount)
def test_running_twice_is_a_no_op(self):
self.load(date(2031, 7, 14))
count = Transaction.all_objects.count()
+16 -1
View File
@@ -1,7 +1,7 @@
from unittest.mock import patch
import procrastinate
from django.db import connection
from django.db import connection, transaction
from django.test import SimpleTestCase, TransactionTestCase
from procrastinate.testing import InMemoryConnector
@@ -87,3 +87,18 @@ class ProcrastinateConnectionRecoveryTests(TransactionTestCase):
connection.connection.close()
self.assertEqual(task.func(), 1)
def test_task_called_inside_a_transaction_keeps_its_connection(self):
"""Rule dry runs call tasks directly inside a transaction they roll back."""
def sample_task():
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
return cursor.fetchone()[0]
app, task = make_app_with_task(sample_task)
on_app_ready(app)
with transaction.atomic():
connection.close_at = 0 # obsolete, as with CONN_MAX_AGE=0
self.assertEqual(task.func(), 1)
+11
View File
@@ -61,6 +61,12 @@ class ExportForm(forms.Form):
label=_("Installment Plans"),
initial=True,
)
quick_transactions = forms.BooleanField(
required=False,
widget=forms.CheckboxInput(),
label=_("Quick Transactions"),
initial=True,
)
exchange_rates = forms.BooleanField(
required=False,
widget=forms.CheckboxInput(),
@@ -116,6 +122,7 @@ class ExportForm(forms.Form):
"tags",
"installment_plans",
"recurring_transactions",
"quick_transactions",
"exchange_rates_services",
"exchange_rates",
"bank_sync",
@@ -142,10 +149,12 @@ class RestoreForm(forms.Form):
transactions_tags = forms.FileField(required=False, label=_("Tags"))
transactions_entities = forms.FileField(required=False, label=_("Entities"))
transactions = forms.FileField(required=False, label=_("Transactions"))
sub_transactions = forms.FileField(required=False, label=_("Sub-transactions"))
installment_plans = forms.FileField(required=False, label=_("Installment Plans"))
recurring_transactions = forms.FileField(
required=False, label=_("Recurring Transactions")
)
quick_transactions = forms.FileField(required=False, label=_("Quick Transactions"))
automatic_exchange_rates = forms.FileField(
required=False, label=_("Automatic Exchange Rates")
)
@@ -180,11 +189,13 @@ class RestoreForm(forms.Form):
"accounts",
"currencies",
"transactions",
"sub_transactions",
"transactions_categories",
"transactions_entities",
"transactions_tags",
"installment_plans",
"recurring_transactions",
"quick_transactions",
"automatic_exchange_rates",
"exchange_rates",
"bank_sync_services",
@@ -1,4 +1,9 @@
from functools import reduce
from operator import or_
from django.db.models import Q
from import_export import fields, resources
from import_export.widgets import ForeignKeyWidget
from apps.accounts.models import Account
from apps.export_app.widgets.foreign_key import (
@@ -14,6 +19,8 @@ from apps.transactions.models import (
TransactionEntity,
RecurringTransaction,
InstallmentPlan,
QuickTransaction,
SubTransaction,
)
from apps.export_app.widgets.numbers import UniversalDecimalWidget
@@ -166,3 +173,106 @@ class InstallmentPlanResource(resources.ModelResource):
def dehydrate_account_owner(self, obj):
"""Export the account's owner ID for proper import matching."""
return obj.account.owner_id if obj.account else None
class AnyOwnerForeignKeyWidget(ForeignKeyWidget):
"""Finds the parent among every user's rows, soft-deleted ones included."""
def get_queryset(self, value, row, *args, **kwargs):
return self.model._base_manager.all()
class QuickTransactionResource(resources.ModelResource):
account = fields.Field(
attribute="account",
column_name="account",
widget=AllObjectsForeignKeyWidget(Account, "name"),
)
to_account = fields.Field(
attribute="to_account",
column_name="to_account",
widget=AllObjectsForeignKeyWidget(Account, "name"),
)
category = fields.Field(
attribute="category",
column_name="category",
widget=AutoCreateForeignKeyWidget(TransactionCategory, "name"),
)
tags = fields.Field(
attribute="tags",
column_name="tags",
widget=AutoCreateManyToManyWidget(TransactionTag, field="name"),
)
entities = fields.Field(
attribute="entities",
column_name="entities",
widget=AutoCreateManyToManyWidget(TransactionEntity, field="name"),
)
internal_id = EmptyStringToNoneField(
column_name="internal_id", attribute="internal_id"
)
amount = fields.Field(
attribute="amount",
column_name="amount",
widget=UniversalDecimalWidget(),
)
to_amount = fields.Field(
attribute="to_amount",
column_name="to_amount",
widget=UniversalDecimalWidget(),
)
class Meta:
model = QuickTransaction
def get_queryset(self):
return QuickTransaction.all_objects.all()
SUB_TRANSACTION_BACKUP_PARENTS = (
"transaction",
"installment_plan",
"recurring_transaction",
"quick_transaction",
)
class SubTransactionResource(resources.ModelResource):
transaction = fields.Field(
attribute="transaction",
column_name="transaction",
widget=AnyOwnerForeignKeyWidget(Transaction),
)
installment_plan = fields.Field(
attribute="installment_plan",
column_name="installment_plan",
widget=AnyOwnerForeignKeyWidget(InstallmentPlan),
)
recurring_transaction = fields.Field(
attribute="recurring_transaction",
column_name="recurring_transaction",
widget=AnyOwnerForeignKeyWidget(RecurringTransaction),
)
quick_transaction = fields.Field(
attribute="quick_transaction",
column_name="quick_transaction",
widget=AnyOwnerForeignKeyWidget(QuickTransaction),
)
amount = fields.Field(
attribute="amount",
column_name="amount",
widget=UniversalDecimalWidget(),
)
def __init__(self, parents=SUB_TRANSACTION_BACKUP_PARENTS, **kwargs):
"""`parents`: the kinds of parent being exported, whose parts go along."""
super().__init__(**kwargs)
self.parents = parents
class Meta:
model = SubTransaction
def get_queryset(self):
return SubTransaction.objects.filter(
reduce(or_, (Q(**{f"{p}__isnull": False}) for p in self.parents), Q(pk__in=[]))
)
+70 -2
View File
@@ -1,4 +1,5 @@
import io
from datetime import date
import zipfile
from decimal import Decimal
@@ -9,9 +10,21 @@ from apps.accounts.models import Account, InvestmentClass
from apps.common.middleware.thread_local import delete_current_user, write_current_user
from apps.currencies.models import Currency
from apps.export_app.resources.accounts import AccountResource, InvestmentClassResource
from apps.export_app.resources.transactions import TransactionEntityResource
from apps.export_app.resources.transactions import (
InstallmentPlanResource,
QuickTransactionResource,
SubTransactionResource,
TransactionEntityResource,
TransactionResource,
)
from apps.export_app.views import process_imports
from apps.transactions.models import TransactionEntity
from apps.transactions.models import (
InstallmentPlan,
QuickTransaction,
SubTransaction,
Transaction,
TransactionEntity,
)
class InvestmentRestoreTests(TestCase):
@@ -51,3 +64,58 @@ class InvestmentRestoreTests(TestCase):
self.assertEqual(account.investment_class.name, "Stocks")
self.assertEqual(account.investment_class.target, Decimal("60"))
self.assertEqual([e.name for e in account.income_entities.all()], ["Broker"])
class SubTransactionBackupTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(email="s@test.com", password="pw")
write_current_user(self.user)
self.addCleanup(delete_current_user)
account = Account.objects.create(
name="A", currency=Currency.objects.create(code="USD", name="USD", decimal_places=2)
)
self.transaction = Transaction.objects.create(
account=account, type="EX", date=date(2030, 1, 10), amount=5
)
self.plan = InstallmentPlan.objects.create(
account=account, type="EX", description="Laptop", number_of_installments=2,
start_date=date(2030, 1, 10), installment_amount=100,
)
SubTransaction.objects.create(transaction=self.transaction, name="Fee", amount="1.25")
SubTransaction.objects.create(transaction=self.transaction, name="Item", amount="3.75")
SubTransaction.objects.create(installment_plan=self.plan, name="Principal", amount=100)
lunch = QuickTransaction.objects.create(
name="Lunch", account=account, type="EX", amount=Decimal("13.90")
)
SubTransaction.objects.create(quick_transaction=lunch, name="Meal", amount="11.90")
SubTransaction.objects.create(quick_transaction=lunch, name="Tip", amount=2)
def _parts(self):
return sorted(
SubTransaction.objects.values_list(
"name", "transaction", "installment_plan", "quick_transaction__name", "amount"
)
)
def test_round_trip_puts_parts_back_on_their_parents(self):
before = self._parts()
backup = io.BytesIO()
with zipfile.ZipFile(backup, "w") as z:
for resource, name in (
(TransactionResource(), "transactions"),
(InstallmentPlanResource(), "installment_plans"),
(QuickTransactionResource(), "quick_transactions"),
(SubTransactionResource(), "sub_transactions"),
):
z.writestr(f"{name}.csv", resource.export().csv)
SubTransaction.objects.all().delete()
QuickTransaction.all_objects.all().delete()
backup.seek(0)
process_imports(None, {"zip_file": backup})
self.assertEqual(self._parts(), before)
def test_exports_only_the_parts_of_exported_parents(self):
dataset = SubTransactionResource(parents=["installment_plan"]).export()
self.assertEqual([row["name"] for row in dataset.dict], ["Principal"])
+28
View File
@@ -46,6 +46,8 @@ from apps.export_app.resources.transactions import (
TransactionCategoyResource,
InstallmentPlanResource,
RecurringTransactionResource,
QuickTransactionResource,
SubTransactionResource,
)
from apps.export_app.resources.users import UserResource
from apps.common.decorators.demo import disabled_on_demo
@@ -84,6 +86,9 @@ def export_form(request):
export_recurring_transactions = form.cleaned_data.get(
"recurring_transactions", False
)
export_quick_transactions = form.cleaned_data.get(
"quick_transactions", False
)
export_exchange_rates_services = form.cleaned_data.get(
"exchange_rates_services", False
@@ -123,6 +128,27 @@ def export_form(request):
exports.append(
(RecurringTransactionResource().export(), "recurring_transactions")
)
if export_quick_transactions:
exports.append(
(QuickTransactionResource().export(), "quick_transactions")
)
sub_transaction_parents = [
parent
for parent, exported in (
("transaction", export_transactions),
("installment_plan", export_installment_plans),
("recurring_transaction", export_recurring_transactions),
("quick_transaction", export_quick_transactions),
)
if exported
]
if sub_transaction_parents:
exports.append(
(
SubTransactionResource(parents=sub_transaction_parents).export(),
"sub_transactions",
)
)
if export_exchange_rates_services:
exports.append(
(ExchangeRateServiceResource().export(), "automatic_exchange_rates")
@@ -250,7 +276,9 @@ def process_imports(request, cleaned_data):
("exchange_rates", ExchangeRateResource),
("installment_plans", InstallmentPlanResource),
("recurring_transactions", RecurringTransactionResource),
("quick_transactions", QuickTransactionResource),
("transactions", TransactionResource),
("sub_transactions", SubTransactionResource),
("bank_sync_services", BankSyncServiceResource),
("bank_sync_accounts", BankSyncAccountResource),
("dca_strategies", DCAStrategyResource),
+2 -1
View File
@@ -308,6 +308,7 @@ def latest_transactions(request):
transactions = (
Transaction.objects.filter(created_at__gte=limit)
.collapse_transfers()
.prefetch_related("sub_transactions")
.order_by("-id")[:30]
)
@@ -325,7 +326,7 @@ def late_transactions(request):
now = timezone.localdate(timezone.now())
transactions = Transaction.objects.filter(
is_paid=False, date__lt=now
).collapse_transfers()
).collapse_transfers().prefetch_related("sub_transactions")
return render(
request,
+1
View File
@@ -215,6 +215,7 @@ def investment_detail(request, account_id):
"account__currency__exchange_currency",
"account__exchange_currency",
)
.prefetch_related("sub_transactions")
.order_by("-date", "-id")[:50]
)
income = []
+1
View File
@@ -93,6 +93,7 @@ def transactions_list(request, month: int, year: int):
"installment_plan",
"entities",
"dca_expense_entries",
"sub_transactions",
"dca_income_entries",
"linked_transaction__account__currency",
"linked_transaction__account__group",
+2
View File
@@ -190,6 +190,7 @@ class UpdateOrCreateTransactionRuleActionForm(forms.ModelForm):
"set_date": _("Date"),
"set_reference_date": _("Reference Date"),
"set_amount": _("Amount"),
"set_sub_transactions": _("Sub-transactions"),
"set_description": _("Description"),
"set_tags": _("Tags"),
"set_entities": _("Entities"),
@@ -367,6 +368,7 @@ class UpdateOrCreateTransactionRuleActionForm(forms.ModelForm):
Field("set_reference_date", rows=1),
Field("set_description", rows=1),
Field("set_amount", rows=1),
Field("set_sub_transactions", rows=1),
Field("set_category", rows=1),
Field("set_tags", rows=1),
Field("set_notes", rows=1),
@@ -0,0 +1,23 @@
# Generated by Django 5.2.17 on 2026-11-14 03:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rules', '0018_transactionrule_order'),
]
operations = [
migrations.AddField(
model_name='updateorcreatetransactionruleaction',
name='set_sub_transactions',
field=models.TextField(blank=True, verbose_name='Sub-transactions'),
),
migrations.AlterField(
model_name='transactionruleaction',
name='field',
field=models.CharField(choices=[('account', 'Account'), ('type', 'Type'), ('is_paid', 'Paid'), ('date', 'Date'), ('reference_date', 'Reference Date'), ('mute', 'Mute'), ('amount', 'Amount'), ('sub_transactions', 'Sub-transactions'), ('description', 'Description'), ('notes', 'Notes'), ('category', 'Category'), ('tags', 'Tags'), ('entities', 'Entities'), ('internal_nome', 'Internal Note'), ('internal_id', 'Internal ID')], max_length=50, verbose_name='Field'),
),
]
+5
View File
@@ -39,6 +39,7 @@ class TransactionRuleAction(models.Model):
reference_date = "reference_date", _("Reference Date")
mute = "mute", _("Mute")
amount = "amount", _("Amount")
sub_transactions = "sub_transactions", _("Sub-transactions")
description = "description", _("Description")
notes = "notes", _("Notes")
category = "category", _("Category")
@@ -315,6 +316,10 @@ class UpdateOrCreateTransactionRuleAction(models.Model):
verbose_name=_("Tags"),
blank=True,
)
set_sub_transactions = models.TextField(
verbose_name=_("Sub-transactions"),
blank=True,
)
set_mute = models.TextField(
verbose_name=_("Mute"),
blank=True,
+94 -6
View File
@@ -17,12 +17,14 @@ from procrastinate.contrib.django import app
from simpleeval import EvalWithCompoundTypes
from apps.accounts.models import Account
from apps.common.functions.decimals import truncate_decimal
from apps.common.middleware.thread_local import write_current_user, delete_current_user
from apps.rules.models import (
TransactionRule,
TransactionRuleAction,
)
from apps.transactions.models import (
SubTransaction,
Transaction,
TransactionCategory,
TransactionTag,
@@ -32,6 +34,39 @@ from apps.rules.utils import transactions
logger = logging.getLogger(__name__)
SUB_TRANSACTIONS_SHAPE = (
"Sub-transactions must be a list like [{'name': 'Fee', 'amount': 1.5}, ...]"
)
def build_sub_transactions(transaction: Transaction, value) -> list[SubTransaction]:
"""Validated sub-transactions for `transaction` from a rule expression's result."""
if not isinstance(value, (list, tuple)):
raise ValueError(SUB_TRANSACTIONS_SHAPE)
places = transaction.account.currency.decimal_places
subs = []
for item in value:
if not isinstance(item, dict) or item.get("amount") is None:
raise ValueError(SUB_TRANSACTIONS_SHAPE)
sub = SubTransaction(
transaction=transaction,
name=str(item.get("name") or "").strip(),
amount=truncate_decimal(
value=Decimal(str(item["amount"])), decimal_places=places
),
)
# the transaction may not be saved yet, so its link isn't checked here
sub.full_clean(exclude=["transaction"], validate_constraints=False)
subs.append(sub)
return subs
def _snapshot(transaction: Transaction) -> Transaction:
"""A copy to show in dry-run results, as the transaction is right now."""
copy = transaction.deepcopy()
copy.copy_sub_transactions_from(transaction)
return copy
class DryRunResults:
def __init__(self, dry_run: bool):
@@ -49,7 +84,7 @@ class DryRunResults:
if not self.dry_run:
return
if isinstance(instance, Transaction):
instance = instance.deepcopy()
instance = _snapshot(instance)
elif isinstance(instance, dict):
instance = deepcopy(instance)
@@ -65,7 +100,7 @@ class DryRunResults:
if not self.dry_run:
return
if isinstance(instance, Transaction):
instance = instance.deepcopy()
instance = _snapshot(instance)
elif isinstance(instance, dict):
instance = deepcopy(instance)
@@ -95,7 +130,7 @@ class DryRunResults:
return
if isinstance(end_instance, Transaction):
end_instance = end_instance.deepcopy()
end_instance = _snapshot(end_instance)
elif isinstance(end_instance, dict):
end_instance = deepcopy(end_instance)
@@ -201,6 +236,14 @@ def check_for_transaction_rules(
f"{prefix}entities_ids": (
[x.id for x in transaction.entities.all()] if transaction.id else []
),
f"{prefix}sub_transactions": (
[
{"name": s.name, "amount": s.amount}
for s in transaction.sub_transactions.all()
]
if transaction.id
else []
),
f"{prefix}is_expense": transaction.type == Transaction.Type.EXPENSE,
f"{prefix}is_income": transaction.type == Transaction.Type.INCOME,
f"{prefix}is_paid": transaction.is_paid,
@@ -250,6 +293,10 @@ def check_for_transaction_rules(
f"{prefix}entities_ids": [
x[0] for x in transaction.get("entities", [])
],
f"{prefix}sub_transactions": [
{"name": s["name"], "amount": Decimal(s["amount"])}
for s in transaction.get("sub_transactions", [])
],
f"{prefix}is_expense": transaction.get("type")
== Transaction.Type.EXPENSE,
f"{prefix}is_income": transaction.get("type")
@@ -274,6 +321,22 @@ def check_for_transaction_rules(
f"{prefix}installment_total": transaction.get("installment_total"),
}
def _evaluate_sub_transactions(transaction, value):
"""The parts an expression's `value` gives `transaction`, with its amount set
to their sum, or None for a transfer, which can't have any."""
if transaction.linked_transaction_id:
_log("Skipped: transfers can't have sub-transactions")
return None
subs = build_sub_transactions(transaction, value)
if subs:
transaction.amount = sum(s.amount for s in subs)
_log(f"Sub-transactions will be set as: {[(s.name, s.amount) for s in subs]}")
return subs
def _save_sub_transactions(transaction, subs):
transaction.sub_transactions.all().delete()
SubTransaction.objects.bulk_create(subs)
def _process_update_or_create_transaction_action(processed_action):
"""Helper to process a single linked transaction action"""
@@ -295,7 +358,7 @@ def check_for_transaction_rules(
existing = True
if dry_run:
starting_instance = transaction.deepcopy()
starting_instance = _snapshot(transaction)
_log("Found at least one matching transaction, using latest:")
_log("{}".format(pformat(model_to_dict(transaction))))
@@ -348,7 +411,15 @@ def check_for_transaction_rules(
processed_action.set_reference_date
)
if processed_action.set_amount:
subs = None
if processed_action.set_sub_transactions:
subs = _evaluate_sub_transactions(
transaction, simple.eval(processed_action.set_sub_transactions)
)
# A transaction with parts gets its amount from them
has_parts = bool(subs) if subs is not None else transaction.has_sub_transactions
if processed_action.set_amount and not has_parts:
transaction.amount = simple.eval(processed_action.set_amount)
if processed_action.set_description:
@@ -383,6 +454,8 @@ def check_for_transaction_rules(
)
)
transaction.save()
if subs is not None:
_save_sub_transactions(transaction, subs)
# Handle M2M fields after save
tags = []
@@ -441,7 +514,10 @@ def check_for_transaction_rules(
dry_run_results.header("edit_transaction", action=processed_action)
field = processed_action.field
original_value = getattr(transaction, field)
if field == TransactionRuleAction.Field.sub_transactions:
original_value = list(transaction.sub_transactions.values("name", "amount"))
else:
original_value = getattr(transaction, field)
new_value = simple.eval(processed_action.value)
tags = []
@@ -518,6 +594,18 @@ def check_for_transaction_rules(
transaction.entities.add(entity)
entities.append(entity)
elif field == TransactionRuleAction.Field.sub_transactions:
subs = _evaluate_sub_transactions(transaction, new_value)
if subs is not None:
_save_sub_transactions(transaction, subs)
new_value = ", ".join(f"{s.name}: {s.amount}" for s in subs) or "[]"
elif (
field == TransactionRuleAction.Field.amount
and transaction.has_sub_transactions
):
_log("Skipped: the amount is the sum of the transaction's sub-transactions")
else:
setattr(
transaction,
+108 -2
View File
@@ -6,10 +6,15 @@ from django.contrib.auth import get_user_model
from django.test import TransactionTestCase
from apps.accounts.models import Account
from apps.common.middleware.thread_local import write_current_user
from apps.currencies.models import Currency
from apps.rules.models import TransactionRule, UpdateOrCreateTransactionRuleAction
from apps.rules.models import (
TransactionRule,
TransactionRuleAction,
UpdateOrCreateTransactionRuleAction,
)
from apps.rules.tasks import check_for_transaction_rules
from apps.transactions.models import Transaction
from apps.transactions.models import SubTransaction, Transaction
def run_check_for_transaction_rules_without_worker_wrapper(**kwargs):
@@ -122,3 +127,104 @@ class CheckForTransactionRulesTests(TransactionTestCase):
generated_transaction = Transaction.objects.get(description="Muted copy")
self.assertTrue(generated_transaction.mute)
self.assertFalse(generated_transaction.is_paid)
@patch("apps.rules.signals.check_for_transaction_rules.defer")
def test_edit_amount_skips_transactions_with_sub_transactions(self, mock_defer):
rule = TransactionRule.objects.create(
active=True, on_update=True, name="Set amount", trigger="True", owner=self.user
)
TransactionRuleAction.objects.create(rule=rule, field="amount", value="99")
TransactionRuleAction.objects.create(rule=rule, field="description", value="'Ruled'")
amounts = {}
for parts in ([], [Decimal("4"), Decimal("6")]):
transaction = Transaction.objects.create(
account=self.account, type=Transaction.Type.EXPENSE, amount=sum(parts) or 1,
date=date(2026, 5, 4), owner=self.user,
)
for amount in parts:
SubTransaction.objects.create(transaction=transaction, name="Part", amount=amount)
run_check_for_transaction_rules_without_worker_wrapper(
instance_id=transaction.id, user_id=self.user.id, signal="transaction_updated"
)
transaction.refresh_from_db()
self.assertEqual(transaction.description, "Ruled")
amounts[len(parts)] = transaction.amount
self.assertEqual(amounts, {0: Decimal("99"), 2: Decimal("10")})
class SubTransactionRuleTests(TransactionTestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(email="subs@example.com", password="x")
currency = Currency.objects.create(code="USD", name="US Dollar", decimal_places=2)
self.account = Account.objects.create(name="Main", currency=currency, owner=self.user)
self.rule = TransactionRule.objects.create(
active=True, on_update=True, name="Parts", trigger="True", owner=self.user
)
def _transaction(self, *parts, amount=None):
transaction = Transaction.objects.create(
account=self.account, type=Transaction.Type.EXPENSE, date=date(2026, 5, 4),
amount=amount if amount is not None else sum(a for _, a in parts), owner=self.user,
)
for name, part in parts:
SubTransaction.objects.create(transaction=transaction, name=name, amount=part)
return transaction
def _run(self, transaction):
with patch("apps.rules.signals.check_for_transaction_rules.defer"):
run_check_for_transaction_rules_without_worker_wrapper(
instance_id=transaction.id, user_id=self.user.id, signal="transaction_updated"
)
transaction.refresh_from_db()
return transaction.amount, list(transaction.sub_transactions.values_list("name", "amount"))
def _edit(self, expression):
TransactionRuleAction.objects.create(rule=self.rule, field="sub_transactions", value=expression)
def test_edit_action_adds_changes_and_deletes_parts(self):
self._edit(
'[{"name": s["name"], "amount": s["amount"] * 2} for s in sub_transactions'
' if s["name"] != "Tip"] + [{"name": "Fee", "amount": decimal("0.50")}]'
)
result = self._run(self._transaction(("Meal", Decimal("10")), ("Tip", Decimal("2"))))
self.assertEqual(result, (Decimal("20.50"), [("Meal", Decimal("20")), ("Fee", Decimal("0.5"))]))
def test_edit_action_splits_a_plain_transaction_and_clearing_keeps_amount(self):
self._edit('[{"name": "Principal", "amount": amount - 5}, {"name": "Fee", "amount": 5}]')
self.assertEqual(
self._run(self._transaction(amount=Decimal("100"))),
(Decimal("100"), [("Principal", Decimal("95")), ("Fee", Decimal("5"))]),
)
self.rule.transaction_actions.update(value="[]")
self.assertEqual(self._run(self._transaction(("A", Decimal("3")))), (Decimal("3"), []))
def test_invalid_parts_leave_the_transaction_alone(self):
transaction = self._transaction(("A", Decimal("3")))
for expression in ('"Fee"', '[{"name": "Fee"}]', '[{"name": "", "amount": 1}]',
'[{"name": "Refund", "amount": -1}]'):
with self.subTest(expression=expression):
self.rule.transaction_actions.all().delete()
self._edit(expression)
self.assertEqual(self._run(transaction), (Decimal("3"), [("A", Decimal("3"))]))
def test_transfers_are_skipped(self):
out, inc = self._transaction(amount=Decimal("5")), self._transaction(amount=Decimal("5"))
write_current_user(self.user)
with patch("apps.rules.signals.check_for_transaction_rules.defer"):
Transaction.objects.filter(pk=out.pk).update(linked_transaction=inc)
self._edit('[{"name": "Fee", "amount": 1}]')
self.assertEqual(self._run(out), (Decimal("5"), []))
def test_update_or_create_creates_a_transaction_from_its_parts(self):
UpdateOrCreateTransactionRuleAction.objects.create(
rule=self.rule, set_account="account_id", set_type="'EX'", set_date="date",
set_description="'Copy'", set_amount="999",
set_sub_transactions="sub_transactions + [{'name': 'Fee', 'amount': 1}]",
)
self._run(self._transaction(("A", Decimal("3"))))
copy = Transaction.objects.get(description="Copy")
self.assertEqual(copy.amount, Decimal("4"))
self.assertEqual(
list(copy.sub_transactions.values_list("name", "amount")),
[("A", Decimal("3")), ("Fee", Decimal("1"))],
)
+4
View File
@@ -86,6 +86,10 @@ def serialize_transaction(sender: Transaction, deleted: bool):
"notes": sender.notes,
"tags": list(sender.tags.values_list("id", "name")),
"entities": list(sender.entities.values_list("id", "name")),
"sub_transactions": [
{"name": name, "amount": str(amount)}
for name, amount in sender.sub_transactions.values_list("name", "amount")
],
"deleted": deleted,
"internal_note": sender.internal_note,
"internal_id": sender.internal_id,
+117 -16
View File
@@ -8,13 +8,14 @@ from apps.common.widgets.decimal import ArbitraryDecimalDisplayNumberInput
from apps.common.widgets.tom_select import TomSelectMultiple
from apps.currencies.models import Currency
from apps.transactions.models import (
SubTransaction,
Transaction,
TransactionCategory,
TransactionEntity,
TransactionTag,
)
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Column, Field, Layout, Row
from crispy_forms.layout import HTML, Column, Div, Field, Layout, Row
from dateutil.relativedelta import relativedelta
from django import forms
from django.db.models import Q
@@ -34,11 +35,26 @@ MUTE_STATUS_CHOICES = (
def content_filter(queryset, name, value):
queryset = queryset.filter(
Q(description__icontains=value) | Q(notes__icontains=value)
Q(description__icontains=value)
| Q(notes__icontains=value)
# a subquery, so a transaction with several matching parts isn't listed twice
| Q(pk__in=SubTransaction.objects.filter(name__icontains=value).values("transaction"))
)
return queryset
def exclude_matching(positive_filter):
"""Turn a positive filter method into one that drops the rows it would keep."""
def method(queryset, name, value):
if not value:
return queryset
matching = positive_filter(queryset, name, value)
return queryset.exclude(pk__in=matching.values("pk"))
return method
class MonthYearFilter(Filter):
field_class = MonthYearFormField
@@ -134,6 +150,42 @@ class TransactionsFilter(django_filters.FilterSet):
lookup_expr="lte",
label=_("Amount max"),
)
exclude_description = django_filters.CharFilter(
label=_("Content"),
method=exclude_matching(content_filter),
widget=forms.TextInput(attrs={"type": "search"}),
)
exclude_account = django_filters.ModelMultipleChoiceFilter(
field_name="account__name",
queryset=Account.objects.all(),
to_field_name="name",
exclude=True,
label=_("Accounts"),
widget=TomSelectMultiple(checkboxes=True, remove_button=True, group_by="group"),
)
exclude_currency = django_filters.ModelMultipleChoiceFilter(
field_name="account__currency",
queryset=Currency.objects.all(),
to_field_name="id",
exclude=True,
label=_("Currencies"),
widget=TomSelectMultiple(checkboxes=True, remove_button=True),
)
exclude_category = django_filters.MultipleChoiceFilter(
label=_("Categories"),
widget=TomSelectMultiple(checkboxes=True, remove_button=True),
method="filter_exclude_category",
)
exclude_tags = django_filters.MultipleChoiceFilter(
label=_("Tags"),
widget=TomSelectMultiple(checkboxes=True, remove_button=True),
method="filter_exclude_tags",
)
exclude_entities = django_filters.MultipleChoiceFilter(
label=_("Entities"),
widget=TomSelectMultiple(checkboxes=True, remove_button=True),
method="filter_exclude_entities",
)
class Meta:
model = Transaction
@@ -188,21 +240,53 @@ class TransactionsFilter(django_filters.FilterSet):
"mute_status",
template="transactions/widgets/transaction_type_filter_buttons.html",
),
Field("description"),
Row(Column("date_start"), Column("date_end")),
Row(
Column("reference_date_start"),
Column("reference_date_end"),
Div(
HTML(
'<div role="tablist" class="tabs tabs-border mb-2">'
'<button type="button" role="tab" class="tab" '
":class=\"{'tab-active': tab === 'include'}\" "
":aria-selected=\"tab === 'include'\" "
"@click=\"tab = 'include'\">"
f"{_('Include')}</button>"
'<button type="button" role="tab" class="tab" '
":class=\"{'tab-active': tab === 'exclude'}\" "
":aria-selected=\"tab === 'exclude'\" "
"@click=\"tab = 'exclude'\">"
f"{_('Exclude')}</button>"
"</div>"
),
Div(
Field("description"),
Row(Column("date_start"), Column("date_end")),
Row(
Column("reference_date_start"),
Column("reference_date_end"),
),
Row(
Column("from_amount"),
Column("to_amount"),
),
Field("account", size=1),
Field("currency", size=1),
Field("category", size=1),
Field("tags", size=1),
Field("entities", size=1),
role="tabpanel",
x_show="tab === 'include'",
),
Div(
Field("exclude_description"),
Field("exclude_account", size=1),
Field("exclude_currency", size=1),
Field("exclude_category", size=1),
Field("exclude_tags", size=1),
Field("exclude_entities", size=1),
role="tabpanel",
x_show="tab === 'exclude'",
x_cloak="",
),
x_data="{ tab: 'include' }",
),
Row(
Column("from_amount"),
Column("to_amount"),
),
Field("account", size=1),
Field("currency", size=1),
Field("category", size=1),
Field("tags", size=1),
Field("entities", size=1),
)
self.form.fields["to_amount"].widget = ArbitraryDecimalDisplayNumberInput()
@@ -211,6 +295,7 @@ class TransactionsFilter(django_filters.FilterSet):
self.form.fields["date_end"].widget = AirDatePickerInput()
self.form.fields["account"].queryset = Account.objects.all()
self.form.fields["exclude_account"].queryset = Account.objects.all()
category_choices = list(
TransactionCategory.objects.values_list("name", "name").order_by("name")
)
@@ -219,11 +304,15 @@ class TransactionsFilter(django_filters.FilterSet):
("uncategorized", _("Uncategorized")),
]
self.form.fields["category"].choices = custom_choices + category_choices
self.form.fields["exclude_category"].choices = (
custom_choices + category_choices
)
tag_choices = list(
TransactionTag.objects.values_list("name", "name").order_by("name")
)
custom_tag_choices = [("any", _("Tagged")), ("untagged", _("Untagged"))]
self.form.fields["tags"].choices = custom_tag_choices + tag_choices
self.form.fields["exclude_tags"].choices = custom_tag_choices + tag_choices
entity_choices = list(
TransactionEntity.objects.values_list("name", "name").order_by("name")
)
@@ -232,6 +321,9 @@ class TransactionsFilter(django_filters.FilterSet):
("no_entity", _("No entity")),
]
self.form.fields["entities"].choices = custom_entity_choices + entity_choices
self.form.fields["exclude_entities"].choices = (
custom_entity_choices + entity_choices
)
@property
def has_active_filters(self):
@@ -363,6 +455,15 @@ class TransactionsFilter(django_filters.FilterSet):
return queryset
def filter_exclude_category(self, queryset, name, value):
return exclude_matching(self.filter_category)(queryset, name, value)
def filter_exclude_tags(self, queryset, name, value):
return exclude_matching(self.filter_tags)(queryset, name, value)
def filter_exclude_entities(self, queryset, name, value):
return exclude_matching(self.filter_entities)(queryset, name, value)
@staticmethod
def filter_mute_status(queryset, name, value):
from apps.common.middleware.thread_local import get_current_user
+95 -4
View File
@@ -17,6 +17,7 @@ from apps.transactions.models import (
TransactionAttachment,
QuickTransaction,
RecurringTransaction,
SubTransaction,
Transaction,
TransactionCategory,
TransactionEntity,
@@ -54,7 +55,89 @@ class MultipleFileField(forms.FileField):
return []
class TransactionForm(forms.ModelForm):
class SubTransactionForm(forms.ModelForm):
class Meta:
model = SubTransaction
fields = ["name", "amount"]
widgets = {
"name": forms.TextInput(
attrs={"class": "input join-item flex-1", "placeholder": _("Name")}
),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Built per request so the mask uses the user's number format
self.fields["amount"].widget = ArbitraryDecimalDisplayNumberInput(
attrs={
"class": "input join-item w-2/5",
"inputmode": "decimal",
"placeholder": _("Amount"),
}
)
class SubTransactionsFormMixin:
"""Adds sub-transactions to a transaction or template form; while there are any,
the amount field is their sum. Transfers don't take them.
Rendered by transactions/widgets/sub_transactions.html, placed after the amount.
"""
sub_amount_field = "amount"
def __init__(self, *args, sub_transactions_initial=None, **kwargs):
super().__init__(*args, **kwargs)
data = self.data if self.is_bound else None
if data is not None and "sub-TOTAL_FORMS" not in data:
# Posts without the formset (e.g. shortcuts to /add/) leave sub-transactions alone
data = {"sub-TOTAL_FORMS": "0", "sub-INITIAL_FORMS": "0"}
initial = sub_transactions_initial or []
self.sub_transactions = forms.inlineformset_factory(
type(self.instance),
SubTransaction,
form=SubTransactionForm,
extra=len(initial),
can_delete=True,
)(data, instance=self.instance, prefix="sub", initial=initial)
# With sub-transactions the amount is their sum, see clean()
self.fields[self.sub_amount_field].required = False
def _takes_sub_transactions(self):
return self.cleaned_data.get("type") != "TR"
def clean(self):
cleaned_data = super().clean()
field = self.sub_amount_field
if self._takes_sub_transactions() and self.sub_transactions.is_valid():
amounts = [
f.cleaned_data["amount"]
for f in self.sub_transactions.forms
if f.cleaned_data and not f.cleaned_data.get("DELETE")
]
if amounts:
cleaned_data[field] = sum(amounts)
if cleaned_data.get(field) is None and field not in self.errors:
self.add_error(field, self.fields[field].error_messages["required"])
return cleaned_data
def is_valid(self):
return super().is_valid() and (
not self._takes_sub_transactions() or self.sub_transactions.is_valid()
)
def save(self, *args, **kwargs):
with db_transaction.atomic():
instance = super().save(*args, **kwargs)
if self._takes_sub_transactions():
self.sub_transactions.instance = instance
self.sub_transactions.save()
else:
instance.sub_transactions.all().delete()
return instance
class TransactionForm(SubTransactionsFormMixin, forms.ModelForm):
category = DynamicModelChoiceField(
create_field="name",
model=TransactionCategory,
@@ -164,6 +247,7 @@ class TransactionForm(forms.ModelForm):
),
"description",
Field("amount", inputmode="decimal"),
HTML('{% include "transactions/widgets/sub_transactions.html" %}'),
Row(
Column("category"),
Column("tags"),
@@ -187,6 +271,7 @@ class TransactionForm(forms.ModelForm):
),
"description",
Field("amount", inputmode="decimal"),
HTML('{% include "transactions/widgets/sub_transactions.html" %}'),
Accordion(
AccordionGroup(
_("More"),
@@ -322,7 +407,7 @@ def _type_aware(form, *layout):
)
class QuickTransactionForm(forms.ModelForm):
class QuickTransactionForm(SubTransactionsFormMixin, forms.ModelForm):
category = DynamicModelChoiceField(
create_field="name",
model=TransactionCategory,
@@ -432,6 +517,7 @@ class QuickTransactionForm(forms.ModelForm):
),
"description",
Field("amount", inputmode="decimal"),
HTML('{% include "transactions/widgets/sub_transactions.html" %}'),
_transfer_fields(self),
Row(
Column("category"),
@@ -833,7 +919,9 @@ class TransferForm(forms.Form):
return from_transaction, to_transaction
class InstallmentPlanForm(forms.ModelForm):
class InstallmentPlanForm(SubTransactionsFormMixin, forms.ModelForm):
sub_amount_field = "installment_amount"
account = forms.ModelChoiceField(
queryset=Account.objects.filter(is_archived=False),
label=_("Account"),
@@ -956,6 +1044,7 @@ class InstallmentPlanForm(forms.ModelForm):
Column("recurrence", css_class="col-span-12 md:col-span-4"),
),
"installment_amount",
HTML('{% include "transactions/widgets/sub_transactions.html" %}'),
Row(
Column("category"),
Column("tags"),
@@ -989,6 +1078,7 @@ class InstallmentPlanForm(forms.ModelForm):
# Take the amount set on the form, even if already paid
source_transaction.amount = instance.installment_amount
source_transaction.save()
source_transaction.copy_sub_transactions_from(instance)
instance.update_transactions()
elif is_new:
instance.create_transactions()
@@ -1085,7 +1175,7 @@ class TransactionCategoryForm(forms.ModelForm):
)
class RecurringTransactionForm(forms.ModelForm):
class RecurringTransactionForm(SubTransactionsFormMixin, forms.ModelForm):
account = forms.ModelChoiceField(
queryset=Account.objects.filter(is_archived=False),
label=_("Account"),
@@ -1209,6 +1299,7 @@ class RecurringTransactionForm(forms.ModelForm):
"description",
Switch("add_description_to_transaction"),
"amount",
HTML('{% include "transactions/widgets/sub_transactions.html" %}'),
_transfer_fields(self),
Row(
Column("category"),
@@ -0,0 +1,34 @@
# Generated by Django 5.2.17 on 2026-11-13 22:22
import apps.transactions.validators
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('transactions', '0052_transfer_templates'),
]
operations = [
migrations.CreateModel(
name='SubTransaction',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, verbose_name='Name')),
('amount', models.DecimalField(decimal_places=30, max_digits=42, validators=[apps.transactions.validators.validate_non_negative, apps.transactions.validators.validate_decimal_places], verbose_name='Amount')),
('installment_plan', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sub_transactions', to='transactions.installmentplan')),
('quick_transaction', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sub_transactions', to='transactions.quicktransaction')),
('recurring_transaction', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sub_transactions', to='transactions.recurringtransaction')),
('transaction', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sub_transactions', to='transactions.transaction', verbose_name='Transaction')),
],
options={
'verbose_name': 'Sub-transaction',
'verbose_name_plural': 'Sub-transactions',
'db_table': 'sub_transactions',
'ordering': ['id'],
'constraints': [models.CheckConstraint(condition=models.Q(models.Q(('installment_plan__isnull', True), ('quick_transaction__isnull', True), ('recurring_transaction__isnull', True), ('transaction__isnull', False)), models.Q(('installment_plan__isnull', True), ('quick_transaction__isnull', True), ('recurring_transaction__isnull', False), ('transaction__isnull', True)), models.Q(('installment_plan__isnull', False), ('quick_transaction__isnull', True), ('recurring_transaction__isnull', True), ('transaction__isnull', True)), models.Q(('installment_plan__isnull', True), ('quick_transaction__isnull', False), ('recurring_transaction__isnull', True), ('transaction__isnull', True)), _connector='OR'), name='sub_transaction_has_one_parent')],
},
),
]
+175 -28
View File
@@ -1,6 +1,8 @@
import calendar
import decimal
import functools
import logging
import operator
import uuid
from copy import deepcopy
from pathlib import Path
@@ -447,9 +449,10 @@ class Transaction(OwnedObject):
if isinstance(self.amount, (str, int, float)):
self.amount = decimal.Decimal(str(self.amount))
self.amount = truncate_decimal(
value=self.amount, decimal_places=account.currency.decimal_places
)
if self.amount is not None: # missing amount is reported by field validation
self.amount = truncate_decimal(
value=self.amount, decimal_places=account.currency.decimal_places
)
# Normalize reference_date
if self.reference_date:
@@ -575,6 +578,24 @@ class Transaction(OwnedObject):
def hard_delete(self, *args, **kwargs):
super().delete(*args, **kwargs)
@property
def has_sub_transactions(self):
return bool(self.pk) and self.sub_transactions.exists()
@property
def saved_sub_transactions(self):
"""Sub-transactions, or none for an unsaved preview (which can't query them)."""
return self.sub_transactions.all() if self.pk else []
def copy_sub_transactions_from(self, source):
"""Makes this transaction's sub-transactions copies of ``source``'s (a
transaction or a template that generates them)."""
self.sub_transactions.all().delete()
SubTransaction.objects.bulk_create(
SubTransaction(transaction=self, name=sub.name, amount=sub.amount)
for sub in source.sub_transactions.all()
)
def exchanged_amount(self):
return self._exchanged_to(
self.account.exchange_currency or self.account.currency.exchange_currency
@@ -661,6 +682,81 @@ class Transaction(OwnedObject):
return new_obj
SUB_TRANSACTION_PARENTS = (
"transaction",
"recurring_transaction",
"installment_plan",
"quick_transaction",
)
class SubTransaction(models.Model):
"""A named part of a transaction, or of a template that generates them; when
present, the parts add up to its amount. Exactly one parent is set.
Soft deletion follows the parent: sub-transactions are only reached through it.
"""
transaction = models.ForeignKey(
Transaction,
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="sub_transactions",
verbose_name=_("Transaction"),
)
recurring_transaction = models.ForeignKey(
"RecurringTransaction",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="sub_transactions",
)
installment_plan = models.ForeignKey(
"InstallmentPlan",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="sub_transactions",
)
quick_transaction = models.ForeignKey(
"QuickTransaction",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="sub_transactions",
)
name = models.CharField(max_length=255, verbose_name=_("Name"))
amount = models.DecimalField(
max_digits=42,
decimal_places=30,
verbose_name=_("Amount"),
validators=[validate_non_negative, validate_decimal_places],
)
class Meta:
verbose_name = _("Sub-transaction")
verbose_name_plural = _("Sub-transactions")
db_table = "sub_transactions"
ordering = ["id"]
constraints = [
models.CheckConstraint(
# One of: only "transaction" set, only "recurring_transaction" set, ...
condition=functools.reduce(
operator.or_,
(
Q(**{f"{p}__isnull": p != parent for p in SUB_TRANSACTION_PARENTS})
for parent in SUB_TRANSACTION_PARENTS
),
),
name="sub_transaction_has_one_parent",
)
]
def __str__(self):
return self.name
class TransactionAttachment(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
transaction = models.ForeignKey(
@@ -858,6 +954,7 @@ class InstallmentPlan(models.Model):
)
new_transaction.tags.set(self.tags.all())
new_transaction.entities.set(self.entities.all())
new_transaction.copy_sub_transactions_from(self)
@transaction.atomic
def update_transactions(self):
@@ -899,6 +996,7 @@ class InstallmentPlan(models.Model):
not existing_transaction.is_paid
): # Don't update value for paid transactions
existing_transaction.amount = self.installment_amount
existing_transaction.copy_sub_transactions_from(self)
existing_transaction.save()
@@ -925,6 +1023,7 @@ class InstallmentPlan(models.Model):
)
new_transaction.tags.set(self.tags.all())
new_transaction.entities.set(self.entities.all())
new_transaction.copy_sub_transactions_from(self)
# Remove any extra transactions that are no longer part of the plan
self.transactions.filter(
@@ -1130,6 +1229,7 @@ class RecurringTransaction(TransferTemplate):
# different one, and the scoped default manager would hide private rows.
created_transaction.tags.set(self.tags(manager="all_objects").all())
created_transaction.entities.set(self.entities(manager="all_objects").all())
created_transaction.copy_sub_transactions_from(self)
self.complete_transfer(created_transaction)
def adopt_transaction(self, existing_transaction, date, reference_date):
@@ -1172,6 +1272,7 @@ class RecurringTransaction(TransferTemplate):
existing_transaction.save()
existing_transaction.tags.set(self.tags(manager="all_objects").all())
existing_transaction.entities.set(self.entities(manager="all_objects").all())
existing_transaction.copy_sub_transactions_from(self)
def get_recurrence_delta(self):
if self.recurrence_type == self.RecurrenceType.DAY:
@@ -1261,36 +1362,82 @@ class RecurringTransaction(TransferTemplate):
"""
Updates all unpaid transactions associated with this RecurringTransaction.
Only unpaid transactions (`is_paid=False`) are modified. Updates fields like
amount, description, category, notes, and many-to-many relationships (tags, entities).
Only unpaid transactions (`is_paid=False`) are modified. They keep their dates
and take the account, type, amount, description, category, notes, tags and
entities of the recurrence; a transfer's "to" side takes the "to" account and
amount. Turning the recurrence into a transfer adds the missing "to" sides,
and turning it into an income or expense removes them.
"""
unpaid_transactions = self.transactions.filter(is_paid=False)
unpaid_transactions = list(
self.transactions.filter(is_paid=False).select_related(
"linked_transaction"
)
)
to_side_ids = {
existing_transaction.pk
for existing_transaction in unpaid_transactions
if self._is_to_side(existing_transaction)
}
for existing_transaction in unpaid_transactions:
# Update fields based on RecurringTransaction
is_to_side = (
existing_transaction.linked_transaction_id
and existing_transaction.type == Transaction.Type.INCOME
)
existing_transaction.amount = (
self.to_amount or self.amount if is_to_side else self.amount
)
existing_transaction.description = (
self.description if self.add_description_to_transaction else ""
)
existing_transaction.category = self.category
existing_transaction.notes = (
self.notes if self.add_notes_to_transaction else ""
)
if existing_transaction.pk in to_side_ids:
if self.is_transfer:
self._apply_to(
existing_transaction,
self.to_account,
Transaction.Type.INCOME,
self.to_amount or self.amount,
existing_transaction.date,
existing_transaction.reference_date,
)
# Otherwise its unpaid "from" side removes it below
continue
# Update many-to-many relationships (see create_transaction)
existing_transaction.tags.set(self.tags(manager="all_objects").all())
existing_transaction.entities.set(
self.entities(manager="all_objects").all()
)
if (
not self.is_transfer
and existing_transaction.linked_transaction_id in to_side_ids
):
to_side = existing_transaction.linked_transaction
existing_transaction.linked_transaction = None
to_side.linked_transaction = None
to_side.delete(_with_partner=False)
# Save updated transaction
existing_transaction.save()
partner = existing_transaction.linked_transaction
if (
partner
and partner.recurring_transaction_id != self.pk
and (
{self.transaction_type, partner.type}
!= {Transaction.Type.INCOME, Transaction.Type.EXPENSE}
or self.account_id == partner.account_id
)
):
# A link made elsewhere (e.g. a DCA entry) that the new type or account
# would break: unlink it and keep the partner
Transaction.all_objects.filter(pk=partner.pk).update(
linked_transaction=None
)
existing_transaction.linked_transaction = None
self._apply_to(
existing_transaction,
self.account,
self.transaction_type,
self.amount,
existing_transaction.date,
existing_transaction.reference_date,
)
if not existing_transaction.linked_transaction_id:
self.complete_transfer(existing_transaction)
def _is_to_side(self, existing_transaction):
"""Whether a transaction is the "to" side of a transfer this generated."""
return bool(
existing_transaction.linked_transaction_id
and existing_transaction.type == Transaction.Type.INCOME
and existing_transaction.linked_transaction.recurring_transaction_id
== self.pk
)
def delete_unpaid_transactions(self):
"""
@@ -0,0 +1,71 @@
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from apps.accounts.models import Account
from apps.currencies.models import Currency
from apps.transactions.models import Transaction, TransactionCategory, TransactionTag
@override_settings(
STORAGES={
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
"staticfiles": {
"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"
},
},
WHITENOISE_AUTOREFRESH=True,
)
class ExcludeFilterTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
email="exclude@test.com", password="pass"
)
self.client.force_login(self.user)
currency = Currency.objects.create(code="BRL", name="Real", decimal_places=2)
self.account = Account.objects.create(name="Wallet", currency=currency)
food = TransactionCategory.objects.create(name="Food")
home = TransactionTag.objects.create(name="home")
self.make("Groceries", category=food).tags.add(home)
self.make("Restaurant", category=food, notes="with friends")
self.make("Rent").tags.add(home)
self.make("Gift")
def make(self, description, **kwargs):
today = timezone.localdate(timezone.now())
return Transaction.objects.create(
account=self.account,
type=Transaction.Type.EXPENSE,
date=today,
reference_date=today.replace(day=1),
amount=Decimal("10"),
description=description,
**kwargs,
)
def listed(self, params):
response = self.client.get(
reverse("transactions_all_list"), params, HTTP_HX_REQUEST="true"
)
self.assertEqual(response.status_code, 200)
page = response.context["page_obj"]
late = response.context["late_transactions"] or []
return sorted(t.description for t in [*page, *late])
def test_exclusions_join_with_inclusions(self):
cases = [
({"exclude_category": ["Food"]}, ["Gift", "Rent"]),
({"exclude_category": ["uncategorized"]}, ["Groceries", "Restaurant"]),
({"exclude_tags": ["home"]}, ["Gift", "Restaurant"]),
({"exclude_tags": ["untagged"]}, ["Groceries", "Rent"]),
({"exclude_description": "friends"}, ["Gift", "Groceries", "Rent"]),
({"exclude_account": ["Wallet"]}, []),
# positive and negative filters are applied together
({"category": ["Food"], "exclude_tags": ["home"]}, ["Restaurant"]),
]
for params, expected in cases:
self.assertEqual(self.listed(params), expected, params)
@@ -0,0 +1,321 @@
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from rest_framework.test import APIClient
from apps.accounts.models import Account, AccountGroup
from apps.currencies.models import Currency
from apps.transactions.models import (
InstallmentPlan,
QuickTransaction,
RecurringTransaction,
SubTransaction,
Transaction,
)
from apps.transactions.filters import content_filter, exclude_matching
from apps.transactions.views.actions import clone_transaction
def _subs(*rows, initial=0):
data = {"sub-TOTAL_FORMS": str(len(rows)), "sub-INITIAL_FORMS": str(initial)}
for i, row in enumerate(rows):
data.update({f"sub-{i}-{k}": v for k, v in row.items()})
return data
@override_settings(
STORAGES={
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"},
},
WHITENOISE_AUTOREFRESH=True,
)
class SubTransactionTests(TestCase):
def setUp(self):
user = get_user_model().objects.create_user(email="u@test.com", password="pw")
self.client.login(username="u@test.com", password="pw")
currency = Currency.objects.create(code="USD", name="USD", decimal_places=2)
self.account = Account.objects.create(
name="A", group=AccountGroup.objects.create(name="G"), currency=currency
)
self.base = {
"account": self.account.id,
"type": "EX",
"is_paid": True,
"date": timezone.localdate().isoformat(),
"description": "Groceries",
}
def _add(self, data):
return self.client.post(
reverse("transaction_add"), {**data, "submit": ""}, headers={"HX-Request": "true"}
)
def test_amount_is_sum_of_sub_transactions(self):
response = self._add(
{**self.base, "amount": "999", **_subs(
{"name": "Milk", "amount": "2.50"}, {"name": "Bread", "amount": "4"}
)}
)
self.assertEqual(response.status_code, 204)
transaction = Transaction.objects.get()
self.assertEqual(transaction.amount, Decimal("6.50"))
self.assertEqual(
list(transaction.sub_transactions.values_list("name", flat=True)),
["Milk", "Bread"],
)
def test_amount_required_without_sub_transactions(self):
response = self._add({**self.base, **_subs()})
self.assertEqual(response.status_code, 200)
self.assertIn("amount", response.context["form"].errors)
self.assertFalse(Transaction.objects.exists())
def test_sub_transaction_needs_name(self):
response = self._add({**self.base, **_subs({"name": "", "amount": "3"})})
self.assertEqual(response.status_code, 200)
self.assertFalse(Transaction.objects.exists())
def test_edit_removing_sub_transactions_restores_typed_amount(self):
transaction = Transaction.objects.create(
account=self.account, type="EX", date=timezone.localdate(), amount=5
)
sub = SubTransaction.objects.create(transaction=transaction, name="Fee", amount=5)
response = self.client.post(
reverse("transaction_edit", kwargs={"transaction_id": transaction.id}),
{**self.base, "amount": "12", **_subs(
{"id": sub.id, "name": "Fee", "amount": "5", "DELETE": "on"}, initial=1
)},
headers={"HX-Request": "true"},
)
self.assertEqual(response.status_code, 204)
transaction.refresh_from_db()
self.assertEqual(transaction.amount, Decimal("12"))
self.assertFalse(transaction.sub_transactions.exists())
@override_settings(ENABLE_SOFT_DELETE=True)
def test_soft_delete_hides_and_hard_delete_removes_sub_transactions(self):
transaction = Transaction.objects.create(
account=self.account, type="EX", date=timezone.localdate(), amount=5
)
SubTransaction.objects.create(transaction=transaction, name="Fee", amount=5)
url = reverse("transaction_delete", kwargs={"transaction_id": transaction.id})
self.client.delete(url, headers={"HX-Request": "true"})
# soft: sub-transactions stay with (and are hidden by) the deleted parent
self.assertTrue(Transaction.deleted_objects.filter(pk=transaction.pk).exists())
self.assertEqual(SubTransaction.objects.count(), 1)
self.client.delete(url, headers={"HX-Request": "true"})
self.assertFalse(SubTransaction.objects.exists())
def test_clone_copies_sub_transactions(self):
transaction = Transaction.objects.create(
account=self.account, type="EX", date=timezone.localdate(), amount=5
)
SubTransaction.objects.create(transaction=transaction, name="Fee", amount=5)
clone = clone_transaction(transaction)
self.assertEqual(list(clone.sub_transactions.values_list("name", "amount")), [("Fee", Decimal("5"))])
def test_content_filter_matches_sub_transaction_names(self):
shop = Transaction.objects.create(
account=self.account, type="EX", date=timezone.localdate(), amount=5, description="Shop"
)
SubTransaction.objects.create(transaction=shop, name="Milk", amount=2)
SubTransaction.objects.create(transaction=shop, name="Oat milk", amount=3)
other = Transaction.objects.create(
account=self.account, type="EX", date=timezone.localdate(), amount=1, description="Bus"
)
everything = Transaction.all_objects.all()
self.assertEqual(list(content_filter(everything, "description", "milk")), [shop])
self.assertEqual(list(exclude_matching(content_filter)(everything, "x", "milk")), [other])
def test_bulk_edit_leaves_amount_of_split_transactions(self):
split = Transaction.objects.create(
account=self.account, type="EX", date=timezone.localdate(), amount=5
)
SubTransaction.objects.create(transaction=split, name="Fee", amount=5)
plain = Transaction.objects.create(
account=self.account, type="EX", date=timezone.localdate(), amount=1
)
response = self.client.post(
reverse("transactions_bulk_edit"),
{"transactions": [split.id, plain.id], "amount": "50", "description": "Edited"},
headers={"HX-Request": "true"},
)
self.assertEqual(response.status_code, 204)
split.refresh_from_db()
plain.refresh_from_db()
self.assertEqual((split.amount, split.description), (Decimal("5"), "Edited"))
self.assertEqual(plain.amount, Decimal("50"))
def _post(self, url_name, data):
return self.client.post(reverse(url_name), data, headers={"HX-Request": "true"})
def _parts(self, transaction):
return list(transaction.sub_transactions.values_list("name", "amount"))
def test_quick_transaction_parts_are_copied_to_created_transaction(self):
self._post(
"quick_transaction_add",
{**self.base, "name": "Lunch", **_subs({"name": "Meal", "amount": "20"}, {"name": "Tip", "amount": "2"})},
)
quick = QuickTransaction.objects.get()
self.assertEqual(quick.amount, Decimal("22"))
self.client.get(
reverse("quick_transaction_add_as_transaction", kwargs={"quick_transaction_id": quick.id}),
headers={"HX-Request": "true"},
)
transaction = Transaction.objects.get()
self.assertEqual(transaction.amount, Decimal("22"))
self.assertEqual(self._parts(transaction), [("Meal", Decimal("20")), ("Tip", Decimal("2"))])
def test_quick_transfer_drops_parts(self):
other = Account.objects.create(name="B", group=self.account.group, currency=self.account.currency)
response = self._post(
"quick_transaction_add",
{**self.base, "type": "TR", "to_account": other.id, "amount": "5", "name": "Move",
**_subs({"name": "Hidden", "amount": "9"})},
)
self.assertEqual(response.status_code, 204)
quick = QuickTransaction.objects.get()
self.assertEqual(quick.amount, Decimal("5"))
self.assertFalse(quick.sub_transactions.exists())
def test_recurring_parts_follow_generated_and_unpaid_transactions(self):
self._post(
"recurring_transaction_add",
{**self.base, "start_date": timezone.localdate().isoformat(), "recurrence_type": "month",
"recurrence_interval": 1, "keep_at_most": 2, **_subs({"name": "Plan", "amount": "10"})},
)
recurring = RecurringTransaction.all_objects.get()
self.assertEqual(recurring.amount, Decimal("10"))
generated = recurring.transactions.all()
self.assertTrue(generated)
for transaction in generated:
self.assertEqual(self._parts(transaction), [("Plan", Decimal("10"))])
sub = recurring.sub_transactions.get()
self.client.post(
reverse("recurring_transaction_edit", kwargs={"recurring_transaction_id": recurring.id}),
{**self.base, "start_date": timezone.localdate().isoformat(), "recurrence_type": "month",
"recurrence_interval": 1, "keep_at_most": 2,
**_subs({"id": sub.id, "name": "Plan", "amount": "10"}, {"name": "Tax", "amount": "1"}, initial=1)},
headers={"HX-Request": "true"},
)
for transaction in recurring.transactions.all():
self.assertEqual(transaction.amount, Decimal("11"))
self.assertEqual(len(self._parts(transaction)), 2)
def test_installment_parts_are_copied_to_each_installment(self):
self._post(
"installment_plan_add",
{**self.base, "number_of_installments": 2, "installment_start": 1,
"start_date": timezone.localdate().isoformat(), "recurrence": "monthly",
**_subs({"name": "Principal", "amount": "90"}, {"name": "Interest", "amount": "10"})},
)
plan = InstallmentPlan.all_objects.get()
self.assertEqual(plan.installment_amount, Decimal("100"))
self.assertEqual(plan.transactions.count(), 2)
for transaction in plan.transactions.all():
self.assertEqual(transaction.amount, Decimal("100"))
self.assertEqual(len(self._parts(transaction)), 2)
class SubTransactionApiTests(TestCase):
def setUp(self):
user = get_user_model().objects.create_user(
email="api@test.com", password="pw", is_superuser=True
)
self.api = APIClient()
self.api.force_authenticate(user=user)
currency = Currency.objects.create(code="EUR", name="EUR", decimal_places=2)
self.account = Account.objects.create(name="A", currency=currency, owner=user)
def test_create_read_and_update_sub_transactions(self):
response = self.api.post(
"/api/transactions/",
{"account_id": self.account.id, "type": "EX", "date": "2030-01-10", "description": "Shop",
"sub_transactions": [{"name": "A", "amount": "1.50"}, {"name": "B", "amount": "2"}]},
format="json",
)
self.assertEqual(response.status_code, 201, response.data)
self.assertEqual(Decimal(response.data["amount"]), Decimal("3.50"))
self.assertEqual([s["name"] for s in response.data["sub_transactions"]], ["A", "B"])
url = f"/api/transactions/{response.data['id']}/"
# The amount can't drift from the parts
response = self.api.patch(url, {"amount": "9"}, format="json")
self.assertEqual(response.status_code, 400)
response = self.api.patch(url, {"sub_transactions": [{"name": "C", "amount": "4"}]}, format="json")
self.assertEqual(response.status_code, 200, response.data)
self.assertEqual(Decimal(response.data["amount"]), Decimal("4"))
self.assertEqual(self.api.get(url).data["sub_transactions"][0]["name"], "C")
def test_amount_required_without_sub_transactions(self):
response = self.api.post(
"/api/transactions/",
{"account_id": self.account.id, "type": "EX", "date": "2030-01-10"},
format="json",
)
self.assertEqual(response.status_code, 400)
self.assertIn("amount", response.data)
def _parts(self, owner):
return [(s.name, s.amount) for s in owner.sub_transactions.all()]
def test_installment_plan_parts_reach_every_installment(self):
response = self.api.post(
"/api/installment-plans/",
{"account": self.account.id, "type": "EX", "description": "Laptop",
"number_of_installments": 3, "start_date": "2030-01-10", "recurrence": "monthly",
"sub_transactions": [{"name": "Principal", "amount": "90"}, {"name": "Interest", "amount": "10"}]},
format="json",
)
self.assertEqual(response.status_code, 201, response.data)
self.assertEqual(Decimal(response.data["installment_amount"]), Decimal("100"))
plan = InstallmentPlan.all_objects.get()
installments = plan.transactions.all()
self.assertEqual(len(installments), 3)
for transaction in installments:
self.assertEqual(transaction.amount, Decimal("100"))
self.assertEqual(len(self._parts(transaction)), 2)
url = f"/api/installment-plans/{plan.id}/"
self.assertEqual(self.api.patch(url, {"installment_amount": "5"}, format="json").status_code, 400)
response = self.api.patch(url, {"sub_transactions": [{"name": "Principal", "amount": "80"}]}, format="json")
self.assertEqual(response.status_code, 200, response.data)
for transaction in plan.transactions.all():
self.assertEqual(self._parts(transaction), [("Principal", Decimal("80"))])
self.assertEqual(transaction.amount, Decimal("80"))
def test_recurring_parts_follow_its_transactions_and_transfers_drop_them(self):
response = self.api.post(
"/api/recurring-transactions/",
{"account": self.account.id, "type": "EX", "description": "Internet",
"start_date": timezone.localdate().isoformat(), "recurrence_type": "month", "recurrence_interval": 1,
"sub_transactions": [{"name": "Plan", "amount": "50"}, {"name": "Router", "amount": "10"}]},
format="json",
)
self.assertEqual(response.status_code, 201, response.data)
self.assertEqual(Decimal(response.data["amount"]), Decimal("60"))
self.assertEqual([s["name"] for s in response.data["sub_transactions"]], ["Plan", "Router"])
recurring = RecurringTransaction.all_objects.get()
generated = Transaction.all_objects.filter(recurring_transaction=recurring)
self.assertTrue(generated)
for transaction in generated:
self.assertEqual(transaction.amount, Decimal("60"))
self.assertEqual(len(self._parts(transaction)), 2)
other = Account.objects.create(name="B", currency=self.account.currency, owner=self.account.owner)
url = f"/api/recurring-transactions/{recurring.id}/"
self.assertEqual(
self.api.patch(url, {"type": "TR", "to_account": other.id,
"sub_transactions": [{"name": "X", "amount": "1"}]}, format="json").status_code,
400,
)
response = self.api.patch(url, {"type": "TR", "to_account": other.id}, format="json")
self.assertEqual(response.status_code, 200, response.data)
self.assertEqual(response.data["sub_transactions"], [])
+253 -12
View File
@@ -251,19 +251,20 @@ class TransferTemplateTests(TransferTestBase):
"""Recurring and quick transactions of type Transfer."""
def _recurring(self, **overrides):
return RecurringTransaction.objects.create(
account=self.checking,
type=RecurringTransaction.Type.TRANSFER,
to_account=self.savings,
amount=Decimal("100"),
to_amount=Decimal("95"),
description="Savings",
start_date=timezone.localdate(),
recurrence_type=RecurringTransaction.RecurrenceType.MONTH,
recurrence_interval=1,
keep_at_most=2,
data = {
"account": self.checking,
"type": RecurringTransaction.Type.TRANSFER,
"to_account": self.savings,
"amount": Decimal("100"),
"to_amount": Decimal("95"),
"description": "Savings",
"start_date": timezone.localdate(),
"recurrence_type": RecurringTransaction.RecurrenceType.MONTH,
"recurrence_interval": 1,
"keep_at_most": 2,
**overrides,
)
}
return RecurringTransaction.objects.create(**data)
def test_recurring_transfer_generates_linked_pairs(self):
recurring = self._recurring()
@@ -294,6 +295,187 @@ class TransferTemplateTests(TransferTestBase):
{(Transaction.Type.EXPENSE, Decimal("10")), (Transaction.Type.INCOME, Decimal("9"))},
)
def test_recurring_update_moves_unpaid_to_new_account_and_type(self):
recurring = self._recurring(type=RecurringTransaction.Type.EXPENSE)
recurring.create_upcoming_transactions()
paid = recurring.transactions.earliest("date")
paid.is_paid = True
paid.save()
recurring.account = self.savings
recurring.type = RecurringTransaction.Type.INCOME
recurring.save()
recurring.update_unpaid_transactions()
paid.refresh_from_db()
self.assertEqual(
(paid.account, paid.type), (self.checking, Transaction.Type.EXPENSE)
)
unpaid = recurring.transactions.filter(is_paid=False)
self.assertTrue(unpaid.exists())
self.assertEqual(
set(unpaid.values_list("account", "type")),
{(self.savings.id, Transaction.Type.INCOME)},
)
def test_recurring_transfer_update_moves_to_sides_to_new_account(self):
recurring = self._recurring()
recurring.create_upcoming_transactions()
brokerage = Account.objects.create(
name="Brokerage", group=self.checking.group, currency=self.checking.currency
)
recurring.to_account = brokerage
recurring.save()
recurring.update_unpaid_transactions()
self.assertEqual(
set(recurring.transactions.values_list("type", "account")),
{
(Transaction.Type.EXPENSE, self.checking.id),
(Transaction.Type.INCOME, brokerage.id),
},
)
def test_recurring_update_into_transfer_adds_to_sides(self):
recurring = self._recurring(type=RecurringTransaction.Type.INCOME)
recurring.create_upcoming_transactions()
occurrences = recurring.transactions.count()
recurring.type = RecurringTransaction.Type.TRANSFER
recurring.save()
recurring.update_unpaid_transactions()
expenses = recurring.transactions.filter(type=Transaction.Type.EXPENSE)
self.assertEqual(expenses.count(), occurrences)
self.assertEqual(recurring.transactions.count(), occurrences * 2)
for from_t in expenses:
to_t = from_t.linked_transaction
self.assertEqual(from_t.account, self.checking)
self.assertEqual(to_t.linked_transaction, from_t)
self.assertEqual(to_t.account, self.savings)
self.assertEqual(to_t.amount, Decimal("95"))
self.assertEqual(to_t.recurring_transaction, recurring)
def _assert_update_out_of_transfer_removes_to_sides(self):
recurring = self._recurring()
recurring.create_upcoming_transactions()
paid_from = recurring.transactions.filter(
type=Transaction.Type.EXPENSE
).earliest("date")
paid_from.is_paid = True
paid_from.save()
paid_to = paid_from.linked_transaction
occurrences = recurring.transactions.filter(
type=Transaction.Type.EXPENSE
).count()
recurring.type = RecurringTransaction.Type.EXPENSE
recurring.save()
recurring.update_unpaid_transactions()
unpaid = recurring.transactions.filter(is_paid=False)
self.assertEqual(unpaid.count(), occurrences - 1)
self.assertEqual(
set(unpaid.values_list("account", "type", "linked_transaction")),
{(self.checking.id, Transaction.Type.EXPENSE, None)},
)
paid_from.refresh_from_db()
self.assertEqual(paid_from.linked_transaction, paid_to)
def test_recurring_update_out_of_transfer_removes_to_sides(self):
self._assert_update_out_of_transfer_removes_to_sides()
self.assertFalse(Transaction.deleted_objects.exists())
@override_settings(ENABLE_SOFT_DELETE=True)
def test_recurring_update_out_of_transfer_soft_deletes_to_sides(self):
self._assert_update_out_of_transfer_removes_to_sides()
self.assertTrue(Transaction.deleted_objects.exists())
self.assertFalse(
Transaction.deleted_objects.exclude(linked_transaction=None).exists()
)
def test_recurring_update_keeps_transfer_linked_by_hand(self):
recurring = self._recurring(type=RecurringTransaction.Type.INCOME)
recurring.create_upcoming_transactions()
income = recurring.transactions.earliest("date")
expense = Transaction.objects.create(
account=self.savings,
type=Transaction.Type.EXPENSE,
amount=Decimal("100"),
date=income.date,
description="Outside",
is_paid=False,
)
expense.link_transfer(income)
recurring.amount = Decimal("120")
recurring.save()
recurring.update_unpaid_transactions()
income.refresh_from_db()
self.assertEqual(income.linked_transaction, expense)
self.assertEqual(income.amount, Decimal("120"))
self.assertTrue(Transaction.objects.filter(pk=expense.pk).exists())
def test_recurring_update_unlinks_transfer_linked_by_hand_when_broken(self):
for change in ({"type": RecurringTransaction.Type.EXPENSE}, {"account": self.savings}):
with self.subTest(change=change):
recurring = self._recurring(type=RecurringTransaction.Type.INCOME)
recurring.create_upcoming_transactions()
income = recurring.transactions.earliest("date")
outside = Transaction.objects.create(
account=self.savings,
type=Transaction.Type.EXPENSE,
amount=Decimal("100"),
date=income.date,
description="Outside",
is_paid=False,
)
outside.link_transfer(income)
for field, value in change.items():
setattr(recurring, field, value)
recurring.save()
recurring.update_unpaid_transactions()
income.refresh_from_db()
outside.refresh_from_db()
self.assertIsNone(income.linked_transaction)
self.assertIsNone(outside.linked_transaction)
self.assertEqual(
(outside.account, outside.type, outside.amount),
(self.savings, Transaction.Type.EXPENSE, Decimal("100")),
)
def test_edit_view_moves_unpaid_transactions(self):
recurring = self._recurring(type=RecurringTransaction.Type.EXPENSE)
recurring.create_upcoming_transactions()
response = self.client.post(
reverse(
"recurring_transaction_edit",
kwargs={"recurring_transaction_id": recurring.id},
),
{
"type": "EX",
"account": self.savings.id,
"amount": "100",
"description": "Savings",
"start_date": recurring.start_date.isoformat(),
"recurrence_type": "month",
"recurrence_interval": "1",
"keep_at_most": "2",
},
HTTP_HX_REQUEST="true",
)
self.assertEqual(response.status_code, 204)
self.assertEqual(
set(recurring.transactions.values_list("account", flat=True)),
{self.savings.id},
)
def test_transfer_type_requires_other_account(self):
form = RecurringTransactionForm(
{
@@ -439,3 +621,62 @@ class TransferReviewFixTests(TransferTestBase):
partner.refresh_from_db()
self.assertIsNone(partner.linked_transaction)
class BulkActionTests(TransferTestBase):
def _get(self, name, *ids, **kwargs):
query = "&".join(f"transactions={pk}" for pk in ids)
return self.client.get(
reverse(name, kwargs=kwargs) + f"?{query}", HTTP_HX_REQUEST="true"
)
def _expense(self, **fields):
return Transaction.objects.create(
account=self.checking,
type=Transaction.Type.EXPENSE,
amount=Decimal("10"),
date=date(2026, 3, 10),
description="Coffee",
**fields,
)
def test_change_month_updates_a_fully_selected_transfer_once_per_side(self):
from_t, to_t = self._transfer()
updated = []
receiver = lambda sender, **kwargs: updated.append(sender.pk) # noqa: E731
transaction_updated.connect(receiver, weak=False)
self.addCleanup(transaction_updated.disconnect, receiver)
response = self._get(
"transactions_bulk_change_month", from_t.id, to_t.id, change_type="next"
)
self.assertEqual(response.status_code, 204)
from_t.refresh_from_db()
to_t.refresh_from_db()
self.assertEqual(from_t.reference_date, date(2026, 4, 1))
self.assertEqual(to_t.reference_date, date(2026, 4, 1))
self.assertEqual(sorted(updated), sorted([from_t.pk, to_t.pk])) # once per side
def test_change_month_rejects_unknown_direction(self):
t = self._expense()
response = self._get("transactions_bulk_change_month", t.id, change_type="sideways")
self.assertEqual(response.status_code, 400)
def test_move_to_today(self):
t = self._expense()
self._get("transactions_bulk_move_to_today", t.id)
t.refresh_from_db()
self.assertEqual(t.date, timezone.localdate(timezone.now()))
def test_mute_skips_transactions_controlled_elsewhere(self):
muted_category = TransactionCategory.objects.create(name="Hidden", mute=True)
plain = self._expense()
by_category = self._expense(category=muted_category)
self._get("transactions_bulk_mute", plain.id, by_category.id)
plain.refresh_from_db()
by_category.refresh_from_db()
self.assertTrue(plain.mute)
self.assertFalse(by_category.mute)
+108
View File
@@ -312,6 +312,54 @@ class TransactionConvertViewTests(TestCase):
set(plan.transactions.values_list("amount", flat=True)), {70}
)
def test_transfer_form_prefills_side_from_type(self):
initial = self._get("transaction_convert_to_transfer").context["form"].initial
self.assertEqual(initial["from_account"], self.account.id)
self.assertEqual(initial["from_tags"], ["TestTag"])
self.assertNotIn("to_account", initial)
self.transaction.type = Transaction.Type.INCOME
self.transaction.save()
initial = self._get("transaction_convert_to_transfer").context["form"].initial
self.assertEqual(initial["to_account"], self.account.id)
self.assertNotIn("from_account", initial)
self.assertEqual(initial["from_amount"], 50)
self.assertNotIn("to_amount", initial)
def test_transfer_replaces_original_transaction(self):
other = Account.objects.create(name="Savings", currency=self.currency)
response = self._post(
"transaction_convert_to_transfer",
{
"from_account": self.account.id,
"to_account": other.id,
"from_amount": "50",
"date": "2030-01-15",
"is_paid": "on",
},
)
self.assertEqual(response.status_code, 204)
self.assertFalse(Transaction.objects.filter(id=self.transaction.id).exists())
self.assertEqual(
Transaction.objects.filter(linked_transaction__isnull=False).count(), 2
)
# A transfer can't be converted into one again
self.transaction = Transaction.objects.get(account=other)
self.assertEqual(self._get("transaction_convert_to_transfer").status_code, 404)
def test_invalid_transfer_keeps_original_transaction(self):
response = self._post(
"transaction_convert_to_transfer",
{
"from_account": self.account.id,
"to_account": self.account.id,
"from_amount": "50",
"date": "2030-01-15",
},
)
self.assertEqual(response.status_code, 200)
self.assertTrue(Transaction.objects.filter(id=self.transaction.id).exists())
def test_linked_transaction_cannot_be_converted_into_plan(self):
self._post(
"transaction_convert_to_installment_plan",
@@ -332,3 +380,63 @@ class TransactionConvertViewTests(TestCase):
self.assertEqual(
self._get("transaction_convert_to_installment_plan").status_code, 404
)
@override_settings(
STORAGES={
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"},
},
WHITENOISE_AUTOREFRESH=True,
)
class InstallmentRecurringIsolationTests(TestCase):
"""Per-object plan views must 404 for objects on another user's private account."""
def setUp(self):
User = get_user_model()
owner = User.objects.create_user(email="owner@test.com", password="pw")
User.objects.create_user(email="other@test.com", password="pw")
self.client.login(username="other@test.com", password="pw")
currency = Currency.objects.create(code="USD", name="US Dollar", decimal_places=2)
account = Account.all_objects.create(name="Private", currency=currency, owner=owner)
self.plan = InstallmentPlan.all_objects.create(
account=account,
type=Transaction.Type.EXPENSE,
description="Owner plan",
number_of_installments=3,
start_date=date(2025, 1, 1),
installment_amount=100,
)
self.recurring = RecurringTransaction.all_objects.create(
account=account,
type=Transaction.Type.EXPENSE,
amount=50,
description="Owner recurring",
start_date=date(2025, 1, 1),
recurrence_type=RecurringTransaction.RecurrenceType.MONTH,
recurrence_interval=1,
)
def test_other_user_gets_404(self):
cases = [
("get", "installment_plan_transactions", "installment_plan_id", self.plan),
("get", "installment_plan_edit", "installment_plan_id", self.plan),
("get", "installment_plan_refresh", "installment_plan_id", self.plan),
("delete", "installment_plan_delete", "installment_plan_id", self.plan),
("get", "recurring_transaction_transactions", "recurring_transaction_id", self.recurring),
("get", "recurring_transaction_edit", "recurring_transaction_id", self.recurring),
("get", "recurring_transaction_toggle_pause", "recurring_transaction_id", self.recurring),
("get", "recurring_transaction_finish", "recurring_transaction_id", self.recurring),
("delete", "recurring_transaction_delete", "recurring_transaction_id", self.recurring),
]
for method, name, kwarg, obj in cases:
with self.subTest(name=name):
url = reverse(name, kwargs={kwarg: obj.id})
response = getattr(self.client, method)(url, HTTP_HX_REQUEST="true")
self.assertEqual(response.status_code, 404)
self.assertTrue(InstallmentPlan.all_objects.filter(id=self.plan.id).exists())
self.recurring.refresh_from_db()
self.assertFalse(self.recurring.is_paused)
self.assertIsNone(self.recurring.end_date)
+20
View File
@@ -81,6 +81,21 @@ urlpatterns = [
views.bulk_clone_transactions,
name="transactions_bulk_clone",
),
path(
"transactions/actions/change-month/<str:change_type>/",
views.bulk_change_month,
name="transactions_bulk_change_month",
),
path(
"transactions/actions/move-to-today/",
views.bulk_move_to_today,
name="transactions_bulk_move_to_today",
),
path(
"transactions/actions/mute/",
views.bulk_mute,
name="transactions_bulk_mute",
),
path(
"transaction/<int:transaction_id>/pay/",
views.transaction_pay,
@@ -417,4 +432,9 @@ urlpatterns = [
views.transaction_convert_to_installment_plan,
name="transaction_convert_to_installment_plan",
),
path(
"transaction/<int:transaction_id>/convert/transfer/",
views.transaction_convert_to_transfer,
name="transaction_convert_to_transfer",
),
]
+77
View File
@@ -1,10 +1,12 @@
import json
from copy import deepcopy
from dateutil.relativedelta import relativedelta
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _, ngettext_lazy
from apps.common.decorators.htmx import only_htmx
@@ -30,6 +32,7 @@ def _copy(transaction):
new_transaction.tags.add(*transaction.tags.all())
new_transaction.entities.add(*transaction.entities.all())
new_transaction.copy_sub_transactions_from(transaction)
return new_transaction
@@ -149,6 +152,80 @@ def bulk_undelete_transactions(request):
)
def _bulk_update(request, transactions, change):
"""Applies change to each selected transaction like its single action does.
A transfer moves as a pair through save(), so a selected partner is skipped.
"""
done = set()
for transaction in transactions:
if transaction.linked_transaction_id in done:
continue
old_data = deepcopy(transaction)
change(transaction)
transaction.save()
transaction_updated.send(sender=transaction, old_data=old_data)
done.add(transaction.id)
count = len(done)
messages.success(
request,
ngettext_lazy(
"%(count)s transaction updated successfully",
"%(count)s transactions updated successfully",
count,
)
% {"count": count},
)
return HttpResponse(status=204, headers={"HX-Trigger": "updated"})
@only_htmx
@login_required
def bulk_change_month(request, change_type):
months = {"previous": -1, "next": 1}.get(change_type)
if months is None:
return HttpResponse(status=400)
def change(transaction):
transaction.reference_date += relativedelta(months=months)
return _bulk_update(
request,
Transaction.objects.filter(id__in=request.GET.getlist("transactions")),
change,
)
@only_htmx
@login_required
def bulk_move_to_today(request):
today = timezone.localdate(timezone.now())
def change(transaction):
transaction.date = today
return _bulk_update(
request,
Transaction.objects.filter(id__in=request.GET.getlist("transactions")),
change,
)
@only_htmx
@login_required
def bulk_mute(request):
# Visibility controlled by the account or category can't be changed here.
transactions = Transaction.objects.filter(
id__in=request.GET.getlist("transactions"), mute=False
).exclude(Q(account__untracked_by=request.user) | Q(category__mute=True))
def change(transaction):
transaction.mute = True
return _bulk_update(request, transactions, change)
@only_htmx
@login_required
def bulk_clone_transactions(request):
@@ -12,6 +12,7 @@ from apps.transactions.forms import (
InstallmentPlanForm,
QuickTransactionForm,
RecurringTransactionForm,
TransferForm,
)
from apps.transactions.models import Transaction
@@ -36,6 +37,10 @@ def _initial_from_transaction(transaction: Transaction):
return initial
def _sub_transactions_initial(transaction: Transaction):
return list(transaction.sub_transactions.values("name", "amount"))
def _get_unlinked_transaction(transaction_id):
# Transactions already generated by a plan or recurrence can't be converted again
return get_object_or_404(
@@ -77,6 +82,7 @@ def transaction_convert_to_quick_transaction(request, transaction_id):
)
else:
form = QuickTransactionForm(
sub_transactions_initial=_sub_transactions_initial(transaction),
initial={
**_initial_from_transaction(transaction),
"is_paid": transaction.is_paid,
@@ -113,6 +119,7 @@ def transaction_convert_to_recurring_transaction(request, transaction_id):
)
else:
form = RecurringTransactionForm(
sub_transactions_initial=_sub_transactions_initial(transaction),
initial={
**_initial_from_transaction(transaction),
"amount": transaction.amount,
@@ -153,6 +160,7 @@ def transaction_convert_to_installment_plan(request, transaction_id):
)
else:
form = InstallmentPlanForm(
sub_transactions_initial=_sub_transactions_initial(transaction),
initial={
**_initial_from_transaction(transaction),
"installment_amount": transaction.amount,
@@ -168,3 +176,54 @@ def transaction_convert_to_installment_plan(request, transaction_id):
transaction_id,
"transaction_convert_to_installment_plan",
)
@only_htmx
@login_required
@require_http_methods(["GET", "POST"])
def transaction_convert_to_transfer(request, transaction_id):
transaction = _get_unlinked_transaction(transaction_id)
if transaction.linked_transaction_id:
raise Http404() # Already a transfer
if request.method == "POST":
form = TransferForm(request.POST)
if form.is_valid():
with db_transaction.atomic():
form.save()
transaction.delete()
messages.success(request, _("Transaction converted into a transfer"))
return HttpResponse(
status=204,
headers={"HX-Trigger": "updated, hide_offcanvas"},
)
else:
# An expense leaves its account (the "from" side), an income enters it ("to")
side = "from" if transaction.type == Transaction.Type.EXPENSE else "to"
form = TransferForm(
initial={
f"{side}_account": transaction.account_id,
f"{side}_category": transaction.category_id,
f"{side}_tags": list(transaction.tags.values_list("name", flat=True)),
f"{side}_entities": list(
transaction.entities.values_list("name", flat=True)
),
# To amount stays empty, so it follows from amount
"from_amount": transaction.amount,
"date": transaction.date,
"reference_date": transaction.reference_date,
"description": transaction.description,
"notes": transaction.notes,
"mute": transaction.mute,
"is_paid": transaction.is_paid,
}
)
return _render_convert_form(
request,
form,
_("Convert into transfer"),
transaction_id,
"transaction_convert_to_transfer",
)
@@ -66,8 +66,8 @@ def finished_installment_plans_list(request):
@login_required
@require_http_methods(["GET"])
def installment_plan_transactions(request, installment_plan_id):
installment_plan = get_object_or_404(InstallmentPlan, id=installment_plan_id)
transactions = installment_plan.transactions.all().order_by("reference_date", "id")
installment_plan = get_object_or_404(InstallmentPlan.objects, id=installment_plan_id)
transactions = installment_plan.transactions.prefetch_related("sub_transactions").order_by("reference_date", "id")
return render(
request,
@@ -106,7 +106,7 @@ def installment_plan_add(request):
@login_required
@require_http_methods(["GET", "POST"])
def installment_plan_edit(request, installment_plan_id):
installment_plan = get_object_or_404(InstallmentPlan, id=installment_plan_id)
installment_plan = get_object_or_404(InstallmentPlan.objects, id=installment_plan_id)
if request.method == "POST":
form = InstallmentPlanForm(request.POST, instance=installment_plan)
@@ -134,7 +134,7 @@ def installment_plan_edit(request, installment_plan_id):
@login_required
@require_http_methods(["GET"])
def installment_plan_refresh(request, installment_plan_id):
installment_plan = get_object_or_404(InstallmentPlan, id=installment_plan_id)
installment_plan = get_object_or_404(InstallmentPlan.objects, id=installment_plan_id)
installment_plan.update_transactions()
messages.success(request, _("Installment Plan refreshed successfully"))
@@ -151,7 +151,7 @@ def installment_plan_refresh(request, installment_plan_id):
@login_required
@require_http_methods(["DELETE"])
def installment_plan_delete(request, installment_plan_id):
installment_plan = get_object_or_404(InstallmentPlan, id=installment_plan_id)
installment_plan = get_object_or_404(InstallmentPlan.objects, id=installment_plan_id)
installment_plan.delete()
@@ -155,6 +155,7 @@ def quick_transaction_add_as_transaction(request, quick_transaction_id):
new_transaction.save()
new_transaction.tags.set(quick_transaction.tags.all())
new_transaction.entities.set(quick_transaction.entities.all())
new_transaction.copy_sub_transactions_from(quick_transaction)
to_transaction = quick_transaction.complete_transfer(new_transaction)
transaction_created.send(sender=new_transaction)
@@ -88,9 +88,9 @@ def finished_recurring_transactions_list(request):
@require_http_methods(["GET"])
def recurring_transaction_transactions(request, recurring_transaction_id):
recurring_transaction = get_object_or_404(
RecurringTransaction, id=recurring_transaction_id
RecurringTransaction.objects, id=recurring_transaction_id
)
transactions = recurring_transaction.transactions.collapse_transfers().order_by(
transactions = recurring_transaction.transactions.collapse_transfers().prefetch_related("sub_transactions").order_by(
"reference_date", "id"
)
@@ -132,7 +132,7 @@ def recurring_transaction_add(request):
@require_http_methods(["GET", "POST"])
def recurring_transaction_edit(request, recurring_transaction_id):
recurring_transaction = get_object_or_404(
RecurringTransaction, id=recurring_transaction_id
RecurringTransaction.objects, id=recurring_transaction_id
)
if request.method == "POST":
@@ -162,7 +162,7 @@ def recurring_transaction_edit(request, recurring_transaction_id):
@require_http_methods(["GET"])
def recurring_transaction_toggle_pause(request, recurring_transaction_id):
recurring_transaction = get_object_or_404(
RecurringTransaction, id=recurring_transaction_id
RecurringTransaction.objects, id=recurring_transaction_id
)
current_paused = recurring_transaction.is_paused
recurring_transaction.is_paused = not current_paused
@@ -201,7 +201,7 @@ def recurring_transaction_toggle_pause(request, recurring_transaction_id):
@require_http_methods(["GET"])
def recurring_transaction_finish(request, recurring_transaction_id):
recurring_transaction: RecurringTransaction = get_object_or_404(
RecurringTransaction, id=recurring_transaction_id
RecurringTransaction.objects, id=recurring_transaction_id
)
today = timezone.localdate(timezone.now()) - relativedelta(days=1)
@@ -227,7 +227,7 @@ def recurring_transaction_finish(request, recurring_transaction_id):
@require_http_methods(["DELETE"])
def recurring_transaction_delete(request, recurring_transaction_id):
recurring_transaction = get_object_or_404(
RecurringTransaction, id=recurring_transaction_id
RecurringTransaction.objects, id=recurring_transaction_id
)
recurring_transaction.delete()
@@ -409,6 +409,8 @@ def transactions_bulk_edit(request):
transaction.tags.set(value)
elif field_name == "entities":
transaction.entities.set(value)
elif field_name == "amount" and transaction.has_sub_transactions:
continue # its amount is the sum of its parts
else:
setattr(transaction, field_name, value)
@@ -821,6 +823,7 @@ def transaction_all_list(request):
"installment_plan",
"entities",
"dca_expense_entries",
"sub_transactions",
"dca_income_entries",
"linked_transaction__account__currency",
"linked_transaction__account__group",
@@ -990,6 +993,7 @@ def transactions_trash_can_list(request):
"installment_plan",
"entities",
"dca_expense_entries",
"sub_transactions",
"dca_income_entries",
"linked_transaction__account__currency",
"linked_transaction__account__group",
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -5,6 +5,7 @@
{% block title %}{% translate 'Share settings' %}{% endblock %}
{% block body %}
<p class="text-sm text-base-content/70 mb-3">{% translate "Everyone who can see this account can add, edit and delete its transactions, installment plans and recurring transactions." %}</p>
<form hx-post="{% url "account_share_settings" pk=object.id %}" hx-target="#generic-offcanvas" novalidate>
{% crispy form %}
</form>
+47 -3
View File
@@ -2,10 +2,12 @@
{% load i18n %}
{# With "Combine transfers" on, a transfer is shown once: its "from" side with the "to" side alongside #}
{% with transaction=transaction.display_transaction transfer_to=transaction.transfer_to is_transfer=transaction.shown_as_transfer %}
{% with subs=transaction.saved_sub_transactions %}
<div
{% if transaction.id and not dummy %}data-transaction-id="{{ transaction.id }}"{% endif %}
class="transaction {% if is_transfer %}transfer{% elif transaction.type == "EX" %}expense{% else %}income{% endif %} group/transaction">
<div class="flex my-1">
class="transaction {% if is_transfer %}transfer{% elif transaction.type == "EX" %}expense{% else %}income{% endif %} group/transaction"
{% if subs %}x-data="{ subsOpen: false }"{% endif %}>
<div class="flex my-1 {% if subs %}mb-6{% endif %}">
{% if not disable_selection or not dummy %}
<label class="px-3 flex! items-center justify-center">
<input class="checkbox" type="checkbox" name="transactions" value="{{ transaction.id }}"
@@ -15,7 +17,7 @@
<div class="border-s-4 border-e-0 border-t-0
hover:bg-base-200 p-2 {% if transaction.account.is_asset %}border-dashed{% else %}border-solid{% endif %}
{% if is_transfer %}border-s-info{% elif transaction.type == "EX" %}border-s-error{% else %}border-s-success{% endif %} relative
w-full transaction-item bg-base-100 rounded">
w-full min-w-0 transaction-item bg-base-100 rounded">
<div class="flex flex-wrap lg:flex-nowrap font-mono text-sm items-center">
<div class="lg:w-auto w-full flex items-center text-2xl lg:text-xl lg:text-center text-center p-0 cursor-pointer">
{% if not transaction.deleted %}
@@ -259,6 +261,16 @@
</div>
</a>
</li>
<li class="menu-disabled" aria-disabled="true">
<a class="flex items-center">
<i class="fa-solid fa-money-bill-transfer fa-fw mr-2"></i>
<div>
{% translate 'Transfer' %}
<div
class="block text-base-content/60 text-xs font-medium">{% translate 'Already part of a plan or recurrence' %}</div>
</div>
</a>
</li>
{% else %}
<li><a href="#"
hx-get="{% url 'transaction_convert_to_recurring_transaction' transaction_id=transaction.id %}"
@@ -282,6 +294,11 @@
hx-target="#generic-offcanvas" hx-swap="innerHTML"><i
class="fa-solid fa-divide fa-fw mr-2"></i>{% translate 'Installment Plan' %}</a>
</li>
<li><a href="#"
hx-get="{% url 'transaction_convert_to_transfer' transaction_id=transaction.id %}"
hx-target="#generic-offcanvas" hx-swap="innerHTML"><i
class="fa-solid fa-money-bill-transfer fa-fw mr-2"></i>{% translate 'Transfer' %}</a>
</li>
{% endif %}
{% endif %}
</ul>
@@ -327,7 +344,34 @@
</div>
{% endif %}
</div>
{% if subs %}
{# Breakdown, opened from the tab hanging under the card; amounts line up with the total #}
<div x-show="subsOpen" x-collapse x-cloak>
<ul class="mt-2 pt-2 border-t border-dashed border-base-content/15 font-mono text-sm lg:ps-12">
{% for sub in subs %}
<li class="flex justify-between gap-4 py-0.5">
<span class="truncate text-base-content/80">{{ sub.name }}</span>
<span class="whitespace-nowrap text-base-content/70"><c-amount.display
:amount="sub.amount"
:prefix="transaction.account.currency.prefix"
:suffix="transaction.account.currency.suffix"
:decimal_places="transaction.account.currency.decimal_places"
divless></c-amount.display></span>
</li>
{% endfor %}
</ul>
</div>
<button type="button"
class="absolute top-full left-1/2 -translate-x-1/2 flex items-center gap-1.5 px-3 pb-0.5 rounded-b-md
bg-base-100 hover:bg-base-200 text-xs font-mono text-base-content/60 hover:text-base-content cursor-pointer"
@click="subsOpen = !subsOpen" :aria-expanded="subsOpen">
<i class="fa-solid fa-list-ul fa-fw"></i>
{% blocktranslate count counter=subs|length %}{{ counter }} item{% plural %}{{ counter }} items{% endblocktranslate %}
<i class="fa-solid fa-chevron-down fa-fw transition-transform duration-200" :class="subsOpen && 'rotate-180'"></i>
</button>
{% endif %}
</div>
</div>
</div>
{% endwith %}
{% endwith %}
@@ -17,38 +17,38 @@
end
end">
<div class="card bg-base-300 shadow slide-in-bottom-short max-w-[90vw] card-border mt-5">
<div class="card-body flex-row p-2 flex justify-between items-center gap-3 overflow-x-auto">
<div class="card-body flex-row p-2 flex justify-between items-center gap-2 sm:gap-3 overflow-x-auto">
{% spaceless %}
<div class="font-bold text-md ms-2" id="selected-count">0</div>
<div class="divider divider-horizontal m-0"></div>
<div>
<button role="button" class="btn btn-secondary btn-sm" type="button" data-bs-toggle="dropdown"
aria-expanded="false">
<i class="fa-regular fa-square-check fa-fw"></i>
<i class="fa-solid fa-chevron-down fa-xs"></i>
<div class="divider divider-horizontal m-0 max-sm:hidden"></div>
<div class="join">
<button class="btn btn-secondary btn-sm join-item" type="button" data-tippy-content="{% translate 'Unselect All' %}"
aria-label="{% translate 'Unselect All' %}"
_="on click set <#transactions-list input[type='checkbox']/>'s checked to false then call me.blur() then trigger change">
<i class="fa-solid fa-xmark fa-fw"></i>
</button>
<ul class="dropdown-menu menu">
<li>
<a class="cursor-pointer"
_="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 text-success me-3"></i>{% translate 'Select All' %}
</a>
</li>
<li>
<a class="cursor-pointer"
_="on click set <#transactions-list input[type='checkbox']/>'s checked to false then call me.blur() then trigger change">
<i class="fa-regular fa-square text-error me-3"></i>{% translate 'Unselect All' %}
</a>
</li>
<li>
<a class="cursor-pointer"
_="on click for checkbox in <#transactions-list input[type='checkbox']/> set checkbox.checked to (not checkbox.checked) end then call me.blur() then trigger change">
<i class="fa-solid fa-arrow-right-arrow-left text-info me-3"></i>{% translate 'Invert election' %}
</a>
</li>
</ul>
<div>
<button role="button" class="btn btn-secondary btn-sm join-item" type="button" data-bs-toggle="dropdown"
aria-expanded="false">
<i class="fa-solid fa-chevron-down fa-xs"></i>
</button>
<ul class="dropdown-menu menu">
<li>
<a class="cursor-pointer"
_="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 text-success me-3"></i>{% translate 'Select All' %}
</a>
</li>
<li>
<a class="cursor-pointer"
_="on click for checkbox in <#transactions-list input[type='checkbox']/> set checkbox.checked to (not checkbox.checked) end then call me.blur() then trigger change">
<i class="fa-solid fa-arrow-right-arrow-left text-info me-3"></i>{% translate 'Invert selection' %}
</a>
</li>
</ul>
</div>
</div>
<div class="divider divider-horizontal m-0"></div>
<div class="divider divider-horizontal m-0 max-sm:hidden"></div>
<button class="btn btn-secondary btn-sm" hx-get="{% url 'transactions_bulk_undelete' %}" hx-include=".transaction"
data-tippy-content="{% translate 'Restore' %}">
<i class="fa-solid fa-trash-arrow-up fa-fw"></i>
@@ -59,7 +59,7 @@
data-confirm-text="{% translate "Yes, delete them!" %}" _="install prompt_swal">
<i class="fa-solid fa-trash text-error"></i>
</button>
<div class="divider divider-horizontal m-0"></div>
<div class="divider divider-horizontal m-0 max-sm:hidden"></div>
<div class="join" _="on selected_transactions_updated from #actions-bar
set realTotal to math.bignumber(0)
set flatTotal to math.bignumber(0)
@@ -102,8 +102,8 @@
writeText(original_value) on navigator.clipboard
put '{% translate "copied!" %}' into #real-total-front's innerText wait 1s put original_value
into #real-total-front's innerText end">
<i class="fa-solid fa-plus fa-fw me-md-2"></i>
<span class="hidden md:inline-block" id="real-total-front">0</span>
<i class="fa-solid fa-plus fa-fw sm:me-2"></i>
<span class="hidden sm:inline-block" id="real-total-front">0</span>
</button>
<div>
<button class="join-item btn btn-sm btn-secondary" type="button" data-bs-toggle="dropdown"
@@ -17,74 +17,99 @@
end
end">
<div class="card bg-base-300 shadow slide-in-bottom-short max-w-[90vw] card-border mt-5">
<div class="card-body flex-row p-2 flex justify-between items-center gap-3 overflow-x-auto">
<div class="card-body flex-row p-2 flex justify-between items-center gap-2 sm:gap-3 overflow-x-auto">
{% spaceless %}
<div class="font-bold text-md ms-2" id="selected-count">0</div>
<div class="divider divider-horizontal m-0"></div>
<div>
<button role="button" class="btn btn-secondary btn-sm" type="button" data-bs-toggle="dropdown"
aria-expanded="false">
<i class="fa-regular fa-square-check fa-fw"></i>
<i class="fa-solid fa-chevron-down fa-xs"></i>
</button>
<ul class="dropdown-menu menu">
<li>
<a class="cursor-pointer"
_="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 text-success me-3"></i>{% translate 'Select All' %}
</a>
</li>
<li>
<a class="cursor-pointer"
_="on click set <#transactions-list input[type='checkbox']/>'s checked to false then call me.blur() then trigger change">
<i class="fa-regular fa-square text-error me-3"></i>{% translate 'Unselect All' %}
</a>
</li>
<li>
<a class="cursor-pointer"
_="on click for checkbox in <#transactions-list input[type='checkbox']/> set checkbox.checked to (not checkbox.checked) end then call me.blur() then trigger change">
<i class="fa-solid fa-arrow-right-arrow-left text-info me-3"></i>{% translate 'Invert selection' %}
</a>
</li>
</ul>
</div>
<div class="divider divider-horizontal m-0"></div>
<div class="divider divider-horizontal m-0 max-sm:hidden"></div>
<div class="join">
<button class="btn btn-secondary join-item btn-sm" hx-get="{% url 'transactions_bulk_edit' %}"
hx-target="#generic-offcanvas" hx-include=".transaction" data-tippy-content="{% translate 'Edit' %}">
<i class="fa-solid fa-pencil"></i>
<button class="btn btn-secondary btn-sm join-item" type="button" data-tippy-content="{% translate 'Unselect All' %}"
aria-label="{% translate 'Unselect All' %}"
_="on click set <#transactions-list input[type='checkbox']/>'s checked to false then call me.blur() then trigger change">
<i class="fa-solid fa-xmark fa-fw"></i>
</button>
<div>
<button type="button" role="button" class="join-item btn btn-sm btn-secondary" data-bs-toggle="dropdown"
<button role="button" class="btn btn-secondary btn-sm join-item" type="button" data-bs-toggle="dropdown"
aria-expanded="false">
<i class="fa-solid fa-chevron-down fa-xs"></i>
</button>
<ul class="dropdown-menu menu">
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_unpay' %}" hx-include=".transaction">
<i class="fa-regular fa-circle text-red-400 fa-fw me-3"></i>{% translate 'Mark as unpaid' %}
<a class="cursor-pointer"
_="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 text-success me-3"></i>{% translate 'Select All' %}
</a>
</li>
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_pay' %}" hx-include=".transaction">
<i class="fa-regular fa-circle-check text-green-400 fa-fw me-3"></i>{% translate 'Mark as paid' %}
<a class="cursor-pointer"
_="on click for checkbox in <#transactions-list input[type='checkbox']/> set checkbox.checked to (not checkbox.checked) end then call me.blur() then trigger change">
<i class="fa-solid fa-arrow-right-arrow-left text-info me-3"></i>{% translate 'Invert selection' %}
</a>
</li>
</ul>
</div>
</div>
<button class="btn btn-secondary btn-sm" hx-get="{% url 'transactions_bulk_clone' %}" hx-include=".transaction"
data-tippy-content="{% translate 'Duplicate' %}">
<i class="fa-solid fa-clone fa-fw"></i>
</button>
<button class="btn btn-error btn-sm" hx-get="{% url 'transactions_bulk_delete' %}" hx-include=".transaction"
hx-trigger="confirmed" data-tippy-content="{% translate 'Delete' %}" data-bypass-on-ctrl="true"
data-title="{% translate "Are you sure?" %}" data-text="{% translate "You won't be able to revert this!" %}"
data-confirm-text="{% translate "Yes, delete them!" %}" _="install prompt_swal">
<i class="fa-solid fa-trash"></i>
</button>
<div class="divider divider-horizontal m-0"></div>
<div class="divider divider-horizontal m-0 max-sm:hidden"></div>
{# Below md every action folds into a single menu so the bar doesn't overflow #}
<div class="hidden md:flex items-center gap-3">
<div class="join">
<button class="btn btn-secondary join-item btn-sm" hx-get="{% url 'transactions_bulk_edit' %}"
hx-target="#generic-offcanvas" hx-include=".transaction" data-tippy-content="{% translate 'Edit' %}">
<i class="fa-solid fa-pencil"></i>
</button>
<div>
<button type="button" role="button" class="join-item btn btn-sm btn-secondary" data-bs-toggle="dropdown"
aria-expanded="false">
<i class="fa-solid fa-chevron-down fa-xs"></i>
</button>
<ul class="dropdown-menu menu">
{% include 'includes/transactions_bulk_actions.html' %}
</ul>
</div>
</div>
<button class="btn btn-secondary btn-sm" hx-get="{% url 'transactions_bulk_clone' %}" hx-include=".transaction"
data-tippy-content="{% translate 'Duplicate' %}">
<i class="fa-solid fa-clone fa-fw"></i>
</button>
<button class="btn btn-error btn-sm" hx-get="{% url 'transactions_bulk_delete' %}" hx-include=".transaction"
hx-trigger="confirmed" data-tippy-content="{% translate 'Delete' %}" data-bypass-on-ctrl="true"
data-title="{% translate "Are you sure?" %}" data-text="{% translate "You won't be able to revert this!" %}"
data-confirm-text="{% translate "Yes, delete them!" %}" _="install prompt_swal">
<i class="fa-solid fa-trash"></i>
</button>
</div>
<div class="md:hidden">
<button type="button" role="button" class="btn btn-secondary btn-sm" data-bs-toggle="dropdown"
aria-expanded="false" aria-label="{% translate 'More actions' %}">
<i class="fa-solid fa-ellipsis-vertical fa-fw"></i>
</button>
<ul class="dropdown-menu menu">
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_edit' %}" hx-target="#generic-offcanvas"
hx-include=".transaction">
<i class="fa-solid fa-pencil fa-fw me-3"></i>{% translate 'Edit' %}
</a>
</li>
<hr class="my-1 hr">
{% include 'includes/transactions_bulk_actions.html' %}
<hr class="my-1 hr">
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_clone' %}" hx-include=".transaction">
<i class="fa-solid fa-clone fa-fw me-3"></i>{% translate 'Duplicate' %}
</a>
</li>
<hr class="my-1 hr">
<li>
<a class="cursor-pointer text-error" hx-get="{% url 'transactions_bulk_delete' %}" hx-include=".transaction"
hx-trigger="confirmed" data-bypass-on-ctrl="true"
data-title="{% translate "Are you sure?" %}" data-text="{% translate "You won't be able to revert this!" %}"
data-confirm-text="{% translate "Yes, delete them!" %}" _="install prompt_swal">
<i class="fa-solid fa-trash fa-fw me-3"></i>{% translate 'Delete' %}
</a>
</li>
</ul>
</div>
<div class="divider divider-horizontal m-0 max-sm:hidden"></div>
<div class="join" _="on selected_transactions_updated from #actions-bar
set realTotal to math.bignumber(0)
set flatTotal to math.bignumber(0)
@@ -127,8 +152,8 @@
writeText(original_value) on navigator.clipboard
put '{% translate "copied!" %}' into #real-total-front's innerText wait 1s put original_value
into #real-total-front's innerText end">
<i class="fa-solid fa-plus fa-fw me-md-2"></i>
<span class="hidden md:inline-block" id="real-total-front">0</span>
<i class="fa-solid fa-plus fa-fw sm:me-2"></i>
<span class="hidden sm:inline-block" id="real-total-front">0</span>
</button>
<div>
<button class="join-item btn btn-sm btn-secondary" type="button" data-bs-toggle="dropdown"
@@ -0,0 +1,35 @@
{% load i18n %}
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_unpay' %}" hx-include=".transaction">
<i class="fa-regular fa-circle text-red-400 fa-fw me-3"></i>{% translate 'Mark as unpaid' %}
</a>
</li>
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_pay' %}" hx-include=".transaction">
<i class="fa-regular fa-circle-check text-green-400 fa-fw me-3"></i>{% translate 'Mark as paid' %}
</a>
</li>
<hr class="my-1 hr">
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_mute' %}" hx-include=".transaction">
<i class="fa-solid fa-eye-slash fa-fw me-3"></i>{% translate 'Hide from summaries' %}
</a>
</li>
<hr class="my-1 hr">
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_change_month' change_type='previous' %}"
hx-include=".transaction">
<i class="fa-solid fa-calendar-minus fa-fw me-3"></i>{% translate 'Move to previous month' %}
</a>
</li>
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_change_month' change_type='next' %}"
hx-include=".transaction">
<i class="fa-solid fa-calendar-plus fa-fw me-3"></i>{% translate 'Move to next month' %}
</a>
</li>
<li>
<a class="cursor-pointer" hx-get="{% url 'transactions_bulk_move_to_today' %}" hx-include=".transaction">
<i class="fa-solid fa-calendar-day fa-fw me-3"></i>{% translate 'Move to today' %}
</a>
</li>
@@ -283,8 +283,16 @@
{% endif %}
{% endif %}
</div>
{# Breakdown, e.g. fees and taxes inside a contribution #}
{% with subs=tx.sub_transactions.all %}{% if subs %}
<ul class="mt-1 ps-2 border-s border-base-300 text-xs text-base-content/60">
{% for sub in subs %}
<li class="flex justify-between gap-3"><span>{{ sub.name }}</span><span class="tabular-nums whitespace-nowrap"><c-amount.display :amount="sub.amount" :prefix="a.prefix" :suffix="a.suffix" :decimal_places="a.decimal_places" divless></c-amount.display></span></li>
{% endfor %}
</ul>
{% endif %}{% endwith %}
</td>
<td class="text-end tabular-nums whitespace-nowrap">
<td class="text-end tabular-nums whitespace-nowrap align-top">
<c-amount.display :amount="tx.amount" :prefix="a.prefix" :suffix="a.suffix" :decimal_places="a.decimal_places" color="{% if tx.type == 'IN' %}green{% else %}red{% endif %}" divless></c-amount.display>
{# What the other side paid beats a rate conversion, so it's shown first #}
{% if p and p.account.currency != a %}
@@ -0,0 +1,14 @@
{% load i18n %}
<div class="sub-row" {% if sub.DELETE.value %}hidden{% endif %}>
{{ sub.id }}
<input type="checkbox" name="{{ sub.DELETE.html_name }}" class="hidden" {% if sub.DELETE.value %}checked{% endif %}>
<div class="join w-full">
{{ sub.name }}
{{ sub.amount }}
<button type="button" class="btn btn-soft btn-error join-item" @click="remove($el.closest('.sub-row'))"
aria-label="{% translate 'Remove' %}"><i class="fa-solid fa-xmark fa-fw"></i></button>
</div>
{% for error in sub.non_field_errors %}<div class="text-error text-sm">{{ error }}</div>{% endfor %}
{% for error in sub.name.errors %}<div class="text-error text-sm">{{ error }}</div>{% endfor %}
{% for error in sub.amount.errors %}<div class="text-error text-sm">{{ error }}</div>{% endfor %}
</div>
@@ -0,0 +1,58 @@
{% load i18n formats %}
{% with formset=form.sub_transactions %}
{# The amount is the sum of these rows, so it's hidden while there are any. #}
{# Transfers don't take them; `type` comes from the form's _type_aware scope when it has one. #}
<div class="fieldset"
x-data="{
count: 0,
total: '',
get transfer() { return this.type === 'TR' },
recalc() {
const rows = [...$refs.rows.querySelectorAll('.sub-row:not([hidden])')];
this.count = rows.length;
const sum = rows.reduce((acc, row) => {
const raw = row.querySelector('[name$=-amount]').value
.replaceAll('{% get_thousand_separator %}', '').replace('{% get_decimal_separator %}', '.');
return acc + (parseFloat(raw) || 0);
}, 0);
this.total = sum.toLocaleString('en-US', {maximumFractionDigits: 20}).replaceAll(',', ' ').replace('.', '{% get_decimal_separator %}').replaceAll(' ', '{% get_thousand_separator %}');
document.getElementById('div_id_{{ form.sub_amount_field }}').hidden = this.count > 0 && !this.transfer;
},
add() {
const total = $refs.rows.parentElement.querySelector('[name=sub-TOTAL_FORMS]');
$refs.rows.insertAdjacentHTML('beforeend', $refs.tpl.innerHTML.replaceAll('__prefix__', total.value));
total.value = +total.value + 1;
this.$nextTick(() => { this.recalc(); $refs.rows.lastElementChild.querySelector('input').focus(); });
},
remove(row) {
row.querySelector('[name$=-DELETE]').checked = true;
row.hidden = true;
this.recalc();
},
}"
x-show="!transfer"
x-effect="transfer; recalc()"
@input="recalc()">
{{ formset.management_form }}
{% for error in formset.non_form_errors %}<div class="text-error text-sm mb-2">{{ error }}</div>{% endfor %}
<span class="fieldset-legend" x-show="count > 0" x-cloak>{% translate 'Sub-transactions' %}</span>
<div x-ref="rows" class="flex flex-col gap-2">
{% for sub in formset %}
{% include "transactions/widgets/sub_transaction_row.html" with sub=sub %}
{% endfor %}
</div>
<template x-ref="tpl">
{% include "transactions/widgets/sub_transaction_row.html" with sub=formset.empty_form %}
</template>
<div class="flex items-center justify-between gap-2">
<button type="button" class="btn btn-ghost btn-sm" @click="add()">
<i class="fa-solid fa-plus fa-fw"></i>{% translate 'Add sub-transaction' %}
</button>
<span class="text-sm tabular-nums" x-show="count > 0" x-cloak>{% translate 'Total' %}: <span class="font-semibold" x-text="total"></span></span>
</div>
</div>
{% endwith %}
+18 -4
View File
@@ -113,18 +113,32 @@ function isMobile() {
// swaps the body: AirDatepicker then rebuilds the container, but keeps the old
// overlay, which is left detached and can't receive the clicks that close a picker.
let mobileOverlay = null;
// The container AirDatepicker opens every picker into (its own reference, not a lookup by
// id: a history restore brings back lifeless copies of it from htmx's snapshot).
let globalContainer = null;
function createAirDatepicker(element, opts) {
const datepicker = new AirDatepicker(element, opts);
mobileOverlay ??= document.querySelector('.air-datepicker-overlay');
const container = document.getElementById(AirDatepicker.defaultGlobalContainerId);
if (mobileOverlay && !mobileOverlay.isConnected && container) {
globalContainer = datepicker.$container;
mobileOverlay ??= globalContainer.querySelector('.air-datepicker-overlay');
if (mobileOverlay && !mobileOverlay.isConnected) {
mobileOverlay.classList.remove('-active-'); // its picker was swapped out while open
container.appendChild(mobileOverlay);
globalContainer.appendChild(mobileOverlay);
}
return datepicker;
}
// Pickers kept by hx-preserve aren't recreated, so nothing makes AirDatepicker rebuild
// the container the swap removed: put it back, and drop any snapshot copies of it.
// Runs after htmx:load, so pickers created by this swap have already set globalContainer.
document.addEventListener('htmx:afterSwap', () => {
if (!globalContainer) return;
document.querySelectorAll(`#${AirDatepicker.defaultGlobalContainerId}`).forEach(c => {
if (c !== globalContainer) c.remove();
});
if (!globalContainer.isConnected) document.body.appendChild(globalContainer);
});
window.DatePicker = async function createDynamicDatePicker(element) {
let todayButton = {
content: element.dataset.nowButtonTxt,
Generated
+3 -3
View File
@@ -1069,11 +1069,11 @@ wheels = [
[[package]]
name = "soupsieve"
version = "2.9"
version = "4.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/80/f1/93422647dd7e461f23d254e6b2bfa687a85b53aeb4903fcdbb74474d4584/soupsieve-2.9.tar.gz", hash = "sha256:acee8417325c5653e1377dc31eccad59eb82cbc65942afe6174c53b3aaad63fc", size = 122122, upload-time = "2026-07-19T01:35:18.425Z" }
sdist = { url = "https://files.pythonhosted.org/packages/7d/5e/19b7c5d20bc2f226c44f33a9d9aab9740efed7555b96e656231fd564e514/soupsieve-4.0.tar.gz", hash = "sha256:ccd6470b256394ac44b08b86fd94b30a17d335a5335c8a3d15565f7b03d3c8cf", size = 151929, upload-time = "2026-11-03T14:28:55.388Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/7b/d6/3185ab5ad1280319b31986898f3206dd7227cd75e293d4dba2a5e6bf27a0/soupsieve-2.9-py3-none-any.whl", hash = "sha256:a2b2c76d67df2382d245409fd71e321a571717e58463efa32ace87dcadac2c12", size = 37387, upload-time = "2026-07-19T01:35:17.106Z" },
{ url = "https://files.pythonhosted.org/packages/4f/18/d24df2f733ee0655c58717d51add4118a70e64692d0e47d403b9aac4cf98/soupsieve-4.0-py3-none-any.whl", hash = "sha256:5e7494bfce90e06676cfb4c5c2cf22243e98e5cf24646bb1ecdda46d318550a0", size = 50158, upload-time = "2026-11-03T14:28:53.988Z" },
]
[[package]]