D28: одна декларативная спецификация листов Excel (SheetSpec)
SHEETS в infrastructure/repositories/excel_repository.py описывает имя листа, порядок полей, класс модели и поле FinancialModel; save()/load() идут по этой таблице, ручные ветки по именам листов и _SHEET_CONFIG удалены. ModelInfo описан отдельным InfoSheetSpec. Поведение и порядок листов/колонок не изменились; добавлены тесты, что добавление спецификации автоматически даёт запись и чтение.
This commit is contained in:
1 parent
f50106ca96
commit
f41fc19cc9
3 files changed
+224
-118
No files matched your search
@@ -1,13 +1,21 @@
|
||||
"""ExcelRepository — хранит FinancialModel в .xlsx (7 листов данных + ModelInfo).
|
||||
"""ExcelRepository — хранит FinancialModel в .xlsx.
|
||||
|
||||
Состав листов, порядок полей и классы моделей описаны одной декларативной
|
||||
таблицей `SHEETS` (D28). `save()` и `load()` идут по этой таблице, поэтому
|
||||
новый лист добавляется одной записью в `SHEETS` — без новых веток
|
||||
`if sheet_name == ...` в коде записи или чтения.
|
||||
|
||||
Листы данных: Accounts, Transactions, Recurring, Assets, Liabilities,
|
||||
ExchangeRates, Scenarios. Плюс служебный лист ModelInfo (base_currency).
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from pydantic import BaseModel
|
||||
|
||||
from application.repositories.model_repository import ModelRepository
|
||||
from domain import (
|
||||
@@ -26,36 +34,119 @@ class ExcelRepositoryError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
_SHEET_CONFIG = {
|
||||
"Accounts": {
|
||||
"fields": ["id", "name", "currency", "balance"],
|
||||
"cls": Account,
|
||||
},
|
||||
"Transactions": {
|
||||
"fields": ["id", "date", "account", "category", "amount", "description"],
|
||||
"cls": Transaction,
|
||||
},
|
||||
"Recurring": {
|
||||
"fields": ["id", "start_date", "end_date", "frequency", "amount", "category"],
|
||||
"cls": RecurringCashflow,
|
||||
},
|
||||
"Assets": {
|
||||
"fields": ["id", "name", "value", "growth_rate"],
|
||||
"cls": Asset,
|
||||
},
|
||||
"Liabilities": {
|
||||
"fields": ["id", "name", "balance", "interest", "payment"],
|
||||
"cls": Liability,
|
||||
},
|
||||
"ExchangeRates": {
|
||||
"fields": ["from_currency", "to_currency", "rate"],
|
||||
"cls": ExchangeRate,
|
||||
},
|
||||
"Scenarios": {
|
||||
"fields": ["id", "name", "income_multiplier", "expense_multiplier", "growth_multiplier", "description"],
|
||||
"cls": ForecastScenario,
|
||||
},
|
||||
}
|
||||
@dataclass(frozen=True)
|
||||
class SheetSpec:
|
||||
"""Описание листа-коллекции.
|
||||
|
||||
`fields` задаёт и заголовки, и порядок колонок; `collection` — имя поля
|
||||
`FinancialModel`, в которое читаются строки и из которого они пишутся.
|
||||
Специфику полей (например, отсутствие `id` у `ExchangeRates`) описывает
|
||||
сам список `fields`, отдельного кода для этого не нужно.
|
||||
"""
|
||||
|
||||
name: str
|
||||
fields: tuple[str, ...]
|
||||
cls: type[BaseModel]
|
||||
collection: str
|
||||
|
||||
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:
|
||||
return
|
||||
|
||||
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))
|
||||
|
||||
|
||||
@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 _cell(value: Any) -> Any:
|
||||
"""Значение для записи в ячейку: UUID сериализуется строкой."""
|
||||
return str(value) if isinstance(value, UUID) else value
|
||||
|
||||
|
||||
def _headers(header_row: tuple) -> list[str]:
|
||||
return [str(header).strip().lower() if header else "" for header in header_row]
|
||||
|
||||
|
||||
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"Failed to parse row in {sheet_name}: {e}") from e
|
||||
|
||||
|
||||
class ExcelRepository(ModelRepository):
|
||||
@@ -65,36 +156,14 @@ class ExcelRepository(ModelRepository):
|
||||
raise ExcelRepositoryError(f"File not found: {p}")
|
||||
|
||||
wb = load_workbook(p, read_only=True, data_only=True)
|
||||
model = FinancialModel()
|
||||
model.exchange_rates = []
|
||||
|
||||
for sheet_name, config in _SHEET_CONFIG.items():
|
||||
if sheet_name not in wb.sheetnames:
|
||||
continue
|
||||
ws = wb[sheet_name]
|
||||
rows = list(ws.iter_rows(values_only=True))
|
||||
if len(rows) < 2:
|
||||
continue
|
||||
|
||||
headers = [str(h).strip().lower() if h else "" for h in rows[0]]
|
||||
for row in rows[1:]:
|
||||
if not any(v is not None for v in row):
|
||||
continue
|
||||
data = {}
|
||||
for i, header in enumerate(headers):
|
||||
val = row[i] if i < len(row) else None
|
||||
if val is not None:
|
||||
data[header] = str(val) if not isinstance(val, (int, float)) else val
|
||||
self._add_to_model(model, sheet_name, data, config["cls"])
|
||||
|
||||
if "ModelInfo" in wb.sheetnames:
|
||||
ws = wb["ModelInfo"]
|
||||
rows = list(ws.iter_rows(values_only=True))
|
||||
for row in rows:
|
||||
if row[0] and str(row[0]).strip().lower() == "base_currency" and len(row) > 1:
|
||||
model.base_currency = str(row[1]).strip()
|
||||
|
||||
wb.close()
|
||||
try:
|
||||
model = FinancialModel()
|
||||
# Курсы валют заданы DEFAULT_RATES; лист ExchangeRates их заменяет.
|
||||
model.exchange_rates = []
|
||||
for spec in SHEETS:
|
||||
spec.read(wb, model)
|
||||
finally:
|
||||
wb.close()
|
||||
return model
|
||||
|
||||
def save(self, model: FinancialModel, path: str | Path) -> None:
|
||||
@@ -103,31 +172,8 @@ class ExcelRepository(ModelRepository):
|
||||
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active)
|
||||
|
||||
collections = {
|
||||
"Accounts": model.accounts,
|
||||
"Transactions": model.transactions,
|
||||
"Recurring": model.recurring,
|
||||
"Assets": model.assets,
|
||||
"Liabilities": model.liabilities,
|
||||
"ExchangeRates": model.exchange_rates,
|
||||
"Scenarios": model.scenarios,
|
||||
}
|
||||
|
||||
for sheet_name, items in collections.items():
|
||||
config = _SHEET_CONFIG[sheet_name]
|
||||
ws = wb.create_sheet(title=sheet_name)
|
||||
ws.append(config["fields"])
|
||||
for item in items:
|
||||
row = [
|
||||
str(getattr(item, f)) if isinstance(getattr(item, f), UUID) else getattr(item, f)
|
||||
for f in config["fields"]
|
||||
]
|
||||
ws.append(row)
|
||||
|
||||
ws_info = wb.create_sheet(title="ModelInfo")
|
||||
ws_info.append(["Property", "Value"])
|
||||
ws_info.append(["base_currency", model.base_currency])
|
||||
for spec in SHEETS:
|
||||
spec.write(wb, model)
|
||||
|
||||
try:
|
||||
wb.save(p)
|
||||
@@ -146,23 +192,3 @@ class ExcelRepository(ModelRepository):
|
||||
parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as e:
|
||||
raise ExcelRepositoryError(f"Не удалось создать каталог {parent}: {e}") from e
|
||||
|
||||
def _add_to_model(self, model: FinancialModel, sheet_name: str, data: dict, cls) -> None:
|
||||
try:
|
||||
instance = cls.model_validate(data)
|
||||
except Exception as e:
|
||||
raise ExcelRepositoryError(f"Failed to parse row in {sheet_name}: {e}") from e
|
||||
if sheet_name == "Accounts":
|
||||
model.accounts.append(instance)
|
||||
elif sheet_name == "Transactions":
|
||||
model.transactions.append(instance)
|
||||
elif sheet_name == "Recurring":
|
||||
model.recurring.append(instance)
|
||||
elif sheet_name == "Assets":
|
||||
model.assets.append(instance)
|
||||
elif sheet_name == "Liabilities":
|
||||
model.liabilities.append(instance)
|
||||
elif sheet_name == "ExchangeRates":
|
||||
model.exchange_rates.append(instance)
|
||||
elif sheet_name == "Scenarios":
|
||||
model.scenarios.append(instance)
|
||||
Reference in new issue
Block a user