- 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
776 lines
30 KiB
Python
776 lines
30 KiB
Python
"""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 (
|
||
Account,
|
||
Asset,
|
||
ExchangeRate,
|
||
FinancialModel,
|
||
Liability,
|
||
RecurringCashflow,
|
||
Transaction,
|
||
)
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Схема листов
|
||
# ---------------------------------------------------------------------------
|
||
|
||
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)
|
||
|
||
# Канонический столбец -> принимаемые заголовки (ru + en).
|
||
_ALIASES: dict[str, dict[str, tuple[str, ...]]] = {
|
||
"Accounts": {
|
||
"id": ("id",),
|
||
"name": ("name", "название", "имя"),
|
||
"currency": ("currency", "валюта"),
|
||
"balance": ("balance", "баланс"),
|
||
},
|
||
"Transactions": {
|
||
"id": ("id",),
|
||
"date": ("date", "дата"),
|
||
"account": ("account", "счёт", "счет", "account_name"),
|
||
"category": ("category", "категория"),
|
||
"amount": ("amount", "сумма"),
|
||
"description": ("description", "описание", "комментарий"),
|
||
},
|
||
"Recurring": {
|
||
"id": ("id",),
|
||
"account": ("account", "счёт", "счет"),
|
||
"start_date": ("start_date", "дата_начала", "начало"),
|
||
"end_date": ("end_date", "дата_окончания", "конец"),
|
||
"frequency": ("frequency", "периодичность", "частота"),
|
||
"amount": ("amount", "сумма"),
|
||
"category": ("category", "категория"),
|
||
},
|
||
"Assets": {
|
||
"id": ("id",),
|
||
"name": ("name", "название"),
|
||
"value": ("value", "стоимость"),
|
||
"growth_rate": ("growth_rate", "рост", "доходность"),
|
||
},
|
||
"Liabilities": {
|
||
"id": ("id",),
|
||
"name": ("name", "название"),
|
||
"balance": ("balance", "баланс", "остаток"),
|
||
"interest": ("interest", "ставка", "процент"),
|
||
"payment": ("payment", "платёж", "платеж", "платёж_мес"),
|
||
},
|
||
"ExchangeRates": {
|
||
"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}")
|
||
|
||
collector = _IssueCollector()
|
||
model = FinancialModel()
|
||
|
||
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
|
||
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 collector.truncated:
|
||
collector.warn(f"ошибок больше {_MAX_ERRORS} — показаны первые {_MAX_ERRORS}")
|
||
|
||
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)
|
||
|
||
self._write_sheet(
|
||
wb,
|
||
"ModelInfo",
|
||
["Property", "Value"],
|
||
[["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 _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:
|
||
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",
|
||
]
|