Импорт создавал модель с DEFAULT_RATES, а затем лист «Курсы валют» целиком заменял список — даже пустой. После `cf template-xlsx` → `cf import-xlsx` в модели не оставалось ни одного курса, включая USD → RUB = 80, хотя README обещал обратное. Теперь курсы из листа накладываются на дефолтные: пара из файла обновляет такую же дефолтную, остальные дефолтные сохраняются. Было → стало (пустой шаблон): exchange_rates = [] → [USD → RUB = 80]. Файл с EUR → RUB = 90: [EUR → RUB = 90] → [USD → RUB = 80, EUR → RUB = 90]. Refs: review/2026-11-29-review.md §2 Н4, §6 R4.
549 lines
22 KiB
Python
549 lines
22 KiB
Python
"""ExcelRepository — .xlsx как поверхность сборки модели (D35).
|
||
|
||
Файл читается терпимо: заголовки принимаются на русском и английском в любом
|
||
порядке и регистре, числа — в пользовательских форматах («1 234,56», «₽1200»,
|
||
«(100)» = −100), даты — и как даты Excel, и как текст. Ошибки строк не
|
||
роняют импорт: они собираются в отчёт с адресом «лист!строка», и файл с
|
||
ошибками не сохраняется.
|
||
|
||
Публичный контракт:
|
||
|
||
- ``ExcelRepository.load(path)`` — модель или ``ExcelRepositoryError``;
|
||
- ``ExcelRepository.load_report(path)`` — модель + ошибки + предупреждения;
|
||
- ``ExcelRepository.save(model, path)`` — записать модель в .xlsx.
|
||
|
||
Устройство листов описано в `excel_schema` (таблица `SHEETS`) — она же
|
||
источник заголовков, синонимов и типов значений (D28).
|
||
"""
|
||
|
||
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 load_workbook
|
||
from openpyxl.utils.exceptions import InvalidFileException
|
||
from pydantic import ValidationError
|
||
|
||
from application.repositories.model_repository import ModelRepository
|
||
from domain import Account, ExchangeRate, FinancialModel
|
||
from domain.currency import DEFAULT_RATES
|
||
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,
|
||
find_sheet_title,
|
||
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):
|
||
"""Ошибка импорта/экспорта .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)
|
||
|
||
|
||
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)
|
||
|
||
|
||
def _merge_exchange_rates(sheet_rates: list[ExchangeRate]) -> list[ExchangeRate]:
|
||
"""Дополнить курсы по умолчанию курсами из листа (Н4).
|
||
|
||
Пара из листа заменяет такую же дефолтную (пользователь мог обновить
|
||
USD → RUB), но отсутствующие в листе пары остаются: пустой лист больше
|
||
не означает «курсов нет».
|
||
"""
|
||
merged: dict[tuple[str, str], ExchangeRate] = {
|
||
(rate.from_currency.upper(), rate.to_currency.upper()): rate.model_copy() for rate in DEFAULT_RATES
|
||
}
|
||
for rate in sheet_rates:
|
||
merged[(rate.from_currency.upper(), rate.to_currency.upper())] = rate
|
||
return list(merged.values())
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Разбор значений ячеек
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
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("пустое число")
|
||
|
||
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 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:
|
||
"""Прочитать модель; при ошибках данных поднять ``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()
|
||
|
||
try:
|
||
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:
|
||
if not isinstance(spec, SheetSpec) or spec.collection == "accounts":
|
||
continue
|
||
rows = self._read_sheet(spec, workbook, index, collector)
|
||
if spec.collection == "exchange_rates":
|
||
# Пустой лист «Курсы валют» не должен стирать курсы по
|
||
# умолчанию: иначе любой валютный счёт выпадает из
|
||
# прогноза (Н4).
|
||
model.exchange_rates = _merge_exchange_rates(rows)
|
||
else:
|
||
setattr(model, spec.collection, rows)
|
||
self._check_formulas(file_path, workbook, collector)
|
||
finally:
|
||
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:
|
||
"""Прочитать лист настроек модели: «свойство → значение»."""
|
||
for spec in SHEETS:
|
||
if not isinstance(spec, InfoSheetSpec):
|
||
continue
|
||
title = find_sheet_title(spec, workbook.sheetnames)
|
||
if title is None:
|
||
continue
|
||
accepted = spec.accepted_keys()
|
||
for row in workbook[title].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
|
||
label = find_sheet_title(spec, workbook.sheetnames) or spec.sheet_title
|
||
for row_number, data in self._read_rows(spec, workbook, collector):
|
||
instance = self._validate(spec, data, row_number, collector, label)
|
||
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"{label}: имя счёта «{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 = []
|
||
label = find_sheet_title(spec, workbook.sheetnames) or spec.sheet_title
|
||
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(
|
||
label,
|
||
row_number,
|
||
"account",
|
||
f"неизвестный счёт «{reference}»; известные счета: {index.describe()}",
|
||
)
|
||
continue
|
||
data["account"] = resolved
|
||
instance = self._validate(spec, data, row_number, collector, label)
|
||
if instance is not None:
|
||
instances.append(instance)
|
||
return instances
|
||
|
||
def _read_rows(
|
||
self,
|
||
spec: SheetSpec,
|
||
workbook,
|
||
collector: _IssueCollector,
|
||
) -> list[tuple[int, dict]]:
|
||
"""Строки листа как пары (номер строки, данные по полям)."""
|
||
title = find_sheet_title(spec, workbook.sheetnames)
|
||
label = title or spec.sheet_title
|
||
if title is None:
|
||
collector.warn(f"{label}: лист отсутствует")
|
||
return []
|
||
|
||
sheet = workbook[title]
|
||
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, label)
|
||
if not columns:
|
||
collector.warn(f"{label}: не найдено ни одного известного столбца — лист пропущен")
|
||
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(label, 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,
|
||
label: str = "",
|
||
) -> 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"{label}: неизвестный столбец «{str(raw).strip()}» — пропущен")
|
||
continue
|
||
if column in columns:
|
||
collector.warn(f"{label}: столбец «{column.header}» задан дважды — используется первый")
|
||
continue
|
||
columns[column] = column_index
|
||
return columns
|
||
|
||
def _validate(
|
||
self,
|
||
spec: SheetSpec,
|
||
data: dict,
|
||
row_number: int,
|
||
collector: _IssueCollector,
|
||
label: str = "",
|
||
):
|
||
sheet_label = label or spec.sheet_title
|
||
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(sheet_label, row_number, field_name, message)
|
||
except (TypeError, ValueError) as exc:
|
||
collector.error(sheet_label, 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:
|
||
"""Записать модель в .xlsx (файл пригоден для правки и обратного импорта)."""
|
||
try:
|
||
write_workbook(model, path, force=True, sheets=SHEETS)
|
||
except TemplateError as exc:
|
||
raise ExcelRepositoryError(str(exc)) from exc
|
||
|
||
|
||
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",
|
||
]
|