feat: split a transaction across multiple categories

Один чек часто смешивает несколько категорий трат (гипермаркет: часть — продукты,
часть — бытовая химия). Раньше такую транзакцию приходилось огрублять до одной
категории или дробить вручную на несколько записей. Теперь у транзакции есть
второй режим: 2+ доли (TransactionSplit) с суммами по разным категориям, которые
обязаны в точности складываться в сумму транзакции.

- Новая модель TransactionSplit + миграция.
- split_rule_violation() проверяет инварианты на создании и редактировании.
- category_rollup.py — общий helper, которым теперь пользуются Dashboard, отчёт
  по категориям и бюджеты, учитывая доли сплитов наравне с обычными транзакциями.
- Фильтр по категории в списке транзакций находит и сплит-транзакции.
- Сплиты попадают в полный бэкап/восстановление БД.
- 13 новых backend-тестов.
- Фронтенд: переключатель «Разбить на несколько категорий» в форме транзакции
  с повторяемыми строками и индикатором остатка суммы; строка транзакции в
  списке показывает все категории сплита.
This commit is contained in:
ZProger
2026-08-30 18:42:13 +03:00
parent b045d378f0
commit 0134cdb6bf
20 changed files with 1008 additions and 144 deletions

View File

@@ -7,7 +7,7 @@ from app.models.goal import Goal, GoalContribution
from app.models.recurring import RecurringTransaction
from app.models.settings import AppSettings
from app.models.tag import Tag
from app.models.transaction import Transaction
from app.models.transaction import Transaction, TransactionSplit
__all__ = [
"Account",
@@ -24,4 +24,5 @@ __all__ = [
"RecurringTransaction",
"Tag",
"Transaction",
"TransactionSplit",
]

View File

@@ -35,3 +35,32 @@ class Transaction(Base, TimestampMixin):
transfer_account: Mapped["Account | None"] = relationship(foreign_keys=[transfer_account_id])
category: Mapped["Category | None"] = relationship(back_populates="transactions")
tags: Mapped[list["Tag"]] = relationship(secondary=transaction_tags, back_populates="transactions")
splits: Mapped[list["TransactionSplit"]] = relationship(
back_populates="transaction", cascade="all, delete-orphan", order_by="TransactionSplit.id"
)
class TransactionSplit(Base):
"""One category's slice of a transaction whose amount is divided across
several categories (one receipt, several kinds of goods) — an
alternative to Transaction.category_id, not an addition to it: a split
transaction has category_id=NULL and two or more of these instead, and
their amounts must add up to the parent's amount exactly (see
schemas/transaction.py's split_rule_violation).
category_id is nullable + SET NULL, same as Transaction.category_id
itself — deleting a category must not break *reading* a split that used
to point at it, only creating/editing one requires a live category (see
routes/transactions.py, and the same lesson already applied to
transfer_account_id)."""
__tablename__ = "transaction_splits"
id: Mapped[int] = mapped_column(primary_key=True)
transaction_id: Mapped[int] = mapped_column(ForeignKey("transactions.id", ondelete="CASCADE"), nullable=False)
category_id: Mapped[int | None] = mapped_column(ForeignKey("categories.id", ondelete="SET NULL"), nullable=True)
amount: Mapped[Numeric] = mapped_column(Numeric(14, 2), nullable=False)
note: Mapped[str | None] = mapped_column(String(200), nullable=True)
transaction: Mapped["Transaction"] = relationship(back_populates="splits")
category: Mapped["Category | None"] = relationship()