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:
oqyude committed 2026-11-15 06:12:41 +03:00
1 parent 885a91f15f
commit 6b13a15408
17 files changed
+1612 -212

No files matched your search

+12 -1
View File
@@ -19,6 +19,7 @@ from typer.main import get_command
from infrastructure.cli.app import app
from infrastructure.cli.commands.config import app as config_app
from infrastructure.cli.paths import AppPaths
EXPECTED_COMMANDS = {
"init",
@@ -28,6 +29,7 @@ EXPECTED_COMMANDS = {
"compare",
"import-xlsx",
"export-xlsx",
"template-xlsx",
"analyze",
"info",
}
@@ -74,8 +76,17 @@ EXPECTED_PARAMS = {
("currency", ("--currency", "-c"), None, False),
],
"compare": [("months", ("--months", "-m"), 12, False), ("currency", ("--currency", "-c"), None, False)],
"import-xlsx": [("path", ("path",), None, True)],
"import-xlsx": [("path", ("path",), None, True), ("dry_run", ("--dry-run",), False, False)],
"export-xlsx": [("path", ("path",), EXPECTED_EXPORT_DEFAULT, False)],
"template-xlsx": [
(
"path",
("path",),
str(AppPaths.from_env().data_dir / "model_template.xlsx").replace("\\", "/"),
False,
),
("force", ("--force", "-f"), False, False),
],
"analyze": [("months", ("--months", "-m"), 12, False), ("currency", ("--currency", "-c"), None, False)],
"info": [],
}
+360
View File
@@ -0,0 +1,360 @@
"""Тесты Excel-поверхности сборки модели (D35, D36)."""
from decimal import Decimal
from pathlib import Path
import pytest
from openpyxl import Workbook, load_workbook
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
from infrastructure.repositories.excel_template import write_template
def _write_sheets(path: Path, sheets: dict[str, list[list]]) -> Path:
"""Создать .xlsx с заданными листами (как будто пользователь заполнил файл)."""
wb = Workbook()
wb.remove(wb.active)
for name, rows in sheets.items():
ws = wb.create_sheet(title=name)
for row in rows:
ws.append(row)
wb.save(path)
wb.close()
return path
class TestTemplate:
"""D36: каркас шаблона."""
def test_template_has_all_sheets_and_instruction(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
assert wb.sheetnames == [
"Accounts",
"Transactions",
"Recurring",
"Assets",
"Liabilities",
"ExchangeRates",
"Scenarios",
"ModelInfo",
"Инструкция",
]
finally:
wb.close()
def test_template_headers_are_russian(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
assert [cell.value for cell in wb["Accounts"][1]] == ["ID", "Название", "Валюта", "Баланс"]
assert [cell.value for cell in wb["Transactions"][1]] == [
"ID",
"Дата",
"Счёт",
"Категория",
"Сумма",
"Описание",
"Валюта",
]
finally:
wb.close()
def test_template_has_dropdowns(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
validations = wb["Transactions"].data_validations.dataValidation
assert validations
# Валюта и счёт — с выпадающими списками.
formulas = {validation.formula1 for validation in validations}
assert any("Accounts" in formula for formula in formulas)
assert any("RUB" in formula for formula in formulas)
recurring_validations = wb["Recurring"].data_validations.dataValidation
assert any("monthly" in v.formula1 for v in recurring_validations)
finally:
wb.close()
def test_instruction_sheet_describes_columns(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
ws = wb["Инструкция"]
text = "\n".join(
str(cell.value) for row in ws.iter_rows() for cell in row if cell.value is not None
)
assert "Порядок работы" in text
assert "Счёт" in text
assert "Периодичность" in text
finally:
wb.close()
def test_template_is_imported_without_errors(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.accounts == []
def test_existing_file_is_not_overwritten(self, tmp_path: Path):
path = tmp_path / "template.xlsx"
write_template(path)
with pytest.raises(Exception):
write_template(path)
def test_force_overwrites(self, tmp_path: Path):
path = tmp_path / "template.xlsx"
write_template(path)
write_template(path, force=True)
assert path.exists()
class TestTolerantImport:
"""D35: импорт принимает то, что пишет человек."""
def test_russian_headers_and_text_numbers(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [
["Название", "Валюта", "Баланс"],
["Основной", "RUB", "1 234,56"],
],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.accounts[0].name == "Основной"
assert result.model.accounts[0].balance == Decimal("1234.56")
def test_english_headers_are_accepted(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [
["name", "currency", "balance"],
["Main", "RUB", 100],
],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.accounts[0].name == "Main"
def test_column_order_does_not_matter(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [
["Баланс", "Название", "Валюта"],
[500, "Main", "RUB"],
],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.accounts[0].name == "Main"
assert result.model.accounts[0].balance == Decimal("500")
@pytest.mark.parametrize(
("value", "expected"),
[
("1 234,56", Decimal("1234.56")),
("1,234.56", Decimal("1234.56")),
("₽1 200,50", Decimal("1200.50")),
("(100)", Decimal("-100")),
("-1200", Decimal("-1200")),
],
)
def test_number_formats(self, tmp_path: Path, value, expected):
# Отрицательные суммы — в столбце «Сумма» регулярного платежа:
# баланс счёта отрицательным быть не может (правило модели).
path = _write_sheets(
tmp_path / "model.xlsx",
{"Recurring": [["Сумма"], [value]]},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.recurring[0].amount == expected
@pytest.mark.parametrize(
("value", "expected"),
[
("2026-11-01", "2026-11-01"),
("01.11.2026", "2026-11-01"),
("01/11/2026", "2026-11-01"),
],
)
def test_date_formats(self, tmp_path: Path, value, expected):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Счёт"]],
"Transactions": [["Дата", "Счёт", "Сумма"], [value, "Счёт", 100]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.transactions[0].date == expected
def test_account_is_resolved_by_name(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название", "Валюта", "Баланс"], ["Основной", "RUB", 100]],
"Transactions": [["Дата", "Счёт", "Сумма"], ["2026-11-01", "Основной", 500]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.transactions[0].account == str(result.model.accounts[0].id)
def test_unknown_account_is_an_error_with_address(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Основной"]],
"Transactions": [["Дата", "Счёт", "Сумма"], ["2026-11-01", "Нет такого", 500]],
},
)
result = ExcelRepository().load_report(path)
assert len(result.errors) == 1
error = result.errors[0]
assert error.sheet == "Transactions"
assert error.row == 2
assert "Нет такого" in error.message
def test_load_raises_on_errors(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{"Accounts": [["Название", "Баланс"], ["Счёт", "не число"]]},
)
with pytest.raises(ExcelRepositoryError):
ExcelRepository().load(path)
def test_unknown_column_is_a_warning(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{"Accounts": [["Название", "Баланс", "Пожелание"], ["Счёт", 100, "хочу миллион"]]},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert any("Пожелание" in warning for warning in result.warnings)
def test_duplicate_account_names_are_a_warning(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{"Accounts": [["Название", "Баланс"], ["Счёт", 100], ["счёт", 200]]},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert any("повторяется" in warning for warning in result.warnings)
def test_russian_frequency_is_normalized(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Счёт"]],
"Recurring": [["Периодичность", "Сумма"], ["ежемесячно", -1500]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.recurring[0].frequency == "monthly"
def test_empty_periodicity_falls_back_to_monthly(self, tmp_path: Path):
# Пустая ячейка в Excel — это «не задано», а не ошибка: период по
# умолчанию задаёт сама модель.
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Счёт"]],
"Recurring": [["Периодичность", "Сумма"], ["", -1500]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.recurring[0].frequency == "monthly"
def test_unknown_periodicity_is_an_error(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Счёт"]],
"Recurring": [["Периодичность", "Сумма"], ["hourly", -1500]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors
assert "периодичность" in result.errors[0].message.lower()
def test_model_info_accepts_russian_labels(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"ModelInfo": [
["Свойство", "Значение"],
["Базовая валюта", "EUR"],
["Валюта вывода", "USD"],
],
"Accounts": [["Название"], ["Счёт"]],
},
)
result = ExcelRepository().load_report(path)
assert result.model.base_currency == "EUR"
assert result.model.display_currency == "USD"
def test_empty_model_info_cell_is_not_the_word_none(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"ModelInfo": [
["Свойство", "Значение"],
["Базовая валюта", "RUB"],
["Валюта вывода", None],
],
},
)
result = ExcelRepository().load_report(path)
assert result.model.display_currency == ""
class TestExportIsEditable:
"""D36: выгруженный файл — это шаблон с данными."""
def test_export_contains_instruction_and_validations(self, sample_model, tmp_path: Path):
path = tmp_path / "exported.xlsx"
ExcelRepository().save(sample_model, path)
wb = load_workbook(path)
try:
assert "Инструкция" in wb.sheetnames
assert wb["Transactions"].data_validations.dataValidation
assert [cell.value for cell in wb["Accounts"][1]] == ["ID", "Название", "Валюта", "Баланс"]
finally:
wb.close()
def test_exported_file_can_be_imported_back(self, sample_model, tmp_path: Path):
path = tmp_path / "exported.xlsx"
ExcelRepository().save(sample_model, path)
loaded = ExcelRepository().load(path)
assert [a.name for a in loaded.accounts] == ["Основной счёт", "Сбережения"]
assert loaded.accounts[0].balance == Decimal("5000")
assert loaded.transactions[0].date == "2026-01-01"
def test_export_preserves_own_currency_of_operations(self, tmp_path: Path):
from domain import Account, FinancialModel, Transaction
model = FinancialModel(
accounts=[Account(name="Доллары", currency="USD", balance=Decimal("100"))],
transactions=[
Transaction(date="2026-01-01", account="Доллары", amount=Decimal("5"), currency="EUR")
],
)
path = tmp_path / "currencies.xlsx"
ExcelRepository().save(model, path)
loaded = ExcelRepository().load(path)
assert loaded.transactions[0].currency == "EUR"
assert loaded.accounts[0].currency == "USD"
+10 -7
View File
@@ -12,6 +12,7 @@ from infrastructure.repositories.excel_repository import InfoSheetSpec, SheetSpe
_SCENARIO_FIELDS = ["id", "name", "income_multiplier", "expense_multiplier", "growth_multiplier", "description"]
# Листы данных в таблице `SHEETS` (D28).
_EXPECTED_SHEETS = [
"Accounts",
"Transactions",
@@ -23,6 +24,9 @@ _EXPECTED_SHEETS = [
"ModelInfo",
]
# Листы в записанном файле: данные + памятка (D36).
_EXPECTED_WORKBOOK_SHEETS = [*_EXPECTED_SHEETS, "Инструкция"]
class TestExcelRepository:
def test_export_creates_file(self, sample_model, tmp_path: Path):
@@ -191,7 +195,7 @@ class TestExcelRoundTripByValues:
wb = load_workbook(p)
try:
assert wb.sheetnames == _EXPECTED_SHEETS
assert wb.sheetnames == _EXPECTED_WORKBOOK_SHEETS
finally:
wb.close()
@@ -270,7 +274,9 @@ class TestScenariosSheet:
assert "Scenarios" in wb.sheetnames
ws = wb["Scenarios"]
assert ws.max_row == 1
assert [cell.value for cell in ws[1]] == _SCENARIO_FIELDS
assert [cell.value for cell in ws[1]] == list(
next(spec for spec in excel_repository.SHEETS if getattr(spec, "name", "") == "Scenarios").headers
)
finally:
wb.close()
@@ -301,10 +307,7 @@ class TestSheetSpecIsSingleSource:
try:
for spec in excel_repository.SHEETS:
headers = [cell.value for cell in wb[spec.name][1]]
if isinstance(spec, InfoSheetSpec):
assert headers == ["Property", "Value"]
else:
assert headers == list(spec.fields), f"{spec.name}: заголовки не из спецификации"
assert headers == list(spec.headers), f"{spec.name}: заголовки не из спецификации"
finally:
wb.close()
@@ -322,7 +325,7 @@ class TestSheetSpecIsSingleSource:
wb = load_workbook(p)
try:
assert wb.sheetnames == ["AccountsCopy", "ModelInfo"]
assert wb.sheetnames == ["AccountsCopy", "ModelInfo", "Инструкция"]
finally:
wb.close()
+4 -12
View File
@@ -256,9 +256,7 @@ class TestTransactionDates:
return [row["balance"] for row in rows]
def test_future_transaction_lands_in_its_own_month(self):
model = self._model(
Transaction(date="2026-03-10", account="Счёт", category="income", amount=Decimal("1000"))
)
model = self._model(Transaction(date="2026-03-10", account="Счёт", category="income", amount=Decimal("1000")))
assert self._balances(model) == [
Decimal("0.00"),
Decimal("0.00"),
@@ -270,9 +268,7 @@ class TestTransactionDates:
def test_past_transaction_does_not_move_the_forecast(self):
# Операция до начала сетки уже учтена в балансе счёта.
model = self._model(
Transaction(date="2025-12-01", account="Счёт", category="income", amount=Decimal("1000"))
)
model = self._model(Transaction(date="2025-12-01", account="Счёт", category="income", amount=Decimal("1000")))
assert self._balances(model) == [Decimal("0.00")] * 6
def test_transaction_without_date_goes_to_the_first_month(self):
@@ -282,16 +278,12 @@ class TestTransactionDates:
assert self._balances(model) == [Decimal("500.00")] * 6
def test_transaction_after_horizon_is_ignored(self):
model = self._model(
Transaction(date="2027-01-10", account="Счёт", category="income", amount=Decimal("1000"))
)
model = self._model(Transaction(date="2027-01-10", account="Счёт", category="income", amount=Decimal("1000")))
assert self._balances(model) == [Decimal("0.00")] * 6
def test_transaction_is_found_by_account_name(self):
# Excel-автор пишет в ячейке имя счёта, а не UUID.
model = self._model(
Transaction(date="2026-01-05", account="Счёт", category="income", amount=Decimal("700"))
)
model = self._model(Transaction(date="2026-01-05", account="Счёт", category="income", amount=Decimal("700")))
assert self._balances(model)[0] == Decimal("700.00")
def test_transaction_is_found_by_account_uuid(self):