D34: валюты в прогнозе — конвертация по курсам и валюта вывода
- расчёт ведётся в базовой валюте модели: баланс счёта переводится из валюты счёта, операция — из своей валюты (пусто = валюта счёта), актив и обязательство — из своей (пусто = базовая); - нет курса — не падение, а предупреждение: сумма не попадает в прогноз, но пользователь видит, чего не хватает (нет курса USD → RUB); - FinancialModel.display_currency — валюта вывода по умолчанию; новая команда cf config display-currency; cf forecast/scenario/compare печатают предупреждения расчёта; cf info показывает обе валюты и суммы в валюте их владельца; - рост активов при нулевых балансах теперь делится поровну — раньше он делился по доле от единицы и просто исчезал. Тесты: 296 → 302 (класс TestForecastCurrency: конвертация баланса, операции, актива, регулярного платежа, предупреждение об отсутствии курса).
This commit is contained in:
1 parent
289f039ed8
commit
885a91f15f
14 files changed
+300
-45
No files matched your search
+109
-29
@@ -2,7 +2,8 @@ from copy import deepcopy
|
||||
from datetime import date, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
|
||||
from domain import Account, FinancialModel, Transaction
|
||||
from domain import Account, FinancialModel, RecurringCashflow
|
||||
from domain.currency import CurrencyConverter, CurrencyError
|
||||
from domain.recurrence import parse_date
|
||||
|
||||
|
||||
@@ -67,36 +68,77 @@ class ForecastService:
|
||||
Транзакции раскладываются по датам (D33): операция из прошлого уже учтена
|
||||
в балансе счёта и в прогноз не попадает, операция будущего попадает в
|
||||
месяц своей даты. Регулярные платежи считаются по календарю (D32).
|
||||
|
||||
Валюты (D34): расчёт ведётся в базовой валюте модели. Баланс счёта —
|
||||
в валюте счёта, операция — в своей валюте (пусто = валюта счёта или
|
||||
базовая). Нет курса — не ошибка, а предупреждение: сумма не попадает
|
||||
в прогноз, но пользователь видит, чего не хватает.
|
||||
"""
|
||||
|
||||
def __init__(self, model: FinancialModel, start_month: str | date | None = None):
|
||||
def __init__(
|
||||
self,
|
||||
model: FinancialModel,
|
||||
start_month: str | date | None = None,
|
||||
converter: CurrencyConverter | None = None,
|
||||
):
|
||||
self.model = deepcopy(model)
|
||||
self.start_month = _first_of_month(start_month)
|
||||
# Предупреждения расчёта (D33): операция без счёта, счёт не найден.
|
||||
self._converter = converter or CurrencyConverter(self.model.exchange_rates)
|
||||
# Предупреждения расчёта: счёт не найден, нет курса валюты.
|
||||
self.warnings: list[str] = []
|
||||
|
||||
@property
|
||||
def converter(self) -> CurrencyConverter:
|
||||
return self._converter
|
||||
|
||||
def forecast_cashflow(self, months: int = 12) -> list[dict]:
|
||||
if months < 1:
|
||||
raise ForecastError("Число месяцев должно быть не меньше 1")
|
||||
|
||||
self.warnings = []
|
||||
base = self.model.base_currency
|
||||
|
||||
# Локальное состояние расчёта — вместо мутации модели (D14).
|
||||
# `liability_balances` — текущий остаток по каждому обязательству,
|
||||
# `asset_values` — текущая стоимость каждого актива.
|
||||
liability_balances = [li.balance for li in self.model.liabilities]
|
||||
asset_values = [a.value for a in self.model.assets]
|
||||
# Локальное состояние расчёта — вместо мутации модели (D14). Все
|
||||
# суммы переводятся в базовую валюту: `liability_balances` — текущий
|
||||
# остаток по каждому обязательству, `asset_values` — текущая стоимость
|
||||
# каждого актива.
|
||||
liability_balances = [
|
||||
self._to_base(li.balance, li.currency or base, f"обязательство «{li.name}»") or _ZERO
|
||||
for li in self.model.liabilities
|
||||
]
|
||||
asset_values = [
|
||||
self._to_base(a.value, a.currency or base, f"актив «{a.name}»") or _ZERO
|
||||
for a in self.model.assets
|
||||
]
|
||||
account_balances = [
|
||||
self._to_base(account.balance, account.currency or base, f"счёт «{account.name}»") or _ZERO
|
||||
for account in self.model.accounts
|
||||
]
|
||||
|
||||
# Транзакции, разложенные по счетам и месяцам сетки (D33).
|
||||
transactions_by_account = self._group_transactions(months)
|
||||
transactions_by_account = self._group_transactions(months, base)
|
||||
|
||||
# Регулярные платежи — сумма списания переводится в базовую валюту
|
||||
# один раз, а не на каждый месяц (D34).
|
||||
recurring_base: list[tuple[RecurringCashflow, Decimal]] = []
|
||||
for r in self.model.recurring:
|
||||
amount = self._to_base(
|
||||
r.amount,
|
||||
r.currency or base,
|
||||
f"регулярный платёж «{r.category or r.id}»",
|
||||
)
|
||||
if amount is None:
|
||||
continue
|
||||
recurring_base.append((r, amount))
|
||||
|
||||
results = []
|
||||
for index, account in enumerate(self.model.accounts):
|
||||
monthly = self._project_account(
|
||||
account,
|
||||
account_balances[index],
|
||||
months,
|
||||
liability_balances,
|
||||
transactions_by_account.get(index, []),
|
||||
recurring_base,
|
||||
)
|
||||
for m in range(months):
|
||||
results.append(
|
||||
@@ -115,11 +157,18 @@ class ForecastService:
|
||||
value * a.growth_rate / _HUNDRED / _TWELVE for value, a in zip(asset_values, self.model.assets)
|
||||
)
|
||||
month_rows = [r for r in results if r["month"] == m + 1]
|
||||
total_bal = sum(r["balance"] for r in month_rows) or _ONE
|
||||
for r in month_rows:
|
||||
share = r["balance"] / total_bal
|
||||
r["income"] = _q(r["income"] + total_growth * share)
|
||||
r["balance"] = _q(r["balance"] + total_growth * share)
|
||||
total_bal = sum(r["balance"] for r in month_rows)
|
||||
if total_bal > 0:
|
||||
shares = [r["balance"] / total_bal for r in month_rows]
|
||||
elif month_rows:
|
||||
# Балансов нет — рост активов делим поровну. Раньше делили по
|
||||
# доле от единицы, и при нулевых балансах рост просто исчезал.
|
||||
shares = [_ONE / len(month_rows)] * len(month_rows)
|
||||
else:
|
||||
shares = []
|
||||
for row, share in zip(month_rows, shares):
|
||||
row["income"] = _q(row["income"] + total_growth * share)
|
||||
row["balance"] = _q(row["balance"] + total_growth * share)
|
||||
|
||||
# Compound asset values for next month (локально, модель не меняется)
|
||||
asset_values = [
|
||||
@@ -128,15 +177,38 @@ class ForecastService:
|
||||
|
||||
return results
|
||||
|
||||
# -- валюты -------------------------------------------------------------
|
||||
|
||||
def _to_base(self, amount: Decimal, currency: str, subject: str = "") -> Decimal | None:
|
||||
"""Привести сумму к базовой валюте модели. ``None`` — курса нет.
|
||||
|
||||
Отсутствующий курс не роняет прогноз: сумма не попадает в расчёт,
|
||||
но в `warnings` появляется понятное сообщение — что именно не учтено.
|
||||
"""
|
||||
base = self.model.base_currency
|
||||
source = (currency or base).upper()
|
||||
if source == base.upper():
|
||||
return amount
|
||||
try:
|
||||
return self._converter.convert(amount, source, base)
|
||||
except CurrencyError:
|
||||
prefix = f"{subject}: " if subject else ""
|
||||
self.warnings.append(
|
||||
f"{prefix}нет курса {source} → {base}, сумма {amount} {source} не учтена в прогнозе"
|
||||
)
|
||||
return None
|
||||
|
||||
# -- транзакции ---------------------------------------------------------
|
||||
|
||||
def _group_transactions(self, months: int) -> dict[int, list[tuple[int, Transaction]]]:
|
||||
def _group_transactions(
|
||||
self, months: int, base: str
|
||||
) -> dict[int, list[tuple[int, Decimal]]]:
|
||||
"""Разложить транзакции по счетам и месяцам сетки прогноза (D33).
|
||||
|
||||
Возвращает словарь «индекс счёта → список (месяц сетки, транзакция)».
|
||||
Возвращает словарь «индекс счёта → список (месяц сетки, сумма)».
|
||||
Транзакции из прошлого отбрасываются: они уже учтены в балансе счёта.
|
||||
"""
|
||||
grouped: dict[int, list[tuple[int, Transaction]]] = {}
|
||||
grouped: dict[int, list[tuple[int, Decimal]]] = {}
|
||||
for t in self.model.transactions:
|
||||
account_index = self._account_index(t.account)
|
||||
if account_index is None:
|
||||
@@ -154,7 +226,13 @@ class ForecastService:
|
||||
# За пределами горизонта прогноза.
|
||||
continue
|
||||
|
||||
grouped.setdefault(account_index, []).append((month_index, t))
|
||||
account = self.model.accounts[account_index]
|
||||
currency = t.currency or account.currency or base
|
||||
amount = self._to_base(t.amount, currency, f"транзакция «{t.description or t.category or t.id}»")
|
||||
if amount is None:
|
||||
continue
|
||||
|
||||
grouped.setdefault(account_index, []).append((month_index, amount))
|
||||
return grouped
|
||||
|
||||
def _transaction_month(self, value: str) -> int | None:
|
||||
@@ -184,12 +262,13 @@ class ForecastService:
|
||||
|
||||
def _project_account(
|
||||
self,
|
||||
account: Account,
|
||||
start_balance: Decimal,
|
||||
months: int,
|
||||
liability_balances: list[Decimal],
|
||||
transactions: list[tuple[int, Transaction]],
|
||||
transactions: list[tuple[int, Decimal]],
|
||||
recurring_base: list[tuple[RecurringCashflow, Decimal]],
|
||||
) -> list[dict]:
|
||||
balance = account.balance
|
||||
balance = start_balance
|
||||
monthly = []
|
||||
for m in range(months):
|
||||
income = _ZERO
|
||||
@@ -203,26 +282,27 @@ class ForecastService:
|
||||
# D33: транзакция попадает в месяц СВОЕЙ даты, а не в каждый
|
||||
# месяц подряд. Транзакции из прошлого уже учтены в балансе
|
||||
# счёта — в прогноз они не попадают.
|
||||
for month_index, t in transactions:
|
||||
for month_index, amount in transactions:
|
||||
if month_index != m:
|
||||
continue
|
||||
if t.amount > 0:
|
||||
income += t.amount
|
||||
if amount > 0:
|
||||
income += amount
|
||||
else:
|
||||
expenses += abs(t.amount)
|
||||
expenses += abs(amount)
|
||||
|
||||
for r in self.model.recurring:
|
||||
for r, unit_amount in recurring_base:
|
||||
# D32: платёж раскладывается по календарю — сколько и каких
|
||||
# списаний выпадает в этот месяц, решает сам календарь
|
||||
# (daily/weekly/monthly/yearly), а не делитель периода.
|
||||
share = r.amount_in_month(
|
||||
count = r.occurrences_in_month(
|
||||
month_start.isoformat(),
|
||||
month_end.isoformat(),
|
||||
default_start=self.start_month.isoformat(),
|
||||
)
|
||||
|
||||
if share == 0:
|
||||
if count == 0:
|
||||
continue
|
||||
share = unit_amount * count
|
||||
# D16a: классификация только по знаку; `category` — подпись,
|
||||
# а не правило (то же правило в ScenarioService.apply/what_if).
|
||||
if share > 0:
|
||||
|
||||
@@ -4,6 +4,7 @@ from decimal import Decimal
|
||||
|
||||
from application.forecast import ForecastService
|
||||
from domain import FinancialModel, ForecastScenario
|
||||
from domain.currency import CurrencyConverter
|
||||
|
||||
DEFAULT_SCENARIOS = {
|
||||
"baseline": ForecastScenario(
|
||||
@@ -31,10 +32,17 @@ DEFAULT_SCENARIOS = {
|
||||
|
||||
|
||||
class ScenarioService:
|
||||
def __init__(self, model: FinancialModel, start_month: str | date | None = None):
|
||||
def __init__(
|
||||
self,
|
||||
model: FinancialModel,
|
||||
start_month: str | date | None = None,
|
||||
converter: CurrencyConverter | None = None,
|
||||
):
|
||||
self.model = deepcopy(model)
|
||||
# Месяц старта сетки прогноза (D16b) — тот же для всех сценариев.
|
||||
self.start_month = start_month
|
||||
# Курсы для перевода сумм в базовую валюту (D34).
|
||||
self._converter = converter
|
||||
|
||||
def apply(self, scenario: ForecastScenario, months: int = 12) -> dict:
|
||||
model = deepcopy(self.model)
|
||||
@@ -56,10 +64,11 @@ class ScenarioService:
|
||||
for a in model.assets:
|
||||
a.growth_rate = a.growth_rate * scenario.growth_multiplier
|
||||
|
||||
service = ForecastService(model, start_month=self.start_month)
|
||||
service = ForecastService(model, start_month=self.start_month, converter=self._converter)
|
||||
result = service.summary(months)
|
||||
result["scenario"] = scenario.name
|
||||
result["scenario_description"] = scenario.description
|
||||
result["warnings"] = list(service.warnings)
|
||||
return result
|
||||
|
||||
def compare(self, months: int = 12) -> dict:
|
||||
|
||||
+11
-4
@@ -42,8 +42,8 @@ class RecurringCashflow(BaseModel):
|
||||
raise ValueError("сумма не может быть нулевой")
|
||||
return v
|
||||
|
||||
def amount_in_month(self, month_start: str, month_end: str, default_start: str = "") -> Decimal:
|
||||
"""Сумма списаний за календарный месяц ``[month_start, month_end]`` (D32).
|
||||
def occurrences_in_month(self, month_start: str, month_end: str, default_start: str = "") -> int:
|
||||
"""Сколько списаний платежа выпадает в календарный месяц (D32).
|
||||
|
||||
`month_start`/`month_end` — ISO-даты (начало и конец месяца сетки
|
||||
прогноза). Считается календарно: daily — по числу дней месяца,
|
||||
@@ -57,7 +57,7 @@ class RecurringCashflow(BaseModel):
|
||||
start = parse_date(month_start)
|
||||
end = parse_date(month_end)
|
||||
if start is None or end is None or end < start:
|
||||
return Decimal("0")
|
||||
return 0
|
||||
|
||||
days = occurrence_dates(
|
||||
start_date=self.start_date or default_start,
|
||||
@@ -66,4 +66,11 @@ class RecurringCashflow(BaseModel):
|
||||
window_start=start,
|
||||
window_end=end,
|
||||
)
|
||||
return self.amount * len(days)
|
||||
return len(days)
|
||||
|
||||
def amount_in_month(self, month_start: str, month_end: str, default_start: str = "") -> Decimal:
|
||||
"""Сумма списаний за календарный месяц ``[month_start, month_end]`` (D32).
|
||||
|
||||
`amount` — сумма ОДНОГО списания.
|
||||
"""
|
||||
return self.amount * self.occurrences_in_month(month_start, month_end, default_start)
|
||||
@@ -11,6 +11,7 @@ from infrastructure.cli.services import (
|
||||
fail_validation,
|
||||
fmt_amount,
|
||||
load_model,
|
||||
print_warnings,
|
||||
resolve_currency,
|
||||
)
|
||||
from infrastructure.i18n import t
|
||||
@@ -41,6 +42,7 @@ def compare(
|
||||
table.add_column(t("cmd.forecast.col.expenses"), justify="right")
|
||||
|
||||
for name, r in results.items():
|
||||
print_warnings(r.get("warnings", []))
|
||||
b = convert_value(converter, r["total_balance"], base_curr, target_curr)
|
||||
i = convert_value(converter, r["total_income"], base_curr, target_curr)
|
||||
e = convert_value(converter, r["total_expenses"], base_curr, target_curr)
|
||||
|
||||
@@ -16,6 +16,7 @@ from infrastructure.cli.commands.config._app import app
|
||||
# Порядок импортов задаёт порядок регистрации команд, а значит и порядок
|
||||
# их показа в `cf config --help` — он должен совпадать с прежним монолитом.
|
||||
from infrastructure.cli.commands.config import base_currency # noqa: F401
|
||||
from infrastructure.cli.commands.config import display_currency # noqa: F401
|
||||
from infrastructure.cli.commands.config import rates # noqa: F401
|
||||
from infrastructure.cli.commands.config import accounts # noqa: F401
|
||||
from infrastructure.cli.commands.config import transactions # noqa: F401
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""`cf config display-currency` — валюта вывода по умолчанию."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def display_currency(
|
||||
currency: str = typer.Argument(None, help=t("cmd.config.display_currency.arg")),
|
||||
) -> None:
|
||||
"""Показать или установить валюту вывода по умолчанию"""
|
||||
model = load_model()
|
||||
if currency:
|
||||
model.display_currency = currency.upper()
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.display_currency.ok", currency=model.display_currency))
|
||||
else:
|
||||
console.print(
|
||||
t("cmd.config.display_currency.show", currency=f"[bold]{model.output_currency}[/bold]")
|
||||
)
|
||||
@@ -9,6 +9,7 @@ from infrastructure.cli.services import (
|
||||
convert_value,
|
||||
fmt_amount,
|
||||
load_model,
|
||||
print_warnings,
|
||||
resolve_currency,
|
||||
)
|
||||
from infrastructure.i18n import t
|
||||
@@ -26,6 +27,9 @@ def forecast(
|
||||
forecast_service, _, _, converter = build_services(model)
|
||||
base_curr = model.base_currency
|
||||
results = forecast_service.forecast_cashflow(months)
|
||||
# Предупреждения расчёта (нет курса, счёт не найден) — пользователь должен
|
||||
# видеть, что в прогноз не попало (D34).
|
||||
print_warnings(forecast_service.warnings)
|
||||
# Сводка считается по тому же набору строк, который печатается таблицей —
|
||||
# «Итог» совпадает с последней строкой (D14).
|
||||
summary = forecast_service.summary(months, results=results)
|
||||
|
||||
@@ -15,6 +15,8 @@ def info() -> None:
|
||||
|
||||
console.print(f"[bold]{t('cmd.info.metadata')}[/bold]")
|
||||
console.print(f" {t('cmd.info.base_currency', currency=model.base_currency, symbol=symbol)}")
|
||||
output_symbol = converter.get_symbol(model.output_currency)
|
||||
console.print(f" {t('cmd.info.display_currency', currency=model.output_currency, symbol=output_symbol)}")
|
||||
console.print(f" {t('cmd.info.accounts', count=len(model.accounts))}")
|
||||
console.print(f" {t('cmd.info.transactions', count=len(model.transactions))}")
|
||||
console.print(f" {t('cmd.info.recurring', count=len(model.recurring))}")
|
||||
@@ -28,7 +30,8 @@ def info() -> None:
|
||||
tbl.add_column(t("table.accounts.col.currency"))
|
||||
tbl.add_column(t("table.accounts.col.balance"), justify="right")
|
||||
for a in model.accounts:
|
||||
tbl.add_row(a.name, a.currency, CurrencyConverter.format_money(a.balance, a.currency))
|
||||
currency = a.currency or model.base_currency
|
||||
tbl.add_row(a.name, currency, CurrencyConverter.format_money(a.balance, currency))
|
||||
console.print(tbl)
|
||||
|
||||
if model.transactions:
|
||||
@@ -38,7 +41,8 @@ def info() -> None:
|
||||
tbl.add_column(t("table.transactions.col.amount"), justify="right")
|
||||
tbl.add_column(t("table.transactions.col.description"))
|
||||
for tx in model.transactions[:10]:
|
||||
amount_str = CurrencyConverter.format_money(tx.amount, model.base_currency)
|
||||
currency = tx.currency or _account_currency(model, tx.account) or model.base_currency
|
||||
amount_str = CurrencyConverter.format_money(tx.amount, currency)
|
||||
tbl.add_row(tx.date, tx.category, amount_str, tx.description)
|
||||
if len(model.transactions) > 10:
|
||||
console.print(tbl)
|
||||
@@ -52,7 +56,8 @@ def info() -> None:
|
||||
tbl.add_column(t("table.recurring.col.amount"), justify="right")
|
||||
tbl.add_column(t("table.recurring.col.category"))
|
||||
for r in model.recurring:
|
||||
amount_str = CurrencyConverter.format_money(r.amount, model.base_currency)
|
||||
currency = r.currency or _account_currency(model, r.account) or model.base_currency
|
||||
amount_str = CurrencyConverter.format_money(r.amount, currency)
|
||||
tbl.add_row(r.frequency, amount_str, r.category)
|
||||
console.print(tbl)
|
||||
|
||||
@@ -62,7 +67,8 @@ def info() -> None:
|
||||
tbl.add_column(t("table.assets.col.value"), justify="right")
|
||||
tbl.add_column(t("table.assets.col.growth"), justify="right")
|
||||
for a in model.assets:
|
||||
value_str = CurrencyConverter.format_money(a.value, model.base_currency)
|
||||
currency = a.currency or model.base_currency
|
||||
value_str = CurrencyConverter.format_money(a.value, currency)
|
||||
tbl.add_row(a.name, value_str, f"{a.growth_rate:.1f}%")
|
||||
console.print(tbl)
|
||||
|
||||
@@ -73,7 +79,19 @@ def info() -> None:
|
||||
tbl.add_column(t("table.liabilities.col.rate"), justify="right")
|
||||
tbl.add_column(t("table.liabilities.col.payment"), justify="right")
|
||||
for li in model.liabilities:
|
||||
balance_str = CurrencyConverter.format_money(li.balance, model.base_currency)
|
||||
payment_str = CurrencyConverter.format_money(li.payment, model.base_currency)
|
||||
currency = li.currency or model.base_currency
|
||||
balance_str = CurrencyConverter.format_money(li.balance, currency)
|
||||
payment_str = CurrencyConverter.format_money(li.payment, currency)
|
||||
tbl.add_row(li.name, balance_str, f"{li.interest:.1f}%", payment_str)
|
||||
console.print(tbl)
|
||||
|
||||
|
||||
def _account_currency(model, reference: str) -> str:
|
||||
"""Валюта счёта по ссылке (UUID или имя). Пусто — счёт не найден."""
|
||||
value = (reference or "").strip()
|
||||
if not value:
|
||||
return ""
|
||||
for account in model.accounts:
|
||||
if value == str(account.id) or value.casefold() == account.name.strip().casefold():
|
||||
return account.currency or model.base_currency
|
||||
return ""
|
||||
@@ -11,6 +11,7 @@ from infrastructure.cli.services import (
|
||||
fail_validation,
|
||||
fmt_amount,
|
||||
load_model,
|
||||
print_warnings,
|
||||
resolve_currency,
|
||||
)
|
||||
from infrastructure.i18n import t
|
||||
@@ -45,6 +46,7 @@ def scenario(
|
||||
balance = convert_value(converter, result["total_balance"], base_curr, target_curr)
|
||||
income = convert_value(converter, result["total_income"], base_curr, target_curr)
|
||||
expenses = convert_value(converter, result["total_expenses"], base_curr, target_curr)
|
||||
print_warnings(result.get("warnings", []))
|
||||
console.print(f"[bold]{t('cmd.scenario.label')}:[/bold] {result['scenario']}")
|
||||
console.print(f"[dim]{result['scenario_description']}[/dim]")
|
||||
console.print(f"{t('cmd.scenario.label.balance')}: {fmt_amount(balance, target_curr, symbol)}")
|
||||
|
||||
@@ -63,14 +63,25 @@ def build_services(
|
||||
) -> tuple[ForecastService, ScenarioService, AssistantService, CurrencyConverter]:
|
||||
"""Composition root: собрать граф сервисов с зависимостями."""
|
||||
converter = CurrencyConverter(model.exchange_rates)
|
||||
forecast_service = ForecastService(model)
|
||||
scenario_service = ScenarioService(model)
|
||||
forecast_service = ForecastService(model, converter=converter)
|
||||
scenario_service = ScenarioService(model, converter=converter)
|
||||
assistant_service = AssistantService(model, forecast_service=forecast_service, converter=converter)
|
||||
return forecast_service, scenario_service, assistant_service, converter
|
||||
|
||||
|
||||
def print_warnings(warnings: list[str]) -> None:
|
||||
"""Напечатать предупреждения расчёта (нет курса, счёт не найден)."""
|
||||
for warning in warnings:
|
||||
console.print(f"[yellow]{warning}[/yellow]")
|
||||
|
||||
|
||||
def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str, str]:
|
||||
target = currency or model.base_currency
|
||||
"""Валюта вывода и её символ.
|
||||
|
||||
По умолчанию — валюта вывода модели (`display_currency`, а она, в свою
|
||||
очередь, наследует базовую валюту), а не всегда базовая (D34).
|
||||
"""
|
||||
target = (currency or model.output_currency).upper()
|
||||
converter = CurrencyConverter(model.exchange_rates)
|
||||
symbol = converter.get_symbol(target)
|
||||
return target, symbol
|
||||
|
||||
@@ -57,6 +57,7 @@ MESSAGES: dict[str, str] = {
|
||||
"cmd.info.help": "Сводка всей финансовой модели",
|
||||
"cmd.info.metadata": "Метаданные",
|
||||
"cmd.info.base_currency": "Базовая валюта: {currency} ({symbol})",
|
||||
"cmd.info.display_currency": "Валюта вывода: {currency} ({symbol})",
|
||||
"cmd.info.accounts": "Счетов: {count}",
|
||||
"cmd.info.transactions": "Транзакций: {count}",
|
||||
"cmd.info.recurring": "Регулярных платежей: {count}",
|
||||
@@ -105,6 +106,10 @@ MESSAGES: dict[str, str] = {
|
||||
"cmd.config.base_currency.arg": "Код валюты (RUB, USD, EUR...)",
|
||||
"cmd.config.base_currency.ok": "Базовая валюта установлена: {currency}",
|
||||
"cmd.config.base_currency.show": "Базовая валюта: {currency}",
|
||||
"cmd.config.display_currency.help": "Показать или установить валюту вывода по умолчанию",
|
||||
"cmd.config.display_currency.arg": "Код валюты (RUB, USD, EUR...)",
|
||||
"cmd.config.display_currency.ok": "Валюта вывода установлена: {currency}",
|
||||
"cmd.config.display_currency.show": "Валюта вывода: {currency}",
|
||||
"cmd.config.rate_set.help": "Добавить или обновить курс валюты",
|
||||
"cmd.config.rate_set.arg.from": "Из валюты",
|
||||
"cmd.config.rate_set.arg.to": "В валюту",
|
||||
|
||||
@@ -34,6 +34,7 @@ EXPECTED_COMMANDS = {
|
||||
|
||||
EXPECTED_CONFIG_COMMANDS = {
|
||||
"base-currency",
|
||||
"display-currency",
|
||||
"rate-set",
|
||||
"rate-list",
|
||||
"rate-remove",
|
||||
@@ -81,6 +82,7 @@ EXPECTED_PARAMS = {
|
||||
|
||||
EXPECTED_CONFIG_PARAMS = {
|
||||
"base-currency": [("currency", ("currency",), None, False)],
|
||||
"display-currency": [("currency", ("currency",), None, False)],
|
||||
"rate-set": [
|
||||
("from_currency", ("from_currency",), None, True),
|
||||
("to_currency", ("to_currency",), None, True),
|
||||
|
||||
+89
-1
@@ -3,7 +3,7 @@ from decimal import Decimal
|
||||
import pytest
|
||||
|
||||
from application.forecast import ForecastError, ForecastService
|
||||
from domain import Account, FinancialModel, RecurringCashflow, Transaction
|
||||
from domain import Account, Asset, ExchangeRate, FinancialModel, RecurringCashflow, Transaction
|
||||
from domain.recurrence import FREQUENCIES, normalize_frequency
|
||||
|
||||
_MAIN_ACCOUNT = "Основной счёт"
|
||||
@@ -314,6 +314,94 @@ class TestTransactionDates:
|
||||
assert "не найден" in service.warnings[0]
|
||||
|
||||
|
||||
class TestForecastCurrency:
|
||||
"""D34: расчёт ведётся в базовой валюте, суммы переводятся по курсам."""
|
||||
|
||||
_GRID = "2026-01-01"
|
||||
|
||||
@staticmethod
|
||||
def _model(**kwargs) -> FinancialModel:
|
||||
defaults = dict(
|
||||
base_currency="RUB",
|
||||
accounts=[Account(name="Счёт", currency="RUB", balance=Decimal("0"))],
|
||||
exchange_rates=[ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))],
|
||||
)
|
||||
defaults.update(kwargs)
|
||||
return FinancialModel(**defaults)
|
||||
|
||||
def test_account_balance_is_converted_to_base_currency(self):
|
||||
model = self._model(
|
||||
accounts=[Account(name="Доллары", currency="USD", balance=Decimal("1000"))],
|
||||
)
|
||||
service = ForecastService(model, start_month=self._GRID)
|
||||
rows = service.forecast_cashflow(1)
|
||||
assert rows[0]["balance"] == Decimal("80000.00")
|
||||
|
||||
def test_transaction_uses_its_own_currency(self):
|
||||
account = Account(name="Счёт", currency="RUB", balance=Decimal("0"))
|
||||
model = self._model(
|
||||
accounts=[account],
|
||||
transactions=[
|
||||
Transaction(
|
||||
date="2026-01-05",
|
||||
account=str(account.id),
|
||||
category="income",
|
||||
amount=Decimal("10"),
|
||||
currency="USD",
|
||||
)
|
||||
],
|
||||
)
|
||||
rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(1)
|
||||
assert rows[0]["income"] == Decimal("800.00")
|
||||
|
||||
def test_transaction_without_currency_inherits_account_currency(self):
|
||||
account = Account(name="Доллары", currency="USD", balance=Decimal("0"))
|
||||
model = self._model(
|
||||
accounts=[account],
|
||||
transactions=[
|
||||
Transaction(date="2026-01-05", account=str(account.id), category="income", amount=Decimal("10"))
|
||||
],
|
||||
)
|
||||
rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(1)
|
||||
assert rows[0]["income"] == Decimal("800.00")
|
||||
|
||||
def test_asset_value_is_converted_to_base_currency(self):
|
||||
model = self._model(
|
||||
assets=[Asset(name="Акции", value=Decimal("100"), growth_rate=Decimal("8"), currency="USD")],
|
||||
)
|
||||
service = ForecastService(model, start_month=self._GRID)
|
||||
rows = service.forecast_cashflow(1)
|
||||
# 100 USD = 8000 RUB, рост 8% годовых → 8000 × 0.08 / 12 = 53.33.
|
||||
assert rows[0]["income"] == Decimal("53.33")
|
||||
|
||||
def test_missing_rate_produces_warning_and_skips_amount(self):
|
||||
model = self._model(
|
||||
base_currency="EUR",
|
||||
accounts=[Account(name="Доллары", currency="USD", balance=Decimal("1000"))],
|
||||
exchange_rates=[],
|
||||
)
|
||||
service = ForecastService(model, start_month=self._GRID)
|
||||
rows = service.forecast_cashflow(1)
|
||||
assert rows[0]["balance"] == Decimal("0.00")
|
||||
assert service.warnings
|
||||
assert "нет курса USD → EUR" in service.warnings[0]
|
||||
|
||||
def test_recurring_amount_is_converted_to_base_currency(self):
|
||||
model = self._model(
|
||||
recurring=[
|
||||
RecurringCashflow(
|
||||
start_date="2026-01-01",
|
||||
frequency="monthly",
|
||||
amount=Decimal("-100"),
|
||||
category="rent",
|
||||
currency="USD",
|
||||
)
|
||||
],
|
||||
)
|
||||
rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(1)
|
||||
assert rows[0]["expenses"] == Decimal("8000.00")
|
||||
|
||||
|
||||
class TestRecurringSchedule:
|
||||
"""D32: периодичность recurring считается по календарю.
|
||||
|
||||
|
||||
@@ -136,6 +136,7 @@ class TestScenarioCharacterization:
|
||||
"months": 6,
|
||||
"scenario": "what-if",
|
||||
"scenario_description": description,
|
||||
"warnings": [],
|
||||
}
|
||||
|
||||
twelve = ScenarioService(sample_model, start_month=_GRID_START).what_if(
|
||||
@@ -148,6 +149,7 @@ class TestScenarioCharacterization:
|
||||
"months": 12,
|
||||
"scenario": "what-if",
|
||||
"scenario_description": description,
|
||||
"warnings": [],
|
||||
}
|
||||
|
||||
def test_compare_matches_apply(self, sample_model):
|
||||
|
||||
Reference in new issue
Block a user