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() p = tmp_path / "test.xlsx" repo.save(sample_model, p) assert p.exists() def test_export_import_roundtrip(self, sample_model, tmp_path: Path): repo = ExcelRepository() p = tmp_path / "roundtrip.xlsx" repo.save(sample_model, p) loaded = repo.load(p) assert len(loaded.accounts) == len(sample_model.accounts) assert len(loaded.transactions) == len(sample_model.transactions) assert len(loaded.recurring) == len(sample_model.recurring) assert len(loaded.assets) == len(sample_model.assets) assert len(loaded.liabilities) == len(sample_model.liabilities) assert len(loaded.exchange_rates) == len(sample_model.exchange_rates) def test_roundtrip_preserves_base_currency(self, tmp_path: Path): repo = ExcelRepository() model = FinancialModel(base_currency="EUR") p = tmp_path / "eur_model.xlsx" repo.save(model, p) loaded = repo.load(p) assert loaded.base_currency == "EUR" def test_import_missing_file(self): repo = ExcelRepository() try: repo.load("nonexistent.xlsx") assert False, "Expected ExcelRepositoryError" except ExcelRepositoryError: pass def test_export_empty_model(self, tmp_path: Path): repo = ExcelRepository() model = FinancialModel() 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)