Open-source personal finance manager. Self-hosted, privacy-first.
feat(loans): split recorded mortgage payments (#1288)
eilandnl75103b0457d7
diff --git a/backend/alembic/versions/101_mortgage_payment_allocations.py b/backend/alembic/versions/101_mortgage_payment_allocations.pynew file mode 100644index 00000000..5b348935--- /dev/null+++ b/backend/alembic/versions/101_mortgage_payment_allocations.py@@ -0,0 +1,112 @@+"""store recorded mortgage payment breakdowns++Revision ID: 101+Revises: 100+"""++import sqlalchemy as sa+from sqlalchemy.dialects import postgresql++from alembic import op++revision = "101"+down_revision = "100"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ if "mortgage_payment_allocations" not in sa.inspect(op.get_bind()).get_table_names():+ op.create_table(+ "mortgage_payment_allocations",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column(+ "workspace_id",+ postgresql.UUID(as_uuid=True),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column(+ "payment_transaction_id",+ postgresql.UUID(as_uuid=True),+ sa.ForeignKey("transactions.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column(+ "loan_account_id",+ postgresql.UUID(as_uuid=True),+ sa.ForeignKey("accounts.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("principal_amount", sa.Numeric(15, 2), nullable=False),+ sa.Column("interest_amount", sa.Numeric(15, 2), nullable=False),+ sa.Column(+ "loan_transaction_id",+ postgresql.UUID(as_uuid=True),+ sa.ForeignKey("transactions.id", ondelete="CASCADE"),+ nullable=True,+ unique=True,+ ),+ sa.CheckConstraint(+ "principal_amount >= 0", name="ck_mortgage_payment_principal_nonnegative"+ ),+ sa.CheckConstraint(+ "interest_amount >= 0", name="ck_mortgage_payment_interest_nonnegative"+ ),+ sa.UniqueConstraint(+ "payment_transaction_id", "loan_account_id", name="uq_mortgage_payment_loan"+ ),+ )++ indexes = {+ index["name"]+ for index in sa.inspect(op.get_bind()).get_indexes("mortgage_payment_allocations")+ }+ for index_name, column in (+ ("ix_mortgage_payment_allocations_workspace_id", "workspace_id"),+ ("ix_mortgage_payment_allocations_payment_transaction_id", "payment_transaction_id"),+ ("ix_mortgage_payment_allocations_loan_account_id", "loan_account_id"),+ ):+ if index_name not in indexes:+ op.create_index(index_name, "mortgage_payment_allocations", [column])++ # A bank payment can be deleted from many places (single and bulk delete,+ # account or user deletion, provider sync). Deleting it cascades to its+ # breakdown rows, and each of those takes its principal entry with it, or+ # the loan would stay reduced. AFTER DELETE on the breakdown table, because+ # a BEFORE trigger on transactions fails when one statement deletes both+ # the payment and its principal entry.+ op.execute("""+ CREATE OR REPLACE FUNCTION delete_mortgage_principal_entry() RETURNS trigger+ LANGUAGE plpgsql AS $$+ BEGIN+ DELETE FROM transactions+ WHERE id = OLD.loan_transaction_id+ AND source = 'mortgage_principal';+ RETURN NULL;+ END;+ $$;+ """)+ op.execute("""+ DO $$+ BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_trigger+ WHERE tgname = 'trg_delete_mortgage_principal_entry'+ AND tgrelid = 'mortgage_payment_allocations'::regclass+ AND NOT tgisinternal+ ) THEN+ CREATE TRIGGER trg_delete_mortgage_principal_entry+ AFTER DELETE ON mortgage_payment_allocations+ FOR EACH ROW WHEN (OLD.loan_transaction_id IS NOT NULL)+ EXECUTE FUNCTION delete_mortgage_principal_entry();+ END IF;+ END;+ $$;+ """)+++def downgrade() -> None:+ # This migration also upgrades databases from the legacy combined revision.+ # Do not remove mortgage data when rolling back the version marker.+ passdiff --git a/backend/app/api/mortgage_payments.py b/backend/app/api/mortgage_payments.pynew file mode 100644index 00000000..3743263b--- /dev/null+++ b/backend/app/api/mortgage_payments.py@@ -0,0 +1,243 @@+import uuid+from decimal import Decimal++from fastapi import APIRouter, Depends, HTTPException, status+from pydantic import BaseModel, Field, model_validator+from sqlalchemy import delete, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.database import get_async_session+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)+from app.models.account import Account+from app.models.category import Category+from app.models.mortgage_payment_allocation import (+ MORTGAGE_PRINCIPAL_SOURCE,+ MortgagePaymentAllocation,+)+from app.models.transaction import Transaction+from app.services import mortgage_service++router = APIRouter(prefix="/api/mortgage-payments", tags=["mortgage payments"])+++class AllocationInput(BaseModel):+ loan_account_id: uuid.UUID+ principal_amount: Decimal = Field(ge=0, decimal_places=2)+ interest_amount: Decimal = Field(ge=0, decimal_places=2)+++class AllocationReplace(BaseModel):+ allocations: list[AllocationInput] = Field(min_length=1)++ @model_validator(mode="after")+ def unique_loan_parts(self):+ ids = [row.loan_account_id for row in self.allocations]+ if len(ids) != len(set(ids)):+ raise ValueError("Each loan part can only appear once")+ return self+++def _percentage(part: Decimal, total: Decimal) -> float:+ return float(part / total * 100) if total else 0.0+++def _allocation_read(row: MortgagePaymentAllocation, loan: Account) -> dict:+ total = row.principal_amount + row.interest_amount+ bank_managed = loan.connection_id is not None+ return {+ "loan_account_id": row.loan_account_id,+ "loan_name": loan.display_name or loan.name,+ "principal_amount": float(row.principal_amount),+ "interest_amount": float(row.interest_amount),+ "payment_amount": float(total),+ "principal_percentage": _percentage(row.principal_amount, total),+ "interest_percentage": _percentage(row.interest_amount, total),+ # The bank reports a connected loan's balance itself, so its principal+ # is never posted here; that is not the same as a pre-snapshot payment.+ "bank_managed": bank_managed,+ "historical": (+ not bank_managed and row.principal_amount > 0 and row.loan_transaction_id is None+ ),+ }+++def _payment_read(+ payment: Transaction,+ payment_account: Account,+ rows: list[tuple[MortgagePaymentAllocation, Account]],+) -> dict:+ principal_total = sum((row.principal_amount for row, _ in rows), Decimal("0.00"))+ interest_total = sum((row.interest_amount for row, _ in rows), Decimal("0.00"))+ return {+ "payment_transaction_id": payment.id,+ "payment_amount": float(payment.amount),+ "currency": payment.currency,+ "payment_account_name": payment_account.display_name or payment_account.name,+ "allocations": [_allocation_read(row, loan) for row, loan in rows],+ "principal_total": float(principal_total),+ "interest_total": float(interest_total),+ "principal_percentage": _percentage(principal_total, payment.amount),+ "interest_percentage": _percentage(interest_total, payment.amount),+ }+++async def _get_payment(+ session: AsyncSession,+ payment_id: uuid.UUID,+ workspace_id: uuid.UUID,+ *,+ lock: bool = False,+):+ query = (+ select(Transaction, Account)+ .join(Account, Transaction.account_id == Account.id)+ .where(Transaction.id == payment_id, Transaction.workspace_id == workspace_id)+ )+ if lock:+ # Replacing a breakdown deletes and re-inserts its rows; two saves of+ # the same payment must take turns, or both insert the same loan part.+ query = query.with_for_update(of=Transaction)+ result = await session.execute(query)+ return result.one_or_none()+++async def _delete_allocations(+ session: AsyncSession, payment_id: uuid.UUID, workspace_id: uuid.UUID+) -> None:+ existing = await session.execute(+ select(MortgagePaymentAllocation.loan_transaction_id).where(+ MortgagePaymentAllocation.payment_transaction_id == payment_id,+ MortgagePaymentAllocation.workspace_id == workspace_id,+ )+ )+ loan_transaction_ids = [row[0] for row in existing.all() if row[0] is not None]+ await session.execute(+ delete(MortgagePaymentAllocation).where(+ MortgagePaymentAllocation.payment_transaction_id == payment_id,+ MortgagePaymentAllocation.workspace_id == workspace_id,+ )+ )+ if loan_transaction_ids:+ await session.execute(+ delete(Transaction).where(+ Transaction.id.in_(loan_transaction_ids),+ Transaction.source == MORTGAGE_PRINCIPAL_SOURCE,+ )+ )+ await session.flush()++[email protected]("/{payment_id}")+async def get_mortgage_payment_allocations(+ payment_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ payment_row = await _get_payment(session, payment_id, ctx.workspace.id)+ if payment_row is None:+ raise HTTPException(404, "Payment transaction not found")+ payment, payment_account = payment_row+ result = await session.execute(+ select(MortgagePaymentAllocation, Account)+ .join(Account, MortgagePaymentAllocation.loan_account_id == Account.id)+ .where(+ MortgagePaymentAllocation.payment_transaction_id == payment_id,+ MortgagePaymentAllocation.workspace_id == ctx.workspace.id,+ )+ .order_by(Account.name)+ )+ rows = [(allocation, loan) for allocation, loan in result.all()]+ return _payment_read(payment, payment_account, rows)++[email protected]("/{payment_id}")+async def replace_mortgage_payment_allocations(+ payment_id: uuid.UUID,+ data: AllocationReplace,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ payment_row = await _get_payment(session, payment_id, ctx.workspace.id, lock=True)+ if payment_row is None:+ raise HTTPException(404, "Payment transaction not found")+ payment, payment_account = payment_row+ if payment.type != "debit" or payment_account.type == "loan" or payment.amount <= 0:+ raise HTTPException(400, "Mortgage allocations require a debit from a non-loan account")+ if payment.status != "posted":+ raise HTTPException(400, "Mortgage allocations require a posted payment")+ if payment.is_ignored:+ raise HTTPException(400, "An ignored payment cannot have a mortgage breakdown")+ if payment.category_id is not None and await session.scalar(+ select(Category.is_ignored).where(Category.id == payment.category_id)+ ):+ raise HTTPException(400, "A payment in an ignored category cannot have a mortgage breakdown")+ if payment.transfer_pair_id is not None:+ raise HTTPException(400, "A transfer to another account cannot be a mortgage payment")+ total = sum(+ (row.principal_amount + row.interest_amount for row in data.allocations),+ Decimal("0.00"),+ )+ if total != payment.amount:+ raise HTTPException(400, "Principal and interest must add up to the payment amount")++ ids = [row.loan_account_id for row in data.allocations]+ result = await session.execute(+ select(Account).where(+ Account.id.in_(ids),+ Account.workspace_id == ctx.workspace.id,+ Account.type == "loan",+ )+ )+ loans = {account.id: account for account in result.scalars().all()}+ if len(loans) != len(ids):+ raise HTTPException(400, "Every linked account must be a loan in this workspace")+ if any(account.secured_asset_id is None for account in loans.values()):+ raise HTTPException(400, "Every loan part must be linked to a property")+ if any(account.currency != payment.currency for account in loans.values()):+ raise HTTPException(400, "Payment and loan parts must use the same currency")++ await _delete_allocations(session, payment_id, ctx.workspace.id)++ allocation_rows: list[tuple[MortgagePaymentAllocation, Account]] = []+ for item in data.allocations:+ loan = loans[item.loan_account_id]+ loan_tx_id = None+ opening_date = await mortgage_service.opening_balance_date(session, loan)+ if mortgage_service.posts_principal(+ loan, item.principal_amount, payment.date, opening_date+ ):+ loan_tx = mortgage_service.principal_entry(+ loan, ctx.user_id, payment, item.principal_amount+ )+ session.add(loan_tx)+ await session.flush()+ loan_tx_id = loan_tx.id+ allocation = MortgagePaymentAllocation(+ workspace_id=ctx.workspace.id,+ payment_transaction_id=payment_id,+ loan_account_id=loan.id,+ principal_amount=item.principal_amount,+ interest_amount=item.interest_amount,+ loan_transaction_id=loan_tx_id,+ )+ session.add(allocation)+ allocation_rows.append((allocation, loan))++ await session.commit()+ return _payment_read(payment, payment_account, allocation_rows)++[email protected]("/{payment_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_mortgage_payment_allocations(+ payment_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ if await _get_payment(session, payment_id, ctx.workspace.id, lock=True) is None:+ raise HTTPException(404, "Payment transaction not found")+ await _delete_allocations(session, payment_id, ctx.workspace.id)+ await session.commit()diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex f501c4cd..af032744 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -583,9 +583,12 @@ async def toggle_ignore_transaction(ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),):- transaction = await transaction_service.toggle_ignore_transaction(- session, transaction_id, ctx.workspace.id- )+ try:+ transaction = await transaction_service.toggle_ignore_transaction(+ session, transaction_id, ctx.workspace.id+ )+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not transaction:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")primary_currency = ctx.user.primary_currency@@ -637,9 +640,12 @@ async def delete_transaction(ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),):- deleted = await transaction_service.delete_transaction(- session, transaction_id, ctx.workspace.id, apply_to- )+ try:+ deleted = await transaction_service.delete_transaction(+ session, transaction_id, ctx.workspace.id, apply_to+ )+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")@@ -650,7 +656,10 @@ async def bulk_delete_transactions(ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),):- deleted_count = await transaction_service.bulk_delete_transactions(- session, ctx.workspace.id, data.transaction_ids- )+ try:+ deleted_count = await transaction_service.bulk_delete_transactions(+ session, ctx.workspace.id, data.transaction_ids+ )+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))return {"deleted": deleted_count}diff --git a/backend/app/main.py b/backend/app/main.pyindex bad681ea..23a37de2 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -37,6 +37,7 @@ from app.api.fiscal import router as fiscal_routerfrom app.api.invoice_attachments import router as invoice_attachments_routerfrom app.api.invoice_schedules import router as invoice_schedules_routerfrom app.api.invoices import router as invoices_router+from app.api.mortgage_payments import router as mortgage_payments_routerfrom app.api.products import router as products_routerfrom app.api.public_invoices import router as public_invoices_routerfrom app.api.payees import router as payees_router@@ -175,6 +176,7 @@ app.include_router(category_groups_router)app.include_router(rules_router)app.include_router(reconciliation_router)app.include_router(transactions_router)+app.include_router(mortgage_payments_router)app.include_router(import_router)app.include_router(import_logs_router)app.include_router(accounts_router)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 696c275f..0a60cdbc 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -35,6 +35,7 @@ from app.models.invoice import ()from app.models.invoice_attachment import InvoiceAttachmentfrom app.models.invoice_schedule import InvoiceSchedule, InvoiceScheduleTerm+from app.models.mortgage_payment_allocation import MortgagePaymentAllocationfrom app.models.product import Product, ProductPricefrom app.models.reconciliation import (ReconciliationEvent,@@ -89,6 +90,7 @@ __all__ = ["InvoiceInstallment","InvoiceSchedule","InvoiceScheduleTerm",+ "MortgagePaymentAllocation","Product","ProductPrice","ReconciliationEvent",diff --git a/backend/app/models/mortgage_payment_allocation.py b/backend/app/models/mortgage_payment_allocation.pynew file mode 100644index 00000000..9b32a107--- /dev/null+++ b/backend/app/models/mortgage_payment_allocation.py@@ -0,0 +1,112 @@+import uuid+from decimal import Decimal+from typing import Optional++from sqlalchemy import CheckConstraint, ForeignKey, Numeric, UniqueConstraint, event+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.core.database import Base++# Transaction.source of the principal entry a breakdown posts to its loan. The+# entry is owned by the breakdown: edit or remove it through the bank payment.+MORTGAGE_PRINCIPAL_SOURCE = "mortgage_principal"+++class MortgagePaymentAllocation(Base):+ """Actual principal and interest components for one loan in a payment."""++ __tablename__ = "mortgage_payment_allocations"+ __table_args__ = (+ UniqueConstraint(+ "payment_transaction_id", "loan_account_id", name="uq_mortgage_payment_loan"+ ),+ CheckConstraint("principal_amount >= 0", name="ck_mortgage_payment_principal_nonnegative"),+ CheckConstraint("interest_amount >= 0", name="ck_mortgage_payment_interest_nonnegative"),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )+ payment_transaction_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("transactions.id", ondelete="CASCADE"),+ index=True,+ )+ loan_account_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), index=True+ )+ principal_amount: Mapped[Decimal] = mapped_column(Numeric(15, 2))+ interest_amount: Mapped[Decimal] = mapped_column(Numeric(15, 2))+ loan_transaction_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("transactions.id", ondelete="CASCADE"),+ unique=True,+ nullable=True,+ )+++++def _install_principal_cleanup(target, connection, **kw) -> None:+ """Delete a principal entry whenever its breakdown row goes.++ A bank payment can be deleted from many places (single and bulk delete,+ account or user deletion, provider sync). Deleting it cascades to its+ breakdown rows, and each of those takes its principal entry with it, or the+ loan would stay reduced. Migration 097 installs the PostgreSQL trigger on+ existing databases; this keeps schemas built with metadata.create_all+ (tests) equivalent.++ PostgreSQL uses an AFTER trigger on the breakdown table: a BEFORE trigger+ on transactions would fail when one statement deletes both the payment and+ its principal entry. SQLite test databases do not enforce foreign keys, so+ there the trigger follows the payment row itself.+ """+ if connection.dialect.name == "postgresql":+ translate = connection.get_execution_options().get("schema_translate_map") or {}+ schema = translate.get(None)+ prefix = f'"{schema}".' if schema else ""+ connection.exec_driver_sql(+ f"""+ CREATE OR REPLACE FUNCTION {prefix}delete_mortgage_principal_entry()+ RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN+ DELETE FROM {prefix}transactions+ WHERE id = OLD.loan_transaction_id+ AND source = '{MORTGAGE_PRINCIPAL_SOURCE}';+ RETURN NULL;+ END;+ $$+ """+ )+ connection.exec_driver_sql(+ f"""+ CREATE TRIGGER trg_delete_mortgage_principal_entry+ AFTER DELETE ON {prefix}mortgage_payment_allocations+ FOR EACH ROW WHEN (OLD.loan_transaction_id IS NOT NULL)+ EXECUTE FUNCTION {prefix}delete_mortgage_principal_entry()+ """+ )+ elif connection.dialect.name == "sqlite":+ connection.exec_driver_sql(+ f"""+ CREATE TRIGGER IF NOT EXISTS trg_delete_mortgage_principal_entry+ AFTER DELETE ON transactions+ FOR EACH ROW BEGIN+ DELETE FROM transactions+ WHERE source = '{MORTGAGE_PRINCIPAL_SOURCE}'+ AND id IN (+ SELECT loan_transaction_id+ FROM mortgage_payment_allocations+ WHERE payment_transaction_id = OLD.id+ );+ DELETE FROM mortgage_payment_allocations+ WHERE payment_transaction_id = OLD.id OR loan_transaction_id = OLD.id;+ END+ """+ )+++event.listen(MortgagePaymentAllocation.__table__, "after_create", _install_principal_cleanup)diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex 644d493b..cc9a4c62 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -22,6 +22,7 @@ from app.models.account import Accountfrom app.models.asset import LOAN_COLLATERAL_TYPES, Assetfrom app.models.bank_connection import BankConnectionfrom app.models.credit_card_bill import CreditCardBill+from app.models.mortgage_payment_allocation import MortgagePaymentAllocationfrom app.models.transaction import Transactionfrom app.schemas.account import AccountCreate, AccountUpdate, LoanBalanceUpdatefrom app.services._query_filters import (@@ -34,7 +35,7 @@ from app.services._query_filters import (is_not_ignored,reporting_date_col,)-from app.services import loan_schedule+from app.services import loan_schedule, mortgage_servicefrom app.services.credit_card_service import (apply_effective_date,cc_cycle_bill_due_dates,@@ -60,16 +61,18 @@ def get_account_name(account: Account) -> str:return account.display_name or account.name-def _simplefin_to_internal_balance(provider: str, account_type: str, balance: Decimal) -> Decimal:- """Normalize a SimpleFIN balance to Securo's positive-for-debt convention.+LIABILITY_ACCOUNT_TYPES = frozenset({"credit_card", "loan"})- SimpleFIN reports a credit card's balance as negative debt and exposes no- account type, so the provider stores it raw and labels every account- "checking". Pluggy/Enable report card debt as a positive number, which is- the convention every downstream site (serialize_account, _account_balance_at,- sync_opening_balance_for_connected_account, ...) assumes. Flip SimpleFIN card- balances to match so those sites stay provider-agnostic.++def _provider_to_internal_balance(provider: str, account_type: str, balance: Decimal) -> Decimal:+ """Normalize provider balances to positive-for-debt for liabilities.++ A loan's balance is always debt. SimpleFIN reports credit card debt as a+ negative value and exposes no account type, so only that combination needs+ a sign flip."""+ if account_type == "loan":+ return abs(balance)if provider == "simplefin" and account_type == "credit_card":return -balancereturn balance@@ -316,10 +319,10 @@ def serialize_account(open_bill_total: Optional[Decimal] = None,balance_date: Optional[_Date] = None,) -> dict:- # Connected CC: provider stores positive for debt → negate.+ # Connected credit cards and loans store positive for debt → negate.# Manual accounts: transaction math already gives correct sign.if acc.connection_id:- resolved_balance = float(acc.balance) * (-1 if acc.type == "credit_card" else 1)+ resolved_balance = float(acc.balance) * (-1 if acc.type in LIABILITY_ACCOUNT_TYPES else 1)else:resolved_balance = float(current_balance or 0)@@ -486,6 +489,8 @@ async def update_account(new_type = update_data.get("type", account.type)if account.connection_id is not None and new_type == "loan":raise ValueError("Bank-connected accounts cannot be loans yet")+ if account.type == "loan" and new_type != "loan" and await _has_mortgage_allocations(session, account):+ raise ValueError("Remove this loan's mortgage payment breakdowns before changing its type")# Switching between a loan and any other type flips what the balance means# (money held vs. money owed). That is safe for an account that only has# its opening balance; with real history it would silently reinterpret it.@@ -550,13 +555,13 @@ async def update_account(setattr(account, key, value)# SimpleFIN stores a card's balance with the raw provider sign (negative# for debt) under type="checking". When the user flips the type across- # the credit_card boundary, the downstream display sites start (or stop)+ # a liability boundary, the downstream display sites start (or stop)# applying the positive-for-debt negation, so the stored value must flip# too — otherwise the card double-counts. Mirror the ingestion-time- # normalization (_simplefin_to_internal_balance) here so the correction+ # normalization (_provider_to_internal_balance) here so the correction# is immediate, not deferred to the next sync. Load the provider via# session.get (identity-map hit, never a lazy-load that throws).- if old_type != new_type and "credit_card" in (old_type, new_type):+ if (old_type in LIABILITY_ACCOUNT_TYPES) != (new_type in LIABILITY_ACCOUNT_TYPES):conn = (await session.get(BankConnection, account.connection_id)if account.connection_id is not None@@ -564,6 +569,8 @@ async def update_account()if conn is not None and conn.provider == "simplefin":account.balance = -account.balance+ if new_type == "loan":+ account.balance = _provider_to_internal_balance("", "loan", account.balance)# If the override moves the account away from credit_card, drop any# stale card metadata so it isn't left half credit-card.if new_type != "credit_card":@@ -648,6 +655,10 @@ async def update_account(if cycle_fields_changed:await _recompute_effective_dates(session, account)+ if account.type == "loan" and ("balance" in update_data or balance_date):+ await session.flush()+ await mortgage_service.resync_principal_entries(session, account)+await session.commit()await session.refresh(account)return account@@ -670,6 +681,15 @@ async def _validate_secured_asset(raise ValueError("Linked asset must be a property or vehicle in the same workspace")+async def _has_mortgage_allocations(session: AsyncSession, account: Account) -> bool:+ linked = await session.scalar(+ select(MortgagePaymentAllocation.id)+ .where(MortgagePaymentAllocation.loan_account_id == account.id)+ .limit(1)+ )+ return linked is not None++async def _recompute_effective_dates(session: AsyncSession, account: Account) -> None:"""Recompute effective_date on every transaction in this account.@@ -711,8 +731,8 @@ async def sync_opening_balance_for_connected_account(# transaction amounts on a CC trends negative as debt accrues, so the target# we want SUM(signed txs) to hit is -balance. For every other account type# the target is simply the stored balance.- is_cc = account.type == "credit_card"- target = -account.balance if is_cc else account.balance+ is_liability = account.type in LIABILITY_ACCOUNT_TYPES+ target = -account.balance if is_liability else account.balanceeffective_amount = case((Transaction.currency == account.currency, Transaction.amount),@@ -809,6 +829,8 @@ async def delete_account(session: AsyncSession, account_id: uuid.UUID, workspace# Only allow deleting manual accountsif account.connection_id is not None:raise ValueError("Cannot delete bank-connected accounts")+ if await _has_mortgage_allocations(session, account):+ raise ValueError("Remove this loan's mortgage payment breakdowns before deleting it")# Clean up attachment files for all transactions in this accountfrom app.services.attachment_service import cleanup_attachment_files@@ -956,9 +978,9 @@ async def get_account_summary()current_balance = float(balance_result.scalar() or 0)- # Connected CC: provider balance is positive for debt → negate.- # Manual CC: transaction math already gives negative for debt.- if account.type == "credit_card" and account.connection_id:+ # Connected liabilities store positive for debt; transaction math already+ # gives a negative balance for manual accounts.+ if account.type in LIABILITY_ACCOUNT_TYPES and account.connection_id:current_balance = -current_balance# Bucketing date: for credit-card txs the user can override which cycle@@ -1459,7 +1481,7 @@ async def get_account_balance_history(if not date_to:date_to = today- sign = -1.0 if (account.type == "credit_card" and account.connection_id) else 1.0+ sign = -1.0 if (account.type in LIABILITY_ACCOUNT_TYPES and account.connection_id) else 1.0series = await _account_daily_balance_series(session, account_id, date_from, date_to, account.currency)diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex 600eb07a..9eb16d3e 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -42,7 +42,7 @@ from app.services import admin_servicefrom app.services import reconciliation_service, recurring_match_servicefrom app.services.text_similarity import token_overlapfrom app.services.account_service import (- _simplefin_to_internal_balance,+ _provider_to_internal_balance,sync_opening_balance_for_connected_account,)from app.services.asset_group_service import (@@ -2407,7 +2407,7 @@ async def sync_connection(# label; once the user overrides the type to credit_card the# downstream sites negate it, so store positive-for-debt to keep# them provider-agnostic and avoid double-counting.- account.balance = _simplefin_to_internal_balance(+ account.balance = _provider_to_internal_balance(connection.provider,account.type,_account_balance(acc_data, auto_invested_deducted),@@ -2466,7 +2466,11 @@ async def sync_connection(display_name=institution.name if institution else None,masked_number=acc_data.masked_number,type=acc_data.type,- balance=_account_balance(acc_data, auto_invested_deducted),+ balance=_provider_to_internal_balance(+ connection.provider,+ acc_data.type,+ _account_balance(acc_data, auto_invested_deducted),+ ),currency=acc_data.currency,credit_limit=acc_data.credit_limit if is_cc else None,statement_close_day=acc_data.statement_close_day if is_cc else None,diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex 1638f0fb..993604f8 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -1313,7 +1313,7 @@ async def _account_balance_at(if account.connection_id:# Start from the provider's authoritative current balancecurrent_bal = float(account.balance)- if account.type == "credit_card":+ if account.type in {"credit_card", "loan"}:current_bal = -current_bal# The provider number is the source of truth for the current balance,@@ -1458,7 +1458,7 @@ async def _total_balance_by_currency(for account in accounts:if account.connection_id:bal = float(account.balance)- if account.type == "credit_card":+ if account.type in {"credit_card", "loan"}:bal = -balif cutoff < today:bal -= connected_deltas.get(account.id, 0.0)diff --git a/backend/app/services/mortgage_service.py b/backend/app/services/mortgage_service.pynew file mode 100644index 00000000..ee3b2451--- /dev/null+++ b/backend/app/services/mortgage_service.py@@ -0,0 +1,98 @@+import uuid+from datetime import date+from typing import Optional++from sqlalchemy import select, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.mortgage_payment_allocation import (+ MORTGAGE_PRINCIPAL_SOURCE,+ MortgagePaymentAllocation,+)+from app.models.transaction import Transaction+from app.services.credit_card_service import apply_effective_date+++async def opening_balance_date(session: AsyncSession, loan: Account) -> Optional[date]:+ return await session.scalar(+ select(Transaction.date)+ .where(+ Transaction.account_id == loan.id,+ Transaction.workspace_id == loan.workspace_id,+ Transaction.source == "opening_balance",+ )+ .order_by(Transaction.date.desc())+ .limit(1)+ )+++def posts_principal(+ loan: Account, principal: object, payment_date: date, opening_date: Optional[date]+) -> bool:+ """Whether a breakdown's principal belongs in the loan's own ledger.++ A bank-connected loan's balance comes from the bank, which also books the+ repayment itself; posting principal here would count it twice. An opening+ balance is a snapshot of the loan at the end of that date, so a payment on+ or before it is already reflected in the balance.+ """+ if not principal or loan.connection_id is not None:+ return False+ return opening_date is None or payment_date > opening_date+++def principal_entry(+ loan: Account, user_id: uuid.UUID, payment: Transaction, principal+) -> Transaction:+ entry = Transaction(+ user_id=user_id,+ workspace_id=loan.workspace_id,+ account_id=loan.id,+ description=f"Principal repayment: {payment.description}",+ amount=principal,+ currency=loan.currency,+ date=payment.date,+ type="credit",+ status="posted",+ source=MORTGAGE_PRINCIPAL_SOURCE,+ exclude_from_pnl=True,+ )+ apply_effective_date(entry, loan)+ return entry+++async def resync_principal_entries(session: AsyncSession, loan: Account) -> None:+ """Re-apply the posting rule to every breakdown on this loan.++ Called when the loan's opening balance moves: a later snapshot already+ includes repayments made before it, and an earlier one no longer does.+ Does not commit; the caller owns the transaction boundary.+ """+ opening_date = await opening_balance_date(session, loan)+ rows = await session.execute(+ select(MortgagePaymentAllocation, Transaction)+ .join(Transaction, Transaction.id == MortgagePaymentAllocation.payment_transaction_id)+ .where(MortgagePaymentAllocation.loan_account_id == loan.id)+ )+ for allocation, payment in rows.all():+ wanted = posts_principal(loan, allocation.principal_amount, payment.date, opening_date)+ if wanted and allocation.loan_transaction_id is None:+ entry = principal_entry(loan, payment.user_id, payment, allocation.principal_amount)+ session.add(entry)+ await session.flush()+ allocation.loan_transaction_id = entry.id+ elif not wanted and allocation.loan_transaction_id is not None:+ entry_id = allocation.loan_transaction_id+ # Detach first: the principal entry's foreign key cascades to the+ # breakdown row, which has to survive.+ await session.execute(+ update(MortgagePaymentAllocation)+ .where(MortgagePaymentAllocation.id == allocation.id)+ .values(loan_transaction_id=None)+ )+ allocation.loan_transaction_id = None+ entry = await session.get(Transaction, entry_id)+ if entry is not None:+ await session.delete(entry)+ await session.flush()diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 90eafc7c..5466face 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -47,6 +47,7 @@ _ACCOUNT_TYPE_COLORS: dict[str, str] = {"checking": "#6366F1","savings": "#3B82F6","credit_card": "#F43F5E",+ "loan": "#F43F5E","investment": "#8B5CF6","wallet": "#F59E0B",}@@ -179,7 +180,7 @@ async def _net_worth_at(session, Decimal(str(abs(bal))), account.currency, primary_currency, cutoff)converted_val = float(converted)- if account.type == "credit_card" or bal < 0:+ if account.type in {"credit_card", "loan"} or bal < 0:liabilities_total += converted_valif converted_val > 0:composition.append(ReportCompositionItem(diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 56cb5544..1c7b4d43 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -15,6 +15,10 @@ from app.models.account import Accountfrom app.models.bank_connection import BankConnectionfrom app.models.category import Categoryfrom app.models.group import Group, GroupMember+from app.models.mortgage_payment_allocation import (+ MORTGAGE_PRINCIPAL_SOURCE,+ MortgagePaymentAllocation,+)from app.models.payee import Payeefrom app.schemas.transaction import (DescriptionSuggestion,@@ -785,9 +789,15 @@ async def get_transaction(session: AsyncSession,transaction_id: uuid.UUID,workspace_id: uuid.UUID,+ *,+ for_update: bool = False,) -> Optional[Transaction]:- """Fetch a single transaction by id, scoped to the workspace."""- result = await session.execute(+ """Fetch a single transaction by id, scoped to the workspace.++ ``for_update`` takes the row lock a mortgage breakdown save also takes, so+ a guard that checks for a breakdown and then edits the row cannot interleave+ with a breakdown being saved in between."""+ query = (select(Transaction).where(Transaction.id == transaction_id,@@ -799,6 +809,9 @@ async def get_transaction(selectinload(Transaction.splits),))+ if for_update:+ query = query.with_for_update(of=Transaction)+ result = await session.execute(query)transaction = result.scalar_one_or_none()if transaction:count_result = await session.execute(@@ -1267,6 +1280,7 @@ async def link_existing_as_transfer(Transaction.id.in_(transaction_ids),Transaction.workspace_id == workspace_id,)+ .with_for_update())txns = list(result.scalars().all())if len(txns) != 2:@@ -1275,6 +1289,7 @@ async def link_existing_as_transfer(for tx in txns:if tx.transfer_pair_id is not None:raise ValueError("Transaction is already part of a transfer")+ await _ensure_not_mortgage_linked(session, workspace_id, tx)if txns[0].account_id == txns[1].account_id:raise ValueError("Transactions must be in different accounts")@@ -1313,13 +1328,14 @@ async def create_transfer_counterpart("""from decimal import Decimal- anchor = await get_transaction(session, transaction_id, workspace_id)+ anchor = await get_transaction(session, transaction_id, workspace_id, for_update=True)if not anchor:raise ValueError("Transaction not found")if anchor.transfer_pair_id is not None:raise ValueError("Transaction is already part of a transfer")if anchor.account_id == to_account_id:raise ValueError("Counterpart must be in a different account")+ await _ensure_not_mortgage_linked(session, workspace_id, anchor)to_result = await session.execute(select(Account)@@ -1446,6 +1462,8 @@ async def _get_series_transactions(workspace_id: uuid.UUID,tx: Transaction,apply_to: str,+ *,+ for_update: bool = False,) -> list[Transaction]:"""Return the sibling installments of ``tx``'s series, ordered by number.@@ -1469,9 +1487,10 @@ async def _get_series_transactions(]if apply_to == "future":conditions.append(Transaction.installment_number >= tx.installment_number)- result = await session.execute(- select(Transaction).where(*conditions).order_by(Transaction.installment_number)- )+ query = select(Transaction).where(*conditions).order_by(Transaction.installment_number)+ if for_update:+ query = query.with_for_update()+ result = await session.execute(query)return list(result.scalars().all())@@ -1630,6 +1649,43 @@ async def _apply_update_to_row(await split_service.replace_splits(session, tx, splits_payload, user_id)+# Columns that decide how a transaction moves a balance. Changing any of them+# on a mortgage payment (or its generated principal entry) would leave the+# saved principal/interest breakdown out of step with the ledger.+_LEDGER_FIELDS = ("account_id", "amount", "currency", "date", "type", "status", "is_ignored")+++async def _has_mortgage_breakdown(+ session: AsyncSession, workspace_id: uuid.UUID, payment_id: uuid.UUID+) -> bool:+ linked = await session.scalar(+ select(MortgagePaymentAllocation.id)+ .where(+ MortgagePaymentAllocation.payment_transaction_id == payment_id,+ MortgagePaymentAllocation.workspace_id == workspace_id,+ )+ .limit(1)+ )+ return linked is not None+++async def _category_is_ignored(session: AsyncSession, category_id: Optional[uuid.UUID]) -> bool:+ if category_id is None:+ return False+ return bool(await session.scalar(select(Category.is_ignored).where(Category.id == category_id)))+++async def _ensure_not_mortgage_linked(+ session: AsyncSession, workspace_id: uuid.UUID, tx: Transaction+) -> None:+ """A payment with a breakdown already moves its principal to the loan, and+ the principal entry is that movement; neither can become a transfer too."""+ if tx.source == MORTGAGE_PRINCIPAL_SOURCE or await _has_mortgage_breakdown(+ session, workspace_id, tx.id+ ):+ raise ValueError("A mortgage payment with a breakdown cannot also be a transfer")++async def update_transaction(session: AsyncSession,transaction_id: uuid.UUID,@@ -1637,7 +1693,7 @@ async def update_transaction(user_id: uuid.UUID,data: TransactionUpdate,) -> Optional[Transaction]:- transaction = await get_transaction(session, transaction_id, workspace_id)+ transaction = await get_transaction(session, transaction_id, workspace_id, for_update=True)if not transaction:return None@@ -1713,11 +1769,37 @@ async def update_transaction(rows = [transaction]scoped_update = Noneif apply_to != "this" and _is_installment(transaction):- rows = await _get_series_transactions(session, workspace_id, transaction, apply_to)+ rows = await _get_series_transactions(+ session, workspace_id, transaction, apply_to, for_update=True+ )scoped_update = {k: v for k, v in update_data.items() if k in installment_scoped_fields}+ # The user can remove the breakdown first, edit the payment, then enter+ # the corrected split. Principal entries are owned by their breakdown.+ for row in rows:+ row_update = update_data if row.id == transaction.id else scoped_update or {}+ changed = {+ field+ for field in (*_LEDGER_FIELDS, "category_id", "exclude_from_pnl")+ if field in row_update and row_update[field] != getattr(row, field)+ }+ if row.source == MORTGAGE_PRINCIPAL_SOURCE and changed:+ raise ValueError("Edit the mortgage breakdown on its bank payment instead")+ # Balances skip rows in an ignored category, just like ignored rows.+ # Moving either into or out of an ignored category changes the bank+ # side of a mortgage allocation and would desync its loan principal.+ moves_balance = bool(changed & set(_LEDGER_FIELDS)) or (+ "category_id" in changed+ and (+ await _category_is_ignored(session, row.category_id)+ or await _category_is_ignored(session, row_update["category_id"])+ )+ )+ if moves_balance and await _has_mortgage_breakdown(session, workspace_id, row.id):+ raise ValueError("Remove the mortgage breakdown before changing this payment")+for row in rows:# The edited transaction itself reflects the full form payload; the# sibling installments only receive the whitelisted fields (and keep@@ -1760,13 +1842,36 @@ async def bulk_update_category(category_id: Optional[uuid.UUID] = None,) -> int:await _ensure_category_in_workspace(session, workspace_id, category_id)- result = await session.execute(- update(Transaction)- .where(- Transaction.id.in_(transaction_ids),- Transaction.workspace_id == workspace_id,+ # Principal entries keep no category; skip them rather than fail the batch.+ target = [+ Transaction.id.in_(transaction_ids),+ Transaction.workspace_id == workspace_id,+ Transaction.source != MORTGAGE_PRINCIPAL_SOURCE,+ ]+ # A category change can alter whether an allocated bank payment contributes+ # to balances, either by entering or leaving an ignored category.+ await session.execute(+ select(Transaction.id).where(*target).order_by(Transaction.id).with_for_update()+ )+ linked_query = (+ select(MortgagePaymentAllocation.id)+ .join(Transaction, Transaction.id == MortgagePaymentAllocation.payment_transaction_id)+ .where(*target)+ )+ if await _category_is_ignored(session, category_id):+ linked = await session.scalar(linked_query.limit(1))+ else:+ linked = await session.scalar(+ linked_query.where(+ Transaction.category_id.in_(+ select(Category.id).where(Category.is_ignored.is_(True))+ )+ ).limit(1))- .values(category_id=category_id)+ if linked is not None:+ raise ValueError("Remove the mortgage breakdown before changing this payment")+ result = await session.execute(+ update(Transaction).where(*target).values(category_id=category_id))await session.commit()return cast(CursorResult, result).rowcount@@ -2015,9 +2120,13 @@ async def toggle_ignore_transaction(other field is touched) so the edit dialog can offer ignore as aone-click action alongside delete, instead of bundling it into theform's Salvar flow."""- transaction = await get_transaction(session, transaction_id, workspace_id)+ transaction = await get_transaction(session, transaction_id, workspace_id, for_update=True)if not transaction:return None+ if transaction.source == MORTGAGE_PRINCIPAL_SOURCE:+ raise ValueError("Edit the mortgage breakdown on its bank payment instead")+ if await _has_mortgage_breakdown(session, workspace_id, transaction.id):+ raise ValueError("Remove the mortgage breakdown before changing this payment")transaction.is_ignored = not transaction.is_ignoredawait session.commit()await session.refresh(transaction)@@ -2054,7 +2163,7 @@ async def delete_transaction(may be "future" (this row + all later installments) or "all" (every rowin the series); otherwise only the single row is removed. Paired transferlegs are cascade-deleted as before. Returns False when not found."""- transaction = await get_transaction(session, transaction_id, workspace_id)+ transaction = await get_transaction(session, transaction_id, workspace_id, for_update=True)if not transaction:return False@@ -2062,7 +2171,11 @@ async def delete_transaction(# delete and the row is part of a series.rows: list[Transaction] = [transaction]if apply_to != "this" and _is_installment(transaction):- rows = await _get_series_transactions(session, workspace_id, transaction, apply_to)+ rows = await _get_series_transactions(+ session, workspace_id, transaction, apply_to, for_update=True+ )+ if any(row.source == MORTGAGE_PRINCIPAL_SOURCE for row in rows):+ raise ValueError("Remove the mortgage breakdown on its bank payment instead")# Clean up attachment files from storage before ORM cascade deletes DB recordsfrom app.services.attachment_service import cleanup_attachment_files@@ -2101,7 +2214,7 @@ async def bulk_delete_transactions(from app.services.attachment_service import cleanup_attachment_filesresult = await session.execute(- select(Transaction.id, Transaction.transfer_pair_id)+ select(Transaction.id, Transaction.transfer_pair_id, Transaction.source).where(Transaction.id.in_(transaction_ids),Transaction.workspace_id == workspace_id,@@ -2110,6 +2223,8 @@ async def bulk_delete_transactions(transactions = result.all()if not transactions:return 0+ if any(row[2] == MORTGAGE_PRINCIPAL_SOURCE for row in transactions):+ raise ValueError("Remove the mortgage breakdown on its bank payment instead")valid_ids = [row[0] for row in transactions]transfer_pair_ids = {row[1] for row in transactions if row[1]}diff --git a/backend/app/services/transfer_detection_service.py b/backend/app/services/transfer_detection_service.pyindex 0d44becc..e25424ae 100644--- a/backend/app/services/transfer_detection_service.py+++ b/backend/app/services/transfer_detection_service.py@@ -51,10 +51,14 @@ from datetime import timedeltafrom decimal import Decimalfrom typing import Any, Optional-from sqlalchemy import select+from sqlalchemy import exists, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.account import Account+from app.models.mortgage_payment_allocation import (+ MORTGAGE_PRINCIPAL_SOURCE,+ MortgagePaymentAllocation,+)from app.models.transaction import Transactionfrom app.services import reconciliation_policyfrom app.services import reconciliation_rule_service as rule_service@@ -192,6 +196,12 @@ async def _pool(query = select(Transaction).where(Transaction.workspace_id == workspace_id,Transaction.transfer_pair_id.is_(None),+ # A mortgage payment with a saved breakdown already moves its+ # principal to the loan, and the principal entry is that movement.+ # Pairing either as a transfer would move the money a second time.+ # Not a policy knob: workspace rule overrides must not re-enable it.+ Transaction.source != MORTGAGE_PRINCIPAL_SOURCE,+ ~exists().where(MortgagePaymentAllocation.payment_transaction_id == Transaction.id),)if ignored_sources:query = query.where(Transaction.source.not_in(ignored_sources))diff --git a/backend/tests/api_contract/baseline.json b/backend/tests/api_contract/baseline.jsonindex e528dc34..9e16617d 100644--- a/backend/tests/api_contract/baseline.json+++ b/backend/tests/api_contract/baseline.json@@ -32,6 +32,7 @@"DELETE /api/invoices/{invoice_id}/deductions/{deduction_id}": 401,"DELETE /api/invoices/{invoice_id}/schedule": 401,"DELETE /api/invoices/{invoice_id}/share": 401,+ "DELETE /api/mortgage-payments/{payment_id}": 401,"DELETE /api/payees/{payee_id}": 401,"DELETE /api/products/{product_id}": 401,"DELETE /api/products/{product_id}/prices/{price_id}": 401,@@ -137,6 +138,7 @@"GET /api/invoices/{invoice_id}/document": 401,"GET /api/invoices/{invoice_id}/pdf": 401,"GET /api/invoices/{invoice_id}/statement": 401,+ "GET /api/mortgage-payments/{payment_id}": 401,"GET /api/payees": 401,"GET /api/payees/{payee_id}": 401,"GET /api/payees/{payee_id}/summary": 401,@@ -324,6 +326,7 @@"POST /api/workspaces/{workspace_id}/archive": 401,"POST /api/workspaces/{workspace_id}/members": 401,"PUT /api/agents/{agent_id}/tools": 401,+ "PUT /api/mortgage-payments/{payment_id}": 401,"PUT /api/reconciliation/rules/{node}/order": 401},"empty": {@@ -394,6 +397,7 @@"POST /api/transactions/{transaction_id}/create-counterpart": 422,"POST /api/workspaces": 422,"POST /api/workspaces/{workspace_id}/members": 422,+ "PUT /api/mortgage-payments/{payment_id}": 422,"PUT /api/reconciliation/rules/{node}/order": 422},"ok": {@@ -429,6 +433,7 @@"DELETE /api/invoices/{invoice_id}/deductions/{deduction_id}": 404,"DELETE /api/invoices/{invoice_id}/schedule": 200,"DELETE /api/invoices/{invoice_id}/share": 204,+ "DELETE /api/mortgage-payments/{payment_id}": 404,"DELETE /api/payees/{payee_id}": 409,"DELETE /api/products/{product_id}": 204,"DELETE /api/products/{product_id}/prices/{price_id}": 404,@@ -533,6 +538,7 @@"GET /api/invoices/{invoice_id}/document": 200,"GET /api/invoices/{invoice_id}/pdf": 200,"GET /api/invoices/{invoice_id}/statement": 200,+ "GET /api/mortgage-payments/{payment_id}": 404,"GET /api/payees": 200,"GET /api/payees/{payee_id}": 200,"GET /api/payees/{payee_id}/summary": 200,@@ -719,6 +725,7 @@"POST /api/workspaces/{workspace_id}/archive": 400,"POST /api/workspaces/{workspace_id}/members": 400,"PUT /api/agents/{agent_id}/tools": 200,+ "PUT /api/mortgage-payments/{payment_id}": 404,"PUT /api/reconciliation/rules/{node}/order": 400},"unknown_id": {@@ -752,6 +759,7 @@"DELETE /api/invoices/{invoice_id}/deductions/{deduction_id}": 404,"DELETE /api/invoices/{invoice_id}/schedule": 404,"DELETE /api/invoices/{invoice_id}/share": 404,+ "DELETE /api/mortgage-payments/{payment_id}": 404,"DELETE /api/payees/{payee_id}": 404,"DELETE /api/products/{product_id}": 404,"DELETE /api/products/{product_id}/prices/{price_id}": 404,@@ -798,6 +806,7 @@"GET /api/invoices/{invoice_id}/document": 404,"GET /api/invoices/{invoice_id}/pdf": 404,"GET /api/invoices/{invoice_id}/statement": 404,+ "GET /api/mortgage-payments/{payment_id}": 404,"GET /api/payees/{payee_id}": 404,"GET /api/payees/{payee_id}/summary": 404,"GET /api/products/{product_id}": 404,@@ -883,7 +892,8 @@"POST /api/transactions/{transaction_id}/post-today": 404,"POST /api/workspaces/{workspace_id}/archive": 404,"POST /api/workspaces/{workspace_id}/members": 404,- "PUT /api/agents/{agent_id}/tools": 404+ "PUT /api/agents/{agent_id}/tools": 404,+ "PUT /api/mortgage-payments/{payment_id}": 422},"viewer": {"DELETE /api/accounts/{account_id}": 403,@@ -916,6 +926,7 @@"DELETE /api/invoices/{invoice_id}/deductions/{deduction_id}": 403,"DELETE /api/invoices/{invoice_id}/schedule": 403,"DELETE /api/invoices/{invoice_id}/share": 403,+ "DELETE /api/mortgage-payments/{payment_id}": 403,"DELETE /api/payees/{payee_id}": 403,"DELETE /api/products/{product_id}": 403,"DELETE /api/products/{product_id}/prices/{price_id}": 403,@@ -1069,6 +1080,7 @@"POST /api/workspaces/{workspace_id}/archive": 403,"POST /api/workspaces/{workspace_id}/members": 403,"PUT /api/agents/{agent_id}/tools": 403,+ "PUT /api/mortgage-payments/{payment_id}": 403,"PUT /api/reconciliation/rules/{node}/order": 403}}diff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.pyindex 7de82a94..f79cc4d4 100644--- a/backend/tests/test_account_service.py+++ b/backend/tests/test_account_service.py@@ -24,7 +24,7 @@ from app.models.recurring_transaction import RecurringTransactionfrom app.models.transaction import Transactionfrom app.schemas.account import AccountCreate, AccountUpdatefrom app.services.account_service import (- _simplefin_to_internal_balance,+ _provider_to_internal_balance,create_account,close_account,delete_account,@@ -1339,26 +1339,26 @@ async def _make_provider_connection(return conn.id-def test_simplefin_to_internal_balance_flips_card():+def test_provider_to_internal_balance_flips_card():"""SimpleFIN reports card debt as a negative number; normalize to positive."""- assert _simplefin_to_internal_balance(+ assert _provider_to_internal_balance("simplefin", "credit_card", Decimal("-500.00")) == Decimal("500.00")-def test_simplefin_to_internal_balance_checking_unchanged():+def test_provider_to_internal_balance_checking_unchanged():"""A SimpleFIN non-card balance is already in the right convention."""- assert _simplefin_to_internal_balance(+ assert _provider_to_internal_balance("simplefin", "checking", Decimal("1500.00")) == Decimal("1500.00")-def test_simplefin_to_internal_balance_other_provider_unchanged():+def test_provider_to_internal_balance_other_provider_unchanged():"""Pluggy/Enable already use positive-for-debt — never flip their cards."""- assert _simplefin_to_internal_balance(+ assert _provider_to_internal_balance("pluggy", "credit_card", Decimal("500.00")) == Decimal("500.00")- assert _simplefin_to_internal_balance(+ assert _provider_to_internal_balance("enable_banking", "credit_card", Decimal("500.00")) == Decimal("500.00")@@ -1454,6 +1454,81 @@ async def test_update_simplefin_type_change_not_crossing_card_keeps_balance(assert updated.balance == Decimal("1500.00")+def test_provider_to_internal_balance_flips_loan():+ assert _provider_to_internal_balance(+ "simplefin", "loan", Decimal("-250000.00")+ ) == Decimal("250000.00")+++def test_provider_to_internal_balance_stores_any_loan_as_positive_debt():+ for provider in ("enable_banking", "pluggy", "simplefin"):+ assert _provider_to_internal_balance(+ provider, "loan", Decimal("-250000.00")+ ) == Decimal("250000.00")+ assert _provider_to_internal_balance(+ provider, "loan", Decimal("250000.00")+ ) == Decimal("250000.00")+++def test_provider_to_internal_balance_keeps_checking_raw():+ """A loan synced before loans existed is stored as checking; its balance+ must keep the bank's sign so it still shows as debt, not flip to an asset."""+ assert _provider_to_internal_balance(+ "enable_banking", "checking", Decimal("-250000.00")+ ) == Decimal("-250000.00")+++++++async def test_update_simplefin_loan_to_credit_card_keeps_liability_sign(+ session: AsyncSession, test_user, test_workspace,+):+ conn_id = await _make_provider_connection(session, test_user.id, "simplefin")+ account = await _make_account(+ session,+ test_user.id,+ "SimpleFIN Mortgage",+ acc_type="loan",+ balance="250000.00",+ connection_id=conn_id,+ external_id="sf-loan-card-1",+ )++ updated = await update_account(+ session, account.id, test_workspace.id, AccountUpdate(type="credit_card")+ )++ assert updated is not None+ assert updated.balance == Decimal("250000.00")+ assert serialize_account(updated, None, None)["current_balance"] == pytest.approx(-250000.0)+++async def test_update_simplefin_loan_to_checking_flips_balance_to_asset_sign(+ session: AsyncSession, test_user, test_workspace,+):+ conn_id = await _make_provider_connection(session, test_user.id, "simplefin")+ account = await _make_account(+ session,+ test_user.id,+ "SimpleFIN Mortgage",+ acc_type="loan",+ balance="250000.00",+ connection_id=conn_id,+ external_id="sf-loan-checking-1",+ )++ updated = await update_account(+ session, account.id, test_workspace.id, AccountUpdate(type="checking")+ )++ assert updated is not None+ assert updated.balance == Decimal("-250000.00")++# ----- per-account institution resolution (issue #345) ------------------------diff --git a/backend/tests/test_mortgage_payments_api.py b/backend/tests/test_mortgage_payments_api.pynew file mode 100644index 00000000..c36af588--- /dev/null+++ b/backend/tests/test_mortgage_payments_api.py@@ -0,0 +1,1019 @@+import uuid+from datetime import date+from decimal import Decimal++import pytest+from httpx import AsyncClient+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.asset import Asset+from app.models.bank_connection import BankConnection+from app.models.mortgage_payment_allocation import (+ MORTGAGE_PRINCIPAL_SOURCE,+ MortgagePaymentAllocation,+)+from app.models.transaction import Transaction+from app.models.user import User+from app.models.workspace import Workspace, WorkspaceMember+++async def _make_payment_and_loan(+ session: AsyncSession,+ user: User,+ workspace: Workspace,+ *,+ snapshot_date: date,+):+ property_asset = Asset(+ id=uuid.uuid4(),+ user_id=user.id,+ workspace_id=workspace.id,+ name="Home",+ type="real_estate",+ currency="EUR",+ valuation_method="manual",+ )+ session.add(property_asset)+ await session.flush()+ bank_account = Account(+ id=uuid.uuid4(),+ user_id=user.id,+ workspace_id=workspace.id,+ name="Current",+ type="checking",+ balance=Decimal("0"),+ currency="EUR",+ )+ loan_account = Account(+ id=uuid.uuid4(),+ user_id=user.id,+ workspace_id=workspace.id,+ name="Mortgage",+ type="loan",+ balance=Decimal("48802.47"),+ currency="EUR",+ secured_asset_id=property_asset.id,+ )+ session.add_all([bank_account, loan_account])+ await session.flush()+ payment = Transaction(+ id=uuid.uuid4(),+ user_id=user.id,+ workspace_id=workspace.id,+ account_id=bank_account.id,+ description="Nationale-Nederlanden",+ amount=Decimal("232.83"),+ currency="EUR",+ date=date(2026, 6, 2),+ effective_date=date(2026, 6, 2),+ type="debit",+ source="sync",+ status="posted",+ )+ snapshot = Transaction(+ id=uuid.uuid4(),+ user_id=user.id,+ workspace_id=workspace.id,+ account_id=loan_account.id,+ description="Saldo initial",+ amount=Decimal("48802.47"),+ currency="EUR",+ date=snapshot_date,+ effective_date=snapshot_date,+ type="debit",+ source="opening_balance",+ status="posted",+ )+ session.add_all([payment, snapshot])+ await session.commit()+ return payment, loan_account+++async def test_historical_mortgage_payment_links_without_double_reducing_current_balance(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session,+ test_user,+ test_workspace,+ snapshot_date=date(2026, 9, 29),+ )++ response = await client.put(+ f"/api/mortgage-payments/{payment.id}",+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 167.76,+ "interest_amount": 65.07,+ }+ ]+ },+ )++ assert response.status_code == 200, response.text+ assert response.json()["principal_total"] == 167.76+ assert response.json()["allocations"][0]["historical"] is True+ allocation = await session.scalar(+ select(MortgagePaymentAllocation).where(+ MortgagePaymentAllocation.payment_transaction_id == payment.id,+ )+ )+ assert allocation is not None+ assert allocation.loan_transaction_id is None+ loan_transactions = await session.scalars(+ select(Transaction).where(Transaction.account_id == loan.id)+ )+ assert [(tx.type, tx.amount) for tx in loan_transactions.all()] == [+ ("debit", Decimal("48802.47")),+ ]+++async def test_payment_after_balance_snapshot_posts_principal_to_loan_ledger(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session,+ test_user,+ test_workspace,+ snapshot_date=date(2026, 5, 31),+ )++ response = await client.put(+ f"/api/mortgage-payments/{payment.id}",+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 167.76,+ "interest_amount": 65.07,+ }+ ]+ },+ )++ assert response.status_code == 200, response.text+ allocation = await session.scalar(+ select(MortgagePaymentAllocation).where(+ MortgagePaymentAllocation.payment_transaction_id == payment.id,+ )+ )+ assert allocation is not None and allocation.loan_transaction_id is not None+ loan_transaction = await session.get(Transaction, allocation.loan_transaction_id)+ assert loan_transaction is not None+ assert loan_transaction.type == "credit"+ assert loan_transaction.amount == Decimal("167.76")+ assert response.json()["allocations"][0]["historical"] is False+++async def test_payment_can_allocate_principal_and_interest_across_loan_parts(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, first_loan = await _make_payment_and_loan(+ session,+ test_user,+ test_workspace,+ snapshot_date=date(2026, 5, 31),+ )+ second_loan = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Mortgage part 2",+ type="loan",+ balance=Decimal("10000.00"),+ currency="EUR",+ secured_asset_id=first_loan.secured_asset_id,+ )+ session.add(second_loan)+ await session.commit()++ response = await client.put(+ f"/api/mortgage-payments/{payment.id}",+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(first_loan.id),+ "principal_amount": 100,+ "interest_amount": 20,+ },+ {+ "loan_account_id": str(second_loan.id),+ "principal_amount": 67.76,+ "interest_amount": 45.07,+ },+ ]+ },+ )++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["principal_total"] == 167.76+ assert body["interest_total"] == 65.07+ assert len(body["allocations"]) == 2+ allocations = (+ await session.scalars(+ select(MortgagePaymentAllocation).where(+ MortgagePaymentAllocation.payment_transaction_id == payment.id,+ )+ )+ ).all()+ assert {row.loan_account_id for row in allocations} == {first_loan.id, second_loan.id}+ for row in allocations:+ assert row.loan_transaction_id is not None+ loan_transaction = await session.get(Transaction, row.loan_transaction_id)+ assert loan_transaction is not None+ assert loan_transaction.account_id == row.loan_account_id+ assert loan_transaction.amount == row.principal_amount+ assert loan_transaction.type == "credit"+++async def test_pending_payment_does_not_post_a_repayment(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session,+ test_user,+ test_workspace,+ snapshot_date=date(2026, 5, 31),+ )+ payment.status = "pending"+ await session.commit()++ response = await client.put(+ f"/api/mortgage-payments/{payment.id}",+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 167.76,+ "interest_amount": 65.07,+ }+ ]+ },+ )++ assert response.status_code == 400+ assert "posted" in response.json()["detail"]+ assert (+ await session.scalars(+ select(MortgagePaymentAllocation).where(+ MortgagePaymentAllocation.payment_transaction_id == payment.id,+ )+ )+ ).all() == []+++async def test_interest_only_payment_has_no_zero_value_loan_transaction(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session,+ test_user,+ test_workspace,+ snapshot_date=date(2026, 5, 31),+ )++ response = await client.put(+ f"/api/mortgage-payments/{payment.id}",+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 0,+ "interest_amount": 232.83,+ }+ ]+ },+ )++ assert response.status_code == 200, response.text+ assert response.json()["allocations"][0]["historical"] is False+ allocation = await session.scalar(+ select(MortgagePaymentAllocation).where(+ MortgagePaymentAllocation.payment_transaction_id == payment.id,+ )+ )+ assert allocation is not None+ assert allocation.loan_transaction_id is None+ assert (+ len(+ (+ await session.scalars(+ select(Transaction).where(+ Transaction.account_id == loan.id,+ )+ )+ ).all()+ )+ == 1+ )+++async def test_replacing_payment_removes_only_its_previous_principal_transaction(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session,+ test_user,+ test_workspace,+ snapshot_date=date(2026, 5, 31),+ )+ url = f"/api/mortgage-payments/{payment.id}"+ first = await client.put(+ url,+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 167.76,+ "interest_amount": 65.07,+ }+ ]+ },+ )+ assert first.status_code == 200, first.text+ original = await session.scalar(+ select(MortgagePaymentAllocation).where(+ MortgagePaymentAllocation.payment_transaction_id == payment.id,+ )+ )+ assert original is not None+ original_transaction_id = original.loan_transaction_id+ assert original_transaction_id is not None++ replacement = await client.put(+ url,+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 150,+ "interest_amount": 82.83,+ }+ ]+ },+ )++ assert replacement.status_code == 200, replacement.text+ assert await session.get(Transaction, original_transaction_id) is None+ loan_transactions = (+ await session.scalars(+ select(Transaction).where(+ Transaction.account_id == loan.id,+ )+ )+ ).all()+ assert sorted((tx.type, tx.amount) for tx in loan_transactions) == [+ ("credit", Decimal("150.00")),+ ("debit", Decimal("48802.47")),+ ]+++async def test_payment_rejects_fractional_cents(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session,+ test_user,+ test_workspace,+ snapshot_date=date(2026, 5, 31),+ )++ response = await client.put(+ f"/api/mortgage-payments/{payment.id}",+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": "167.765",+ "interest_amount": "65.065",+ }+ ]+ },+ )++ assert response.status_code == 422+++async def test_breakdown_can_be_removed_before_editing_payment(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session,+ test_user,+ test_workspace,+ snapshot_date=date(2026, 5, 31),+ )+ url = f"/api/mortgage-payments/{payment.id}"+ created = await client.put(+ url,+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 167.76,+ "interest_amount": 65.07,+ }+ ]+ },+ )+ assert created.status_code == 200, created.text++ blocked = await client.patch(+ f"/api/transactions/{payment.id}",+ headers=auth_headers,+ json={"amount": 233.83},+ )+ assert blocked.status_code == 400+ assert "Remove the mortgage breakdown" in blocked.json()["detail"]++ removed = await client.delete(url, headers=auth_headers)+ assert removed.status_code == 204, removed.text+ assert (await client.get(url, headers=auth_headers)).json()["allocations"] == []+ assert (+ await session.scalars(+ select(Transaction).where(+ Transaction.account_id == loan.id,+ Transaction.source == MORTGAGE_PRINCIPAL_SOURCE,+ )+ )+ ).all() == []++ changed = await client.patch(+ f"/api/transactions/{payment.id}",+ headers=auth_headers,+ json={"amount": 233.83},+ )+ assert changed.status_code == 200, changed.text+++async def _post_breakdown(client: AsyncClient, auth_headers, payment, loan):+ response = await client.put(+ f"/api/mortgage-payments/{payment.id}",+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 167.76,+ "interest_amount": 65.07,+ }+ ]+ },+ )+ assert response.status_code == 200, response.text+ return response.json()+++async def _principal_entry(session: AsyncSession, payment) -> Transaction:+ allocation = await session.scalar(+ select(MortgagePaymentAllocation).where(+ MortgagePaymentAllocation.payment_transaction_id == payment.id,+ )+ )+ assert allocation is not None and allocation.loan_transaction_id is not None+ entry = await session.get(Transaction, allocation.loan_transaction_id)+ assert entry is not None+ return entry+++async def test_principal_entry_is_owned_by_its_breakdown(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ await _post_breakdown(client, auth_headers, payment, loan)+ entry = await _principal_entry(session, payment)+ assert entry.source == MORTGAGE_PRINCIPAL_SOURCE+ assert entry.exclude_from_pnl is True++ edited = await client.patch(+ f"/api/transactions/{entry.id}", headers=auth_headers, json={"amount": 100}+ )+ assert edited.status_code == 400+ deleted = await client.delete(f"/api/transactions/{entry.id}", headers=auth_headers)+ assert deleted.status_code == 400+ bulk = await client.post(+ "/api/transactions/bulk-delete",+ headers=auth_headers,+ json={"transaction_ids": [str(entry.id)]},+ )+ assert bulk.status_code == 400++ breakdown = (+ await client.get(f"/api/mortgage-payments/{payment.id}", headers=auth_headers)+ ).json()+ assert breakdown["principal_total"] == 167.76+ stored = await session.scalar(select(Transaction.amount).where(Transaction.id == entry.id))+ assert stored == Decimal("167.76")+++async def test_deleting_payment_removes_its_principal_entry(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ await _post_breakdown(client, auth_headers, payment, loan)+ entry = await _principal_entry(session, payment)++ response = await client.delete(f"/api/transactions/{payment.id}", headers=auth_headers)++ assert response.status_code == 204, response.text+ assert await session.scalar(select(Transaction.id).where(Transaction.id == entry.id)) is None+++async def test_payment_on_snapshot_date_is_already_in_the_balance(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 6, 2)+ )++ body = await _post_breakdown(client, auth_headers, payment, loan)++ assert body["allocations"][0]["historical"] is True+ entries = (+ await session.scalars(+ select(Transaction).where(Transaction.source == MORTGAGE_PRINCIPAL_SOURCE)+ )+ ).all()+ assert entries == []+++async def test_bank_connected_loan_keeps_split_without_posting_principal(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ from datetime import datetime, timezone++ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ connection = BankConnection(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ provider="enable_banking",+ external_id=f"ext-{uuid.uuid4().hex[:8]}",+ institution_name="Lender",+ credentials={"token": "fake"},+ status="active",+ last_sync_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc),+ )+ session.add(connection)+ await session.flush()+ loan.connection_id = connection.id+ await session.commit()++ body = await _post_breakdown(client, auth_headers, payment, loan)++ row = body["allocations"][0]+ assert row["bank_managed"] is True+ assert row["historical"] is False+ assert body["principal_total"] == 167.76+ entries = (+ await session.scalars(+ select(Transaction).where(Transaction.source == MORTGAGE_PRINCIPAL_SOURCE)+ )+ ).all()+ assert entries == []+++async def test_loan_with_breakdowns_cannot_be_deleted_or_retyped(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ await _post_breakdown(client, auth_headers, payment, loan)++ deleted = await client.delete(f"/api/accounts/{loan.id}", headers=auth_headers)+ assert deleted.status_code == 400+ retyped = await client.patch(+ f"/api/accounts/{loan.id}", headers=auth_headers, json={"type": "checking"}+ )+ assert retyped.status_code == 400+ assert "mortgage payment breakdowns" in retyped.json()["detail"]++ removed = await client.delete(f"/api/mortgage-payments/{payment.id}", headers=auth_headers)+ assert removed.status_code == 204+ assert (+ await client.delete(f"/api/accounts/{loan.id}", headers=auth_headers)+ ).status_code == 204+++async def test_linked_loan_without_breakdowns_can_become_another_type(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ _, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )++ response = await client.patch(+ f"/api/accounts/{loan.id}", headers=auth_headers, json={"type": "checking"}+ )++ assert response.status_code == 200, response.text+ assert response.json()["type"] == "checking"+ assert response.json()["secured_asset_id"] is None+++async def test_breakdown_rows_cannot_become_transfers(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ await _post_breakdown(client, auth_headers, payment, loan)+ entry = await _principal_entry(session, payment)+ other = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=loan.id,+ description="Lender credit",+ amount=Decimal("232.83"),+ currency="EUR",+ date=date(2026, 6, 2),+ effective_date=date(2026, 6, 2),+ type="credit",+ source="manual",+ status="posted",+ )+ session.add(other)+ await session.commit()++ linked = await client.post(+ "/api/transactions/link-transfer",+ headers=auth_headers,+ json={"transaction_ids": [str(payment.id), str(other.id)]},+ )+ assert linked.status_code == 400+ counterpart = await client.post(+ f"/api/transactions/{payment.id}/create-counterpart",+ headers=auth_headers,+ json={"to_account_id": str(loan.id)},+ )+ assert counterpart.status_code == 400+ principal_counterpart = await client.post(+ f"/api/transactions/{entry.id}/create-counterpart",+ headers=auth_headers,+ json={"to_account_id": str(payment.account_id)},+ )+ assert principal_counterpart.status_code == 400++ from app.services.transfer_detection_service import _pool++ accounts = {+ account.id: account+ for account in (+ await session.scalars(select(Account).where(Account.workspace_id == test_workspace.id))+ ).all()+ }+ pool_ids = {tx.id for tx in await _pool(session, test_workspace.id, set(), [], accounts)}+ assert payment.id not in pool_ids+ assert entry.id not in pool_ids+ assert other.id in pool_ids+++async def test_breakdown_payment_cannot_be_ignored(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ from app.models.category import Category++ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ await _post_breakdown(client, auth_headers, payment, loan)+ entry = await _principal_entry(session, payment)+ ignored_category = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Ignored",+ is_ignored=True,+ )+ session.add(ignored_category)+ await session.commit()++ for tx_id in (payment.id, entry.id):+ toggled = await client.patch(f"/api/transactions/{tx_id}/ignore", headers=auth_headers)+ assert toggled.status_code == 400+ flagged = await client.patch(+ f"/api/transactions/{tx_id}", headers=auth_headers, json={"is_ignored": True}+ )+ assert flagged.status_code == 400+ moved = await client.patch(+ f"/api/transactions/{payment.id}",+ headers=auth_headers,+ json={"category_id": str(ignored_category.id)},+ )+ assert moved.status_code == 400+ bulk = await client.patch(+ "/api/transactions/bulk-categorize",+ headers=auth_headers,+ json={"transaction_ids": [str(payment.id)], "category_id": str(ignored_category.id)},+ )+ assert bulk.status_code == 400+++async def test_ignored_payments_cannot_be_allocated_or_uncategorized(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ from app.models.category import Category++ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ ignored_category = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Ignored",+ is_ignored=True,+ )+ session.add(ignored_category)+ payment.category_id = ignored_category.id+ await session.commit()++ allocation = await client.put(+ f"/api/mortgage-payments/{payment.id}",+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 167.76,+ "interest_amount": 65.07,+ }+ ]+ },+ )+ assert allocation.status_code == 400++ # Simulate an older or externally imported breakdown attached before the+ # category was marked ignored: moving it out must also preserve the guard.+ payment.category_id = None+ await session.commit()+ await _post_breakdown(client, auth_headers, payment, loan)+ payment.category_id = ignored_category.id+ await session.commit()+ moved = await client.patch(+ f"/api/transactions/{payment.id}", headers=auth_headers, json={"category_id": None}+ )+ assert moved.status_code == 400+++async def test_moving_the_opening_balance_reapplies_the_posting_rule(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ await _post_breakdown(client, auth_headers, payment, loan)++ async def principal_rows():+ return (+ await session.scalars(+ select(Transaction.amount).where(+ Transaction.account_id == loan.id,+ Transaction.source == MORTGAGE_PRINCIPAL_SOURCE,+ )+ )+ ).all()++ assert await principal_rows() == [Decimal("167.76")]++ # A June snapshot already includes the June payment's repayment.+ later = await client.patch(+ f"/api/accounts/{loan.id}",+ headers=auth_headers,+ json={"balance": 48634.71, "balance_date": "2026-06-30"},+ )+ assert later.status_code == 200, later.text+ assert await principal_rows() == []+ breakdown = (+ await client.get(f"/api/mortgage-payments/{payment.id}", headers=auth_headers)+ ).json()+ assert breakdown["allocations"][0]["historical"] is True+ assert breakdown["principal_total"] == 167.76++ earlier = await client.patch(+ f"/api/accounts/{loan.id}",+ headers=auth_headers,+ json={"balance": 48802.47, "balance_date": "2026-05-31"},+ )+ assert earlier.status_code == 200, earlier.text+ assert await principal_rows() == [Decimal("167.76")]+++async def _other_workspace(session: AsyncSession, user: User) -> Workspace:+ """A second workspace the same user owns, to probe the workspace boundary."""+ other = Workspace(+ id=uuid.uuid4(), name="Other household", kind="personal", created_by_user_id=user.id+ )+ session.add(other)+ await session.flush()+ session.add(+ WorkspaceMember(+ id=uuid.uuid4(), workspace_id=other.id, user_id=user.id, role="owner"+ )+ )+ await session.commit()+ return other+++async def test_a_breakdown_of_another_workspace_is_not_reachable(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+):+ """Every route scopes the payment to the active workspace.++ The same user owns both workspaces here, so only the scoping keeps one+ out of the other; membership alone would let all three routes through.+ """+ other = await _other_workspace(session, test_user)+ payment, loan = await _make_payment_and_loan(+ session, test_user, other, snapshot_date=date(2026, 9, 29)+ )+ body = {+ "allocations": [+ {+ "loan_account_id": str(loan.id),+ "principal_amount": 167.76,+ "interest_amount": 65.07,+ }+ ]+ }+ owner_headers = {**auth_headers, "X-Workspace-Id": str(other.id)}++ read = await client.get(f"/api/mortgage-payments/{payment.id}", headers=auth_headers)+ write = await client.put(+ f"/api/mortgage-payments/{payment.id}", headers=auth_headers, json=body+ )+ remove = await client.delete(+ f"/api/mortgage-payments/{payment.id}", headers=auth_headers+ )+ from_owner = await client.put(+ f"/api/mortgage-payments/{payment.id}", headers=owner_headers, json=body+ )++ assert read.status_code == 404+ assert write.status_code == 404+ assert remove.status_code == 404+ assert from_owner.status_code == 200, from_owner.text+ assert await session.scalar(+ select(MortgagePaymentAllocation.workspace_id).where(+ MortgagePaymentAllocation.payment_transaction_id == payment.id+ )+ ) == other.id+++async def test_a_loan_from_another_workspace_cannot_take_a_part(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ """The loan id arrives from the client, so a payment here must not be able+ to name a loan over there and move its balance."""+ payment, _ = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 9, 29)+ )+ other = await _other_workspace(session, test_user)+ _, other_loan = await _make_payment_and_loan(+ session, test_user, other, snapshot_date=date(2026, 9, 29)+ )++ response = await client.put(+ f"/api/mortgage-payments/{payment.id}",+ headers=auth_headers,+ json={+ "allocations": [+ {+ "loan_account_id": str(other_loan.id),+ "principal_amount": 167.76,+ "interest_amount": 65.07,+ }+ ]+ },+ )++ assert response.status_code == 400+ assert "loan in this workspace" in response.json()["detail"]+ assert await session.scalar(+ select(Transaction.id).where(+ Transaction.account_id == other_loan.id,+ Transaction.source == MORTGAGE_PRINCIPAL_SOURCE,+ )+ ) is Nonediff --git a/backend/tests/test_mortgage_payments_postgres.py b/backend/tests/test_mortgage_payments_postgres.pynew file mode 100644index 00000000..4add734e--- /dev/null+++ b/backend/tests/test_mortgage_payments_postgres.py@@ -0,0 +1,213 @@+"""The mortgage payment API against real PostgreSQL: foreign-key cascades and the+principal-cleanup trigger only behave like production there."""+from datetime import date++import pytest+import pytest_asyncio+from httpx import ASGITransport, AsyncClient+from sqlalchemy import delete, func, select++from app.core.database import get_async_session+from app.main import app+from app.models.mortgage_payment_allocation import (+ MORTGAGE_PRINCIPAL_SOURCE,+ MortgagePaymentAllocation,+)+from app.models.transaction import Transaction+from tests.test_mortgage_payments_api import ( # noqa: F401 -- rerun on PostgreSQL+ _make_payment_and_loan,+ _post_breakdown,+ test_bank_connected_loan_keeps_split_without_posting_principal,+ test_breakdown_payment_cannot_be_ignored,+ test_breakdown_rows_cannot_become_transfers,+ test_breakdown_can_be_removed_before_editing_payment,+ test_deleting_payment_removes_its_principal_entry,+ test_historical_mortgage_payment_links_without_double_reducing_current_balance,+ test_linked_loan_without_breakdowns_can_become_another_type,+ test_loan_with_breakdowns_cannot_be_deleted_or_retyped,+ test_moving_the_opening_balance_reapplies_the_posting_rule,+ test_payment_after_balance_snapshot_posts_principal_to_loan_ledger,+ test_payment_can_allocate_principal_and_interest_across_loan_parts,+ test_payment_on_snapshot_date_is_already_in_the_balance,+ test_principal_entry_is_owned_by_its_breakdown,+ test_replacing_payment_removes_only_its_previous_principal_transaction,+)+++@pytest_asyncio.fixture+async def session(postgres_sessions):+ async with postgres_sessions() as session:+ yield session+ await session.rollback()+++def clean_db(postgres_sessions):+ """Each test starts in a fresh per-test PostgreSQL schema."""+++@pytest_asyncio.fixture+async def client(postgres_sessions, monkeypatch):+ async def pg_session():+ async with postgres_sessions() as session:+ yield session++ monkeypatch.setitem(app.dependency_overrides, get_async_session, pg_session)+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ yield client+++async def test_one_statement_deleting_payment_and_principal_succeeds(+ client, auth_headers, session, test_user, test_workspace+):+ """Deleting a user's or workspace's rows hits the payment and its principal+ entry in one statement; the cleanup trigger must not reject that."""+ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ await _post_breakdown(client, auth_headers, payment, loan)++ await session.execute(delete(Transaction).where(Transaction.user_id == test_user.id))+ await session.commit()++ assert await session.scalar(select(func.count()).select_from(MortgagePaymentAllocation)) == 0+ assert (+ await session.scalar(+ select(func.count())+ .select_from(Transaction)+ .where(Transaction.source == MORTGAGE_PRINCIPAL_SOURCE)+ )+ == 0+ )+++async def test_concurrent_breakdown_saves_take_turns(+ client, auth_headers, session, test_user, test_workspace+):+ import asyncio++ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ body = {+ "allocations": [+ {"loan_account_id": str(loan.id), "principal_amount": 167.76, "interest_amount": 65.07}+ ]+ }++ responses = await asyncio.gather(+ *(+ client.put(f"/api/mortgage-payments/{payment.id}", headers=auth_headers, json=body)+ for _ in range(4)+ )+ )++ assert [response.status_code for response in responses] == [200] * 4+ assert await session.scalar(select(func.count()).select_from(MortgagePaymentAllocation)) == 1+ assert (+ await session.scalar(+ select(func.count())+ .select_from(Transaction)+ .where(Transaction.source == MORTGAGE_PRINCIPAL_SOURCE)+ )+ == 1+ )+++async def test_payment_edit_waits_for_a_breakdown_being_saved(+ client, auth_headers, session, postgres_sessions, test_user, test_workspace+):+ """An edit that passed its breakdown check just before a save commits would+ change the payment under a breakdown that no longer matches it. The edit+ has to queue behind the save and then see the breakdown."""+ import asyncio+ from decimal import Decimal++ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )++ async with postgres_sessions() as saving:+ await saving.execute(+ select(Transaction.id).where(Transaction.id == payment.id).with_for_update()+ )+ edit = asyncio.create_task(+ client.patch(+ f"/api/transactions/{payment.id}", headers=auth_headers, json={"amount": 999}+ )+ )+ await asyncio.sleep(0.5)+ assert not edit.done()++ saving.add(+ MortgagePaymentAllocation(+ workspace_id=test_workspace.id,+ payment_transaction_id=payment.id,+ loan_account_id=loan.id,+ principal_amount=Decimal("167.76"),+ interest_amount=Decimal("65.07"),+ )+ )+ await saving.commit()+ response = await asyncio.wait_for(edit, timeout=10)++ assert response.status_code == 400+ assert "mortgage breakdown" in response.json()["detail"]+++async def test_bulk_category_waits_for_a_breakdown_being_saved(+ client, auth_headers, session, postgres_sessions, test_user, test_workspace+):+ """Moving payments into an ignored category checks for breakdowns first; a+ breakdown committed between that check and the update must still be seen."""+ import asyncio+ import uuid+ from decimal import Decimal++ from app.models.category import Category++ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ ignored = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Ignored",+ is_ignored=True,+ )+ session.add(ignored)+ await session.commit()++ async with postgres_sessions() as saving:+ await saving.execute(+ select(Transaction.id).where(Transaction.id == payment.id).with_for_update()+ )+ bulk = asyncio.create_task(+ client.patch(+ "/api/transactions/bulk-categorize",+ headers=auth_headers,+ json={"transaction_ids": [str(payment.id)], "category_id": str(ignored.id)},+ )+ )+ await asyncio.sleep(0.5)+ assert not bulk.done()++ saving.add(+ MortgagePaymentAllocation(+ workspace_id=test_workspace.id,+ payment_transaction_id=payment.id,+ loan_account_id=loan.id,+ principal_amount=Decimal("167.76"),+ interest_amount=Decimal("65.07"),+ )+ )+ await saving.commit()+ response = await asyncio.wait_for(bulk, timeout=10)++ assert response.status_code == 400+ assert "mortgage breakdown" in response.json()["detail"]diff --git a/backend/tests/test_providers_enable_banking.py b/backend/tests/test_providers_enable_banking.pyindex 75ed730f..170fea0c 100644--- a/backend/tests/test_providers_enable_banking.py+++ b/backend/tests/test_providers_enable_banking.py@@ -102,6 +102,7 @@ def test_cash_account_type_mapping():assert _map_cash_account_type("CACC") == "checking"assert _map_cash_account_type("SVGS") == "savings"assert _map_cash_account_type("CARD") == "credit_card"+ assert _map_cash_account_type("LOAN") == "checking"assert _map_cash_account_type(None) == "checking"assert _map_cash_account_type("UNKNOWN_TYPE") == "checking"@@ -320,6 +321,56 @@ async def test_handle_oauth_callback_builds_connection_data(eb_keys):assert conn.credentials.get("session_id") is None[email protected]("reported", ["-250000.00", "250000.00"])+async def test_loan_account_keeps_the_bank_reported_balance(eb_keys, reported):+ """Sign normalization happens on storage, by the account's stored type+ (account_service._provider_to_internal_balance), not in the provider."""+ provider = EnableBankingProvider()++ def handler(request: httpx.Request) -> httpx.Response:+ path = request.url.path+ if path == "/sessions":+ return httpx.Response(+ 200,+ json={+ "session_id": "sess-loan",+ "accounts": [+ {+ "uid": "loan-uid-1",+ "currency": "EUR",+ "display_name": "Mortgage",+ "cash_account_type": "LOAN",+ }+ ],+ "aspsp": {"name": "ING", "country": "NL"},+ "access": {"valid_until": "2026-12-01T00:00:00Z"},+ },+ )+ if path == "/accounts/loan-uid-1/balances":+ return httpx.Response(+ 200,+ json={+ "balances": [+ {+ "balance_type": "CLBD",+ "balance_amount": {"amount": reported, "currency": "EUR"},+ }+ ]+ },+ )+ return httpx.Response(404)++ with _patch_client(provider, handler):+ conn = await provider.handle_oauth_callback("code-loan")+ acc = conn.accounts[0]+ # A LOAN account still maps to checking: loans on a bank connection are+ # not modelled yet. What matters here is that the provider passes the+ # reported balance through untouched, whatever the type.+ assert acc.type == "checking"+ assert acc.balance == Decimal(reported)++@pytest.mark.asyncioasync def test_get_transactions_parses_nested_and_flat_shapes(eb_keys):"""Both `transactions:{booked,pending}` and flat list must produce thediff --git a/data/attachments/0518029d-a91b-4345-835a-5bfbe961cd67/invoices/6fed37d5-7de9-47b9-931a-3660dbb35fa7/820d6b1a_1.pdf b/data/attachments/0518029d-a91b-4345-835a-5bfbe961cd67/invoices/6fed37d5-7de9-47b9-931a-3660dbb35fa7/820d6b1a_1.pdfnew file mode 100644index 00000000..0da88919--- /dev/null+++ b/data/attachments/0518029d-a91b-4345-835a-5bfbe961cd67/invoices/6fed37d5-7de9-47b9-931a-3660dbb35fa7/820d6b1a_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132915-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132915-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 805+>>+stream+Gb!#ZgMY_1&:O:Sb[Xh1c-5PQOX:3.5tJfY;dW@r<fKG@VF:C]Nis:/DNuF]b87;4Hd9hq3t)/462C3>'&Z+a(Y8f.OF@9eb!8"B6(6lp$l$$fAeiI.L!^G8W:,Bt"GZ+.fdBb%DFl!ea5B*2@o-3/_V+Tkp%#b?#O)>dn!bH$C^tB!&19^"!3n(NgE>3#NE[7L=FSjWZXH2C_4Te$K;]Fr'Kn"`)PbqCL)scpr(:;9`^(dE.!_'/6:$eNYkmd?4Df(-i/D7`[Eh1"=i=s*aXA1bUk8mG4#mdY[SMuqqS3iFUXVUab-S4+&QWp#Am5iE]m@6hn[+LP(?[YeI>9hn*09fjU_U0m--c^+U8*;Rk-#-s\aqP:PtUGF^R$`+mqjHCcKAOklKQT-fJr!6E+bQ1#</!EM.CQa-A"G3-1"9k&B*!B3p2tu1:$4SlldAZo*pe<gQ:lIm3HJB:pDC;_?t)am[d-kVScPddYFk(h"HO%[email protected][=oGA%dmAC=k^$D(p%XiPCQ8kCIhHOMBsQWbsI^)%jhnT7f/k\\%MnZ2$Kp#bJX3cr2nPJ2TpA.FX*/FM7D[0#0>mBgofgId2ro.-JTM^X:d<b$2GM]1CY_8ciO()jQGNRtf#^IeGq3?JkK8cmO+(.=t-.9d`7iNo)e";A3@P6YA'AF5?JH,UaU82V`Z,MB0cii0=BL`))8=P.UQ\U&"5EZuHN8_KjSlD7:W`T'_P#`T0Wg=HPg0hnLs>*30%;Q63(Yg?.OEY`dr4+3-Yg25.2-ga;*Qg;L:*J)\5)HlA-a^<bdCH;~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<db5b802cd5678b972de5008d1ca356c9><db5b802cd5678b972de5008d1ca356c9>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1807+%%EOFdiff --git a/data/attachments/3eb25ee9-14a3-4b76-89fb-2cba68f3f9c5/invoices/c8ccadfc-8abf-4fe3-b2fc-c7eeed189b2a/42b52a87_1.pdf b/data/attachments/3eb25ee9-14a3-4b76-89fb-2cba68f3f9c5/invoices/c8ccadfc-8abf-4fe3-b2fc-c7eeed189b2a/42b52a87_1.pdfnew file mode 100644index 00000000..c5557892--- /dev/null+++ b/data/attachments/3eb25ee9-14a3-4b76-89fb-2cba68f3f9c5/invoices/c8ccadfc-8abf-4fe3-b2fc-c7eeed189b2a/42b52a87_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 604+>>+stream+Gau0@9lJKG&A@sBbV>c&R$moe;VWb#/X1'uiY(c-WeROIKtksd?Df-0Bd3dclWoM%qqeu2*X:&^gZPI\_!;E4NYkk@Ig*8o+eM#jX#;TGWJQO@/9.IrR3SeG-5WGml<EidQdZs"M=CWj#[0lIaq?$kMnAl:iW\Bna=i;kK!'fOCCm[N(k=TneL$(YBP7L##KMlGoAR2go^KKh0d,bH"K)5mE7Ubn60K6LeSXt=2i1'>P3T!LQ%EG>@-]g@?#=O-OG7A2F_FZJ9u`CnFI)7!>S"?:lhptKp'iK`LshK5<j`2a#&ud\VS4#ud["G7IeDgSpRdA5;1_9>j/i]9']ngpp.nDk6>k>l]8/@jmPn)@\ms)jTA!hPGjjU<*=5)PH`?I]rm?gQ2k#_.O.NK?%J-kh4.MkAK&`4$AlkHm-oPL)`?hDCgHZ+&T2M*rH90=NJBThrIY<*_BcEgAY(:PS0R8L:]>C5qQ2KRt.XebcST!p3f:ue0=c?3^n,Vu=NKM""LBgL*HE$P-?:N:'1.c]PcS2ns^B&OD7/@kqA>XkF)/sr'j/Tsu)"_n7EnB/O>-$B*["(d\;H%oUqaf14]=L9##H>XEV#~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<da3a905f6e78bcf15277070622649b69><da3a905f6e78bcf15277070622649b69>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1606+%%EOFdiff --git a/data/attachments/4e2756b4-594e-42f5-86cf-ee19e48f2c2c/invoices/0e723b4b-d8a7-4f82-9f9d-5f8954f61ea1/12262ae2_1.pdf b/data/attachments/4e2756b4-594e-42f5-86cf-ee19e48f2c2c/invoices/0e723b4b-d8a7-4f82-9f9d-5f8954f61ea1/12262ae2_1.pdfnew file mode 100644index 00000000..5c5a6853--- /dev/null+++ b/data/attachments/4e2756b4-594e-42f5-86cf-ee19e48f2c2c/invoices/0e723b4b-d8a7-4f82-9f9d-5f8954f61ea1/12262ae2_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 601+>>+stream+Gau0@gMRZj%"7$:n7,W6@sdXI<*L'd(>90ZnIh*&;)PH]"b%Q>?IC.EdRFRjS!@W0cLLF-1Q\3`4>3$$D_eshAmg1;%;aEY5(Par9jE3IM2Pd.i^h0H7p(gG/k1EBfCB5l]/rIpirqa\[$Gg#,ts=8%mO-R"3<E_%u29ZY(:e4&?eS@J2krc9b7ubcis[b[NF8dibcZuiHKE'+R53pVZ9A/etTZ?kSE=2pZcI1&s4RfePW60JmkE^lS1eUgYbaJKkAFfPa#+gGZ(0ZEda8>!V^XuT>B<s5fF./H;ZDr(4jFIXs_6=QNK[FP"\'@Y'tfrZ+(l%B[f*"]!+\%N_X3de7:)j<_^5bBTqVF'/e5jK?!c;,V,G[*l$;g@0ga(opsDn)`$kPZOuNNZ^&44I]C_SAuDZe3$s40eKtniRkUY`-)TX*+GIa0.8:77TB:VgB%#uOo(f/"N&J3Ji?D_$&pJMQ6+8B?_8"Onfp6irIotKdMT'*\7W#sD`0W;M!f%a:0tGb+V/Q#^K&2V]\h\b4H[`U-pPOe!2sSLYs'@M>p.k(G$=h,L+&eZ@p=?CSW\$pI\-*s4[5Y@OP_RoC"faedVcfh~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<32770a2b8ffb8c31dae3f94d0391ab3d><32770a2b8ffb8c31dae3f94d0391ab3d>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1603+%%EOFdiff --git a/data/attachments/54b89a42-4623-4465-b05c-ec2634b37777/invoices/be544e15-26ef-4122-9fde-42f56f6021b8/1b1b4e72_1.pdf b/data/attachments/54b89a42-4623-4465-b05c-ec2634b37777/invoices/be544e15-26ef-4122-9fde-42f56f6021b8/1b1b4e72_1.pdfnew file mode 100644index 00000000..69c09b03--- /dev/null+++ b/data/attachments/54b89a42-4623-4465-b05c-ec2634b37777/invoices/be544e15-26ef-4122-9fde-42f56f6021b8/1b1b4e72_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 602+>>+stream+Gau0@gMYJ*&:O:Sb[Wo_0Je'*V79N%>:A1uM3j$fW#D[j(4Mm\]hV9?dma\YXYm`IF6:^:0T_m]5!LV"?>"M*`4uHM/$MGMq#otf[;c4B9j@g2M'F=i*+:uc\JPKNhjR?Nm-Y]^N#)accs"k'Q7t=>f.L0-FUfIQ7NCF=k.0K6TPr!5s`.D1\.*L,L`1Yl334+-%j@&&5.e"/9*nE!ifPB.\u[KW\`ih,]SXPDDUMWK'$A'FYoa>E9rmgBM9lBkTD-LF2-4A3?heB=U4LomlqMSkia3?_Ck_-p=PB<K"Y%&D%S*lH=`&D+Q)C='pE)s1,WW-"tdhhR]p];%?B6s3tR0jAo!fMeJ=;NYAhL*J;r>e0Z]bHOo$"SM12UQho"j*t=W^UY1Irkh4,80JDau_qD"=30$R<G.!0[@M=Jq>[gmN%A]*\.Aa#;VpkPSa@pnC69a;6NR9*)5e'@P]Yp@H@F4C6Idh9@525VQ2g:2G;6cK>`i(J6JG>YS8DoTI"""ht<;K?C,Np/9Uau%LQs@kmJ3+ktrJc+Ye%aKC\@pGiWkqjToOI0,fA9\7X4l"/J4gGO;gT2T8CLDI\j5onWPr#:~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<a09f1e14e2f8770983375ab5c1b171be><a09f1e14e2f8770983375ab5c1b171be>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1604+%%EOFdiff --git a/data/attachments/61ebc6eb-14f3-4908-92d0-f8089e243f39/invoices/e3146e4a-8f96-4ed8-86bd-6d671fd22efe/f76788a2_1.pdf b/data/attachments/61ebc6eb-14f3-4908-92d0-f8089e243f39/invoices/e3146e4a-8f96-4ed8-86bd-6d671fd22efe/f76788a2_1.pdfnew file mode 100644index 00000000..44523188--- /dev/null+++ b/data/attachments/61ebc6eb-14f3-4908-92d0-f8089e243f39/invoices/e3146e4a-8f96-4ed8-86bd-6d671fd22efe/f76788a2_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 602+>>+stream+Gau0@gMYJ*&:O:Sb[Wo_0Je'*V79N%>:A1uM3j$fW#D[j(4Mm\]hV9?dma\YXYm`IF6:^:0T_m]5!LV"?>"M*`4uHM/$MGMq#otf[;c4B9j@g2M'F=i*+:uc\JPKNhjR?Nm-Y]^N#)accs"k'Q7t=>f.L0-FUfIQ7NCF=k.0K6TPr!5s`.D1\.*L,L`1Yl334+-%j@&&5.e"/9*nE!ifPB.\u[KW\`ih,]SXPDDUMWK'$A'FYoa>E9rmgBM9lBkTD-LF2-4A3?heB=U4LomlqMSkia3?_Ck_-p=PB<K"Y%&D%S*lH=`&D+Q)C='pE)s1,WW-"tdhhR]p];%?B6s3tR0jAo!fMeJ=;NYAhL*J;r>e0Z]bHOo$"SM12UQho"j*t=W^UY1Irkh4,80JDau_qD"=30$R<G.!0[@M=Jq>[gmN%A]*\.Aa#;VpkPSa@pnC69a;6NR9*)5e'@P]Yp@H@F4C6Idh9@525VQ2g:2G;6cK>`i(J6JG>YS8DoTI"""ht<;K?C,Np/9Uau%LQs@kmJ3+ktrJc+Ye%aKC\@pGiWkqjToOI0,fA9\7X4l"/J4gGO;gT2T8CLDI\j5onWPr#:~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<b97cc04be37afa8d3c5f899616945a77><b97cc04be37afa8d3c5f899616945a77>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1604+%%EOFdiff --git a/data/attachments/6677991c-76dc-412b-b3f2-93364369e642/invoices/f43d9dc2-b5c6-44ac-80e6-77f20ef879c3/00b165b9_1.pdf b/data/attachments/6677991c-76dc-412b-b3f2-93364369e642/invoices/f43d9dc2-b5c6-44ac-80e6-77f20ef879c3/00b165b9_1.pdfnew file mode 100644index 00000000..ba0e42dc--- /dev/null+++ b/data/attachments/6677991c-76dc-412b-b3f2-93364369e642/invoices/f43d9dc2-b5c6-44ac-80e6-77f20ef879c3/00b165b9_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 602+>>+stream+Gau0@gMYJ*&:O:Sb[Wo_0Je'*V79N%>:A1uM3j$fW#D[j(4Mm\]hV9?dma\YXYm`IF6:^:0T_m]5!LV"?>"M*`4uHM/$MGMq#otf[;c4B9j@g2M'F=i*+:uc\JPKNhjR?Nm-Y]^N#)accs"k'Q7t=>f.L0-FUfIQ7NCF=k.0K6TPr!5s`.D1\.*L,L`1Yl334+-%j@&&5.e"/9*nE!ifPB.\u[KW\`ih,]SXPDDUMWK'$A'FYoa>E9rmgBM9lBkTD-LF2-4A3?heB=U4LomlqMSkia3?_Ck_-p=PB<K"Y%&D%S*lH=`&D+Q)C='pE)s1,WW-"tdhhR]p];%?B6s3tR0jAo!fMeJ=;NYAhL*J;r>e0Z]bHOo$"SM12UQho"j*t=W^UY1Irkh4,80JDau_qD"=30$R<G.!0[@M=Jq>[gmN%A]*\.Aa#;VpkPSa@pnC69a;6NR9*)5e'@P]Yp@H@F4C6Idh9@525VQ2g:2G;6cK>`i(J6JG>YS8DoTI"""ht<;K?C,Np/9Uau%LQs@kmJ3+ktrJc+Ye%aKC\@pGiWkqjToOI0,fA9\7X4l"/J4gGO;gT2T8CLDI\j5onWPr#:~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<82fce5b0439173fefd4c501679745453><82fce5b0439173fefd4c501679745453>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1604+%%EOFdiff --git a/data/attachments/7b95605f-8027-46c6-9f36-fbc4b0912c79/invoices/65ff450e-7cd1-4454-94b1-5f30d5a8ba6b/1570328a_1.pdf b/data/attachments/7b95605f-8027-46c6-9f36-fbc4b0912c79/invoices/65ff450e-7cd1-4454-94b1-5f30d5a8ba6b/1570328a_1.pdfnew file mode 100644index 00000000..9e347e73--- /dev/null+++ b/data/attachments/7b95605f-8027-46c6-9f36-fbc4b0912c79/invoices/65ff450e-7cd1-4454-94b1-5f30d5a8ba6b/1570328a_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 604+>>+stream+Gau0@9lJKG&A@sBbV>c&R$moe;VWb#/X1'uiY(c-WeROIKtksd?Df-0Bd3dclWoM%qqeu2*X:&^gZPI\_!;E4NYkk@Ig*8o+eM#jX#;TGWJQO@/9.IrR3SeG-5WGml<EidQdZs"M=CWj#[0lIaq?$kMnAl:iW\Bna=i;kK!'fOCCm[N(k=TneL$(YBP7L##KMlGoAR2go^KKh0d,bH"K)5mE7Ubn60K6LeSXt=2i1'>P3T!LQ%EG>@-]g@?#=O-OG7A2F_FZJ9u`CnFI)7!>S"?:lhptKp'iK`LshK5<j`2a#&ud\VS4#ud["G7IeDgSpRdA5;1_9>j/i]9']ngpp.nDk6>k>l]8/@jmPn)@\ms)jTA!hPGjjU<*=5)PH`?I]rm?gQ2k#_.O.NK?%J-kh4.MkAK&`4$AlkHm-oPL)`?hDCgHZ+&T2M&>4ItX75`Se&8''k_[P?Ls)@.,cPF&ec.h'!paUeBQdUtYuq;uR74Xq52`>Gud%hPA^(^V1&GeiC7QV-0"AH][kPB:I:%$QVF)fQ$MUq]c&B);7n!OoO!Xt#Ba5sM8"GO;N/[AkfQ$b-<_275BJO#.<RWs_mV!3[hSW;~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<44b262cfa4217253b542e62a1698d275><44b262cfa4217253b542e62a1698d275>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1606+%%EOFdiff --git a/data/attachments/894a04d6-95f5-4309-8b12-ca4a837599b2/invoices/176469e2-8d8d-4f3e-8630-28507ae5e7f9/2aee642c_1.pdf b/data/attachments/894a04d6-95f5-4309-8b12-ca4a837599b2/invoices/176469e2-8d8d-4f3e-8630-28507ae5e7f9/2aee642c_1.pdfnew file mode 100644index 00000000..3f9525c3--- /dev/null+++ b/data/attachments/894a04d6-95f5-4309-8b12-ca4a837599b2/invoices/176469e2-8d8d-4f3e-8630-28507ae5e7f9/2aee642c_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 625+>>+stream+Gau1,a`>iq&;KY"MEVpc2r-Xo&WB&Eb!N>j`'jh6P-P`T#%!qQjp9#EEL!<<UM>eNqg4_h"6mr#n#%JIb6"9-0X*h4"k]Q'iY:r-X6ftY._>u+erGtGF+hfZjC/g*IB>]lG'1hr@_=r3K%?*fZ@pUs\c/udT0RB*`R@"=d+*BMJTs=E&)p!L[NQujTe-KCQ60;mh<U$I_k6:m-e,1&:'$[=X@7+ldfO.7O6jT!&s4RfNMF3g$&4GV2IhR>[&'0U.[cRRTlN.n*foluBp##(Gu+=6SpQj:-YP2$PYT_\Z:/.UM!K^KFm2/R3[LQ1X824bTB5I55bk19XU@W-b2d[@hjEaum[inr0psSqju;Td]NBR]<pn;(G7e]_gk_X"Fb?di+4[Db])h?6f/mCHmO1L^Rsd,(/dB:Pp#t)Od?l$Ho?$Vudl>Ps0SedZ6CSdGe>C47H7PeQpbAVMU&Ajm!guW`HfWB;g,7Su.tih6a\+b+.L`mU`V58#D>&tWic\T[#(sm*0h2*`kReobSI$9V\79Ou0+E=C0-f[$RA;WscS0Z0HNigT&a<Wi`/O_ee'n"[n*:BlX.UD1j1@5E[_HT\RMr[=+Y@GI@V;[OHBT/drW:p.G*;~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<72238f825132ec4f5b0b9e97be06cf93><72238f825132ec4f5b0b9e97be06cf93>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1627+%%EOFdiff --git a/data/attachments/8ffebd96-2ad3-4ab1-99ff-0d5103c3088a/invoices/626d263c-e9f8-4ecc-8645-8b27c329ba22/e722080d_1.pdf b/data/attachments/8ffebd96-2ad3-4ab1-99ff-0d5103c3088a/invoices/626d263c-e9f8-4ecc-8645-8b27c329ba22/e722080d_1.pdfnew file mode 100644index 00000000..c3bc6a3a--- /dev/null+++ b/data/attachments/8ffebd96-2ad3-4ab1-99ff-0d5103c3088a/invoices/626d263c-e9f8-4ecc-8645-8b27c329ba22/e722080d_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132915-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132915-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 595+>>+stream+Gau1+9lJKG&;KZQ'lsdS).mKqY7qcV[7)AL-S>uGLoR/CUuLi!l]6-,@bOAhQG(jo^!Ae/Ne`2XjR3"Y%IcErX&B3<aBsKM>0(@'k,+%EE%5i>N'eR6=lp"EOibQjE;-J^_SbZ!Oi2Kq&-T*]?"FJOe(*U[DY4)%2<:)]7*p($[tT&i63VA':V./Od*N8TX6$7Fq=(h$o^KKg;$lnFJl@1W3,;Ar'tSs-o<\6S2i1'>P5;,\<J"YSYjE:%54*#1O<V#A*D4JRA3=YR(V.6#D5I2/cR5+W-`EFVascOX]1$*^L`;%&NSB".Xr$kKF+<l]G#Fs[b44&:,C4BN[eQaHH]`Y,nLgP1SpO2]^$ZVWPtt\g16gY5pNe+o_&[*6Qcm^0bkoLu`-V&lj_2k6mD[3,>TK>H&su%e7)DbH$u%+&e*/GT+n9VGF$ia$q&d[OqoG,9ARi*f'nhKua\+b+.L`mU`E0h*ct7X\q0'*UR5BiD@Z9#l/)kXH,(W)k%nn&B;X8\ECd`338NJY7_<g4Q:&3sdCYo!ZKM'lY]ri<5"+D4gT=FUFTri'(RZ=f\+g#EriYX,h[,2R2rW$IE=MF~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<9e6c4d8867faf84ae457002a1c0e31e9><9e6c4d8867faf84ae457002a1c0e31e9>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1597+%%EOFdiff --git a/data/attachments/902b8cc3-f93a-45b7-b2e5-801d2fe16b08/invoices/a6d6a33a-f647-450e-8d57-d5a9796c7c95/98383c30_1.pdf b/data/attachments/902b8cc3-f93a-45b7-b2e5-801d2fe16b08/invoices/a6d6a33a-f647-450e-8d57-d5a9796c7c95/98383c30_1.pdfnew file mode 100644index 00000000..09bac358--- /dev/null+++ b/data/attachments/902b8cc3-f93a-45b7-b2e5-801d2fe16b08/invoices/a6d6a33a-f647-450e-8d57-d5a9796c7c95/98383c30_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 604+>>+stream+Gau0@9lJKG&A@sBbV>c&R$moe;VWb#/X1'uiY(c-WeROIKtksd?Df-0Bd3dclWoM%qqeu2*X:&^gZPI\_!;E4NYkk@Ig*8o+eM#jX#;TGWJQO@/9.IrR3SeG-5WGml<EidQdZs"M=CWj#[0lIaq?$kMnAl:iW\Bna=i;kK!'fOCCm[N(k=TneL$(YBP7L##KMlGoAR2go^KKh0d,bH"K)5mE7Ubn60K6LeSXt=2i1'>P3T!LQ%EG>@-]g@?#=O-OG7A2F_FZJ9u`CnFI)7!>S"?:lhptKp'iK`LshK5<j`2a#&ud\VS4#ud["G7IeDgSpRdA5;1_9>j/i]9']ngpp.nDk6>k>l]8/@jmPn)@\ms)jTA!hPGjjU<*=5)PH`?I]rm?gQ2k#_.O.NK?%J-kh4.MkAK&`4$AlkHm-oPL)`?hDCgHZ+&T2M*rH90=NJBThrIY<*_BcEgAY(:PS0R8L:]>C5qQ2KRt.XebcST!p3f:ue0=c?3^n,Vu=NKM""LBgL*HE$P-?:N:'1.c]PcS2ns^B&OD7/@kqA>XkF)/sr'j/Tsu)"_n7EnB/O>-$B*["(d\;H%oUqaf14]=L9##H>XEV#~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<fe5c6751cbd0cd45036519aa2b0ecfcd><fe5c6751cbd0cd45036519aa2b0ecfcd>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1606+%%EOFdiff --git a/data/attachments/99231a61-f6e6-425b-a1a6-d1447013505b/invoices/171aad31-55af-4c5a-bbe1-bcb21c3e25f2/3b1f9d44_1.pdf b/data/attachments/99231a61-f6e6-425b-a1a6-d1447013505b/invoices/171aad31-55af-4c5a-bbe1-bcb21c3e25f2/3b1f9d44_1.pdfnew file mode 100644index 00000000..f339d3dc--- /dev/null+++ b/data/attachments/99231a61-f6e6-425b-a1a6-d1447013505b/invoices/171aad31-55af-4c5a-bbe1-bcb21c3e25f2/3b1f9d44_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132915-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132915-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 592+>>+stream+Gau1+95i9E&BF8='QX[RREj$jY7qcV[7)B7:L#(n&62(d8]B:oerOnl'%0=eQG(jo4hq"Z4:J#5GP<a`J2\?@c59Y+Ig*8o+eM,kS'EY%WRsWn%X+XYR3Se7-5WGm_mf1C&)J<OM=CWj#[0mdAI4R,`Tlu%nI"h=jOZ7WcujTBL3PjJ"`^84Rh-7[cj#+QpUf4.I+L&uptbkHKR+BL.DQRd[4&15h8-c"g&)k[6mN+2o;JimJmkFYobsPgD.k8X,-sZX9$!u"4D?H\\\64(V>X$44j85)dF*=+_@]5-T$RD8Be+6$"taeM12;,4#8(&Hi^R3I@uI"9l]_$Xom$*,IXfYUMeJ=;*`(VX*nGHtFadn8]r1>l8f3.A8pTUkc\BZ!SRTQaoPEW&bj4unFEX>]gs%)uLK6g[:_AF='Z>*>$W9OnPg\(.r\4?SR;!W9C9q]8cFAIFOYD';#BtkfGGt;:NJB7Cld#7*`SJgM0j0H4-ZDM%a]p*1aPhut6bYDMID0McDk'D11Z-"/e,4(Y^M'1Nl15@LYkNJ"2Ac\s\>DH/SZBY1eXeT<D$`P_dGDgh;MJmm'PRIGrlJ9b~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<35bc0d8785eb140aba00ddd9b3bbf473><35bc0d8785eb140aba00ddd9b3bbf473>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1594+%%EOFdiff --git a/data/attachments/9a4392c6-52e6-44ad-a21d-dc48dd2b2eeb/invoices/ac8a474b-988c-4cd1-ac3e-afbb173d9ee7/e818e855_1.pdf b/data/attachments/9a4392c6-52e6-44ad-a21d-dc48dd2b2eeb/invoices/ac8a474b-988c-4cd1-ac3e-afbb173d9ee7/e818e855_1.pdfnew file mode 100644index 00000000..833dd3ae--- /dev/null+++ b/data/attachments/9a4392c6-52e6-44ad-a21d-dc48dd2b2eeb/invoices/ac8a474b-988c-4cd1-ac3e-afbb173d9ee7/e818e855_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132915-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132915-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 596+>>+stream+Gau1+9lJKG&;KZQ'lsdS).mKqY7qcV[7)AL-S>uGLoR/CUuLi![b'b%`3bYY/UOViHCoCn?Om8'ao21])W5am=/QHXOM:j$[#iV,btT8ri7,_70U=[rZHNoh,En$_i9jhD$('0_,Dkpl+UD7E]#kq'VlS)@h<G1)CWJ/ELnO)(D@>u\KF6^,T6;A)TV3A1=3FAkoAOQ(ki$aWUCuil"K)68E7Ubn.Wbd9k%F:0DA&'[,d!iU<XFM?_R<s1qR!#c5WY<=etG_sFW&NZo0mOMEa*7meFO"/rWucP&7lRKXPG))(rVENR)\MY&N:!n[CO'KIQOOTW,oUoiJ9?O3EuEf,^YZ#9B'5FRlh4MW.-rYkabLtY#;@qn@`-76Z>QKhW==7+nL.<)mLGI><*Vn;gWMi37eL41C;:!/s/t8_N9XH9Wtom$AkBRRN$Q6c2U%@g./m4[>iQTf-+BE9O?_pXt]&L'jpoCV9KL]oBg.41Kc7UM_SrOY)(EgMZaMM4>==q91qM!b6j,<PB:ENK%\3+)i-oY'9,oPO(VG7hW]1=?nD4q9LIsr=A*"$;jnc:"sLC]2fXduh/q9aB`8"<$s;9~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<7d918a7d39363b3aac735764aeb90e4b><7d918a7d39363b3aac735764aeb90e4b>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1598+%%EOFdiff --git a/data/attachments/b46dce1e-5750-486b-827b-3dad6c57d5ca/invoices/1d2f1b96-66c8-4ba2-8f29-06e03767cd27/4b0cd97d_1.pdf b/data/attachments/b46dce1e-5750-486b-827b-3dad6c57d5ca/invoices/1d2f1b96-66c8-4ba2-8f29-06e03767cd27/4b0cd97d_1.pdfnew file mode 100644index 00000000..935d6b2b--- /dev/null+++ b/data/attachments/b46dce1e-5750-486b-827b-3dad6c57d5ca/invoices/1d2f1b96-66c8-4ba2-8f29-06e03767cd27/4b0cd97d_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 604+>>+stream+Gau0@9lJKG&A@sBbV>c&R$moe;VWb#/X1'uiY(c-WeROIKtksd?Df-0Bd3dclWoM%qqeu2*X:&^gZPI\_!;E4NYkk@Ig*8o+eM#jX#;TGWJQO@/9.IrR3SeG-5WGml<EidQdZs"M=CWj#[0lIaq?$kMnAl:iW\Bna=i;kK!'fOCCm[N(k=TneL$(YBP7L##KMlGoAR2go^KKh0d,bH"K)5mE7Ubn60K6LeSXt=2i1'>P3T!LQ%EG>@-]g@?#=O-OG7A2F_FZJ9u`CnFI)7!>S"?:lhptKp'iK`LshK5<j`2a#&ud\VS4#ud["G7IeDgSpRdA5;1_9>j/i]9']ngpp.nDk6>k>l]8/@jmPn)@\ms)jTA!hPGjjU<*=5)PH`?I]rm?gQ2k#_.O.NK?%J-kh4.MkAK&`4$AlkHm-oPL)`?hDCgHZ+&T2M*rH90=NJBThrIY<*_BcEgAY(:PS0R8L:]>C5qQ2KRt.XebcST!p3f:ue0=c?3^n,Vu=NKM""LBgL*HE$P-?:N:'1.c]PcS2ns^B&OD7/@kqA>XkF)/sr'j/Tsu)"_n7EnB/O>-$B*["(d\;H%oUqaf14]=L9##H>XEV#~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<da5cbc85a97083a39f79066375b600ab><da5cbc85a97083a39f79066375b600ab>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1606+%%EOFdiff --git a/data/attachments/bf1f05b9-d472-467f-83ed-3f1e49eaa7f2/invoices/c27f2774-1742-4abd-b5dc-541232450360/394c8632_1.pdf b/data/attachments/bf1f05b9-d472-467f-83ed-3f1e49eaa7f2/invoices/c27f2774-1742-4abd-b5dc-541232450360/394c8632_1.pdfnew file mode 100644index 00000000..d9412939--- /dev/null+++ b/data/attachments/bf1f05b9-d472-467f-83ed-3f1e49eaa7f2/invoices/c27f2774-1742-4abd-b5dc-541232450360/394c8632_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132915-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132915-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 595+>>+stream+Gau1+9lJKG&;KZQ'lsdS).mKqY7qcV[7)AL-S>uGLoR/CUuLi!l]6-,@bOAhQG(jo^!Ae/Ne`2XjR3"Y%IcErX&B3<aBsKM>0(@'k,+%EE%5i>N'eR6=lp"EOibQjE;-J^_SbZ!Oi2Kq&-T*]?"FJOe(*U[DY4)%2<:)]7*p($[tT&i63VA':V./Od*N8TX6$7Fq=(h$o^KKg;$lnFJl@1W3,;Ar'tSs-o<\6S2i1'>P5;,\<J"YSYjE:%54*#1O<V#A*D4JRA3=YR(V.6#D5I2/cR5+W-`EFVascOX]1$*^L`;%&NSB".Xr$kKF+<l]G#Fs[b44&:,C4BN[eQaHH]`Y,nLgP1SpO2]^$ZVWPtt\g16gY5pNe+o_&[*6Qcm^0bkoLu`-V&lj_2k6mD[3,>TK>H&su%e7)DbH$u%+&e*/GT+n9VGF$ia$q&d[OqoG,9ARi*f'nhKua\+b+.L`mU`E0h*ct7X\q0'*UR5BiD@Z9#l/)kXH,(W)k%nn&B;X8\ECd`338NJY7_<g4Q:&3sdCYo!ZKM'lY]ri<5"+D4gT=FUFTri'(RZ=f\+g#EriYX,h[,2R2rW$IE=MF~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<a9a8800f7170aa889cd271a60eb055c6><a9a8800f7170aa889cd271a60eb055c6>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1597+%%EOFdiff --git a/data/attachments/e0bb89a7-e796-45b9-85cd-6ff5e053f45e/invoices/398cf73a-d3ef-4257-817d-704c56e52abc/00cdc097_1.pdf b/data/attachments/e0bb89a7-e796-45b9-85cd-6ff5e053f45e/invoices/398cf73a-d3ef-4257-817d-704c56e52abc/00cdc097_1.pdfnew file mode 100644index 00000000..ab18b58e--- /dev/null+++ b/data/attachments/e0bb89a7-e796-45b9-85cd-6ff5e053f45e/invoices/398cf73a-d3ef-4257-817d-704c56e52abc/00cdc097_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 599+>>+stream+Gau0@gMYJ*&:O:Sb[WnKR$kY&;HspcMqT_1i["YW<&Geu<;\qdp,[?EKJl`ngKLrL4_N%[%g2(<h=KA6i'W7nV[P,<IfN][OO'TE9c"W(<8o)=CE+d+jp::8ai,ZIs0I*iFa(ks@_=r3K%?+QZ@p?a@eF]TGQ[aWo%PmTT^1Ol)T:qR7NbIuD&^Cr1phtQU[@emF8`(Ho^K?c2'V=N"K)5mE7Ubn;<SMPc(F-4DA&'[,h5biQ%EG>@-]O8IG<aT+GFFL3g>k-a`u7*cZ4ApgCa014eKRG]g0OF;$KoOWYU0)+Dr=A1mA)2\ro`>+''>7gLOsH2r;,b6q'krB)`TV-fe#g]SgHekFN?0dli?/pXEb(eTd/4l^]^4GEh+4k?e[dbIuSbp#t)Od4fLmMj)i)._$Ra^`;VO$.U7/WER5^Hjca3paN&=U$'mP"_8snSfhBWgW!o^.hF<G-84ms<u?%7OrsX)[E8-ToC(5hDQd/9(1Ykn4$n<d=!Vb+i=V9S?7LB,QP&kM9[]4%4&!B45D"5P7/@i3A>Yi37bg2nIG8/2%#-M0\SG]WI8t,u3l!$IWN!Rf6_nhQ^+Re1"6Ff1B)~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<abc41d0f2f625cd950ad650e56e583fa><abc41d0f2f625cd950ad650e56e583fa>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1601+%%EOFdiff --git a/data/attachments/e156a22a-59cf-45ce-a957-2617d59de762/invoices/bb5c31d1-45d1-4917-bb78-8239a8803aa1/9cf11ac4_1.pdf b/data/attachments/e156a22a-59cf-45ce-a957-2617d59de762/invoices/bb5c31d1-45d1-4917-bb78-8239a8803aa1/9cf11ac4_1.pdfnew file mode 100644index 00000000..f2da27f7--- /dev/null+++ b/data/attachments/e156a22a-59cf-45ce-a957-2617d59de762/invoices/bb5c31d1-45d1-4917-bb78-8239a8803aa1/9cf11ac4_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 602+>>+stream+Gau0@gMYJ*&:O:Sb[Wo_0Je'*V79N%>:A1uM3j$fW#D[j(4Mm\]hV9?dma\YXYm`IF6:^:0T_m]5!LV"?>"M*`4uHM/$MGMq#otf[;c4B9j@g2M'F=i*+:uc\JPKNhjR?Nm-Y]^N#)accs"k'Q7t=>f.L0-FUfIQ7NCF=k.0K6TPr!5s`.D1\.*L,L`1Yl334+-%j@&&5.e"/9*nE!ifPB.\u[KW\`ih,]SXPDDUMWK'$A'FYoa>E9rmgBM9lBkTD-LF2-4A3?heB=U4LomlqMSkia3?_Ck_-p=PB<K"Y%&D%S*lH=`&D+Q)C='pE)s1,WW-"tdhhR]p];%?B6s3tR0jAo!fMeJ=;NYAhL*J;r>e0Z]bHOo$"SM12UQho"j*t=W^UY1Irkh4,80JDau_qD"=30$R<G.!0[@M=Jq>[gmN%A]*\.Aa#;VpkPSa@pnC69a;6NR9*)5e'@P]Yp@H@F4C6Idh9@525VQ2g:2G;6cK>`i(J6JG>YS8DoTI"""ht<;K?C,Np/9Uau%LQs@kmJ3+ktrJc+Ye%aKC\@pGiWkqjToOI0,fA9\7X4l"/J4gGO;gT2T8CLDI\j5onWPr#:~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<c3f967e35047f01343726c0c6a94f045><c3f967e35047f01343726c0c6a94f045>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1604+%%EOFdiff --git a/data/attachments/efac7b3e-31bf-434c-945d-7f10969e02cb/invoices/5a1b199e-814d-404f-97bd-e66a73f348bf/11a5bd6e_1.pdf b/data/attachments/efac7b3e-31bf-434c-945d-7f10969e02cb/invoices/5a1b199e-814d-404f-97bd-e66a73f348bf/11a5bd6e_1.pdfnew file mode 100644index 00000000..89d15507--- /dev/null+++ b/data/attachments/efac7b3e-31bf-434c-945d-7f10969e02cb/invoices/5a1b199e-814d-404f-97bd-e66a73f348bf/11a5bd6e_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132915-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132915-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 827+>>+stream+Gb!#Z>u)A9&:NGC0orcjgR5V0O&V7gTI?milAMXqBLH$]D>N]_qZR?[#gJg&c$naAh0[Gk3Hl;AP_8Pmf*T75'L&$"&4:aKA<_Xe!8TKR`u-:;j30!;isMP)$F%#Rg(5*5hm-%V>htQ0erIRn<lUf614b),lhU/=qAl@BOM7oNYd-:%?%=p1q&5'#H!1I#?>3Z^T\At+Q5T?.;@\.':GnkA85Sq4!GdX'>8qmAEUk?")&ig7kbI39?4-p2>/1nt+67-q1BM2GZ`&9fEm,^kkaqIrmWmNgEPIau(!PeHP"Zt-,.3V<#Y'*J'f!Qt%`N5lJj8GE2ttd\r3SH()=(MNaml%=2'n6DN@Aj*-kdU9S1oFu0Z]fGH)t7SDu%):;0d(aO`rqeU/;F[7`34p7tt6cr7jG"m[m&T2e+&qI9j_(F9t5a9ql^C)'gH=,E,,`YD;oXaM^foQ^`/][8EmT]hMo=[KUl9L?HJ2W,pO@P:g*^HCaG,/J?YFr!r/A/um!g_+GHtdu[aq>sXa=;AAjB<'W+E=qZ3-4?A,RW1n7<qQdr@ZI>/0UE/Z*ID;7GTB<=)IKb)=4R?T_gpUW,.^U;/e&lBC.k.X@-U<G&;2XU)OjuH$MR4nRn-NuM+7F^8cMm17'Ac!4`Y.i_8,P;$I$4(E;5#73h.&`=qOFk9&J@:^`=jq&bJ/AMjZqDN8C(A]iIY$G;E9ob=tc[T9=("Z=G__PLV54;<dQ4"et\K.C8"rpSR4U!'TUP=&>YSn+n!cdMS0c#,pno2M#e"O1b339f<s(_\>nBMS:As^<,fB#N7&_+*NG6u/s,u7oEB5&~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<79f44ff4b46a2a55575e6398aa4a7ef4><79f44ff4b46a2a55575e6398aa4a7ef4>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1829+%%EOFdiff --git a/data/attachments/ff9645a1-c681-46a0-95ec-1c2952a5894f/invoices/ab2a77a7-fee5-411f-95d3-a0df218635ba/8c2fb48c_1.pdf b/data/attachments/ff9645a1-c681-46a0-95ec-1c2952a5894f/invoices/ab2a77a7-fee5-411f-95d3-a0df218635ba/8c2fb48c_1.pdfnew file mode 100644index 00000000..0449d048--- /dev/null+++ b/data/attachments/ff9645a1-c681-46a0-95ec-1c2952a5894f/invoices/ab2a77a7-fee5-411f-95d3-a0df218635ba/8c2fb48c_1.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (anonymous) /CreationDate (D:20260930132914-03'00') /Creator (anonymous) /Keywords () /ModDate (D:20260930132914-03'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Fatura 1) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 602+>>+stream+Gau0@gMYJ*&:O:Sb[Wo_0Je'*V79N%>:A1uM3j$fW#D[j(4Mm\]hV9?dma\YXYm`IF6:^:0T_m]5!LV"?>"M*`4uHM/$MGMq#otf[;c4B9j@g2M'F=i*+:uc\JPKNhjR?Nm-Y]^N#)accs"k'Q7t=>f.L0-FUfIQ7NCF=k.0K6TPr!5s`.D1\.*L,L`1Yl334+-%j@&&5.e"/9*nE!ifPB.\u[KW\`ih,]SXPDDUMWK'$A'FYoa>E9rmgBM9lBkTD-LF2-4A3?heB=U4LomlqMSkia3?_Ck_-p=PB<K"Y%&D%S*lH=`&D+Q)C='pE)s1,WW-"tdhhR]p];%?B6s3tR0jAo!fMeJ=;NYAhL*J;r>e0Z]bHOo$"SM12UQho"j*t=W^UY1Irkh4,80JDau_qD"=30$R<G.!0[@M=Jq>[gmN%A]*\.Aa#;VpkPSa@pnC69a;6NR9*)5e'@P]Yp@H@F4C6Idh9@525VQ2g:2G;6cK>`i(J6JG>YS8DoTI"""ht<;K?C,Np/9Uau%LQs@kmJ3+ktrJc+Ye%aKC\@pGiWkqjToOI0,fA9\7X4l"/J4gGO;gT2T8CLDI\j5onWPr#:~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000321 00000 n+0000000524 00000 n+0000000592 00000 n+0000000853 00000 n+0000000912 00000 n+trailer+<<+/ID+[<a9b9a5aa9386c33ed5520bac561c4705><a9b9a5aa9386c33ed5520bac561c4705>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+1604+%%EOFdiff --git a/frontend/src/components/transaction-dialog.test.tsx b/frontend/src/components/transaction-dialog.test.tsxindex 4512f8ac..ceaed895 100644--- a/frontend/src/components/transaction-dialog.test.tsx+++ b/frontend/src/components/transaction-dialog.test.tsx@@ -2,7 +2,7 @@ import { screen, within } from '@testing-library/react'import { afterEach, expect, it, vi } from 'vitest'import { TransactionDialog } from '@/components/transaction-dialog'-import { currencies, groups, payees, transactions } from '@/lib/api'+import { assets, currencies, groups, mortgagePayments, payees, transactions } from '@/lib/api'import { renderWithProviders, t } from '@/test/utils'import type { Account, RecurringTransaction, Transaction } from '@/types'@@ -253,3 +253,145 @@ it('unlinks the pair only after the unlink confirmation is accepted', async () =expect(onUnlinkTransfer).toHaveBeenCalledTimes(1)expect(onUnlinkTransfer).toHaveBeenCalledWith('pair-1160')})++it.each([+ ['ignored transaction', { is_ignored: true }],+ ['transfer', { transfer_pair_id: 'pair-1160' }],+ ['ignored category', { category: { id: 'ignored', is_ignored: true } as Transaction['category'] }],+])('hides mortgage allocation controls for an ineligible %s', async (_name, overrides) => {+ vi.spyOn(currencies, 'list').mockResolvedValue([])+ vi.spyOn(payees, 'list').mockResolvedValue([])+ vi.spyOn(groups, 'list').mockResolvedValue([])+ const getAllocations = vi.spyOn(mortgagePayments, 'get').mockResolvedValue({+ payment_transaction_id: 'tx-1160-leg',+ payment_amount: 250,+ currency: 'USD',+ payment_account_name: 'Zeta Bank',+ allocations: [],+ principal_total: 0,+ interest_total: 0,+ principal_percentage: 0,+ interest_percentage: 0,+ })+ const securedLoan = {+ id: 'loan-1',+ name: 'Mortgage',+ type: 'loan',+ currency: 'USD',+ secured_asset_id: 'property-1',+ } as Account++ renderWithProviders(+ <TransactionDialog+ open+ onClose={vi.fn()}+ transaction={transferLegFixture('pair-1160', {+ source: 'sync',+ transfer_pair_id: null,+ ...overrides,+ })}+ categories={[]}+ categoryGroups={[]}+ accounts={[...accountFixtures, securedLoan]}+ onSave={vi.fn()}+ loading={false}+ error={null}+ />,+ )++ expect(screen.queryByText(t('transactions.mortgageAllocation'))).not.toBeInTheDocument()+ expect(getAllocations).not.toHaveBeenCalled()+})++it('reads the split against the payment, not against the parts entered so far', async () => {+ vi.spyOn(currencies, 'list').mockResolvedValue([])+ vi.spyOn(payees, 'list').mockResolvedValue([])+ vi.spyOn(groups, 'list').mockResolvedValue([])+ vi.spyOn(assets, 'list').mockResolvedValue([])+ vi.spyOn(mortgagePayments, 'get').mockResolvedValue({+ payment_transaction_id: 'tx-1160-leg',+ payment_amount: 250,+ currency: 'USD',+ payment_account_name: 'Zeta Bank',+ allocations: [],+ principal_total: 0,+ interest_total: 0,+ principal_percentage: 0,+ interest_percentage: 0,+ })+ const securedLoan = {+ id: 'loan-1',+ name: 'Mortgage',+ type: 'loan',+ currency: 'USD',+ secured_asset_id: 'property-1',+ } as Account+ const { user } = renderWithProviders(+ <TransactionDialog+ open+ onClose={vi.fn()}+ transaction={transferLegFixture('pair-1160', { source: 'sync', transfer_pair_id: null })}+ categories={[]}+ categoryGroups={[]}+ accounts={[...accountFixtures, securedLoan]}+ onSave={vi.fn()}+ loading={false}+ error={null}+ />,+ )++ await user.click(await screen.findByRole('button', { name: t('transactions.mortgageAllocation') }))+ await user.type(await screen.findByLabelText(t('transactions.mortgagePrincipal')), '100')++ // 100 of a 250 payment is 40%, with the rest of the payment still+ // unallocated. Against the parts alone it would read as the whole payment.+ expect(+ await screen.findByText(t('transactions.mortgageSplitPercentages', { principal: '40.0', interest: '0.0' })),+ ).toBeInTheDocument()+})++it('does not submit the transaction when Enter is pressed in a mortgage split field', async () => {+ vi.spyOn(currencies, 'list').mockResolvedValue([])+ vi.spyOn(payees, 'list').mockResolvedValue([])+ vi.spyOn(groups, 'list').mockResolvedValue([])+ vi.spyOn(assets, 'list').mockResolvedValue([])+ vi.spyOn(mortgagePayments, 'get').mockResolvedValue({+ payment_transaction_id: 'tx-1160-leg',+ payment_amount: 250,+ currency: 'USD',+ payment_account_name: 'Zeta Bank',+ allocations: [],+ principal_total: 0,+ interest_total: 0,+ principal_percentage: 0,+ interest_percentage: 0,+ })+ const onSave = vi.fn()+ const securedLoan = {+ id: 'loan-1',+ name: 'Mortgage',+ type: 'loan',+ currency: 'USD',+ secured_asset_id: 'property-1',+ } as Account+ const { user } = renderWithProviders(+ <TransactionDialog+ open+ onClose={vi.fn()}+ transaction={transferLegFixture('pair-1160', { source: 'sync', transfer_pair_id: null })}+ categories={[]}+ categoryGroups={[]}+ accounts={[...accountFixtures, securedLoan]}+ onSave={onSave}+ loading={false}+ error={null}+ />,+ )++ await user.click(await screen.findByRole('button', { name: t('transactions.mortgageAllocation') }))+ const principalInput = await screen.findByLabelText(t('transactions.mortgagePrincipal'))+ await user.type(principalInput, '100')+ await user.keyboard('{Enter}')++ expect(onSave).not.toHaveBeenCalled()+})diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsxindex 2863bc5e..00d3cd38 100644--- a/frontend/src/components/transaction-dialog.tsx+++ b/frontend/src/components/transaction-dialog.tsx@@ -4,11 +4,13 @@ import { useTranslation } from 'react-i18next'import { Link } from 'react-router-dom'import { useDateLocale, useDisplayLocale } from '@/hooks/use-display-locale'import { formatAmountInput, formatCurrency, parseAmountInput } from '@/lib/format'+import { amountToCents, parseCents } from '@/lib/mortgage-split'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { useAuth } from '@/contexts/auth-context'-import { currencies as currenciesApi, transactions as transactionsApi, settings as settingsApi, payees as payeesApi, rules as rulesApi, categories as categoriesApi, categoryGroups as categoryGroupsApi } from '@/lib/api'+import { assets as assetsApi, currencies as currenciesApi, transactions as transactionsApi, settings as settingsApi, payees as payeesApi, rules as rulesApi, categories as categoriesApi, categoryGroups as categoryGroupsApi, mortgagePayments as mortgagePaymentsApi } from '@/lib/api'import { localDateString } from '@/lib/date-utils'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'+import { extractApiError } from '@/lib/api-errors'import { normalizeRuleMatchValue } from '@/lib/rule-match-utils'import { findCategoryReference, getRuleCategoryId } from '@/lib/category-reference-utils'import { flattenConditions, hasConditionGroups } from '@/lib/rule-conditions'@@ -117,7 +119,7 @@ export function TransactionDialog({transaction: Transaction | nullcategories: Category[]categoryGroups: CategoryGroup[]- accounts: { id: string; name: string; display_name?: string | null; type?: string; currency?: string }[]+ accounts: { id: string; name: string; display_name?: string | null; type?: string; currency?: string; secured_asset_id?: string | null }[]recurringMatch?: RecurringTransactiononSave: (data: TransactionSavePayload, recurringData?: { frequency: string; end_date?: string }, installmentData?: InstallmentSeriesInput, pendingFiles?: File[], action?: SaveAction) => voidonDelete?: () => void@@ -406,7 +408,7 @@ function TransactionForm({defaultAccountId?: stringcategories: Category[]categoryGroups: CategoryGroup[]- accounts: { id: string; name: string; display_name?: string | null; type?: string; currency?: string }[]+ accounts: { id: string; name: string; display_name?: string | null; type?: string; currency?: string; secured_asset_id?: string | null }[]recurringMatch?: RecurringTransactiononSave: (data: TransactionEditPayload, recurringData?: { frequency: string; end_date?: string }, installmentData?: InstallmentSeriesInput, pendingFiles?: File[], action?: SaveAction) => voidonDelete?: () => void@@ -1305,6 +1307,10 @@ function TransactionForm({/>)}+ {!isCreating && transaction?.type === 'debit' && transaction.status === 'posted' && !transaction.is_ignored && !transaction.transfer_pair_id && !transaction.category?.is_ignored && Number(transaction.amount) > 0 && accounts.find(a => a.id === transaction.account_id)?.type !== 'loan' && accounts.some(a => a.type === 'loan' && a.secured_asset_id) && (+ <MortgagePaymentEditor transaction={transaction} accounts={accounts} />+ )}+{!isCreating && transaction ? (<TransactionAttachmentstransactionId={transaction.id}@@ -1548,6 +1554,120 @@ function TransactionForm({)}+function MortgagePaymentEditor({+ transaction,+ accounts,+}: {+ transaction: Transaction+ accounts: { id: string; name: string; display_name?: string | null; type?: string; currency?: string; secured_asset_id?: string | null }[]+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const loans = useMemo(+ () => accounts.filter(account => account.type === 'loan' && account.secured_asset_id && account.currency === transaction.currency),+ [accounts, transaction.currency],+ )+ const account = accounts.find(item => item.id === transaction.account_id)+ const { data } = useQuery({+ queryKey: ['mortgage-payment', transaction.id],+ queryFn: () => mortgagePaymentsApi.get(transaction.id),+ })+ const [draftAmounts, setDraftAmounts] = useState<Record<string, { principal: string; interest: string }> | null>(null)+ const [expandedOverride, setExpandedOverride] = useState<boolean | null>(null)+ const isExpanded = expandedOverride ?? !!data?.allocations.length+ const amounts = draftAmounts ?? Object.fromEntries((data?.allocations ?? []).map(row => [row.loan_account_id, {+ principal: String(row.principal_amount), interest: String(row.interest_amount),+ }]))+ const { data: propertyAssets } = useQuery({+ queryKey: ['assets'],+ queryFn: () => assetsApi.list(),+ })+ const refreshMortgageData = async () => {+ invalidateFinancialQueries(queryClient)+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ['mortgage-payment', transaction.id] }),+ queryClient.invalidateQueries({ queryKey: ['accounts'] }),+ queryClient.invalidateQueries({ queryKey: ['mortgage-balance-history'] }),+ queryClient.invalidateQueries({ queryKey: ['transactions'] }),+ queryClient.invalidateQueries({ queryKey: ['reports'] }),+ ])+ }+ const save = useMutation({+ mutationFn: () => mortgagePaymentsApi.replace(transaction.id, loans+ .filter(item => amounts[item.id])+ .map(item => ({+ loan_account_id: item.id,+ principal_amount: (parseCents(amounts[item.id].principal) ?? 0) / 100,+ interest_amount: (parseCents(amounts[item.id].interest) ?? 0) / 100,+ }))),+ onSuccess: async () => {+ await refreshMortgageData()+ toast.success(t('transactions.mortgageSaved'))+ },+ onError: (error) => toast.error(extractApiError(error, t('transactions.mortgageSaveError'))),+ })+ const remove = useMutation({+ mutationFn: () => mortgagePaymentsApi.remove(transaction.id),+ onSuccess: async () => {+ setDraftAmounts(null)+ await refreshMortgageData()+ toast.success(t('transactions.mortgageRemoved'))+ },+ onError: (error) => toast.error(extractApiError(error, t('transactions.mortgageSaveError'))),+ })+ if (account?.type === 'loan' || loans.length === 0) return null+ // Compare whole cents: the backend requires two decimals and an exact total.+ const parts = loans.flatMap(item => {+ const value = amounts[item.id]+ return value ? [parseCents(value.principal), parseCents(value.interest)] : []+ })+ const partsValid = parts.every(cents => cents !== null)+ const totalCents = parts.reduce<number>((sum, cents) => sum + (cents ?? 0), 0)+ const total = totalCents / 100+ // Share of the payment, not of the parts entered so far: the label says+ // "payment split", and while the parts are still short of the payment a+ // denominator of their own sum reads as 100% of a payment half allocated.+ const paymentAmount = Number(transaction.amount)+ const percentage = (value: string, totalAmount: number) => totalAmount ? (Number(value || 0) / totalAmount * 100).toFixed(1) : '0.0'+ return (+ <section className="rounded-lg border border-border p-3 space-y-3">+ <button type="button" className="w-full text-left text-sm font-medium" onClick={() => setExpandedOverride(!isExpanded)}>+ {t('transactions.mortgageAllocation')}+ {data?.allocations.length ? ' · ' + data.allocations.length : ''}+ </button>+ {isExpanded && <>+ <p className="text-xs text-muted-foreground">{t('transactions.mortgageCurrencyHint', { currency: transaction.currency })}</p>+ {loans.map(loan => {+ const value = amounts[loan.id] ?? { principal: '', interest: '' }+ const propertyName = propertyAssets?.find(asset => asset.id === loan.secured_asset_id)?.name+ return (+ <div key={loan.id} className="rounded-md bg-muted/40 p-3 space-y-2">+ <div className="text-sm font-medium">{loan.display_name || loan.name}{propertyName ? <span className="ml-1 text-xs font-normal text-muted-foreground">· {propertyName}</span> : null}</div>+ <div className="grid grid-cols-2 gap-3">+ <label className="text-xs text-muted-foreground">{t('transactions.mortgagePrincipal')}+ <Input type="number" min="0" step="0.01" value={value.principal} onKeyDown={e => { if (e.key === 'Enter') e.preventDefault() }} onChange={e => setDraftAmounts(prev => ({ ...(prev ?? amounts), [loan.id]: { ...value, principal: e.target.value } }))} />+ </label>+ <label className="text-xs text-muted-foreground">{t('transactions.mortgageInterest')}+ <Input type="number" min="0" step="0.01" value={value.interest} onKeyDown={e => { if (e.key === 'Enter') e.preventDefault() }} onChange={e => setDraftAmounts(prev => ({ ...(prev ?? amounts), [loan.id]: { ...value, interest: e.target.value } }))} />+ </label>+ </div>+ <p className="text-xs text-muted-foreground">{t('transactions.mortgageSplitPercentages', { principal: percentage(value.principal, paymentAmount), interest: percentage(value.interest, paymentAmount) })}</p>+ </div>+ )+ })}+ <p className="text-xs text-muted-foreground">{t('transactions.mortgagePaymentTotal', { total: total.toFixed(2), payment: Number(transaction.amount).toFixed(2), currency: transaction.currency })}</p>+ <Button type="button" size="sm" variant="outline" disabled={save.isPending || !partsValid || totalCents <= 0 || totalCents !== amountToCents(Number(transaction.amount))} onClick={() => save.mutate()}>+ {save.isPending ? t('common.saving') : t('transactions.saveMortgageAllocation')}+ </Button>+ {data?.allocations.length ? <Button type="button" size="sm" variant="ghost" disabled={remove.isPending} onClick={() => remove.mutate()}>{t('transactions.removeMortgageAllocation')}</Button> : null}+ {data?.allocations.length ? <p className="text-xs text-muted-foreground">{t('transactions.mortgageSavedSummary', { principal: data.principal_total.toFixed(2), interest: data.interest_total.toFixed(2), currency: data.currency, principalPercentage: data.principal_percentage.toFixed(1), interestPercentage: data.interest_percentage.toFixed(1) })}</p> : null}+ {data?.allocations.some(row => row.historical) && <p className="text-xs text-muted-foreground">{t('transactions.mortgageHistoricalNote')}</p>}+ {data?.allocations.some(row => row.bank_managed) && <p className="text-xs text-muted-foreground">{t('transactions.mortgageBankManagedNote')}</p>}+ </>}+ </section>+ )+}+function AddTransactionToRuleDialog({open,onOpenChange,diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex b71650ce..9f1ff32a 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -550,6 +550,49 @@ export const accounts = {},}+export interface MortgagePaymentAllocation {+ loan_account_id: string+ loan_name: string+ principal_amount: number+ interest_amount: number+ payment_amount: number+ principal_percentage: number+ interest_percentage: number+ historical: boolean+ bank_managed: boolean+}++export const mortgagePayments = {+ get: async (paymentId: string): Promise<{+ payment_transaction_id: string+ payment_amount: number+ currency: string+ payment_account_name: string+ allocations: MortgagePaymentAllocation[]+ principal_total: number+ interest_total: number+ principal_percentage: number+ interest_percentage: number+ }> => {+ const { data } = await api.get(`/mortgage-payments/${paymentId}`)+ return data+ },+ replace: async (+ paymentId: string,+ allocations: {+ loan_account_id: string+ principal_amount: number+ interest_amount: number+ }[],+ ) => {+ const { data } = await api.put(`/mortgage-payments/${paymentId}`, { allocations })+ return data+ },+ remove: async (paymentId: string): Promise<void> => {+ await api.delete(`/mortgage-payments/${paymentId}`)+ },+}+// Transactionsexport const transactions = {list: async (params?: {diff --git a/frontend/src/lib/mortgage-split.test.ts b/frontend/src/lib/mortgage-split.test.tsnew file mode 100644index 00000000..3bff185e--- /dev/null+++ b/frontend/src/lib/mortgage-split.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest'++import { amountToCents, parseCents } from '@/lib/mortgage-split'++describe('mortgage split cents', () => {+ it('parses whole and two-decimal amounts into cents', () => {+ expect(parseCents('167.76')).toBe(16776)+ expect(parseCents('65,07')).toBe(6507)+ expect(parseCents('150')).toBe(15000)+ expect(parseCents('0.5')).toBe(50)+ expect(parseCents('')).toBe(0)+ })++ it('rejects fractional cents and malformed input', () => {+ expect(parseCents('100.001')).toBeNull()+ expect(parseCents('-5')).toBeNull()+ expect(parseCents('abc')).toBeNull()+ })++ it('catches a one-cent mismatch that float tolerance let through', () => {+ const total = (parseCents('100.00') ?? 0) + (parseCents('132.84') ?? 0)+ expect(total).not.toBe(amountToCents(232.83))+ expect((parseCents('100.00') ?? 0) + (parseCents('132.83') ?? 0)).toBe(amountToCents(232.83))+ })+})diff --git a/frontend/src/lib/mortgage-split.ts b/frontend/src/lib/mortgage-split.tsnew file mode 100644index 00000000..d915285e--- /dev/null+++ b/frontend/src/lib/mortgage-split.ts@@ -0,0 +1,17 @@+/**+ * Parse a principal or interest input into whole cents. Empty counts as zero;+ * anything negative, non-numeric or with more than two decimals is rejected,+ * matching the backend's `decimal_places=2` validation.+ */+export function parseCents(value: string): number | null {+ const trimmed = value.trim()+ if (trimmed === '') return 0+ const match = /^(\d+)(?:[.,](\d{0,2}))?$/.exec(trimmed)+ if (!match) return null+ return Number(match[1]) * 100 + Number((match[2] ?? '').padEnd(2, '0'))+}++/** Whole cents of a payment amount as the API reports it. */+export function amountToCents(amount: number): number {+ return Math.round(amount * 100)+}diff --git a/frontend/src/locales/cs.json b/frontend/src/locales/cs.jsonindex 0038b846..46699fb6 100644--- a/frontend/src/locales/cs.json+++ b/frontend/src/locales/cs.json@@ -920,6 +920,20 @@},"transactions": {"title": "Transakce",+ "mortgageAllocation": "Rozpis splátky hypotéky",+ "mortgagePrincipal": "Splátka jistiny",+ "mortgageInterest": "Úrok",+ "mortgageCurrencyHint": "Zadejte všechny části v {{currency}}.",+ "mortgageSplitPercentages": "Rozdělení splátky: {{principal}}% jistina / {{interest}}% úrok",+ "mortgagePaymentTotal": "Součet částí: {{currency}} {{total}}; splátka: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Uložit rozpis hypotéky",+ "mortgageSaved": "Rozpis hypotéky uložen",+ "mortgageRemoved": "Rozpis hypotéky odstraněn",+ "removeMortgageAllocation": "Odstranit rozpis",+ "mortgageSaveError": "Rozpis hypotéky se nepodařilo uložit. Zkontrolujte, zda se části rovnají splátce.",+ "mortgageSavedSummary": "Uložené součty: {{currency}} {{principal}} jistina ({{principalPercentage}}%) a {{currency}} {{interest}} úrok ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Tato splátka předchází zaznamenanému zůstatku hypotéky. Rozdělení se uloží, dluh se ale znovu nesnižuje.",+ "mortgageBankManagedNote": "Zůstatek tohoto úvěru hlásí vaše banka, proto se rozdělení uloží bez opětovného zaúčtování jistiny.","section": "Finance","monthPrevious": "Předchozí měsíc","monthNext": "Další měsíc",diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 6645590e..20ac2228 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -888,6 +888,20 @@},"transactions": {"title": "Transaktionen",+ "mortgageAllocation": "Aufteilung der Hypothekenzahlung",+ "mortgagePrincipal": "Tilgung",+ "mortgageInterest": "Zinsen",+ "mortgageCurrencyHint": "Alle Teilbeträge in {{currency}} angeben.",+ "mortgageSplitPercentages": "Aufteilung der Zahlung: {{principal}}% Tilgung / {{interest}}% Zinsen",+ "mortgagePaymentTotal": "Summe der Teilbeträge: {{currency}} {{total}}; Zahlung: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Aufteilung der Hypothek speichern",+ "mortgageSaved": "Aufteilung der Hypothek gespeichert",+ "mortgageRemoved": "Aufteilung der Hypothek entfernt",+ "removeMortgageAllocation": "Aufteilung entfernen",+ "mortgageSaveError": "Aufteilung konnte nicht gespeichert werden. Prüfen Sie, ob die Teilbeträge die Zahlung ergeben.",+ "mortgageSavedSummary": "Gespeicherte Summen: {{currency}} {{principal}} Tilgung ({{principalPercentage}}%) und {{currency}} {{interest}} Zinsen ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Diese Zahlung liegt vor dem erfassten Hypothekensaldo. Die Aufteilung wird gespeichert, die Schuld wird aber nicht erneut verringert.",+ "mortgageBankManagedNote": "Ihre Bank meldet den Saldo dieses Darlehens, daher wird die Aufteilung gespeichert, ohne die Tilgung erneut zu buchen.","section": "Finanzen","monthPrevious": "Vorheriger Monat","monthNext": "Nächster Monat",diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex 19d4095e..78c24457 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -1142,6 +1142,20 @@},"transactions": {"title": "Συναλλαγές",+ "mortgageAllocation": "Ανάλυση πληρωμής στεγαστικού δανείου",+ "mortgagePrincipal": "Αποπληρωμή κεφαλαίου",+ "mortgageInterest": "Τόκοι",+ "mortgageCurrencyHint": "Καταχωρίστε όλα τα μέρη σε {{currency}}.",+ "mortgageSplitPercentages": "Κατανομή πληρωμής: {{principal}}% κεφάλαιο / {{interest}}% τόκοι",+ "mortgagePaymentTotal": "Σύνολο μερών: {{currency}} {{total}}· πληρωμή: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Αποθήκευση ανάλυσης",+ "mortgageSaved": "Η ανάλυση του στεγαστικού δανείου αποθηκεύτηκε",+ "mortgageRemoved": "Η ανάλυση του στεγαστικού δανείου αφαιρέθηκε",+ "removeMortgageAllocation": "Αφαίρεση ανάλυσης",+ "mortgageSaveError": "Δεν ήταν δυνατή η αποθήκευση της ανάλυσης. Ελέγξτε ότι τα μέρη αθροίζουν στο ποσό της πληρωμής.",+ "mortgageSavedSummary": "Αποθηκευμένα σύνολα: {{currency}} {{principal}} κεφάλαιο ({{principalPercentage}}%) και {{currency}} {{interest}} τόκοι ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Αυτή η πληρωμή προηγείται του καταγεγραμμένου υπολοίπου του δανείου. Η κατανομή αποθηκεύεται, αλλά το χρέος δεν μειώνεται ξανά.",+ "mortgageBankManagedNote": "Η τράπεζά σας δηλώνει το υπόλοιπο αυτού του δανείου, οπότε η κατανομή αποθηκεύεται χωρίς να καταχωριστεί ξανά το κεφάλαιο.","section": "Οικονομικά","monthPrevious": "Προηγούμενος μήνας","monthNext": "Επόμενος μήνας",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 1a22fe31..28a6a9de 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -888,6 +888,20 @@},"transactions": {"title": "Transactions",+ "mortgageAllocation": "Mortgage payment breakdown",+ "mortgagePrincipal": "Principal repayment",+ "mortgageInterest": "Interest",+ "mortgageCurrencyHint": "Enter all parts in {{currency}}.",+ "mortgageSplitPercentages": "Payment split: {{principal}}% principal / {{interest}}% interest",+ "mortgagePaymentTotal": "Parts total: {{currency}} {{total}}; payment: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Save mortgage breakdown",+ "mortgageSaved": "Mortgage breakdown saved",+ "mortgageRemoved": "Mortgage breakdown removed",+ "removeMortgageAllocation": "Remove breakdown",+ "mortgageSaveError": "Could not save mortgage breakdown. Check that the parts add up to the payment.",+ "mortgageSavedSummary": "Saved totals: {{currency}} {{principal}} principal ({{principalPercentage}}%) and {{currency}} {{interest}} interest ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "This payment predates the recorded mortgage balance. Its split is saved, but the debt is not reduced again.",+ "mortgageBankManagedNote": "Your bank reports this loan's balance, so the split is saved without posting the principal again.","section": "Financial","monthPrevious": "Previous month","monthNext": "Next month",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex cc34861d..d69c3862 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -890,6 +890,20 @@},"transactions": {"title": "Transacciones",+ "mortgageAllocation": "Desglose del pago de la hipoteca",+ "mortgagePrincipal": "Amortización de capital",+ "mortgageInterest": "Intereses",+ "mortgageCurrencyHint": "Introduce todas las partes en {{currency}}.",+ "mortgageSplitPercentages": "División del pago: {{principal}}% capital / {{interest}}% intereses",+ "mortgagePaymentTotal": "Total de las partes: {{currency}} {{total}}; pago: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Guardar desglose de la hipoteca",+ "mortgageSaved": "Desglose de la hipoteca guardado",+ "mortgageRemoved": "Desglose de la hipoteca eliminado",+ "removeMortgageAllocation": "Eliminar desglose",+ "mortgageSaveError": "No se pudo guardar el desglose. Comprueba que las partes sumen el importe del pago.",+ "mortgageSavedSummary": "Totales guardados: {{currency}} {{principal}} de capital ({{principalPercentage}}%) y {{currency}} {{interest}} de intereses ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Este pago es anterior al saldo registrado de la hipoteca. Su división se guarda, pero la deuda no se reduce de nuevo.",+ "mortgageBankManagedNote": "Tu banco informa del saldo de este préstamo, así que la división se guarda sin registrar de nuevo la amortización.","section": "Financiero","monthPrevious": "Mes anterior","monthNext": "Mes siguiente",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex f1ddae50..0005c4b6 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -890,6 +890,20 @@},"transactions": {"title": "Transactions",+ "mortgageAllocation": "Répartition du paiement du prêt immobilier",+ "mortgagePrincipal": "Remboursement du capital",+ "mortgageInterest": "Intérêts",+ "mortgageCurrencyHint": "Saisissez toutes les parts en {{currency}}.",+ "mortgageSplitPercentages": "Répartition du paiement : {{principal}}% de capital / {{interest}}% d'intérêts",+ "mortgagePaymentTotal": "Total des parts : {{currency}} {{total}} ; paiement : {{currency}} {{payment}}",+ "saveMortgageAllocation": "Enregistrer la répartition",+ "mortgageSaved": "Répartition du prêt enregistrée",+ "mortgageRemoved": "Répartition du prêt supprimée",+ "removeMortgageAllocation": "Supprimer la répartition",+ "mortgageSaveError": "Impossible d'enregistrer la répartition. Vérifiez que les parts correspondent au montant du paiement.",+ "mortgageSavedSummary": "Totaux enregistrés : {{currency}} {{principal}} de capital ({{principalPercentage}}%) et {{currency}} {{interest}} d'intérêts ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Ce paiement est antérieur au solde enregistré du prêt. Sa répartition est enregistrée, mais la dette n'est pas réduite une seconde fois.",+ "mortgageBankManagedNote": "Votre banque communique le solde de ce prêt, la répartition est donc enregistrée sans comptabiliser de nouveau le capital.","section": "Finances","monthPrevious": "Mois précédent","monthNext": "Mois suivant",diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex d201fd0e..f501c03e 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -888,6 +888,20 @@},"transactions": {"title": "लेन-देन",+ "mortgageAllocation": "बंधक भुगतान का विवरण",+ "mortgagePrincipal": "मूलधन की अदायगी",+ "mortgageInterest": "ब्याज",+ "mortgageCurrencyHint": "सभी हिस्से {{currency}} में दर्ज करें।",+ "mortgageSplitPercentages": "भुगतान का विभाजन: {{principal}}% मूलधन / {{interest}}% ब्याज",+ "mortgagePaymentTotal": "हिस्सों का कुल: {{currency}} {{total}}; भुगतान: {{currency}} {{payment}}",+ "saveMortgageAllocation": "बंधक विवरण सहेजें",+ "mortgageSaved": "बंधक विवरण सहेजा गया",+ "mortgageRemoved": "बंधक विवरण हटाया गया",+ "removeMortgageAllocation": "विवरण हटाएँ",+ "mortgageSaveError": "बंधक विवरण सहेजा नहीं जा सका। जाँचें कि हिस्सों का योग भुगतान के बराबर है।",+ "mortgageSavedSummary": "सहेजा गया कुल: {{currency}} {{principal}} मूलधन ({{principalPercentage}}%) और {{currency}} {{interest}} ब्याज ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "यह भुगतान दर्ज किए गए बंधक शेष से पहले का है। इसका विभाजन सहेजा गया है, पर ऋण दोबारा कम नहीं किया जाता।",+ "mortgageBankManagedNote": "इस ऋण का शेष आपका बैंक बताता है, इसलिए विभाजन सहेजा जाता है और मूलधन दोबारा दर्ज नहीं होता।","section": "वित्तीय","monthPrevious": "पिछला महीना","monthNext": "अगला महीना",diff --git a/frontend/src/locales/hu.json b/frontend/src/locales/hu.jsonindex 23ab3abf..73fa166a 100644--- a/frontend/src/locales/hu.json+++ b/frontend/src/locales/hu.json@@ -888,6 +888,20 @@},"transactions": {"title": "Tranzakciók",+ "mortgageAllocation": "Jelzáloghitel-törlesztés bontása",+ "mortgagePrincipal": "Tőketörlesztés",+ "mortgageInterest": "Kamat",+ "mortgageCurrencyHint": "Minden részt {{currency}} pénznemben adjon meg.",+ "mortgageSplitPercentages": "A törlesztés megoszlása: {{principal}}% tőke / {{interest}}% kamat",+ "mortgagePaymentTotal": "Részek összege: {{currency}} {{total}}; törlesztés: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Bontás mentése",+ "mortgageSaved": "A jelzáloghitel bontása mentve",+ "mortgageRemoved": "A jelzáloghitel bontása eltávolítva",+ "removeMortgageAllocation": "Bontás eltávolítása",+ "mortgageSaveError": "A bontást nem sikerült menteni. Ellenőrizze, hogy a részek összege megegyezik a törlesztéssel.",+ "mortgageSavedSummary": "Mentett összegek: {{currency}} {{principal}} tőke ({{principalPercentage}}%) és {{currency}} {{interest}} kamat ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Ez a törlesztés korábbi, mint a rögzített jelzáloghitel-egyenleg. A megosztás mentésre kerül, de a tartozás nem csökken újra.",+ "mortgageBankManagedNote": "Ennek a hitelnek az egyenlegét a bankja jelenti, ezért a megosztás mentése a tőke ismételt könyvelése nélkül történik.","section": "Pénzügyek","monthPrevious": "Előző hónap","monthNext": "Következő hónap",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex d4b2dac3..b0e78e63 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -890,6 +890,20 @@},"transactions": {"title": "Transazioni",+ "mortgageAllocation": "Dettaglio del pagamento del mutuo",+ "mortgagePrincipal": "Quota capitale",+ "mortgageInterest": "Interessi",+ "mortgageCurrencyHint": "Inserisci tutte le parti in {{currency}}.",+ "mortgageSplitPercentages": "Ripartizione del pagamento: {{principal}}% capitale / {{interest}}% interessi",+ "mortgagePaymentTotal": "Totale delle parti: {{currency}} {{total}}; pagamento: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Salva dettaglio del mutuo",+ "mortgageSaved": "Dettaglio del mutuo salvato",+ "mortgageRemoved": "Dettaglio del mutuo rimosso",+ "removeMortgageAllocation": "Rimuovi dettaglio",+ "mortgageSaveError": "Impossibile salvare il dettaglio. Verifica che le parti corrispondano all'importo del pagamento.",+ "mortgageSavedSummary": "Totali salvati: {{currency}} {{principal}} di capitale ({{principalPercentage}}%) e {{currency}} {{interest}} di interessi ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Questo pagamento è precedente al saldo registrato del mutuo. La ripartizione viene salvata, ma il debito non viene ridotto di nuovo.",+ "mortgageBankManagedNote": "La tua banca comunica il saldo di questo prestito, quindi la ripartizione viene salvata senza registrare di nuovo la quota capitale.","section": "Finanze","monthPrevious": "Mese precedente","monthNext": "Mese successivo",diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex 91cae94b..dac57029 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -888,6 +888,20 @@},"transactions": {"title": "取引",+ "mortgageAllocation": "住宅ローン返済の内訳",+ "mortgagePrincipal": "元金返済",+ "mortgageInterest": "利息",+ "mortgageCurrencyHint": "すべての内訳を {{currency}} で入力してください。",+ "mortgageSplitPercentages": "返済の内訳: 元金 {{principal}}% / 利息 {{interest}}%",+ "mortgagePaymentTotal": "内訳の合計: {{currency}} {{total}}、返済額: {{currency}} {{payment}}",+ "saveMortgageAllocation": "内訳を保存",+ "mortgageSaved": "住宅ローンの内訳を保存しました",+ "mortgageRemoved": "住宅ローンの内訳を削除しました",+ "removeMortgageAllocation": "内訳を削除",+ "mortgageSaveError": "内訳を保存できませんでした。内訳の合計が返済額と一致しているか確認してください。",+ "mortgageSavedSummary": "保存した合計: 元金 {{currency}} {{principal}} ({{principalPercentage}}%)、利息 {{currency}} {{interest}} ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "この返済は記録されている住宅ローン残高より前のものです。内訳は保存されますが、残債は再度減額されません。",+ "mortgageBankManagedNote": "このローンの残高は銀行から取得しているため、元金を再度計上せずに内訳のみを保存します。","section": "財務","monthPrevious": "前月","monthNext": "翌月",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex b0acb251..4aa3498b 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -888,6 +888,20 @@},"transactions": {"title": "Transacties",+ "mortgageAllocation": "Verdeling hypotheekbetaling",+ "mortgagePrincipal": "Aflossing",+ "mortgageInterest": "Rente",+ "mortgageCurrencyHint": "Vul alle delen in {{currency}} in.",+ "mortgageSplitPercentages": "Verdeling: {{principal}}% aflossing / {{interest}}% rente",+ "mortgagePaymentTotal": "Delen samen: {{currency}} {{total}}; betaling: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Verdeling opslaan",+ "mortgageSaved": "Hypotheekverdeling opgeslagen",+ "mortgageRemoved": "Hypotheekverdeling verwijderd",+ "removeMortgageAllocation": "Verdeling verwijderen",+ "mortgageSaveError": "Opslaan mislukt. Controleer of de bedragen samen gelijk zijn aan de betaling.",+ "mortgageSavedSummary": "Opgeslagen: {{currency}} {{principal}} aflossing ({{principalPercentage}}%) en {{currency}} {{interest}} rente ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Deze betaling is ouder dan de ingevoerde hypotheekstand. De verdeling is opgeslagen, zonder de schuld opnieuw te verlagen.",+ "mortgageBankManagedNote": "Je bank levert het saldo van deze lening, dus de verdeling is opgeslagen zonder de aflossing nogmaals te boeken.","section": "Financieel","monthPrevious": "Vorige maand","monthNext": "Volgende maand",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex ad6fccca..0833a408 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -902,6 +902,20 @@},"transactions": {"title": "Transakcje",+ "mortgageAllocation": "Rozbicie raty kredytu hipotecznego",+ "mortgagePrincipal": "Spłata kapitału",+ "mortgageInterest": "Odsetki",+ "mortgageCurrencyHint": "Podaj wszystkie części w {{currency}}.",+ "mortgageSplitPercentages": "Podział raty: {{principal}}% kapitału / {{interest}}% odsetek",+ "mortgagePaymentTotal": "Suma części: {{currency}} {{total}}; rata: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Zapisz rozbicie raty",+ "mortgageSaved": "Rozbicie raty zapisane",+ "mortgageRemoved": "Rozbicie raty usunięte",+ "removeMortgageAllocation": "Usuń rozbicie",+ "mortgageSaveError": "Nie udało się zapisać rozbicia. Sprawdź, czy części sumują się do kwoty raty.",+ "mortgageSavedSummary": "Zapisane sumy: {{currency}} {{principal}} kapitału ({{principalPercentage}}%) i {{currency}} {{interest}} odsetek ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Ta rata jest wcześniejsza niż zapisane saldo kredytu. Podział zostaje zapisany, ale dług nie jest ponownie pomniejszany.",+ "mortgageBankManagedNote": "Saldo tego kredytu podaje bank, więc podział zostaje zapisany bez ponownego księgowania kapitału.","section": "Finanse","monthPrevious": "Poprzedni miesiąc","monthNext": "Następny miesiąc",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 32c18436..d2b63479 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -890,6 +890,20 @@},"transactions": {"title": "Transações",+ "mortgageAllocation": "Detalhamento do pagamento da hipoteca",+ "mortgagePrincipal": "Amortização",+ "mortgageInterest": "Juros",+ "mortgageCurrencyHint": "Informe todas as parcelas em {{currency}}.",+ "mortgageSplitPercentages": "Divisão do pagamento: {{principal}}% amortização / {{interest}}% juros",+ "mortgagePaymentTotal": "Total das parcelas: {{currency}} {{total}}; pagamento: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Salvar detalhamento da hipoteca",+ "mortgageSaved": "Detalhamento da hipoteca salvo",+ "mortgageRemoved": "Detalhamento da hipoteca removido",+ "removeMortgageAllocation": "Remover detalhamento",+ "mortgageSaveError": "Não foi possível salvar. Confira se as parcelas somam o valor do pagamento.",+ "mortgageSavedSummary": "Total salvo: {{currency}} {{principal}} de amortização ({{principalPercentage}}%) e {{currency}} {{interest}} de juros ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Este pagamento é anterior ao saldo registrado da hipoteca. A divisão foi salva sem reduzir a dívida novamente.",+ "mortgageBankManagedNote": "Seu banco informa o saldo deste empréstimo, então a divisão foi salva sem lançar a amortização novamente.","section": "Financeiro","monthPrevious": "Mês anterior","monthNext": "Próximo mês",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex ec133a0a..fef4709d 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -890,6 +890,20 @@},"transactions": {"title": "Transações",+ "mortgageAllocation": "Detalhamento do pagamento da hipoteca",+ "mortgagePrincipal": "Amortização",+ "mortgageInterest": "Juros",+ "mortgageCurrencyHint": "Informe todas as parcelas em {{currency}}.",+ "mortgageSplitPercentages": "Divisão do pagamento: {{principal}}% amortização / {{interest}}% juros",+ "mortgagePaymentTotal": "Total das parcelas: {{currency}} {{total}}; pagamento: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Salvar detalhamento da hipoteca",+ "mortgageSaved": "Detalhamento da hipoteca salvo",+ "mortgageRemoved": "Detalhamento da hipoteca removido",+ "removeMortgageAllocation": "Remover detalhamento",+ "mortgageSaveError": "Não foi possível salvar. Confira se as parcelas somam o valor do pagamento.",+ "mortgageSavedSummary": "Total salvo: {{currency}} {{principal}} de amortização ({{principalPercentage}}%) e {{currency}} {{interest}} de juros ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Este pagamento é anterior ao saldo registrado da hipoteca. A divisão foi salva sem reduzir a dívida novamente.",+ "mortgageBankManagedNote": "O banco comunica o saldo deste empréstimo, por isso a amortização não é registada novamente.","section": "Financeiro","monthPrevious": "Mês anterior","monthNext": "Próximo mês",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 1c8d1899..33964b3c 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -896,6 +896,20 @@},"transactions": {"title": "Транзакции",+ "mortgageAllocation": "Разбивка ипотечного платежа",+ "mortgagePrincipal": "Погашение основного долга",+ "mortgageInterest": "Проценты",+ "mortgageCurrencyHint": "Укажите все части в {{currency}}.",+ "mortgageSplitPercentages": "Разбивка платежа: {{principal}}% основного долга / {{interest}}% процентов",+ "mortgagePaymentTotal": "Сумма частей: {{currency}} {{total}}; платёж: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Сохранить разбивку",+ "mortgageSaved": "Разбивка ипотечного платежа сохранена",+ "mortgageRemoved": "Разбивка ипотечного платежа удалена",+ "removeMortgageAllocation": "Удалить разбивку",+ "mortgageSaveError": "Не удалось сохранить разбивку. Проверьте, что сумма частей равна платежу.",+ "mortgageSavedSummary": "Сохранённые суммы: {{currency}} {{principal}} основного долга ({{principalPercentage}}%) и {{currency}} {{interest}} процентов ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Этот платёж предшествует записанному остатку по ипотеке. Разбивка сохраняется, но долг повторно не уменьшается.",+ "mortgageBankManagedNote": "Остаток по этому кредиту сообщает банк, поэтому разбивка сохраняется без повторного проведения основного долга.","section": "Финансы","monthPrevious": "Предыдущий месяц","monthNext": "Следующий месяц",diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex e7a01313..3cb5b53e 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -904,6 +904,20 @@},"transactions": {"title": "Transakcie",+ "mortgageAllocation": "Rozpis splátky hypotéky",+ "mortgagePrincipal": "Splátka istiny",+ "mortgageInterest": "Úrok",+ "mortgageCurrencyHint": "Zadajte všetky časti v {{currency}}.",+ "mortgageSplitPercentages": "Rozdelenie splátky: {{principal}}% istina / {{interest}}% úrok",+ "mortgagePaymentTotal": "Súčet častí: {{currency}} {{total}}; splátka: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Uložiť rozpis hypotéky",+ "mortgageSaved": "Rozpis hypotéky uložený",+ "mortgageRemoved": "Rozpis hypotéky odstránený",+ "removeMortgageAllocation": "Odstrániť rozpis",+ "mortgageSaveError": "Rozpis hypotéky sa nepodarilo uložiť. Skontrolujte, či sa časti rovnajú splátke.",+ "mortgageSavedSummary": "Uložené súčty: {{currency}} {{principal}} istina ({{principalPercentage}}%) a {{currency}} {{interest}} úrok ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Táto splátka predchádza zaznamenanému zostatku hypotéky. Rozdelenie sa uloží, dlh sa však znova neznižuje.",+ "mortgageBankManagedNote": "Zostatok tohto úveru hlási vaša banka, preto sa rozdelenie uloží bez opätovného zaúčtovania istiny.","section": "Financie","monthPrevious": "Predchádzajúci mesiac","monthNext": "Ďalší mesiac",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex a25962a8..6ea969c0 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -896,6 +896,20 @@},"transactions": {"title": "Транзакції",+ "mortgageAllocation": "Розподіл іпотечного платежу",+ "mortgagePrincipal": "Погашення основної суми",+ "mortgageInterest": "Відсотки",+ "mortgageCurrencyHint": "Укажіть усі частини в {{currency}}.",+ "mortgageSplitPercentages": "Розподіл платежу: {{principal}}% основної суми / {{interest}}% відсотків",+ "mortgagePaymentTotal": "Сума частин: {{currency}} {{total}}; платіж: {{currency}} {{payment}}",+ "saveMortgageAllocation": "Зберегти розподіл",+ "mortgageSaved": "Розподіл іпотечного платежу збережено",+ "mortgageRemoved": "Розподіл іпотечного платежу вилучено",+ "removeMortgageAllocation": "Вилучити розподіл",+ "mortgageSaveError": "Не вдалося зберегти розподіл. Перевірте, чи сума частин дорівнює платежу.",+ "mortgageSavedSummary": "Збережені суми: {{currency}} {{principal}} основної суми ({{principalPercentage}}%) і {{currency}} {{interest}} відсотків ({{interestPercentage}}%)",+ "mortgageHistoricalNote": "Цей платіж передує записаному залишку за іпотекою. Розподіл збережено, але борг повторно не зменшується.",+ "mortgageBankManagedNote": "Залишок за цим кредитом повідомляє ваш банк, тому розподіл збережено без повторного проведення основної суми.","section": "Фінанси","monthPrevious": "Попередній місяць","monthNext": "Наступний місяць",diff --git a/frontend/src/pages/dashboard.test.tsx b/frontend/src/pages/dashboard.test.tsxindex eb3c9027..1074f672 100644--- a/frontend/src/pages/dashboard.test.tsx+++ b/frontend/src/pages/dashboard.test.tsx@@ -19,13 +19,17 @@ const api = vi.hoisted(() => ({},transactions: { list: vi.fn(), calendar: vi.fn() },budgets: { comparison: vi.fn() },- categories: { list: vi.fn() },- categoryGroups: { list: vi.fn() },+ categories: { list: vi.fn(), listIncludingHidden: vi.fn() },+ categoryGroups: { list: vi.fn(), listIncludingHidden: vi.fn() },accounts: { list: vi.fn() },+ assets: { list: vi.fn() },+ currencies: { list: vi.fn() },+ mortgagePayments: { get: vi.fn() },goals: { summary: vi.fn() },groups: { list: vi.fn() },payees: { list: vi.fn() },- rules: { create: vi.fn() },+ rules: { create: vi.fn(), list: vi.fn() },+ settings: { attachments: vi.fn() },}))vi.mock('@/lib/api', () => api)@@ -140,11 +144,28 @@ beforeEach(() => {api.transactions.list.mockResolvedValue({ items: [], total: 0 })api.budgets.comparison.mockResolvedValue([])api.categories.list.mockResolvedValue([])+ api.categories.listIncludingHidden.mockResolvedValue([])api.categoryGroups.list.mockResolvedValue([])+ api.categoryGroups.listIncludingHidden.mockResolvedValue([])api.accounts.list.mockResolvedValue(accounts)+ api.assets.list.mockResolvedValue([{ id: 'home', name: 'PR review home' }])+ api.currencies.list.mockResolvedValue([])+ api.mortgagePayments.get.mockResolvedValue({+ payment_transaction_id: 'payment-1',+ payment_amount: 250,+ currency: 'USD',+ payment_account_name: 'Checking',+ allocations: [],+ principal_total: 0,+ interest_total: 0,+ principal_percentage: 0,+ interest_percentage: 0,+ })api.goals.summary.mockResolvedValue([])api.groups.list.mockResolvedValue([])api.payees.list.mockResolvedValue([])+ api.rules.list.mockResolvedValue([])+ api.settings.attachments.mockResolvedValue({ enabled: false })})describe('Dashboard net worth breakdown', () => {@@ -185,6 +206,43 @@ describe('Dashboard net worth breakdown', () => {})})+it('shows the mortgage breakdown editor for a payment opened from the dashboard', async () => {+ const loan = account({+ id: 'mortgage',+ name: 'Mortgage',+ type: 'loan',+ secured_asset_id: 'home',+ })+ api.accounts.list.mockResolvedValue([...accounts, loan])+ api.transactions.list.mockResolvedValue({+ items: [{+ id: 'payment-1', user_id: 'user-1', account_id: 'checking', category_id: null,+ category: null, external_id: null, description: 'Mortgage payment', original_description: null,+ amount: 250, currency: 'USD', date: '2026-10-05', type: 'debit', source: 'manual',+ status: 'posted', payee: null, payee_id: null, payee_name: null, notes: null,+ transfer_pair_id: null, amount_primary: null, fx_rate_used: null, fx_fallback: false,+ installment_number: null, total_installments: null, installment_total_amount: null,+ installment_purchase_date: null, installment_series_id: null, bill_id: null,+ effective_bill_date: null, splits: [], is_ignored: false,+ }],+ total: 1,+ page: 1,+ limit: 500,+ })+ const { user } = renderWithProviders(+ <TooltipProvider delayDuration={0}>+ <DashboardPage />+ </TooltipProvider>,+ )++ await user.click(await screen.findByText('Mortgage payment'))+ await user.click(await screen.findByRole('button', { name: t('transactions.mortgageAllocation') }))++ expect(await screen.findByText(/Enter all parts in USD/)).toBeInTheDocument()+ expect(screen.getByLabelText(t('transactions.mortgagePrincipal'))).toBeInTheDocument()+ expect(screen.getByLabelText(t('transactions.mortgageInterest'))).toBeInTheDocument()+})+describe('Dashboard available balance without an FX rate', () => {const renderDashboard = () => renderWithProviders(<TooltipProvider delayDuration={0}>diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsxindex 9917f8f3..8a61f580 100644--- a/frontend/src/pages/dashboard.tsx+++ b/frontend/src/pages/dashboard.tsx@@ -1812,7 +1812,14 @@ export default function DashboardPage() {transaction={editingTx}categories={categoriesList ?? []}categoryGroups={categoryGroupsList ?? []}- accounts={(accountsList ?? []).map((a: { id: string; name: string; display_name?: string | null }) => ({ id: a.id, name: getAccountName(a) }))}+ accounts={(accountsList ?? []).map((a) => ({+ id: a.id,+ name: getAccountName(a),+ display_name: a.display_name,+ type: a.type,+ currency: a.currency,+ secured_asset_id: a.secured_asset_id,+ }))}onSave={(data) => {if (editingTx) updateMutation.mutate({ id: editingTx.id, ...data })}}