D17: validate_assignment=True — присваивание проверяется, курс пишется Decimal
- 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
This commit is contained in:
1 parent
43ab5685ec
commit
c702818d43
16 files changed
+229
-22
No files matched your search
@@ -1,6 +1,7 @@
|
||||
"""cf compare — сравнить все сценарии."""
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
@@ -8,6 +9,7 @@ from infrastructure.cli.services import (
|
||||
build_services,
|
||||
console,
|
||||
convert_value,
|
||||
fail_validation,
|
||||
fmt_amount,
|
||||
load_model,
|
||||
resolve_currency,
|
||||
@@ -25,7 +27,12 @@ def compare(
|
||||
target_curr, symbol = resolve_currency(model, currency)
|
||||
_, scenario_service, _, converter = build_services(model)
|
||||
base_curr = model.base_currency
|
||||
results = scenario_service.compare(months)
|
||||
try:
|
||||
results = scenario_service.compare(months)
|
||||
except ValidationError as e:
|
||||
# Сценарий может обнулить суммы (множитель 0) — модель это
|
||||
# отклоняет (валидация при присваивании, D17).
|
||||
fail_validation(e)
|
||||
|
||||
table = Table(title=t("cmd.compare.title", currency=target_curr))
|
||||
table.add_column(t("cmd.compare.col.scenario"), style="cyan")
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"""cf config — подкоманды для редактирования модели (базовая валюта, счета, транзакции, ...)."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from domain import (
|
||||
@@ -13,7 +16,7 @@ from domain import (
|
||||
Transaction,
|
||||
)
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
|
||||
app = typer.Typer(name="config", help=t("config.help"))
|
||||
|
||||
@@ -49,19 +52,27 @@ def rate_set(
|
||||
"""Добавить или обновить курс валюты"""
|
||||
model = load_model()
|
||||
fc, tc = from_currency.upper(), to_currency.upper()
|
||||
# Курс пишем Decimal: поле объявлено как Decimal, а float в него класть
|
||||
# нельзя (D17).
|
||||
rate_value = Decimal(str(rate))
|
||||
existing = [r for r in model.exchange_rates if r.from_currency == fc and r.to_currency == tc]
|
||||
if existing:
|
||||
existing[0].rate = rate
|
||||
else:
|
||||
model.exchange_rates.append(
|
||||
ExchangeRate(
|
||||
from_currency=fc,
|
||||
to_currency=tc,
|
||||
rate=rate,
|
||||
try:
|
||||
if existing:
|
||||
existing[0].rate = rate_value
|
||||
else:
|
||||
model.exchange_rates.append(
|
||||
ExchangeRate(
|
||||
from_currency=fc,
|
||||
to_currency=tc,
|
||||
rate=rate_value,
|
||||
)
|
||||
)
|
||||
)
|
||||
except ValidationError as e:
|
||||
# Отрицательный или нулевой курс отклоняет валидатор модели —
|
||||
# показываем понятное сообщение вместо traceback (D17).
|
||||
fail_validation(e)
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_set.ok', fc=fc, tc=tc, rate=rate)}")
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_set.ok', fc=fc, tc=tc, rate=rate_value)}")
|
||||
|
||||
|
||||
@app.command(name="rate-list")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""cf scenario — применить именованный сценарий (baseline/optimistic/pessimistic)."""
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
|
||||
from application.scenarios import DEFAULT_SCENARIOS
|
||||
from infrastructure.cli.i18n import t
|
||||
@@ -8,6 +9,7 @@ from infrastructure.cli.services import (
|
||||
build_services,
|
||||
console,
|
||||
convert_value,
|
||||
fail_validation,
|
||||
fmt_amount,
|
||||
load_model,
|
||||
resolve_currency,
|
||||
@@ -34,7 +36,12 @@ def scenario(
|
||||
console.print(t("cmd.scenario.err.available", scenarios=", ".join(DEFAULT_SCENARIOS.keys())))
|
||||
raise typer.Exit(1)
|
||||
|
||||
result = scenario_service.apply(scenario_obj, months)
|
||||
try:
|
||||
result = scenario_service.apply(scenario_obj, months)
|
||||
except ValidationError as e:
|
||||
# Сценарий может обнулить суммы (множитель 0) — модель это
|
||||
# отклоняет (валидация при присваивании, D17).
|
||||
fail_validation(e)
|
||||
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)
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""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,
|
||||
@@ -27,7 +29,12 @@ def whatif(
|
||||
target_curr, symbol = resolve_currency(model, currency)
|
||||
_, scenario_service, _, converter = build_services(model)
|
||||
base_curr = model.base_currency
|
||||
result = scenario_service.what_if(income, expense, growth, months)
|
||||
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)
|
||||
|
||||
@@ -253,6 +253,7 @@ _r("cmd.config.liability_remove.err", "Обязательство '{id}' не н
|
||||
# ── global ─────────────────────────────────────────────────────
|
||||
|
||||
_r("global.ok", "OK")
|
||||
_r("global.validation_error", "Ошибка валидации данных: {error}")
|
||||
|
||||
# ── prompts ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -3,13 +3,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import NoReturn
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.console import Console
|
||||
|
||||
from application.forecast import ForecastService
|
||||
from application.scenarios import ScenarioService
|
||||
from domain import CurrencyConverter, FinancialModel
|
||||
from infrastructure.ai.assistant import AssistantService
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.paths import MODEL_PATH
|
||||
from infrastructure.repositories import JsonFileRepository
|
||||
|
||||
@@ -18,6 +22,21 @@ console = Console()
|
||||
_json_repo = JsonFileRepository()
|
||||
|
||||
|
||||
def fail_validation(exc: ValidationError) -> NoReturn:
|
||||
"""Показать ошибку валидации понятным сообщением и завершить команду.
|
||||
|
||||
Доменные модели валидируют и при присваивании (D17), поэтому «нельзя
|
||||
положить отрицательный курс» — ожидаемая ошибка ввода, а не сбой
|
||||
программы: пользователь получает понятное сообщение и код возврата 1
|
||||
вместо traceback.
|
||||
"""
|
||||
details = "; ".join(
|
||||
f"{'.'.join(str(part) for part in error['loc']) or 'значение'}: {error['msg']}" for error in exc.errors()
|
||||
)
|
||||
console.print(f"[red]{t('global.validation_error', error=details)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
def load_model() -> FinancialModel:
|
||||
if MODEL_PATH.exists():
|
||||
return _json_repo.load(MODEL_PATH)
|
||||
|
||||
Reference in new issue
Block a user