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:
oqyude committed 2026-11-11 15:40:37 +03:00
1 parent b90ca4c282
commit cdda703b37
39 files changed
+2181 -198

No files matched your search

+2 -2
View File
@@ -1,9 +1,9 @@
import json
from decimal import Decimal
from infrastructure.ai import prompts
from domain import CurrencyConverter, FinancialModel
from application.forecast import ForecastService
from domain import CurrencyConverter, FinancialModel
from infrastructure.ai import prompts
class AssistantError(Exception):
+3 -1
View File
@@ -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)
+2
View File
@@ -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",
]
+16 -4
View File
@@ -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
+57 -11
View File
@@ -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 -2
View File
@@ -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 -1
View File
@@ -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))))
+31 -2
View File
@@ -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", "Список регулярных платежей")
+1
View File
@@ -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"
+14 -2
View File
@@ -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)
+15 -2
View File
@@ -1,4 +1,17 @@
from infrastructure.repositories.excel_repository import ExcelRepository, ExcelRepositoryError
from infrastructure.repositories.excel_repository import (
ExcelImportResult,
ExcelRepository,
ExcelRepositoryError,
ExcelRowError,
)
from infrastructure.repositories.excel_template import write_template
from infrastructure.repositories.json_file_repository import JsonFileRepository
__all__ = ["JsonFileRepository", "ExcelRepository", "ExcelRepositoryError"]
__all__ = [
"JsonFileRepository",
"ExcelRepository",
"ExcelRepositoryError",
"ExcelImportResult",
"ExcelRowError",
"write_template",
]
+719 -82
View File
@@ -1,8 +1,36 @@
"""ExcelRepository — хранит FinancialModel в .xlsx (5 листов + ModelInfo)."""
"""ExcelRepository — .xlsx как полноценная поверхность authoring.
Файл содержит листы ``ModelInfo``, ``Accounts``, ``Transactions``, ``Recurring``,
``Assets``, ``Liabilities``, ``ExchangeRates``. При импорте заголовки принимаются
на русском и английском без учёта регистра, пробелов, ``_`` и ``-``. Пользователь
может заполнять файл руками (без колонки ``id``, счёта — по имени) и импортировать
его командой ``cf import-xlsx``.
Публичный контракт:
- ``ExcelRepository.load(path)`` — вернуть модель или поднять ``ExcelRepositoryError``
с компактной сводкой ошибок;
- ``ExcelRepository.load_report(path)`` — никогда не падает на ошибках данных,
собирает их в ``ExcelImportResult`` (не больше 100 ошибок);
- ``ExcelRepository.save(model, path)`` — записать модель в .xlsx;
- ``write_template(path, force=False)`` — сгенерировать пустой шаблон (см.
``infrastructure.repositories.excel_template``).
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from pathlib import Path
from uuid import UUID
from zipfile import BadZipFile
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font
from openpyxl.utils import get_column_letter
from openpyxl.utils.exceptions import InvalidFileException
from pydantic import ValidationError
from application.repositories.model_repository import ModelRepository
from domain import (
@@ -15,124 +43,733 @@ from domain import (
Transaction,
)
# ---------------------------------------------------------------------------
# Схема листов
# ---------------------------------------------------------------------------
class ExcelRepositoryError(Exception):
pass
CANONICAL_COLUMNS: dict[str, tuple[str, ...]] = {
"Accounts": ("id", "name", "currency", "balance"),
"Transactions": ("id", "date", "account", "category", "amount", "description"),
"Recurring": ("id", "account", "start_date", "end_date", "frequency", "amount", "category"),
"Assets": ("id", "name", "value", "growth_rate"),
"Liabilities": ("id", "name", "balance", "interest", "payment"),
"ExchangeRates": ("from_currency", "to_currency", "rate"),
}
SHEET_ORDER: tuple[str, ...] = ("ModelInfo", *CANONICAL_COLUMNS)
_SHEET_CONFIG = {
# Канонический столбец -> принимаемые заголовки (ru + en).
_ALIASES: dict[str, dict[str, tuple[str, ...]]] = {
"Accounts": {
"fields": ["id", "name", "currency", "balance"],
"cls": Account,
"id": ("id",),
"name": ("name", "название", "имя"),
"currency": ("currency", "валюта"),
"balance": ("balance", "баланс"),
},
"Transactions": {
"fields": ["id", "date", "account", "category", "amount", "description"],
"cls": Transaction,
"id": ("id",),
"date": ("date", "дата"),
"account": ("account", "счёт", "счет", "account_name"),
"category": ("category", "категория"),
"amount": ("amount", "сумма"),
"description": ("description", "описание", "комментарий"),
},
"Recurring": {
"fields": ["id", "start_date", "end_date", "frequency", "amount", "category"],
"cls": RecurringCashflow,
"id": ("id",),
"account": ("account", "счёт", "счет"),
"start_date": ("start_date", "дата_начала", "начало"),
"end_date": ("end_date", "дата_окончания", "конец"),
"frequency": ("frequency", "периодичность", "частота"),
"amount": ("amount", "сумма"),
"category": ("category", "категория"),
},
"Assets": {
"fields": ["id", "name", "value", "growth_rate"],
"cls": Asset,
"id": ("id",),
"name": ("name", "название"),
"value": ("value", "стоимость"),
"growth_rate": ("growth_rate", "рост", "доходность"),
},
"Liabilities": {
"fields": ["id", "name", "balance", "interest", "payment"],
"cls": Liability,
"id": ("id",),
"name": ("name", "название"),
"balance": ("balance", "баланс", "остаток"),
"interest": ("interest", "ставка", "процент"),
"payment": ("payment", "платёж", "платеж", "платёж_мес"),
},
"ExchangeRates": {
"fields": ["from_currency", "to_currency", "rate"],
"cls": ExchangeRate,
"from_currency": ("from_currency", "из", "валюта_из"),
"to_currency": ("to_currency", "в", "валюта_в"),
"rate": ("rate", "курс"),
},
}
# Тип значения канонического столбца.
FIELD_KINDS: dict[str, dict[str, str]] = {
"Accounts": {"id": "id", "name": "text", "currency": "currency", "balance": "decimal"},
"Transactions": {
"id": "id",
"date": "date",
"account": "account",
"category": "text",
"amount": "decimal",
"description": "text",
},
"Recurring": {
"id": "id",
"account": "account_optional",
"start_date": "date",
"end_date": "date",
"frequency": "frequency",
"amount": "decimal",
"category": "text",
},
"Assets": {"id": "id", "name": "text", "value": "decimal", "growth_rate": "decimal"},
"Liabilities": {
"id": "id",
"name": "text",
"balance": "decimal",
"interest": "decimal",
"payment": "decimal",
},
"ExchangeRates": {"from_currency": "currency", "to_currency": "currency", "rate": "decimal"},
}
_MONEY_FORMAT = "#,##0.00"
_RATE_FORMAT = "0.00"
_DATE_FORMAT = "yyyy-mm-dd"
# Форматы числовых ячеек: (лист, столбец) -> number_format.
CELL_NUMBER_FORMATS: dict[tuple[str, str], str] = {
("Accounts", "balance"): _MONEY_FORMAT,
("Transactions", "date"): _DATE_FORMAT,
("Transactions", "amount"): _MONEY_FORMAT,
("Recurring", "start_date"): _DATE_FORMAT,
("Recurring", "end_date"): _DATE_FORMAT,
("Recurring", "amount"): _MONEY_FORMAT,
("Assets", "value"): _MONEY_FORMAT,
("Assets", "growth_rate"): _RATE_FORMAT,
("Liabilities", "balance"): _MONEY_FORMAT,
("Liabilities", "interest"): _RATE_FORMAT,
("Liabilities", "payment"): _MONEY_FORMAT,
("ExchangeRates", "rate"): _RATE_FORMAT,
("Accounts", "currency"): "@",
}
COLUMN_WIDTHS: dict[str, int] = {
"id": 38,
"name": 26,
"currency": 10,
"balance": 16,
"date": 12,
"account": 22,
"category": 16,
"amount": 14,
"description": 40,
"start_date": 12,
"end_date": 12,
"frequency": 14,
"value": 16,
"growth_rate": 12,
"interest": 10,
"payment": 14,
"from_currency": 14,
"to_currency": 14,
"rate": 10,
"Property": 24,
"Value": 22,
}
_TARGETS: dict[str, str] = {
"Accounts": "accounts",
"Transactions": "transactions",
"Recurring": "recurring",
"Assets": "assets",
"Liabilities": "liabilities",
}
_SAVE_ATTR: dict[str, str] = {**_TARGETS, "ExchangeRates": "exchange_rates"}
_DATE_FORMATS = ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%Y/%m/%d", "%d-%m-%Y")
_FREQUENCIES = ("daily", "weekly", "monthly", "yearly")
_FREQUENCY_ALIASES = {
"день": "daily",
"ежедневно": "daily",
"неделя": "weekly",
"еженедельно": "weekly",
"месяц": "monthly",
"ежемесячно": "monthly",
"год": "yearly",
"ежегодно": "yearly",
}
_MAX_ERRORS = 100
_NON_NUMERIC = re.compile(r"[^0-9,.\-+]")
# ---------------------------------------------------------------------------
# Публичные типы
# ---------------------------------------------------------------------------
class ExcelRepositoryError(Exception):
"""Ошибка импорта/экспорта .xlsx (файл не найден, ошибки данных, шаблон есть)."""
@dataclass(frozen=True)
class ExcelRowError:
"""Одна ошибка строки листа (row — 1-based номер строки в Excel)."""
sheet: str
row: int
field: str
message: str
def __str__(self) -> str:
prefix = f"{self.sheet}!{self.row}"
if self.field:
prefix += f" [{self.field}]"
return f"{prefix}: {self.message}"
@dataclass
class ExcelImportResult:
"""Результат импорта: модель + накопленные ошибки строк + предупреждения."""
model: FinancialModel
errors: list[ExcelRowError] = field(default_factory=list)
warnings: list[str] = field(default_factory=list)
# ---------------------------------------------------------------------------
# Нормализация значений
# ---------------------------------------------------------------------------
def _norm_header(value: object) -> str:
"""Ключ заголовка: без регистра/пробелов/``_``/``-``, ё == е."""
if value is None:
return ""
text = str(value).strip().casefold().replace("ё", "е")
return re.sub(r"[\s_\-]+", "", text)
def _name_key(value: str) -> str:
return value.strip().casefold().replace("ё", "е")
def _is_empty(value: object) -> bool:
if value is None:
return True
if isinstance(value, str):
return not value.strip()
return False
def _parse_date(value: object) -> str:
"""Вернуть ISO-дату ``YYYY-MM-DD``; время отбрасывается. Иначе ValueError."""
if isinstance(value, datetime):
return value.date().isoformat()
if isinstance(value, date):
return value.isoformat()
text = str(value).strip()
if not text:
raise ValueError("пустая дата")
text = text.split("T", 1)[0]
if " " in text:
text = text.split(" ", 1)[0]
for fmt in _DATE_FORMATS:
try:
return datetime.strptime(text, fmt).date().isoformat()
except ValueError:
continue
raise ValueError(
f"некорректная дата '{value}' — используйте 2026-01-31, 31.01.2026, "
"31/01/2026, 2026/01/31 или 31-01-2026"
)
def _parse_decimal(value: object) -> Decimal:
"""Разобрать число из ячейки: NBSP/пробелы, запятая, символы валют, (скобки)."""
if isinstance(value, bool):
raise ValueError(f"некорректное число '{value}'")
if isinstance(value, (int, float, Decimal)):
number = Decimal(str(value))
if not number.is_finite():
raise ValueError(f"некорректное число '{value}'")
return number
text = str(value).strip()
if not text:
raise ValueError("пустое число")
negative = text.startswith("(") and text.endswith(")")
if negative:
text = text[1:-1]
text = text.replace("\u00a0", "").replace("\u202f", "")
text = _NON_NUMERIC.sub("", text) # пробелы, символы валют, проценты, буквы
text = text.replace("(", "").replace(")", "")
if not text or text in {"-", "+", ".", ","}:
raise ValueError(f"некорректное число '{value}'")
sign = -1 if negative else 1
if text[0] in "+-":
if text[0] == "-":
sign = -sign
text = text[1:]
if text.endswith(("-", "+")):
if text[-1] == "-":
sign = -sign
text = text[:-1]
if "-" in text or "+" in text:
raise ValueError(f"некорректное число '{value}'")
if "," in text and "." in text:
# Оба разделителя: запятая — тысячи, точка — десятичный (по спецификации).
text = text.replace(",", "")
elif "," in text:
if text.count(",") > 1:
text = text.replace(",", "") # 1,234,567 — запятые как тысячи
else:
text = text.replace(",", ".")
elif text.count(".") > 1:
text = text.replace(".", "")
try:
number = Decimal(text)
except InvalidOperation as exc:
raise ValueError(f"некорректное число '{value}'") from exc
if not number.is_finite():
raise ValueError(f"некорректное число '{value}'")
return number if sign > 0 else -number
def _convert_value(kind: str, value: object) -> tuple[object | None, str | None]:
"""Сконвертировать значение ячейки. Возвращает (значение, текст ошибки)."""
if kind == "id":
text = str(value).strip()
try:
return UUID(text), None
except ValueError:
return None, f"некорректный id '{text}' — ожидается UUID или пустая ячейка"
if kind == "text":
text = str(value).strip()
return (text or None), None
if kind == "currency":
text = str(value).strip().upper()
return (text or None), None
if kind == "date":
try:
return _parse_date(value), None
except ValueError as exc:
return None, str(exc)
if kind == "decimal":
try:
return _parse_decimal(value), None
except ValueError as exc:
return None, str(exc)
if kind == "frequency":
text = str(value).strip().casefold()
canonical = _FREQUENCY_ALIASES.get(text, text)
if canonical not in _FREQUENCIES:
return None, (
f"недопустимая периодичность '{value}' — используйте "
+ ", ".join(_FREQUENCIES)
)
return canonical, None
if kind in {"account", "account_optional"}:
return str(value).strip(), None
# Неизвестный тип — оставляем как есть.
return value, None
# ---------------------------------------------------------------------------
# Внутренние структуры
# ---------------------------------------------------------------------------
class _IssueCollector:
def __init__(self) -> None:
self.errors: list[ExcelRowError] = []
self.warnings: list[str] = []
self.truncated = False
def error(self, sheet: str, row: int, field_name: str, message: str) -> None:
if len(self.errors) >= _MAX_ERRORS:
self.truncated = True
return
self.errors.append(ExcelRowError(sheet=sheet, row=row, field=field_name, message=message))
def warn(self, message: str) -> None:
if message not in self.warnings:
self.warnings.append(message)
@dataclass
class _AccountIndex:
by_name: dict[str, str] = field(default_factory=dict)
by_id: set[str] = field(default_factory=set)
names: list[str] = field(default_factory=list)
def describe(self) -> str:
if not self.names:
return "(на листе Accounts нет счетов)"
return ", ".join(self.names)
# ---------------------------------------------------------------------------
# Репозиторий
# ---------------------------------------------------------------------------
class ExcelRepository(ModelRepository):
# -- импорт -------------------------------------------------------------
def load(self, path: str | Path) -> FinancialModel:
"""Прочитать модель; при ошибках данных поднять ``ExcelRepositoryError``."""
result = self.load_report(path)
if result.errors:
shown = "; ".join(str(e) for e in result.errors[:5])
tail = f"; … ещё {len(result.errors) - 5}" if len(result.errors) > 5 else ""
raise ExcelRepositoryError(
f"Не удалось импортировать Excel: {len(result.errors)} ошибок — {shown}{tail}"
)
return result.model
def load_report(self, path: str | Path) -> ExcelImportResult:
"""Прочитать модель, собрав ошибки строк вместо исключения."""
p = Path(path)
if not p.exists():
raise ExcelRepositoryError(f"File not found: {p}")
wb = load_workbook(p, read_only=True, data_only=True)
collector = _IssueCollector()
model = FinancialModel()
model.exchange_rates = []
for sheet_name, config in _SHEET_CONFIG.items():
if sheet_name not in wb.sheetnames:
continue
ws = wb[sheet_name]
rows = list(ws.iter_rows(values_only=True))
if len(rows) < 2:
continue
headers = [str(h).strip().lower() if h else "" for h in rows[0]]
for row in rows[1:]:
if not any(v is not None for v in row):
try:
wb = load_workbook(p, data_only=True)
except (BadZipFile, InvalidFileException, KeyError, OSError) as exc:
raise ExcelRepositoryError(f"Не удалось открыть Excel-файл {p}: {exc}") from exc
try:
self._read_model_info(wb, model)
accounts, index = self._read_accounts(wb, collector)
model.accounts = accounts
for sheet_name, attribute in _TARGETS.items():
if sheet_name == "Accounts":
continue
data = {}
for i, header in enumerate(headers):
val = row[i] if i < len(row) else None
if val is not None:
data[header] = str(val) if not isinstance(val, (int, float)) else val
self._add_to_model(model, sheet_name, data, config["cls"])
setattr(model, attribute, self._read_rows(wb, sheet_name, index, collector))
self._read_exchange_rates(wb, model, collector)
self._check_formulas(wb, p, collector)
finally:
wb.close()
if "ModelInfo" in wb.sheetnames:
ws = wb["ModelInfo"]
rows = list(ws.iter_rows(values_only=True))
for row in rows:
if row[0] and str(row[0]).strip().lower() == "base_currency" and len(row) > 1:
model.base_currency = str(row[1]).strip()
if collector.truncated:
collector.warn(f"ошибок больше {_MAX_ERRORS} — показаны первые {_MAX_ERRORS}")
wb.close()
return model
return ExcelImportResult(model=model, errors=collector.errors, warnings=collector.warnings)
# -- экспорт ------------------------------------------------------------
def save(self, model: FinancialModel, path: str | Path) -> None:
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
wb = Workbook()
wb.remove(wb.active)
collections = {
"Accounts": model.accounts,
"Transactions": model.transactions,
"Recurring": model.recurring,
"Assets": model.assets,
"Liabilities": model.liabilities,
"ExchangeRates": model.exchange_rates,
}
self._write_sheet(
wb,
"ModelInfo",
["Property", "Value"],
[["base_currency", model.base_currency]],
)
for sheet_name, items in collections.items():
config = _SHEET_CONFIG[sheet_name]
ws = wb.create_sheet(title=sheet_name)
ws.append(config["fields"])
for item in items:
row = [
str(getattr(item, f)) if isinstance(getattr(item, f), UUID)
else getattr(item, f)
for f in config["fields"]
]
ws.append(row)
ws_info = wb.create_sheet(title="ModelInfo")
ws_info.append(["Property", "Value"])
ws_info.append(["base_currency", model.base_currency])
name_by_id = {str(account.id): account.name for account in model.accounts}
for sheet_name in CANONICAL_COLUMNS:
items = getattr(model, _SAVE_ATTR[sheet_name], [])
rows = [self._row_values(sheet_name, item, name_by_id) for item in items]
self._write_sheet(wb, sheet_name, list(CANONICAL_COLUMNS[sheet_name]), rows)
wb.save(p)
def _add_to_model(self, model: FinancialModel, sheet_name: str, data: dict, cls) -> None:
# -- чтение -------------------------------------------------------------
def _read_model_info(self, wb, model: FinancialModel) -> None:
if "ModelInfo" not in wb.sheetnames:
return
for row in wb["ModelInfo"].iter_rows(values_only=True):
if not row or _is_empty(row[0]):
continue
if _norm_header(row[0]) in {"basecurrency", "базоваявалюта"} and len(row) > 1:
if not _is_empty(row[1]):
model.base_currency = str(row[1]).strip()
def _read_accounts(
self, wb, collector: _IssueCollector
) -> tuple[list[Account], _AccountIndex]:
accounts: list[tuple[int, Account]] = []
for row_number, data in self._sheet_rows(wb, "Accounts", collector):
instance = self._validate(Account, data, "Accounts", row_number, collector)
if instance is not None:
accounts.append((row_number, instance))
index = _AccountIndex()
first_row: dict[str, int] = {}
for row_number, account in accounts:
key = _name_key(account.name)
if key:
if key in index.by_name:
collector.warn(
f"Accounts: имя счёта '{account.name}' повторяется "
f"(строка {row_number}, первая — {first_row[key]}) — используется первый"
)
else:
index.by_name[key] = str(account.id)
index.names.append(account.name)
first_row[key] = row_number
index.by_id.add(str(account.id))
return [account for _, account in accounts], index
def _read_rows(
self, wb, sheet_name: str, index: _AccountIndex, collector: _IssueCollector
) -> list:
cls = {
"Transactions": Transaction,
"Recurring": RecurringCashflow,
"Assets": Asset,
"Liabilities": Liability,
}[sheet_name]
required_account = sheet_name == "Transactions"
accounts_field = "account" if sheet_name in {"Transactions", "Recurring"} else None
instances = []
for row_number, data in self._sheet_rows(wb, sheet_name, collector):
if accounts_field is not None:
reference = data.pop(accounts_field, None)
if not reference:
if required_account:
collector.error(
sheet_name,
row_number,
accounts_field,
"счёт обязателен — укажите имя счёта из листа Accounts; "
f"известные счета: {index.describe()}",
)
continue
data[accounts_field] = ""
else:
resolved = self._resolve_account(
reference, index, sheet_name, row_number, accounts_field, collector
)
if resolved is None:
continue
data[accounts_field] = resolved
instance = self._validate(cls, data, sheet_name, row_number, collector)
if instance is not None:
instances.append(instance)
return instances
def _read_exchange_rates(self, wb, model: FinancialModel, collector: _IssueCollector) -> None:
rates = []
for row_number, data in self._sheet_rows(wb, "ExchangeRates", collector):
instance = self._validate(ExchangeRate, data, "ExchangeRates", row_number, collector)
if instance is not None:
rates.append(instance)
if rates:
model.exchange_rates = rates
elif "ExchangeRates" not in wb.sheetnames:
collector.warn("ExchangeRates: лист отсутствует — используются курсы по умолчанию")
else:
collector.warn("ExchangeRates: нет строк с курсами — используются курсы по умолчанию")
def _resolve_account(
self,
reference: str,
index: _AccountIndex,
sheet_name: str,
row_number: int,
field_name: str,
collector: _IssueCollector,
) -> str | None:
text = str(reference).strip()
key = _name_key(text)
if key in index.by_name:
return index.by_name[key]
try:
instance = cls.model_validate(data)
except Exception as e:
raise ExcelRepositoryError(f"Failed to parse row in {sheet_name}: {e}") from e
if sheet_name == "Accounts":
model.accounts.append(instance)
elif sheet_name == "Transactions":
model.transactions.append(instance)
elif sheet_name == "Recurring":
model.recurring.append(instance)
elif sheet_name == "Assets":
model.assets.append(instance)
elif sheet_name == "Liabilities":
model.liabilities.append(instance)
elif sheet_name == "ExchangeRates":
model.exchange_rates.append(instance)
uuid = UUID(text)
except ValueError:
uuid = None
if uuid is not None and str(uuid) in index.by_id:
return str(uuid)
collector.error(
sheet_name,
row_number,
field_name,
f"неизвестный счёт '{text}'; известные счета: {index.describe()}",
)
return None
def _sheet_rows(self, wb, sheet_name: str, collector: _IssueCollector):
"""Отдать (номер_строки, данные) для листа; ошибки конверсии — в collector."""
if sheet_name not in wb.sheetnames:
return []
ws = wb[sheet_name]
header = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), ())
if not any(not _is_empty(value) for value in header):
return []
columns = self._map_columns(header, sheet_name, collector)
if not columns:
collector.warn(f"{sheet_name}: не найдено ни одного известного столбца — лист пропущен")
return []
rows = []
for offset, raw_row in enumerate(ws.iter_rows(min_row=2, values_only=True)):
row_number = offset + 2
if not any(not _is_empty(value) for value in raw_row):
continue
data: dict[str, object] = {}
row_ok = True
for field_name, column_index in columns.items():
value = raw_row[column_index] if column_index < len(raw_row) else None
if _is_empty(value):
continue
converted, error = _convert_value(FIELD_KINDS[sheet_name][field_name], value)
if error is not None:
collector.error(sheet_name, row_number, field_name, error)
row_ok = False
continue
if converted is not None:
data[field_name] = converted
if row_ok:
rows.append((row_number, data))
return rows
def _map_columns(
self, header: tuple, sheet_name: str, collector: _IssueCollector
) -> dict[str, int]:
lookup: dict[str, str] = {}
for canonical, aliases in _ALIASES[sheet_name].items():
for alias in aliases:
lookup[_norm_header(alias)] = canonical
columns: dict[str, int] = {}
for column_index, raw in enumerate(header):
key = _norm_header(raw)
if not key:
continue
canonical = lookup.get(key)
if canonical is None:
collector.warn(
f"{sheet_name}: неизвестный столбец '{str(raw).strip()}' — пропущен"
)
continue
if canonical in columns:
collector.warn(
f"{sheet_name}: столбец '{canonical}' задан дважды — используется первый"
)
continue
columns[canonical] = column_index
return columns
def _validate(self, cls, data: dict, sheet_name: str, row_number: int, collector: _IssueCollector):
try:
return cls.model_validate(data)
except ValidationError as exc:
for error in exc.errors():
field_name = ".".join(str(part) for part in error.get("loc", ()))
message = str(error.get("msg", "ошибка валидации"))
if message.startswith("Value error, "):
message = message[len("Value error, "):]
collector.error(sheet_name, row_number, field_name, message)
except (TypeError, ValueError) as exc:
collector.error(sheet_name, row_number, "", str(exc))
return None
# -- формулы ------------------------------------------------------------
def _check_formulas(self, wb_data, path: Path, collector: _IssueCollector) -> None:
wb_formulas = load_workbook(path, data_only=False)
try:
for ws in wb_formulas.worksheets:
cached_ws = wb_data[ws.title] if ws.title in wb_data.sheetnames else None
for row in ws.iter_rows():
for cell in row:
is_formula = cell.data_type == "f" or (
isinstance(cell.value, str) and cell.value.startswith("=")
)
if not is_formula:
continue
cached = cached_ws[cell.coordinate].value if cached_ws is not None else None
if cached is None:
collector.warn(
f"{ws.title}!{cell.row}: формула без сохранённого значения — "
"пересчитайте и сохраните файл в Excel"
)
finally:
wb_formulas.close()
# -- запись -------------------------------------------------------------
def _row_values(self, sheet_name: str, item, name_by_id: dict[str, str]) -> list:
values = []
for field_name in CANONICAL_COLUMNS[sheet_name]:
raw = getattr(item, field_name, None)
values.append(self._cell_value(sheet_name, field_name, raw, name_by_id))
return values
def _cell_value(self, sheet_name: str, field_name: str, raw, name_by_id: dict[str, str]):
kind = FIELD_KINDS[sheet_name][field_name]
if kind in {"account", "account_optional"}:
text = "" if raw is None else str(raw).strip()
if not text:
return None
# В Excel пишем имя счёта; неизвестную ссылку оставляем как есть.
return name_by_id.get(text, text)
if kind == "id":
return str(raw)
if kind == "date":
if _is_empty(raw):
return None
try:
return date.fromisoformat(_parse_date(raw))
except ValueError:
return str(raw)
if kind == "decimal":
return float(raw)
if _is_empty(raw):
return None
return str(raw) if not isinstance(raw, str) else raw
def _write_sheet(self, wb: Workbook, sheet_name: str, headers: list[str], rows: list[list]) -> None:
ws = wb.create_sheet(title=sheet_name)
ws.append(headers)
for cell in ws[1]:
cell.font = Font(bold=True)
for row in rows:
ws.append(row)
for column_index, field_name in enumerate(headers, start=1):
letter = get_column_letter(column_index)
ws.column_dimensions[letter].width = COLUMN_WIDTHS.get(field_name, 18)
number_format = CELL_NUMBER_FORMATS.get((sheet_name, field_name))
if number_format:
for row_number in range(2, len(rows) + 2):
ws.cell(row=row_number, column=column_index).number_format = number_format
ws.freeze_panes = "A2"
last_row = max(len(rows) + 1, 1)
ws.auto_filter.ref = f"A1:{get_column_letter(len(headers))}{last_row}"
__all__ = [
"CANONICAL_COLUMNS",
"CELL_NUMBER_FORMATS",
"COLUMN_WIDTHS",
"ExcelImportResult",
"ExcelRepository",
"ExcelRepositoryError",
"ExcelRowError",
"FIELD_KINDS",
"SHEET_ORDER",
]
@@ -0,0 +1,222 @@
"""Генератор пустого Excel-шаблона для ручного заполнения модели.
``write_template(path)`` создаёт .xlsx только с заголовками листов, форматами
чисел и выпадающими списками, плюс лист «Инструкция» на русском. Шаблон
импортируется без ошибок и даёт пустую ``FinancialModel``.
"""
from __future__ import annotations
from pathlib import Path
from openpyxl import Workbook
from openpyxl.styles import Font
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.datavalidation import DataValidation
from domain.currency import CURRENCY_DECIMALS
from infrastructure.repositories.excel_repository import (
CANONICAL_COLUMNS,
CELL_NUMBER_FORMATS,
COLUMN_WIDTHS,
FIELD_KINDS,
ExcelRepositoryError,
)
_TEMPLATE_ROWS = 500
_VALIDATION_ROWS = 1000
_ACCOUNT_RANGE = "=Accounts!$B$2:$B$500"
_INSTRUCTION_SHEET = "Инструкция"
_FREQUENCIES_EN = ("daily", "weekly", "monthly", "yearly")
_FREQUENCIES_RU = ("ежедневно", "еженедельно", "ежемесячно", "ежегодно")
# Подсказка по типу значения: (обязательно, формат / допустимые значения).
_KIND_HELP: dict[str, tuple[str, str]] = {
"id": ("нет", "UUID или пусто — id создаётся автоматически"),
"text": ("—", "текст"),
"currency": ("—", "код валюты: " + ", ".join(CURRENCY_DECIMALS)),
"decimal": ("—", "число, напр. 1 234,56"),
"date": ("—", "2026-01-31, 31.01.2026, 31/01/2026, 2026/01/31, 31-01-2026"),
"frequency": (
"—",
"daily / weekly / monthly / yearly "
"(ежедневно / еженедельно / ежемесячно / ежегодно)",
),
"account": ("да", "имя счёта из листа Accounts"),
"account_optional": ("нет", "имя счёта из Accounts; пусто = все счета"),
}
_REQUIRED: dict[tuple[str, str], bool] = {
("Accounts", "name"): True,
("Transactions", "date"): True,
("Transactions", "account"): True,
("Transactions", "amount"): True,
("Recurring", "start_date"): True,
("Recurring", "frequency"): True,
("Recurring", "amount"): True,
("Assets", "name"): True,
("Liabilities", "name"): True,
("ExchangeRates", "from_currency"): True,
("ExchangeRates", "to_currency"): True,
("ExchangeRates", "rate"): True,
}
def _column_index(sheet_name: str, field_name: str) -> int:
return CANONICAL_COLUMNS[sheet_name].index(field_name) + 1
def _list_validation(values: tuple[str, ...], *, prompt: str) -> DataValidation:
return DataValidation(
type="list",
formula1='"' + ",".join(values) + '"',
allow_blank=True,
showDropDown=False,
promptTitle="Допустимые значения",
prompt=prompt,
)
def _account_validation() -> DataValidation:
return DataValidation(
type="list",
formula1=_ACCOUNT_RANGE,
allow_blank=True,
showDropDown=False,
promptTitle="Счёт",
prompt="Имя счёта из листа Accounts",
)
def _write_columns_sheet(wb: Workbook, sheet_name: str) -> None:
headers = list(CANONICAL_COLUMNS[sheet_name])
ws = wb.create_sheet(title=sheet_name)
ws.append(headers)
for cell in ws[1]:
cell.font = Font(bold=True)
for column_index, field_name in enumerate(headers, start=1):
letter = get_column_letter(column_index)
ws.column_dimensions[letter].width = COLUMN_WIDTHS.get(field_name, 18)
number_format = CELL_NUMBER_FORMATS.get((sheet_name, field_name))
if number_format:
for row_number in range(2, _TEMPLATE_ROWS + 1):
ws.cell(row=row_number, column=column_index).number_format = number_format
ws.freeze_panes = "A2"
ws.auto_filter.ref = f"A1:{get_column_letter(len(headers))}{_TEMPLATE_ROWS}"
def _add_validations(wb: Workbook) -> None:
currency = _list_validation(tuple(CURRENCY_DECIMALS), prompt="Код валюты, напр. RUB")
accounts_ws = wb["Accounts"]
account_currency_col = get_column_letter(_column_index("Accounts", "currency"))
accounts_ws.add_data_validation(currency)
currency.add(f"{account_currency_col}2:{account_currency_col}{_VALIDATION_ROWS}")
transactions = wb["Transactions"]
tx_account_col = get_column_letter(_column_index("Transactions", "account"))
tx_account_validation = _account_validation()
transactions.add_data_validation(tx_account_validation)
tx_account_validation.add(f"{tx_account_col}2:{tx_account_col}{_VALIDATION_ROWS}")
recurring = wb["Recurring"]
rec_account_col = get_column_letter(_column_index("Recurring", "account"))
rec_frequency_col = get_column_letter(_column_index("Recurring", "frequency"))
rec_account_validation = _account_validation()
recurring.add_data_validation(rec_account_validation)
rec_account_validation.add(f"{rec_account_col}2:{rec_account_col}{_VALIDATION_ROWS}")
frequency = _list_validation(
_FREQUENCIES_EN + _FREQUENCIES_RU,
prompt="daily / weekly / monthly / yearly или ежедневно / еженедельно / ежемесячно / ежегодно",
)
recurring.add_data_validation(frequency)
frequency.add(f"{rec_frequency_col}2:{rec_frequency_col}{_VALIDATION_ROWS}")
def _instruction_rows() -> list[tuple[str, str, str, str]]:
rows: list[tuple[str, str, str, str]] = []
def line(text: str) -> None:
rows.append((text, "", "", ""))
line("Порядок работы")
line("1. Заполните листы Accounts, Transactions, Recurring, Assets, Liabilities, ExchangeRates.")
line("2. Сохраните файл в Excel — формулы должны быть пересчитаны и сохранены.")
line("3. Импортируйте модель командой: cf import-xlsx путь/к/файлу.xlsx")
line("")
line("Правила заполнения")
line("• id можно оставить пустым — идентификатор создаётся автоматически.")
line("• счёт указывается по имени из листа Accounts (регистр и лишние пробелы не важны).")
line("• пустой счёт в Recurring = платёж относится ко всем счетам.")
line("• сумма со знаком: положительная = доход, отрицательная = расход.")
line("• даты: 2026-01-31, 31.01.2026, 31/01/2026, 2026/01/31, 31-01-2026 (время отбрасывается).")
line("• числа: 1 234,56 или 1234.56; символы валют и пробелы игнорируются; (100) = -100.")
line("• валюта: " + ", ".join(CURRENCY_DECIMALS) + ".")
line(
"• периодичность: " + ", ".join(_FREQUENCIES_EN) + " (можно по-русски: "
+ ", ".join(_FREQUENCIES_RU) + ")."
)
line("")
rows.append(("Лист", "Столбец", "Обязательно", "Формат / допустимые значения"))
for sheet_name, fields in FIELD_KINDS.items():
for field_name, kind in fields.items():
required = "да" if _REQUIRED.get((sheet_name, field_name)) else _KIND_HELP[kind][0]
rows.append((sheet_name, field_name, required, _KIND_HELP[kind][1]))
return rows
def _write_instruction_sheet(wb: Workbook) -> None:
ws = wb.create_sheet(title=_INSTRUCTION_SHEET)
ws.column_dimensions["A"].width = 74
ws.column_dimensions["B"].width = 22
ws.column_dimensions["C"].width = 14
ws.column_dimensions["D"].width = 64
title = ws.cell(row=1, column=1, value="Инструкция: заполнение Excel-шаблона")
title.font = Font(bold=True, size=14)
for offset, values in enumerate(_instruction_rows(), start=2):
for column, value in enumerate(values, start=1):
ws.cell(row=offset, column=column, value=value or None)
if values[0] and not values[1] and not values[2] and not values[3]:
ws.cell(row=offset, column=1).font = Font(bold=True)
ws.freeze_panes = "A2"
def write_template(path: str | Path, *, force: bool = False) -> Path:
"""Создать пустой шаблон .xlsx. Существующий файл — ошибка, если не ``force``."""
target = Path(path)
if target.exists() and not force:
raise ExcelRepositoryError(
f"Файл уже существует: {target} — используйте force=True, чтобы перезаписать"
)
target.parent.mkdir(parents=True, exist_ok=True)
wb = Workbook()
wb.remove(wb.active)
wb.create_sheet(title="ModelInfo")
info_ws = wb["ModelInfo"]
info_ws.append(["Property", "Value"])
for cell in info_ws[1]:
cell.font = Font(bold=True)
info_ws.column_dimensions["A"].width = COLUMN_WIDTHS["Property"]
info_ws.column_dimensions["B"].width = COLUMN_WIDTHS["Value"]
info_ws.freeze_panes = "A2"
for sheet_name in CANONICAL_COLUMNS:
_write_columns_sheet(wb, sheet_name)
_add_validations(wb)
_write_instruction_sheet(wb)
wb.save(target)
return target
__all__ = ["write_template"]