D35, D36: Excel как поверхность сборки модели
Импорт и выгрузка переработаны в полноценную поверхность авторства. Схема (infrastructure/repositories/excel_schema.py): - таблица SHEETS описывает листы, русские заголовки, синонимы заголовков и типы значений — один источник истины для записи и чтения (D28); - заголовки русские (D19), синонимы — русские и английские, порядок столбцов и регистр не важны; - новые столбцы: валюта у транзакций/регулярных/активов/обязательств и счёт у регулярного платежа. Импорт (терпимый): - числа: «1 234,56», «1,234.56», «₽1200», «(100)» = −100; - даты: датой Excel или текстом (2026-11-01 / 01.11.2026 / 01/11/2026); - счёт — по имени или UUID; неизвестный счёт — ошибка с адресом лист!строка; - ошибки строк собираются в отчёт, файл с ошибками не сохраняется; - предупреждения: неизвестный столбец, повтор имени счёта, формула без сохранённого значения, отсутствующий лист; - cf import-xlsx --dry-run — проверка без записи модели. Шаблон и выгрузка: - cf template-xlsx — каркас: русские заголовки, форматы чисел и дат, выпадающие списки (валюта, периодичность, счёт), лист «Инструкция»; - cf export-xlsx пишет тот же шаблон, уже заполненный данными, — цикл «выгрузить → поправить в Excel → импортировать» работает; - перед перезаписью модели сохраняется резервная копия model.json.bak. Тесты: 302 → 333 (tests/test_excel_authoring.py).
This commit is contained in:
1 parent
885a91f15f
commit
6b13a15408
17 files changed
+1612
-212
No files matched your search
@@ -19,6 +19,7 @@ from infrastructure.cli.commands import (
|
||||
info,
|
||||
init,
|
||||
scenario,
|
||||
template_xlsx,
|
||||
whatif,
|
||||
)
|
||||
from infrastructure.i18n import setup_i18n, t
|
||||
@@ -35,6 +36,7 @@ app.command(name="whatif")(whatif.whatif)
|
||||
app.command(name="compare")(compare.compare)
|
||||
app.command(name="import-xlsx")(import_xlsx.import_xlsx)
|
||||
app.command(name="export-xlsx")(export_xlsx.export_xlsx)
|
||||
app.command(name="template-xlsx")(template_xlsx.template_xlsx)
|
||||
app.command(name="analyze")(analyze.analyze)
|
||||
app.command(name="info")(info.info)
|
||||
|
||||
|
||||
@@ -19,6 +19,4 @@ def display_currency(
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.display_currency.ok", currency=model.display_currency))
|
||||
else:
|
||||
console.print(
|
||||
t("cmd.config.display_currency.show", currency=f"[bold]{model.output_currency}[/bold]")
|
||||
)
|
||||
console.print(t("cmd.config.display_currency.show", currency=f"[bold]{model.output_currency}[/bold]"))
|
||||
@@ -1,32 +1,80 @@
|
||||
"""cf import-xlsx — импорт данных из Excel."""
|
||||
"""`cf import-xlsx` — импорт модели из Excel.
|
||||
|
||||
Импорт терпимый: заголовки принимаются на русском и английском, числа и даты
|
||||
разбираются в пользовательских форматах, счёт — по имени или UUID. Ошибки
|
||||
строк собираются в таблицу с адресом «лист!строка»; файл с ошибками не
|
||||
сохраняется. `--dry-run` проверяет файл, не трогая модель.
|
||||
"""
|
||||
|
||||
import typer
|
||||
from rich.markup import escape
|
||||
from rich.table import Table
|
||||
|
||||
from infrastructure.cli.services import console, save_model
|
||||
from infrastructure.i18n import t
|
||||
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
|
||||
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError, ExcelRowError
|
||||
|
||||
_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]")
|
||||
|
||||
|
||||
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))
|
||||
@@ -0,0 +1,29 @@
|
||||
"""`cf template-xlsx` — создать Excel-шаблон для ручного заполнения модели."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.markup import escape
|
||||
|
||||
from infrastructure.cli.paths import AppPaths
|
||||
from infrastructure.cli.services import console
|
||||
from infrastructure.i18n import t
|
||||
from infrastructure.repositories import TemplateError, write_template
|
||||
|
||||
|
||||
def template_xlsx(
|
||||
path: Path = typer.Argument(
|
||||
AppPaths.from_env().data_dir / "model_template.xlsx",
|
||||
help=t("cmd.template.arg.path"),
|
||||
),
|
||||
force: bool = typer.Option(False, "--force", "-f", help=t("cmd.template.opt.force")),
|
||||
) -> None:
|
||||
"""Создать Excel-шаблон для заполнения модели"""
|
||||
try:
|
||||
target = write_template(path, force=force)
|
||||
except TemplateError 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))))
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from decimal import Decimal
|
||||
from typing import NoReturn
|
||||
|
||||
@@ -55,7 +56,20 @@ def load_model() -> FinancialModel:
|
||||
|
||||
|
||||
def save_model(model: FinancialModel) -> None:
|
||||
_json_repo.save(model, AppPaths.from_env().model_path)
|
||||
"""Сохранить модель. Прежний файл остаётся рядом как `.bak` (D35).
|
||||
|
||||
Импорт из Excel заменяет модель целиком — если файл оказался не тем,
|
||||
прежнее состояние можно вернуть одной командой копирования.
|
||||
"""
|
||||
model_path = AppPaths.from_env().model_path
|
||||
if model_path.exists():
|
||||
backup_path = model_path.with_suffix(model_path.suffix + ".bak")
|
||||
try:
|
||||
shutil.copy2(model_path, backup_path)
|
||||
console.print(f"[dim]{t('cmd.import.backup', path=backup_path)}[/dim]")
|
||||
except OSError as exc:
|
||||
console.print(f"[yellow]{t('cmd.import.backup_failed', error=exc)}[/yellow]")
|
||||
_json_repo.save(model, model_path)
|
||||
|
||||
|
||||
def build_services(
|
||||
|
||||
Reference in new issue
Block a user