T9: Excel as the model authoring surface
- 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
This commit is contained in:
1 parent
b90ca4c282
commit
cdda703b37
39 files changed
+2181
-198
No files matched your search
@@ -1,9 +1,24 @@
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
from domain import FinancialModel
|
||||
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
|
||||
|
||||
|
||||
def _write_workbook(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)
|
||||
return path
|
||||
|
||||
|
||||
class TestExcelRepository:
|
||||
def test_export_creates_file(self, sample_model, tmp_path: Path):
|
||||
repo = ExcelRepository()
|
||||
@@ -47,3 +62,281 @@ class TestExcelRepository:
|
||||
p = tmp_path / "empty.xlsx"
|
||||
repo.save(model, p)
|
||||
assert p.exists()
|
||||
|
||||
|
||||
class TestExcelAuthoringImport:
|
||||
def test_hand_authored_workbook_without_ids(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "hand.xlsx",
|
||||
{
|
||||
"Accounts": [["name", "currency", "balance"], ["Карта", "RUB", 1000]],
|
||||
"Transactions": [
|
||||
["date", "account", "category", "amount", "description"],
|
||||
["2026-11-01", "Карта", "food", -500, "продукты"],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
model = ExcelRepository().load(path)
|
||||
|
||||
assert len(model.accounts) == 1
|
||||
account = model.accounts[0]
|
||||
assert account.balance == Decimal("1000")
|
||||
assert model.transactions[0].account == str(account.id)
|
||||
assert model.transactions[0].date == "2026-11-01"
|
||||
assert model.transactions[0].amount == Decimal("-500")
|
||||
|
||||
def test_russian_headers_dates_and_numeric_strings(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "ru.xlsx",
|
||||
{
|
||||
"Accounts": [["название", "валюта", "баланс"], ["Карта", "rub", "1 234,56"]],
|
||||
"Transactions": [
|
||||
["дата", "счёт", "категория", "сумма"],
|
||||
["01.11.2026", "карта", "income", "1 234,56"],
|
||||
],
|
||||
"Recurring": [
|
||||
["счёт", "дата_начала", "периодичность", "сумма"],
|
||||
["Карта", "01.11.2026", "ежемесячно", -100],
|
||||
],
|
||||
"Liabilities": [
|
||||
["название", "остаток", "ставка", "платёж_мес"],
|
||||
["Кредит", "20 000,00", "5,5", "500"],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert result.errors == []
|
||||
model = result.model
|
||||
assert model.accounts[0].currency == "RUB"
|
||||
assert model.accounts[0].balance == Decimal("1234.56")
|
||||
assert model.transactions[0].date == "2026-11-01"
|
||||
assert model.transactions[0].amount == Decimal("1234.56")
|
||||
assert model.transactions[0].account == str(model.accounts[0].id)
|
||||
assert model.recurring[0].frequency == "monthly"
|
||||
assert model.recurring[0].account == str(model.accounts[0].id)
|
||||
assert model.liabilities[0].payment == Decimal("500")
|
||||
assert model.liabilities[0].interest == Decimal("5.5")
|
||||
|
||||
def test_unknown_account_reports_sheet_and_row(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "bad_account.xlsx",
|
||||
{
|
||||
"Accounts": [["name", "currency", "balance"], ["Карта", "RUB", 100]],
|
||||
"Transactions": [
|
||||
["date", "account", "amount"],
|
||||
["2026-11-01", "Наличные", -100],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
repo = ExcelRepository()
|
||||
result = repo.load_report(path)
|
||||
|
||||
assert len(result.errors) == 1
|
||||
error = result.errors[0]
|
||||
assert (error.sheet, error.row, error.field) == ("Transactions", 2, "account")
|
||||
assert "Наличные" in error.message
|
||||
assert "Карта" in error.message
|
||||
assert result.model.transactions == []
|
||||
|
||||
try:
|
||||
repo.load(path)
|
||||
assert False, "Expected ExcelRepositoryError"
|
||||
except ExcelRepositoryError as exc:
|
||||
assert "Transactions!" in str(exc)
|
||||
|
||||
def test_duplicate_account_names_warn_and_first_wins(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "dupes.xlsx",
|
||||
{
|
||||
"Accounts": [
|
||||
["name", "currency", "balance"],
|
||||
["Карта", "RUB", 100],
|
||||
["карта", "RUB", 200],
|
||||
],
|
||||
"Transactions": [
|
||||
["date", "account", "amount"],
|
||||
["2026-11-01", "Карта", -10],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert result.errors == []
|
||||
assert any("повторяется" in warning for warning in result.warnings)
|
||||
assert len(result.model.accounts) == 2
|
||||
assert result.model.transactions[0].account == str(result.model.accounts[0].id)
|
||||
|
||||
def test_missing_exchange_rates_keeps_defaults(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "no_rates.xlsx",
|
||||
{"Accounts": [["name", "currency", "balance"], ["Карта", "RUB", 100]]},
|
||||
)
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert result.errors == []
|
||||
assert any("ExchangeRates" in warning for warning in result.warnings)
|
||||
rates = result.model.exchange_rates
|
||||
assert len(rates) == 1
|
||||
assert (rates[0].from_currency, rates[0].to_currency) == ("USD", "RUB")
|
||||
assert rates[0].rate == Decimal("80")
|
||||
|
||||
def test_empty_exchange_rates_sheet_keeps_defaults(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "empty_rates.xlsx",
|
||||
{
|
||||
"Accounts": [["name", "currency", "balance"], ["Карта", "RUB", 100]],
|
||||
"ExchangeRates": [["from_currency", "to_currency", "rate"]],
|
||||
},
|
||||
)
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert result.errors == []
|
||||
assert len(result.model.exchange_rates) == 1
|
||||
assert result.model.exchange_rates[0].rate == Decimal("80")
|
||||
|
||||
def test_export_writes_account_names_and_reimport_restores_ids(self, sample_model, tmp_path: Path):
|
||||
repo = ExcelRepository()
|
||||
path = tmp_path / "names.xlsx"
|
||||
repo.save(sample_model, path)
|
||||
|
||||
wb = load_workbook(path)
|
||||
try:
|
||||
transactions = wb["Transactions"]
|
||||
account_column = [cell.value for cell in transactions["C"][1:]]
|
||||
assert account_column == ["Основной счёт", "Основной счёт"]
|
||||
assert all(str(sample_model.accounts[0].id) not in str(value) for value in account_column)
|
||||
|
||||
recurring = wb["Recurring"]
|
||||
assert [cell.value for cell in recurring["B"][1:]] == [None, None]
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
loaded = repo.load(path)
|
||||
assert {transaction.account for transaction in loaded.transactions} == {
|
||||
str(sample_model.accounts[0].id)
|
||||
}
|
||||
assert [recurring.account for recurring in loaded.recurring] == ["", ""]
|
||||
assert loaded.accounts[0].id == sample_model.accounts[0].id
|
||||
|
||||
def test_bad_frequency_is_row_error(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "bad_frequency.xlsx",
|
||||
{
|
||||
"Recurring": [
|
||||
["start_date", "frequency", "amount"],
|
||||
["2026-01-01", "sometimes", 100],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert len(result.errors) == 1
|
||||
error = result.errors[0]
|
||||
assert (error.sheet, error.row, error.field) == ("Recurring", 2, "frequency")
|
||||
assert "sometimes" in error.message
|
||||
assert result.model.recurring == []
|
||||
|
||||
def test_invalid_date_is_row_error(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "bad_date.xlsx",
|
||||
{
|
||||
"Accounts": [["name", "currency", "balance"], ["Карта", "RUB", 100]],
|
||||
"Transactions": [
|
||||
["date", "account", "amount"],
|
||||
["31.02.2026", "Карта", -10],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert len(result.errors) == 1
|
||||
assert (result.errors[0].sheet, result.errors[0].row, result.errors[0].field) == (
|
||||
"Transactions",
|
||||
2,
|
||||
"date",
|
||||
)
|
||||
|
||||
def test_formula_without_cached_value_warns(self, tmp_path: Path):
|
||||
path = tmp_path / "formula.xlsx"
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active)
|
||||
|
||||
accounts = wb.create_sheet("Accounts")
|
||||
accounts.append(["name", "currency", "balance"])
|
||||
accounts.append(["Карта", "RUB", 1000])
|
||||
|
||||
transactions = wb.create_sheet("Transactions")
|
||||
transactions.append(["date", "account", "amount"])
|
||||
transactions.append(["2026-11-01", "Карта", "=100+50"])
|
||||
wb.save(path)
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert result.errors == []
|
||||
assert any("формула без сохранённого значения" in warning for warning in result.warnings)
|
||||
|
||||
def test_unknown_header_warns_with_sheet_and_name(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "unknown_header.xlsx",
|
||||
{
|
||||
"Accounts": [
|
||||
["name", "currency", "balance", "заметка"],
|
||||
["Карта", "RUB", 100, "лишнее"],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert result.errors == []
|
||||
assert any("Accounts" in warning and "заметка" in warning for warning in result.warnings)
|
||||
|
||||
def test_unknown_headers_are_ignored_but_known_columns_work(self, tmp_path: Path):
|
||||
path = _write_workbook(
|
||||
tmp_path / "mixed_headers.xlsx",
|
||||
{
|
||||
"Accounts": [
|
||||
["name", "currency", "balance", "extra"],
|
||||
["Карта", "RUB", 100, "x"],
|
||||
],
|
||||
"Transactions": [
|
||||
["Дата", "СЧЕТ", "Сумма", "Комментарий"],
|
||||
["2026/11/01", "Карта", "(1 000,50)", "тест"],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
model = ExcelRepository().load(path)
|
||||
|
||||
assert model.transactions[0].date == "2026-11-01"
|
||||
assert model.transactions[0].amount == Decimal("-1000.50")
|
||||
assert model.transactions[0].description == "тест"
|
||||
|
||||
def test_corrupt_file_raises_repository_error(self, tmp_path: Path):
|
||||
path = tmp_path / "corrupt.xlsx"
|
||||
path.write_text("not an excel file", encoding="utf-8")
|
||||
|
||||
try:
|
||||
ExcelRepository().load(path)
|
||||
assert False, "Expected ExcelRepositoryError"
|
||||
except ExcelRepositoryError:
|
||||
pass
|
||||
|
||||
def test_errors_are_capped_at_100(self, tmp_path: Path):
|
||||
rows = [["account"]] + [["Нет такого"] for _ in range(120)]
|
||||
path = _write_workbook(tmp_path / "many_errors.xlsx", {"Transactions": rows})
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert len(result.errors) == 100
|
||||
assert any("100" in warning for warning in result.warnings)
|
||||
|
||||
Reference in new issue
Block a user