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
@@ -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
|
||||
|
||||
Reference in new issue
Block a user