D25: config_cmd.py → пакет commands/config/ по семействам сущностей (19 подкоманд, поверхность без изменений)

This commit is contained in:
oqyude committed 2026-10-25 17:19:00 +03:00
1 parent bd23b03c08
commit 3d4ee910b4
16 files changed
+706 -450

No files matched your search

+2 -2
View File
@@ -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__":
+2 -2
View File
@@ -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
-435
View File
@@ -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