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(
|
||||
|
||||
@@ -44,6 +44,28 @@ MESSAGES: dict[str, str] = {
|
||||
"{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств",
|
||||
"cmd.import.base_currency": "Базовая валюта: {currency}",
|
||||
"cmd.import.err": "Ошибка импорта: {error}",
|
||||
"cmd.import.warn": "Предупреждение: {warning}",
|
||||
"cmd.import.opt.dry_run": "Только проверить файл, не сохраняя модель",
|
||||
"cmd.import.dry_run.title": "Проверка файла (--dry-run):",
|
||||
"cmd.import.dry_run.ok": "В файле: счета — {accounts}, транзакции — {transactions}, "
|
||||
"регулярные платежи — {recurring}, активы — {assets}, обязательства — {liabilities}",
|
||||
"cmd.import.dry_run.base_currency": "Базовая валюта: {currency}",
|
||||
"cmd.import.dry_run.not_saved": "Модель не сохранена (--dry-run)",
|
||||
"cmd.import.errors.title": "Ошибки в файле: {count}",
|
||||
"cmd.import.errors.col.sheet": "Лист",
|
||||
"cmd.import.errors.col.row": "Строка",
|
||||
"cmd.import.errors.col.field": "Столбец",
|
||||
"cmd.import.errors.col.message": "Сообщение",
|
||||
"cmd.import.errors.hint": "Файл не сохранён. Первая ошибка: {first}",
|
||||
"cmd.import.backup": "Прежняя модель сохранена: {path}",
|
||||
"cmd.import.backup_failed": "Не удалось сохранить резервную копию модели: {error}",
|
||||
"cmd.template.help": "Создать Excel-шаблон для заполнения модели",
|
||||
"cmd.template.arg.path": "Путь для .xlsx файла",
|
||||
"cmd.template.opt.force": "Перезаписать существующий файл",
|
||||
"cmd.template.ok": "Шаблон создан: {path}",
|
||||
"cmd.template.hint": "Заполните шаблон и загрузите модель: {path}",
|
||||
"cmd.template.err": "Ошибка шаблона: {error}",
|
||||
"cmd.template.err.exists": "Файл уже существует: {path} — используйте --force",
|
||||
"cmd.export.help": "Экспорт модели в Excel",
|
||||
"cmd.export.arg.path": "Путь для .xlsx файла",
|
||||
"cmd.export.ok": "Модель экспортирована в {path}",
|
||||
|
||||
@@ -1,4 +1,19 @@
|
||||
from infrastructure.repositories.excel_repository import ExcelRepository, ExcelRepositoryError
|
||||
from infrastructure.repositories.excel_repository import (
|
||||
ExcelImportResult,
|
||||
ExcelRepository,
|
||||
ExcelRepositoryError,
|
||||
ExcelRowError,
|
||||
)
|
||||
from infrastructure.repositories.excel_template import TemplateError, write_template, write_workbook
|
||||
from infrastructure.repositories.json_file_repository import JsonFileRepository
|
||||
|
||||
__all__ = ["JsonFileRepository", "ExcelRepository", "ExcelRepositoryError"]
|
||||
__all__ = [
|
||||
"JsonFileRepository",
|
||||
"ExcelRepository",
|
||||
"ExcelRepositoryError",
|
||||
"ExcelImportResult",
|
||||
"ExcelRowError",
|
||||
"TemplateError",
|
||||
"write_template",
|
||||
"write_workbook",
|
||||
]
|
||||
@@ -1,194 +1,516 @@
|
||||
"""ExcelRepository — хранит FinancialModel в .xlsx.
|
||||
"""ExcelRepository — .xlsx как поверхность сборки модели (D35).
|
||||
|
||||
Состав листов, порядок полей и классы моделей описаны одной декларативной
|
||||
таблицей `SHEETS` (D28). `save()` и `load()` идут по этой таблице, поэтому
|
||||
новый лист добавляется одной записью в `SHEETS` — без новых веток
|
||||
`if sheet_name == ...` в коде записи или чтения.
|
||||
Файл читается терпимо: заголовки принимаются на русском и английском в любом
|
||||
порядке и регистре, числа — в пользовательских форматах («1 234,56», «₽1200»,
|
||||
«(100)» = −100), даты — и как даты Excel, и как текст. Ошибки строк не
|
||||
роняют импорт: они собираются в отчёт с адресом «лист!строка», и файл с
|
||||
ошибками не сохраняется.
|
||||
|
||||
Листы данных: Accounts, Transactions, Recurring, Assets, Liabilities,
|
||||
ExchangeRates, Scenarios. Плюс служебный лист ModelInfo (base_currency).
|
||||
Публичный контракт:
|
||||
|
||||
- ``ExcelRepository.load(path)`` — модель или ``ExcelRepositoryError``;
|
||||
- ``ExcelRepository.load_report(path)`` — модель + ошибки + предупреждения;
|
||||
- ``ExcelRepository.save(model, path)`` — записать модель в .xlsx.
|
||||
|
||||
Устройство листов описано в `excel_schema` (таблица `SHEETS`) — она же
|
||||
источник заголовков, синонимов и типов значений (D28).
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
from __future__ import annotations
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from pydantic import BaseModel
|
||||
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 load_workbook
|
||||
from openpyxl.utils.exceptions import InvalidFileException
|
||||
from pydantic import ValidationError
|
||||
|
||||
from application.repositories.model_repository import ModelRepository
|
||||
from domain import (
|
||||
Account,
|
||||
Asset,
|
||||
ExchangeRate,
|
||||
FinancialModel,
|
||||
ForecastScenario,
|
||||
Liability,
|
||||
RecurringCashflow,
|
||||
Transaction,
|
||||
from domain import Account, FinancialModel
|
||||
from domain.recurrence import normalize_frequency
|
||||
from infrastructure.repositories.excel_schema import (
|
||||
ACCOUNT,
|
||||
ACCOUNT_OPTIONAL,
|
||||
CURRENCY,
|
||||
DATE,
|
||||
DECIMAL,
|
||||
FREQUENCY,
|
||||
ID,
|
||||
SHEETS,
|
||||
Column,
|
||||
InfoSheetSpec,
|
||||
SheetSpec,
|
||||
build_header_index,
|
||||
is_empty,
|
||||
)
|
||||
from infrastructure.repositories.excel_template import TemplateError, write_workbook
|
||||
|
||||
_MAX_ERRORS = 100
|
||||
_NON_NUMERIC = re.compile(r"[^0-9,.\-+]")
|
||||
|
||||
# Частота: русские синонимы приводятся к канону (domain.recurrence).
|
||||
_FREQUENCY_HELP = "daily / weekly / monthly / yearly (или ежедневно / еженедельно / ежемесячно / ежегодно)"
|
||||
|
||||
|
||||
class ExcelRepositoryError(Exception):
|
||||
pass
|
||||
"""Ошибка импорта/экспорта .xlsx (файл не найден, ошибки данных, каталог)."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SheetSpec:
|
||||
"""Описание листа-коллекции.
|
||||
class ExcelRowError:
|
||||
"""Одна ошибка строки листа (row — 1-based номер строки в Excel)."""
|
||||
|
||||
`fields` задаёт и заголовки, и порядок колонок; `collection` — имя поля
|
||||
`FinancialModel`, в которое читаются строки и из которого они пишутся.
|
||||
Специфику полей (например, отсутствие `id` у `ExchangeRates`) описывает
|
||||
сам список `fields`, отдельного кода для этого не нужно.
|
||||
"""
|
||||
sheet: str
|
||||
row: int
|
||||
field: str
|
||||
message: str
|
||||
|
||||
name: str
|
||||
fields: tuple[str, ...]
|
||||
cls: type[BaseModel]
|
||||
collection: str
|
||||
def __str__(self) -> str:
|
||||
prefix = f"{self.sheet}!{self.row}"
|
||||
if self.field:
|
||||
prefix += f" [{self.field}]"
|
||||
return f"{prefix}: {self.message}"
|
||||
|
||||
def write(self, wb: Workbook, model: FinancialModel) -> None:
|
||||
ws = wb.create_sheet(title=self.name)
|
||||
ws.append(list(self.fields))
|
||||
for item in getattr(model, self.collection):
|
||||
ws.append([_cell(getattr(item, field)) for field in self.fields])
|
||||
|
||||
def read(self, wb: Workbook, model: FinancialModel) -> None:
|
||||
if self.name not in wb.sheetnames:
|
||||
return
|
||||
rows = list(wb[self.name].iter_rows(values_only=True))
|
||||
if len(rows) < 2:
|
||||
@dataclass
|
||||
class ExcelImportResult:
|
||||
"""Результат импорта: модель + ошибки строк + предупреждения."""
|
||||
|
||||
model: FinancialModel
|
||||
errors: list[ExcelRowError] = field(default_factory=list)
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
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))
|
||||
|
||||
headers = _headers(rows[0])
|
||||
for row in rows[1:]:
|
||||
if not any(value is not None for value in row):
|
||||
continue
|
||||
data = _row_data(headers, row)
|
||||
getattr(model, self.collection).append(_parse_row(self.name, self.cls, data))
|
||||
def warn(self, message: str) -> None:
|
||||
if message not in self.warnings:
|
||||
self.warnings.append(message)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InfoSheetSpec:
|
||||
"""Служебный лист «свойство → значение» (ModelInfo)."""
|
||||
|
||||
name: str = "ModelInfo"
|
||||
properties: tuple[tuple[str, str], ...] = (("base_currency", "base_currency"),)
|
||||
|
||||
def write(self, wb: Workbook, model: FinancialModel) -> None:
|
||||
ws = wb.create_sheet(title=self.name)
|
||||
ws.append(["Property", "Value"])
|
||||
for prop, attr in self.properties:
|
||||
ws.append([prop, getattr(model, attr)])
|
||||
|
||||
def read(self, wb: Workbook, model: FinancialModel) -> None:
|
||||
if self.name not in wb.sheetnames:
|
||||
return
|
||||
attrs = dict(self.properties)
|
||||
for row in wb[self.name].iter_rows(values_only=True):
|
||||
if not row or row[0] is None or len(row) < 2:
|
||||
continue
|
||||
attr = attrs.get(str(row[0]).strip().lower())
|
||||
if attr is not None:
|
||||
setattr(model, attr, str(row[1]).strip())
|
||||
# ---------------------------------------------------------------------------
|
||||
# Разбор значений ячеек
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
# Единственный источник истины о листах Excel (D28). Порядок записей —
|
||||
# порядок листов в книге.
|
||||
SHEETS: tuple[SheetSpec | InfoSheetSpec, ...] = (
|
||||
SheetSpec("Accounts", ("id", "name", "currency", "balance"), Account, "accounts"),
|
||||
SheetSpec(
|
||||
"Transactions",
|
||||
("id", "date", "account", "category", "amount", "description"),
|
||||
Transaction,
|
||||
"transactions",
|
||||
),
|
||||
SheetSpec(
|
||||
"Recurring",
|
||||
("id", "start_date", "end_date", "frequency", "amount", "category"),
|
||||
RecurringCashflow,
|
||||
"recurring",
|
||||
),
|
||||
SheetSpec("Assets", ("id", "name", "value", "growth_rate"), Asset, "assets"),
|
||||
SheetSpec("Liabilities", ("id", "name", "balance", "interest", "payment"), Liability, "liabilities"),
|
||||
SheetSpec("ExchangeRates", ("from_currency", "to_currency", "rate"), ExchangeRate, "exchange_rates"),
|
||||
SheetSpec(
|
||||
"Scenarios",
|
||||
("id", "name", "income_multiplier", "expense_multiplier", "growth_multiplier", "description"),
|
||||
ForecastScenario,
|
||||
"scenarios",
|
||||
),
|
||||
InfoSheetSpec(),
|
||||
)
|
||||
def parse_decimal(value: object) -> Decimal:
|
||||
"""Разобрать число из ячейки: пробелы, запятая, символы валют, скобки."""
|
||||
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("пустое число")
|
||||
|
||||
def _cell(value: Any) -> Any:
|
||||
"""Значение для записи в ячейку: UUID сериализуется строкой."""
|
||||
return str(value) if isinstance(value, UUID) else value
|
||||
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}»")
|
||||
|
||||
def _headers(header_row: tuple) -> list[str]:
|
||||
return [str(header).strip().lower() if header else "" for header in header_row]
|
||||
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(".", "")
|
||||
|
||||
|
||||
def _row_data(headers: list[str], row: tuple) -> dict[str, Any]:
|
||||
data: dict[str, Any] = {}
|
||||
for i, header in enumerate(headers):
|
||||
value = row[i] if i < len(row) else None
|
||||
if value is not None:
|
||||
data[header] = str(value) if not isinstance(value, (int, float)) else value
|
||||
return data
|
||||
|
||||
|
||||
def _parse_row(sheet_name: str, cls: type[BaseModel], data: dict[str, Any]) -> BaseModel:
|
||||
try:
|
||||
return cls.model_validate(data)
|
||||
except Exception as e:
|
||||
raise ExcelRepositoryError(f"Не удалось разобрать строку листа {sheet_name}: {e}") from e
|
||||
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 parse_date_cell(value: object) -> str:
|
||||
"""Разобрать дату в ISO-формате `YYYY-MM-DD`."""
|
||||
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 ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%Y/%m/%d", "%d-%m-%Y"):
|
||||
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_id_cell(value: object) -> UUID | None:
|
||||
"""Разобрать UUID. Пустая ячейка — «сгенерировать автоматически»."""
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return UUID(text)
|
||||
except ValueError:
|
||||
raise ValueError(f"некорректный ID «{text}» — ожидается UUID или пустая ячейка") from None
|
||||
|
||||
|
||||
def convert_cell(kind: str, value: object) -> object:
|
||||
"""Привести значение ячейки к типу столбца. Бросает ValueError с текстом."""
|
||||
if kind == ID:
|
||||
return parse_id_cell(value)
|
||||
if kind == DECIMAL:
|
||||
return parse_decimal(value)
|
||||
if kind == DATE:
|
||||
return parse_date_cell(value)
|
||||
if kind == CURRENCY:
|
||||
return str(value).strip().upper() or None
|
||||
if kind == FREQUENCY:
|
||||
text = str(value).strip()
|
||||
try:
|
||||
return normalize_frequency(text)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{exc} — {_FREQUENCY_HELP}") from None
|
||||
if kind in {ACCOUNT, ACCOUNT_OPTIONAL}:
|
||||
return str(value).strip()
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Индекс счетов
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class _AccountIndex:
|
||||
"""Счета, найденные на листе Accounts: по имени и по UUID."""
|
||||
|
||||
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)
|
||||
|
||||
def resolve(self, reference: str) -> str | None:
|
||||
"""UUID счёта по имени или UUID. ``None`` — счёт не найден."""
|
||||
text = str(reference).strip()
|
||||
if not text:
|
||||
return None
|
||||
key = text.casefold().replace("ё", "е")
|
||||
if key in self.by_name:
|
||||
return self.by_name[key]
|
||||
try:
|
||||
uuid = UUID(text)
|
||||
except ValueError:
|
||||
return None
|
||||
if str(uuid) in self.by_id:
|
||||
return str(uuid)
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Репозиторий
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ExcelRepository(ModelRepository):
|
||||
# -- импорт -------------------------------------------------------------
|
||||
|
||||
def load(self, path: str | Path) -> FinancialModel:
|
||||
p = Path(path)
|
||||
if not p.exists():
|
||||
raise ExcelRepositoryError(f"Файл не найден: {p}")
|
||||
"""Прочитать модель; при ошибках данных поднять ``ExcelRepositoryError``."""
|
||||
result = self.load_report(path)
|
||||
if result.errors:
|
||||
shown = "; ".join(str(error) for error 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:
|
||||
"""Прочитать модель, собрав ошибки строк вместо исключения."""
|
||||
file_path = Path(path)
|
||||
if not file_path.exists():
|
||||
raise ExcelRepositoryError(f"Файл не найден: {file_path}")
|
||||
|
||||
collector = _IssueCollector()
|
||||
model = FinancialModel()
|
||||
|
||||
wb = load_workbook(p, read_only=True, data_only=True)
|
||||
try:
|
||||
model = FinancialModel()
|
||||
# Курсы валют заданы DEFAULT_RATES; лист ExchangeRates их заменяет.
|
||||
model.exchange_rates = []
|
||||
workbook = load_workbook(file_path, data_only=True)
|
||||
except (BadZipFile, InvalidFileException, KeyError, OSError) as exc:
|
||||
raise ExcelRepositoryError(f"Не удалось открыть Excel-файл {file_path}: {exc}") from exc
|
||||
|
||||
try:
|
||||
self._read_info_sheet(workbook, model)
|
||||
accounts, index = self._read_accounts(workbook, collector)
|
||||
model.accounts = accounts
|
||||
for spec in SHEETS:
|
||||
spec.read(wb, model)
|
||||
if not isinstance(spec, SheetSpec) or spec.collection == "accounts":
|
||||
continue
|
||||
setattr(model, spec.collection, self._read_sheet(spec, workbook, index, collector))
|
||||
self._check_formulas(file_path, workbook, collector)
|
||||
finally:
|
||||
wb.close()
|
||||
return model
|
||||
workbook.close()
|
||||
|
||||
if collector.truncated:
|
||||
collector.warn(f"ошибок больше {_MAX_ERRORS} — показаны первые {_MAX_ERRORS}")
|
||||
|
||||
return ExcelImportResult(model=model, errors=collector.errors, warnings=collector.warnings)
|
||||
|
||||
def _read_info_sheet(self, workbook, model: FinancialModel) -> None:
|
||||
"""Прочитать ModelInfo: «свойство → значение»."""
|
||||
for spec in SHEETS:
|
||||
if not isinstance(spec, InfoSheetSpec):
|
||||
continue
|
||||
if spec.name not in workbook.sheetnames:
|
||||
continue
|
||||
accepted = spec.accepted_keys()
|
||||
for row in workbook[spec.name].iter_rows(values_only=True):
|
||||
if not row or is_empty(row[0]) or len(row) < 2:
|
||||
continue
|
||||
key = str(row[0]).strip().casefold().replace("ё", "е")
|
||||
attribute = accepted.get(_normalize_key(key))
|
||||
if attribute is None:
|
||||
continue
|
||||
# Пустая ячейка — свойство не задано: иначе в модель попало
|
||||
# бы «None» строкой.
|
||||
if is_empty(row[1]):
|
||||
continue
|
||||
setattr(model, attribute, str(row[1]).strip().upper())
|
||||
|
||||
def _read_accounts(self, workbook, collector: _IssueCollector) -> tuple[list[Account], _AccountIndex]:
|
||||
accounts: list[Account] = []
|
||||
index = _AccountIndex()
|
||||
first_row: dict[str, int] = {}
|
||||
for spec in SHEETS:
|
||||
if not isinstance(spec, SheetSpec) or spec.collection != "accounts":
|
||||
continue
|
||||
for row_number, data in self._read_rows(spec, workbook, collector):
|
||||
instance = self._validate(spec, data, row_number, collector)
|
||||
if instance is None:
|
||||
continue
|
||||
accounts.append(instance)
|
||||
key = instance.name.strip().casefold().replace("ё", "е")
|
||||
if key:
|
||||
if key in index.by_name:
|
||||
collector.warn(
|
||||
f"Accounts: имя счёта «{instance.name}» повторяется "
|
||||
f"(строка {row_number}, первая — {first_row[key]}) — используется первая"
|
||||
)
|
||||
else:
|
||||
index.by_name[key] = str(instance.id)
|
||||
index.names.append(instance.name)
|
||||
first_row[key] = row_number
|
||||
index.by_id.add(str(instance.id))
|
||||
return accounts, index
|
||||
|
||||
def _read_sheet(
|
||||
self,
|
||||
spec: SheetSpec,
|
||||
workbook,
|
||||
index: _AccountIndex,
|
||||
collector: _IssueCollector,
|
||||
) -> list:
|
||||
instances = []
|
||||
for row_number, data in self._read_rows(spec, workbook, collector):
|
||||
if spec.collection in {"transactions", "recurring"}:
|
||||
reference = data.get("account")
|
||||
if reference is not None:
|
||||
resolved = index.resolve(reference)
|
||||
if resolved is None:
|
||||
collector.error(
|
||||
spec.name,
|
||||
row_number,
|
||||
"account",
|
||||
f"неизвестный счёт «{reference}»; известные счета: {index.describe()}",
|
||||
)
|
||||
continue
|
||||
data["account"] = resolved
|
||||
instance = self._validate(spec, data, row_number, collector)
|
||||
if instance is not None:
|
||||
instances.append(instance)
|
||||
return instances
|
||||
|
||||
def _read_rows(
|
||||
self,
|
||||
spec: SheetSpec,
|
||||
workbook,
|
||||
collector: _IssueCollector,
|
||||
) -> list[tuple[int, dict]]:
|
||||
"""Строки листа как пары (номер строки, данные по полям)."""
|
||||
if spec.name not in workbook.sheetnames:
|
||||
collector.warn(f"{spec.name}: лист отсутствует")
|
||||
return []
|
||||
|
||||
sheet = workbook[spec.name]
|
||||
header = next(sheet.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(spec, header, collector)
|
||||
if not columns:
|
||||
collector.warn(f"{spec.name}: не найдено ни одного известного столбца — лист пропущен")
|
||||
return []
|
||||
|
||||
rows: list[tuple[int, dict]] = []
|
||||
for offset, raw_row in enumerate(sheet.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 column, column_index in columns.items():
|
||||
value = raw_row[column_index] if column_index < len(raw_row) else None
|
||||
if is_empty(value):
|
||||
continue
|
||||
try:
|
||||
converted = convert_cell(column.kind, value)
|
||||
except ValueError as exc:
|
||||
collector.error(spec.name, row_number, column.field, str(exc))
|
||||
row_ok = False
|
||||
continue
|
||||
if converted is not None:
|
||||
data[column.field] = converted
|
||||
if row_ok:
|
||||
rows.append((row_number, data))
|
||||
return rows
|
||||
|
||||
def _map_columns(
|
||||
self,
|
||||
spec: SheetSpec,
|
||||
header: tuple,
|
||||
collector: _IssueCollector,
|
||||
) -> dict[Column, int]:
|
||||
index = build_header_index(spec)
|
||||
columns: dict[Column, int] = {}
|
||||
for column_index, raw in enumerate(header):
|
||||
if is_empty(raw):
|
||||
continue
|
||||
key = _normalize_key(str(raw))
|
||||
column = index.get(key)
|
||||
if column is None:
|
||||
collector.warn(f"{spec.name}: неизвестный столбец «{str(raw).strip()}» — пропущен")
|
||||
continue
|
||||
if column in columns:
|
||||
collector.warn(f"{spec.name}: столбец «{column.header}» задан дважды — используется первый")
|
||||
continue
|
||||
columns[column] = column_index
|
||||
return columns
|
||||
|
||||
def _validate(
|
||||
self,
|
||||
spec: SheetSpec,
|
||||
data: dict,
|
||||
row_number: int,
|
||||
collector: _IssueCollector,
|
||||
):
|
||||
try:
|
||||
return spec.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(spec.name, row_number, field_name, message)
|
||||
except (TypeError, ValueError) as exc:
|
||||
collector.error(spec.name, row_number, "", str(exc))
|
||||
return None
|
||||
|
||||
def _check_formulas(self, file_path: Path, workbook, collector: _IssueCollector) -> None:
|
||||
"""Предупредить о формулах без сохранённого значения (Excel не пересчитал)."""
|
||||
try:
|
||||
formulas = load_workbook(file_path, data_only=False)
|
||||
except (BadZipFile, InvalidFileException, OSError):
|
||||
return
|
||||
try:
|
||||
for sheet in formulas.worksheets:
|
||||
cached_sheet = workbook[sheet.title] if sheet.title in workbook.sheetnames else None
|
||||
for row in sheet.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_sheet[cell.coordinate].value if cached_sheet is not None else None
|
||||
if cached is None:
|
||||
collector.warn(
|
||||
f"{sheet.title}!{cell.row}: формула без сохранённого значения — "
|
||||
"пересчитайте и сохраните файл в Excel"
|
||||
)
|
||||
finally:
|
||||
formulas.close()
|
||||
|
||||
# -- экспорт ------------------------------------------------------------
|
||||
|
||||
def save(self, model: FinancialModel, path: str | Path) -> None:
|
||||
p = Path(path)
|
||||
self._ensure_parent_dir(p)
|
||||
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active)
|
||||
for spec in SHEETS:
|
||||
spec.write(wb, model)
|
||||
|
||||
"""Записать модель в .xlsx (файл пригоден для правки и обратного импорта)."""
|
||||
try:
|
||||
wb.save(p)
|
||||
except OSError as e:
|
||||
raise ExcelRepositoryError(f"Не удалось сохранить файл {p}: {e}") from e
|
||||
write_workbook(model, path, force=True, sheets=SHEETS)
|
||||
except TemplateError as exc:
|
||||
raise ExcelRepositoryError(str(exc)) from exc
|
||||
|
||||
@staticmethod
|
||||
def _ensure_parent_dir(p: Path) -> None:
|
||||
"""Создать родительский каталог файла, если его нет (D19).
|
||||
|
||||
Раньше экспорт в несуществующий каталог падал с сырым
|
||||
`FileNotFoundError` из openpyxl — без понятного сообщения.
|
||||
"""
|
||||
parent = p.parent
|
||||
try:
|
||||
parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as e:
|
||||
raise ExcelRepositoryError(f"Не удалось создать каталог {parent}: {e}") from e
|
||||
def _normalize_key(value: str) -> str:
|
||||
"""Ключ заголовка/свойства: без пробелов, ``_`` и ``-``; «ё» == «е»."""
|
||||
text = value.strip().casefold().replace("ё", "е")
|
||||
return re.sub(r"[\s_\-]+", "", text)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ExcelImportResult",
|
||||
"ExcelRepository",
|
||||
"ExcelRepositoryError",
|
||||
"ExcelRowError",
|
||||
"SHEETS",
|
||||
"parse_date_cell",
|
||||
"parse_decimal",
|
||||
]
|
||||
@@ -0,0 +1,256 @@
|
||||
"""Схема листов Excel — единственный источник истины (D28, D35).
|
||||
|
||||
Таблица `SHEETS` описывает и запись, и чтение: список листов, их порядок,
|
||||
заголовки столбцов, принимаемые синонимы заголовков и типы значений.
|
||||
|
||||
Заголовки — русские (D19: всё, что видит пользователь, — на русском), но
|
||||
импорт принимает и английские синонимы, и любой порядок столбцов, и любой
|
||||
регистр: `_`/`-`/пробелы и «ё» не важны.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from domain import (
|
||||
Account,
|
||||
Asset,
|
||||
ExchangeRate,
|
||||
ForecastScenario,
|
||||
Liability,
|
||||
RecurringCashflow,
|
||||
Transaction,
|
||||
)
|
||||
|
||||
# Типы значений в ячейках.
|
||||
TEXT = "text"
|
||||
DECIMAL = "decimal"
|
||||
DATE = "date"
|
||||
CURRENCY = "currency"
|
||||
ID = "id"
|
||||
FREQUENCY = "frequency"
|
||||
ACCOUNT = "account"
|
||||
ACCOUNT_OPTIONAL = "account_optional"
|
||||
|
||||
# Форматы чисел и дат в Excel.
|
||||
MONEY_FORMAT = "#,##0.00"
|
||||
RATE_FORMAT = "0.00"
|
||||
PERCENT_FORMAT = "0.00"
|
||||
DATE_FORMAT = "yyyy-mm-dd"
|
||||
TEXT_FORMAT = "@"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Column:
|
||||
"""Столбец листа Excel.
|
||||
|
||||
`field` — имя поля модели; `header` — заголовок, который видит человек;
|
||||
`kind` — тип значения (разбор при импорте); `aliases` — дополнительные
|
||||
заголовки, которые принимаются при импорте.
|
||||
"""
|
||||
|
||||
field: str
|
||||
header: str
|
||||
kind: str = TEXT
|
||||
aliases: tuple[str, ...] = ()
|
||||
number_format: str = ""
|
||||
|
||||
def accepted_headers(self) -> tuple[str, ...]:
|
||||
"""Все варианты заголовка, которые принимает импорт."""
|
||||
return (self.header, self.field, *self.aliases)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SheetSpec:
|
||||
"""Описание листа-коллекции.
|
||||
|
||||
`fields` — имена полей модели (в порядке колонок); `columns` — расширенное
|
||||
описание (заголовок, тип, синонимы). Если `columns` не задан, строится
|
||||
из `fields` — лист с заголовками в стиле модели.
|
||||
"""
|
||||
|
||||
name: str
|
||||
fields: tuple[str, ...]
|
||||
cls: type[BaseModel]
|
||||
collection: str
|
||||
columns: tuple[Column, ...] = ()
|
||||
|
||||
def resolved_columns(self) -> tuple[Column, ...]:
|
||||
if self.columns:
|
||||
return self.columns
|
||||
return tuple(Column(field=field, header=field) for field in self.fields)
|
||||
|
||||
@property
|
||||
def headers(self) -> tuple[str, ...]:
|
||||
return tuple(column.header for column in self.resolved_columns())
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InfoSheetSpec:
|
||||
"""Служебный лист «свойство → значение» (ModelInfo)."""
|
||||
|
||||
name: str = "ModelInfo"
|
||||
# (свойство модели, ключ в файле, подпись для человека)
|
||||
properties: tuple[tuple[str, str, str], ...] = (
|
||||
("base_currency", "base_currency", "Базовая валюта"),
|
||||
("display_currency", "display_currency", "Валюта вывода"),
|
||||
)
|
||||
|
||||
@property
|
||||
def headers(self) -> tuple[str, ...]:
|
||||
return ("Свойство", "Значение")
|
||||
|
||||
def accepted_keys(self) -> dict[str, str]:
|
||||
"""Ключ свойства → атрибут модели (принимаются и подписи, и ключи)."""
|
||||
mapping: dict[str, str] = {}
|
||||
for attr, key, label in self.properties:
|
||||
for variant in (key, attr, label, label.casefold()):
|
||||
mapping[_normalize_header(variant)] = attr
|
||||
return mapping
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Таблица листов
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SHEETS: tuple[SheetSpec | InfoSheetSpec, ...] = (
|
||||
SheetSpec(
|
||||
"Accounts",
|
||||
("id", "name", "currency", "balance"),
|
||||
Account,
|
||||
"accounts",
|
||||
columns=(
|
||||
Column("id", "ID", ID, ("ид", "идентификатор")),
|
||||
Column("name", "Название", TEXT, ("имя", "наименование")),
|
||||
Column("currency", "Валюта", CURRENCY, ("код валюты", "валюта счёта")),
|
||||
Column("balance", "Баланс", DECIMAL, ("остаток", "остаток счёта"), MONEY_FORMAT),
|
||||
),
|
||||
),
|
||||
SheetSpec(
|
||||
"Transactions",
|
||||
("id", "date", "account", "category", "amount", "description", "currency"),
|
||||
Transaction,
|
||||
"transactions",
|
||||
columns=(
|
||||
Column("id", "ID", ID, ("ид", "идентификатор")),
|
||||
Column("date", "Дата", DATE, ("дата операции", "дата транзакции"), DATE_FORMAT),
|
||||
Column("account", "Счёт", ACCOUNT, ("счет", "имя счёта", "account_name")),
|
||||
Column("category", "Категория", TEXT, ("категория операции",)),
|
||||
Column("amount", "Сумма", DECIMAL, ("сумма операции",), MONEY_FORMAT),
|
||||
Column("description", "Описание", TEXT, ("комментарий", "примечание")),
|
||||
Column("currency", "Валюта", CURRENCY, ("валюта операции",)),
|
||||
),
|
||||
),
|
||||
SheetSpec(
|
||||
"Recurring",
|
||||
("id", "account", "start_date", "end_date", "frequency", "amount", "category", "currency"),
|
||||
RecurringCashflow,
|
||||
"recurring",
|
||||
columns=(
|
||||
Column("id", "ID", ID, ("ид", "идентификатор")),
|
||||
Column("account", "Счёт", ACCOUNT_OPTIONAL, ("счет", "имя счёта")),
|
||||
Column("start_date", "Начало", DATE, ("дата начала",), DATE_FORMAT),
|
||||
Column("end_date", "Конец", DATE, ("дата окончания",), DATE_FORMAT),
|
||||
Column(
|
||||
"frequency",
|
||||
"Периодичность",
|
||||
FREQUENCY,
|
||||
("частота", "период"),
|
||||
),
|
||||
Column("amount", "Сумма", DECIMAL, ("сумма платежа",), MONEY_FORMAT),
|
||||
Column("category", "Категория", TEXT, ("категория платежа",)),
|
||||
Column("currency", "Валюта", CURRENCY, ("валюта платежа",)),
|
||||
),
|
||||
),
|
||||
SheetSpec(
|
||||
"Assets",
|
||||
("id", "name", "value", "growth_rate", "currency"),
|
||||
Asset,
|
||||
"assets",
|
||||
columns=(
|
||||
Column("id", "ID", ID, ("ид", "идентификатор")),
|
||||
Column("name", "Название", TEXT, ("имя", "наименование")),
|
||||
Column("value", "Стоимость", DECIMAL, ("стоимость актива",), MONEY_FORMAT),
|
||||
Column("growth_rate", "Рост %", DECIMAL, ("рост", "доходность", "годовой рост"), PERCENT_FORMAT),
|
||||
Column("currency", "Валюта", CURRENCY, ("валюта актива",)),
|
||||
),
|
||||
),
|
||||
SheetSpec(
|
||||
"Liabilities",
|
||||
("id", "name", "balance", "interest", "payment", "currency"),
|
||||
Liability,
|
||||
"liabilities",
|
||||
columns=(
|
||||
Column("id", "ID", ID, ("ид", "идентификатор")),
|
||||
Column("name", "Название", TEXT, ("имя", "наименование")),
|
||||
Column("balance", "Остаток", DECIMAL, ("остаток долга",), MONEY_FORMAT),
|
||||
Column("interest", "Ставка %", DECIMAL, ("процент", "ставка"), PERCENT_FORMAT),
|
||||
Column("payment", "Платёж", DECIMAL, ("платеж", "ежемесячный платёж"), MONEY_FORMAT),
|
||||
Column("currency", "Валюта", CURRENCY, ("валюта долга",)),
|
||||
),
|
||||
),
|
||||
SheetSpec(
|
||||
"ExchangeRates",
|
||||
("from_currency", "to_currency", "rate"),
|
||||
ExchangeRate,
|
||||
"exchange_rates",
|
||||
columns=(
|
||||
Column("from_currency", "Из валюты", CURRENCY, ("из", "валюта из")),
|
||||
Column("to_currency", "В валюту", CURRENCY, ("в", "валюта в")),
|
||||
Column("rate", "Курс", DECIMAL, ("значение курса",), RATE_FORMAT),
|
||||
),
|
||||
),
|
||||
SheetSpec(
|
||||
"Scenarios",
|
||||
("id", "name", "income_multiplier", "expense_multiplier", "growth_multiplier", "description"),
|
||||
ForecastScenario,
|
||||
"scenarios",
|
||||
columns=(
|
||||
Column("id", "ID", ID, ("ид", "идентификатор")),
|
||||
Column("name", "Название", TEXT, ("имя", "название сценария")),
|
||||
Column("income_multiplier", "Множитель дохода", DECIMAL, ("доход", "доход ×")),
|
||||
Column("expense_multiplier", "Множитель расхода", DECIMAL, ("расход", "расход ×")),
|
||||
Column("growth_multiplier", "Множитель роста", DECIMAL, ("рост", "рост ×")),
|
||||
Column("description", "Описание", TEXT, ("комментарий",)),
|
||||
),
|
||||
),
|
||||
InfoSheetSpec(),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Разбор заголовков и значений
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_NON_ALNUM = re.compile(r"[\s_\-]+")
|
||||
|
||||
|
||||
def _normalize_header(value: object) -> str:
|
||||
"""Ключ заголовка: без регистра, пробелов, ``_`` и ``-``; «ё» == «е»."""
|
||||
if value is None:
|
||||
return ""
|
||||
text = str(value).strip().casefold().replace("ё", "е")
|
||||
return _NON_ALNUM.sub("", text)
|
||||
|
||||
|
||||
def build_header_index(spec: SheetSpec) -> dict[str, Column]:
|
||||
"""Сопоставление «нормализованный заголовок → столбец» для листа."""
|
||||
index: dict[str, Column] = {}
|
||||
for column in spec.resolved_columns():
|
||||
for alias in column.accepted_headers():
|
||||
key = _normalize_header(alias)
|
||||
if key and key not in index:
|
||||
index[key] = column
|
||||
return index
|
||||
|
||||
|
||||
def is_empty(value: object) -> bool:
|
||||
"""Пустая ячейка: None или строка из одних пробелов."""
|
||||
if value is None:
|
||||
return True
|
||||
if isinstance(value, str):
|
||||
return not value.strip()
|
||||
return False
|
||||
@@ -0,0 +1,321 @@
|
||||
"""Генератор Excel-шаблона для ручной сборки модели (D36).
|
||||
|
||||
`write_workbook()` собирает книгу, в которой можно заполнять модель руками:
|
||||
листы с русскими заголовками, форматы чисел и дат, выпадающие списки
|
||||
(валюта, периодичность, счёт) и лист «Инструкция» с правилами заполнения.
|
||||
|
||||
Один и тот же генератор обслуживает и каркас (`cf template-xlsx`), и выгрузку
|
||||
(`cf export-xlsx`): выгруженный файл — это тот же шаблон, уже заполненный
|
||||
данными, поэтому цикл «выгрузить → поправить в Excel → импортировать»
|
||||
работает без ручной переделки.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
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 import FinancialModel
|
||||
from domain.currency import CURRENCY_DECIMALS
|
||||
from infrastructure.repositories.excel_schema import (
|
||||
ACCOUNT,
|
||||
ACCOUNT_OPTIONAL,
|
||||
CURRENCY,
|
||||
DATE,
|
||||
DECIMAL,
|
||||
FREQUENCY,
|
||||
ID,
|
||||
SHEETS,
|
||||
Column,
|
||||
InfoSheetSpec,
|
||||
SheetSpec,
|
||||
)
|
||||
|
||||
INSTRUCTION_SHEET = "Инструкция"
|
||||
|
||||
_TEMPLATE_ROWS = 500
|
||||
_VALIDATION_ROWS = 1000
|
||||
_ACCOUNT_RANGE = "=Accounts!$B$2:$B$500"
|
||||
|
||||
_FREQUENCIES_EN = ("daily", "weekly", "monthly", "yearly")
|
||||
_FREQUENCIES_RU = ("ежедневно", "еженедельно", "ежемесячно", "ежегодно")
|
||||
|
||||
# Подсказка по типу значения: (обязательно, формат / допустимые значения).
|
||||
_KIND_HELP: dict[str, tuple[str, str]] = {
|
||||
ID: ("нет", "UUID или пусто — идентификатор создаётся автоматически"),
|
||||
"text": ("—", "текст"),
|
||||
CURRENCY: ("—", "код валюты: " + ", ".join(CURRENCY_DECIMALS)),
|
||||
DECIMAL: ("—", "число: 1 234,56 или 1234.56; (100) = −100"),
|
||||
DATE: ("—", "2026-01-31, 31.01.2026, 31/01/2026 или дата в ячейке Excel"),
|
||||
FREQUENCY: ("—", "daily / weekly / monthly / yearly (или по-русски)"),
|
||||
ACCOUNT: ("да", "имя счёта из листа Accounts"),
|
||||
ACCOUNT_OPTIONAL: ("нет", "имя счёта из Accounts; пусто = все счета"),
|
||||
}
|
||||
|
||||
# Обязательные поля листов (для колонки «Обязательно» в инструкции).
|
||||
_REQUIRED: dict[tuple[str, str], bool] = {
|
||||
("Accounts", "name"): True,
|
||||
("Accounts", "balance"): True,
|
||||
("Transactions", "date"): True,
|
||||
("Transactions", "account"): True,
|
||||
("Transactions", "amount"): True,
|
||||
("Recurring", "frequency"): True,
|
||||
("Recurring", "amount"): True,
|
||||
("Assets", "name"): True,
|
||||
("Assets", "value"): True,
|
||||
("Liabilities", "name"): True,
|
||||
("Liabilities", "balance"): True,
|
||||
("ExchangeRates", "from_currency"): True,
|
||||
("ExchangeRates", "to_currency"): True,
|
||||
("ExchangeRates", "rate"): True,
|
||||
}
|
||||
|
||||
|
||||
class TemplateError(Exception):
|
||||
"""Не удалось создать шаблон (файл уже есть, каталог недоступен)."""
|
||||
|
||||
|
||||
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 _cell_value(column: Column, item) -> object:
|
||||
"""Значение поля модели для записи в ячейку."""
|
||||
raw = getattr(item, column.field, None)
|
||||
if column.kind == ID:
|
||||
return str(raw) if raw else ""
|
||||
if column.kind == CURRENCY:
|
||||
return str(raw).strip().upper() if raw else None
|
||||
if column.kind == DATE:
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(str(raw))
|
||||
except ValueError:
|
||||
return str(raw)
|
||||
if column.kind == DECIMAL:
|
||||
return float(raw) if raw is not None else None
|
||||
if column.kind in {ACCOUNT, ACCOUNT_OPTIONAL}:
|
||||
text = str(raw).strip() if raw else ""
|
||||
return text or None
|
||||
return str(raw) if raw is not None else None
|
||||
|
||||
|
||||
def _write_sheet(wb: Workbook, spec: SheetSpec, model: FinancialModel | None) -> None:
|
||||
columns = spec.resolved_columns()
|
||||
ws = wb.create_sheet(title=spec.name)
|
||||
ws.append(list(spec.headers))
|
||||
for cell in ws[1]:
|
||||
cell.font = Font(bold=True)
|
||||
|
||||
if model is not None:
|
||||
for item in getattr(model, spec.collection, []):
|
||||
ws.append([_cell_value(column, item) for column in columns])
|
||||
|
||||
for column_index, column in enumerate(columns, start=1):
|
||||
letter = get_column_letter(column_index)
|
||||
ws.column_dimensions[letter].width = _column_width(column)
|
||||
if column.number_format:
|
||||
for row_number in range(2, _TEMPLATE_ROWS + 1):
|
||||
ws.cell(row=row_number, column=column_index).number_format = column.number_format
|
||||
|
||||
ws.freeze_panes = "A2"
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(columns))}{_TEMPLATE_ROWS}"
|
||||
|
||||
|
||||
def _column_width(column: Column) -> int:
|
||||
widths = {
|
||||
"id": 38,
|
||||
"name": 24,
|
||||
"currency": 10,
|
||||
"balance": 14,
|
||||
"date": 12,
|
||||
"account": 22,
|
||||
"category": 18,
|
||||
"amount": 14,
|
||||
"description": 34,
|
||||
"start_date": 12,
|
||||
"end_date": 12,
|
||||
"frequency": 16,
|
||||
"value": 14,
|
||||
"growth_rate": 10,
|
||||
"interest": 10,
|
||||
"payment": 14,
|
||||
"from_currency": 12,
|
||||
"to_currency": 12,
|
||||
"rate": 12,
|
||||
"income_multiplier": 18,
|
||||
"expense_multiplier": 18,
|
||||
"growth_multiplier": 18,
|
||||
}
|
||||
return widths.get(column.field, 18)
|
||||
|
||||
|
||||
def _write_info_sheet(wb: Workbook, model: FinancialModel | None, spec: InfoSheetSpec) -> None:
|
||||
ws = wb.create_sheet(title=spec.name)
|
||||
ws.append(list(spec.headers))
|
||||
for cell in ws[1]:
|
||||
cell.font = Font(bold=True)
|
||||
if model is not None:
|
||||
for attribute, _key, label in spec.properties:
|
||||
value = getattr(model, attribute, "") or ""
|
||||
ws.append([label, value])
|
||||
else:
|
||||
for _attribute, _key, label in spec.properties:
|
||||
ws.append([label, None])
|
||||
ws.column_dimensions["A"].width = 26
|
||||
ws.column_dimensions["B"].width = 22
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
|
||||
def _add_validations(wb: Workbook, table) -> None:
|
||||
"""Выпадающие списки: валюта, периодичность, счёт."""
|
||||
for spec in table:
|
||||
if not isinstance(spec, SheetSpec):
|
||||
continue
|
||||
columns = spec.resolved_columns()
|
||||
for column in columns:
|
||||
letter = get_column_letter(columns.index(column) + 1)
|
||||
if column.kind == CURRENCY:
|
||||
validation = _list_validation(
|
||||
tuple(CURRENCY_DECIMALS),
|
||||
prompt="Код валюты, например RUB. Пусто — валюта счёта или базовая.",
|
||||
)
|
||||
elif column.kind == FREQUENCY:
|
||||
validation = _list_validation(
|
||||
_FREQUENCIES_EN + _FREQUENCIES_RU,
|
||||
prompt="daily / weekly / monthly / yearly (или по-русски)",
|
||||
)
|
||||
elif column.kind in {ACCOUNT, ACCOUNT_OPTIONAL}:
|
||||
validation = _account_validation()
|
||||
else:
|
||||
continue
|
||||
spec_sheet = wb[spec.name]
|
||||
spec_sheet.add_data_validation(validation)
|
||||
validation.add(f"{letter}2:{letter}{_VALIDATION_ROWS}")
|
||||
|
||||
|
||||
def _instruction_rows(table) -> 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 --dry-run")
|
||||
line("4. Импортируйте модель: cf import-xlsx путь/к/файлу.xlsx")
|
||||
line("")
|
||||
|
||||
line("Правила заполнения")
|
||||
line("• id можно оставить пустым — идентификатор создаётся автоматически.")
|
||||
line("• счёт указывается по имени из листа Accounts (регистр и лишние пробелы не важны).")
|
||||
line("• пустой счёт в Recurring = платёж относится ко всем счетам.")
|
||||
line("• сумма со знаком: положительная = доход, отрицательная = расход.")
|
||||
line("• сумма — сумма ОДНОГО списания: для yearly это разовая плата за год.")
|
||||
line("• даты: 2026-01-31, 31.01.2026, 31/01/2026 или дата в ячейке Excel.")
|
||||
line("• числа: 1 234,56 или 1234.56; символы валют и пробелы игнорируются; (100) = −100.")
|
||||
line("• валюта: " + ", ".join(CURRENCY_DECIMALS) + ". Пусто — валюта счёта (или базовая).")
|
||||
line("• периодичность: " + ", ".join(_FREQUENCIES_EN) + " (можно по-русски).")
|
||||
line("• транзакция с датой в прошлом уже учтена в балансе счёта — в прогноз не попадёт.")
|
||||
line("")
|
||||
|
||||
rows.append(("Лист", "Столбец", "Обязательно", "Формат / допустимые значения"))
|
||||
for spec in table:
|
||||
if not isinstance(spec, SheetSpec):
|
||||
continue
|
||||
for column in spec.resolved_columns():
|
||||
required = "да" if _REQUIRED.get((spec.name, column.field)) else _KIND_HELP[column.kind][0]
|
||||
rows.append((spec.name, column.header, required, _KIND_HELP[column.kind][1]))
|
||||
return rows
|
||||
|
||||
|
||||
def _write_instruction_sheet(wb: Workbook, table) -> None:
|
||||
ws = wb.create_sheet(title=INSTRUCTION_SHEET)
|
||||
ws.column_dimensions["A"].width = 72
|
||||
ws.column_dimensions["B"].width = 24
|
||||
ws.column_dimensions["C"].width = 14
|
||||
ws.column_dimensions["D"].width = 62
|
||||
|
||||
title = ws.cell(row=1, column=1, value="Инструкция: заполнение Excel-шаблона")
|
||||
title.font = Font(bold=True, size=14)
|
||||
|
||||
for offset, values in enumerate(_instruction_rows(table), 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_workbook(
|
||||
model: FinancialModel | None,
|
||||
path: str | Path,
|
||||
*,
|
||||
force: bool = False,
|
||||
sheets=None,
|
||||
) -> Path:
|
||||
"""Создать книгу Excel: шаблон с данными (или пустой каркас).
|
||||
|
||||
`model=None` — пустой каркас для ручного заполнения.
|
||||
`sheets` — таблица листов; по умолчанию берётся из `excel_schema`.
|
||||
"""
|
||||
table = tuple(sheets) if sheets is not None else SHEETS
|
||||
target = Path(path)
|
||||
if target.exists() and not force:
|
||||
raise TemplateError(f"Файл уже существует: {target} — используйте force, чтобы перезаписать")
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as exc:
|
||||
raise TemplateError(f"Не удалось создать каталог {target.parent}: {exc}") from exc
|
||||
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active)
|
||||
|
||||
for spec in table:
|
||||
if isinstance(spec, SheetSpec):
|
||||
_write_sheet(wb, spec, model)
|
||||
else:
|
||||
_write_info_sheet(wb, model, spec)
|
||||
|
||||
_add_validations(wb, table)
|
||||
_write_instruction_sheet(wb, table)
|
||||
|
||||
try:
|
||||
wb.save(target)
|
||||
except OSError as exc:
|
||||
raise TemplateError(f"Не удалось сохранить файл {target}: {exc}") from exc
|
||||
return target
|
||||
|
||||
|
||||
def write_template(path: str | Path, *, force: bool = False) -> Path:
|
||||
"""Создать пустой каркас .xlsx для ручного заполнения."""
|
||||
return write_workbook(None, path, force=force)
|
||||
|
||||
|
||||
__all__ = ["TemplateError", "write_template", "write_workbook"]
|
||||
Reference in new issue
Block a user