Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

feat(loans): contract terms, payment schedule and balance from the lender's statement (#1234)

Tássio Noronha7cbe88082e8a
diff --git a/backend/alembic/versions/099_loan_terms.py b/backend/alembic/versions/099_loan_terms.py
new file mode 100644
index 00000000..a79c105c
--- /dev/null
+++ b/backend/alembic/versions/099_loan_terms.py
@@ -0,0 +1,41 @@
+"""loan contract terms: kind, original amount, rate, term and amortization
+
+Revision ID: 099
+Revises: 098
+"""
+
+import sqlalchemy as sa
+
+from alembic import op
+
+revision = "099"
+down_revision = "098"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column("accounts", sa.Column("loan_kind", sa.String(length=20), nullable=True))
+ op.add_column(
+ "accounts", sa.Column("loan_original_amount", sa.Numeric(precision=15, scale=2), nullable=True)
+ )
+ op.add_column(
+ "accounts", sa.Column("loan_interest_rate", sa.Numeric(precision=9, scale=6), nullable=True)
+ )
+ op.add_column("accounts", sa.Column("loan_rate_period", sa.String(length=20), nullable=True))
+ op.add_column("accounts", sa.Column("loan_term_months", sa.SmallInteger(), nullable=True))
+ op.add_column("accounts", sa.Column("loan_first_payment_date", sa.Date(), nullable=True))
+ op.add_column("accounts", sa.Column("loan_amortization", sa.String(length=10), nullable=True))
+
+
+def downgrade() -> None:
+ for column in (
+ "loan_amortization",
+ "loan_first_payment_date",
+ "loan_term_months",
+ "loan_rate_period",
+ "loan_interest_rate",
+ "loan_original_amount",
+ "loan_kind",
+ ):
+ op.drop_column("accounts", column)
diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.py
index 51c18b55..f683756e 100644
--- a/backend/app/api/accounts.py
+++ b/backend/app/api/accounts.py
@@ -18,6 +18,9 @@ from app.schemas.account import (
AccountCreate,
AccountRead,
AccountRunningBalancePoint,
+ LoanBalanceAdjustment,
+ LoanBalanceUpdate,
+ LoanScheduleRead,
AccountSummary,
AccountUpdate,
CreditCardBillRead,
@@ -190,6 +193,36 @@ async def get_account_bills(
return bills
[email protected]("/{account_id}/loan-schedule", response_model=LoanScheduleRead)
+async def get_loan_schedule(
+ account_id: uuid.UUID,
+ ctx: WorkspaceContext = Depends(current_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ schedule = await account_service.get_loan_schedule(session, account_id, ctx.workspace.id)
+ if schedule is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Loan account not found")
+ return schedule
+
+
[email protected]("/{account_id}/loan-balance", response_model=LoanBalanceAdjustment)
+async def adjust_loan_balance(
+ account_id: uuid.UUID,
+ data: LoanBalanceUpdate,
+ ctx: WorkspaceContext = Depends(current_writable_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ try:
+ result = await account_service.adjust_loan_balance(
+ session, account_id, ctx.workspace.id, ctx.user_id, data
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+ if result is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Loan account not found")
+ return result
+
+
@router.get("/{account_id}", response_model=AccountRead)
async def get_account(
account_id: uuid.UUID,
diff --git a/backend/app/models/account.py b/backend/app/models/account.py
index c0ca46e4..7bb80425 100644
--- a/backend/app/models/account.py
+++ b/backend/app/models/account.py
@@ -1,9 +1,9 @@
import uuid
-from datetime import datetime
+from datetime import date, datetime
from decimal import Decimal
from typing import TYPE_CHECKING, Optional
-from sqlalchemy import Boolean, DateTime, ForeignKey, Numeric, SmallInteger, String
+from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Numeric, SmallInteger, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
@@ -47,6 +47,15 @@ class Account(Base):
UUID(as_uuid=True), ForeignKey("assets.id", ondelete="SET NULL"), nullable=True, index=True
)
balance: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0.00"))
+ # Loan accounts only: the contract terms, all optional. The payment
+ # schedule is computed from them on read (app/services/loan_schedule.py).
+ loan_kind: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
+ loan_original_amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)
+ loan_interest_rate: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=9, scale=6), nullable=True)
+ loan_rate_period: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
+ loan_term_months: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
+ loan_first_payment_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
+ loan_amortization: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)
currency: Mapped[str] = mapped_column(String(3), default="USD")
balance_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)
credit_limit: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)
diff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.py
index 445dafa6..37e824b1 100644
--- a/backend/app/schemas/account.py
+++ b/backend/app/schemas/account.py
@@ -1,9 +1,13 @@
import uuid
from datetime import date, datetime
from decimal import Decimal
-from typing import Optional
+from typing import Literal, Optional
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, Field
+
+LoanKind = Literal["mortgage", "auto", "personal", "student", "other"]
+LoanRatePeriod = Literal["monthly", "yearly_effective", "yearly_nominal"]
+LoanAmortization = Literal["price", "sac"]
class AccountBase(BaseModel):
@@ -28,6 +32,14 @@ class AccountCreate(BaseModel):
minimum_payment: Optional[Decimal] = None
card_brand: Optional[str] = None
card_level: Optional[str] = None
+ # Loan accounts only: contract terms, all optional (see loan_schedule.py).
+ loan_kind: Optional[LoanKind] = None
+ loan_original_amount: Optional[Decimal] = Field(default=None, gt=0)
+ loan_interest_rate: Optional[Decimal] = Field(default=None, ge=0, le=100)
+ loan_rate_period: Optional[LoanRatePeriod] = None
+ loan_term_months: Optional[int] = Field(default=None, ge=1, le=600)
+ loan_first_payment_date: Optional[date] = None
+ loan_amortization: Optional[LoanAmortization] = None
class AccountUpdate(BaseModel):
@@ -43,6 +55,14 @@ class AccountUpdate(BaseModel):
minimum_payment: Optional[Decimal] = None
card_brand: Optional[str] = None
card_level: Optional[str] = None
+ # Loan accounts only: contract terms, all optional (see loan_schedule.py).
+ loan_kind: Optional[LoanKind] = None
+ loan_original_amount: Optional[Decimal] = Field(default=None, gt=0)
+ loan_interest_rate: Optional[Decimal] = Field(default=None, ge=0, le=100)
+ loan_rate_period: Optional[LoanRatePeriod] = None
+ loan_term_months: Optional[int] = Field(default=None, ge=1, le=600)
+ loan_first_payment_date: Optional[date] = None
+ loan_amortization: Optional[LoanAmortization] = None
class AccountRead(AccountBase):
@@ -76,6 +96,13 @@ class AccountRead(AccountBase):
minimum_payment: Optional[float] = None
card_brand: Optional[str] = None
card_level: Optional[str] = None
+ loan_kind: Optional[str] = None
+ loan_original_amount: Optional[float] = None
+ loan_interest_rate: Optional[float] = None
+ loan_rate_period: Optional[str] = None
+ loan_term_months: Optional[int] = None
+ loan_first_payment_date: Optional[date] = None
+ loan_amortization: Optional[str] = None
shared_balance_group: Optional[str] = None
# Open bill of a card on a shared credit line (earliest due_date on or
# after today), in the account's currency. The sidebar leads with it so
@@ -134,3 +161,55 @@ class AccountRunningBalancePoint(BaseModel):
date: date
balance: float
balance_primary: Optional[float] = None
+
+
+class LoanInstallmentRead(BaseModel):
+ number: int
+ due_date: date
+ payment: float
+ interest: float
+ principal: float
+ balance: float
+
+
+class LoanScheduleRead(BaseModel):
+ """A loan's payment schedule, computed from its contract terms on read."""
+
+ account_id: uuid.UUID
+ currency: str
+ # What the account's own transactions say is still owed (never negative).
+ current_debt: float
+ # False until every term the schedule needs is set; `missing` lists them.
+ configured: bool
+ missing: list[str] = []
+ monthly_payment: Optional[float] = None
+ payments_due: Optional[int] = None
+ remaining_payments: Optional[int] = None
+ next_payment: Optional[LoanInstallmentRead] = None
+ scheduled_balance: Optional[float] = None
+ # Positive when less is owed than the contract expects by now.
+ ahead_by: Optional[float] = None
+ total_interest: Optional[float] = None
+ total_paid: Optional[float] = None
+ payoff_date: Optional[date] = None
+ projected_payoff_date: Optional[date] = None
+ paid_off: bool = False
+ installments: list[LoanInstallmentRead] = []
+
+
+class LoanBalanceUpdate(BaseModel):
+ """What the lender says is owed on a date, to bring the ledger in line."""
+
+ balance: Decimal = Field(ge=0)
+ date: date
+ description: str = Field(min_length=1, max_length=500)
+ # Category of the adjustment when the debt grew (interest, indexation).
+ category_id: Optional[uuid.UUID] = None
+
+
+class LoanBalanceAdjustment(BaseModel):
+ # Positive when the debt grew, negative when it fell, zero when the
+ # ledger already matched and nothing was recorded.
+ adjustment: float
+ current_debt: float
+ transaction_id: Optional[uuid.UUID] = None
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index dbf68503..644d493b 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -23,7 +23,7 @@ from app.models.asset import LOAN_COLLATERAL_TYPES, Asset
from app.models.bank_connection import BankConnection
from app.models.credit_card_bill import CreditCardBill
from app.models.transaction import Transaction
-from app.schemas.account import AccountCreate, AccountUpdate
+from app.schemas.account import AccountCreate, AccountUpdate, LoanBalanceUpdate
from app.services._query_filters import (
counts_as_pnl,
counts_in_current_balance,
@@ -34,15 +34,27 @@ from app.services._query_filters import (
is_not_ignored,
reporting_date_col,
)
+from app.services import loan_schedule
from app.services.credit_card_service import (
apply_effective_date,
cc_cycle_bill_due_dates,
compute_available_credit,
get_cycle_dates,
)
-from app.services.fx_rate_service import _resolve_rate
+from app.services.fx_rate_service import _resolve_rate, stamp_primary_amount
from app.models.category import Category
+# Loan accounts only: contract terms the payment schedule is computed from.
+LOAN_TERM_FIELDS = (
+ "loan_kind",
+ "loan_original_amount",
+ "loan_interest_rate",
+ "loan_rate_period",
+ "loan_term_months",
+ "loan_first_payment_date",
+ "loan_amortization",
+)
+
def get_account_name(account: Account) -> str:
return account.display_name or account.name
@@ -334,6 +346,13 @@ def serialize_account(
"minimum_payment": float(acc.minimum_payment) if acc.minimum_payment is not None else None,
"card_brand": acc.card_brand,
"card_level": acc.card_level,
+ "loan_kind": acc.loan_kind,
+ "loan_original_amount": float(acc.loan_original_amount) if acc.loan_original_amount is not None else None,
+ "loan_interest_rate": float(acc.loan_interest_rate) if acc.loan_interest_rate is not None else None,
+ "loan_rate_period": acc.loan_rate_period,
+ "loan_term_months": acc.loan_term_months,
+ "loan_first_payment_date": acc.loan_first_payment_date,
+ "loan_amortization": acc.loan_amortization,
"shared_balance_group": acc.shared_balance_group,
# The card's own open bill, when it sits on a shared credit line.
# Null for every other account and for shared cards without one.
@@ -429,6 +448,7 @@ async def create_account(
minimum_payment=data.minimum_payment if is_cc else None,
card_brand=data.card_brand if is_cc else None,
card_level=data.card_level if is_cc else None,
+ **{field: getattr(data, field) if data.type == "loan" else None for field in LOAN_TERM_FIELDS},
)
session.add(account)
await session.flush() # get account.id without committing
@@ -571,6 +591,8 @@ async def update_account(
account.card_level = None
if account.type != "loan":
account.secured_asset_id = None
+ for field in LOAN_TERM_FIELDS:
+ setattr(account, field, None)
opening_balance_type_changed = old_type != account.type and "loan" in {old_type, account.type}
# When balance changes, sync the opening_balance transaction
@@ -1590,3 +1612,145 @@ async def get_account_running_balance(
})
current += timedelta(days=1)
return series
+
+
+async def get_loan_schedule(
+ session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID
+) -> Optional[dict]:
+ """The loan's contract schedule next to what its ledger says is owed.
+
+ None when the account does not exist in this workspace or is not a loan.
+ """
+ account = await get_account_with_balances(session, account_id, workspace_id)
+ if not account or account["type"] != "loan":
+ return None
+ current_debt = max(Decimal("0"), -Decimal(str(account["current_balance"])))
+ payload: dict = {
+ "account_id": account["id"],
+ "currency": account["currency"],
+ "current_debt": float(current_debt),
+ "configured": False,
+ }
+ required = (
+ "loan_original_amount",
+ "loan_interest_rate",
+ "loan_rate_period",
+ "loan_term_months",
+ "loan_first_payment_date",
+ "loan_amortization",
+ )
+ missing = [field for field in required if account.get(field) is None]
+ if missing:
+ payload["missing"] = missing
+ return payload
+
+ method = account["loan_amortization"]
+ schedule = loan_schedule.build_schedule(
+ principal=Decimal(str(account["loan_original_amount"])),
+ rate_percent=Decimal(str(account["loan_interest_rate"])),
+ rate_period=account["loan_rate_period"],
+ term_months=account["loan_term_months"],
+ first_payment_date=account["loan_first_payment_date"],
+ method=method,
+ )
+ summary = loan_schedule.summarize(
+ schedule,
+ actual_balance=current_debt,
+ today=app_today(),
+ method=method,
+ rate=loan_schedule.monthly_rate(
+ Decimal(str(account["loan_interest_rate"])), account["loan_rate_period"]
+ ),
+ )
+
+ def installment(row: loan_schedule.Installment) -> dict:
+ return {
+ "number": row.number,
+ "due_date": row.due_date,
+ "payment": float(row.payment),
+ "interest": float(row.interest),
+ "principal": float(row.principal),
+ "balance": float(row.balance),
+ }
+
+ payload.update(
+ configured=True,
+ monthly_payment=float((summary.next_payment or schedule[0]).payment),
+ payments_due=summary.payments_due,
+ remaining_payments=summary.remaining_payments,
+ next_payment=installment(summary.next_payment) if summary.next_payment else None,
+ scheduled_balance=float(summary.scheduled_balance),
+ ahead_by=float(summary.ahead_by),
+ total_interest=float(summary.total_interest),
+ total_paid=float(summary.total_paid),
+ payoff_date=summary.payoff_date,
+ projected_payoff_date=summary.projected_payoff_date,
+ paid_off=summary.paid_off,
+ installments=[installment(row) for row in schedule],
+ )
+ return payload
+
+
+async def adjust_loan_balance(
+ session: AsyncSession,
+ account_id: uuid.UUID,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+ data: LoanBalanceUpdate,
+) -> Optional[dict]:
+ """Record the gap between the lender's balance and the ledger's.
+
+ Indexed or renegotiated contracts move in ways the schedule cannot
+ compute, so the lender's statement wins: the difference becomes one
+ ordinary transaction on the loan. A debt that grew is a cost of the loan
+ (indexation, interest, fees) and counts as an expense. A debt that fell
+ without a recorded payment is most often a payment missing from the
+ ledger, so it moves the balance but stays out of income.
+
+ None when the account does not exist in this workspace or is not a loan.
+ """
+ account = await get_account(session, account_id, workspace_id)
+ if not account or account.type != "loan":
+ return None
+ if data.date > app_today():
+ raise ValueError("The statement date cannot be in the future")
+
+ owed = -Decimal(str(await _account_balance_at(session, account.id, data.date, account.currency)))
+ difference = (data.balance - owed).quantize(Decimal("0.01"))
+ transaction = None
+ if difference != 0:
+ grew = difference > 0
+ category_id = data.category_id if grew else None
+ if category_id is not None:
+ found = await session.execute(
+ select(Category.id).where(Category.id == category_id, Category.workspace_id == workspace_id)
+ )
+ if found.scalar_one_or_none() is None:
+ raise ValueError("Category not found")
+ transaction = Transaction(
+ user_id=user_id,
+ workspace_id=workspace_id,
+ account_id=account.id,
+ category_id=category_id,
+ description=data.description,
+ amount=abs(difference),
+ currency=account.currency,
+ date=data.date,
+ type="debit" if grew else "credit",
+ source="manual",
+ status="posted",
+ exclude_from_pnl=not grew,
+ )
+ apply_effective_date(transaction, account)
+ session.add(transaction)
+ await session.flush()
+ await stamp_primary_amount(session, user_id, transaction)
+ await session.commit()
+
+ refreshed = await get_account_with_balances(session, account.id, workspace_id)
+ assert refreshed is not None
+ return {
+ "adjustment": float(difference),
+ "current_debt": float(max(Decimal("0"), -Decimal(str(refreshed["current_balance"])))),
+ "transaction_id": transaction.id if transaction else None,
+ }
diff --git a/backend/app/services/loan_schedule.py b/backend/app/services/loan_schedule.py
new file mode 100644
index 00000000..449860e8
--- /dev/null
+++ b/backend/app/services/loan_schedule.py
@@ -0,0 +1,178 @@
+"""Loan payment schedule computed from the contract terms, on read.
+
+Nothing here writes to the ledger. The schedule is what the contract says,
+the account's transactions are what actually happened, and the summary
+compares the two (ahead or behind, projected payoff from the real balance).
+"""
+
+import calendar
+from dataclasses import dataclass
+from datetime import date
+from decimal import ROUND_HALF_UP, Decimal
+from typing import Optional
+
+LOAN_KINDS = ("mortgage", "auto", "personal", "student", "other")
+# How the contract quotes its rate. Brazilian contracts usually quote a monthly
+# rate or an effective yearly one; US loans quote a nominal yearly rate (APR).
+RATE_PERIODS = ("monthly", "yearly_effective", "yearly_nominal")
+# price: constant payment (French amortization). sac: constant principal, the
+# payment falls every month (Sistema de Amortização Constante).
+AMORTIZATION_METHODS = ("price", "sac")
+MAX_TERM_MONTHS = 600
+
+_CENT = Decimal("0.01")
+# A projection that ends within this much of zero is treated as paid off: the
+# contract payment is rounded to cents, so a remainder of a few cents is noise.
+_PAYOFF_TOLERANCE = Decimal("1.00")
+_MAX_PROJECTION_MONTHS = 1200
+
+
+def _cents(value: Decimal) -> Decimal:
+ return value.quantize(_CENT, rounding=ROUND_HALF_UP)
+
+
+def monthly_rate(rate_percent: Decimal, rate_period: str) -> Decimal:
+ rate = Decimal(rate_percent) / 100
+ if rate_period == "monthly":
+ return rate
+ if rate_period == "yearly_nominal":
+ return rate / 12
+ # Effective yearly rate: the monthly rate that compounds to it over a year.
+ return (1 + rate) ** (Decimal(1) / Decimal(12)) - 1
+
+
+def add_months(start: date, months: int) -> date:
+ month_index = start.month - 1 + months
+ year = start.year + month_index // 12
+ month = month_index % 12 + 1
+ return date(year, month, min(start.day, calendar.monthrange(year, month)[1]))
+
+
+@dataclass(frozen=True)
+class Installment:
+ number: int
+ due_date: date
+ payment: Decimal
+ interest: Decimal
+ principal: Decimal
+ balance: Decimal
+
+
+def build_schedule(
+ *,
+ principal: Decimal,
+ rate_percent: Decimal,
+ rate_period: str,
+ term_months: int,
+ first_payment_date: date,
+ method: str,
+) -> list[Installment]:
+ rate = monthly_rate(rate_percent, rate_period)
+ principal = Decimal(principal)
+ if method == "price":
+ if rate == 0:
+ fixed_payment = _cents(principal / term_months)
+ else:
+ fixed_payment = _cents(principal * rate / (1 - (1 + rate) ** -term_months))
+ else:
+ fixed_principal = _cents(principal / term_months)
+
+ schedule: list[Installment] = []
+ balance = principal
+ for number in range(1, term_months + 1):
+ interest = _cents(balance * rate)
+ if number == term_months:
+ # The last installment absorbs the rounding of the earlier ones.
+ principal_part = balance
+ elif method == "price":
+ principal_part = fixed_payment - interest
+ else:
+ principal_part = fixed_principal
+ balance = balance - principal_part
+ schedule.append(
+ Installment(
+ number=number,
+ due_date=add_months(first_payment_date, number - 1),
+ payment=interest + principal_part,
+ interest=interest,
+ principal=principal_part,
+ balance=_cents(balance),
+ )
+ )
+ return schedule
+
+
+@dataclass(frozen=True)
+class LoanSummary:
+ payments_due: int
+ remaining_payments: int
+ next_payment: Optional[Installment]
+ scheduled_balance: Decimal
+ # Positive when the real balance is below the contract's: ahead of schedule.
+ ahead_by: Decimal
+ total_interest: Decimal
+ total_paid: Decimal
+ payoff_date: date
+ projected_payoff_date: Optional[date]
+ paid_off: bool
+
+
+def _projected_payoff(
+ schedule: list[Installment],
+ actual_balance: Decimal,
+ start: date,
+ method: str,
+ rate: Decimal,
+) -> Optional[date]:
+ """When the real balance reaches zero paying what the contract asks."""
+ if method == "sac":
+ amortization = schedule[0].principal
+ if amortization <= 0:
+ return None
+ remaining = max(actual_balance - _PAYOFF_TOLERANCE, Decimal("0"))
+ months = int((remaining / amortization).to_integral_value(rounding="ROUND_CEILING"))
+ return add_months(start, max(months, 1) - 1)
+
+ payment = schedule[0].payment
+ balance = actual_balance
+ for month in range(_MAX_PROJECTION_MONTHS):
+ interest = balance * rate
+ if payment <= interest:
+ return None # the payment does not even cover the interest
+ balance = balance + interest - payment
+ if balance <= _PAYOFF_TOLERANCE:
+ return add_months(start, month)
+ return None
+
+
+def summarize(
+ schedule: list[Installment],
+ *,
+ actual_balance: Decimal,
+ today: date,
+ method: str,
+ rate: Decimal,
+) -> LoanSummary:
+ due = [row for row in schedule if row.due_date < today]
+ upcoming = [row for row in schedule if row.due_date >= today]
+ original = schedule[0].balance + schedule[0].principal
+ scheduled_balance = due[-1].balance if due else original
+ paid_off = actual_balance <= 0
+
+ projected = None
+ if not paid_off:
+ start = upcoming[0].due_date if upcoming else add_months(schedule[-1].due_date, 1)
+ projected = _projected_payoff(schedule, actual_balance, start, method, rate)
+
+ return LoanSummary(
+ payments_due=len(due),
+ remaining_payments=len(upcoming),
+ next_payment=upcoming[0] if upcoming and not paid_off else None,
+ scheduled_balance=scheduled_balance,
+ ahead_by=scheduled_balance - actual_balance,
+ total_interest=sum((row.interest for row in schedule), Decimal("0")),
+ total_paid=sum((row.payment for row in schedule), Decimal("0")),
+ payoff_date=schedule[-1].due_date,
+ projected_payoff_date=projected,
+ paid_off=paid_off,
+ )
diff --git a/backend/tests/api_contract/baseline.json b/backend/tests/api_contract/baseline.json
index 52c9e201..e528dc34 100644
--- a/backend/tests/api_contract/baseline.json
+++ b/backend/tests/api_contract/baseline.json
@@ -47,6 +47,7 @@
"GET /api/accounts/{account_id}/balance-history": 401,
"GET /api/accounts/{account_id}/bills": 401,
"GET /api/accounts/{account_id}/running-balance": 401,
+ "GET /api/accounts/{account_id}/loan-schedule": 401,
"GET /api/accounts/{account_id}/summary": 401,
"GET /api/admin/accounting-mode": 401,
"GET /api/admin/date-format": 401,
@@ -222,6 +223,7 @@
"PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 401,
"POST /api/accounts": 401,
"POST /api/accounts/{account_id}/close": 401,
+ "POST /api/accounts/{account_id}/loan-balance": 401,
"POST /api/accounts/{account_id}/reopen": 401,
"POST /api/admin/users": 401,
"POST /api/agents": 401,
@@ -334,6 +336,7 @@
"PATCH /api/transactions/{transaction_id}/attachments/{attachment_id}": 422,
"PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 422,
"POST /api/accounts": 422,
+ "POST /api/accounts/{account_id}/loan-balance": 422,
"POST /api/admin/users": 422,
"POST /api/agents": 422,
"POST /api/agents/connections": 422,
@@ -441,6 +444,7 @@
"GET /api/accounts/{account_id}/balance-history": 200,
"GET /api/accounts/{account_id}/bills": 200,
"GET /api/accounts/{account_id}/running-balance": 200,
+ "GET /api/accounts/{account_id}/loan-schedule": 200,
"GET /api/accounts/{account_id}/summary": 200,
"GET /api/admin/accounting-mode": 200,
"GET /api/admin/date-format": 200,
@@ -614,6 +618,7 @@
"PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 400,
"POST /api/accounts": 201,
"POST /api/accounts/{account_id}/close": 200,
+ "POST /api/accounts/{account_id}/loan-balance": 200,
"POST /api/accounts/{account_id}/reopen": 400,
"POST /api/admin/users": 201,
"POST /api/agents": 201,
@@ -761,6 +766,7 @@
"GET /api/accounts/{account_id}/balance-history": 404,
"GET /api/accounts/{account_id}/bills": 404,
"GET /api/accounts/{account_id}/running-balance": 404,
+ "GET /api/accounts/{account_id}/loan-schedule": 404,
"GET /api/accounts/{account_id}/summary": 404,
"GET /api/admin/users/{user_id}": 404,
"GET /api/agents/connections/{conn_id}": 404,
@@ -839,6 +845,7 @@
"PATCH /api/workspaces/{workspace_id}": 404,
"PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 404,
"POST /api/accounts/{account_id}/close": 404,
+ "POST /api/accounts/{account_id}/loan-balance": 404,
"POST /api/accounts/{account_id}/reopen": 404,
"POST /api/agents/connections/{conn_id}/test": 404,
"POST /api/agents/conversations/{conversation_id}/generate-title": 404,
@@ -962,6 +969,7 @@
"PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 403,
"POST /api/accounts": 403,
"POST /api/accounts/{account_id}/close": 403,
+ "POST /api/accounts/{account_id}/loan-balance": 403,
"POST /api/accounts/{account_id}/reopen": 403,
"POST /api/agents": 403,
"POST /api/agents/connections": 201,
diff --git a/backend/tests/api_contract/cases.py b/backend/tests/api_contract/cases.py
index 7a877835..d356e75b 100644
--- a/backend/tests/api_contract/cases.py
+++ b/backend/tests/api_contract/cases.py
@@ -107,6 +107,10 @@ PARAM_WORLD_KEYS_BY_OPERATION: dict[tuple[str, str], dict[str, str]] = {
("GET", "statement"),
)
}
+PARAM_WORLD_KEYS_BY_OPERATION.update({
+ (method, f"/api/accounts/{{account_id}}/{route}"): {"account_id": "loan_account_id"}
+ for method, route in (("GET", "loan-schedule"), ("POST", "loan-balance"))
+})
@dataclass(frozen=True)
class KnownBug:
diff --git a/backend/tests/api_contract/world.py b/backend/tests/api_contract/world.py
index 505ab396..f2fea021 100644
--- a/backend/tests/api_contract/world.py
+++ b/backend/tests/api_contract/world.py
@@ -111,6 +111,11 @@ STEPS: list[Step] = [
files=lambda w: {"file": ("receipt.png", PNG_BYTES, "image/png")}),
Step("agents_connection_id", "POST", "/api/agents/connections",
lambda w: {"name": "Local LLM", "kind": "ollama", "base_url": "http://ollama:11434"}),
+ # A loan with contract terms, so the loan schedule route has a happy path.
+ Step("loan_account_id", "POST", "/api/accounts",
+ lambda w: {"name": "Car loan", "type": "loan", "balance": 1200, "currency": "USD",
+ "loan_original_amount": 1200, "loan_interest_rate": 1, "loan_rate_period": "monthly",
+ "loan_term_months": 12, "loan_first_payment_date": MONTH, "loan_amortization": "price"}),
]
diff --git a/backend/tests/test_loan_balance.py b/backend/tests/test_loan_balance.py
new file mode 100644
index 00000000..69122277
--- /dev/null
+++ b/backend/tests/test_loan_balance.py
@@ -0,0 +1,163 @@
+import uuid
+from datetime import timedelta
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.app_clock import app_today
+from app.models.user import User
+from app.models.workspace import Workspace, WorkspaceMember
+
+
+async def _loan(client: AsyncClient, headers: dict, balance: float = 10000) -> dict:
+ response = await client.post(
+ "/api/accounts",
+ headers=headers,
+ json={
+ "name": "Mortgage",
+ "type": "loan",
+ "balance": balance,
+ "balance_date": (app_today() - timedelta(days=60)).isoformat(),
+ },
+ )
+ assert response.status_code == 201, response.text
+ return response.json()
+
+
+async def _statement(client: AsyncClient, headers: dict, loan_id: str, **body):
+ payload = {"balance": 10000, "date": app_today().isoformat(), "description": "Indexation and interest", **body}
+ return await client.post(f"/api/accounts/{loan_id}/loan-balance", headers=headers, json=payload)
+
+
+async def _transactions(client: AsyncClient, headers: dict, account_id: str) -> list[dict]:
+ response = await client.get(
+ "/api/transactions", headers=headers, params={"account_id": account_id, "limit": 100}
+ )
+ assert response.status_code == 200, response.text
+ return response.json()["items"]
+
+
+async def _month_expenses(client: AsyncClient, headers: dict, account_id: str) -> float:
+ today = app_today()
+ response = await client.get(
+ f"/api/accounts/{account_id}/summary",
+ headers=headers,
+ params={"from": today.replace(day=1).isoformat(), "to": today.isoformat()},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()["monthly_expenses"]
+
+
+async def test_a_higher_statement_records_the_growth_as_a_loan_cost(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers)
+ category = (
+ await client.post("/api/categories", headers=auth_headers, json={"name": "Loan interest", "icon": "percent", "color": "#ef4444"})
+ ).json()
+
+ response = await _statement(client, auth_headers, loan["id"], balance=10250.40, category_id=category["id"])
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["adjustment"] == 250.40
+ assert body["current_debt"] == 10250.40
+ adjustment = next(tx for tx in await _transactions(client, auth_headers, loan["id"]) if tx["id"] == body["transaction_id"])
+ assert adjustment["type"] == "debit"
+ assert float(adjustment["amount"]) == 250.40
+ assert adjustment["source"] == "manual"
+ assert adjustment["category_id"] == category["id"]
+ assert adjustment["exclude_from_pnl"] is False
+ assert await _month_expenses(client, auth_headers, loan["id"]) == 250.40
+
+
+async def test_a_lower_statement_moves_the_balance_but_is_not_income(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers)
+
+ body = (await _statement(client, auth_headers, loan["id"], balance=9800)).json()
+
+ assert body["adjustment"] == -200
+ assert body["current_debt"] == 9800
+ adjustment = next(tx for tx in await _transactions(client, auth_headers, loan["id"]) if tx["id"] == body["transaction_id"])
+ assert adjustment["type"] == "credit"
+ assert adjustment["exclude_from_pnl"] is True
+
+
+async def test_a_matching_statement_records_nothing(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers)
+ before = await _transactions(client, auth_headers, loan["id"])
+
+ body = (await _statement(client, auth_headers, loan["id"], balance=10000)).json()
+
+ assert body == {"adjustment": 0, "current_debt": 10000, "transaction_id": None}
+ assert len(await _transactions(client, auth_headers, loan["id"])) == len(before)
+
+
+async def test_the_statement_is_compared_with_the_ledger_on_its_own_date(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers)
+ checking = (
+ await client.post("/api/accounts", headers=auth_headers, json={"name": "Checking", "type": "checking", "balance": 5000})
+ ).json()
+ paid = await client.post(
+ "/api/transactions/transfer",
+ headers=auth_headers,
+ json={
+ "from_account_id": checking["id"],
+ "to_account_id": loan["id"],
+ "amount": 1000,
+ "date": app_today().isoformat(),
+ "description": "Installment",
+ },
+ )
+ assert paid.status_code == 201, paid.text
+
+ # Last week's statement predates the payment: only the 100 of growth is new.
+ body = (
+ await _statement(
+ client, auth_headers, loan["id"], balance=10100, date=(app_today() - timedelta(days=7)).isoformat()
+ )
+ ).json()
+
+ assert body["adjustment"] == 100
+ assert body["current_debt"] == 9100
+
+
+async def test_invalid_statements_are_rejected(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers)
+ checking = (
+ await client.post("/api/accounts", headers=auth_headers, json={"name": "Checking", "type": "checking", "balance": 5000})
+ ).json()
+
+ future = await _statement(client, auth_headers, loan["id"], date=(app_today() + timedelta(days=1)).isoformat())
+ negative = await _statement(client, auth_headers, loan["id"], balance=-1)
+ not_a_loan = await _statement(client, auth_headers, checking["id"])
+ unknown_category = await _statement(client, auth_headers, loan["id"], balance=10500, category_id=str(uuid.uuid4()))
+
+ assert future.status_code == 400
+ assert negative.status_code == 422
+ assert not_a_loan.status_code == 404
+ assert unknown_category.status_code == 400
+ assert await _transactions(client, auth_headers, loan["id"]) == []
+
+
+async def test_a_loan_of_another_workspace_cannot_be_adjusted(
+ client: AsyncClient,
+ auth_headers,
+ session: AsyncSession,
+ test_user: User,
+):
+ other = Workspace(id=uuid.uuid4(), name="Other household", kind="personal", created_by_user_id=test_user.id)
+ session.add(other)
+ await session.flush()
+ session.add(WorkspaceMember(id=uuid.uuid4(), workspace_id=other.id, user_id=test_user.id, role="owner"))
+ await session.commit()
+ loan = await _loan(client, {**auth_headers, "X-Workspace-Id": str(other.id)})
+
+ response = await _statement(client, auth_headers, loan["id"], balance=10500)
+
+ assert response.status_code == 404
diff --git a/backend/tests/test_loan_schedule.py b/backend/tests/test_loan_schedule.py
new file mode 100644
index 00000000..bf3e07ab
--- /dev/null
+++ b/backend/tests/test_loan_schedule.py
@@ -0,0 +1,164 @@
+from datetime import date
+from decimal import Decimal
+
+import pytest
+
+from app.services.loan_schedule import (
+ add_months,
+ build_schedule,
+ monthly_rate,
+ summarize,
+)
+
+
+def test_monthly_rate_follows_the_rate_period():
+ assert monthly_rate(Decimal("1.5"), "monthly") == Decimal("0.015")
+ assert monthly_rate(Decimal("12"), "yearly_nominal") == Decimal("0.01")
+ # 12.6825% a year compounded monthly is 1% a month.
+ assert monthly_rate(Decimal("12.682503"), "yearly_effective").quantize(Decimal("0.000001")) == Decimal(
+ "0.010000"
+ )
+
+
+def test_add_months_clamps_to_the_end_of_a_short_month():
+ assert add_months(date(2026, 1, 31), 1) == date(2026, 2, 28)
+ assert add_months(date(2026, 1, 31), 2) == date(2026, 3, 31)
+ assert add_months(date(2026, 11, 15), 3) == date(2027, 2, 15)
+
+
+def test_price_schedule_has_a_constant_payment_and_pays_off_exactly():
+ schedule = build_schedule(
+ principal=Decimal("10000"),
+ rate_percent=Decimal("1"),
+ rate_period="monthly",
+ term_months=12,
+ first_payment_date=date(2026, 1, 10),
+ method="price",
+ )
+
+ assert len(schedule) == 12
+ # 10,000 at 1% a month over 12 months: 888.49 a month.
+ assert {row.payment for row in schedule[:-1]} == {Decimal("888.49")}
+ assert schedule[0].interest == Decimal("100.00")
+ assert schedule[0].principal == Decimal("788.49")
+ assert schedule[-1].balance == Decimal("0.00")
+ assert sum(row.principal for row in schedule) == Decimal("10000.00")
+ assert schedule[-1].due_date == date(2026, 12, 10)
+
+
+def test_sac_schedule_has_constant_principal_and_falling_payments():
+ schedule = build_schedule(
+ principal=Decimal("12000"),
+ rate_percent=Decimal("1"),
+ rate_period="monthly",
+ term_months=12,
+ first_payment_date=date(2026, 1, 10),
+ method="sac",
+ )
+
+ assert {row.principal for row in schedule} == {Decimal("1000.00")}
+ assert schedule[0].payment == Decimal("1120.00")
+ assert schedule[1].payment == Decimal("1110.00")
+ assert schedule[-1].payment == Decimal("1010.00")
+ assert schedule[-1].balance == Decimal("0.00")
+
+
+def test_a_zero_rate_loan_splits_the_principal_evenly():
+ schedule = build_schedule(
+ principal=Decimal("1000"),
+ rate_percent=Decimal("0"),
+ rate_period="monthly",
+ term_months=3,
+ first_payment_date=date(2026, 1, 1),
+ method="price",
+ )
+
+ assert [row.payment for row in schedule] == [Decimal("333.33"), Decimal("333.33"), Decimal("333.34")]
+ assert schedule[-1].balance == Decimal("0.00")
+
+
+def _price_12():
+ return build_schedule(
+ principal=Decimal("10000"),
+ rate_percent=Decimal("1"),
+ rate_period="monthly",
+ term_months=12,
+ first_payment_date=date(2026, 1, 10),
+ method="price",
+ )
+
+
+def test_summary_compares_the_contract_with_the_real_balance():
+ schedule = _price_12()
+
+ # 6,000 owed against about 7,623 scheduled: more than a full payment ahead.
+ summary = summarize(schedule, actual_balance=Decimal("6000"), today=date(2026, 4, 1), method="price", rate=Decimal("0.01"))
+
+ # Three installments were due before April 1st.
+ assert summary.payments_due == 3
+ assert summary.remaining_payments == 9
+ assert summary.next_payment == schedule[3]
+ assert summary.scheduled_balance == schedule[2].balance
+ # Owing less than the contract says means the loan is ahead of schedule.
+ assert summary.ahead_by == schedule[2].balance - Decimal("6000")
+ assert summary.total_interest == sum(row.interest for row in schedule)
+ assert summary.payoff_date == date(2026, 12, 10)
+ assert summary.projected_payoff_date is not None
+ assert summary.projected_payoff_date == date(2026, 11, 10)
+
+
+def test_summary_of_a_paid_off_loan():
+ summary = summarize(_price_12(), actual_balance=Decimal("0"), today=date(2026, 6, 1), method="price", rate=Decimal("0.01"))
+
+ assert summary.projected_payoff_date is None
+ assert summary.paid_off is True
+
+
[email protected]("method", ["price", "sac"])
+def test_projection_from_the_real_balance_keeps_the_contract_payment(method: str):
+ schedule = build_schedule(
+ principal=Decimal("12000"),
+ rate_percent=Decimal("1"),
+ rate_period="monthly",
+ term_months=12,
+ first_payment_date=date(2026, 1, 10),
+ method=method,
+ )
+
+ # Nothing paid yet and the first installment is next: the projection is the contract.
+ summary = summarize(schedule, actual_balance=Decimal("12000"), today=date(2026, 1, 1), method=method, rate=Decimal("0.01"))
+
+ assert summary.projected_payoff_date == summary.payoff_date
+
+
+def test_a_balance_above_the_contract_is_behind_schedule():
+ schedule = _price_12()
+
+ summary = summarize(schedule, actual_balance=Decimal("9500"), today=date(2026, 4, 1), method="price", rate=Decimal("0.01"))
+
+ assert summary.ahead_by < 0
+
+
+def test_sac_projection_ignores_the_cents_lost_to_rounding():
+ # 400,000 over 360 months amortizes 1,111.11 a month, 0.40 short over the
+ # contract; one payment behind must project one month late, not two.
+ schedule = build_schedule(
+ principal=Decimal("400000"),
+ rate_percent=Decimal("11.5"),
+ rate_period="yearly_effective",
+ term_months=360,
+ first_payment_date=date(2025, 11, 10),
+ method="sac",
+ )
+ behind_one_payment = schedule[11].balance + schedule[11].principal
+
+ summary = summarize(
+ schedule,
+ actual_balance=behind_one_payment,
+ today=date(2026, 10, 22),
+ method="sac",
+ rate=monthly_rate(Decimal("11.5"), "yearly_effective"),
+ )
+
+ assert summary.payoff_date == date(2055, 10, 10)
+ assert summary.projected_payoff_date == date(2055, 11, 10)
diff --git a/backend/tests/test_loan_terms.py b/backend/tests/test_loan_terms.py
new file mode 100644
index 00000000..704d36f8
--- /dev/null
+++ b/backend/tests/test_loan_terms.py
@@ -0,0 +1,195 @@
+import uuid
+from datetime import date
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.app_clock import app_today
+from app.models.user import User
+from app.models.workspace import Workspace, WorkspaceMember
+from app.services.loan_schedule import add_months
+
+TERMS = {
+ "loan_kind": "personal",
+ "loan_original_amount": 10000,
+ "loan_interest_rate": 1,
+ "loan_rate_period": "monthly",
+ "loan_term_months": 12,
+ "loan_amortization": "price",
+}
+
+
+def _first_payment(months_ago: int) -> str:
+ return add_months(app_today().replace(day=1), -months_ago).replace(day=10).isoformat()
+
+
+async def _loan(client: AsyncClient, headers: dict, **overrides) -> dict:
+ body = {
+ "name": "Personal loan",
+ "type": "loan",
+ "balance": 10000,
+ "loan_first_payment_date": _first_payment(0),
+ **TERMS,
+ **overrides,
+ }
+ response = await client.post("/api/accounts", headers=headers, json=body)
+ assert response.status_code == 201, response.text
+ return response.json()
+
+
+async def test_a_loan_keeps_its_contract_terms(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers)
+
+ fetched = (await client.get(f"/api/accounts/{loan['id']}", headers=auth_headers)).json()
+
+ assert fetched["loan_kind"] == "personal"
+ assert fetched["loan_original_amount"] == 10000
+ assert fetched["loan_interest_rate"] == 1
+ assert fetched["loan_rate_period"] == "monthly"
+ assert fetched["loan_term_months"] == 12
+ assert fetched["loan_amortization"] == "price"
+
+
+async def test_the_schedule_follows_the_contract(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers)
+
+ schedule = await client.get(f"/api/accounts/{loan['id']}/loan-schedule", headers=auth_headers)
+
+ assert schedule.status_code == 200, schedule.text
+ body = schedule.json()
+ assert body["configured"] is True
+ assert body["monthly_payment"] == 888.49
+ assert len(body["installments"]) == 12
+ assert body["installments"][-1]["balance"] == 0
+ assert body["current_debt"] == 10000
+ assert body["paid_off"] is False
+
+
+async def test_a_payment_beyond_the_contract_puts_the_loan_ahead(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers, loan_first_payment_date=_first_payment(-1))
+ checking = (
+ await client.post(
+ "/api/accounts",
+ headers=auth_headers,
+ json={"name": "Checking", "type": "checking", "balance": 5000},
+ )
+ ).json()
+ paid = await client.post(
+ "/api/transactions/transfer",
+ headers=auth_headers,
+ json={
+ "from_account_id": checking["id"],
+ "to_account_id": loan["id"],
+ "amount": 3000,
+ "date": app_today().isoformat(),
+ "description": "Extra payment",
+ },
+ )
+ assert paid.status_code == 201, paid.text
+
+ body = (await client.get(f"/api/accounts/{loan['id']}/loan-schedule", headers=auth_headers)).json()
+
+ # Nothing is due yet, so the contract still expects the full 10,000.
+ assert body["current_debt"] == 7000
+ assert body["scheduled_balance"] == 10000
+ assert body["ahead_by"] == 3000
+ assert body["projected_payoff_date"] < body["payoff_date"]
+
+
+async def test_an_incomplete_contract_lists_what_is_missing(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers, loan_term_months=None, loan_interest_rate=None)
+
+ body = (await client.get(f"/api/accounts/{loan['id']}/loan-schedule", headers=auth_headers)).json()
+
+ assert body["configured"] is False
+ assert set(body["missing"]) == {"loan_term_months", "loan_interest_rate"}
+ assert body["installments"] == []
+
+
+async def test_terms_are_only_kept_on_loans(client: AsyncClient, auth_headers):
+ checking = await client.post(
+ "/api/accounts",
+ headers=auth_headers,
+ json={"name": "Checking", "type": "checking", "balance": 100, **TERMS},
+ )
+ loan = await _loan(client, auth_headers)
+ retyped = await client.patch(
+ f"/api/accounts/{loan['id']}", headers=auth_headers, json={"type": "checking"}
+ )
+
+ assert checking.status_code == 201, checking.text
+ assert checking.json()["loan_kind"] is None
+ assert retyped.status_code == 200, retyped.text
+ assert retyped.json()["loan_term_months"] is None
+ assert retyped.json()["loan_amortization"] is None
+ schedule = await client.get(f"/api/accounts/{checking.json()['id']}/loan-schedule", headers=auth_headers)
+ assert schedule.status_code == 404
+
+
+ "field,value",
+ [
+ ("loan_interest_rate", 150),
+ ("loan_term_months", 0),
+ ("loan_term_months", 601),
+ ("loan_original_amount", -1),
+ ("loan_kind", "boat"),
+ ("loan_rate_period", "weekly"),
+ ("loan_amortization", "german"),
+ ],
+)
+async def test_invalid_terms_are_rejected(client: AsyncClient, auth_headers, field: str, value):
+ response = await client.post(
+ "/api/accounts",
+ headers=auth_headers,
+ json={"name": "Loan", "type": "loan", "balance": 1000, **TERMS, field: value},
+ )
+
+ assert response.status_code == 422
+
+
+async def test_terms_can_be_edited(client: AsyncClient, auth_headers):
+ loan = await _loan(client, auth_headers)
+
+ updated = await client.patch(
+ f"/api/accounts/{loan['id']}",
+ headers=auth_headers,
+ json={"loan_amortization": "sac", "loan_first_payment_date": date(2026, 3, 5).isoformat()},
+ )
+
+ assert updated.status_code == 200, updated.text
+ assert updated.json()["loan_amortization"] == "sac"
+ assert updated.json()["loan_first_payment_date"] == "2026-03-05"
+ assert updated.json()["loan_term_months"] == 12
+
+
+async def test_the_schedule_of_another_workspace_is_not_found(
+ client: AsyncClient,
+ auth_headers,
+ session: AsyncSession,
+ test_user: User,
+):
+ other = Workspace(id=uuid.uuid4(), name="Other household", kind="personal", created_by_user_id=test_user.id)
+ session.add(other)
+ await session.flush()
+ session.add(WorkspaceMember(id=uuid.uuid4(), workspace_id=other.id, user_id=test_user.id, role="owner"))
+ await session.commit()
+ loan = await _loan(client, {**auth_headers, "X-Workspace-Id": str(other.id)})
+
+ from_default = await client.get(f"/api/accounts/{loan['id']}/loan-schedule", headers=auth_headers)
+ from_owner = await client.get(
+ f"/api/accounts/{loan['id']}/loan-schedule",
+ headers={**auth_headers, "X-Workspace-Id": str(other.id)},
+ )
+
+ assert from_default.status_code == 404
+ assert from_owner.status_code == 200
diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsx
index fdc5a025..64ad6d92 100644
--- a/frontend/src/components/app-layout.tsx
+++ b/frontend/src/components/app-layout.tsx
@@ -1,5 +1,11 @@
import { useState, useCallback, useEffect, useMemo, lazy, Suspense } from 'react'
-import { getAccountName, sidebarAccountBalance, sortAccountsByAbsoluteBalance, sumAccountsTotal } from '@/lib/account-utils'
+import {
+ getAccountName,
+ sidebarAccountBalance,
+ sidebarAccounts,
+ sortAccountsByAbsoluteBalance,
+ sumAccountsTotal,
+} from '@/lib/account-utils'
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useDisplayLocale } from '@/hooks/use-display-locale'
@@ -190,7 +196,7 @@ export function AppLayout() {
queryFn: () => accountsApi.list(),
})
- const allAccounts = accountsList ?? []
+ const allAccounts = sidebarAccounts(accountsList ?? [])
// When a collection is active, the sidebar list + total reflect only its
// accounts (issue #105). null = all accounts.
const visibleAccounts = activeAccountIds
diff --git a/frontend/src/components/loan-balance-dialog.test.tsx b/frontend/src/components/loan-balance-dialog.test.tsx
new file mode 100644
index 00000000..c164eb9a
--- /dev/null
+++ b/frontend/src/components/loan-balance-dialog.test.tsx
@@ -0,0 +1,106 @@
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { LoanBalanceDialog } from '@/components/loan-balance-dialog'
+import { todayInTimezone } from '@/lib/date-utils'
+import { formatCurrency } from '@/lib/format'
+import { renderWithProviders, t } from '@/test/utils'
+
+const adjustLoanBalance = vi.fn()
+
+vi.mock('@/lib/api', () => ({
+ accounts: { adjustLoanBalance: (id: string, body: unknown) => adjustLoanBalance(id, body) },
+ categories: { list: async () => [] },
+ categoryGroups: { list: async () => [] },
+}))
+
+// The date picker reads the display locale from the signed-in user.
+vi.mock('@/hooks/use-display-locale', () => ({
+ useDisplayLocale: () => 'en-US',
+ useDateLocale: () => 'en-US',
+}))
+
+let workspaceTimezone: string | undefined
+vi.mock('@/hooks/use-timezone', () => ({ useEffectiveTimezone: () => workspaceTimezone }))
+
+const money = (value: number) => formatCurrency(value, 'BRL', 'en-US')
+
+function renderDialog(onClose = vi.fn()) {
+ renderWithProviders(
+ <LoanBalanceDialog open onClose={onClose} accountId="loan" currentDebt={10000} currency="BRL" locale="en-US" />,
+ )
+ return onClose
+}
+
+function typeBalance(value: string) {
+ fireEvent.change(screen.getByLabelText(t('loans.adjustBalance')), { target: { value } })
+}
+
+describe('LoanBalanceDialog', () => {
+ beforeEach(() => {
+ adjustLoanBalance.mockReset()
+ workspaceTimezone = undefined
+ })
+
+ it('previews a higher statement as a cost of the loan', () => {
+ renderDialog()
+
+ typeBalance('10250.4')
+
+ expect(screen.getByRole('status')).toHaveTextContent(t('loans.adjustPreviewGrew', { amount: money(250.4) }))
+ })
+
+ it('previews a lower statement as a correction that is not income', () => {
+ renderDialog()
+
+ typeBalance('9800')
+
+ expect(screen.getByRole('status')).toHaveTextContent(t('loans.adjustPreviewFell', { amount: money(200) }))
+ })
+
+ it('says when the statement already matches the ledger', () => {
+ renderDialog()
+
+ expect(screen.getByRole('status')).toHaveTextContent(t('loans.adjustPreviewMatches'))
+ })
+
+ it('sends the statement and closes', async () => {
+ adjustLoanBalance.mockResolvedValue({ adjustment: 250.4, current_debt: 10250.4, transaction_id: 'tx' })
+ const onClose = renderDialog()
+
+ typeBalance('10250.4')
+ fireEvent.click(screen.getByRole('button', { name: t('common.save') }))
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled())
+ expect(adjustLoanBalance).toHaveBeenCalledWith(
+ 'loan',
+ expect.objectContaining({
+ balance: 10250.4,
+ description: t('loans.adjustDefaultDescription'),
+ category_id: null,
+ }),
+ )
+ })
+
+ it('does not send a negative balance', () => {
+ renderDialog()
+
+ typeBalance('-5')
+
+ expect(screen.getByRole('button', { name: t('common.save') })).toBeDisabled()
+ })
+
+ it('dates the statement today in the workspace timezone', async () => {
+ workspaceTimezone = 'Pacific/Kiritimati'
+ adjustLoanBalance.mockResolvedValue({ adjustment: 0, current_debt: 10000, transaction_id: null })
+ const onClose = renderDialog()
+
+ fireEvent.click(screen.getByRole('button', { name: t('common.save') }))
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled())
+ expect(adjustLoanBalance).toHaveBeenCalledWith(
+ 'loan',
+ expect.objectContaining({ date: todayInTimezone('Pacific/Kiritimati') }),
+ )
+ })
+})
diff --git a/frontend/src/components/loan-balance-dialog.tsx b/frontend/src/components/loan-balance-dialog.tsx
new file mode 100644
index 00000000..c17c1d10
--- /dev/null
+++ b/frontend/src/components/loan-balance-dialog.tsx
@@ -0,0 +1,154 @@
+import { useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+
+import { CategorySelect } from '@/components/category-select'
+import { Button } from '@/components/ui/button'
+import { DatePickerInput } from '@/components/ui/date-picker-input'
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { useEffectiveTimezone } from '@/hooks/use-timezone'
+import { accounts, categories as categoriesApi, categoryGroups as categoryGroupsApi } from '@/lib/api'
+import { extractApiError } from '@/lib/api-errors'
+import { todayInTimezone } from '@/lib/date-utils'
+import { formatCurrency } from '@/lib/format'
+import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
+
+/**
+ * Brings a loan's ledger in line with the lender's statement. Indexed or
+ * renegotiated contracts move in ways the schedule cannot compute; the
+ * backend records the difference as one transaction on the loan.
+ */
+export function LoanBalanceDialog({
+ open,
+ onClose,
+ accountId,
+ currentDebt,
+ currency,
+ locale,
+}: {
+ open: boolean
+ onClose: () => void
+ accountId: string
+ currentDebt: number
+ currency: string
+ locale: string
+}) {
+ const { t } = useTranslation()
+ const queryClient = useQueryClient()
+ // The backend checks the date against today in the workspace timezone.
+ const today = todayInTimezone(useEffectiveTimezone())
+ const [balance, setBalance] = useState(String(currentDebt))
+ // Follows the workspace date until the user picks one.
+ const [pickedDate, setPickedDate] = useState<string | null>(null)
+ const date = pickedDate ?? today
+ const [description, setDescription] = useState(t('loans.adjustDefaultDescription'))
+ const [categoryId, setCategoryId] = useState('')
+
+ const { data: categoryList = [] } = useQuery({ queryKey: ['categories'], queryFn: categoriesApi.list, enabled: open })
+ const { data: groupList = [] } = useQuery({ queryKey: ['categoryGroups'], queryFn: categoryGroupsApi.list, enabled: open })
+
+ const money = (value: number) => formatCurrency(value, currency, locale)
+ const statement = balance.trim() === '' ? NaN : Number(balance)
+ const valid = Number.isFinite(statement) && statement >= 0 && description.trim() !== '' && date !== ''
+ // The ledger is only known for today here; on another date the backend
+ // compares with the balance on that day.
+ const difference = valid && date === today ? Math.round((statement - currentDebt) * 100) / 100 : null
+
+ const mutation = useMutation({
+ mutationFn: () =>
+ accounts.adjustLoanBalance(accountId, {
+ balance: statement,
+ date,
+ description: description.trim(),
+ category_id: categoryId || null,
+ }),
+ onSuccess: (result) => {
+ invalidateFinancialQueries(queryClient)
+ toast.success(
+ result.adjustment === 0
+ ? t('loans.adjustMatched')
+ : t('loans.adjustRecorded', { amount: money(Math.abs(result.adjustment)) }),
+ )
+ onClose()
+ },
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+
+ return (
+ <Dialog open={open} onOpenChange={(value) => !value && onClose()}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t('loans.adjustTitle')}</DialogTitle>
+ <DialogDescription>{t('loans.adjustHint')}</DialogDescription>
+ </DialogHeader>
+ <form
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (valid) mutation.mutate()
+ }}
+ >
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1">
+ <Label htmlFor="loan-statement-balance">{t('loans.adjustBalance')}</Label>
+ <Input
+ id="loan-statement-balance"
+ type="number"
+ step="0.01"
+ min="0"
+ value={balance}
+ onChange={(event) => setBalance(event.target.value)}
+ required
+ />
+ </div>
+ <div className="space-y-1">
+ <Label>{t('loans.adjustDate')}</Label>
+ <DatePickerInput value={date} onChange={setPickedDate} />
+ </div>
+ </div>
+ <div className="space-y-1">
+ <Label htmlFor="loan-adjust-description">{t('loans.adjustDescription')}</Label>
+ <Input
+ id="loan-adjust-description"
+ value={description}
+ maxLength={500}
+ onChange={(event) => setDescription(event.target.value)}
+ required
+ />
+ </div>
+ <div className="space-y-1">
+ <Label>{t('loans.adjustCategory')}</Label>
+ <CategorySelect
+ value={categoryId}
+ onChange={setCategoryId}
+ categories={categoryList}
+ groups={groupList}
+ allowNone
+ creatable
+ />
+ </div>
+ <p className="text-xs text-muted-foreground" role="status">
+ {difference === null
+ ? t('loans.adjustOnDate')
+ : difference > 0
+ ? t('loans.adjustPreviewGrew', { amount: money(difference) })
+ : difference < 0
+ ? t('loans.adjustPreviewFell', { amount: money(-difference) })
+ : t('loans.adjustPreviewMatches')}
+ </p>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button type="submit" disabled={!valid || mutation.isPending}>
+ {mutation.isPending ? t('common.loading') : t('common.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/components/loan-schedule-card.test.tsx b/frontend/src/components/loan-schedule-card.test.tsx
new file mode 100644
index 00000000..7ebdfc3b
--- /dev/null
+++ b/frontend/src/components/loan-schedule-card.test.tsx
@@ -0,0 +1,130 @@
+import { fireEvent, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { LoanScheduleCard } from '@/components/loan-schedule-card'
+import { formatCurrency } from '@/lib/format'
+import { renderWithProviders, t } from '@/test/utils'
+import type { LoanSchedule } from '@/types'
+
+const loanSchedule = vi.fn()
+
+vi.mock('@/lib/api', () => ({
+ accounts: { loanSchedule: (id: string) => loanSchedule(id) },
+ categories: { list: async () => [] },
+ categoryGroups: { list: async () => [] },
+ timezones: { list: async () => ({ default: 'UTC', available: [] }) },
+}))
+
+// The date picker reads the display locale from the signed-in user.
+vi.mock('@/hooks/use-display-locale', () => ({
+ useDisplayLocale: () => 'en-US',
+ useDateLocale: () => 'en-US',
+}))
+
+const installments = [
+ { number: 1, due_date: '2026-01-10', payment: 888.49, interest: 100, principal: 788.49, balance: 9211.51 },
+ { number: 2, due_date: '2026-02-10', payment: 888.49, interest: 92.12, principal: 796.37, balance: 8415.14 },
+ { number: 3, due_date: '2026-03-10', payment: 888.47, interest: 84.15, principal: 804.32, balance: 0 },
+]
+
+function schedule(overrides: Partial<LoanSchedule> = {}): LoanSchedule {
+ return {
+ account_id: 'loan',
+ currency: 'EUR',
+ current_debt: 8000,
+ configured: true,
+ missing: [],
+ monthly_payment: 888.49,
+ payments_due: 1,
+ remaining_payments: 2,
+ next_payment: installments[1],
+ scheduled_balance: 9211.51,
+ ahead_by: 1211.51,
+ total_interest: 276.27,
+ total_paid: 2665.45,
+ payoff_date: '2026-03-10',
+ projected_payoff_date: '2026-03-10',
+ paid_off: false,
+ installments,
+ ...overrides,
+ }
+}
+
+const props = { accountId: 'loan', locale: 'en-US', dateLocale: 'en-US', mask: (value: string) => value }
+const money = (value: number) => formatCurrency(value, 'EUR', 'en-US')
+
+describe('LoanScheduleCard', () => {
+ beforeEach(() => loanSchedule.mockReset())
+
+ it('shows the next payment split and how far ahead the loan is', async () => {
+ loanSchedule.mockResolvedValue(schedule())
+
+ renderWithProviders(<LoanScheduleCard {...props} />)
+
+ expect(await screen.findByText(money(888.49))).toBeInTheDocument()
+ expect(screen.getByText(t('loans.ahead', { amount: money(1211.51) }))).toBeInTheDocument()
+ expect(screen.getByText(t('loans.remainingValue', { remaining: 2, total: 3 }))).toBeInTheDocument()
+ expect(
+ screen.getByText(
+ t('loans.nextPaymentSplit', {
+ date: new Date('2026-02-10T00:00:00').toLocaleDateString('en-US'),
+ interest: money(92.12),
+ principal: money(796.37),
+ }),
+ ),
+ ).toBeInTheDocument()
+ })
+
+ it('says when the loan is behind the contract', async () => {
+ loanSchedule.mockResolvedValue(schedule({ ahead_by: -300 }))
+
+ renderWithProviders(<LoanScheduleCard {...props} />)
+
+ expect(await screen.findByText(t('loans.behind', { amount: money(300) }))).toBeInTheDocument()
+ })
+
+ it('opens the full schedule on demand', async () => {
+ loanSchedule.mockResolvedValue(schedule())
+
+ renderWithProviders(<LoanScheduleCard {...props} />)
+ fireEvent.click(await screen.findByRole('button', { name: t('loans.showSchedule') }))
+
+ expect(screen.getAllByRole('row')).toHaveLength(installments.length + 1)
+ expect(screen.getByText(money(888.47))).toBeInTheDocument()
+ })
+
+ it('asks for the contract terms when they are missing', async () => {
+ loanSchedule.mockResolvedValue(
+ schedule({ configured: false, missing: ['loan_interest_rate'], next_payment: null, installments: [] }),
+ )
+
+ renderWithProviders(<LoanScheduleCard {...props} />)
+
+ expect(await screen.findByText(t('loans.notConfigured'))).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: t('loans.showSchedule') })).not.toBeInTheDocument()
+ })
+
+ it('offers to update the balance only to members who can write', async () => {
+ loanSchedule.mockResolvedValue(schedule())
+
+ const { unmount } = renderWithProviders(<LoanScheduleCard {...props} />)
+ await screen.findByText(money(888.49))
+ expect(screen.queryByRole('button', { name: t('loans.adjustAction') })).not.toBeInTheDocument()
+ unmount()
+
+ renderWithProviders(<LoanScheduleCard {...props} canWrite />)
+ fireEvent.click(await screen.findByRole('button', { name: t('loans.adjustAction') }))
+
+ expect(await screen.findByRole('dialog', { name: t('loans.adjustTitle') })).toBeInTheDocument()
+ })
+
+ it('lets a loan without terms be updated from the statement', async () => {
+ loanSchedule.mockResolvedValue(
+ schedule({ configured: false, missing: ['loan_interest_rate'], next_payment: null, installments: [] }),
+ )
+
+ renderWithProviders(<LoanScheduleCard {...props} canWrite />)
+
+ expect(await screen.findByRole('button', { name: t('loans.adjustAction') })).toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/components/loan-schedule-card.tsx b/frontend/src/components/loan-schedule-card.tsx
new file mode 100644
index 00000000..964a36f7
--- /dev/null
+++ b/frontend/src/components/loan-schedule-card.tsx
@@ -0,0 +1,176 @@
+import { useState } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+
+import { LoanBalanceDialog } from '@/components/loan-balance-dialog'
+import { accounts } from '@/lib/api'
+import { formatCurrency } from '@/lib/format'
+
+/** Below this difference from the contract, the loan reads as on schedule. */
+const ON_SCHEDULE_TOLERANCE = 1
+
+/**
+ * A loan's contract next to its real balance: next payment, what is left,
+ * payoff by the contract and at the current pace, and the full schedule.
+ * The backend computes it from the account's contract terms on read. The
+ * lender's statement can always correct the balance, with or without terms.
+ */
+export function LoanScheduleCard({
+ accountId,
+ locale,
+ dateLocale,
+ mask,
+ canWrite = false,
+}: {
+ accountId: string
+ locale: string
+ dateLocale: string
+ mask: (value: string) => string
+ canWrite?: boolean
+}) {
+ const { t } = useTranslation()
+ const [showSchedule, setShowSchedule] = useState(false)
+ const [adjusting, setAdjusting] = useState(false)
+ const { data } = useQuery({
+ queryKey: ['accounts', accountId, 'loan-schedule'],
+ queryFn: () => accounts.loanSchedule(accountId),
+ })
+ if (!data) return null
+
+ const money = (value: number) => mask(formatCurrency(value, data.currency, locale))
+ const day = (value: string) => new Date(value + 'T00:00:00').toLocaleDateString(dateLocale)
+ const adjust = canWrite && (
+ <>
+ <button
+ type="button"
+ className="text-xs font-medium text-primary hover:underline"
+ onClick={() => setAdjusting(true)}
+ >
+ {t('loans.adjustAction')}
+ </button>
+ {adjusting && (
+ <LoanBalanceDialog
+ open
+ onClose={() => setAdjusting(false)}
+ accountId={accountId}
+ currentDebt={data.current_debt}
+ currency={data.currency}
+ locale={locale}
+ />
+ )}
+ </>
+ )
+
+ if (!data.configured) {
+ return (
+ <div className="bg-card rounded-xl border border-border shadow-sm p-4 space-y-1">
+ <div className="flex items-center justify-between gap-3">
+ <h2 className="text-sm font-semibold">{t('loans.title')}</h2>
+ {adjust}
+ </div>
+ <p className="text-sm text-muted-foreground">{t('loans.notConfigured')}</p>
+ </div>
+ )
+ }
+
+ const total = data.installments.length
+ const aheadBy = data.ahead_by ?? 0
+ const status = data.paid_off
+ ? t('loans.paidOff')
+ : Math.abs(aheadBy) < ON_SCHEDULE_TOLERANCE
+ ? t('loans.onSchedule')
+ : aheadBy > 0
+ ? t('loans.ahead', { amount: money(aheadBy) })
+ : t('loans.behind', { amount: money(-aheadBy) })
+
+ return (
+ <div className="bg-card rounded-xl border border-border shadow-sm">
+ <div className="flex items-center justify-between gap-3 px-4 pt-4">
+ <h2 className="text-sm font-semibold">{t('loans.title')}</h2>
+ <div className="flex items-center gap-3">
+ <span
+ className={`text-xs font-medium ${!data.paid_off && aheadBy <= -ON_SCHEDULE_TOLERANCE ? 'text-rose-500' : 'text-emerald-600'}`}
+ >
+ {status}
+ </span>
+ {adjust}
+ </div>
+ </div>
+ <dl className="grid grid-cols-2 lg:grid-cols-4 gap-4 p-4 text-sm">
+ <div>
+ <dt className="text-xs text-muted-foreground">{t('loans.nextPayment')}</dt>
+ <dd className="font-semibold tabular-nums">{data.next_payment ? money(data.next_payment.payment) : '—'}</dd>
+ {data.next_payment && (
+ <dd className="text-xs text-muted-foreground">
+ {t('loans.nextPaymentSplit', {
+ date: day(data.next_payment.due_date),
+ interest: money(data.next_payment.interest),
+ principal: money(data.next_payment.principal),
+ })}
+ </dd>
+ )}
+ </div>
+ <div>
+ <dt className="text-xs text-muted-foreground">{t('loans.remaining')}</dt>
+ <dd className="font-semibold tabular-nums">
+ {t('loans.remainingValue', { remaining: data.remaining_payments ?? 0, total })}
+ </dd>
+ <dd className="text-xs text-muted-foreground">
+ {t('loans.totalInterest')}: {money(data.total_interest ?? 0)}
+ </dd>
+ </div>
+ <div>
+ <dt className="text-xs text-muted-foreground">{t('loans.payoff')}</dt>
+ <dd className="font-semibold tabular-nums">{data.payoff_date ? day(data.payoff_date) : '—'}</dd>
+ </div>
+ <div>
+ <dt className="text-xs text-muted-foreground">{t('loans.projectedPayoff')}</dt>
+ <dd className="font-semibold tabular-nums">
+ {data.projected_payoff_date ? day(data.projected_payoff_date) : '—'}
+ </dd>
+ </div>
+ </dl>
+ <div className="border-t border-border px-4 py-2">
+ <button
+ type="button"
+ className="text-xs font-medium text-primary hover:underline"
+ onClick={() => setShowSchedule(!showSchedule)}
+ aria-expanded={showSchedule}
+ >
+ {showSchedule ? t('loans.hideSchedule') : t('loans.showSchedule')}
+ </button>
+ </div>
+ {showSchedule && (
+ <div className="max-h-96 overflow-auto border-t border-border">
+ <table className="w-full text-xs tabular-nums">
+ <thead className="sticky top-0 bg-card text-muted-foreground">
+ <tr>
+ <th className="px-4 py-2 text-left font-medium">#</th>
+ <th className="px-2 py-2 text-left font-medium">{t('loans.colDate')}</th>
+ <th className="px-2 py-2 text-right font-medium">{t('loans.colPayment')}</th>
+ <th className="px-2 py-2 text-right font-medium">{t('loans.colInterest')}</th>
+ <th className="px-2 py-2 text-right font-medium">{t('loans.colPrincipal')}</th>
+ <th className="px-4 py-2 text-right font-medium">{t('loans.colBalance')}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {data.installments.map((row) => (
+ <tr
+ key={row.number}
+ className={`border-t border-border ${row.number === data.next_payment?.number ? 'bg-primary/5 font-medium' : ''}`}
+ >
+ <td className="px-4 py-1.5">{row.number}</td>
+ <td className="px-2 py-1.5">{day(row.due_date)}</td>
+ <td className="px-2 py-1.5 text-right">{money(row.payment)}</td>
+ <td className="px-2 py-1.5 text-right">{money(row.interest)}</td>
+ <td className="px-2 py-1.5 text-right">{money(row.principal)}</td>
+ <td className="px-4 py-1.5 text-right">{money(row.balance)}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/account-utils.test.ts b/frontend/src/lib/account-utils.test.ts
index 660ede73..5abd418e 100644
--- a/frontend/src/lib/account-utils.test.ts
+++ b/frontend/src/lib/account-utils.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest'
-import { sidebarAccountBalance, sortAccountsByAbsoluteBalance, sortAccountsByDisplayName, sumAccountsTotal } from './account-utils'
+import {
+ sidebarAccountBalance,
+ sidebarAccounts,
+ sortAccountsByAbsoluteBalance,
+ sortAccountsByDisplayName,
+ sumAccountsTotal,
+} from './account-utils'
describe('sortAccountsByDisplayName', () => {
it('orders accounts by display name when present and falls back to name', () => {
@@ -91,6 +97,18 @@ describe('sumAccountsTotal', () => {
})
})
+describe('sidebarAccounts', () => {
+ it('leaves loans out of the sidebar list', () => {
+ const accounts = [
+ { id: 'checking', type: 'checking' },
+ { id: 'card', type: 'credit_card' },
+ { id: 'mortgage', type: 'loan' },
+ ]
+
+ expect(sidebarAccounts(accounts).map((account) => account.id)).toEqual(['checking', 'card'])
+ })
+})
+
describe('sidebarAccountBalance', () => {
const sharedCard = (extra: Record<string, unknown> = {}) => ({
type: 'credit_card',
diff --git a/frontend/src/lib/account-utils.ts b/frontend/src/lib/account-utils.ts
index 00ecf532..25c01f0b 100644
--- a/frontend/src/lib/account-utils.ts
+++ b/frontend/src/lib/account-utils.ts
@@ -22,6 +22,14 @@ export function sumAccountBalances(
}, 0)
}
+/**
+ * The accounts the sidebar lists. Loans and financing are long-term debt, not
+ * money to move day to day: they live on the Accounts page and in net worth.
+ */
+export function sidebarAccounts<T extends Pick<Account, 'type'>>(accounts: readonly T[]): T[] {
+ return accounts.filter((account) => account.type !== 'loan')
+}
+
/**
* The number a sidebar account row shows.
*
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 6624d25c..b71650ce 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -21,6 +21,9 @@ import type {
AccountRunningBalancePoint,
Collection,
CreditCardBill,
+ LoanBalanceAdjustment,
+ LoanBalanceUpdate,
+ LoanSchedule,
DescriptionSuggestion,
Transaction,
Payee,
@@ -525,6 +528,14 @@ export const accounts = {
const { data } = await api.get(`/accounts/${id}/running-balance`, { params: { from, to } })
return data
},
+ loanSchedule: async (id: string): Promise<LoanSchedule> => {
+ const { data } = await api.get(`/accounts/${id}/loan-schedule`)
+ return data
+ },
+ adjustLoanBalance: async (id: string, body: LoanBalanceUpdate): Promise<LoanBalanceAdjustment> => {
+ const { data } = await api.post(`/accounts/${id}/loan-balance`, body)
+ return data
+ },
bills: async (id: string, limit = 24): Promise<CreditCardBill[]> => {
const { data } = await api.get(`/accounts/${id}/bills`, { params: { limit } })
return data
diff --git a/frontend/src/locales/cs.json b/frontend/src/locales/cs.json
index 520dbc1c..6dbe126b 100644
--- a/frontend/src/locales/cs.json
+++ b/frontend/src/locales/cs.json
@@ -1271,6 +1271,31 @@
"noSecuredProperty": "Žádný propojený majetek",
"loanRetypeHint": "Pouze účet bez transakcí může přejít na typ Úvěr nebo z něj.",
"loanRetypeBlocked": "Tento účet má transakce, takže nemůže přejít na typ Úvěr ani z něj. Vytvořte místo toho nový úvěrový účet.",
+ "loanTerms": "Smluvní podmínky (nepovinné)",
+ "loanKind": "Typ úvěru",
+ "loanKindNone": "Neuvedeno",
+ "loanKinds": {
+ "mortgage": "Hypotéka",
+ "auto": "Úvěr na vozidlo",
+ "personal": "Spotřebitelský úvěr",
+ "student": "Studentský úvěr",
+ "other": "Jiný"
+ },
+ "loanOriginalAmount": "Výše úvěru",
+ "loanInterestRate": "Úroková sazba (%)",
+ "loanRatePeriod": "Období sazby",
+ "loanRatePeriods": {
+ "monthly": "měsíčně",
+ "yearly_effective": "ročně (efektivní)",
+ "yearly_nominal": "ročně (nominální)"
+ },
+ "loanTermMonths": "Doba splácení (měsíce)",
+ "loanFirstPayment": "První splátka",
+ "loanAmortization": "Splácení",
+ "loanAmortizations": {
+ "price": "Stejná splátka (anuita)",
+ "sac": "Stejná jistina"
+ },
"balanceLoan": "Nesplacený dluh",
"creditLimit": "Úvěrový limit",
"statementCloseDay": "Den uzávěrky výpisu",
@@ -1403,6 +1428,42 @@
"expired": "Vypršelo"
}
},
+ "loans": {
+ "title": "Úvěrová smlouva",
+ "notConfigured": "Zadejte částku, sazbu, dobu splácení a první splátku v nastavení účtu, abyste viděli splátkový kalendář a datum splacení.",
+ "nextPayment": "Příští splátka",
+ "nextPaymentSplit": "{{date}} · úrok {{interest}} · jistina {{principal}}",
+ "remaining": "Zbývající splátky",
+ "remainingValue": "{{remaining}} z {{total}}",
+ "totalInterest": "Úroky celkem",
+ "payoff": "Splacení podle smlouvy",
+ "projectedPayoff": "Splacení současným tempem",
+ "ahead": "{{amount}} napřed oproti smlouvě",
+ "behind": "{{amount}} pozadu oproti smlouvě",
+ "onSchedule": "Podle plánu",
+ "paidOff": "Splaceno",
+ "showSchedule": "Zobrazit splátkový kalendář",
+ "hideSchedule": "Skrýt kalendář",
+ "colDate": "Datum",
+ "colPayment": "Splátka",
+ "colInterest": "Úrok",
+ "colPrincipal": "Jistina",
+ "colBalance": "Zůstatek",
+ "adjustAction": "Aktualizovat zůstatek",
+ "adjustTitle": "Aktualizovat zbývající dluh",
+ "adjustHint": "Zadejte zůstatek, který uvádí věřitel. Securo zapíše rozdíl jako jednu transakci na tomto úvěru, aby indexované nebo přejednané smlouvy odpovídaly bance.",
+ "adjustBalance": "Zbývající dluh",
+ "adjustDate": "Datum výpisu",
+ "adjustDescription": "Popis",
+ "adjustDefaultDescription": "Indexace a úroky",
+ "adjustCategory": "Kategorie (když dluh vzrostl)",
+ "adjustOnDate": "Rozdíl se počítá vůči zůstatku k tomuto datu.",
+ "adjustPreviewGrew": "Dluh vzrostl o {{amount}}: zapíše se jako náklad úvěru.",
+ "adjustPreviewFell": "Dluh klesl o {{amount}}: zůstatek se opraví, aniž by se počítal jako příjem.",
+ "adjustPreviewMatches": "Zůstatek už odpovídá bance.",
+ "adjustRecorded": "Zůstatek aktualizován: zapsáno {{amount}}",
+ "adjustMatched": "Zůstatek už odpovídal, nic nebylo zapsáno"
+ },
"connections": {
"settings": "Nastavení propojení",
"displayName": "Přezdívka",
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index 4fce3dca..2c8ade5f 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -1200,6 +1200,31 @@
"noSecuredProperty": "Kein verknüpfter Vermögenswert",
"loanRetypeHint": "Nur ein Konto ohne Buchungen kann zu Kredit oder von Kredit wechseln.",
"loanRetypeBlocked": "Dieses Konto hat Buchungen und kann daher nicht zu Kredit oder von Kredit wechseln. Lege stattdessen ein neues Kreditkonto an.",
+ "loanTerms": "Vertragsdaten (optional)",
+ "loanKind": "Kreditart",
+ "loanKindNone": "Nicht angegeben",
+ "loanKinds": {
+ "mortgage": "Immobilienfinanzierung",
+ "auto": "Fahrzeugfinanzierung",
+ "personal": "Privatkredit",
+ "student": "Studienkredit",
+ "other": "Sonstiges"
+ },
+ "loanOriginalAmount": "Kreditbetrag",
+ "loanInterestRate": "Zinssatz (%)",
+ "loanRatePeriod": "Zinsperiode",
+ "loanRatePeriods": {
+ "monthly": "pro Monat",
+ "yearly_effective": "pro Jahr (effektiv)",
+ "yearly_nominal": "pro Jahr (nominal)"
+ },
+ "loanTermMonths": "Laufzeit (Monate)",
+ "loanFirstPayment": "Erste Rate",
+ "loanAmortization": "Tilgung",
+ "loanAmortizations": {
+ "price": "Gleiche Rate (Annuität)",
+ "sac": "Gleiche Tilgung"
+ },
"balanceLoan": "Offene Schuld",
"creditLimit": "Kreditlimit",
"statementCloseDay": "Abrechnungsstichtag",
@@ -1320,6 +1345,42 @@
"expired": "Abgelaufen"
}
},
+ "loans": {
+ "title": "Kreditvertrag",
+ "notConfigured": "Gib Betrag, Zinssatz, Laufzeit und erste Rate in den Kontoeinstellungen an, um Tilgungsplan und Enddatum zu sehen.",
+ "nextPayment": "Nächste Rate",
+ "nextPaymentSplit": "{{date}} · Zinsen {{interest}} · Tilgung {{principal}}",
+ "remaining": "Verbleibende Raten",
+ "remainingValue": "{{remaining}} von {{total}}",
+ "totalInterest": "Zinsen gesamt",
+ "payoff": "Ende laut Vertrag",
+ "projectedPayoff": "Ende im aktuellen Tempo",
+ "ahead": "{{amount}} vor dem Vertrag",
+ "behind": "{{amount}} hinter dem Vertrag",
+ "onSchedule": "Im Plan",
+ "paidOff": "Abbezahlt",
+ "showSchedule": "Tilgungsplan anzeigen",
+ "hideSchedule": "Tilgungsplan ausblenden",
+ "colDate": "Datum",
+ "colPayment": "Rate",
+ "colInterest": "Zinsen",
+ "colPrincipal": "Tilgung",
+ "colBalance": "Restschuld",
+ "adjustAction": "Saldo aktualisieren",
+ "adjustTitle": "Restschuld aktualisieren",
+ "adjustHint": "Gib den Saldo laut Kreditgeber ein. Securo bucht die Differenz als eine Transaktion auf diesem Kredit, damit indexierte oder neu verhandelte Verträge mit der Bank übereinstimmen.",
+ "adjustBalance": "Restschuld",
+ "adjustDate": "Datum des Kontoauszugs",
+ "adjustDescription": "Beschreibung",
+ "adjustDefaultDescription": "Indexierung und Zinsen",
+ "adjustCategory": "Kategorie (wenn die Schuld gestiegen ist)",
+ "adjustOnDate": "Die Differenz wird zum Saldo an diesem Datum berechnet.",
+ "adjustPreviewGrew": "Die Schuld ist um {{amount}} gestiegen: das wird als Kosten des Kredits gebucht.",
+ "adjustPreviewFell": "Die Schuld ist um {{amount}} gesunken: der Saldo wird korrigiert, ohne als Einnahme zu zählen.",
+ "adjustPreviewMatches": "Der Saldo stimmt bereits mit der Bank überein.",
+ "adjustRecorded": "Saldo aktualisiert: {{amount}} gebucht",
+ "adjustMatched": "Der Saldo stimmte bereits, nichts wurde gebucht"
+ },
"connections": {
"settings": "Verbindungseinstellungen",
"displayName": "Spitzname",
diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.json
index 7868e8f3..1c95caa6 100644
--- a/frontend/src/locales/el.json
+++ b/frontend/src/locales/el.json
@@ -927,6 +927,31 @@
"noSecuredProperty": "Κανένα συνδεδεμένο περιουσιακό στοιχείο",
"loanRetypeHint": "Μόνο ένας λογαριασμός χωρίς συναλλαγές μπορεί να αλλάξει σε ή από Δάνειο.",
"loanRetypeBlocked": "Αυτός ο λογαριασμός έχει συναλλαγές, οπότε δεν μπορεί να αλλάξει σε ή από Δάνειο. Δημιουργήστε έναν νέο λογαριασμό δανείου.",
+ "loanTerms": "Όροι σύμβασης (προαιρετικό)",
+ "loanKind": "Τύπος δανείου",
+ "loanKindNone": "Δεν ορίστηκε",
+ "loanKinds": {
+ "mortgage": "Στεγαστικό",
+ "auto": "Δάνειο αυτοκινήτου",
+ "personal": "Προσωπικό δάνειο",
+ "student": "Φοιτητικό δάνειο",
+ "other": "Άλλο"
+ },
+ "loanOriginalAmount": "Ποσό δανείου",
+ "loanInterestRate": "Επιτόκιο (%)",
+ "loanRatePeriod": "Περίοδος επιτοκίου",
+ "loanRatePeriods": {
+ "monthly": "ανά μήνα",
+ "yearly_effective": "ανά έτος (πραγματικό)",
+ "yearly_nominal": "ανά έτος (ονομαστικό)"
+ },
+ "loanTermMonths": "Διάρκεια (μήνες)",
+ "loanFirstPayment": "Πρώτη δόση",
+ "loanAmortization": "Αποπληρωμή",
+ "loanAmortizations": {
+ "price": "Σταθερή δόση",
+ "sac": "Σταθερό κεφάλαιο"
+ },
"balanceLoan": "Ανεξόφλητο χρέος",
"creditLimit": "Πιστωτικό όριο",
"statementCloseDay": "Ημέρα κλεισίματος λογαριασμού",
@@ -1047,6 +1072,42 @@
"expired": "Έληξε"
}
},
+ "loans": {
+ "title": "Σύμβαση δανείου",
+ "notConfigured": "Συμπληρώστε ποσό, επιτόκιο, διάρκεια και πρώτη δόση στις ρυθμίσεις του λογαριασμού για να δείτε το πρόγραμμα αποπληρωμής και την ημερομηνία εξόφλησης.",
+ "nextPayment": "Επόμενη δόση",
+ "nextPaymentSplit": "{{date}} · τόκοι {{interest}} · κεφάλαιο {{principal}}",
+ "remaining": "Υπόλοιπες δόσεις",
+ "remainingValue": "{{remaining}} από {{total}}",
+ "totalInterest": "Συνολικοί τόκοι",
+ "payoff": "Εξόφληση βάσει σύμβασης",
+ "projectedPayoff": "Εξόφληση με τον τρέχοντα ρυθμό",
+ "ahead": "{{amount}} μπροστά από τη σύμβαση",
+ "behind": "{{amount}} πίσω από τη σύμβαση",
+ "onSchedule": "Εντός προγράμματος",
+ "paidOff": "Εξοφλήθηκε",
+ "showSchedule": "Εμφάνιση προγράμματος",
+ "hideSchedule": "Απόκρυψη προγράμματος",
+ "colDate": "Ημερομηνία",
+ "colPayment": "Δόση",
+ "colInterest": "Τόκοι",
+ "colPrincipal": "Κεφάλαιο",
+ "colBalance": "Υπόλοιπο",
+ "adjustAction": "Ενημέρωση υπολοίπου",
+ "adjustTitle": "Ενημέρωση οφειλόμενου υπολοίπου",
+ "adjustHint": "Εισάγετε το υπόλοιπο που δείχνει ο δανειστής. Το Securo καταχωρεί τη διαφορά ως μία συναλλαγή σε αυτό το δάνειο, ώστε οι τιμαριθμοποιημένες ή επαναδιαπραγματευμένες συμβάσεις να συμφωνούν με την τράπεζα.",
+ "adjustBalance": "Οφειλόμενο υπόλοιπο",
+ "adjustDate": "Ημερομηνία αντιγράφου",
+ "adjustDescription": "Περιγραφή",
+ "adjustDefaultDescription": "Τιμαριθμοποίηση και τόκοι",
+ "adjustCategory": "Κατηγορία (όταν αυξήθηκε το χρέος)",
+ "adjustOnDate": "Η διαφορά υπολογίζεται με βάση το υπόλοιπο εκείνης της ημερομηνίας.",
+ "adjustPreviewGrew": "Το χρέος αυξήθηκε κατά {{amount}}: καταχωρείται ως κόστος του δανείου.",
+ "adjustPreviewFell": "Το χρέος μειώθηκε κατά {{amount}}: το υπόλοιπο διορθώνεται χωρίς να μετρά ως έσοδο.",
+ "adjustPreviewMatches": "Το υπόλοιπο συμφωνεί ήδη με την τράπεζα.",
+ "adjustRecorded": "Το υπόλοιπο ενημερώθηκε: καταχωρήθηκαν {{amount}}",
+ "adjustMatched": "Το υπόλοιπο συμφωνούσε ήδη, δεν καταχωρήθηκε τίποτα"
+ },
"connections": {
"settings": "Ρυθμίσεις σύνδεσης",
"displayName": "Ψευδώνυμο",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 58d4a044..08badc1f 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -1199,6 +1199,31 @@
"noSecuredProperty": "No linked asset",
"loanRetypeHint": "Only an account without transactions can switch to or from Loan.",
"loanRetypeBlocked": "This account has transactions, so it can't switch to or from Loan. Create a new loan account instead.",
+ "loanTerms": "Contract terms (optional)",
+ "loanKind": "Loan type",
+ "loanKindNone": "Not set",
+ "loanKinds": {
+ "mortgage": "Home financing",
+ "auto": "Vehicle financing",
+ "personal": "Personal loan",
+ "student": "Student loan",
+ "other": "Other"
+ },
+ "loanOriginalAmount": "Amount borrowed",
+ "loanInterestRate": "Interest rate (%)",
+ "loanRatePeriod": "Rate period",
+ "loanRatePeriods": {
+ "monthly": "per month",
+ "yearly_effective": "per year (effective)",
+ "yearly_nominal": "per year (nominal, APR)"
+ },
+ "loanTermMonths": "Term (months)",
+ "loanFirstPayment": "First payment",
+ "loanAmortization": "Amortization",
+ "loanAmortizations": {
+ "price": "Fixed payment (Price)",
+ "sac": "Fixed principal (SAC)"
+ },
"balanceLoan": "Outstanding debt",
"creditLimit": "Credit limit",
"statementCloseDay": "Statement close day",
@@ -1319,6 +1344,42 @@
"expired": "Expired"
}
},
+ "loans": {
+ "title": "Loan contract",
+ "notConfigured": "Add the amount, rate, term and first payment in the account settings to see the payment schedule and the payoff date.",
+ "nextPayment": "Next payment",
+ "nextPaymentSplit": "{{date}} · interest {{interest}} · principal {{principal}}",
+ "remaining": "Payments left",
+ "remainingValue": "{{remaining}} of {{total}}",
+ "totalInterest": "Total interest",
+ "payoff": "Contract payoff",
+ "projectedPayoff": "Payoff at this pace",
+ "ahead": "{{amount}} ahead of the contract",
+ "behind": "{{amount}} behind the contract",
+ "onSchedule": "On schedule",
+ "paidOff": "Paid off",
+ "showSchedule": "Show schedule",
+ "hideSchedule": "Hide schedule",
+ "colDate": "Date",
+ "colPayment": "Payment",
+ "colInterest": "Interest",
+ "colPrincipal": "Principal",
+ "colBalance": "Balance",
+ "adjustAction": "Update balance",
+ "adjustTitle": "Update the balance owed",
+ "adjustHint": "Enter what the lender says you owe. Securo records the difference as one transaction on this loan, so indexed or renegotiated contracts stay in line with the lender.",
+ "adjustBalance": "Balance owed",
+ "adjustDate": "Statement date",
+ "adjustDescription": "Description",
+ "adjustDefaultDescription": "Indexation and interest",
+ "adjustCategory": "Category (when the debt grew)",
+ "adjustOnDate": "The difference is computed against the balance on that date.",
+ "adjustPreviewGrew": "The debt grew {{amount}}: it is recorded as a cost of the loan.",
+ "adjustPreviewFell": "The debt fell {{amount}}: the balance is corrected without counting as income.",
+ "adjustPreviewMatches": "The ledger already matches this balance.",
+ "adjustRecorded": "Balance updated: {{amount}} recorded",
+ "adjustMatched": "The ledger already matched, nothing was recorded"
+ },
"connections": {
"settings": "Connection settings",
"displayName": "Nickname",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index a8a55b9a..45d794f8 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -1203,6 +1203,31 @@
"noSecuredProperty": "Ningún bien vinculado",
"loanRetypeHint": "Solo una cuenta sin transacciones puede cambiar a Préstamo o desde Préstamo.",
"loanRetypeBlocked": "Esta cuenta tiene transacciones, así que no puede cambiar a Préstamo o desde Préstamo. Crea una nueva cuenta de préstamo.",
+ "loanTerms": "Datos del contrato (opcional)",
+ "loanKind": "Tipo de préstamo",
+ "loanKindNone": "Sin indicar",
+ "loanKinds": {
+ "mortgage": "Financiación de vivienda",
+ "auto": "Financiación de vehículo",
+ "personal": "Préstamo personal",
+ "student": "Préstamo estudiantil",
+ "other": "Otro"
+ },
+ "loanOriginalAmount": "Importe prestado",
+ "loanInterestRate": "Tipo de interés (%)",
+ "loanRatePeriod": "Periodo del tipo",
+ "loanRatePeriods": {
+ "monthly": "al mes",
+ "yearly_effective": "al año (efectivo)",
+ "yearly_nominal": "al año (nominal)"
+ },
+ "loanTermMonths": "Plazo (meses)",
+ "loanFirstPayment": "Primera cuota",
+ "loanAmortization": "Amortización",
+ "loanAmortizations": {
+ "price": "Cuota fija (francés)",
+ "sac": "Amortización constante (SAC)"
+ },
"balanceLoan": "Deuda pendiente",
"creditLimit": "Límite de crédito",
"statementCloseDay": "Día de cierre de estado",
@@ -1323,6 +1348,42 @@
"expired": "Caducada"
}
},
+ "loans": {
+ "title": "Contrato del préstamo",
+ "notConfigured": "Indica importe, tipo, plazo y primera cuota en la edición de la cuenta para ver el cuadro de amortización y la fecha de liquidación.",
+ "nextPayment": "Próxima cuota",
+ "nextPaymentSplit": "{{date}} · intereses {{interest}} · amortización {{principal}}",
+ "remaining": "Cuotas restantes",
+ "remainingValue": "{{remaining}} de {{total}}",
+ "totalInterest": "Intereses totales",
+ "payoff": "Liquidación según contrato",
+ "projectedPayoff": "Liquidación al ritmo actual",
+ "ahead": "{{amount}} por delante del contrato",
+ "behind": "{{amount}} por detrás del contrato",
+ "onSchedule": "Al día",
+ "paidOff": "Liquidado",
+ "showSchedule": "Ver cuadro de amortización",
+ "hideSchedule": "Ocultar cuadro",
+ "colDate": "Fecha",
+ "colPayment": "Cuota",
+ "colInterest": "Intereses",
+ "colPrincipal": "Amortización",
+ "colBalance": "Saldo pendiente",
+ "adjustAction": "Actualizar saldo",
+ "adjustTitle": "Actualizar saldo pendiente",
+ "adjustHint": "Indica el saldo que muestra el banco. Securo registra la diferencia como una transacción en este préstamo, para que los contratos indexados o renegociados coincidan con el banco.",
+ "adjustBalance": "Saldo pendiente",
+ "adjustDate": "Fecha del extracto",
+ "adjustDescription": "Descripción",
+ "adjustDefaultDescription": "Indexación e intereses",
+ "adjustCategory": "Categoría (cuando la deuda aumentó)",
+ "adjustOnDate": "La diferencia se calcula sobre el saldo en esa fecha.",
+ "adjustPreviewGrew": "La deuda aumentó {{amount}}: se registra como coste del préstamo.",
+ "adjustPreviewFell": "La deuda bajó {{amount}}: el saldo se corrige sin contar como ingreso.",
+ "adjustPreviewMatches": "El saldo ya coincide con el del banco.",
+ "adjustRecorded": "Saldo actualizado: {{amount}} registrado",
+ "adjustMatched": "El saldo ya coincidía, no se registró nada"
+ },
"connections": {
"settings": "Configuración de la conexión",
"displayName": "Alias",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 2c0a8676..959a69c1 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -1203,6 +1203,31 @@
"noSecuredProperty": "Aucun bien lié",
"loanRetypeHint": "Seul un compte sans transactions peut passer au type Prêt ou le quitter.",
"loanRetypeBlocked": "Ce compte a des transactions : il ne peut ni passer au type Prêt ni le quitter. Créez plutôt un nouveau compte de prêt.",
+ "loanTerms": "Conditions du contrat (facultatif)",
+ "loanKind": "Type de prêt",
+ "loanKindNone": "Non renseigné",
+ "loanKinds": {
+ "mortgage": "Prêt immobilier",
+ "auto": "Prêt auto",
+ "personal": "Prêt personnel",
+ "student": "Prêt étudiant",
+ "other": "Autre"
+ },
+ "loanOriginalAmount": "Montant emprunté",
+ "loanInterestRate": "Taux d'intérêt (%)",
+ "loanRatePeriod": "Période du taux",
+ "loanRatePeriods": {
+ "monthly": "par mois",
+ "yearly_effective": "par an (effectif)",
+ "yearly_nominal": "par an (nominal)"
+ },
+ "loanTermMonths": "Durée (mois)",
+ "loanFirstPayment": "Première échéance",
+ "loanAmortization": "Amortissement",
+ "loanAmortizations": {
+ "price": "Échéance constante",
+ "sac": "Amortissement constant"
+ },
"balanceLoan": "Dette restante",
"creditLimit": "Limite de crédit",
"statementCloseDay": "Jour de clôture du relevé",
@@ -1323,6 +1348,42 @@
"expired": "Expirée"
}
},
+ "loans": {
+ "title": "Contrat de prêt",
+ "notConfigured": "Renseignez le montant, le taux, la durée et la première échéance dans les réglages du compte pour voir l'échéancier et la date de fin.",
+ "nextPayment": "Prochaine échéance",
+ "nextPaymentSplit": "{{date}} · intérêts {{interest}} · capital {{principal}}",
+ "remaining": "Échéances restantes",
+ "remainingValue": "{{remaining}} sur {{total}}",
+ "totalInterest": "Intérêts totaux",
+ "payoff": "Fin selon le contrat",
+ "projectedPayoff": "Fin au rythme actuel",
+ "ahead": "{{amount}} d'avance sur le contrat",
+ "behind": "{{amount}} de retard sur le contrat",
+ "onSchedule": "À jour",
+ "paidOff": "Remboursé",
+ "showSchedule": "Voir l'échéancier",
+ "hideSchedule": "Masquer l'échéancier",
+ "colDate": "Date",
+ "colPayment": "Échéance",
+ "colInterest": "Intérêts",
+ "colPrincipal": "Capital",
+ "colBalance": "Restant dû",
+ "adjustAction": "Mettre à jour le solde",
+ "adjustTitle": "Mettre à jour le capital restant dû",
+ "adjustHint": "Saisissez le solde indiqué par le prêteur. Securo enregistre la différence comme une transaction sur ce prêt, pour que les contrats indexés ou renégociés restent alignés sur la banque.",
+ "adjustBalance": "Capital restant dû",
+ "adjustDate": "Date du relevé",
+ "adjustDescription": "Description",
+ "adjustDefaultDescription": "Indexation et intérêts",
+ "adjustCategory": "Catégorie (si la dette a augmenté)",
+ "adjustOnDate": "La différence est calculée sur le solde à cette date.",
+ "adjustPreviewGrew": "La dette a augmenté de {{amount}} : c'est enregistré comme un coût du prêt.",
+ "adjustPreviewFell": "La dette a baissé de {{amount}} : le solde est corrigé sans compter comme un revenu.",
+ "adjustPreviewMatches": "Le solde correspond déjà à celui de la banque.",
+ "adjustRecorded": "Solde mis à jour : {{amount}} enregistré",
+ "adjustMatched": "Le solde correspondait déjà, rien n'a été enregistré"
+ },
"connections": {
"settings": "Paramètres de connexion",
"displayName": "Surnom",
diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.json
index fdeb2b5c..d9f2f970 100644
--- a/frontend/src/locales/hi.json
+++ b/frontend/src/locales/hi.json
@@ -1199,6 +1199,31 @@
"noSecuredProperty": "कोई जुड़ी हुई संपत्ति नहीं",
"loanRetypeHint": "केवल बिना लेन-देन वाला खाता ऋण प्रकार में या उससे बदला जा सकता है।",
"loanRetypeBlocked": "इस खाते में लेन-देन हैं, इसलिए इसे ऋण प्रकार में या उससे नहीं बदला जा सकता। इसके बजाय एक नया ऋण खाता बनाएँ।",
+ "loanTerms": "अनुबंध की शर्तें (वैकल्पिक)",
+ "loanKind": "ऋण का प्रकार",
+ "loanKindNone": "नहीं बताया",
+ "loanKinds": {
+ "mortgage": "गृह ऋण",
+ "auto": "वाहन ऋण",
+ "personal": "व्यक्तिगत ऋण",
+ "student": "शिक्षा ऋण",
+ "other": "अन्य"
+ },
+ "loanOriginalAmount": "ऋण राशि",
+ "loanInterestRate": "ब्याज दर (%)",
+ "loanRatePeriod": "दर की अवधि",
+ "loanRatePeriods": {
+ "monthly": "प्रति माह",
+ "yearly_effective": "प्रति वर्ष (प्रभावी)",
+ "yearly_nominal": "प्रति वर्ष (नाममात्र)"
+ },
+ "loanTermMonths": "अवधि (महीने)",
+ "loanFirstPayment": "पहली किस्त",
+ "loanAmortization": "चुकौती",
+ "loanAmortizations": {
+ "price": "समान किस्त (EMI)",
+ "sac": "समान मूलधन"
+ },
"balanceLoan": "बकाया ऋण",
"creditLimit": "क्रेडिट सीमा",
"statementCloseDay": "स्टेटमेंट बंद होने का दिन",
@@ -1319,6 +1344,42 @@
"expired": "समाप्त"
}
},
+ "loans": {
+ "title": "ऋण अनुबंध",
+ "notConfigured": "किस्तों की तालिका और चुकौती की तारीख देखने के लिए खाते की सेटिंग में राशि, दर, अवधि और पहली किस्त भरें।",
+ "nextPayment": "अगली किस्त",
+ "nextPaymentSplit": "{{date}} · ब्याज {{interest}} · मूलधन {{principal}}",
+ "remaining": "बची हुई किस्तें",
+ "remainingValue": "{{total}} में से {{remaining}}",
+ "totalInterest": "कुल ब्याज",
+ "payoff": "अनुबंध के अनुसार चुकौती",
+ "projectedPayoff": "मौजूदा गति से चुकौती",
+ "ahead": "अनुबंध से {{amount}} आगे",
+ "behind": "अनुबंध से {{amount}} पीछे",
+ "onSchedule": "समय पर",
+ "paidOff": "चुकता",
+ "showSchedule": "किस्तों की तालिका दिखाएँ",
+ "hideSchedule": "तालिका छिपाएँ",
+ "colDate": "तारीख",
+ "colPayment": "किस्त",
+ "colInterest": "ब्याज",
+ "colPrincipal": "मूलधन",
+ "colBalance": "बकाया",
+ "adjustAction": "बैलेंस अपडेट करें",
+ "adjustTitle": "बकाया राशि अपडेट करें",
+ "adjustHint": "ऋणदाता जो बकाया बताता है वह दर्ज करें। Securo अंतर को इस ऋण पर एक लेनदेन के रूप में दर्ज करता है, ताकि सूचकांक से जुड़े या फिर से तय किए गए अनुबंध बैंक से मेल खाएं।",
+ "adjustBalance": "बकाया राशि",
+ "adjustDate": "स्टेटमेंट की तारीख",
+ "adjustDescription": "विवरण",
+ "adjustDefaultDescription": "सूचकांक समायोजन और ब्याज",
+ "adjustCategory": "श्रेणी (जब कर्ज बढ़ा हो)",
+ "adjustOnDate": "अंतर उस तारीख के बैलेंस के आधार पर निकाला जाता है।",
+ "adjustPreviewGrew": "कर्ज {{amount}} बढ़ा: इसे ऋण की लागत के रूप में दर्ज किया जाता है।",
+ "adjustPreviewFell": "कर्ज {{amount}} घटा: बैलेंस को आय में गिने बिना ठीक किया जाता है।",
+ "adjustPreviewMatches": "बैलेंस पहले से बैंक से मेल खाता है।",
+ "adjustRecorded": "बैलेंस अपडेट हुआ: {{amount}} दर्ज",
+ "adjustMatched": "बैलेंस पहले से मेल खाता था, कुछ दर्ज नहीं हुआ"
+ },
"connections": {
"settings": "कनेक्शन सेटिंग्स",
"displayName": "उपनाम",
diff --git a/frontend/src/locales/hu.json b/frontend/src/locales/hu.json
index 7e543ed5..4ddf731a 100644
--- a/frontend/src/locales/hu.json
+++ b/frontend/src/locales/hu.json
@@ -1199,6 +1199,31 @@
"noSecuredProperty": "Nincs kapcsolt vagyontárgy",
"loanRetypeHint": "Csak tranzakciók nélküli számla váltható Hitel típusra vagy arról.",
"loanRetypeBlocked": "Ennek a számlának vannak tranzakciói, ezért nem váltható Hitel típusra vagy arról. Hozz létre helyette egy új hitelszámlát.",
+ "loanTerms": "Szerződési adatok (nem kötelező)",
+ "loanKind": "Hitel típusa",
+ "loanKindNone": "Nincs megadva",
+ "loanKinds": {
+ "mortgage": "Lakáshitel",
+ "auto": "Gépjárműhitel",
+ "personal": "Személyi kölcsön",
+ "student": "Diákhitel",
+ "other": "Egyéb"
+ },
+ "loanOriginalAmount": "Felvett összeg",
+ "loanInterestRate": "Kamatláb (%)",
+ "loanRatePeriod": "Kamatperiódus",
+ "loanRatePeriods": {
+ "monthly": "havonta",
+ "yearly_effective": "évente (effektív)",
+ "yearly_nominal": "évente (névleges)"
+ },
+ "loanTermMonths": "Futamidő (hónap)",
+ "loanFirstPayment": "Első törlesztés",
+ "loanAmortization": "Törlesztés",
+ "loanAmortizations": {
+ "price": "Egyenlő részlet (annuitás)",
+ "sac": "Egyenlő tőketörlesztés"
+ },
"balanceLoan": "Fennálló tartozás",
"creditLimit": "Hitelkeret",
"statementCloseDay": "Kivonat zárónapja",
@@ -1319,6 +1344,42 @@
"expired": "Lejárt"
}
},
+ "loans": {
+ "title": "Hitelszerződés",
+ "notConfigured": "Add meg az összeget, a kamatot, a futamidőt és az első törlesztést a számla beállításaiban, hogy lásd a törlesztési tervet és a lejárat dátumát.",
+ "nextPayment": "Következő törlesztés",
+ "nextPaymentSplit": "{{date}} · kamat {{interest}} · tőke {{principal}}",
+ "remaining": "Hátralévő részletek",
+ "remainingValue": "{{remaining}} / {{total}}",
+ "totalInterest": "Összes kamat",
+ "payoff": "Lejárat a szerződés szerint",
+ "projectedPayoff": "Lejárat a jelenlegi ütemben",
+ "ahead": "{{amount}} előrébb a szerződésnél",
+ "behind": "{{amount}} lemaradás a szerződéshez képest",
+ "onSchedule": "Ütemterv szerint",
+ "paidOff": "Visszafizetve",
+ "showSchedule": "Törlesztési terv megjelenítése",
+ "hideSchedule": "Terv elrejtése",
+ "colDate": "Dátum",
+ "colPayment": "Részlet",
+ "colInterest": "Kamat",
+ "colPrincipal": "Tőke",
+ "colBalance": "Fennálló tartozás",
+ "adjustAction": "Egyenleg frissítése",
+ "adjustTitle": "Fennálló tartozás frissítése",
+ "adjustHint": "Add meg a hitelező által közölt egyenleget. A Securo a különbséget egy tranzakcióként rögzíti ezen a hitelen, így az indexált vagy újratárgyalt szerződések egyeznek a bankkal.",
+ "adjustBalance": "Fennálló tartozás",
+ "adjustDate": "Kivonat dátuma",
+ "adjustDescription": "Leírás",
+ "adjustDefaultDescription": "Indexálás és kamat",
+ "adjustCategory": "Kategória (ha a tartozás nőtt)",
+ "adjustOnDate": "A különbség az adott napi egyenleghez képest számolódik.",
+ "adjustPreviewGrew": "A tartozás {{amount}} összeggel nőtt: a hitel költségeként rögzül.",
+ "adjustPreviewFell": "A tartozás {{amount}} összeggel csökkent: az egyenleg bevételként való számolás nélkül javul.",
+ "adjustPreviewMatches": "Az egyenleg már egyezik a bankéval.",
+ "adjustRecorded": "Egyenleg frissítve: {{amount}} rögzítve",
+ "adjustMatched": "Az egyenleg már egyezett, semmi sem lett rögzítve"
+ },
"connections": {
"settings": "Kapcsolat beállításai",
"displayName": "Becenév",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index 9d93e738..dd36fef8 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -1203,6 +1203,31 @@
"noSecuredProperty": "Nessun bene collegato",
"loanRetypeHint": "Solo un conto senza transazioni può passare a Prestito o da Prestito.",
"loanRetypeBlocked": "Questo conto ha delle transazioni, quindi non può passare a Prestito o da Prestito. Crea invece un nuovo conto prestito.",
+ "loanTerms": "Dati del contratto (facoltativo)",
+ "loanKind": "Tipo di prestito",
+ "loanKindNone": "Non indicato",
+ "loanKinds": {
+ "mortgage": "Mutuo casa",
+ "auto": "Finanziamento auto",
+ "personal": "Prestito personale",
+ "student": "Prestito studentesco",
+ "other": "Altro"
+ },
+ "loanOriginalAmount": "Importo finanziato",
+ "loanInterestRate": "Tasso di interesse (%)",
+ "loanRatePeriod": "Periodo del tasso",
+ "loanRatePeriods": {
+ "monthly": "al mese",
+ "yearly_effective": "all'anno (effettivo)",
+ "yearly_nominal": "all'anno (nominale, TAN)"
+ },
+ "loanTermMonths": "Durata (mesi)",
+ "loanFirstPayment": "Prima rata",
+ "loanAmortization": "Ammortamento",
+ "loanAmortizations": {
+ "price": "Rata costante (francese)",
+ "sac": "Quota capitale costante (italiano)"
+ },
"balanceLoan": "Debito residuo",
"creditLimit": "Limite di credito",
"statementCloseDay": "Giorno di chiusura estratto",
@@ -1323,6 +1348,42 @@
"expired": "Scaduta"
}
},
+ "loans": {
+ "title": "Contratto del prestito",
+ "notConfigured": "Inserisci importo, tasso, durata e prima rata nelle impostazioni del conto per vedere il piano di ammortamento e la data di estinzione.",
+ "nextPayment": "Prossima rata",
+ "nextPaymentSplit": "{{date}} · interessi {{interest}} · capitale {{principal}}",
+ "remaining": "Rate rimanenti",
+ "remainingValue": "{{remaining}} di {{total}}",
+ "totalInterest": "Interessi totali",
+ "payoff": "Estinzione da contratto",
+ "projectedPayoff": "Estinzione al ritmo attuale",
+ "ahead": "{{amount}} in anticipo sul contratto",
+ "behind": "{{amount}} in ritardo sul contratto",
+ "onSchedule": "In regola",
+ "paidOff": "Estinto",
+ "showSchedule": "Mostra piano di ammortamento",
+ "hideSchedule": "Nascondi piano",
+ "colDate": "Data",
+ "colPayment": "Rata",
+ "colInterest": "Interessi",
+ "colPrincipal": "Capitale",
+ "colBalance": "Debito residuo",
+ "adjustAction": "Aggiorna saldo",
+ "adjustTitle": "Aggiorna il debito residuo",
+ "adjustHint": "Inserisci il saldo indicato dal finanziatore. Securo registra la differenza come una transazione su questo prestito, così i contratti indicizzati o rinegoziati restano allineati alla banca.",
+ "adjustBalance": "Debito residuo",
+ "adjustDate": "Data dell'estratto",
+ "adjustDescription": "Descrizione",
+ "adjustDefaultDescription": "Indicizzazione e interessi",
+ "adjustCategory": "Categoria (se il debito è aumentato)",
+ "adjustOnDate": "La differenza è calcolata sul saldo a quella data.",
+ "adjustPreviewGrew": "Il debito è aumentato di {{amount}}: viene registrato come costo del prestito.",
+ "adjustPreviewFell": "Il debito è sceso di {{amount}}: il saldo viene corretto senza contare come entrata.",
+ "adjustPreviewMatches": "Il saldo coincide già con quello della banca.",
+ "adjustRecorded": "Saldo aggiornato: {{amount}} registrato",
+ "adjustMatched": "Il saldo coincideva già, non è stato registrato nulla"
+ },
"connections": {
"settings": "Impostazioni connessione",
"displayName": "Soprannome",
diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.json
index b9015120..d121da74 100644
--- a/frontend/src/locales/ja.json
+++ b/frontend/src/locales/ja.json
@@ -1199,6 +1199,31 @@
"noSecuredProperty": "紐付けた資産なし",
"loanRetypeHint": "取引のない口座だけがローンとの間で種類を変更できます。",
"loanRetypeBlocked": "この口座には取引があるため、ローンとの間で種類を変更できません。新しいローン口座を作成してください。",
+ "loanTerms": "契約条件(任意)",
+ "loanKind": "ローンの種類",
+ "loanKindNone": "未設定",
+ "loanKinds": {
+ "mortgage": "住宅ローン",
+ "auto": "自動車ローン",
+ "personal": "個人ローン",
+ "student": "教育ローン",
+ "other": "その他"
+ },
+ "loanOriginalAmount": "借入額",
+ "loanInterestRate": "金利(%)",
+ "loanRatePeriod": "金利の期間",
+ "loanRatePeriods": {
+ "monthly": "月利",
+ "yearly_effective": "年利(実効)",
+ "yearly_nominal": "年利(名目)"
+ },
+ "loanTermMonths": "返済期間(月)",
+ "loanFirstPayment": "初回返済日",
+ "loanAmortization": "返済方式",
+ "loanAmortizations": {
+ "price": "元利均等",
+ "sac": "元金均等"
+ },
"balanceLoan": "残債",
"creditLimit": "利用枠",
"statementCloseDay": "締め日",
@@ -1319,6 +1344,42 @@
"expired": "期限切れ"
}
},
+ "loans": {
+ "title": "ローン契約",
+ "notConfigured": "口座の設定で借入額・金利・期間・初回返済日を入力すると、返済予定表と完済日が表示されます。",
+ "nextPayment": "次回の返済",
+ "nextPaymentSplit": "{{date}} ・ 利息 {{interest}} ・ 元金 {{principal}}",
+ "remaining": "残りの返済回数",
+ "remainingValue": "{{remaining}} / {{total}}",
+ "totalInterest": "利息の合計",
+ "payoff": "契約上の完済日",
+ "projectedPayoff": "現在のペースでの完済日",
+ "ahead": "契約より {{amount}} 先行",
+ "behind": "契約より {{amount}} 遅れ",
+ "onSchedule": "予定どおり",
+ "paidOff": "完済",
+ "showSchedule": "返済予定表を表示",
+ "hideSchedule": "予定表を隠す",
+ "colDate": "日付",
+ "colPayment": "返済額",
+ "colInterest": "利息",
+ "colPrincipal": "元金",
+ "colBalance": "残高",
+ "adjustAction": "残高を更新",
+ "adjustTitle": "残債を更新",
+ "adjustHint": "貸し手が示す残高を入力してください。Securo は差額をこのローンの取引として 1 件記録し、指数連動や条件変更のある契約も金融機関と一致させます。",
+ "adjustBalance": "残債",
+ "adjustDate": "明細の日付",
+ "adjustDescription": "説明",
+ "adjustDefaultDescription": "指数連動と利息",
+ "adjustCategory": "カテゴリ (債務が増えた場合)",
+ "adjustOnDate": "差額はその日付の残高に対して計算されます。",
+ "adjustPreviewGrew": "債務が {{amount}} 増えました: ローンの費用として記録されます。",
+ "adjustPreviewFell": "債務が {{amount}} 減りました: 収入には含めずに残高を修正します。",
+ "adjustPreviewMatches": "残高はすでに金融機関と一致しています。",
+ "adjustRecorded": "残高を更新しました: {{amount}} を記録",
+ "adjustMatched": "残高はすでに一致していたため、何も記録されませんでした"
+ },
"connections": {
"settings": "接続設定",
"displayName": "ニックネーム",
diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json
index 97625ed7..0fe5f87f 100644
--- a/frontend/src/locales/nl.json
+++ b/frontend/src/locales/nl.json
@@ -1200,6 +1200,31 @@
"noSecuredProperty": "Geen gekoppelde bezitting",
"loanRetypeHint": "Alleen een rekening zonder transacties kan naar of van Lening wisselen.",
"loanRetypeBlocked": "Deze rekening heeft transacties en kan daarom niet naar of van Lening wisselen. Maak in plaats daarvan een nieuwe leningrekening aan.",
+ "loanTerms": "Contractgegevens (optioneel)",
+ "loanKind": "Soort lening",
+ "loanKindNone": "Niet ingevuld",
+ "loanKinds": {
+ "mortgage": "Hypotheek",
+ "auto": "Autofinanciering",
+ "personal": "Persoonlijke lening",
+ "student": "Studielening",
+ "other": "Overig"
+ },
+ "loanOriginalAmount": "Geleend bedrag",
+ "loanInterestRate": "Rente (%)",
+ "loanRatePeriod": "Renteperiode",
+ "loanRatePeriods": {
+ "monthly": "per maand",
+ "yearly_effective": "per jaar (effectief)",
+ "yearly_nominal": "per jaar (nominaal)"
+ },
+ "loanTermMonths": "Looptijd (maanden)",
+ "loanFirstPayment": "Eerste termijn",
+ "loanAmortization": "Aflossing",
+ "loanAmortizations": {
+ "price": "Vaste termijn (annuïtair)",
+ "sac": "Vaste aflossing (lineair)"
+ },
"balanceLoan": "Openstaande schuld",
"creditLimit": "Kredietlimiet",
"statementCloseDay": "Verklaring sluitingsdag",
@@ -1321,6 +1346,42 @@
"expired": "Verlopen"
}
},
+ "loans": {
+ "title": "Leningcontract",
+ "notConfigured": "Vul bedrag, rente, looptijd en eerste termijn in bij de rekeninginstellingen om het aflossingsschema en de einddatum te zien.",
+ "nextPayment": "Volgende termijn",
+ "nextPaymentSplit": "{{date}} · rente {{interest}} · aflossing {{principal}}",
+ "remaining": "Resterende termijnen",
+ "remainingValue": "{{remaining}} van {{total}}",
+ "totalInterest": "Totale rente",
+ "payoff": "Einde volgens contract",
+ "projectedPayoff": "Einde in het huidige tempo",
+ "ahead": "{{amount}} voor op het contract",
+ "behind": "{{amount}} achter op het contract",
+ "onSchedule": "Op schema",
+ "paidOff": "Afgelost",
+ "showSchedule": "Aflossingsschema tonen",
+ "hideSchedule": "Schema verbergen",
+ "colDate": "Datum",
+ "colPayment": "Termijn",
+ "colInterest": "Rente",
+ "colPrincipal": "Aflossing",
+ "colBalance": "Restschuld",
+ "adjustAction": "Saldo bijwerken",
+ "adjustTitle": "Openstaande schuld bijwerken",
+ "adjustHint": "Vul het saldo in dat de geldverstrekker opgeeft. Securo boekt het verschil als één transactie op deze lening, zodat geïndexeerde of heronderhandelde contracten gelijk blijven aan de bank.",
+ "adjustBalance": "Openstaande schuld",
+ "adjustDate": "Datum afschrift",
+ "adjustDescription": "Omschrijving",
+ "adjustDefaultDescription": "Indexatie en rente",
+ "adjustCategory": "Categorie (als de schuld is gestegen)",
+ "adjustOnDate": "Het verschil wordt berekend op het saldo op die datum.",
+ "adjustPreviewGrew": "De schuld is {{amount}} gestegen: dit wordt geboekt als kosten van de lening.",
+ "adjustPreviewFell": "De schuld is {{amount}} gedaald: het saldo wordt gecorrigeerd zonder als inkomen te tellen.",
+ "adjustPreviewMatches": "Het saldo komt al overeen met de bank.",
+ "adjustRecorded": "Saldo bijgewerkt: {{amount}} geboekt",
+ "adjustMatched": "Het saldo klopte al, er is niets geboekt"
+ },
"connections": {
"settings": "Verbindingsinstellingen",
"displayName": "Bijnaam",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 58cea0a3..eee1d98d 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -1243,6 +1243,31 @@
"noSecuredProperty": "Brak powiązanego składnika majątku",
"loanRetypeHint": "Tylko konto bez transakcji może zmienić typ na Kredyt lub z Kredytu.",
"loanRetypeBlocked": "To konto ma transakcje, więc nie może zmienić typu na Kredyt ani z Kredytu. Utwórz zamiast tego nowe konto kredytowe.",
+ "loanTerms": "Warunki umowy (opcjonalnie)",
+ "loanKind": "Rodzaj kredytu",
+ "loanKindNone": "Nie podano",
+ "loanKinds": {
+ "mortgage": "Kredyt hipoteczny",
+ "auto": "Kredyt samochodowy",
+ "personal": "Pożyczka gotówkowa",
+ "student": "Kredyt studencki",
+ "other": "Inny"
+ },
+ "loanOriginalAmount": "Kwota kredytu",
+ "loanInterestRate": "Oprocentowanie (%)",
+ "loanRatePeriod": "Okres stopy",
+ "loanRatePeriods": {
+ "monthly": "miesięcznie",
+ "yearly_effective": "rocznie (efektywne)",
+ "yearly_nominal": "rocznie (nominalne)"
+ },
+ "loanTermMonths": "Okres (miesiące)",
+ "loanFirstPayment": "Pierwsza rata",
+ "loanAmortization": "Spłata",
+ "loanAmortizations": {
+ "price": "Raty równe",
+ "sac": "Raty malejące"
+ },
"balanceLoan": "Pozostałe zadłużenie",
"creditLimit": "Limit kredytowy",
"statementCloseDay": "Dzień zamknięcia okresu rozliczeniowego",
@@ -1372,6 +1397,42 @@
"expired": "Wygasłe"
}
},
+ "loans": {
+ "title": "Umowa kredytu",
+ "notConfigured": "Podaj kwotę, oprocentowanie, okres i pierwszą ratę w ustawieniach konta, aby zobaczyć harmonogram spłat i datę spłaty.",
+ "nextPayment": "Następna rata",
+ "nextPaymentSplit": "{{date}} · odsetki {{interest}} · kapitał {{principal}}",
+ "remaining": "Pozostałe raty",
+ "remainingValue": "{{remaining}} z {{total}}",
+ "totalInterest": "Odsetki łącznie",
+ "payoff": "Spłata według umowy",
+ "projectedPayoff": "Spłata w obecnym tempie",
+ "ahead": "{{amount}} przed harmonogramem",
+ "behind": "{{amount}} za harmonogramem",
+ "onSchedule": "Zgodnie z planem",
+ "paidOff": "Spłacony",
+ "showSchedule": "Pokaż harmonogram",
+ "hideSchedule": "Ukryj harmonogram",
+ "colDate": "Data",
+ "colPayment": "Rata",
+ "colInterest": "Odsetki",
+ "colPrincipal": "Kapitał",
+ "colBalance": "Pozostało",
+ "adjustAction": "Zaktualizuj saldo",
+ "adjustTitle": "Zaktualizuj pozostały dług",
+ "adjustHint": "Wpisz saldo podane przez kredytodawcę. Securo zapisze różnicę jako jedną transakcję na tej pożyczce, aby umowy indeksowane lub renegocjowane zgadzały się z bankiem.",
+ "adjustBalance": "Pozostały dług",
+ "adjustDate": "Data wyciągu",
+ "adjustDescription": "Opis",
+ "adjustDefaultDescription": "Indeksacja i odsetki",
+ "adjustCategory": "Kategoria (gdy dług wzrósł)",
+ "adjustOnDate": "Różnica jest liczona względem salda z tego dnia.",
+ "adjustPreviewGrew": "Dług wzrósł o {{amount}}: zostanie zapisany jako koszt pożyczki.",
+ "adjustPreviewFell": "Dług spadł o {{amount}}: saldo zostanie poprawione bez liczenia jako przychód.",
+ "adjustPreviewMatches": "Saldo już zgadza się z bankiem.",
+ "adjustRecorded": "Saldo zaktualizowane: zapisano {{amount}}",
+ "adjustMatched": "Saldo już się zgadzało, nic nie zapisano"
+ },
"connections": {
"settings": "Ustawienia połączenia",
"displayName": "Pseudonim",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 792aeb89..c4f70ecd 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -1203,6 +1203,31 @@
"noSecuredProperty": "Nenhum bem vinculado",
"loanRetypeHint": "Só uma conta sem transações pode mudar de ou para Empréstimo.",
"loanRetypeBlocked": "Esta conta tem transações, então não pode mudar de ou para Empréstimo. Crie uma nova conta de empréstimo.",
+ "loanTerms": "Dados do contrato (opcional)",
+ "loanKind": "Tipo de empréstimo",
+ "loanKindNone": "Não informado",
+ "loanKinds": {
+ "mortgage": "Financiamento imobiliário",
+ "auto": "Financiamento de veículo",
+ "personal": "Empréstimo pessoal",
+ "student": "Crédito estudantil",
+ "other": "Outro"
+ },
+ "loanOriginalAmount": "Valor contratado",
+ "loanInterestRate": "Taxa de juros (%)",
+ "loanRatePeriod": "Período da taxa",
+ "loanRatePeriods": {
+ "monthly": "ao mês",
+ "yearly_effective": "ao ano (efetiva)",
+ "yearly_nominal": "ao ano (nominal)"
+ },
+ "loanTermMonths": "Prazo (meses)",
+ "loanFirstPayment": "Primeira parcela",
+ "loanAmortization": "Sistema de amortização",
+ "loanAmortizations": {
+ "price": "Parcela fixa (Price)",
+ "sac": "Amortização constante (SAC)"
+ },
"balanceLoan": "Dívida em aberto",
"creditLimit": "Limite do cartão",
"statementCloseDay": "Dia de fechamento",
@@ -1323,6 +1348,42 @@
"expired": "Expirada"
}
},
+ "loans": {
+ "title": "Contrato do empréstimo",
+ "notConfigured": "Informe valor, taxa, prazo e primeira parcela na edição da conta para ver a tabela de parcelas e a data de quitação.",
+ "nextPayment": "Próxima parcela",
+ "nextPaymentSplit": "{{date}} · juros {{interest}} · amortização {{principal}}",
+ "remaining": "Parcelas restantes",
+ "remainingValue": "{{remaining}} de {{total}}",
+ "totalInterest": "Juros totais",
+ "payoff": "Quitação pelo contrato",
+ "projectedPayoff": "Quitação no ritmo atual",
+ "ahead": "{{amount}} adiantado em relação ao contrato",
+ "behind": "{{amount}} atrasado em relação ao contrato",
+ "onSchedule": "Em dia",
+ "paidOff": "Quitado",
+ "showSchedule": "Ver tabela de parcelas",
+ "hideSchedule": "Ocultar tabela",
+ "colDate": "Data",
+ "colPayment": "Parcela",
+ "colInterest": "Juros",
+ "colPrincipal": "Amortização",
+ "colBalance": "Saldo devedor",
+ "adjustAction": "Atualizar saldo",
+ "adjustTitle": "Atualizar saldo devedor",
+ "adjustHint": "Informe o saldo que o banco mostra. O Securo lança a diferença como uma transação neste empréstimo, para que contratos com índice ou renegociados fiquem iguais ao banco.",
+ "adjustBalance": "Saldo devedor",
+ "adjustDate": "Data do extrato",
+ "adjustDescription": "Descrição",
+ "adjustDefaultDescription": "Correção monetária e juros",
+ "adjustCategory": "Categoria (quando a dívida aumentou)",
+ "adjustOnDate": "A diferença é calculada sobre o saldo nessa data.",
+ "adjustPreviewGrew": "A dívida aumentou {{amount}}: entra como custo do empréstimo.",
+ "adjustPreviewFell": "A dívida caiu {{amount}}: o saldo é corrigido sem contar como receita.",
+ "adjustPreviewMatches": "O saldo já confere com o do banco.",
+ "adjustRecorded": "Saldo atualizado: {{amount}} lançado",
+ "adjustMatched": "O saldo já conferia, nada foi lançado"
+ },
"connections": {
"settings": "Configurações da conexão",
"displayName": "Apelido",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index 591f1674..e3eccdce 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -1203,6 +1203,31 @@
"noSecuredProperty": "Nenhum bem associado",
"loanRetypeHint": "Só uma conta sem transações pode mudar de ou para Empréstimo.",
"loanRetypeBlocked": "Esta conta tem transações, por isso não pode mudar de ou para Empréstimo. Crie uma nova conta de empréstimo.",
+ "loanTerms": "Dados do contrato (opcional)",
+ "loanKind": "Tipo de empréstimo",
+ "loanKindNone": "Não indicado",
+ "loanKinds": {
+ "mortgage": "Crédito à habitação",
+ "auto": "Crédito automóvel",
+ "personal": "Crédito pessoal",
+ "student": "Crédito estudantil",
+ "other": "Outro"
+ },
+ "loanOriginalAmount": "Montante contratado",
+ "loanInterestRate": "Taxa de juro (%)",
+ "loanRatePeriod": "Período da taxa",
+ "loanRatePeriods": {
+ "monthly": "ao mês",
+ "yearly_effective": "ao ano (efetiva)",
+ "yearly_nominal": "ao ano (nominal, TAN)"
+ },
+ "loanTermMonths": "Prazo (meses)",
+ "loanFirstPayment": "Primeira prestação",
+ "loanAmortization": "Sistema de amortização",
+ "loanAmortizations": {
+ "price": "Prestação constante (Price)",
+ "sac": "Amortização constante (SAC)"
+ },
"balanceLoan": "Montante em dívida",
"creditLimit": "Limite do cartão",
"statementCloseDay": "Dia de fecho",
@@ -1323,6 +1348,42 @@
"expired": "Expirada"
}
},
+ "loans": {
+ "title": "Contrato do empréstimo",
+ "notConfigured": "Indique montante, taxa, prazo e primeira prestação na edição da conta para ver o plano de prestações e a data de liquidação.",
+ "nextPayment": "Próxima prestação",
+ "nextPaymentSplit": "{{date}} · juros {{interest}} · amortização {{principal}}",
+ "remaining": "Prestações em falta",
+ "remainingValue": "{{remaining}} de {{total}}",
+ "totalInterest": "Juros totais",
+ "payoff": "Liquidação pelo contrato",
+ "projectedPayoff": "Liquidação ao ritmo atual",
+ "ahead": "{{amount}} adiantado face ao contrato",
+ "behind": "{{amount}} atrasado face ao contrato",
+ "onSchedule": "Em dia",
+ "paidOff": "Liquidado",
+ "showSchedule": "Ver plano de prestações",
+ "hideSchedule": "Ocultar plano",
+ "colDate": "Data",
+ "colPayment": "Prestação",
+ "colInterest": "Juros",
+ "colPrincipal": "Amortização",
+ "colBalance": "Capital em dívida",
+ "adjustAction": "Atualizar saldo",
+ "adjustTitle": "Atualizar capital em dívida",
+ "adjustHint": "Indique o saldo que o banco apresenta. O Securo regista a diferença como uma transação neste empréstimo, para que contratos indexados ou renegociados fiquem iguais ao banco.",
+ "adjustBalance": "Capital em dívida",
+ "adjustDate": "Data do extrato",
+ "adjustDescription": "Descrição",
+ "adjustDefaultDescription": "Atualização do índice e juros",
+ "adjustCategory": "Categoria (quando a dívida aumentou)",
+ "adjustOnDate": "A diferença é calculada sobre o saldo nessa data.",
+ "adjustPreviewGrew": "A dívida aumentou {{amount}}: é registada como custo do empréstimo.",
+ "adjustPreviewFell": "A dívida diminuiu {{amount}}: o saldo é corrigido sem contar como receita.",
+ "adjustPreviewMatches": "O saldo já coincide com o do banco.",
+ "adjustRecorded": "Saldo atualizado: {{amount}} registado",
+ "adjustMatched": "O saldo já coincidia, nada foi registado"
+ },
"connections": {
"settings": "Definições da ligação",
"displayName": "Nome personalizado",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 91f7a517..4628e3dd 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -1216,6 +1216,31 @@
"noSecuredProperty": "Нет связанного имущества",
"loanRetypeHint": "Только счёт без транзакций можно перевести в тип «Кредит» или из него.",
"loanRetypeBlocked": "У этого счёта есть транзакции, поэтому его нельзя перевести в тип «Кредит» или из него. Создайте новый кредитный счёт.",
+ "loanTerms": "Условия договора (необязательно)",
+ "loanKind": "Тип кредита",
+ "loanKindNone": "Не указан",
+ "loanKinds": {
+ "mortgage": "Ипотека",
+ "auto": "Автокредит",
+ "personal": "Потребительский кредит",
+ "student": "Образовательный кредит",
+ "other": "Другое"
+ },
+ "loanOriginalAmount": "Сумма кредита",
+ "loanInterestRate": "Процентная ставка (%)",
+ "loanRatePeriod": "Период ставки",
+ "loanRatePeriods": {
+ "monthly": "в месяц",
+ "yearly_effective": "в год (эффективная)",
+ "yearly_nominal": "в год (номинальная)"
+ },
+ "loanTermMonths": "Срок (месяцы)",
+ "loanFirstPayment": "Первый платёж",
+ "loanAmortization": "Погашение",
+ "loanAmortizations": {
+ "price": "Аннуитетный платёж",
+ "sac": "Дифференцированный платёж"
+ },
"balanceLoan": "Остаток долга",
"creditLimit": "Кредитный лимит",
"statementCloseDay": "Дата закрытия выписки",
@@ -1336,6 +1361,42 @@
"expired": "Истекло"
}
},
+ "loans": {
+ "title": "Кредитный договор",
+ "notConfigured": "Укажите сумму, ставку, срок и первый платёж в настройках счёта, чтобы увидеть график платежей и дату погашения.",
+ "nextPayment": "Следующий платёж",
+ "nextPaymentSplit": "{{date}} · проценты {{interest}} · основной долг {{principal}}",
+ "remaining": "Осталось платежей",
+ "remainingValue": "{{remaining}} из {{total}}",
+ "totalInterest": "Всего процентов",
+ "payoff": "Погашение по договору",
+ "projectedPayoff": "Погашение в текущем темпе",
+ "ahead": "{{amount}} с опережением договора",
+ "behind": "{{amount}} с отставанием от договора",
+ "onSchedule": "По графику",
+ "paidOff": "Погашен",
+ "showSchedule": "Показать график платежей",
+ "hideSchedule": "Скрыть график",
+ "colDate": "Дата",
+ "colPayment": "Платёж",
+ "colInterest": "Проценты",
+ "colPrincipal": "Основной долг",
+ "colBalance": "Остаток долга",
+ "adjustAction": "Обновить остаток",
+ "adjustTitle": "Обновить остаток долга",
+ "adjustHint": "Введите остаток, который указывает кредитор. Securo запишет разницу одной транзакцией по этому кредиту, чтобы индексируемые или пересмотренные договоры совпадали с банком.",
+ "adjustBalance": "Остаток долга",
+ "adjustDate": "Дата выписки",
+ "adjustDescription": "Описание",
+ "adjustDefaultDescription": "Индексация и проценты",
+ "adjustCategory": "Категория (если долг вырос)",
+ "adjustOnDate": "Разница считается от остатка на эту дату.",
+ "adjustPreviewGrew": "Долг вырос на {{amount}}: это записывается как расход по кредиту.",
+ "adjustPreviewFell": "Долг уменьшился на {{amount}}: остаток исправляется, не считаясь доходом.",
+ "adjustPreviewMatches": "Остаток уже совпадает с банком.",
+ "adjustRecorded": "Остаток обновлён: записано {{amount}}",
+ "adjustMatched": "Остаток уже совпадал, ничего не записано"
+ },
"connections": {
"settings": "Настройки подключения",
"displayName": "Псевдоним",
diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.json
index 9a5b1108..f2bc44e0 100644
--- a/frontend/src/locales/sk.json
+++ b/frontend/src/locales/sk.json
@@ -1255,6 +1255,31 @@
"noSecuredProperty": "Žiadny prepojený majetok",
"loanRetypeHint": "Iba účet bez transakcií môže prejsť na typ Úver alebo z neho.",
"loanRetypeBlocked": "Tento účet má transakcie, preto nemôže prejsť na typ Úver ani z neho. Vytvorte namiesto toho nový úverový účet.",
+ "loanTerms": "Zmluvné podmienky (nepovinné)",
+ "loanKind": "Typ úveru",
+ "loanKindNone": "Neuvedené",
+ "loanKinds": {
+ "mortgage": "Hypotéka",
+ "auto": "Úver na vozidlo",
+ "personal": "Spotrebný úver",
+ "student": "Študentský úver",
+ "other": "Iný"
+ },
+ "loanOriginalAmount": "Výška úveru",
+ "loanInterestRate": "Úroková sadzba (%)",
+ "loanRatePeriod": "Obdobie sadzby",
+ "loanRatePeriods": {
+ "monthly": "mesačne",
+ "yearly_effective": "ročne (efektívna)",
+ "yearly_nominal": "ročne (nominálna)"
+ },
+ "loanTermMonths": "Doba splácania (mesiace)",
+ "loanFirstPayment": "Prvá splátka",
+ "loanAmortization": "Splácanie",
+ "loanAmortizations": {
+ "price": "Rovnaká splátka (anuita)",
+ "sac": "Rovnaká istina"
+ },
"balanceLoan": "Zostatok dlhu",
"creditLimit": "Kreditný limit",
"statementCloseDay": "Deň uzávierky výpisu",
@@ -1387,6 +1412,42 @@
"expired": "Vypršané"
}
},
+ "loans": {
+ "title": "Úverová zmluva",
+ "notConfigured": "Zadajte sumu, sadzbu, dobu splácania a prvú splátku v nastaveniach účtu, aby ste videli splátkový kalendár a dátum splatenia.",
+ "nextPayment": "Ďalšia splátka",
+ "nextPaymentSplit": "{{date}} · úrok {{interest}} · istina {{principal}}",
+ "remaining": "Zostávajúce splátky",
+ "remainingValue": "{{remaining}} z {{total}}",
+ "totalInterest": "Úroky spolu",
+ "payoff": "Splatenie podľa zmluvy",
+ "projectedPayoff": "Splatenie súčasným tempom",
+ "ahead": "{{amount}} vpred oproti zmluve",
+ "behind": "{{amount}} pozadu oproti zmluve",
+ "onSchedule": "Podľa plánu",
+ "paidOff": "Splatené",
+ "showSchedule": "Zobraziť splátkový kalendár",
+ "hideSchedule": "Skryť kalendár",
+ "colDate": "Dátum",
+ "colPayment": "Splátka",
+ "colInterest": "Úrok",
+ "colPrincipal": "Istina",
+ "colBalance": "Zostatok",
+ "adjustAction": "Aktualizovať zostatok",
+ "adjustTitle": "Aktualizovať zostávajúci dlh",
+ "adjustHint": "Zadajte zostatok, ktorý uvádza veriteľ. Securo zapíše rozdiel ako jednu transakciu na tomto úvere, aby indexované alebo prerokované zmluvy zodpovedali banke.",
+ "adjustBalance": "Zostávajúci dlh",
+ "adjustDate": "Dátum výpisu",
+ "adjustDescription": "Popis",
+ "adjustDefaultDescription": "Indexácia a úroky",
+ "adjustCategory": "Kategória (keď dlh vzrástol)",
+ "adjustOnDate": "Rozdiel sa počíta voči zostatku k tomuto dátumu.",
+ "adjustPreviewGrew": "Dlh vzrástol o {{amount}}: zapíše sa ako náklad úveru.",
+ "adjustPreviewFell": "Dlh klesol o {{amount}}: zostatok sa opraví bez toho, aby sa počítal ako príjem.",
+ "adjustPreviewMatches": "Zostatok už zodpovedá banke.",
+ "adjustRecorded": "Zostatok aktualizovaný: zapísané {{amount}}",
+ "adjustMatched": "Zostatok už zodpovedal, nič nebolo zapísané"
+ },
"connections": {
"settings": "Nastavenia prepojenia",
"displayName": "Prezývka",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 8c95b898..fe7a1e84 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -1216,6 +1216,31 @@
"noSecuredProperty": "Немає пов’язаного майна",
"loanRetypeHint": "Лише рахунок без транзакцій можна перевести в тип «Кредит» або з нього.",
"loanRetypeBlocked": "Цей рахунок має транзакції, тому його не можна перевести в тип «Кредит» або з нього. Створіть новий кредитний рахунок.",
+ "loanTerms": "Умови договору (необов’язково)",
+ "loanKind": "Тип кредиту",
+ "loanKindNone": "Не вказано",
+ "loanKinds": {
+ "mortgage": "Іпотека",
+ "auto": "Автокредит",
+ "personal": "Споживчий кредит",
+ "student": "Освітній кредит",
+ "other": "Інше"
+ },
+ "loanOriginalAmount": "Сума кредиту",
+ "loanInterestRate": "Процентна ставка (%)",
+ "loanRatePeriod": "Період ставки",
+ "loanRatePeriods": {
+ "monthly": "на місяць",
+ "yearly_effective": "на рік (ефективна)",
+ "yearly_nominal": "на рік (номінальна)"
+ },
+ "loanTermMonths": "Строк (місяці)",
+ "loanFirstPayment": "Перший платіж",
+ "loanAmortization": "Погашення",
+ "loanAmortizations": {
+ "price": "Ануїтетний платіж",
+ "sac": "Диференційований платіж"
+ },
"balanceLoan": "Залишок боргу",
"creditLimit": "Кредитний ліміт",
"statementCloseDay": "Дата закриття виписки",
@@ -1336,6 +1361,42 @@
"expired": "Термін дії минув"
}
},
+ "loans": {
+ "title": "Кредитний договір",
+ "notConfigured": "Вкажіть суму, ставку, строк і перший платіж у налаштуваннях рахунку, щоб побачити графік платежів і дату погашення.",
+ "nextPayment": "Наступний платіж",
+ "nextPaymentSplit": "{{date}} · відсотки {{interest}} · основний борг {{principal}}",
+ "remaining": "Залишилось платежів",
+ "remainingValue": "{{remaining}} з {{total}}",
+ "totalInterest": "Усього відсотків",
+ "payoff": "Погашення за договором",
+ "projectedPayoff": "Погашення в поточному темпі",
+ "ahead": "{{amount}} з випередженням договору",
+ "behind": "{{amount}} з відставанням від договору",
+ "onSchedule": "За графіком",
+ "paidOff": "Погашено",
+ "showSchedule": "Показати графік платежів",
+ "hideSchedule": "Сховати графік",
+ "colDate": "Дата",
+ "colPayment": "Платіж",
+ "colInterest": "Відсотки",
+ "colPrincipal": "Основний борг",
+ "colBalance": "Залишок боргу",
+ "adjustAction": "Оновити залишок",
+ "adjustTitle": "Оновити залишок боргу",
+ "adjustHint": "Введіть залишок, який вказує кредитор. Securo запише різницю однією транзакцією за цим кредитом, щоб індексовані або переглянуті договори збігалися з банком.",
+ "adjustBalance": "Залишок боргу",
+ "adjustDate": "Дата виписки",
+ "adjustDescription": "Опис",
+ "adjustDefaultDescription": "Індексація та відсотки",
+ "adjustCategory": "Категорія (якщо борг зріс)",
+ "adjustOnDate": "Різниця рахується від залишку на цю дату.",
+ "adjustPreviewGrew": "Борг зріс на {{amount}}: це записується як витрата за кредитом.",
+ "adjustPreviewFell": "Борг зменшився на {{amount}}: залишок виправляється, не враховуючись як дохід.",
+ "adjustPreviewMatches": "Залишок уже збігається з банком.",
+ "adjustRecorded": "Залишок оновлено: записано {{amount}}",
+ "adjustMatched": "Залишок уже збігався, нічого не записано"
+ },
"connections": {
"settings": "Налаштування підключення",
"displayName": "Псевдонім",
diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsx
index 90513d8a..b489e67a 100644
--- a/frontend/src/pages/account-detail.tsx
+++ b/frontend/src/pages/account-detail.tsx
@@ -36,6 +36,7 @@ import { useWorkspace } from '@/contexts/workspace-context'
import { useCreateTransaction } from '@/hooks/use-create-transaction'
import { resolveDateFnsLocale } from '@/lib/date-fns-locale'
import { formatCurrency } from '@/lib/format'
+import { LoanScheduleCard } from '@/components/loan-schedule-card'
import {
AreaChart,
Area,
@@ -1452,6 +1453,10 @@ export default function AccountDetailPage() {
)
})()}
+ {account.type === 'loan' && (
+ <LoanScheduleCard accountId={account.id} locale={locale} dateLocale={dateLocale} mask={mask} canWrite={canWrite} />
+ )}
+
{/* Balance / Cycle spending chart */}
{(() => {
const cycleEmpty = isCreditCard && chartData.length > 0 && chartData[chartData.length - 1].balance === 0
diff --git a/frontend/src/pages/accounts-dialog-loan-terms.test.tsx b/frontend/src/pages/accounts-dialog-loan-terms.test.tsx
new file mode 100644
index 00000000..aeca39c7
--- /dev/null
+++ b/frontend/src/pages/accounts-dialog-loan-terms.test.tsx
@@ -0,0 +1,62 @@
+import { fireEvent, screen, within } from '@testing-library/react'
+import { expect, it, vi } from 'vitest'
+import { renderWithProviders, t } from '@/test/utils'
+import type { Account } from '@/types'
+
+vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ user: null }) }))
+vi.mock('@/lib/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/api')>()),
+ currencies: { list: vi.fn().mockResolvedValue([]) },
+ assets: { list: vi.fn().mockResolvedValue([]) },
+}))
+// A plain input stands in for the calendar popover.
+vi.mock('@/components/ui/date-picker-input', () => ({
+ DatePickerInput: ({ value, onChange }: { value: string; onChange: (v: string) => void }) => (
+ <input value={value} onChange={(e) => onChange(e.target.value)} />
+ ),
+}))
+
+import { AccountDialog } from './accounts'
+
+const loan = {
+ id: 'loan-1',
+ connection_id: null,
+ name: 'Car loan',
+ display_name: null,
+ type: 'loan',
+ balance: -30000,
+ currency: 'BRL',
+ balance_date: '2026-08-01',
+ credit_limit: null,
+ statement_close_day: null,
+ payment_due_day: null,
+ secured_asset_id: null,
+ loan_kind: 'auto',
+ loan_original_amount: 50000,
+ loan_interest_rate: 1.2,
+ loan_rate_period: 'monthly',
+ loan_term_months: 48,
+ loan_first_payment_date: '2026-02-10',
+ loan_amortization: 'price',
+} as Account
+
+function termsSection() {
+ return screen.getByText(t('accounts.loanTerms')).closest('details') as HTMLDetailsElement
+}
+
+it('keeps the contract terms open while the amount is cleared', () => {
+ renderWithProviders(<AccountDialog open onClose={vi.fn()} account={loan} onSave={vi.fn()} loading={false} />)
+
+ expect(termsSection().open).toBe(true)
+ const [amount] = within(termsSection()).getAllByRole('spinbutton')
+ fireEvent.change(amount, { target: { value: '' } })
+
+ expect(termsSection().open).toBe(true)
+})
+
+it('starts with the contract terms closed for a loan without them', () => {
+ const plain = { ...loan, loan_kind: null, loan_original_amount: null, loan_interest_rate: null, loan_term_months: null, loan_first_payment_date: null } as Account
+ renderWithProviders(<AccountDialog open onClose={vi.fn()} account={plain} onSave={vi.fn()} loading={false} />)
+
+ expect(termsSection().open).toBe(false)
+})
diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsx
index 8b62703d..8b648512 100644
--- a/frontend/src/pages/accounts.tsx
+++ b/frontend/src/pages/accounts.tsx
@@ -23,7 +23,7 @@ import {
import { DatePickerInput } from '@/components/ui/date-picker-input'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
-import type { Account, BankConnection } from '@/types'
+import type { Account, BankConnection, LoanAmortization, LoanRatePeriod } from '@/types'
import { RefreshCw, TriangleAlert, Unlink, Settings } from 'lucide-react'
import { AccountIcon, ConnectionLogo } from '@/components/account-icon'
import { getAccountTypeConfig } from '@/lib/account-type-config'
@@ -702,6 +702,56 @@ export default function AccountsPage() {
)
}
+// The contract terms of a loan as the dialog edits them (inputs hold strings).
+type LoanTermsForm = {
+ kind: string
+ amount: string
+ rate: string
+ period: LoanRatePeriod
+ term: string
+ firstPayment: string
+ amortization: LoanAmortization
+}
+
+const LOAN_KINDS = ['mortgage', 'auto', 'personal', 'student', 'other'] as const
+
+function loanTermsFrom(account: Account | null | undefined, currency: string): LoanTermsForm {
+ return {
+ kind: account?.loan_kind ?? '',
+ amount: account?.loan_original_amount?.toString() ?? '',
+ rate: account?.loan_interest_rate?.toString() ?? '',
+ // Brazilian loans are usually quoted per month; elsewhere a yearly APR.
+ period: account?.loan_rate_period ?? (currency === 'BRL' ? 'monthly' : 'yearly_nominal'),
+ term: account?.loan_term_months?.toString() ?? '',
+ firstPayment: account?.loan_first_payment_date ?? '',
+ amortization: account?.loan_amortization ?? 'price',
+ }
+}
+
+type LoanTermsPayload = Pick<
+ Account,
+ | 'loan_kind'
+ | 'loan_original_amount'
+ | 'loan_interest_rate'
+ | 'loan_rate_period'
+ | 'loan_term_months'
+ | 'loan_first_payment_date'
+ | 'loan_amortization'
+>
+
+function loanTermsPayload(terms: LoanTermsForm): LoanTermsPayload {
+ const number = (value: string) => (value.trim() === '' ? null : Number(value))
+ return {
+ loan_kind: (terms.kind || null) as Account['loan_kind'],
+ loan_original_amount: number(terms.amount),
+ loan_interest_rate: number(terms.rate),
+ loan_rate_period: terms.period,
+ loan_term_months: number(terms.term),
+ loan_first_payment_date: terms.firstPayment || null,
+ loan_amortization: terms.amortization,
+ }
+}
+
export function AccountDialog({
open,
onClose,
@@ -752,6 +802,11 @@ export function AccountDialog({
const [statementCloseDay, setStatementCloseDay] = useState(account?.statement_close_day?.toString() ?? '')
const [paymentDueDay, setPaymentDueDay] = useState(account?.payment_due_day?.toString() ?? '')
const [securedAssetId, setSecuredAssetId] = useState(account?.secured_asset_id ?? '')
+ const [loanTerms, setLoanTerms] = useState(() => loanTermsFrom(account, account?.currency ?? userCurrency))
+ // Opened by the user, not by the amount: clearing the amount must not collapse it.
+ const [termsOpen, setTermsOpen] = useState(() => account?.loan_original_amount != null)
+ const setLoanTerm = <K extends keyof LoanTermsForm>(key: K, value: LoanTermsForm[K]) =>
+ setLoanTerms((prev) => ({ ...prev, [key]: value }))
const properties = (assetsList ?? []).filter((asset) => LOAN_COLLATERAL_TYPES.includes(asset.type))
// Send the link the select shows: a saved id that is no longer a listed
@@ -774,6 +829,8 @@ export function AccountDialog({
setStatementCloseDay(account?.statement_close_day?.toString() ?? '')
setPaymentDueDay(account?.payment_due_day?.toString() ?? '')
setSecuredAssetId(account?.secured_asset_id ?? '')
+ setLoanTerms(loanTermsFrom(account, account?.currency ?? userCurrency))
+ setTermsOpen(account?.loan_original_amount != null)
}
return (
@@ -804,7 +861,10 @@ export function AccountDialog({
currency,
}),
type,
- ...(type === 'loan' && { secured_asset_id: securedAssetIsListed ? securedAssetId : null }),
+ ...(type === 'loan' && {
+ secured_asset_id: securedAssetIsListed ? securedAssetId : null,
+ ...loanTermsPayload(loanTerms),
+ }),
display_name: displayName.trim() || null,
...(isCC && {
credit_limit: creditLimit !== '' ? parseFloat(creditLimit) : null,
@@ -923,6 +983,55 @@ export function AccountDialog({
<option key={asset.id} value={asset.id}>{asset.name}</option>
))}
</select>
+ <details
+ className="rounded-lg border border-border p-3 mt-2"
+ open={termsOpen}
+ onToggle={(e) => setTermsOpen(e.currentTarget.open)}
+ >
+ <summary className="cursor-pointer text-sm font-medium">{t('accounts.loanTerms')}</summary>
+ <div className="grid grid-cols-2 gap-3 pt-3">
+ <div className="space-y-1">
+ <Label>{t('accounts.loanKind')}</Label>
+ <select className="w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary" value={loanTerms.kind} onChange={(e) => setLoanTerm('kind', e.target.value)}>
+ <option value="">{t('accounts.loanKindNone')}</option>
+ {LOAN_KINDS.map((kind) => (
+ <option key={kind} value={kind}>{t(`accounts.loanKinds.${kind}`)}</option>
+ ))}
+ </select>
+ </div>
+ <div className="space-y-1">
+ <Label>{t('accounts.loanOriginalAmount')}</Label>
+ <Input type="number" step="0.01" min="0.01" value={loanTerms.amount} onChange={(e) => setLoanTerm('amount', e.target.value)} />
+ </div>
+ <div className="space-y-1">
+ <Label>{t('accounts.loanInterestRate')}</Label>
+ <Input type="number" step="0.0001" min="0" max="100" value={loanTerms.rate} onChange={(e) => setLoanTerm('rate', e.target.value)} />
+ </div>
+ <div className="space-y-1">
+ <Label>{t('accounts.loanRatePeriod')}</Label>
+ <select className="w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary" value={loanTerms.period} onChange={(e) => setLoanTerm('period', e.target.value as LoanRatePeriod)}>
+ <option value="monthly">{t('accounts.loanRatePeriods.monthly')}</option>
+ <option value="yearly_effective">{t('accounts.loanRatePeriods.yearly_effective')}</option>
+ <option value="yearly_nominal">{t('accounts.loanRatePeriods.yearly_nominal')}</option>
+ </select>
+ </div>
+ <div className="space-y-1">
+ <Label>{t('accounts.loanTermMonths')}</Label>
+ <Input type="number" step="1" min="1" max="600" value={loanTerms.term} onChange={(e) => setLoanTerm('term', e.target.value)} />
+ </div>
+ <div className="space-y-1">
+ <Label>{t('accounts.loanFirstPayment')}</Label>
+ <DatePickerInput value={loanTerms.firstPayment} onChange={(value) => setLoanTerm('firstPayment', value)} className="w-full justify-start" />
+ </div>
+ <div className="space-y-1 col-span-2">
+ <Label>{t('accounts.loanAmortization')}</Label>
+ <select className="w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary" value={loanTerms.amortization} onChange={(e) => setLoanTerm('amortization', e.target.value as LoanAmortization)}>
+ <option value="price">{t('accounts.loanAmortizations.price')}</option>
+ <option value="sac">{t('accounts.loanAmortizations.sac')}</option>
+ </select>
+ </div>
+ </div>
+ </details>
</div>
)}
{type === 'credit_card' && (
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 4d7de4de..f1a0729d 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -179,6 +179,14 @@ export interface Account {
institution_logo_url: string | null
type: string
secured_asset_id?: string | null
+ // Loan accounts only: contract terms the payment schedule is computed from.
+ loan_kind?: LoanKind | null
+ loan_original_amount?: number | null
+ loan_interest_rate?: number | null
+ loan_rate_period?: LoanRatePeriod | null
+ loan_term_months?: number | null
+ loan_first_payment_date?: string | null
+ loan_amortization?: LoanAmortization | null
balance: number
current_balance: number
previous_balance: number | null
@@ -1874,3 +1882,52 @@ export interface ReconciliationHistoryEvent {
transaction_id?: string | null
transaction_description?: string | null
}
+
+export type LoanKind = 'mortgage' | 'auto' | 'personal' | 'student' | 'other'
+export type LoanRatePeriod = 'monthly' | 'yearly_effective' | 'yearly_nominal'
+export type LoanAmortization = 'price' | 'sac'
+
+export interface LoanInstallment {
+ number: number
+ due_date: string
+ payment: number
+ interest: number
+ principal: number
+ balance: number
+}
+
+/** The lender's balance on a date, sent to bring a loan's ledger in line. */
+export interface LoanBalanceUpdate {
+ balance: number
+ date: string
+ description: string
+ category_id?: string | null
+}
+
+/** What the backend recorded: positive when the debt grew, 0 when it already matched. */
+export interface LoanBalanceAdjustment {
+ adjustment: number
+ current_debt: number
+ transaction_id: string | null
+}
+
+/** A loan's payment schedule, computed by the backend from its contract terms. */
+export interface LoanSchedule {
+ account_id: string
+ currency: string
+ current_debt: number
+ configured: boolean
+ missing: string[]
+ monthly_payment: number | null
+ payments_due: number | null
+ remaining_payments: number | null
+ next_payment: LoanInstallment | null
+ scheduled_balance: number | null
+ ahead_by: number | null
+ total_interest: number | null
+ total_paid: number | null
+ payoff_date: string | null
+ projected_payoff_date: string | null
+ paid_off: boolean
+ installments: LoanInstallment[]
+}