From 6b13a15408325e751f2be848393250f17dabce36 Mon Sep 17 00:00:00 2001 From: oqyude Date: Sun, 15 Nov 2026 06:12:06 +0300 Subject: [PATCH] =?UTF-8?q?D35,=20D36:=20Excel=20=D0=BA=D0=B0=D0=BA=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B2=D0=B5=D1=80=D1=85=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=8C=20=D1=81=D0=B1=D0=BE=D1=80=D0=BA=D0=B8=20=D0=BC=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Импорт и выгрузка переработаны в полноценную поверхность авторства. Схема (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). --- application/forecast.py | 37 +- domain/recurrence.py | 5 +- domain/recurring.py | 3 + infrastructure/cli/app.py | 2 + .../cli/commands/config/display_currency.py | 4 +- infrastructure/cli/commands/import_xlsx.py | 80 ++- infrastructure/cli/commands/template_xlsx.py | 29 + infrastructure/cli/services.py | 16 +- infrastructure/i18n/ru.py | 22 + infrastructure/repositories/__init__.py | 19 +- .../repositories/excel_repository.py | 624 +++++++++++++----- infrastructure/repositories/excel_schema.py | 256 +++++++ infrastructure/repositories/excel_template.py | 321 +++++++++ tests/test_cli_contract.py | 13 +- tests/test_excel_authoring.py | 360 ++++++++++ tests/test_excel_sync.py | 17 +- tests/test_forecast.py | 16 +- 17 files changed, 1612 insertions(+), 212 deletions(-) create mode 100644 infrastructure/cli/commands/template_xlsx.py create mode 100644 infrastructure/repositories/excel_schema.py create mode 100644 infrastructure/repositories/excel_template.py create mode 100644 tests/test_excel_authoring.py diff --git a/application/forecast.py b/application/forecast.py index c736af3..fc9b37c 100644 --- a/application/forecast.py +++ b/application/forecast.py @@ -107,8 +107,7 @@ class ForecastService: for li in self.model.liabilities ] asset_values = [ - self._to_base(a.value, a.currency or base, f"актив «{a.name}»") or _ZERO - for a in self.model.assets + self._to_base(a.value, a.currency or base, f"актив «{a.name}»") or _ZERO for a in self.model.assets ] account_balances = [ self._to_base(account.balance, account.currency or base, f"счёт «{account.name}»") or _ZERO @@ -119,8 +118,9 @@ class ForecastService: transactions_by_account = self._group_transactions(months, base) # Регулярные платежи — сумма списания переводится в базовую валюту - # один раз, а не на каждый месяц (D34). - recurring_base: list[tuple[RecurringCashflow, Decimal]] = [] + # один раз, а не на каждый месяц (D34). `account_index` — счёт, к + # которому привязан платёж (None = ко всем счетам, D35). + recurring_base: list[tuple[RecurringCashflow, Decimal, int | None]] = [] for r in self.model.recurring: amount = self._to_base( r.amount, @@ -129,7 +129,13 @@ class ForecastService: ) if amount is None: continue - recurring_base.append((r, amount)) + target = self._account_index(r.account) if r.account else None + if r.account and target is None: + self.warnings.append( + f"Регулярный платёж «{r.category or r.id}» — счёт «{r.account}» не найден, платёж пропущен" + ) + continue + recurring_base.append((r, amount, target)) results = [] for index, account in enumerate(self.model.accounts): @@ -139,6 +145,7 @@ class ForecastService: liability_balances, transactions_by_account.get(index, []), recurring_base, + index, ) for m in range(months): results.append( @@ -193,16 +200,12 @@ class ForecastService: return self._converter.convert(amount, source, base) except CurrencyError: prefix = f"{subject}: " if subject else "" - self.warnings.append( - f"{prefix}нет курса {source} → {base}, сумма {amount} {source} не учтена в прогнозе" - ) + self.warnings.append(f"{prefix}нет курса {source} → {base}, сумма {amount} {source} не учтена в прогнозе") return None # -- транзакции --------------------------------------------------------- - def _group_transactions( - self, months: int, base: str - ) -> dict[int, list[tuple[int, Decimal]]]: + def _group_transactions(self, months: int, base: str) -> dict[int, list[tuple[int, Decimal]]]: """Разложить транзакции по счетам и месяцам сетки прогноза (D33). Возвращает словарь «индекс счёта → список (месяц сетки, сумма)». @@ -213,9 +216,7 @@ class ForecastService: account_index = self._account_index(t.account) if account_index is None: label = t.description or t.category or str(t.id) - self.warnings.append( - f"Транзакция «{label}» — счёт «{t.account}» не найден, операция пропущена" - ) + self.warnings.append(f"Транзакция «{label}» — счёт «{t.account}» не найден, операция пропущена") continue month_index = self._transaction_month(t.date) @@ -266,7 +267,8 @@ class ForecastService: months: int, liability_balances: list[Decimal], transactions: list[tuple[int, Decimal]], - recurring_base: list[tuple[RecurringCashflow, Decimal]], + recurring_base: list[tuple[RecurringCashflow, Decimal, int | None]], + account_index: int, ) -> list[dict]: balance = start_balance monthly = [] @@ -290,7 +292,10 @@ class ForecastService: else: expenses += abs(amount) - for r, unit_amount in recurring_base: + for r, unit_amount, target in recurring_base: + # D35: платёж, привязанный к счёту, учитывается только на нём. + if target is not None and target != account_index: + continue # D32: платёж раскладывается по календарю — сколько и каких # списаний выпадает в этот месяц, решает сам календарь # (daily/weekly/monthly/yearly), а не делитель периода. diff --git a/domain/recurrence.py b/domain/recurrence.py index a358a0c..afbb877 100644 --- a/domain/recurrence.py +++ b/domain/recurrence.py @@ -15,6 +15,7 @@ Реализация — на ``dateutil.rrule``: это готовая библиотека для календарных правил повторения, писать свой планировщик вместо неё незачем. """ + from __future__ import annotations from datetime import date, datetime, time @@ -98,9 +99,7 @@ def normalize_frequency(value: str) -> str: raise RecurrenceError("периодичность не указана — допустимо: " + ", ".join(FREQUENCIES)) text = _FREQ_ALIASES.get(text, text) if text not in _FREQ_MAP: - raise RecurrenceError( - f"неизвестная периодичность: {value} — допустимо: " + ", ".join(FREQUENCIES) - ) + raise RecurrenceError(f"неизвестная периодичность: {value} — допустимо: " + ", ".join(FREQUENCIES)) return text diff --git a/domain/recurring.py b/domain/recurring.py index feb9a04..28d29b2 100644 --- a/domain/recurring.py +++ b/domain/recurring.py @@ -20,6 +20,9 @@ class RecurringCashflow(BaseModel): # месяц — решает календарь, а не делитель периода. amount: Decimal = Field(default=Decimal("0")) category: str = "" + # Счёт, к которому привязан платёж: UUID или имя счёта. Пусто — платёж + # относится ко всем счетам (D35: Excel-автор указывает счёт по имени). + account: str = "" # Валюта суммы. Пусто = валюта счёта (или базовая валюта модели). currency: str = "" diff --git a/infrastructure/cli/app.py b/infrastructure/cli/app.py index 0accfdc..b3506ad 100644 --- a/infrastructure/cli/app.py +++ b/infrastructure/cli/app.py @@ -19,6 +19,7 @@ from infrastructure.cli.commands import ( info, init, scenario, + template_xlsx, whatif, ) from infrastructure.i18n import setup_i18n, t @@ -35,6 +36,7 @@ app.command(name="whatif")(whatif.whatif) app.command(name="compare")(compare.compare) app.command(name="import-xlsx")(import_xlsx.import_xlsx) app.command(name="export-xlsx")(export_xlsx.export_xlsx) +app.command(name="template-xlsx")(template_xlsx.template_xlsx) app.command(name="analyze")(analyze.analyze) app.command(name="info")(info.info) diff --git a/infrastructure/cli/commands/config/display_currency.py b/infrastructure/cli/commands/config/display_currency.py index 77bdf85..44f9b9c 100644 --- a/infrastructure/cli/commands/config/display_currency.py +++ b/infrastructure/cli/commands/config/display_currency.py @@ -19,6 +19,4 @@ def display_currency( save_model(model) print_ok(t("cmd.config.display_currency.ok", currency=model.display_currency)) else: - console.print( - t("cmd.config.display_currency.show", currency=f"[bold]{model.output_currency}[/bold]") - ) + console.print(t("cmd.config.display_currency.show", currency=f"[bold]{model.output_currency}[/bold]")) diff --git a/infrastructure/cli/commands/import_xlsx.py b/infrastructure/cli/commands/import_xlsx.py index c34deb5..cb519fe 100644 --- a/infrastructure/cli/commands/import_xlsx.py +++ b/infrastructure/cli/commands/import_xlsx.py @@ -1,32 +1,80 @@ -"""cf import-xlsx — импорт данных из Excel.""" +"""`cf import-xlsx` — импорт модели из Excel. + +Импорт терпимый: заголовки принимаются на русском и английском, числа и даты +разбираются в пользовательских форматах, счёт — по имени или UUID. Ошибки +строк собираются в таблицу с адресом «лист!строка»; файл с ошибками не +сохраняется. `--dry-run` проверяет файл, не трогая модель. +""" import typer +from rich.markup import escape +from rich.table import Table from infrastructure.cli.services import console, save_model from infrastructure.i18n import t -from infrastructure.repositories import ExcelRepository, ExcelRepositoryError +from infrastructure.repositories import ExcelRepository, ExcelRepositoryError, ExcelRowError _repo = ExcelRepository() +def _counts(model) -> dict[str, int]: + return { + "accounts": len(model.accounts), + "transactions": len(model.transactions), + "recurring": len(model.recurring), + "assets": len(model.assets), + "liabilities": len(model.liabilities), + } + + +def _print_warnings(warnings: list[str]) -> None: + for warning in warnings: + console.print(f"[yellow]{t('cmd.import.warn', warning=escape(warning))}[/yellow]") + + +def _print_errors(errors: list[ExcelRowError]) -> None: + table = Table(title=t("cmd.import.errors.title", count=len(errors))) + table.add_column(t("cmd.import.errors.col.sheet")) + table.add_column(t("cmd.import.errors.col.row"), justify="right") + table.add_column(t("cmd.import.errors.col.field")) + table.add_column(t("cmd.import.errors.col.message")) + for error in errors: + table.add_row( + escape(error.sheet), + str(error.row), + escape(error.field) or "—", + escape(error.message), + ) + console.print(table) + console.print(f"[red]{t('cmd.import.errors.hint', first=escape(str(errors[0])))}[/red]") + + def import_xlsx( path: str = typer.Argument(..., help=t("cmd.import.arg.path")), + dry_run: bool = typer.Option(False, "--dry-run", help=t("cmd.import.opt.dry_run")), ) -> None: """Импорт данных из Excel""" try: - model = _repo.load(path) - save_model(model) - console.print( - t( - "cmd.import.ok", - accounts=len(model.accounts), - transactions=len(model.transactions), - recurring=len(model.recurring), - assets=len(model.assets), - liabilities=len(model.liabilities), - ) - ) - console.print(t("cmd.import.base_currency", currency=model.base_currency)) + report = _repo.load_report(path) except ExcelRepositoryError as e: - console.print(f"[red]{t('cmd.import.err', error=str(e))}[/red]") + console.print(f"[red]{t('cmd.import.err', error=escape(str(e)))}[/red]") raise typer.Exit(1) + + _print_warnings(report.warnings) + + if report.errors: + _print_errors(report.errors) + raise typer.Exit(1) + + counts = _counts(report.model) + + if dry_run: + console.print(t("cmd.import.dry_run.title")) + console.print(t("cmd.import.dry_run.ok", **counts)) + console.print(t("cmd.import.dry_run.base_currency", currency=report.model.base_currency)) + console.print(f"[yellow]{t('cmd.import.dry_run.not_saved')}[/yellow]") + return + + save_model(report.model) + console.print(t("cmd.import.ok", **counts)) + console.print(t("cmd.import.base_currency", currency=report.model.base_currency)) diff --git a/infrastructure/cli/commands/template_xlsx.py b/infrastructure/cli/commands/template_xlsx.py new file mode 100644 index 0000000..9cb1e6b --- /dev/null +++ b/infrastructure/cli/commands/template_xlsx.py @@ -0,0 +1,29 @@ +"""`cf template-xlsx` — создать Excel-шаблон для ручного заполнения модели.""" + +from pathlib import Path + +import typer +from rich.markup import escape + +from infrastructure.cli.paths import AppPaths +from infrastructure.cli.services import console +from infrastructure.i18n import t +from infrastructure.repositories import TemplateError, write_template + + +def template_xlsx( + path: Path = typer.Argument( + AppPaths.from_env().data_dir / "model_template.xlsx", + help=t("cmd.template.arg.path"), + ), + force: bool = typer.Option(False, "--force", "-f", help=t("cmd.template.opt.force")), +) -> None: + """Создать Excel-шаблон для заполнения модели""" + try: + target = write_template(path, force=force) + except TemplateError as e: + console.print(f"[red]{t('cmd.template.err', error=escape(str(e)))}[/red]") + raise typer.Exit(1) + + console.print(t("cmd.template.ok", path=escape(str(target)))) + console.print(t("cmd.template.hint", path=escape(str(target)))) diff --git a/infrastructure/cli/services.py b/infrastructure/cli/services.py index 0fedb61..dc34bbf 100644 --- a/infrastructure/cli/services.py +++ b/infrastructure/cli/services.py @@ -2,6 +2,7 @@ from __future__ import annotations +import shutil from decimal import Decimal from typing import NoReturn @@ -55,7 +56,20 @@ def load_model() -> FinancialModel: def save_model(model: FinancialModel) -> None: - _json_repo.save(model, AppPaths.from_env().model_path) + """Сохранить модель. Прежний файл остаётся рядом как `.bak` (D35). + + Импорт из Excel заменяет модель целиком — если файл оказался не тем, + прежнее состояние можно вернуть одной командой копирования. + """ + model_path = AppPaths.from_env().model_path + if model_path.exists(): + backup_path = model_path.with_suffix(model_path.suffix + ".bak") + try: + shutil.copy2(model_path, backup_path) + console.print(f"[dim]{t('cmd.import.backup', path=backup_path)}[/dim]") + except OSError as exc: + console.print(f"[yellow]{t('cmd.import.backup_failed', error=exc)}[/yellow]") + _json_repo.save(model, model_path) def build_services( diff --git a/infrastructure/i18n/ru.py b/infrastructure/i18n/ru.py index d0450ea..6312639 100644 --- a/infrastructure/i18n/ru.py +++ b/infrastructure/i18n/ru.py @@ -44,6 +44,28 @@ MESSAGES: dict[str, str] = { "{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств", "cmd.import.base_currency": "Базовая валюта: {currency}", "cmd.import.err": "Ошибка импорта: {error}", + "cmd.import.warn": "Предупреждение: {warning}", + "cmd.import.opt.dry_run": "Только проверить файл, не сохраняя модель", + "cmd.import.dry_run.title": "Проверка файла (--dry-run):", + "cmd.import.dry_run.ok": "В файле: счета — {accounts}, транзакции — {transactions}, " + "регулярные платежи — {recurring}, активы — {assets}, обязательства — {liabilities}", + "cmd.import.dry_run.base_currency": "Базовая валюта: {currency}", + "cmd.import.dry_run.not_saved": "Модель не сохранена (--dry-run)", + "cmd.import.errors.title": "Ошибки в файле: {count}", + "cmd.import.errors.col.sheet": "Лист", + "cmd.import.errors.col.row": "Строка", + "cmd.import.errors.col.field": "Столбец", + "cmd.import.errors.col.message": "Сообщение", + "cmd.import.errors.hint": "Файл не сохранён. Первая ошибка: {first}", + "cmd.import.backup": "Прежняя модель сохранена: {path}", + "cmd.import.backup_failed": "Не удалось сохранить резервную копию модели: {error}", + "cmd.template.help": "Создать Excel-шаблон для заполнения модели", + "cmd.template.arg.path": "Путь для .xlsx файла", + "cmd.template.opt.force": "Перезаписать существующий файл", + "cmd.template.ok": "Шаблон создан: {path}", + "cmd.template.hint": "Заполните шаблон и загрузите модель: {path}", + "cmd.template.err": "Ошибка шаблона: {error}", + "cmd.template.err.exists": "Файл уже существует: {path} — используйте --force", "cmd.export.help": "Экспорт модели в Excel", "cmd.export.arg.path": "Путь для .xlsx файла", "cmd.export.ok": "Модель экспортирована в {path}", diff --git a/infrastructure/repositories/__init__.py b/infrastructure/repositories/__init__.py index 02721f4..cd01b97 100644 --- a/infrastructure/repositories/__init__.py +++ b/infrastructure/repositories/__init__.py @@ -1,4 +1,19 @@ -from infrastructure.repositories.excel_repository import ExcelRepository, ExcelRepositoryError +from infrastructure.repositories.excel_repository import ( + ExcelImportResult, + ExcelRepository, + ExcelRepositoryError, + ExcelRowError, +) +from infrastructure.repositories.excel_template import TemplateError, write_template, write_workbook from infrastructure.repositories.json_file_repository import JsonFileRepository -__all__ = ["JsonFileRepository", "ExcelRepository", "ExcelRepositoryError"] +__all__ = [ + "JsonFileRepository", + "ExcelRepository", + "ExcelRepositoryError", + "ExcelImportResult", + "ExcelRowError", + "TemplateError", + "write_template", + "write_workbook", +] diff --git a/infrastructure/repositories/excel_repository.py b/infrastructure/repositories/excel_repository.py index 057adef..3b56e6a 100644 --- a/infrastructure/repositories/excel_repository.py +++ b/infrastructure/repositories/excel_repository.py @@ -1,194 +1,516 @@ -"""ExcelRepository — хранит FinancialModel в .xlsx. +"""ExcelRepository — .xlsx как поверхность сборки модели (D35). -Состав листов, порядок полей и классы моделей описаны одной декларативной -таблицей `SHEETS` (D28). `save()` и `load()` идут по этой таблице, поэтому -новый лист добавляется одной записью в `SHEETS` — без новых веток -`if sheet_name == ...` в коде записи или чтения. +Файл читается терпимо: заголовки принимаются на русском и английском в любом +порядке и регистре, числа — в пользовательских форматах («1 234,56», «₽1200», +«(100)» = −100), даты — и как даты Excel, и как текст. Ошибки строк не +роняют импорт: они собираются в отчёт с адресом «лист!строка», и файл с +ошибками не сохраняется. -Листы данных: Accounts, Transactions, Recurring, Assets, Liabilities, -ExchangeRates, Scenarios. Плюс служебный лист ModelInfo (base_currency). +Публичный контракт: + +- ``ExcelRepository.load(path)`` — модель или ``ExcelRepositoryError``; +- ``ExcelRepository.load_report(path)`` — модель + ошибки + предупреждения; +- ``ExcelRepository.save(model, path)`` — записать модель в .xlsx. + +Устройство листов описано в `excel_schema` (таблица `SHEETS`) — она же +источник заголовков, синонимов и типов значений (D28). """ -from dataclasses import dataclass -from pathlib import Path -from typing import Any -from uuid import UUID +from __future__ import annotations -from openpyxl import Workbook, load_workbook -from pydantic import BaseModel +import re +from dataclasses import dataclass, field +from datetime import date, datetime +from decimal import Decimal, InvalidOperation +from pathlib import Path +from uuid import UUID +from zipfile import BadZipFile + +from openpyxl import load_workbook +from openpyxl.utils.exceptions import InvalidFileException +from pydantic import ValidationError from application.repositories.model_repository import ModelRepository -from domain import ( - Account, - Asset, - ExchangeRate, - FinancialModel, - ForecastScenario, - Liability, - RecurringCashflow, - Transaction, +from domain import Account, FinancialModel +from domain.recurrence import normalize_frequency +from infrastructure.repositories.excel_schema import ( + ACCOUNT, + ACCOUNT_OPTIONAL, + CURRENCY, + DATE, + DECIMAL, + FREQUENCY, + ID, + SHEETS, + Column, + InfoSheetSpec, + SheetSpec, + build_header_index, + is_empty, ) +from infrastructure.repositories.excel_template import TemplateError, write_workbook + +_MAX_ERRORS = 100 +_NON_NUMERIC = re.compile(r"[^0-9,.\-+]") + +# Частота: русские синонимы приводятся к канону (domain.recurrence). +_FREQUENCY_HELP = "daily / weekly / monthly / yearly (или ежедневно / еженедельно / ежемесячно / ежегодно)" class ExcelRepositoryError(Exception): - pass + """Ошибка импорта/экспорта .xlsx (файл не найден, ошибки данных, каталог).""" @dataclass(frozen=True) -class SheetSpec: - """Описание листа-коллекции. +class ExcelRowError: + """Одна ошибка строки листа (row — 1-based номер строки в Excel).""" - `fields` задаёт и заголовки, и порядок колонок; `collection` — имя поля - `FinancialModel`, в которое читаются строки и из которого они пишутся. - Специфику полей (например, отсутствие `id` у `ExchangeRates`) описывает - сам список `fields`, отдельного кода для этого не нужно. - """ + sheet: str + row: int + field: str + message: str - name: str - fields: tuple[str, ...] - cls: type[BaseModel] - collection: str + def __str__(self) -> str: + prefix = f"{self.sheet}!{self.row}" + if self.field: + prefix += f" [{self.field}]" + return f"{prefix}: {self.message}" - 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: +@dataclass +class ExcelImportResult: + """Результат импорта: модель + ошибки строк + предупреждения.""" + + model: FinancialModel + errors: list[ExcelRowError] = field(default_factory=list) + warnings: list[str] = field(default_factory=list) + + +class _IssueCollector: + """Сборщик ошибок и предупреждений импорта.""" + + def __init__(self) -> None: + self.errors: list[ExcelRowError] = [] + self.warnings: list[str] = [] + self.truncated = False + + def error(self, sheet: str, row: int, field_name: str, message: str) -> None: + if len(self.errors) >= _MAX_ERRORS: + self.truncated = True return + self.errors.append(ExcelRowError(sheet=sheet, row=row, field=field_name, message=message)) - 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)) + def warn(self, message: str) -> None: + if message not in self.warnings: + self.warnings.append(message) -@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 parse_decimal(value: object) -> Decimal: + """Разобрать число из ячейки: пробелы, запятая, символы валют, скобки.""" + if isinstance(value, bool): + raise ValueError(f"некорректное число «{value}»") + if isinstance(value, (int, float, Decimal)): + number = Decimal(str(value)) + if not number.is_finite(): + raise ValueError(f"некорректное число «{value}»") + return number + text = str(value).strip() + if not text: + raise ValueError("пустое число") -def _cell(value: Any) -> Any: - """Значение для записи в ячейку: UUID сериализуется строкой.""" - return str(value) if isinstance(value, UUID) else value + negative = text.startswith("(") and text.endswith(")") + if negative: + text = text[1:-1] + text = text.replace("\u00a0", "").replace("\u202f", "") + text = _NON_NUMERIC.sub("", text) # пробелы, символы валют, проценты, буквы + text = text.replace("(", "").replace(")", "") + if not text or text in {"-", "+", ".", ","}: + raise ValueError(f"некорректное число «{value}»") + sign = -1 if negative else 1 + if text[0] in "+-": + if text[0] == "-": + sign = -sign + text = text[1:] + if text.endswith(("-", "+")): + if text[-1] == "-": + sign = -sign + text = text[:-1] + if "-" in text or "+" in text: + raise ValueError(f"некорректное число «{value}»") -def _headers(header_row: tuple) -> list[str]: - return [str(header).strip().lower() if header else "" for header in header_row] + if "," in text and "." in text: + # Оба разделителя: запятая — тысячи, точка — десятичный. + text = text.replace(",", "") + elif "," in text: + if text.count(",") > 1: + text = text.replace(",", "") # 1,234,567 — запятые как тысячи + else: + text = text.replace(",", ".") + elif text.count(".") > 1: + text = text.replace(".", "") - -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"Не удалось разобрать строку листа {sheet_name}: {e}") from e + number = Decimal(text) + except InvalidOperation as exc: + raise ValueError(f"некорректное число «{value}»") from exc + if not number.is_finite(): + raise ValueError(f"некорректное число «{value}»") + return number if sign > 0 else -number + + +def parse_date_cell(value: object) -> str: + """Разобрать дату в ISO-формате `YYYY-MM-DD`.""" + if isinstance(value, datetime): + return value.date().isoformat() + if isinstance(value, date): + return value.isoformat() + + text = str(value).strip() + if not text: + raise ValueError("пустая дата") + text = text.split("T", 1)[0] + if " " in text: + text = text.split(" ", 1)[0] + for fmt in ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%Y/%m/%d", "%d-%m-%Y"): + try: + return datetime.strptime(text, fmt).date().isoformat() + except ValueError: + continue + raise ValueError( + f"некорректная дата «{value}» — используйте 2026-01-31, 31.01.2026, 31/01/2026, 2026/01/31 или 31-01-2026" + ) + + +def parse_id_cell(value: object) -> UUID | None: + """Разобрать UUID. Пустая ячейка — «сгенерировать автоматически».""" + text = str(value).strip() + if not text: + return None + try: + return UUID(text) + except ValueError: + raise ValueError(f"некорректный ID «{text}» — ожидается UUID или пустая ячейка") from None + + +def convert_cell(kind: str, value: object) -> object: + """Привести значение ячейки к типу столбца. Бросает ValueError с текстом.""" + if kind == ID: + return parse_id_cell(value) + if kind == DECIMAL: + return parse_decimal(value) + if kind == DATE: + return parse_date_cell(value) + if kind == CURRENCY: + return str(value).strip().upper() or None + if kind == FREQUENCY: + text = str(value).strip() + try: + return normalize_frequency(text) + except ValueError as exc: + raise ValueError(f"{exc} — {_FREQUENCY_HELP}") from None + if kind in {ACCOUNT, ACCOUNT_OPTIONAL}: + return str(value).strip() + text = str(value).strip() + return text or None + + +# --------------------------------------------------------------------------- +# Индекс счетов +# --------------------------------------------------------------------------- + + +@dataclass +class _AccountIndex: + """Счета, найденные на листе Accounts: по имени и по UUID.""" + + by_name: dict[str, str] = field(default_factory=dict) + by_id: set[str] = field(default_factory=set) + names: list[str] = field(default_factory=list) + + def describe(self) -> str: + if not self.names: + return "(на листе Accounts нет счетов)" + return ", ".join(self.names) + + def resolve(self, reference: str) -> str | None: + """UUID счёта по имени или UUID. ``None`` — счёт не найден.""" + text = str(reference).strip() + if not text: + return None + key = text.casefold().replace("ё", "е") + if key in self.by_name: + return self.by_name[key] + try: + uuid = UUID(text) + except ValueError: + return None + if str(uuid) in self.by_id: + return str(uuid) + return None + + +# --------------------------------------------------------------------------- +# Репозиторий +# --------------------------------------------------------------------------- class ExcelRepository(ModelRepository): + # -- импорт ------------------------------------------------------------- + def load(self, path: str | Path) -> FinancialModel: - p = Path(path) - if not p.exists(): - raise ExcelRepositoryError(f"Файл не найден: {p}") + """Прочитать модель; при ошибках данных поднять ``ExcelRepositoryError``.""" + result = self.load_report(path) + if result.errors: + shown = "; ".join(str(error) for error in result.errors[:5]) + tail = f"; … ещё {len(result.errors) - 5}" if len(result.errors) > 5 else "" + raise ExcelRepositoryError(f"Не удалось импортировать Excel: {len(result.errors)} ошибок — {shown}{tail}") + return result.model + + def load_report(self, path: str | Path) -> ExcelImportResult: + """Прочитать модель, собрав ошибки строк вместо исключения.""" + file_path = Path(path) + if not file_path.exists(): + raise ExcelRepositoryError(f"Файл не найден: {file_path}") + + collector = _IssueCollector() + model = FinancialModel() - wb = load_workbook(p, read_only=True, data_only=True) try: - model = FinancialModel() - # Курсы валют заданы DEFAULT_RATES; лист ExchangeRates их заменяет. - model.exchange_rates = [] + workbook = load_workbook(file_path, data_only=True) + except (BadZipFile, InvalidFileException, KeyError, OSError) as exc: + raise ExcelRepositoryError(f"Не удалось открыть Excel-файл {file_path}: {exc}") from exc + + try: + self._read_info_sheet(workbook, model) + accounts, index = self._read_accounts(workbook, collector) + model.accounts = accounts for spec in SHEETS: - spec.read(wb, model) + if not isinstance(spec, SheetSpec) or spec.collection == "accounts": + continue + setattr(model, spec.collection, self._read_sheet(spec, workbook, index, collector)) + self._check_formulas(file_path, workbook, collector) finally: - wb.close() - return model + workbook.close() + + if collector.truncated: + collector.warn(f"ошибок больше {_MAX_ERRORS} — показаны первые {_MAX_ERRORS}") + + return ExcelImportResult(model=model, errors=collector.errors, warnings=collector.warnings) + + def _read_info_sheet(self, workbook, model: FinancialModel) -> None: + """Прочитать ModelInfo: «свойство → значение».""" + for spec in SHEETS: + if not isinstance(spec, InfoSheetSpec): + continue + if spec.name not in workbook.sheetnames: + continue + accepted = spec.accepted_keys() + for row in workbook[spec.name].iter_rows(values_only=True): + if not row or is_empty(row[0]) or len(row) < 2: + continue + key = str(row[0]).strip().casefold().replace("ё", "е") + attribute = accepted.get(_normalize_key(key)) + if attribute is None: + continue + # Пустая ячейка — свойство не задано: иначе в модель попало + # бы «None» строкой. + if is_empty(row[1]): + continue + setattr(model, attribute, str(row[1]).strip().upper()) + + def _read_accounts(self, workbook, collector: _IssueCollector) -> tuple[list[Account], _AccountIndex]: + accounts: list[Account] = [] + index = _AccountIndex() + first_row: dict[str, int] = {} + for spec in SHEETS: + if not isinstance(spec, SheetSpec) or spec.collection != "accounts": + continue + for row_number, data in self._read_rows(spec, workbook, collector): + instance = self._validate(spec, data, row_number, collector) + if instance is None: + continue + accounts.append(instance) + key = instance.name.strip().casefold().replace("ё", "е") + if key: + if key in index.by_name: + collector.warn( + f"Accounts: имя счёта «{instance.name}» повторяется " + f"(строка {row_number}, первая — {first_row[key]}) — используется первая" + ) + else: + index.by_name[key] = str(instance.id) + index.names.append(instance.name) + first_row[key] = row_number + index.by_id.add(str(instance.id)) + return accounts, index + + def _read_sheet( + self, + spec: SheetSpec, + workbook, + index: _AccountIndex, + collector: _IssueCollector, + ) -> list: + instances = [] + for row_number, data in self._read_rows(spec, workbook, collector): + if spec.collection in {"transactions", "recurring"}: + reference = data.get("account") + if reference is not None: + resolved = index.resolve(reference) + if resolved is None: + collector.error( + spec.name, + row_number, + "account", + f"неизвестный счёт «{reference}»; известные счета: {index.describe()}", + ) + continue + data["account"] = resolved + instance = self._validate(spec, data, row_number, collector) + if instance is not None: + instances.append(instance) + return instances + + def _read_rows( + self, + spec: SheetSpec, + workbook, + collector: _IssueCollector, + ) -> list[tuple[int, dict]]: + """Строки листа как пары (номер строки, данные по полям).""" + if spec.name not in workbook.sheetnames: + collector.warn(f"{spec.name}: лист отсутствует") + return [] + + sheet = workbook[spec.name] + header = next(sheet.iter_rows(min_row=1, max_row=1, values_only=True), ()) + if not any(not is_empty(value) for value in header): + return [] + + columns = self._map_columns(spec, header, collector) + if not columns: + collector.warn(f"{spec.name}: не найдено ни одного известного столбца — лист пропущен") + return [] + + rows: list[tuple[int, dict]] = [] + for offset, raw_row in enumerate(sheet.iter_rows(min_row=2, values_only=True)): + row_number = offset + 2 + if not any(not is_empty(value) for value in raw_row): + continue + data: dict[str, object] = {} + row_ok = True + for column, column_index in columns.items(): + value = raw_row[column_index] if column_index < len(raw_row) else None + if is_empty(value): + continue + try: + converted = convert_cell(column.kind, value) + except ValueError as exc: + collector.error(spec.name, row_number, column.field, str(exc)) + row_ok = False + continue + if converted is not None: + data[column.field] = converted + if row_ok: + rows.append((row_number, data)) + return rows + + def _map_columns( + self, + spec: SheetSpec, + header: tuple, + collector: _IssueCollector, + ) -> dict[Column, int]: + index = build_header_index(spec) + columns: dict[Column, int] = {} + for column_index, raw in enumerate(header): + if is_empty(raw): + continue + key = _normalize_key(str(raw)) + column = index.get(key) + if column is None: + collector.warn(f"{spec.name}: неизвестный столбец «{str(raw).strip()}» — пропущен") + continue + if column in columns: + collector.warn(f"{spec.name}: столбец «{column.header}» задан дважды — используется первый") + continue + columns[column] = column_index + return columns + + def _validate( + self, + spec: SheetSpec, + data: dict, + row_number: int, + collector: _IssueCollector, + ): + try: + return spec.cls.model_validate(data) + except ValidationError as exc: + for error in exc.errors(): + field_name = ".".join(str(part) for part in error.get("loc", ())) + message = str(error.get("msg", "ошибка валидации")) + if message.startswith("Value error, "): + message = message[len("Value error, ") :] + collector.error(spec.name, row_number, field_name, message) + except (TypeError, ValueError) as exc: + collector.error(spec.name, row_number, "", str(exc)) + return None + + def _check_formulas(self, file_path: Path, workbook, collector: _IssueCollector) -> None: + """Предупредить о формулах без сохранённого значения (Excel не пересчитал).""" + try: + formulas = load_workbook(file_path, data_only=False) + except (BadZipFile, InvalidFileException, OSError): + return + try: + for sheet in formulas.worksheets: + cached_sheet = workbook[sheet.title] if sheet.title in workbook.sheetnames else None + for row in sheet.iter_rows(): + for cell in row: + is_formula = cell.data_type == "f" or ( + isinstance(cell.value, str) and cell.value.startswith("=") + ) + if not is_formula: + continue + cached = cached_sheet[cell.coordinate].value if cached_sheet is not None else None + if cached is None: + collector.warn( + f"{sheet.title}!{cell.row}: формула без сохранённого значения — " + "пересчитайте и сохраните файл в Excel" + ) + finally: + formulas.close() + + # -- экспорт ------------------------------------------------------------ def save(self, model: FinancialModel, path: str | Path) -> None: - p = Path(path) - self._ensure_parent_dir(p) - - wb = Workbook() - wb.remove(wb.active) - for spec in SHEETS: - spec.write(wb, model) - + """Записать модель в .xlsx (файл пригоден для правки и обратного импорта).""" try: - wb.save(p) - except OSError as e: - raise ExcelRepositoryError(f"Не удалось сохранить файл {p}: {e}") from e + write_workbook(model, path, force=True, sheets=SHEETS) + except TemplateError as exc: + raise ExcelRepositoryError(str(exc)) from exc - @staticmethod - def _ensure_parent_dir(p: Path) -> None: - """Создать родительский каталог файла, если его нет (D19). - Раньше экспорт в несуществующий каталог падал с сырым - `FileNotFoundError` из openpyxl — без понятного сообщения. - """ - parent = p.parent - try: - parent.mkdir(parents=True, exist_ok=True) - except OSError as e: - raise ExcelRepositoryError(f"Не удалось создать каталог {parent}: {e}") from e +def _normalize_key(value: str) -> str: + """Ключ заголовка/свойства: без пробелов, ``_`` и ``-``; «ё» == «е».""" + text = value.strip().casefold().replace("ё", "е") + return re.sub(r"[\s_\-]+", "", text) + + +__all__ = [ + "ExcelImportResult", + "ExcelRepository", + "ExcelRepositoryError", + "ExcelRowError", + "SHEETS", + "parse_date_cell", + "parse_decimal", +] diff --git a/infrastructure/repositories/excel_schema.py b/infrastructure/repositories/excel_schema.py new file mode 100644 index 0000000..af84c7a --- /dev/null +++ b/infrastructure/repositories/excel_schema.py @@ -0,0 +1,256 @@ +"""Схема листов Excel — единственный источник истины (D28, D35). + +Таблица `SHEETS` описывает и запись, и чтение: список листов, их порядок, +заголовки столбцов, принимаемые синонимы заголовков и типы значений. + +Заголовки — русские (D19: всё, что видит пользователь, — на русском), но +импорт принимает и английские синонимы, и любой порядок столбцов, и любой +регистр: `_`/`-`/пробелы и «ё» не важны. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + +from pydantic import BaseModel + +from domain import ( + Account, + Asset, + ExchangeRate, + ForecastScenario, + Liability, + RecurringCashflow, + Transaction, +) + +# Типы значений в ячейках. +TEXT = "text" +DECIMAL = "decimal" +DATE = "date" +CURRENCY = "currency" +ID = "id" +FREQUENCY = "frequency" +ACCOUNT = "account" +ACCOUNT_OPTIONAL = "account_optional" + +# Форматы чисел и дат в Excel. +MONEY_FORMAT = "#,##0.00" +RATE_FORMAT = "0.00" +PERCENT_FORMAT = "0.00" +DATE_FORMAT = "yyyy-mm-dd" +TEXT_FORMAT = "@" + + +@dataclass(frozen=True) +class Column: + """Столбец листа Excel. + + `field` — имя поля модели; `header` — заголовок, который видит человек; + `kind` — тип значения (разбор при импорте); `aliases` — дополнительные + заголовки, которые принимаются при импорте. + """ + + field: str + header: str + kind: str = TEXT + aliases: tuple[str, ...] = () + number_format: str = "" + + def accepted_headers(self) -> tuple[str, ...]: + """Все варианты заголовка, которые принимает импорт.""" + return (self.header, self.field, *self.aliases) + + +@dataclass(frozen=True) +class SheetSpec: + """Описание листа-коллекции. + + `fields` — имена полей модели (в порядке колонок); `columns` — расширенное + описание (заголовок, тип, синонимы). Если `columns` не задан, строится + из `fields` — лист с заголовками в стиле модели. + """ + + name: str + fields: tuple[str, ...] + cls: type[BaseModel] + collection: str + columns: tuple[Column, ...] = () + + def resolved_columns(self) -> tuple[Column, ...]: + if self.columns: + return self.columns + return tuple(Column(field=field, header=field) for field in self.fields) + + @property + def headers(self) -> tuple[str, ...]: + return tuple(column.header for column in self.resolved_columns()) + + +@dataclass(frozen=True) +class InfoSheetSpec: + """Служебный лист «свойство → значение» (ModelInfo).""" + + name: str = "ModelInfo" + # (свойство модели, ключ в файле, подпись для человека) + properties: tuple[tuple[str, str, str], ...] = ( + ("base_currency", "base_currency", "Базовая валюта"), + ("display_currency", "display_currency", "Валюта вывода"), + ) + + @property + def headers(self) -> tuple[str, ...]: + return ("Свойство", "Значение") + + def accepted_keys(self) -> dict[str, str]: + """Ключ свойства → атрибут модели (принимаются и подписи, и ключи).""" + mapping: dict[str, str] = {} + for attr, key, label in self.properties: + for variant in (key, attr, label, label.casefold()): + mapping[_normalize_header(variant)] = attr + return mapping + + +# --------------------------------------------------------------------------- +# Таблица листов +# --------------------------------------------------------------------------- + +SHEETS: tuple[SheetSpec | InfoSheetSpec, ...] = ( + SheetSpec( + "Accounts", + ("id", "name", "currency", "balance"), + Account, + "accounts", + columns=( + Column("id", "ID", ID, ("ид", "идентификатор")), + Column("name", "Название", TEXT, ("имя", "наименование")), + Column("currency", "Валюта", CURRENCY, ("код валюты", "валюта счёта")), + Column("balance", "Баланс", DECIMAL, ("остаток", "остаток счёта"), MONEY_FORMAT), + ), + ), + SheetSpec( + "Transactions", + ("id", "date", "account", "category", "amount", "description", "currency"), + Transaction, + "transactions", + columns=( + Column("id", "ID", ID, ("ид", "идентификатор")), + Column("date", "Дата", DATE, ("дата операции", "дата транзакции"), DATE_FORMAT), + Column("account", "Счёт", ACCOUNT, ("счет", "имя счёта", "account_name")), + Column("category", "Категория", TEXT, ("категория операции",)), + Column("amount", "Сумма", DECIMAL, ("сумма операции",), MONEY_FORMAT), + Column("description", "Описание", TEXT, ("комментарий", "примечание")), + Column("currency", "Валюта", CURRENCY, ("валюта операции",)), + ), + ), + SheetSpec( + "Recurring", + ("id", "account", "start_date", "end_date", "frequency", "amount", "category", "currency"), + RecurringCashflow, + "recurring", + columns=( + Column("id", "ID", ID, ("ид", "идентификатор")), + Column("account", "Счёт", ACCOUNT_OPTIONAL, ("счет", "имя счёта")), + Column("start_date", "Начало", DATE, ("дата начала",), DATE_FORMAT), + Column("end_date", "Конец", DATE, ("дата окончания",), DATE_FORMAT), + Column( + "frequency", + "Периодичность", + FREQUENCY, + ("частота", "период"), + ), + Column("amount", "Сумма", DECIMAL, ("сумма платежа",), MONEY_FORMAT), + Column("category", "Категория", TEXT, ("категория платежа",)), + Column("currency", "Валюта", CURRENCY, ("валюта платежа",)), + ), + ), + SheetSpec( + "Assets", + ("id", "name", "value", "growth_rate", "currency"), + Asset, + "assets", + columns=( + Column("id", "ID", ID, ("ид", "идентификатор")), + Column("name", "Название", TEXT, ("имя", "наименование")), + Column("value", "Стоимость", DECIMAL, ("стоимость актива",), MONEY_FORMAT), + Column("growth_rate", "Рост %", DECIMAL, ("рост", "доходность", "годовой рост"), PERCENT_FORMAT), + Column("currency", "Валюта", CURRENCY, ("валюта актива",)), + ), + ), + SheetSpec( + "Liabilities", + ("id", "name", "balance", "interest", "payment", "currency"), + Liability, + "liabilities", + columns=( + Column("id", "ID", ID, ("ид", "идентификатор")), + Column("name", "Название", TEXT, ("имя", "наименование")), + Column("balance", "Остаток", DECIMAL, ("остаток долга",), MONEY_FORMAT), + Column("interest", "Ставка %", DECIMAL, ("процент", "ставка"), PERCENT_FORMAT), + Column("payment", "Платёж", DECIMAL, ("платеж", "ежемесячный платёж"), MONEY_FORMAT), + Column("currency", "Валюта", CURRENCY, ("валюта долга",)), + ), + ), + SheetSpec( + "ExchangeRates", + ("from_currency", "to_currency", "rate"), + ExchangeRate, + "exchange_rates", + columns=( + Column("from_currency", "Из валюты", CURRENCY, ("из", "валюта из")), + Column("to_currency", "В валюту", CURRENCY, ("в", "валюта в")), + Column("rate", "Курс", DECIMAL, ("значение курса",), RATE_FORMAT), + ), + ), + SheetSpec( + "Scenarios", + ("id", "name", "income_multiplier", "expense_multiplier", "growth_multiplier", "description"), + ForecastScenario, + "scenarios", + columns=( + Column("id", "ID", ID, ("ид", "идентификатор")), + Column("name", "Название", TEXT, ("имя", "название сценария")), + Column("income_multiplier", "Множитель дохода", DECIMAL, ("доход", "доход ×")), + Column("expense_multiplier", "Множитель расхода", DECIMAL, ("расход", "расход ×")), + Column("growth_multiplier", "Множитель роста", DECIMAL, ("рост", "рост ×")), + Column("description", "Описание", TEXT, ("комментарий",)), + ), + ), + InfoSheetSpec(), +) + + +# --------------------------------------------------------------------------- +# Разбор заголовков и значений +# --------------------------------------------------------------------------- + +_NON_ALNUM = re.compile(r"[\s_\-]+") + + +def _normalize_header(value: object) -> str: + """Ключ заголовка: без регистра, пробелов, ``_`` и ``-``; «ё» == «е».""" + if value is None: + return "" + text = str(value).strip().casefold().replace("ё", "е") + return _NON_ALNUM.sub("", text) + + +def build_header_index(spec: SheetSpec) -> dict[str, Column]: + """Сопоставление «нормализованный заголовок → столбец» для листа.""" + index: dict[str, Column] = {} + for column in spec.resolved_columns(): + for alias in column.accepted_headers(): + key = _normalize_header(alias) + if key and key not in index: + index[key] = column + return index + + +def is_empty(value: object) -> bool: + """Пустая ячейка: None или строка из одних пробелов.""" + if value is None: + return True + if isinstance(value, str): + return not value.strip() + return False diff --git a/infrastructure/repositories/excel_template.py b/infrastructure/repositories/excel_template.py new file mode 100644 index 0000000..53b4cee --- /dev/null +++ b/infrastructure/repositories/excel_template.py @@ -0,0 +1,321 @@ +"""Генератор Excel-шаблона для ручной сборки модели (D36). + +`write_workbook()` собирает книгу, в которой можно заполнять модель руками: +листы с русскими заголовками, форматы чисел и дат, выпадающие списки +(валюта, периодичность, счёт) и лист «Инструкция» с правилами заполнения. + +Один и тот же генератор обслуживает и каркас (`cf template-xlsx`), и выгрузку +(`cf export-xlsx`): выгруженный файл — это тот же шаблон, уже заполненный +данными, поэтому цикл «выгрузить → поправить в Excel → импортировать» +работает без ручной переделки. +""" + +from __future__ import annotations + +from datetime import date +from pathlib import Path + +from openpyxl import Workbook +from openpyxl.styles import Font +from openpyxl.utils import get_column_letter +from openpyxl.worksheet.datavalidation import DataValidation + +from domain import FinancialModel +from domain.currency import CURRENCY_DECIMALS +from infrastructure.repositories.excel_schema import ( + ACCOUNT, + ACCOUNT_OPTIONAL, + CURRENCY, + DATE, + DECIMAL, + FREQUENCY, + ID, + SHEETS, + Column, + InfoSheetSpec, + SheetSpec, +) + +INSTRUCTION_SHEET = "Инструкция" + +_TEMPLATE_ROWS = 500 +_VALIDATION_ROWS = 1000 +_ACCOUNT_RANGE = "=Accounts!$B$2:$B$500" + +_FREQUENCIES_EN = ("daily", "weekly", "monthly", "yearly") +_FREQUENCIES_RU = ("ежедневно", "еженедельно", "ежемесячно", "ежегодно") + +# Подсказка по типу значения: (обязательно, формат / допустимые значения). +_KIND_HELP: dict[str, tuple[str, str]] = { + ID: ("нет", "UUID или пусто — идентификатор создаётся автоматически"), + "text": ("—", "текст"), + CURRENCY: ("—", "код валюты: " + ", ".join(CURRENCY_DECIMALS)), + DECIMAL: ("—", "число: 1 234,56 или 1234.56; (100) = −100"), + DATE: ("—", "2026-01-31, 31.01.2026, 31/01/2026 или дата в ячейке Excel"), + FREQUENCY: ("—", "daily / weekly / monthly / yearly (или по-русски)"), + ACCOUNT: ("да", "имя счёта из листа Accounts"), + ACCOUNT_OPTIONAL: ("нет", "имя счёта из Accounts; пусто = все счета"), +} + +# Обязательные поля листов (для колонки «Обязательно» в инструкции). +_REQUIRED: dict[tuple[str, str], bool] = { + ("Accounts", "name"): True, + ("Accounts", "balance"): True, + ("Transactions", "date"): True, + ("Transactions", "account"): True, + ("Transactions", "amount"): True, + ("Recurring", "frequency"): True, + ("Recurring", "amount"): True, + ("Assets", "name"): True, + ("Assets", "value"): True, + ("Liabilities", "name"): True, + ("Liabilities", "balance"): True, + ("ExchangeRates", "from_currency"): True, + ("ExchangeRates", "to_currency"): True, + ("ExchangeRates", "rate"): True, +} + + +class TemplateError(Exception): + """Не удалось создать шаблон (файл уже есть, каталог недоступен).""" + + +def _list_validation(values: tuple[str, ...], *, prompt: str) -> DataValidation: + return DataValidation( + type="list", + formula1='"' + ",".join(values) + '"', + allow_blank=True, + showDropDown=False, + promptTitle="Допустимые значения", + prompt=prompt, + ) + + +def _account_validation() -> DataValidation: + return DataValidation( + type="list", + formula1=_ACCOUNT_RANGE, + allow_blank=True, + showDropDown=False, + promptTitle="Счёт", + prompt="Имя счёта из листа Accounts", + ) + + +def _cell_value(column: Column, item) -> object: + """Значение поля модели для записи в ячейку.""" + raw = getattr(item, column.field, None) + if column.kind == ID: + return str(raw) if raw else "" + if column.kind == CURRENCY: + return str(raw).strip().upper() if raw else None + if column.kind == DATE: + if not raw: + return None + try: + return date.fromisoformat(str(raw)) + except ValueError: + return str(raw) + if column.kind == DECIMAL: + return float(raw) if raw is not None else None + if column.kind in {ACCOUNT, ACCOUNT_OPTIONAL}: + text = str(raw).strip() if raw else "" + return text or None + return str(raw) if raw is not None else None + + +def _write_sheet(wb: Workbook, spec: SheetSpec, model: FinancialModel | None) -> None: + columns = spec.resolved_columns() + ws = wb.create_sheet(title=spec.name) + ws.append(list(spec.headers)) + for cell in ws[1]: + cell.font = Font(bold=True) + + if model is not None: + for item in getattr(model, spec.collection, []): + ws.append([_cell_value(column, item) for column in columns]) + + for column_index, column in enumerate(columns, start=1): + letter = get_column_letter(column_index) + ws.column_dimensions[letter].width = _column_width(column) + if column.number_format: + for row_number in range(2, _TEMPLATE_ROWS + 1): + ws.cell(row=row_number, column=column_index).number_format = column.number_format + + ws.freeze_panes = "A2" + ws.auto_filter.ref = f"A1:{get_column_letter(len(columns))}{_TEMPLATE_ROWS}" + + +def _column_width(column: Column) -> int: + widths = { + "id": 38, + "name": 24, + "currency": 10, + "balance": 14, + "date": 12, + "account": 22, + "category": 18, + "amount": 14, + "description": 34, + "start_date": 12, + "end_date": 12, + "frequency": 16, + "value": 14, + "growth_rate": 10, + "interest": 10, + "payment": 14, + "from_currency": 12, + "to_currency": 12, + "rate": 12, + "income_multiplier": 18, + "expense_multiplier": 18, + "growth_multiplier": 18, + } + return widths.get(column.field, 18) + + +def _write_info_sheet(wb: Workbook, model: FinancialModel | None, spec: InfoSheetSpec) -> None: + ws = wb.create_sheet(title=spec.name) + ws.append(list(spec.headers)) + for cell in ws[1]: + cell.font = Font(bold=True) + if model is not None: + for attribute, _key, label in spec.properties: + value = getattr(model, attribute, "") or "" + ws.append([label, value]) + else: + for _attribute, _key, label in spec.properties: + ws.append([label, None]) + ws.column_dimensions["A"].width = 26 + ws.column_dimensions["B"].width = 22 + ws.freeze_panes = "A2" + + +def _add_validations(wb: Workbook, table) -> None: + """Выпадающие списки: валюта, периодичность, счёт.""" + for spec in table: + if not isinstance(spec, SheetSpec): + continue + columns = spec.resolved_columns() + for column in columns: + letter = get_column_letter(columns.index(column) + 1) + if column.kind == CURRENCY: + validation = _list_validation( + tuple(CURRENCY_DECIMALS), + prompt="Код валюты, например RUB. Пусто — валюта счёта или базовая.", + ) + elif column.kind == FREQUENCY: + validation = _list_validation( + _FREQUENCIES_EN + _FREQUENCIES_RU, + prompt="daily / weekly / monthly / yearly (или по-русски)", + ) + elif column.kind in {ACCOUNT, ACCOUNT_OPTIONAL}: + validation = _account_validation() + else: + continue + spec_sheet = wb[spec.name] + spec_sheet.add_data_validation(validation) + validation.add(f"{letter}2:{letter}{_VALIDATION_ROWS}") + + +def _instruction_rows(table) -> list[tuple[str, str, str, str]]: + rows: list[tuple[str, str, str, str]] = [] + + def line(text: str) -> None: + rows.append((text, "", "", "")) + + line("Порядок работы") + line("1. Заполните листы Accounts, Transactions, Recurring, Assets, Liabilities, ExchangeRates.") + line("2. Сохраните файл в Excel — формулы должны быть пересчитаны и сохранены.") + line("3. Проверьте файл без записи в модель: cf import-xlsx путь/к/файлу.xlsx --dry-run") + line("4. Импортируйте модель: cf import-xlsx путь/к/файлу.xlsx") + line("") + + line("Правила заполнения") + line("• id можно оставить пустым — идентификатор создаётся автоматически.") + line("• счёт указывается по имени из листа Accounts (регистр и лишние пробелы не важны).") + line("• пустой счёт в Recurring = платёж относится ко всем счетам.") + line("• сумма со знаком: положительная = доход, отрицательная = расход.") + line("• сумма — сумма ОДНОГО списания: для yearly это разовая плата за год.") + line("• даты: 2026-01-31, 31.01.2026, 31/01/2026 или дата в ячейке Excel.") + line("• числа: 1 234,56 или 1234.56; символы валют и пробелы игнорируются; (100) = −100.") + line("• валюта: " + ", ".join(CURRENCY_DECIMALS) + ". Пусто — валюта счёта (или базовая).") + line("• периодичность: " + ", ".join(_FREQUENCIES_EN) + " (можно по-русски).") + line("• транзакция с датой в прошлом уже учтена в балансе счёта — в прогноз не попадёт.") + line("") + + rows.append(("Лист", "Столбец", "Обязательно", "Формат / допустимые значения")) + for spec in table: + if not isinstance(spec, SheetSpec): + continue + for column in spec.resolved_columns(): + required = "да" if _REQUIRED.get((spec.name, column.field)) else _KIND_HELP[column.kind][0] + rows.append((spec.name, column.header, required, _KIND_HELP[column.kind][1])) + return rows + + +def _write_instruction_sheet(wb: Workbook, table) -> None: + ws = wb.create_sheet(title=INSTRUCTION_SHEET) + ws.column_dimensions["A"].width = 72 + ws.column_dimensions["B"].width = 24 + ws.column_dimensions["C"].width = 14 + ws.column_dimensions["D"].width = 62 + + title = ws.cell(row=1, column=1, value="Инструкция: заполнение Excel-шаблона") + title.font = Font(bold=True, size=14) + + for offset, values in enumerate(_instruction_rows(table), start=2): + for column, value in enumerate(values, start=1): + ws.cell(row=offset, column=column, value=value or None) + if values[0] and not values[1] and not values[2] and not values[3]: + ws.cell(row=offset, column=1).font = Font(bold=True) + + ws.freeze_panes = "A2" + + +def write_workbook( + model: FinancialModel | None, + path: str | Path, + *, + force: bool = False, + sheets=None, +) -> Path: + """Создать книгу Excel: шаблон с данными (или пустой каркас). + + `model=None` — пустой каркас для ручного заполнения. + `sheets` — таблица листов; по умолчанию берётся из `excel_schema`. + """ + table = tuple(sheets) if sheets is not None else SHEETS + target = Path(path) + if target.exists() and not force: + raise TemplateError(f"Файл уже существует: {target} — используйте force, чтобы перезаписать") + try: + target.parent.mkdir(parents=True, exist_ok=True) + except OSError as exc: + raise TemplateError(f"Не удалось создать каталог {target.parent}: {exc}") from exc + + wb = Workbook() + wb.remove(wb.active) + + for spec in table: + if isinstance(spec, SheetSpec): + _write_sheet(wb, spec, model) + else: + _write_info_sheet(wb, model, spec) + + _add_validations(wb, table) + _write_instruction_sheet(wb, table) + + try: + wb.save(target) + except OSError as exc: + raise TemplateError(f"Не удалось сохранить файл {target}: {exc}") from exc + return target + + +def write_template(path: str | Path, *, force: bool = False) -> Path: + """Создать пустой каркас .xlsx для ручного заполнения.""" + return write_workbook(None, path, force=force) + + +__all__ = ["TemplateError", "write_template", "write_workbook"] diff --git a/tests/test_cli_contract.py b/tests/test_cli_contract.py index 31c6689..ea39c4f 100644 --- a/tests/test_cli_contract.py +++ b/tests/test_cli_contract.py @@ -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": [], } diff --git a/tests/test_excel_authoring.py b/tests/test_excel_authoring.py new file mode 100644 index 0000000..ccb936c --- /dev/null +++ b/tests/test_excel_authoring.py @@ -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" diff --git a/tests/test_excel_sync.py b/tests/test_excel_sync.py index 315d597..1633069 100644 --- a/tests/test_excel_sync.py +++ b/tests/test_excel_sync.py @@ -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() diff --git a/tests/test_forecast.py b/tests/test_forecast.py index a4f2fe5..f596ad0 100644 --- a/tests/test_forecast.py +++ b/tests/test_forecast.py @@ -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):