D25: config_cmd.py → пакет commands/config/ по семействам сущностей (19 подкоманд, поверхность без изменений)
This commit is contained in:
1 parent
bd23b03c08
commit
3d4ee910b4
16 files changed
+706
-450
No files matched your search
@@ -12,7 +12,7 @@ except (AttributeError, OSError):
|
||||
from infrastructure.cli.commands import (
|
||||
analyze,
|
||||
compare,
|
||||
config_cmd,
|
||||
config,
|
||||
export_xlsx,
|
||||
forecast,
|
||||
import_xlsx,
|
||||
@@ -39,7 +39,7 @@ app.command(name="analyze")(analyze.analyze)
|
||||
app.command(name="info")(info.info)
|
||||
|
||||
# Под-приложение config
|
||||
app.add_typer(config_cmd.app, name="config")
|
||||
app.add_typer(config.app, name="config")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from infrastructure.cli.commands import (
|
||||
analyze,
|
||||
compare,
|
||||
config_cmd,
|
||||
config,
|
||||
export_xlsx,
|
||||
forecast,
|
||||
import_xlsx,
|
||||
@@ -14,7 +14,7 @@ from infrastructure.cli.commands import (
|
||||
__all__ = [
|
||||
"analyze",
|
||||
"compare",
|
||||
"config_cmd",
|
||||
"config",
|
||||
"export_xlsx",
|
||||
"forecast",
|
||||
"import_xlsx",
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Пакет `cf config` — подкоманды управления моделью.
|
||||
|
||||
В пакете ровно один объект Typer — `app` (см. `_app.py`). Подкоманды
|
||||
регистрируются декораторами `@app.command()` в модулях семейств сущностей
|
||||
(`base_currency`, `rates`, `accounts`, `transactions`, `recurring`, `assets`,
|
||||
`liabilities`); модули импортируются здесь ради побочного эффекта — так
|
||||
регистрация происходит один раз при первом импорте пакета.
|
||||
|
||||
Наружу пакет отдаёт только `app`: его подключает к корневому CLI
|
||||
`infrastructure/cli/app.py` (`app.add_typer(config.app, name="config")`).
|
||||
"""
|
||||
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
|
||||
# isort: off
|
||||
# Порядок импортов задаёт порядок регистрации команд, а значит и порядок
|
||||
# их показа в `cf config --help` — он должен совпадать с прежним монолитом.
|
||||
from infrastructure.cli.commands.config import base_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
|
||||
from infrastructure.cli.commands.config import recurring # noqa: F401
|
||||
from infrastructure.cli.commands.config import assets # noqa: F401
|
||||
from infrastructure.cli.commands.config import liabilities # noqa: F401
|
||||
|
||||
# isort: on
|
||||
|
||||
__all__ = ["app"]
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Единственный объект Typer для всего пакета `config`.
|
||||
|
||||
Подкоманды регистрируются декораторами `@app.command()` в модулях семейств
|
||||
(`base_currency`, `rates`, `accounts`, ...). Модуль `_app.py` — единственное
|
||||
место в пакете, где создаётся `typer.Typer()`: мёртвых Typer-объектов в
|
||||
пакете быть не должно (D3), иначе часть команд не попадёт в CLI.
|
||||
"""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.i18n import t
|
||||
|
||||
app = typer.Typer(name="config", help=t("config.help"))
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Общая «клейкая» часть CLI-пакета `config`.
|
||||
|
||||
Только инфраструктурные помощники: форматирование сообщений и единая
|
||||
реализация удаления элементов модели. Логики конкретных команд здесь нет —
|
||||
она живёт в модулях семейств (`base_currency`, `rates`, `accounts`, ...).
|
||||
"""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.services import console, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
def print_ok(message: str) -> None:
|
||||
"""Сообщение об успехе в едином формате: `[green]OK[/green] <текст>`."""
|
||||
console.print(f"[green]{t('global.ok')}[/green] {message}")
|
||||
|
||||
|
||||
def print_error(message: str) -> None:
|
||||
"""Сообщение об ошибке в едином формате: `[red]<текст>[/red]`."""
|
||||
console.print(f"[red]{message}[/red]")
|
||||
|
||||
|
||||
def print_warning(message: str) -> None:
|
||||
"""Предупреждение в едином формате: `[yellow]<текст>[/yellow]`."""
|
||||
console.print(f"[yellow]{message}[/yellow]")
|
||||
|
||||
|
||||
def remove_items(
|
||||
model,
|
||||
field: str,
|
||||
predicate,
|
||||
*,
|
||||
identifier: str,
|
||||
ok_key: str,
|
||||
err_key: str,
|
||||
) -> None:
|
||||
"""Удалить элементы `model.field`, для которых `predicate` истинно.
|
||||
|
||||
`predicate(item)` — «этот элемент удалить»: элементы, для которых он
|
||||
ложен, остаются. Если ничего не удалено — сообщение об ошибке и
|
||||
`typer.Exit(1)`; иначе модель сохраняется и печатается подтверждение.
|
||||
"""
|
||||
items = getattr(model, field)
|
||||
kept = [item for item in items if not predicate(item)]
|
||||
if len(kept) == len(items):
|
||||
print_error(t(err_key, id=identifier))
|
||||
raise typer.Exit(1)
|
||||
setattr(model, field, kept)
|
||||
save_model(model)
|
||||
print_ok(t(ok_key, id=identifier))
|
||||
@@ -0,0 +1,59 @@
|
||||
"""`cf config account-*` — счета: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import Account, CurrencyConverter
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def account_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.account_add.opt.name")),
|
||||
balance: float = typer.Option(0.0, "--balance", "-b", help=t("cmd.config.account_add.opt.balance")),
|
||||
currency: str = typer.Option("", "--currency", "-c", help=t("cmd.config.account_add.opt.currency")),
|
||||
) -> None:
|
||||
"""Добавить счёт"""
|
||||
model = load_model()
|
||||
curr = currency.upper() if currency else model.base_currency
|
||||
account = Account(name=name, balance=balance, currency=curr)
|
||||
model.accounts.append(account)
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.account_add.ok", name=name, balance=balance, currency=curr))
|
||||
|
||||
|
||||
@app.command(name="account-list")
|
||||
def account_list() -> None:
|
||||
"""Список счетов"""
|
||||
model = load_model()
|
||||
if not model.accounts:
|
||||
print_warning(t("cmd.config.account_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.accounts_config.title"))
|
||||
table.add_column(t("table.accounts_config.col.id"), style="dim")
|
||||
table.add_column(t("table.accounts_config.col.name"), style="cyan")
|
||||
table.add_column(t("table.accounts_config.col.currency"))
|
||||
table.add_column(t("table.accounts_config.col.balance"), justify="right")
|
||||
for a in model.accounts:
|
||||
balance_str = CurrencyConverter.format_money(a.balance, a.currency)
|
||||
table.add_row(str(a.id)[:8], a.name, a.currency, balance_str)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="account-remove")
|
||||
def account_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.account_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить счёт по ID или названию"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"accounts",
|
||||
lambda a: str(a.id) == identifier or a.name == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.account_remove.ok",
|
||||
err_key="cmd.config.account_remove.err",
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""`cf config asset-*` — активы: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import Asset, CurrencyConverter
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def asset_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.asset_add.opt.name")),
|
||||
value: float = typer.Option(0.0, "--value", "-v", help=t("cmd.config.asset_add.opt.value")),
|
||||
growth_rate: float = typer.Option(0.0, "--growth", "-g", help=t("cmd.config.asset_add.opt.growth")),
|
||||
) -> None:
|
||||
"""Добавить актив"""
|
||||
model = load_model()
|
||||
asset = Asset(name=name, value=value, growth_rate=growth_rate)
|
||||
model.assets.append(asset)
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.asset_add.ok", name=name, value=value))
|
||||
|
||||
|
||||
@app.command(name="asset-list")
|
||||
def asset_list() -> None:
|
||||
"""Список активов"""
|
||||
model = load_model()
|
||||
if not model.assets:
|
||||
print_warning(t("cmd.config.asset_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.assets.title"))
|
||||
table.add_column(t("table.assets.col.id"), style="dim")
|
||||
table.add_column(t("table.assets.col.name"), style="cyan")
|
||||
table.add_column(t("table.assets.col.value"), justify="right")
|
||||
table.add_column(t("table.assets.col.growth"), justify="right")
|
||||
for a in model.assets:
|
||||
value_str = CurrencyConverter.format_money(a.value, model.base_currency)
|
||||
table.add_row(str(a.id)[:8], a.name, value_str, f"{a.growth_rate:.1f}%")
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="asset-remove")
|
||||
def asset_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.asset_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить актив по ID или названию"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"assets",
|
||||
lambda a: str(a.id) == identifier or a.name == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.asset_remove.ok",
|
||||
err_key="cmd.config.asset_remove.err",
|
||||
)
|
||||
@@ -0,0 +1,22 @@
|
||||
"""`cf config base-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 base_currency(
|
||||
currency: str = typer.Argument(None, help=t("cmd.config.base_currency.arg")),
|
||||
) -> None:
|
||||
"""Показать или установить базовую валюту модели"""
|
||||
model = load_model()
|
||||
if currency:
|
||||
model.base_currency = currency.upper()
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.base_currency.ok", currency=model.base_currency))
|
||||
else:
|
||||
console.print(t("cmd.config.base_currency.show", currency=f"[bold]{model.base_currency}[/bold]"))
|
||||
@@ -0,0 +1,62 @@
|
||||
"""`cf config liability-*` — обязательства: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter, Liability
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def liability_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.liability_add.opt.name")),
|
||||
balance: float = typer.Option(0.0, "--balance", "-b", help=t("cmd.config.liability_add.opt.balance")),
|
||||
interest: float = typer.Option(0.0, "--interest", "-i", help=t("cmd.config.liability_add.opt.interest")),
|
||||
payment: float = typer.Option(0.0, "--payment", "-p", help=t("cmd.config.liability_add.opt.payment")),
|
||||
) -> None:
|
||||
"""Добавить обязательство"""
|
||||
model = load_model()
|
||||
liability = Liability(name=name, balance=balance, interest=interest, payment=payment)
|
||||
model.liabilities.append(liability)
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.liability_add.ok", name=name, balance=balance))
|
||||
|
||||
|
||||
@app.command(name="liability-list")
|
||||
def liability_list() -> None:
|
||||
"""Список обязательств"""
|
||||
model = load_model()
|
||||
if not model.liabilities:
|
||||
print_warning(t("cmd.config.liability_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.liabilities.title"))
|
||||
table.add_column(t("table.liabilities.col.id"), style="dim")
|
||||
table.add_column(t("table.liabilities.col.name"), style="cyan")
|
||||
table.add_column(t("table.liabilities.col.balance"), justify="right")
|
||||
table.add_column(t("table.liabilities.col.rate"), justify="right")
|
||||
table.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)
|
||||
row = (str(li.id)[:8], li.name, balance_str, f"{li.interest:.1f}%", payment_str)
|
||||
table.add_row(*row)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="liability-remove")
|
||||
def liability_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.liability_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить обязательство по ID или названию"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"liabilities",
|
||||
lambda li: str(li.id) == identifier or li.name == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.liability_remove.ok",
|
||||
err_key="cmd.config.liability_remove.err",
|
||||
)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""`cf config rate-*` — курсы валют: добавление, список, удаление."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from domain import ExchangeRate
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_error, print_ok, print_warning
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def rate_set(
|
||||
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
|
||||
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
|
||||
rate: float = typer.Argument(..., help=t("cmd.config.rate_set.arg.rate")),
|
||||
) -> None:
|
||||
"""Добавить или обновить курс валюты"""
|
||||
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]
|
||||
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)
|
||||
print_ok(t("cmd.config.rate_set.ok", fc=fc, tc=tc, rate=rate_value))
|
||||
|
||||
|
||||
@app.command(name="rate-list")
|
||||
def rate_list() -> None:
|
||||
"""Список курсов валют"""
|
||||
model = load_model()
|
||||
if not model.exchange_rates:
|
||||
print_warning(t("cmd.config.rate_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.rates.title"))
|
||||
table.add_column(t("table.rates.col.from"), style="cyan")
|
||||
table.add_column(t("table.rates.col.to"), style="cyan")
|
||||
table.add_column(t("table.rates.col.rate"), justify="right")
|
||||
for r in model.exchange_rates:
|
||||
table.add_row(r.from_currency, r.to_currency, str(r.rate))
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="rate-remove")
|
||||
def rate_remove(
|
||||
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
|
||||
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
|
||||
) -> None:
|
||||
"""Удалить курс валюты"""
|
||||
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)]
|
||||
if len(model.exchange_rates) < initial:
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.rate_remove.ok", fc=fc, tc=tc))
|
||||
else:
|
||||
print_error(t("cmd.config.rate_remove.err", fc=fc, tc=tc))
|
||||
raise typer.Exit(1)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""`cf config recurring-*` — регулярные платежи: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter, RecurringCashflow
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def recurring_add(
|
||||
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.recurring_add.opt.amount")),
|
||||
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.recurring_add.opt.category")),
|
||||
frequency: str = typer.Option("monthly", "--frequency", "-f", help=t("cmd.config.recurring_add.opt.frequency")),
|
||||
start_date: str = typer.Option("", "--start", "-s", help=t("cmd.config.recurring_add.opt.start")),
|
||||
end_date: str = typer.Option("", "--end", "-e", help=t("cmd.config.recurring_add.opt.end")),
|
||||
) -> None:
|
||||
"""Добавить регулярный платёж"""
|
||||
model = load_model()
|
||||
rc = RecurringCashflow(
|
||||
start_date=start_date or "",
|
||||
end_date=end_date or "",
|
||||
frequency=frequency,
|
||||
amount=amount,
|
||||
category=category,
|
||||
)
|
||||
model.recurring.append(rc)
|
||||
save_model(model)
|
||||
amount_str = CurrencyConverter.format_money(abs(amount), model.base_currency)
|
||||
print_ok(t("cmd.config.recurring_add.ok", amount_str=amount_str, frequency=frequency))
|
||||
|
||||
|
||||
@app.command(name="recurring-list")
|
||||
def recurring_list() -> None:
|
||||
"""Список регулярных платежей"""
|
||||
model = load_model()
|
||||
if not model.recurring:
|
||||
print_warning(t("cmd.config.recurring_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.recurring.title"))
|
||||
table.add_column(t("table.recurring.col.id"), style="dim")
|
||||
table.add_column(t("table.recurring.col.start"))
|
||||
table.add_column(t("table.recurring.col.end"))
|
||||
table.add_column(t("table.recurring.col.period"))
|
||||
table.add_column(t("table.recurring.col.amount"), justify="right")
|
||||
table.add_column(t("table.recurring.col.category"))
|
||||
for r in model.recurring:
|
||||
amount_str = CurrencyConverter.format_money(r.amount, model.base_currency)
|
||||
row = (str(r.id)[:8], r.start_date, r.end_date, r.frequency, amount_str, r.category)
|
||||
table.add_row(*row)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="recurring-remove")
|
||||
def recurring_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.recurring_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить регулярный платёж по ID"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"recurring",
|
||||
lambda r: str(r.id) == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.recurring_remove.ok",
|
||||
err_key="cmd.config.recurring_remove.err",
|
||||
)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""`cf config transaction-*` — транзакции: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter, Transaction
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_error, print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def transaction_add(
|
||||
account: str = typer.Option(..., "--account", "-a", help=t("cmd.config.transaction_add.opt.account")),
|
||||
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.transaction_add.opt.amount")),
|
||||
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.transaction_add.opt.category")),
|
||||
description: str = typer.Option("", "--description", "-d", help=t("cmd.config.transaction_add.opt.description")),
|
||||
date: str = typer.Option("", "--date", "-D", help=t("cmd.config.transaction_add.opt.date")),
|
||||
) -> None:
|
||||
"""Добавить транзакцию"""
|
||||
model = load_model()
|
||||
account_id = _resolve_account_id(model, account)
|
||||
if not account_id:
|
||||
print_error(t("cmd.config.transaction_add.err", account=account))
|
||||
raise typer.Exit(1)
|
||||
txn = Transaction(
|
||||
date=date or "",
|
||||
account=account_id,
|
||||
category=category,
|
||||
amount=amount,
|
||||
description=description,
|
||||
)
|
||||
model.transactions.append(txn)
|
||||
save_model(model)
|
||||
kind = t("cmd.config.transaction_add.kind.income") if amount >= 0 else t("cmd.config.transaction_add.kind.expense")
|
||||
amount_str = CurrencyConverter.format_money(abs(amount), _account_currency(model, account_id))
|
||||
print_ok(t("cmd.config.transaction_add.ok", kind=kind, amount_str=amount_str, account=account))
|
||||
|
||||
|
||||
@app.command(name="transaction-list")
|
||||
def transaction_list() -> None:
|
||||
"""Список транзакций"""
|
||||
model = load_model()
|
||||
if not model.transactions:
|
||||
print_warning(t("cmd.config.transaction_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.transactions.title"))
|
||||
table.add_column(t("table.accounts_config.col.id"), style="dim")
|
||||
table.add_column(t("table.transactions.col.date"))
|
||||
table.add_column(t("table.accounts_config.col.name"))
|
||||
table.add_column(t("table.transactions.col.category"))
|
||||
table.add_column(t("table.transactions.col.amount"), justify="right")
|
||||
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))
|
||||
table.add_row(
|
||||
str(tx.id)[:8],
|
||||
tx.date,
|
||||
account_name,
|
||||
tx.category,
|
||||
amount_str,
|
||||
tx.description,
|
||||
)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="transaction-remove")
|
||||
def transaction_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.transaction_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить транзакцию по ID"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"transactions",
|
||||
lambda tx: str(tx.id) == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.transaction_remove.ok",
|
||||
err_key="cmd.config.transaction_remove.err",
|
||||
)
|
||||
|
||||
|
||||
# ── helpers ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _resolve_account_id(model, identifier: str) -> str | None:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == identifier or a.name == identifier:
|
||||
return str(a.id)
|
||||
return None
|
||||
|
||||
|
||||
def _account_name(model, account_id: str) -> str:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == account_id:
|
||||
return a.name
|
||||
return account_id[:8]
|
||||
|
||||
|
||||
def _account_currency(model, account_id: str) -> str:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == account_id:
|
||||
return a.currency
|
||||
return model.base_currency
|
||||
@@ -1,435 +0,0 @@
|
||||
"""cf config — подкоманды для редактирования модели (базовая валюта, счета, транзакции, ...)."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from domain import (
|
||||
Account,
|
||||
Asset,
|
||||
CurrencyConverter,
|
||||
ExchangeRate,
|
||||
Liability,
|
||||
RecurringCashflow,
|
||||
Transaction,
|
||||
)
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
app = typer.Typer(name="config", help=t("config.help"))
|
||||
|
||||
|
||||
# ── base-currency ──────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def base_currency(
|
||||
currency: str = typer.Argument(None, help=t("cmd.config.base_currency.arg")),
|
||||
) -> None:
|
||||
"""Показать или установить базовую валюту модели"""
|
||||
model = load_model()
|
||||
if currency:
|
||||
model.base_currency = currency.upper()
|
||||
save_model(model)
|
||||
ok = t("global.ok")
|
||||
msg = t("cmd.config.base_currency.ok", currency=model.base_currency)
|
||||
console.print(f"[green]{ok}[/green] {msg}")
|
||||
else:
|
||||
console.print(t("cmd.config.base_currency.show", currency=f"[bold]{model.base_currency}[/bold]"))
|
||||
|
||||
|
||||
# ── rate ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def rate_set(
|
||||
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
|
||||
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
|
||||
rate: float = typer.Argument(..., help=t("cmd.config.rate_set.arg.rate")),
|
||||
) -> None:
|
||||
"""Добавить или обновить курс валюты"""
|
||||
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]
|
||||
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_value)}")
|
||||
|
||||
|
||||
@app.command(name="rate-list")
|
||||
def rate_list() -> None:
|
||||
"""Список курсов валют"""
|
||||
model = load_model()
|
||||
if not model.exchange_rates:
|
||||
console.print(f"[yellow]{t('cmd.config.rate_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.rates.title"))
|
||||
table.add_column(t("table.rates.col.from"), style="cyan")
|
||||
table.add_column(t("table.rates.col.to"), style="cyan")
|
||||
table.add_column(t("table.rates.col.rate"), justify="right")
|
||||
for r in model.exchange_rates:
|
||||
table.add_row(r.from_currency, r.to_currency, str(r.rate))
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="rate-remove")
|
||||
def rate_remove(
|
||||
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
|
||||
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
|
||||
) -> None:
|
||||
"""Удалить курс валюты"""
|
||||
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)]
|
||||
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)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.rate_remove.err', fc=fc, tc=tc)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── account ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def account_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.account_add.opt.name")),
|
||||
balance: float = typer.Option(0.0, "--balance", "-b", help=t("cmd.config.account_add.opt.balance")),
|
||||
currency: str = typer.Option("", "--currency", "-c", help=t("cmd.config.account_add.opt.currency")),
|
||||
) -> None:
|
||||
"""Добавить счёт"""
|
||||
model = load_model()
|
||||
curr = currency.upper() if currency else model.base_currency
|
||||
account = Account(name=name, balance=balance, currency=curr)
|
||||
model.accounts.append(account)
|
||||
save_model(model)
|
||||
ok = t("global.ok")
|
||||
msg = t("cmd.config.account_add.ok", name=name, balance=balance, currency=curr)
|
||||
console.print(f"[green]{ok}[/green] {msg}")
|
||||
|
||||
|
||||
@app.command(name="account-list")
|
||||
def account_list() -> None:
|
||||
"""Список счетов"""
|
||||
model = load_model()
|
||||
if not model.accounts:
|
||||
console.print(f"[yellow]{t('cmd.config.account_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.accounts_config.title"))
|
||||
table.add_column(t("table.accounts_config.col.id"), style="dim")
|
||||
table.add_column(t("table.accounts_config.col.name"), style="cyan")
|
||||
table.add_column(t("table.accounts_config.col.currency"))
|
||||
table.add_column(t("table.accounts_config.col.balance"), justify="right")
|
||||
for a in model.accounts:
|
||||
balance_str = CurrencyConverter.format_money(a.balance, a.currency)
|
||||
table.add_row(str(a.id)[:8], a.name, a.currency, balance_str)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="account-remove")
|
||||
def account_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.account_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить счёт по 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]
|
||||
if len(model.accounts) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.account_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.account_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── transaction ────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def transaction_add(
|
||||
account: str = typer.Option(..., "--account", "-a", help=t("cmd.config.transaction_add.opt.account")),
|
||||
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.transaction_add.opt.amount")),
|
||||
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.transaction_add.opt.category")),
|
||||
description: str = typer.Option("", "--description", "-d", help=t("cmd.config.transaction_add.opt.description")),
|
||||
date: str = typer.Option("", "--date", "-D", help=t("cmd.config.transaction_add.opt.date")),
|
||||
) -> None:
|
||||
"""Добавить транзакцию"""
|
||||
model = load_model()
|
||||
account_id = _resolve_account_id(model, account)
|
||||
if not account_id:
|
||||
console.print(f"[red]{t('cmd.config.transaction_add.err', account=account)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
txn = Transaction(
|
||||
date=date or "",
|
||||
account=account_id,
|
||||
category=category,
|
||||
amount=amount,
|
||||
description=description,
|
||||
)
|
||||
model.transactions.append(txn)
|
||||
save_model(model)
|
||||
kind = t("cmd.config.transaction_add.kind.income") if amount >= 0 else t("cmd.config.transaction_add.kind.expense")
|
||||
amount_str = CurrencyConverter.format_money(abs(amount), _account_currency(model, account_id))
|
||||
ok = t("global.ok")
|
||||
msg = t("cmd.config.transaction_add.ok", kind=kind, amount_str=amount_str, account=account)
|
||||
console.print(f"[green]{ok}[/green] {msg}")
|
||||
|
||||
|
||||
@app.command(name="transaction-list")
|
||||
def transaction_list() -> None:
|
||||
"""Список транзакций"""
|
||||
model = load_model()
|
||||
if not model.transactions:
|
||||
console.print(f"[yellow]{t('cmd.config.transaction_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.transactions.title"))
|
||||
table.add_column(t("table.accounts_config.col.id"), style="dim")
|
||||
table.add_column(t("table.transactions.col.date"))
|
||||
table.add_column(t("table.accounts_config.col.name"))
|
||||
table.add_column(t("table.transactions.col.category"))
|
||||
table.add_column(t("table.transactions.col.amount"), justify="right")
|
||||
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))
|
||||
table.add_row(
|
||||
str(tx.id)[:8],
|
||||
tx.date,
|
||||
account_name,
|
||||
tx.category,
|
||||
amount_str,
|
||||
tx.description,
|
||||
)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="transaction-remove")
|
||||
def transaction_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.transaction_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить транзакцию по ID"""
|
||||
model = load_model()
|
||||
initial = len(model.transactions)
|
||||
model.transactions = [t for t in model.transactions if str(t.id) != identifier]
|
||||
if len(model.transactions) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.transaction_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.transaction_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── recurring ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def recurring_add(
|
||||
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.recurring_add.opt.amount")),
|
||||
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.recurring_add.opt.category")),
|
||||
frequency: str = typer.Option("monthly", "--frequency", "-f", help=t("cmd.config.recurring_add.opt.frequency")),
|
||||
start_date: str = typer.Option("", "--start", "-s", help=t("cmd.config.recurring_add.opt.start")),
|
||||
end_date: str = typer.Option("", "--end", "-e", help=t("cmd.config.recurring_add.opt.end")),
|
||||
) -> None:
|
||||
"""Добавить регулярный платёж"""
|
||||
model = load_model()
|
||||
rc = RecurringCashflow(
|
||||
start_date=start_date or "",
|
||||
end_date=end_date or "",
|
||||
frequency=frequency,
|
||||
amount=amount,
|
||||
category=category,
|
||||
)
|
||||
model.recurring.append(rc)
|
||||
save_model(model)
|
||||
amount_str = CurrencyConverter.format_money(abs(amount), model.base_currency)
|
||||
ok = t("global.ok")
|
||||
msg = t("cmd.config.recurring_add.ok", amount_str=amount_str, frequency=frequency)
|
||||
console.print(f"[green]{ok}[/green] {msg}")
|
||||
|
||||
|
||||
@app.command(name="recurring-list")
|
||||
def recurring_list() -> None:
|
||||
"""Список регулярных платежей"""
|
||||
model = load_model()
|
||||
if not model.recurring:
|
||||
console.print(f"[yellow]{t('cmd.config.recurring_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.recurring.title"))
|
||||
table.add_column(t("table.recurring.col.id"), style="dim")
|
||||
table.add_column(t("table.recurring.col.start"))
|
||||
table.add_column(t("table.recurring.col.end"))
|
||||
table.add_column(t("table.recurring.col.period"))
|
||||
table.add_column(t("table.recurring.col.amount"), justify="right")
|
||||
table.add_column(t("table.recurring.col.category"))
|
||||
for r in model.recurring:
|
||||
amount_str = CurrencyConverter.format_money(r.amount, model.base_currency)
|
||||
row = (str(r.id)[:8], r.start_date, r.end_date, r.frequency, amount_str, r.category)
|
||||
table.add_row(*row)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="recurring-remove")
|
||||
def recurring_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.recurring_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить регулярный платёж по ID"""
|
||||
model = load_model()
|
||||
initial = len(model.recurring)
|
||||
model.recurring = [r for r in model.recurring if str(r.id) != identifier]
|
||||
if len(model.recurring) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.recurring_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.recurring_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── asset ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def asset_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.asset_add.opt.name")),
|
||||
value: float = typer.Option(0.0, "--value", "-v", help=t("cmd.config.asset_add.opt.value")),
|
||||
growth_rate: float = typer.Option(0.0, "--growth", "-g", help=t("cmd.config.asset_add.opt.growth")),
|
||||
) -> None:
|
||||
"""Добавить актив"""
|
||||
model = load_model()
|
||||
asset = Asset(name=name, value=value, growth_rate=growth_rate)
|
||||
model.assets.append(asset)
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.asset_add.ok', name=name, value=value)}")
|
||||
|
||||
|
||||
@app.command(name="asset-list")
|
||||
def asset_list() -> None:
|
||||
"""Список активов"""
|
||||
model = load_model()
|
||||
if not model.assets:
|
||||
console.print(f"[yellow]{t('cmd.config.asset_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.assets.title"))
|
||||
table.add_column(t("table.assets.col.id"), style="dim")
|
||||
table.add_column(t("table.assets.col.name"), style="cyan")
|
||||
table.add_column(t("table.assets.col.value"), justify="right")
|
||||
table.add_column(t("table.assets.col.growth"), justify="right")
|
||||
for a in model.assets:
|
||||
value_str = CurrencyConverter.format_money(a.value, model.base_currency)
|
||||
table.add_row(str(a.id)[:8], a.name, value_str, f"{a.growth_rate:.1f}%")
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="asset-remove")
|
||||
def asset_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.asset_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить актив по 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]
|
||||
if len(model.assets) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.asset_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.asset_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── liability ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def liability_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.liability_add.opt.name")),
|
||||
balance: float = typer.Option(0.0, "--balance", "-b", help=t("cmd.config.liability_add.opt.balance")),
|
||||
interest: float = typer.Option(0.0, "--interest", "-i", help=t("cmd.config.liability_add.opt.interest")),
|
||||
payment: float = typer.Option(0.0, "--payment", "-p", help=t("cmd.config.liability_add.opt.payment")),
|
||||
) -> None:
|
||||
"""Добавить обязательство"""
|
||||
model = load_model()
|
||||
liability = Liability(name=name, balance=balance, interest=interest, payment=payment)
|
||||
model.liabilities.append(liability)
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.liability_add.ok', name=name, balance=balance)}")
|
||||
|
||||
|
||||
@app.command(name="liability-list")
|
||||
def liability_list() -> None:
|
||||
"""Список обязательств"""
|
||||
model = load_model()
|
||||
if not model.liabilities:
|
||||
console.print(f"[yellow]{t('cmd.config.liability_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.liabilities.title"))
|
||||
table.add_column(t("table.liabilities.col.id"), style="dim")
|
||||
table.add_column(t("table.liabilities.col.name"), style="cyan")
|
||||
table.add_column(t("table.liabilities.col.balance"), justify="right")
|
||||
table.add_column(t("table.liabilities.col.rate"), justify="right")
|
||||
table.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)
|
||||
row = (str(li.id)[:8], li.name, balance_str, f"{li.interest:.1f}%", payment_str)
|
||||
table.add_row(*row)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="liability-remove")
|
||||
def liability_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.liability_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить обязательство по 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]
|
||||
if len(model.liabilities) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.liability_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.liability_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── helpers ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _resolve_account_id(model, identifier: str) -> str | None:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == identifier or a.name == identifier:
|
||||
return str(a.id)
|
||||
return None
|
||||
|
||||
|
||||
def _account_name(model, account_id: str) -> str:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == account_id:
|
||||
return a.name
|
||||
return account_id[:8]
|
||||
|
||||
|
||||
def _account_currency(model, account_id: str) -> str:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == account_id:
|
||||
return a.currency
|
||||
return model.base_currency
|
||||
@@ -65,3 +65,37 @@ class TestNoCliDependency:
|
||||
if imports:
|
||||
offenders[str(path.relative_to(REPO_ROOT))] = imports
|
||||
assert not offenders, f"infrastructure/ai импортирует CLI: {offenders}"
|
||||
|
||||
|
||||
COMMANDS_ROOT = CLI_ROOT / "commands"
|
||||
CONFIG_PKG = COMMANDS_ROOT / "config"
|
||||
|
||||
|
||||
def _typer_instantiations(path: Path) -> list[int]:
|
||||
"""Номера строк, где модуль создаёт `typer.Typer(...)` (D3: мёртвые Typer'ы)."""
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
lines = []
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "Typer":
|
||||
lines.append(node.lineno)
|
||||
return lines
|
||||
|
||||
|
||||
class TestTyperRegistration:
|
||||
"""D25: один Typer-объект на пакет `config`, остальные модули только декорируют."""
|
||||
|
||||
def test_config_package_creates_exactly_one_typer(self):
|
||||
hits = {path: _typer_instantiations(path) for path in sorted(CONFIG_PKG.rglob("*.py"))}
|
||||
hits = {path: lines for path, lines in hits.items() if lines}
|
||||
assert set(hits) == {CONFIG_PKG / "_app.py"}, f"Typer создаётся не только в _app.py: {sorted(map(str, hits))}"
|
||||
assert len(hits[CONFIG_PKG / "_app.py"]) == 1
|
||||
|
||||
def test_other_command_modules_do_not_create_typer_apps(self):
|
||||
offenders = {}
|
||||
for path in sorted(COMMANDS_ROOT.rglob("*.py")):
|
||||
if CONFIG_PKG in path.parents:
|
||||
continue
|
||||
lines = _typer_instantiations(path)
|
||||
if lines:
|
||||
offenders[str(path.relative_to(REPO_ROOT))] = lines
|
||||
assert not offenders, f"модули команд создают собственные Typer: {offenders}"
|
||||
+118
-9
@@ -1,17 +1,22 @@
|
||||
"""Инвариант публичной поверхности CLI.
|
||||
|
||||
Фиксирует набор команд, подкоманд и дефолтных путей, которые видит
|
||||
пользователь. Обязан проходить ДО и ПОСЛЕ любых рефакторингов структуры
|
||||
CLI (D3 — удаление мёртвых typer.Typer(), D25 — разбиение config_cmd.py
|
||||
на пакет): если набор изменился, поведение CLI изменилось без
|
||||
согласования — тест обязан упасть.
|
||||
Фиксирует набор команд, подкоманд, их аргументов/опций и значений по умолчанию —
|
||||
всё, что видит пользователь. Обязан проходить ДО и ПОСЛЕ любых рефакторингов
|
||||
структуры CLI (D3 — удаление мёртвых `typer.Typer()`, D25 — разбиение
|
||||
`config_cmd.py` на пакет `commands/config/`, D26/D27 — вынос i18n): если
|
||||
поверхность изменилась, поведение CLI изменилось без согласования — тест
|
||||
обязан упасть.
|
||||
|
||||
Проверяется по click-представлению (то, что реально исполняется), а не по
|
||||
исходникам: имя команды, порядок и имена параметров, длинные/короткие опции,
|
||||
default и required.
|
||||
"""
|
||||
|
||||
import typer
|
||||
from typer.main import get_command
|
||||
|
||||
from infrastructure.cli.app import app
|
||||
from infrastructure.cli.commands import config_cmd
|
||||
from infrastructure.cli.commands.config import app as config_app
|
||||
|
||||
EXPECTED_COMMANDS = {
|
||||
"init",
|
||||
@@ -49,6 +54,83 @@ EXPECTED_CONFIG_COMMANDS = {
|
||||
|
||||
EXPECTED_EXPORT_DEFAULT = "exports/forecast.xlsx"
|
||||
|
||||
# (имя параметра, опции в порядке объявления, default, required)
|
||||
EXPECTED_PARAMS = {
|
||||
"init": [],
|
||||
"forecast": [("months", ("--months", "-m"), 12, False), ("currency", ("--currency", "-c"), None, False)],
|
||||
"scenario": [
|
||||
("name", ("name",), "baseline", False),
|
||||
("months", ("--months", "-m"), 12, False),
|
||||
("currency", ("--currency", "-c"), None, False),
|
||||
],
|
||||
"whatif": [
|
||||
("income", ("--income", "-i"), 1.0, False),
|
||||
("expense", ("--expense", "-e"), 1.0, False),
|
||||
("growth", ("--growth", "-g"), 1.0, False),
|
||||
("months", ("--months", "-m"), 12, False),
|
||||
("currency", ("--currency", "-c"), None, False),
|
||||
],
|
||||
"compare": [("months", ("--months", "-m"), 12, False), ("currency", ("--currency", "-c"), None, False)],
|
||||
"import-xlsx": [("path", ("path",), None, True)],
|
||||
"export-xlsx": [("path", ("path",), EXPECTED_EXPORT_DEFAULT, False)],
|
||||
"analyze": [("months", ("--months", "-m"), 12, False), ("currency", ("--currency", "-c"), None, False)],
|
||||
"info": [],
|
||||
}
|
||||
|
||||
EXPECTED_CONFIG_PARAMS = {
|
||||
"base-currency": [("currency", ("currency",), None, False)],
|
||||
"rate-set": [
|
||||
("from_currency", ("from_currency",), None, True),
|
||||
("to_currency", ("to_currency",), None, True),
|
||||
("rate", ("rate",), None, True),
|
||||
],
|
||||
"rate-list": [],
|
||||
"rate-remove": [
|
||||
("from_currency", ("from_currency",), None, True),
|
||||
("to_currency", ("to_currency",), None, True),
|
||||
],
|
||||
"account-add": [
|
||||
("name", ("--name", "-n"), None, True),
|
||||
("balance", ("--balance", "-b"), 0.0, False),
|
||||
("currency", ("--currency", "-c"), "", False),
|
||||
],
|
||||
"account-list": [],
|
||||
"account-remove": [("identifier", ("identifier",), None, True)],
|
||||
"transaction-add": [
|
||||
("account", ("--account", "-a"), None, True),
|
||||
("amount", ("--amount", "-m"), None, True),
|
||||
("category", ("--category", "-c"), "", False),
|
||||
("description", ("--description", "-d"), "", False),
|
||||
("date", ("--date", "-D"), "", False),
|
||||
],
|
||||
"transaction-list": [],
|
||||
"transaction-remove": [("identifier", ("identifier",), None, True)],
|
||||
"recurring-add": [
|
||||
("amount", ("--amount", "-m"), None, True),
|
||||
("category", ("--category", "-c"), "", False),
|
||||
("frequency", ("--frequency", "-f"), "monthly", False),
|
||||
("start_date", ("--start", "-s"), "", False),
|
||||
("end_date", ("--end", "-e"), "", False),
|
||||
],
|
||||
"recurring-list": [],
|
||||
"recurring-remove": [("identifier", ("identifier",), None, True)],
|
||||
"asset-add": [
|
||||
("name", ("--name", "-n"), None, True),
|
||||
("value", ("--value", "-v"), 0.0, False),
|
||||
("growth_rate", ("--growth", "-g"), 0.0, False),
|
||||
],
|
||||
"asset-list": [],
|
||||
"asset-remove": [("identifier", ("identifier",), None, True)],
|
||||
"liability-add": [
|
||||
("name", ("--name", "-n"), None, True),
|
||||
("balance", ("--balance", "-b"), 0.0, False),
|
||||
("interest", ("--interest", "-i"), 0.0, False),
|
||||
("payment", ("--payment", "-p"), 0.0, False),
|
||||
],
|
||||
"liability-list": [],
|
||||
"liability-remove": [("identifier", ("identifier",), None, True)],
|
||||
}
|
||||
|
||||
|
||||
def _click_app(typer_app: typer.Typer):
|
||||
"""Развернуть Typer-приложение в click-команду (то, что видит пользователь)."""
|
||||
@@ -59,12 +141,16 @@ def _command_names(typer_app: typer.Typer) -> set[str]:
|
||||
return set(_click_app(typer_app).commands.keys())
|
||||
|
||||
|
||||
def _params(command) -> list[tuple[str, tuple[str, ...], object, bool]]:
|
||||
return [(p.name, tuple(p.opts), p.default, p.required) for p in command.params]
|
||||
|
||||
|
||||
class TestCliSurface:
|
||||
def test_top_level_commands(self):
|
||||
assert _command_names(app) == EXPECTED_COMMANDS | {"config"}
|
||||
|
||||
def test_config_subcommands(self):
|
||||
assert _command_names(config_cmd.app) == EXPECTED_CONFIG_COMMANDS
|
||||
assert _command_names(config_app) == EXPECTED_CONFIG_COMMANDS
|
||||
|
||||
def test_config_subapp_reachable_from_root(self):
|
||||
root = _click_app(app)
|
||||
@@ -78,11 +164,34 @@ class TestCliSurface:
|
||||
continue # sub-typer (config) — у группы callback'а нет by design
|
||||
assert command.callback is not None, f"команда {name} без callback"
|
||||
|
||||
for name, command in _click_app(config_cmd.app).commands.items():
|
||||
for name, command in _click_app(config_app).commands.items():
|
||||
assert command.callback is not None, f"команда config {name} без callback"
|
||||
|
||||
|
||||
class TestDefaultPaths:
|
||||
class TestCliParameters:
|
||||
"""Имя, опции и default каждой команды/подкоманды — часть контракта."""
|
||||
|
||||
def test_top_level_parameters_and_defaults(self):
|
||||
root = _click_app(app)
|
||||
actual = {name: _params(command) for name, command in root.commands.items() if not hasattr(command, "commands")}
|
||||
assert actual == EXPECTED_PARAMS
|
||||
|
||||
def test_config_parameters_and_defaults(self):
|
||||
actual = {name: _params(command) for name, command in _click_app(config_app).commands.items()}
|
||||
assert actual == EXPECTED_CONFIG_PARAMS
|
||||
|
||||
def test_every_parameter_has_help(self):
|
||||
"""Справка опции не должна теряться при переносе команд между модулями."""
|
||||
root = _click_app(app)
|
||||
for name, command in root.commands.items():
|
||||
if hasattr(command, "commands"):
|
||||
continue
|
||||
for param in command.params:
|
||||
assert param.help, f"{name}: у параметра {param.name} пустая справка"
|
||||
for name, command in _click_app(config_app).commands.items():
|
||||
for param in command.params:
|
||||
assert param.help, f"config {name}: у параметра {param.name} пустая справка"
|
||||
|
||||
def test_export_xlsx_default_path_is_unchanged(self):
|
||||
"""Дефолт `cf export-xlsx` — строка, которую видит пользователь в --help."""
|
||||
command = _click_app(app).commands["export-xlsx"]
|
||||
|
||||
+2
-2
@@ -125,8 +125,8 @@ class TestFinancialModel:
|
||||
class TestValidateAssignment:
|
||||
"""D17: модели домена валидируют присваивание (validate_assignment=True).
|
||||
|
||||
Раньше `r.rate = -5` молча принимался, а `config_cmd.py` писал в поле
|
||||
Decimal значение типа float — валидатор при этом не срабатывал.
|
||||
Раньше `r.rate = -5` молча принимался, а команда `cf config rate-set`
|
||||
писала в поле Decimal значение типа float — валидатор при этом не срабатывал.
|
||||
"""
|
||||
|
||||
def test_negative_rate_is_rejected_on_assignment(self):
|
||||
|
||||
Reference in new issue
Block a user