style: привести код к ruff format (line-length 120)
Обнаружено на шаге 0: `ruff format --check .` НЕ был чистым в baseline (24 файла расходились с форматом ruff). `ruff check .` был чистым. Изменение только косметическое (переносы, пустая строка после docstring модуля, склейка вызовов в пределах line-length=120 из [tool.ruff]); поведение не меняется — pytest 81/81 зелёные, `ruff check .` — без ошибок. Нужно, чтобы `ruff format --check .` стал рабочим гейтом (D13 CI).
This commit is contained in:
1 parent
9b53b25a91
commit
af01efc41a
24 files changed
+219
-160
No files matched your search
@@ -1,4 +1,5 @@
|
||||
"""Entry point приложения cf. Регистрирует все команды."""
|
||||
|
||||
import sys
|
||||
|
||||
import typer
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf analyze — AI-анализ финансовой модели (заглушка)."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf compare — сравнить все сценарии."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf config — подкоманды для редактирования модели (базовая валюта, счета, транзакции, ...)."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
@@ -52,11 +53,13 @@ def rate_set(
|
||||
if existing:
|
||||
existing[0].rate = rate
|
||||
else:
|
||||
model.exchange_rates.append(ExchangeRate(
|
||||
from_currency=fc,
|
||||
to_currency=tc,
|
||||
rate=rate,
|
||||
))
|
||||
model.exchange_rates.append(
|
||||
ExchangeRate(
|
||||
from_currency=fc,
|
||||
to_currency=tc,
|
||||
rate=rate,
|
||||
)
|
||||
)
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_set.ok', fc=fc, tc=tc, rate=rate)}")
|
||||
|
||||
@@ -86,10 +89,7 @@ def rate_remove(
|
||||
model = load_model()
|
||||
fc, tc = from_currency.upper(), to_currency.upper()
|
||||
initial = len(model.exchange_rates)
|
||||
model.exchange_rates = [
|
||||
r for r in model.exchange_rates
|
||||
if not (r.from_currency == fc and r.to_currency == tc)
|
||||
]
|
||||
model.exchange_rates = [r for r in model.exchange_rates if not (r.from_currency == fc and r.to_currency == tc)]
|
||||
if len(model.exchange_rates) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_remove.ok', fc=fc, tc=tc)}")
|
||||
@@ -143,10 +143,7 @@ def account_remove(
|
||||
"""Удалить счёт по ID или названию"""
|
||||
model = load_model()
|
||||
initial = len(model.accounts)
|
||||
model.accounts = [
|
||||
a for a in model.accounts
|
||||
if str(a.id) != identifier and a.name != identifier
|
||||
]
|
||||
model.accounts = [a for a in model.accounts if str(a.id) != identifier and a.name != identifier]
|
||||
if len(model.accounts) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.account_remove.ok', id=identifier)}")
|
||||
@@ -204,12 +201,14 @@ def transaction_list() -> None:
|
||||
table.add_column(t("table.transactions.col.description"))
|
||||
for tx in model.transactions:
|
||||
account_name = _account_name(model, tx.account)
|
||||
amount_str = CurrencyConverter.format_money(
|
||||
tx.amount, _account_currency(model, tx.account)
|
||||
)
|
||||
amount_str = CurrencyConverter.format_money(tx.amount, _account_currency(model, tx.account))
|
||||
table.add_row(
|
||||
str(tx.id)[:8], tx.date, account_name, tx.category,
|
||||
amount_str, tx.description,
|
||||
str(tx.id)[:8],
|
||||
tx.date,
|
||||
account_name,
|
||||
tx.category,
|
||||
amount_str,
|
||||
tx.description,
|
||||
)
|
||||
console.print(table)
|
||||
|
||||
@@ -244,8 +243,11 @@ def recurring_add(
|
||||
"""Добавить регулярный платёж"""
|
||||
model = load_model()
|
||||
rc = RecurringCashflow(
|
||||
start_date=start_date or "", end_date=end_date or "",
|
||||
frequency=frequency, amount=amount, category=category,
|
||||
start_date=start_date or "",
|
||||
end_date=end_date or "",
|
||||
frequency=frequency,
|
||||
amount=amount,
|
||||
category=category,
|
||||
)
|
||||
model.recurring.append(rc)
|
||||
save_model(model)
|
||||
@@ -334,10 +336,7 @@ def asset_remove(
|
||||
"""Удалить актив по ID или названию"""
|
||||
model = load_model()
|
||||
initial = len(model.assets)
|
||||
model.assets = [
|
||||
a for a in model.assets
|
||||
if str(a.id) != identifier and a.name != identifier
|
||||
]
|
||||
model.assets = [a for a in model.assets if str(a.id) != identifier and a.name != identifier]
|
||||
if len(model.assets) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.asset_remove.ok', id=identifier)}")
|
||||
@@ -392,10 +391,7 @@ def liability_remove(
|
||||
"""Удалить обязательство по ID или названию"""
|
||||
model = load_model()
|
||||
initial = len(model.liabilities)
|
||||
model.liabilities = [
|
||||
li for li in model.liabilities
|
||||
if str(li.id) != identifier and li.name != identifier
|
||||
]
|
||||
model.liabilities = [li for li in model.liabilities if str(li.id) != identifier and li.name != identifier]
|
||||
if len(model.liabilities) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.liability_remove.ok', id=identifier)}")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf export-xlsx — экспорт модели в Excel."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf forecast — прогноз денежных потоков."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
@@ -37,7 +38,8 @@ def forecast(
|
||||
|
||||
for r in results:
|
||||
table.add_row(
|
||||
r["account"], str(r["month"]),
|
||||
r["account"],
|
||||
str(r["month"]),
|
||||
fmt_amount(convert_value(converter, r["balance"], base_curr, target_curr), target_curr, symbol),
|
||||
fmt_amount(convert_value(converter, r["income"], base_curr, target_curr), target_curr, symbol),
|
||||
fmt_amount(convert_value(converter, r["expenses"], base_curr, target_curr), target_curr, symbol),
|
||||
@@ -47,7 +49,11 @@ def forecast(
|
||||
cb = convert_value(converter, summary["total_balance"], base_curr, target_curr)
|
||||
ci = convert_value(converter, summary["total_income"], base_curr, target_curr)
|
||||
ce = convert_value(converter, summary["total_expenses"], base_curr, target_curr)
|
||||
console.print(t("cmd.forecast.total",
|
||||
balance=fmt_amount(cb, target_curr, symbol),
|
||||
income=fmt_amount(ci, target_curr, symbol),
|
||||
expenses=fmt_amount(ce, target_curr, symbol)))
|
||||
console.print(
|
||||
t(
|
||||
"cmd.forecast.total",
|
||||
balance=fmt_amount(cb, target_curr, symbol),
|
||||
income=fmt_amount(ci, target_curr, symbol),
|
||||
expenses=fmt_amount(ce, target_curr, symbol),
|
||||
)
|
||||
)
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf import-xlsx — импорт данных из Excel."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
@@ -15,12 +16,16 @@ def import_xlsx(
|
||||
try:
|
||||
model = _repo.load(path)
|
||||
save_model(model)
|
||||
console.print(t("cmd.import.ok",
|
||||
accounts=len(model.accounts),
|
||||
transactions=len(model.transactions),
|
||||
recurring=len(model.recurring),
|
||||
assets=len(model.assets),
|
||||
liabilities=len(model.liabilities)))
|
||||
console.print(
|
||||
t(
|
||||
"cmd.import.ok",
|
||||
accounts=len(model.accounts),
|
||||
transactions=len(model.transactions),
|
||||
recurring=len(model.recurring),
|
||||
assets=len(model.assets),
|
||||
liabilities=len(model.liabilities),
|
||||
)
|
||||
)
|
||||
console.print(t("cmd.import.base_currency", currency=model.base_currency))
|
||||
except ExcelRepositoryError as e:
|
||||
console.print(f"[red]{t('cmd.import.err', error=str(e))}[/red]")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf info — сводка всей финансовой модели."""
|
||||
|
||||
from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf scenario — применить именованный сценарий (baseline/optimistic/pessimistic)."""
|
||||
|
||||
import typer
|
||||
|
||||
from application.scenarios import DEFAULT_SCENARIOS
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf whatif — what-if анализ с произвольными множителями."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
|
||||
+62
-51
@@ -68,9 +68,11 @@ _r("cmd.compare.col.scenario", "Сценарий")
|
||||
|
||||
_r("cmd.import.help", "Импорт данных из Excel")
|
||||
_r("cmd.import.arg.path", "Путь к .xlsx файлу")
|
||||
_r("cmd.import.ok",
|
||||
"Импортировано: {accounts} счетов, {transactions} транзакций, "
|
||||
"{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств")
|
||||
_r(
|
||||
"cmd.import.ok",
|
||||
"Импортировано: {accounts} счетов, {transactions} транзакций, "
|
||||
"{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств",
|
||||
)
|
||||
_r("cmd.import.base_currency", "Базовая валюта: {currency}")
|
||||
_r("cmd.import.err", "Ошибка импорта: {error}")
|
||||
|
||||
@@ -254,56 +256,65 @@ _r("global.ok", "OK")
|
||||
|
||||
# ── prompts ───────────────────────────────────────────────────
|
||||
|
||||
_r("prompt.analyze", (
|
||||
"Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n"
|
||||
"\n"
|
||||
"### Модель (JSON):\n"
|
||||
"{model_json}\n"
|
||||
"\n"
|
||||
"### Прогноз на {months} месяцев:\n"
|
||||
"{forecast_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Дай анализ по пунктам:\n"
|
||||
"1. Общее финансовое состояние\n"
|
||||
"2. Тренд денежного потока (рост/падение)\n"
|
||||
"3. Достаточность ликвидности\n"
|
||||
"4. Рекомендации по улучшению"
|
||||
))
|
||||
_r(
|
||||
"prompt.analyze",
|
||||
(
|
||||
"Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n"
|
||||
"\n"
|
||||
"### Модель (JSON):\n"
|
||||
"{model_json}\n"
|
||||
"\n"
|
||||
"### Прогноз на {months} месяцев:\n"
|
||||
"{forecast_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Дай анализ по пунктам:\n"
|
||||
"1. Общее финансовое состояние\n"
|
||||
"2. Тренд денежного потока (рост/падение)\n"
|
||||
"3. Достаточность ликвидности\n"
|
||||
"4. Рекомендации по улучшению"
|
||||
),
|
||||
)
|
||||
|
||||
_r("prompt.advice", (
|
||||
"Ты — финансовый AI-ассистент. Дай персональные рекомендации.\n"
|
||||
"\n"
|
||||
"### Модель:\n"
|
||||
"{model_json}\n"
|
||||
"\n"
|
||||
"### Прогноз:\n"
|
||||
"{forecast_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Вопрос пользователя: {question}\n"
|
||||
"\n"
|
||||
"Ответь как опытный финансовый консультант."
|
||||
))
|
||||
_r(
|
||||
"prompt.advice",
|
||||
(
|
||||
"Ты — финансовый AI-ассистент. Дай персональные рекомендации.\n"
|
||||
"\n"
|
||||
"### Модель:\n"
|
||||
"{model_json}\n"
|
||||
"\n"
|
||||
"### Прогноз:\n"
|
||||
"{forecast_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Вопрос пользователя: {question}\n"
|
||||
"\n"
|
||||
"Ответь как опытный финансовый консультант."
|
||||
),
|
||||
)
|
||||
|
||||
_r("prompt.scenario_comparison", (
|
||||
"Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n"
|
||||
"\n"
|
||||
"### Результаты сценариев:\n"
|
||||
"{scenarios_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Дай рекомендацию: какой сценарий наиболее вероятен и почему."
|
||||
))
|
||||
_r(
|
||||
"prompt.scenario_comparison",
|
||||
(
|
||||
"Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n"
|
||||
"\n"
|
||||
"### Результаты сценариев:\n"
|
||||
"{scenarios_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Дай рекомендацию: какой сценарий наиболее вероятен и почему."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
_current_lang = "ru"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Пути к данным и экспортам."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
DATA_DIR: Path = Path("data")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Composition root + общие хелперы для CLI-команд."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
@@ -34,9 +35,7 @@ def build_services(
|
||||
converter = CurrencyConverter(model.exchange_rates)
|
||||
forecast_service = ForecastService(model)
|
||||
scenario_service = ScenarioService(model)
|
||||
assistant_service = AssistantService(
|
||||
model, forecast_service=forecast_service, converter=converter
|
||||
)
|
||||
assistant_service = AssistantService(model, forecast_service=forecast_service, converter=converter)
|
||||
return forecast_service, scenario_service, assistant_service, converter
|
||||
|
||||
|
||||
@@ -47,9 +46,7 @@ def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str,
|
||||
return target, symbol
|
||||
|
||||
|
||||
def convert_value(
|
||||
converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str
|
||||
) -> Decimal:
|
||||
def convert_value(converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str) -> Decimal:
|
||||
if to_curr == from_curr:
|
||||
return amount
|
||||
return converter.convert(amount, from_curr, to_curr)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""ExcelRepository — хранит FinancialModel в .xlsx (5 листов + ModelInfo)."""
|
||||
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
@@ -107,8 +108,7 @@ class ExcelRepository(ModelRepository):
|
||||
ws.append(config["fields"])
|
||||
for item in items:
|
||||
row = [
|
||||
str(getattr(item, f)) if isinstance(getattr(item, f), UUID)
|
||||
else getattr(item, f)
|
||||
str(getattr(item, f)) if isinstance(getattr(item, f), UUID) else getattr(item, f)
|
||||
for f in config["fields"]
|
||||
]
|
||||
ws.append(row)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""JsonFileRepository — хранит FinancialModel в .json (включая version)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
Reference in new issue
Block a user