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
@@ -14,6 +14,22 @@ from domain import (
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _preserve_stored_model():
|
||||
"""CLI-тесты пишут в настоящий data/model.json — вернуть его после прогона."""
|
||||
from pathlib import Path
|
||||
|
||||
path = Path("data/model.json")
|
||||
backup = path.read_bytes() if path.exists() else None
|
||||
yield
|
||||
if backup is None:
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(backup)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_model() -> FinancialModel:
|
||||
acc_id = uuid4()
|
||||
|
||||
+185
-1
@@ -1,7 +1,7 @@
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from infrastructure.cli.app import app
|
||||
from infrastructure.cli.paths import MODEL_PATH
|
||||
from infrastructure.cli.paths import MODEL_PATH, TEMPLATE_PATH
|
||||
|
||||
runner = CliRunner()
|
||||
|
||||
@@ -167,3 +167,187 @@ class TestCli:
|
||||
result = runner.invoke(app, ["info"])
|
||||
assert "Основной" in result.stdout
|
||||
assert "Акции" in result.stdout
|
||||
|
||||
|
||||
# ── Excel: template-xlsx / import-xlsx ─────────────────────────
|
||||
|
||||
_GOOD_ACCOUNTS = [("Основной", "RUB", 100000)]
|
||||
_GOOD_TRANSACTIONS = [
|
||||
("2026-11-01", "Основной", "salary", 50000, "Зарплата"),
|
||||
("2026-11-05", "Основной", "rent", -35000, "Аренда"),
|
||||
]
|
||||
|
||||
|
||||
def _build_workbook(path, *, accounts=None, transactions=None):
|
||||
"""Собрать минимальный .xlsx руками: Accounts + Transactions (без id)."""
|
||||
from openpyxl import Workbook
|
||||
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active)
|
||||
|
||||
accounts_ws = wb.create_sheet("Accounts")
|
||||
accounts_ws.append(["name", "currency", "balance"])
|
||||
for row in _GOOD_ACCOUNTS if accounts is None else accounts:
|
||||
accounts_ws.append(list(row))
|
||||
|
||||
transactions_ws = wb.create_sheet("Transactions")
|
||||
transactions_ws.append(["date", "account", "category", "amount", "description"])
|
||||
for row in _GOOD_TRANSACTIONS if transactions is None else transactions:
|
||||
transactions_ws.append(list(row))
|
||||
|
||||
wb.save(path)
|
||||
return path
|
||||
|
||||
|
||||
class TestTemplateXlsx:
|
||||
def test_creates_file_at_given_path(self, tmp_path):
|
||||
target = tmp_path / "my_template.xlsx"
|
||||
result = runner.invoke(app, ["template-xlsx", str(target)])
|
||||
|
||||
assert result.exit_code == 0, result.stdout
|
||||
assert target.exists()
|
||||
assert "cf import-xlsx" in result.stdout
|
||||
|
||||
def test_default_path_is_data_template(self):
|
||||
import inspect
|
||||
|
||||
from infrastructure.cli.commands import template_xlsx as module
|
||||
|
||||
default = inspect.signature(module.template_xlsx).parameters["path"].default
|
||||
assert default.default == TEMPLATE_PATH
|
||||
|
||||
def test_default_path_used_when_omitted(self, tmp_path, monkeypatch):
|
||||
from pathlib import Path
|
||||
|
||||
monkeypatch.chdir(tmp_path)
|
||||
result = runner.invoke(app, ["template-xlsx"])
|
||||
|
||||
assert result.exit_code == 0, result.stdout
|
||||
assert Path(TEMPLATE_PATH).exists()
|
||||
|
||||
def test_existing_file_without_force(self, tmp_path):
|
||||
target = tmp_path / "template.xlsx"
|
||||
first = runner.invoke(app, ["template-xlsx", str(target)])
|
||||
assert first.exit_code == 0
|
||||
before = target.read_bytes()
|
||||
|
||||
second = runner.invoke(app, ["template-xlsx", str(target)])
|
||||
|
||||
assert second.exit_code != 0
|
||||
assert "--force" in second.stdout
|
||||
assert target.exists()
|
||||
assert target.read_bytes() == before
|
||||
|
||||
def test_force_overwrites(self, tmp_path):
|
||||
from openpyxl import load_workbook
|
||||
|
||||
target = tmp_path / "template.xlsx"
|
||||
target.write_bytes(b"not a workbook")
|
||||
|
||||
result = runner.invoke(app, ["template-xlsx", str(target), "--force"])
|
||||
|
||||
assert result.exit_code == 0, result.stdout
|
||||
wb = load_workbook(target)
|
||||
try:
|
||||
assert "Accounts" in wb.sheetnames
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
class TestImportXlsx:
|
||||
def test_dry_run_good_book_does_not_save(self, tmp_path, monkeypatch):
|
||||
target = _build_workbook(tmp_path / "good.xlsx")
|
||||
calls = []
|
||||
monkeypatch.setattr("infrastructure.cli.commands.import_xlsx.save_model", calls.append)
|
||||
|
||||
result = runner.invoke(app, ["import-xlsx", str(target), "--dry-run"])
|
||||
|
||||
assert result.exit_code == 0, result.stdout
|
||||
assert "не сохранена" in result.stdout
|
||||
assert "счета — 1" in result.stdout
|
||||
assert calls == []
|
||||
|
||||
def test_unknown_account_blocks_save(self, tmp_path, monkeypatch):
|
||||
target = _build_workbook(
|
||||
tmp_path / "bad.xlsx",
|
||||
transactions=[("2026-11-01", "Неизвестный", "rent", -1000, "Аренда")],
|
||||
)
|
||||
calls = []
|
||||
monkeypatch.setattr("infrastructure.cli.commands.import_xlsx.save_model", calls.append)
|
||||
|
||||
result = runner.invoke(app, ["import-xlsx", str(target)])
|
||||
|
||||
assert result.exit_code == 1, result.stdout
|
||||
assert "Transactions!2" in result.stdout
|
||||
assert "Transactions!2 [account]" in result.stdout
|
||||
assert "Первая ошибка" in result.stdout
|
||||
assert calls == []
|
||||
|
||||
def test_zero_amount_blocks_save(self, tmp_path, monkeypatch):
|
||||
target = _build_workbook(
|
||||
tmp_path / "zero.xlsx",
|
||||
transactions=[("2026-11-01", "Основной", "rent", 0, "Ноль")],
|
||||
)
|
||||
calls = []
|
||||
monkeypatch.setattr("infrastructure.cli.commands.import_xlsx.save_model", calls.append)
|
||||
|
||||
result = runner.invoke(app, ["import-xlsx", str(target)])
|
||||
|
||||
assert result.exit_code == 1, result.stdout
|
||||
assert "Transactions!2" in result.stdout
|
||||
assert calls == []
|
||||
|
||||
def test_good_book_saves_once(self, tmp_path, monkeypatch):
|
||||
target = _build_workbook(tmp_path / "good.xlsx")
|
||||
calls = []
|
||||
monkeypatch.setattr("infrastructure.cli.commands.import_xlsx.save_model", calls.append)
|
||||
|
||||
result = runner.invoke(app, ["import-xlsx", str(target)])
|
||||
|
||||
assert result.exit_code == 0, result.stdout
|
||||
assert len(calls) == 1
|
||||
assert "Импортировано" in result.stdout
|
||||
assert "Базовая валюта" in result.stdout
|
||||
|
||||
def test_missing_file_exits_1(self, tmp_path, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr("infrastructure.cli.commands.import_xlsx.save_model", calls.append)
|
||||
|
||||
result = runner.invoke(app, ["import-xlsx", str(tmp_path / "nope.xlsx")])
|
||||
|
||||
assert result.exit_code == 1
|
||||
assert calls == []
|
||||
|
||||
|
||||
class TestRecurringAccountScope:
|
||||
def test_recurring_add_binds_account_by_name(self):
|
||||
_cleanup()
|
||||
try:
|
||||
runner.invoke(app, ["init"])
|
||||
runner.invoke(app, ["config", "account-add", "--name", "Основной", "--balance", "0"])
|
||||
|
||||
add = runner.invoke(app, [
|
||||
"config", "recurring-add",
|
||||
"--amount", "-500",
|
||||
"--account", "основной",
|
||||
])
|
||||
assert add.exit_code == 0, add.stdout
|
||||
|
||||
lst = runner.invoke(app, ["config", "recurring-list"])
|
||||
assert "Основной" in lst.stdout
|
||||
|
||||
info = runner.invoke(app, ["info"])
|
||||
assert "Основной" in info.stdout
|
||||
finally:
|
||||
_cleanup()
|
||||
|
||||
def test_recurring_add_unknown_account_fails(self):
|
||||
_cleanup()
|
||||
try:
|
||||
runner.invoke(app, ["init"])
|
||||
result = runner.invoke(app, [
|
||||
"config", "recurring-add", "--amount", "-500", "--account", "Нет такого",
|
||||
])
|
||||
assert result.exit_code == 1
|
||||
finally:
|
||||
_cleanup()
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from domain import FinancialModel
|
||||
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError, write_template
|
||||
from infrastructure.repositories.excel_repository import CANONICAL_COLUMNS, SHEET_ORDER
|
||||
|
||||
_EXPECTED_SHEETS = list(SHEET_ORDER) + ["Инструкция"]
|
||||
|
||||
|
||||
def _headers(ws) -> list:
|
||||
return [cell.value for cell in ws[1]]
|
||||
|
||||
|
||||
def _instruction_text(path: Path) -> str:
|
||||
wb = load_workbook(path)
|
||||
try:
|
||||
return "\n".join(
|
||||
str(cell.value)
|
||||
for row in wb["Инструкция"].iter_rows()
|
||||
for cell in row
|
||||
if cell.value is not None
|
||||
)
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
class TestWriteTemplate:
|
||||
def test_creates_file(self, tmp_path: Path):
|
||||
path = write_template(tmp_path / "template.xlsx")
|
||||
assert path == tmp_path / "template.xlsx"
|
||||
assert path.exists()
|
||||
|
||||
def test_sheets_and_canonical_headers(self, tmp_path: Path):
|
||||
path = write_template(tmp_path / "template.xlsx")
|
||||
wb = load_workbook(path)
|
||||
try:
|
||||
assert wb.sheetnames == _EXPECTED_SHEETS
|
||||
assert _headers(wb["ModelInfo"]) == ["Property", "Value"]
|
||||
for sheet_name, columns in CANONICAL_COLUMNS.items():
|
||||
assert _headers(wb[sheet_name]) == list(columns), sheet_name
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
def test_template_loads_as_empty_model(self, tmp_path: Path):
|
||||
path = write_template(tmp_path / "template.xlsx")
|
||||
|
||||
result = ExcelRepository().load_report(path)
|
||||
|
||||
assert result.errors == []
|
||||
assert result.model == FinancialModel()
|
||||
assert ExcelRepository().load(path) == FinancialModel()
|
||||
|
||||
def test_existing_file_requires_force(self, tmp_path: Path):
|
||||
path = tmp_path / "template.xlsx"
|
||||
path.write_bytes(b"not an xlsx")
|
||||
|
||||
with pytest.raises(ExcelRepositoryError):
|
||||
write_template(path)
|
||||
|
||||
assert path.read_bytes() == b"not an xlsx"
|
||||
|
||||
def test_force_overwrites_existing_file(self, tmp_path: Path):
|
||||
path = tmp_path / "template.xlsx"
|
||||
path.write_bytes(b"not an xlsx")
|
||||
|
||||
returned = write_template(path, force=True)
|
||||
|
||||
assert returned == path
|
||||
wb = load_workbook(path)
|
||||
try:
|
||||
assert wb.sheetnames == _EXPECTED_SHEETS
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
def test_creates_missing_parent_directories(self, tmp_path: Path):
|
||||
path = write_template(tmp_path / "nested" / "dir" / "template.xlsx")
|
||||
assert path.exists()
|
||||
|
||||
def test_currency_and_frequency_validations(self, tmp_path: Path):
|
||||
path = write_template(tmp_path / "template.xlsx")
|
||||
wb = load_workbook(path)
|
||||
try:
|
||||
accounts_formulas = " ".join(
|
||||
validation.formula1 for validation in wb["Accounts"].data_validations.dataValidation
|
||||
)
|
||||
assert "RUB" in accounts_formulas
|
||||
assert "JPY" in accounts_formulas
|
||||
|
||||
recurring_formulas = " ".join(
|
||||
validation.formula1 for validation in wb["Recurring"].data_validations.dataValidation
|
||||
)
|
||||
assert "monthly" in recurring_formulas
|
||||
assert "ежемесячно" in recurring_formulas
|
||||
|
||||
transactions_formulas = " ".join(
|
||||
validation.formula1 for validation in wb["Transactions"].data_validations.dataValidation
|
||||
)
|
||||
assert "Accounts!$B$2:$B$500" in transactions_formulas
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
def test_instruction_sheet_mentions_workflow_and_sign_convention(self, tmp_path: Path):
|
||||
path = write_template(tmp_path / "template.xlsx")
|
||||
text = _instruction_text(path)
|
||||
|
||||
assert "cf import-xlsx" in text
|
||||
assert "положительная = доход" in text
|
||||
assert "id можно оставить пустым" in text
|
||||
assert "счёт указывается по имени" in text
|
||||
assert "31.01.2026" in text
|
||||
for sheet_name in CANONICAL_COLUMNS:
|
||||
assert sheet_name in text
|
||||
|
||||
def test_template_has_no_data_rows(self, tmp_path: Path):
|
||||
path = write_template(tmp_path / "template.xlsx")
|
||||
wb = load_workbook(path)
|
||||
try:
|
||||
for sheet_name in CANONICAL_COLUMNS:
|
||||
rows = [
|
||||
row
|
||||
for row in wb[sheet_name].iter_rows(min_row=2, values_only=True)
|
||||
if any(value is not None for value in row)
|
||||
]
|
||||
assert rows == [], sheet_name
|
||||
finally:
|
||||
wb.close()
|
||||
@@ -1,6 +1,7 @@
|
||||
import pytest
|
||||
|
||||
from application.forecast import ForecastError, ForecastService
|
||||
from domain import Account, FinancialModel, RecurringCashflow, Transaction
|
||||
|
||||
|
||||
class TestForecastService:
|
||||
@@ -34,3 +35,80 @@ class TestForecastService:
|
||||
service = ForecastService(empty_model)
|
||||
results = service.forecast_cashflow(months=3)
|
||||
assert results == []
|
||||
|
||||
|
||||
class TestAccountAttribution:
|
||||
"""Модели, собранные в Excel или руками, ссылаются на счёт по имени."""
|
||||
|
||||
def _model(self, *accounts):
|
||||
return FinancialModel(accounts=list(accounts))
|
||||
|
||||
def test_transaction_matched_by_account_name(self):
|
||||
acc = Account(name="Основной", balance=0)
|
||||
model = self._model(acc)
|
||||
model.transactions = [
|
||||
Transaction(date="2026-01-01", account="Основной", amount=1000),
|
||||
Transaction(date="2026-01-01", account="основной ", amount=-300),
|
||||
]
|
||||
results = ForecastService(model).forecast_cashflow(months=1)
|
||||
assert len(results) == 1
|
||||
assert results[0]["income"] == 1000
|
||||
assert results[0]["expenses"] == 300
|
||||
|
||||
def test_transaction_matched_by_account_id(self):
|
||||
acc = Account(name="Основной", balance=0)
|
||||
model = self._model(acc)
|
||||
model.transactions = [
|
||||
Transaction(date="2026-01-01", account=str(acc.id), amount=250),
|
||||
]
|
||||
results = ForecastService(model).forecast_cashflow(months=1)
|
||||
assert results[0]["income"] == 250
|
||||
|
||||
def test_recurring_scoped_to_one_account(self):
|
||||
first = Account(name="Основной", balance=0)
|
||||
second = Account(name="Сбережения", balance=0)
|
||||
model = self._model(first, second)
|
||||
model.recurring = [
|
||||
RecurringCashflow(start_date="2026-01-01", frequency="monthly",
|
||||
amount=500, category="income", account="Основной"),
|
||||
]
|
||||
results = ForecastService(model).forecast_cashflow(months=1)
|
||||
by_account = {r["account"]: r for r in results}
|
||||
assert by_account["Основной"]["income"] == 500
|
||||
assert by_account["Сбережения"]["income"] == 0
|
||||
|
||||
def test_recurring_without_account_applies_to_all(self):
|
||||
model = self._model(Account(name="A"), Account(name="B"))
|
||||
model.recurring = [
|
||||
RecurringCashflow(start_date="2026-01-01", frequency="monthly", amount=100),
|
||||
]
|
||||
results = ForecastService(model).forecast_cashflow(months=1)
|
||||
assert all(r["income"] == 100 for r in results)
|
||||
|
||||
|
||||
class TestSummary:
|
||||
def test_total_balance_sums_all_accounts_of_last_month(self):
|
||||
model = FinancialModel(
|
||||
accounts=[Account(name="A", balance=100), Account(name="B", balance=200)],
|
||||
)
|
||||
summary = ForecastService(model).summary(months=1)
|
||||
assert summary["total_balance"] == 300
|
||||
|
||||
def test_total_balance_is_not_one_account_row(self):
|
||||
model = FinancialModel(
|
||||
accounts=[Account(name="A", balance=100), Account(name="B", balance=200)],
|
||||
)
|
||||
summary = ForecastService(model).summary(months=3)
|
||||
assert summary["total_balance"] == 300
|
||||
|
||||
def test_summary_matches_last_month_rows(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
rows = service.forecast_cashflow(6)
|
||||
summary = service.summary(6)
|
||||
last_month = max(r["month"] for r in rows)
|
||||
expected = sum(r["balance"] for r in rows if r["month"] == last_month)
|
||||
assert summary["total_balance"] == expected
|
||||
|
||||
def test_forecast_is_idempotent(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
assert service.forecast_cashflow(6) == service.forecast_cashflow(6)
|
||||
@@ -13,7 +13,6 @@ from domain import (
|
||||
)
|
||||
from infrastructure.repositories import JsonFileRepository
|
||||
|
||||
|
||||
_repo = JsonFileRepository()
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from domain import Account, Asset, FinancialModel, Transaction
|
||||
from application.repositories import ModelRepository
|
||||
from domain import Account, Asset, FinancialModel, Transaction
|
||||
from infrastructure.repositories import JsonFileRepository
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user