- domain/*: на всех моделях домена (FinancialModel, Account, Transaction,
RecurringCashflow, Asset, Liability, ForecastScenario, ExchangeRate)
включён model_config = ConfigDict(validate_assignment=True). Раньше
присваивание шло мимо валидаторов: `r.rate = -5` принимался, а
config_cmd.py писал в поле Decimal значение типа float.
- infrastructure/cli/commands/config_cmd.py: rate_set пишет
Decimal(str(rate)) вместо float.
- infrastructure/cli/services.py: хелпер fail_validation() — печатает
понятное сообщение (t("global.validation_error")) и завершает команду
кодом 1 вместо traceback.
- infrastructure/cli/i18n.py: добавлен ключ global.validation_error.
- infrastructure/cli/commands/{whatif,scenario,compare}.py: тот же обработчик
для случая «множитель 0 обнуляет сумму» — иначе D17 вводил бы новый traceback.
- tests/test_model.py: +9 тестов (отклонение отрицательного/нулевого курса,
float в поле Decimal не остаётся float, отклонение по всем валидаторам).
- tests/test_cli.py: +4 теста (ненулевой код без traceback, модель не
сохраняется, курс сохраняется строкой-Decimal, валидный курс проходит).
Было → стало:
cf config rate-set USD RUB -- -5 принимался, «OK Курс USD → RUB = -5.0»,
курс сохранялся float (-5.0) + warning
→ «Ошибка валидации данных: rate: Value error,
rate must be positive», код 1, без traceback
cf whatif --income 0 работал (суммы обнулялись молча)
→ «Ошибка валидации данных: amount: Value error,
amount must be non-zero», код 1
47 lines
2.2 KiB
Python
47 lines
2.2 KiB
Python
"""cf whatif — what-if анализ с произвольными множителями."""
|
|
|
|
import typer
|
|
from pydantic import ValidationError
|
|
|
|
from infrastructure.cli.i18n import t
|
|
from infrastructure.cli.services import (
|
|
build_services,
|
|
console,
|
|
convert_value,
|
|
fail_validation,
|
|
fmt_amount,
|
|
load_model,
|
|
resolve_currency,
|
|
)
|
|
|
|
CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency"))
|
|
|
|
|
|
def whatif(
|
|
income: float = typer.Option(1.0, "--income", "-i", help=t("cmd.whatif.opt.income")),
|
|
expense: float = typer.Option(1.0, "--expense", "-e", help=t("cmd.whatif.opt.expense")),
|
|
growth: float = typer.Option(1.0, "--growth", "-g", help=t("cmd.whatif.opt.growth")),
|
|
months: int = typer.Option(12, "--months", "-m", help=t("cmd.whatif.opt.months")),
|
|
currency: str | None = CURRENCY_OPTION,
|
|
) -> None:
|
|
"""What-if анализ с произвольными множителями"""
|
|
model = load_model()
|
|
target_curr, symbol = resolve_currency(model, currency)
|
|
_, scenario_service, _, converter = build_services(model)
|
|
base_curr = model.base_currency
|
|
try:
|
|
result = scenario_service.what_if(income, expense, growth, months)
|
|
except ValidationError as e:
|
|
# Множитель 0 обнуляет суммы транзакций — модель это отклоняет
|
|
# (валидация при присваивании, D17). Показываем сообщение, а не traceback.
|
|
fail_validation(e)
|
|
|
|
balance = convert_value(converter, result["total_balance"], base_curr, target_curr)
|
|
income_v = convert_value(converter, result["total_income"], base_curr, target_curr)
|
|
expenses = convert_value(converter, result["total_expenses"], base_curr, target_curr)
|
|
console.print(f"[bold]{t('cmd.whatif.title')}[/bold]")
|
|
console.print(t("cmd.whatif.params", income=income, expense=expense, growth=growth))
|
|
console.print(f"{t('cmd.scenario.label.balance')}: {fmt_amount(balance, target_curr, symbol)}")
|
|
console.print(f"{t('cmd.scenario.label.income')}: {fmt_amount(income_v, target_curr, symbol)}")
|
|
console.print(f"{t('cmd.scenario.label.expenses')}: {fmt_amount(expenses, target_curr, symbol)}")
|