T9: Excel as the model authoring surface
- ExcelRepository: canonical columns with ru/en aliases, date/number normalization (Excel dates, DD.MM.YYYY, '1 234,56', currency symbols, parentheses), account name->UUID resolution, per-row errors with sheet!row, warnings for formulas without cached values, duplicate names and default exchange rates - ExcelTemplate: skeleton generator (number/date formats, dropdowns for currency, frequency en/ru and account, 'Инструкция' sheet); ship data/model_template.xlsx - CLI: cf template-xlsx [--force]; cf import-xlsx --dry-run with rich error table, import writes nothing when the file has errors - RecurringCashflow.account (empty = all accounts) + name/UUID matching in forecast; cf config recurring-add --account, account column in info/recurring-list - Forecast: runs are idempotent, 'Итог: Баланс' sums all accounts of the last month - README: 'Сборка модели в Excel' section - ruff check . clean (9 pre-existing import/line-length findings fixed) - MetaAgent: T9 archived, req-T9 approved, manifest/checkpoints/state synced 118 tests pass
This commit is contained in:
1 parent
b90ca4c282
commit
cdda703b37
39 files changed
+2181
-198
No files matched your search
@@ -8,7 +8,6 @@ try:
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
|
||||
from infrastructure.cli.i18n import setup_i18n, t
|
||||
from infrastructure.cli.commands import (
|
||||
analyze,
|
||||
compare,
|
||||
@@ -19,8 +18,10 @@ from infrastructure.cli.commands import (
|
||||
info,
|
||||
init,
|
||||
scenario,
|
||||
template_xlsx,
|
||||
whatif,
|
||||
)
|
||||
from infrastructure.cli.i18n import setup_i18n, t
|
||||
|
||||
setup_i18n()
|
||||
|
||||
@@ -32,6 +33,7 @@ app.command(name="forecast")(forecast.forecast)
|
||||
app.command(name="scenario")(scenario.scenario)
|
||||
app.command(name="whatif")(whatif.whatif)
|
||||
app.command(name="compare")(compare.compare)
|
||||
app.command(name="template-xlsx")(template_xlsx.template_xlsx)
|
||||
app.command(name="import-xlsx")(import_xlsx.import_xlsx)
|
||||
app.command(name="export-xlsx")(export_xlsx.export_xlsx)
|
||||
app.command(name="analyze")(analyze.analyze)
|
||||
|
||||
@@ -8,6 +8,7 @@ from infrastructure.cli.commands import (
|
||||
info,
|
||||
init,
|
||||
scenario,
|
||||
template_xlsx,
|
||||
whatif,
|
||||
)
|
||||
|
||||
@@ -21,5 +22,6 @@ __all__ = [
|
||||
"info",
|
||||
"init",
|
||||
"scenario",
|
||||
"template_xlsx",
|
||||
"whatif",
|
||||
]
|
||||
@@ -13,7 +13,7 @@ from domain import (
|
||||
Transaction,
|
||||
)
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.services import load_model, save_model
|
||||
from infrastructure.cli.services import account_label, load_model, save_model
|
||||
|
||||
app = typer.Typer(name="config", help=t("config.help"))
|
||||
console = Console()
|
||||
@@ -242,12 +242,19 @@ def recurring_add(
|
||||
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")),
|
||||
account: str = typer.Option("", "--account", "-a", help=t("cmd.config.recurring_add.opt.account")),
|
||||
) -> None:
|
||||
"""Добавить регулярный платёж"""
|
||||
model = load_model()
|
||||
account_id = ""
|
||||
if account:
|
||||
account_id = _resolve_account_id(model, account) or ""
|
||||
if not account_id:
|
||||
console.print(f"[red]{t('cmd.config.recurring_add.err', account=account)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
rc = RecurringCashflow(
|
||||
start_date=start_date or "", end_date=end_date or "",
|
||||
frequency=frequency, amount=amount, category=category,
|
||||
frequency=frequency, amount=amount, category=category, account=account_id,
|
||||
)
|
||||
model.recurring.append(rc)
|
||||
save_model(model)
|
||||
@@ -266,6 +273,7 @@ def recurring_list() -> None:
|
||||
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.account"))
|
||||
table.add_column(t("table.recurring.col.start"))
|
||||
table.add_column(t("table.recurring.col.end"))
|
||||
table.add_column(t("table.recurring.col.period"))
|
||||
@@ -273,7 +281,8 @@ def recurring_list() -> None:
|
||||
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)
|
||||
owner = account_label(model, r.account, empty=t("table.recurring.all_accounts"))
|
||||
row = (str(r.id)[:8], owner, r.start_date, r.end_date, r.frequency, amount_str, r.category)
|
||||
table.add_row(*row)
|
||||
console.print(table)
|
||||
|
||||
@@ -410,8 +419,11 @@ def liability_remove(
|
||||
|
||||
|
||||
def _resolve_account_id(model, identifier: str) -> str | None:
|
||||
value = (identifier or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
for a in model.accounts:
|
||||
if str(a.id) == identifier or a.name == identifier:
|
||||
if value == str(a.id) or value.casefold() == a.name.strip().casefold():
|
||||
return str(a.id)
|
||||
return None
|
||||
|
||||
|
||||
@@ -1,29 +1,75 @@
|
||||
"""cf import-xlsx — импорт данных из Excel."""
|
||||
import typer
|
||||
from rich.markup import escape
|
||||
from rich.table import Table
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.services import console, save_model
|
||||
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
|
||||
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError, ExcelRowError
|
||||
|
||||
app = typer.Typer()
|
||||
_repo = ExcelRepository()
|
||||
|
||||
|
||||
def _counts(model) -> dict[str, int]:
|
||||
return {
|
||||
"accounts": len(model.accounts),
|
||||
"transactions": len(model.transactions),
|
||||
"recurring": len(model.recurring),
|
||||
"assets": len(model.assets),
|
||||
"liabilities": len(model.liabilities),
|
||||
}
|
||||
|
||||
|
||||
def _print_warnings(warnings: list[str]) -> None:
|
||||
for warning in warnings:
|
||||
console.print(f"[yellow]{t('cmd.import.warn', warning=escape(warning))}[/yellow]")
|
||||
|
||||
|
||||
def _print_errors(errors: list[ExcelRowError]) -> None:
|
||||
table = Table(title=t("cmd.import.errors.title", count=len(errors)))
|
||||
table.add_column(t("cmd.import.errors.col.sheet"))
|
||||
table.add_column(t("cmd.import.errors.col.row"), justify="right")
|
||||
table.add_column(t("cmd.import.errors.col.field"))
|
||||
table.add_column(t("cmd.import.errors.col.message"))
|
||||
for error in errors:
|
||||
table.add_row(
|
||||
escape(error.sheet),
|
||||
str(error.row),
|
||||
escape(error.field) or "—",
|
||||
escape(error.message),
|
||||
)
|
||||
console.print(table)
|
||||
console.print(f"[red]{t('cmd.import.errors.hint', first=escape(str(errors[0])))}[/red]")
|
||||
|
||||
|
||||
@app.command(name="import-xlsx")
|
||||
def import_xlsx(
|
||||
path: str = typer.Argument(..., help=t("cmd.import.arg.path")),
|
||||
dry_run: bool = typer.Option(False, "--dry-run", help=t("cmd.import.opt.dry_run")),
|
||||
) -> None:
|
||||
"""Импорт данных из Excel"""
|
||||
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.base_currency", currency=model.base_currency))
|
||||
report = _repo.load_report(path)
|
||||
except ExcelRepositoryError as e:
|
||||
console.print(f"[red]{t('cmd.import.err', error=str(e))}[/red]")
|
||||
console.print(f"[red]{t('cmd.import.err', error=escape(str(e)))}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
_print_warnings(report.warnings)
|
||||
|
||||
if report.errors:
|
||||
_print_errors(report.errors)
|
||||
raise typer.Exit(1)
|
||||
|
||||
counts = _counts(report.model)
|
||||
|
||||
if dry_run:
|
||||
console.print(t("cmd.import.dry_run.title"))
|
||||
console.print(t("cmd.import.dry_run.ok", **counts))
|
||||
console.print(t("cmd.import.dry_run.base_currency", currency=report.model.base_currency))
|
||||
console.print(f"[yellow]{t('cmd.import.dry_run.not_saved')}[/yellow]")
|
||||
return
|
||||
|
||||
save_model(report.model)
|
||||
console.print(t("cmd.import.ok", **counts))
|
||||
console.print(t("cmd.import.base_currency", currency=report.model.base_currency))
|
||||
@@ -4,7 +4,7 @@ from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.services import console, load_model
|
||||
from infrastructure.cli.services import account_label, console, load_model
|
||||
|
||||
app = typer.Typer()
|
||||
|
||||
@@ -51,12 +51,14 @@ def info() -> None:
|
||||
|
||||
if model.recurring:
|
||||
tbl = Table(title=t("table.recurring.title"))
|
||||
tbl.add_column(t("table.recurring.col.account"))
|
||||
tbl.add_column(t("table.recurring.col.period"))
|
||||
tbl.add_column(t("table.recurring.col.amount"), justify="right")
|
||||
tbl.add_column(t("table.recurring.col.category"))
|
||||
for r in model.recurring:
|
||||
amount_str = CurrencyConverter.format_money(r.amount, model.base_currency)
|
||||
tbl.add_row(r.frequency, amount_str, r.category)
|
||||
owner = account_label(model, r.account, empty=t("table.recurring.all_accounts"))
|
||||
tbl.add_row(owner, r.frequency, amount_str, r.category)
|
||||
console.print(tbl)
|
||||
|
||||
if model.assets:
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""cf init — создать пустую модель."""
|
||||
import typer
|
||||
|
||||
from domain import FinancialModel
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.paths import MODEL_PATH
|
||||
from infrastructure.cli.services import console, save_model
|
||||
from domain import FinancialModel
|
||||
|
||||
app = typer.Typer()
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""cf template-xlsx — создать Excel-шаблон модели для ручного заполнения."""
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.markup import escape
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.paths import TEMPLATE_PATH
|
||||
from infrastructure.cli.services import console
|
||||
from infrastructure.repositories import ExcelRepositoryError, write_template
|
||||
|
||||
app = typer.Typer()
|
||||
|
||||
|
||||
@app.command(name="template-xlsx")
|
||||
def template_xlsx(
|
||||
path: Path = typer.Argument(TEMPLATE_PATH, help=t("cmd.template.arg.path")),
|
||||
force: bool = typer.Option(False, "--force", "-f", help=t("cmd.template.opt.force")),
|
||||
) -> None:
|
||||
"""Создать Excel-шаблон для заполнения модели"""
|
||||
if path.exists() and not force:
|
||||
console.print(f"[red]{t('cmd.template.err.exists', path=escape(str(path)))}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
try:
|
||||
target = write_template(path, force=force)
|
||||
except ExcelRepositoryError as e:
|
||||
console.print(f"[red]{t('cmd.template.err', error=escape(str(e)))}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
console.print(t("cmd.template.ok", path=escape(str(target))))
|
||||
console.print(t("cmd.template.hint", path=escape(str(target))))
|
||||
@@ -68,11 +68,36 @@ _r("cmd.compare.col.scenario", "Сценарий")
|
||||
|
||||
_r("cmd.import.help", "Импорт данных из Excel")
|
||||
_r("cmd.import.arg.path", "Путь к .xlsx файлу")
|
||||
_r("cmd.import.opt.dry_run", "Только проверить файл, не сохраняя модель")
|
||||
_r("cmd.import.ok",
|
||||
"Импортировано: {accounts} счетов, {transactions} транзакций, "
|
||||
"{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств")
|
||||
"Импортировано: счета — {accounts}, транзакции — {transactions}, "
|
||||
"регулярные платежи — {recurring}, активы — {assets}, обязательства — {liabilities}")
|
||||
_r("cmd.import.base_currency", "Базовая валюта: {currency}")
|
||||
_r("cmd.import.err", "Ошибка импорта: {error}")
|
||||
_r("cmd.import.warn", "Предупреждение: {warning}")
|
||||
_r("cmd.import.errors.title", "Ошибки в файле ({count}) — модель не сохранена:")
|
||||
_r("cmd.import.errors.hint", "Первая ошибка: {first}. Исправьте файл и повторите импорт.")
|
||||
_r("cmd.import.errors.col.sheet", "Лист")
|
||||
_r("cmd.import.errors.col.row", "Строка")
|
||||
_r("cmd.import.errors.col.field", "Поле")
|
||||
_r("cmd.import.errors.col.message", "Ошибка")
|
||||
_r("cmd.import.dry_run.title", "Проверка файла (--dry-run):")
|
||||
_r("cmd.import.dry_run.ok",
|
||||
"В файле: счета — {accounts}, транзакции — {transactions}, "
|
||||
"регулярные платежи — {recurring}, активы — {assets}, обязательства — {liabilities}")
|
||||
_r("cmd.import.dry_run.not_saved", "Модель не сохранена (--dry-run)")
|
||||
_r("cmd.import.dry_run.base_currency", "Базовая валюта: {currency}")
|
||||
|
||||
# ── cmd.template ──────────────────────────────────────────────
|
||||
|
||||
_r("cmd.template.help", "Создать Excel-шаблон для заполнения модели")
|
||||
_r("cmd.template.arg.path", "Путь для .xlsx шаблона")
|
||||
_r("cmd.template.opt.force", "Перезаписать существующий файл")
|
||||
_r("cmd.template.ok", "Шаблон создан: {path}")
|
||||
_r("cmd.template.hint", "Заполните файл в Excel и импортируйте: cf import-xlsx {path}")
|
||||
_r("cmd.template.err.exists",
|
||||
"Файл уже существует: {path} — добавьте --force, чтобы перезаписать")
|
||||
_r("cmd.template.err", "Ошибка создания шаблона: {error}")
|
||||
|
||||
# ── cmd.export ────────────────────────────────────────────────
|
||||
|
||||
@@ -119,6 +144,8 @@ _r("table.transactions.col.description", "Описание")
|
||||
|
||||
_r("table.recurring.title", "Регулярные платежи")
|
||||
_r("table.recurring.col.period", "Период")
|
||||
_r("table.recurring.col.account", "Счёт")
|
||||
_r("table.recurring.all_accounts", "все счета")
|
||||
_r("table.recurring.col.amount", "Сумма")
|
||||
_r("table.recurring.col.category", "Категория")
|
||||
_r("table.recurring.col.id", "ID")
|
||||
@@ -209,6 +236,8 @@ _r("cmd.config.recurring_add.opt.category", "Категория")
|
||||
_r("cmd.config.recurring_add.opt.frequency", "Периодичность")
|
||||
_r("cmd.config.recurring_add.opt.start", "Дата начала (YYYY-MM-DD)")
|
||||
_r("cmd.config.recurring_add.opt.end", "Дата окончания (YYYY-MM-DD)")
|
||||
_r("cmd.config.recurring_add.opt.account", "Счёт (имя); пусто — платёж по всем счетам")
|
||||
_r("cmd.config.recurring_add.err", "Счёт не найден: {account}")
|
||||
_r("cmd.config.recurring_add.ok", "Регулярный платёж на {amount_str} ({frequency})")
|
||||
|
||||
_r("cmd.config.recurring_list.help", "Список регулярных платежей")
|
||||
|
||||
@@ -3,3 +3,4 @@ from pathlib import Path
|
||||
|
||||
DATA_DIR: Path = Path("data")
|
||||
MODEL_PATH: Path = DATA_DIR / "model.json"
|
||||
TEMPLATE_PATH: Path = DATA_DIR / "model_template.xlsx"
|
||||
@@ -12,7 +12,6 @@ from infrastructure.ai.assistant import AssistantService
|
||||
from infrastructure.cli.paths import MODEL_PATH
|
||||
from infrastructure.repositories import JsonFileRepository
|
||||
|
||||
|
||||
console = Console()
|
||||
|
||||
_json_repo = JsonFileRepository()
|
||||
@@ -28,7 +27,9 @@ def save_model(model: FinancialModel) -> None:
|
||||
_json_repo.save(model, MODEL_PATH)
|
||||
|
||||
|
||||
def build_services(model: FinancialModel) -> tuple[ForecastService, ScenarioService, AssistantService, CurrencyConverter]:
|
||||
def build_services(
|
||||
model: FinancialModel,
|
||||
) -> tuple[ForecastService, ScenarioService, AssistantService, CurrencyConverter]:
|
||||
"""Composition root: собрать граф сервисов с зависимостями."""
|
||||
converter = CurrencyConverter(model.exchange_rates)
|
||||
forecast_service = ForecastService(model)
|
||||
@@ -39,6 +40,17 @@ def build_services(model: FinancialModel) -> tuple[ForecastService, ScenarioServ
|
||||
return forecast_service, scenario_service, assistant_service, converter
|
||||
|
||||
|
||||
def account_label(model: FinancialModel, ref: str, *, empty: str = "") -> str:
|
||||
"""Человекочитаемое имя счёта по ссылке (UUID или имя); пусто → `empty`."""
|
||||
value = (ref or "").strip()
|
||||
if not value:
|
||||
return empty
|
||||
for account in model.accounts:
|
||||
if value == str(account.id) or value.casefold() == account.name.strip().casefold():
|
||||
return account.name
|
||||
return value
|
||||
|
||||
|
||||
def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str, str]:
|
||||
target = currency or model.base_currency
|
||||
converter = CurrencyConverter(model.exchange_rates)
|
||||
|
||||
Reference in new issue
Block a user