From cdda703b37c79ec1724ed1746457c7a746d6bf53 Mon Sep 17 00:00:00 2001 From: oqyude Date: Wed, 11 Nov 2026 15:40:28 +0300 Subject: [PATCH] T9: Excel as the model authoring surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .agent/archive/index.json | 6 +- .agent/archive/requests/req-T8.json | 6 +- .agent/archive/requests/req-T9.json | 61 ++ .agent/archive/tasks/T8.json | 2 +- .agent/archive/tasks/T9.json | 21 + .agent/checkpoints.json | 78 +- .agent/context/project-state.md | 46 +- .agent/handoff-summary.md | 33 +- .agent/roadmap/sources.md | 9 +- .agent/session-summary.md | 15 +- .agent/tasks/manifest.json | 7 +- .agent/tasks/manifest.md | 49 +- README.md | 48 +- application/forecast.py | 58 +- application/scenarios.py | 2 +- data/model_template.xlsx | Bin 0 -> 37515 bytes domain/currency.py | 2 +- domain/recurring.py | 3 + infrastructure/ai/assistant.py | 4 +- infrastructure/cli/app.py | 4 +- infrastructure/cli/commands/__init__.py | 2 + infrastructure/cli/commands/config_cmd.py | 20 +- infrastructure/cli/commands/import_xlsx.py | 68 +- infrastructure/cli/commands/info.py | 6 +- infrastructure/cli/commands/init.py | 2 +- infrastructure/cli/commands/template_xlsx.py | 32 + infrastructure/cli/i18n.py | 33 +- infrastructure/cli/paths.py | 1 + infrastructure/cli/services.py | 16 +- infrastructure/repositories/__init__.py | 17 +- .../repositories/excel_repository.py | 801 ++++++++++++++++-- infrastructure/repositories/excel_template.py | 222 +++++ tests/conftest.py | 16 + tests/test_cli.py | 186 +++- tests/test_excel_sync.py | 293 +++++++ tests/test_excel_template.py | 129 +++ tests/test_forecast.py | 78 ++ tests/test_model.py | 1 - tests/test_repositories.py | 2 +- 39 files changed, 2181 insertions(+), 198 deletions(-) create mode 100644 .agent/archive/requests/req-T9.json create mode 100644 .agent/archive/tasks/T9.json create mode 100644 data/model_template.xlsx create mode 100644 infrastructure/cli/commands/template_xlsx.py create mode 100644 infrastructure/repositories/excel_template.py create mode 100644 tests/test_excel_template.py diff --git a/.agent/archive/index.json b/.agent/archive/index.json index cf9b8a8..02b56d0 100644 --- a/.agent/archive/index.json +++ b/.agent/archive/index.json @@ -11,7 +11,8 @@ { "id": "T5", "title": "Dependency Injection в сервисах", "archived_at": "2026-10-08T17:05:00Z", "request": "req-T5", "commit": "541a768" }, { "id": "T6", "title": "Декомпозиция CLI", "archived_at": "2026-10-08T17:05:00Z", "request": "req-T6" }, { "id": "T7", "title": "Финальная валидация", "archived_at": "2026-10-08T17:05:00Z", "request": "req-T7", "commit": "3ef1061" }, - { "id": "T8", "title": "ISO 4217-aware форматирование денег (per-currency decimals)", "session": "metaagent-006", "archived_at": "2026-11-11T11:50:09Z", "request": "req-T8", "commit": "d58547e" } + { "id": "T8", "title": "ISO 4217-aware форматирование денег (per-currency decimals)", "session": "metaagent-006", "archived_at": "2026-11-11T11:50:09Z", "request": "req-T8", "commit": "d58547e" }, + { "id": "T9", "title": "Excel как поверхность сборки модели: шаблон-каркас + надёжный импорт", "session": "metaagent-008", "archived_at": "2026-11-11T15:45:00Z", "request": "req-T9", "commit": "3ece296" } ], "requests": [ { "id": "req-T1", "task_id": "T1", "status": "approved", "archived_at": "2026-10-08T17:05:00Z" }, @@ -21,7 +22,8 @@ { "id": "req-T5", "task_id": "T5", "status": "approved", "archived_at": "2026-10-08T17:05:00Z" }, { "id": "req-T6", "task_id": "T6", "status": "approved", "archived_at": "2026-10-08T17:05:00Z" }, { "id": "req-T7", "task_id": "T7", "status": "approved", "archived_at": "2026-10-08T17:05:00Z" }, - { "id": "req-T8", "task_id": "T8", "status": "approved", "archived_at": "2026-11-11T11:50:09Z" } + { "id": "req-T8", "task_id": "T8", "status": "approved", "archived_at": "2026-11-11T11:50:09Z" }, + { "id": "req-T9", "task_id": "T9", "status": "approved", "archived_at": "2026-11-11T15:45:00Z" } ], "checkpoints": [] } diff --git a/.agent/archive/requests/req-T8.json b/.agent/archive/requests/req-T8.json index 8a77da3..e049658 100644 --- a/.agent/archive/requests/req-T8.json +++ b/.agent/archive/requests/req-T8.json @@ -15,7 +15,7 @@ }, "thousands_separator": { "value": ",", - "rationale": "Сохраняем текущее поведение (:,.2f). Locale-чувствительное форматирование (ru: пробел, en: запятая) — отдельная задача T9+, не входит в T8." + "rationale": "Сохраняем текущее поведение (:,.2f). Locale-чувствительное форматирование (ru: пробел, en: запятая) — отдельная задача T11+, не входит в T8." }, "unknown_currency_layout": { "value": "prefix", @@ -24,7 +24,7 @@ }, "internal_precision": { "value": "сохранить Decimal-арифметику без изменений", - "rationale": "T8 только про display. _q() в forecast.py и quantize('0.01') в convert() оставить как есть. Их влияние на точность прогноза и кросс-валютной конвертации — отдельный T9 (если будет нужен). Это решение изолирует blast radius." + "rationale": "T8 только про display. _q() в forecast.py и quantize('0.01') в convert() оставить как есть. Их влияние на точность прогноза и кросс-валютной конвертации — отдельный T10 (если будет нужен). Это решение изолирует blast radius." } }, @@ -87,7 +87,7 @@ "follow_ups": [ { - "id": "T9-candidate", + "id": "T10-candidate", "title": "Не квантовать конвертацию в convert()", "detail": "CurrencyConverter.convert() делает quantize('0.01'), из-за чего 0.1 USD → JPY даёт ≈8.07 вместо ≈7.86. Квантовать только при отображении; convert() возвращает полную точность Decimal. Требует ревизии тестов test_currency.py и проверки сериализации прогноза (_q в forecast.py)." } diff --git a/.agent/archive/requests/req-T9.json b/.agent/archive/requests/req-T9.json new file mode 100644 index 0000000..627617e --- /dev/null +++ b/.agent/archive/requests/req-T9.json @@ -0,0 +1,61 @@ +{ + "request_id": "req-T9", + "task_id": "T9", + "title": "Excel как поверхность сборки модели: шаблон-каркас + надёжный импорт", + "status": "approved", + "created_at": "2026-11-11T12:00:00Z", + "approved_at": "2026-11-11T15:45:00Z", + "goal": "Довести проект до состояния, когда модель можно собрать в Excel: сгенерировать каркас, заполнить руками (счёт по имени, даты ячейками, числа в русском формате) и импортировать так, чтобы прогноз считался корректно.", + + "decisions": { + "account_reference": { + "value": "в модели хранится UUID счёта, в Excel отображается имя", + "rationale": "Имя удобно человеку, UUID устойчив к переименованию и совместим с JSON-моделями. Импорт резолвит имя (регистр/пробелы не важны) или UUID в str(id); экспорт пишет имя по id." + }, + "recurring_account": { + "value": "новое необязательное поле RecurringCashflow.account; пусто = платёж по всем счетам", + "rationale": "До этого регулярный платёж учитывался на каждом счёте (двойной счёт при нескольких счетах). Пустое значение сохраняет прежнее поведение для старых JSON-моделей." + }, + "import_strictness": { + "value": "ошибки блокируют сохранение, предупреждения — нет", + "rationale": "Молча записывать частично битую модель опаснее, чем отказать: пользователь видит лист!строку и правит файл. --dry-run позволяет проверить файл, не трогая model.json." + }, + "exchange_rates": { + "value": "отсутствие листа/строк → курсы по умолчанию + warning", + "rationale": "Раньше пустой лист обнулял курсы и ломал конвертацию в прогнозе." + }, + "unknown_headers": { + "value": "игнорировать + warning", + "rationale": "Пользователь может добавить свои колонки-заметки, не ломая импорт." + } + }, + + "scope": { + "in_scope": [ + "ExcelRepository: алиасы заголовков ru/en, нормализация дат и чисел, резолв счёта, сбор ошибок по строкам, формульные warning'и", + "ExcelTemplate: генератор каркаса с форматами, выпадающими списками и листом «Инструкция»", + "CLI: cf template-xlsx [--force], cf import-xlsx --dry-run, rich-таблица ошибок", + "RecurringCashflow.account + матчинг по имени/UUID в ForecastService", + "Исправления прогноза: идемпотентность вызовов и корректный итоговый баланс по всем счетам", + "README: раздел «Сборка модели в Excel»", + "Репозиторий: готовый data/model_template.xlsx" + ], + "out_of_scope": [ + "Экспорт результатов прогноза в Excel (отдельная задача)", + "Слияние/частичное обновление модели при импорте (сейчас импорт заменяет модель)", + "Привязка обязательств к счёту (liability по-прежнему распределяется на все счета)", + "Locale-aware форматирование чисел (T11)" + ] + }, + + "acceptance_criteria": [ + "cf template-xlsx создаёт файл, который импортируется без ошибок и даёт пустую модель", + "Заполненный руками шаблон (счёт по имени, даты ячейками, без id) импортируется, транзакции попадают в прогноз", + "cf import-xlsx --dry-run не перезаписывает model.json", + "Ошибки показывают лист и номер строки; файл с ошибками не сохраняется", + "Отсутствие листа ExchangeRates не обнуляет курсы", + "Экспорт → импорт сохраняет id счетов и привязки транзакций", + "Повторный вызов forecast_cashflow даёт тот же результат; Итог: Баланс = сумма балансов всех счетов за последний месяц", + "pytest зелёный (было 75), ruff чистый" + ] +} diff --git a/.agent/archive/tasks/T8.json b/.agent/archive/tasks/T8.json index a3dcf19..1418ca0 100644 --- a/.agent/archive/tasks/T8.json +++ b/.agent/archive/tasks/T8.json @@ -16,7 +16,7 @@ }, "review_notes": [ "Противоречие в req-T8: decision 'unknown_currency_layout' был записан как suffix ('1,234.56 CHF'), но acceptance criteria и реализация — prefix ('BHD 1.234'). Решение зафиксировано как prefix (см. req-T8, decision исправлен 2026-11-11).", - "convert() по-прежнему квантует до 0.01, поэтому 0.1 USD → JPY даёт ≈8.07. Это осознанно out_of_scope задачи T8; заведено как кандидат T9." + "convert() по-прежнему квантует до 0.01, поэтому 0.1 USD → JPY даёт ≈8.07. Это осознанно out_of_scope задачи T8; заведено как кандидат T10." ], "archived_at": "2026-11-11T11:50:09Z" } diff --git a/.agent/archive/tasks/T9.json b/.agent/archive/tasks/T9.json new file mode 100644 index 0000000..c9de3d0 --- /dev/null +++ b/.agent/archive/tasks/T9.json @@ -0,0 +1,21 @@ +{ + "id": "T9", + "title": "Excel как поверхность сборки модели: шаблон-каркас + надёжный импорт", + "status": "archived", + "origin": "user:direct", + "request": "req-T9", + "commit": "3ece296", + "summary": "Excel стал полноценной поверхностью сборки модели. ExcelRepository переписан: канонические колонки с алиасами ru/en, нормализация дат (ячейки, ISO, DD.MM.YYYY) и чисел (1 234,56, символы валют, скобки), резолв счёта по имени или UUID, сбор ошибок с лист!строка, warning'и по формулам без кэша, дублям имён и курсам по умолчанию. Новый write_template() создаёт каркас с форматами, выпадающими списками (валюта, периодичность en/ru, счёт) и листом «Инструкция». CLI: cf template-xlsx [--force], cf import-xlsx --dry-run с rich-таблицей ошибок. RecurringCashflow.account (пусто = все счета) + матчинг по имени/UUID. Исправлены прогнозные баги: повторные вызовы больше не накапливают мутации, итоговый баланс — сумма по всем счетам последнего месяца. README: раздел «Сборка модели в Excel»; в репозиторий положен data/model_template.xlsx.", + "verification": { + "tests": "118 passed (было 75; +43: 23 Excel, 10 CLI, 6 прогноз/консистентность, 4 прочих)", + "ruff": "ruff check . — чисто (попутно устранены 9 прежних I001/E501)", + "e2e": "template-xlsx → заполнение openpyxl → import-xlsx --dry-run (model.json не создан) → import-xlsx → forecast (Итог: Баланс = сумма по счетам) → info → export-xlsx; повторный импорт сохраняет id и привязки", + "env": "офлайн-окружение: Python 3.12.13 + пакеты из uv cache (pydantic 2.13.5, typer 0.27.2, openpyxl 3.1.5, pytest 9.1.1), ruff 0.17.1" + }, + "known_limitations": [ + "Импорт заменяет модель целиком; слияния нет", + "Обязательства не привязаны к счёту — процент распределяется на все счета", + "Экспорт прогноза в Excel не делается" + ], + "archived_at": "2026-11-11T15:45:00Z" +} diff --git a/.agent/checkpoints.json b/.agent/checkpoints.json index 7ab865c..e578709 100644 --- a/.agent/checkpoints.json +++ b/.agent/checkpoints.json @@ -1,34 +1,82 @@ { "metaagent_version": "3.0.0", - "session_id": "metaagent-007", + "session_id": "metaagent-008", "target_repo": "/home/oqyude/External/Git/nifodea", - "goal": "Обсуждение архитектуры и серьёзный refactor + закрытие T8 (ISO 4217 money display)", + "goal": "T9: Excel как поверхность сборки модели — шаблон-каркас + надёжный импорт (выполнено)", "project_type": "existing", "phases": { "init": "completed", "analyse": "completed", "roadmap": "completed", - "design": "skipped", + "design": "completed", "decomposition": "completed", "execution": "completed", "metastate": "completed", "handoff": "completed" }, "tasks": [ - { "id": "T1", "title": "Реструктуризация в domain/application/infrastructure + version=1", "status": "archived", "origin": "user:direct" }, - { "id": "T2", "title": "Pydantic v2 — миграция моделей", "status": "archived", "origin": "user:direct" }, - { "id": "T3", "title": "Decimal для денег", "status": "archived", "origin": "user:direct" }, - { "id": "T4", "title": "Repository pattern — ModelRepository", "status": "archived", "origin": "user:direct" }, - { "id": "T5", "title": "Dependency Injection в сервисах", "status": "archived", "origin": "user:direct" }, - { "id": "T6", "title": "Декомпозиция CLI", "status": "archived", "origin": "user:direct" }, - { "id": "T7", "title": "Финальная валидация", "status": "archived", "origin": "user:direct" }, - { "id": "T8", "title": "ISO 4217-aware форматирование денег (per-currency decimals)", "status": "archived", "origin": "user:direct", "commit": "d58547e" } + { + "id": "T1", + "title": "Реструктуризация в domain/application/infrastructure + version=1", + "status": "archived", + "origin": "user:direct" + }, + { + "id": "T2", + "title": "Pydantic v2 — миграция моделей", + "status": "archived", + "origin": "user:direct" + }, + { + "id": "T3", + "title": "Decimal для денег", + "status": "archived", + "origin": "user:direct" + }, + { + "id": "T4", + "title": "Repository pattern — ModelRepository", + "status": "archived", + "origin": "user:direct" + }, + { + "id": "T5", + "title": "Dependency Injection в сервисах", + "status": "archived", + "origin": "user:direct" + }, + { + "id": "T6", + "title": "Декомпозиция CLI", + "status": "archived", + "origin": "user:direct" + }, + { + "id": "T7", + "title": "Финальная валидация", + "status": "archived", + "origin": "user:direct" + }, + { + "id": "T8", + "title": "ISO 4217-aware форматирование денег (per-currency decimals)", + "status": "archived", + "origin": "user:direct", + "commit": "d58547e" + }, + { + "id": "T9", + "title": "Excel как поверхность сборки модели: шаблон-каркас + надёжный импорт", + "status": "archived", + "origin": "user:direct" + } ], "notes": [ "2026-10-09: T8 выполнена и закоммичена (d58547e) в сессии metaagent-006, но артефакты METASTATE не были обновлены.", - "2026-11-11 (metaagent-007): состояние выверено и синхронизировано — T8 архивирована, req-T8 approved, manifest/checkpoints/project-state/handoff/session-summary обновлены; тесты 75, LICENSE = MIT.", - "Динамическая проверка (pytest/ruff) в сессии закрытия недоступна: на машине нет установленных зависимостей и нет доступа к PyPI. Цифра 75/75 взята из коммита d58547e и подтверждена статическим подсчётом тестовых функций.", - "Открытый кандидат T9: CurrencyConverter.convert() квантует до 0.01, из-за чего 0.1 USD → JPY даёт ≈8.07 вместо ≈7.86." + "2026-11-11 (metaagent-007): состояние выверено и синхронизировано — T8 архивирована, req-T8 approved; тесты 75, LICENSE = MIT.", + "2026-11-11 (metaagent-008): T9 — Excel как основная поверхность сборки модели. Найден рабочий офлайн-прогон тестов (uv cache + Python 3.12.13), 75/75 подтверждены динамически.", + "Кандидаты после T9: T10 — убрать quantize('0.01') из convert(); T11 — locale-aware разделитель тысяч.", + "2026-11-11: T9 закрыта — каркас data/model_template.xlsx, CLI template-xlsx/import-xlsx --dry-run, 118 тестов, ruff чистый; e2e-сценарий Excel→модель→прогноз проверен." ], - "last_updated": "2026-11-11T11:50:09Z" + "last_updated": "2026-11-11T15:45:00Z" } diff --git a/.agent/context/project-state.md b/.agent/context/project-state.md index 0731e97..9a43f5d 100644 --- a/.agent/context/project-state.md +++ b/.agent/context/project-state.md @@ -1,6 +1,6 @@ # Project State -**Снимок на момент:** 2026-11-11T11:50 (закрытие T8, сессия `metaagent-007`) +**Снимок на момент:** 2026-11-11T15:45 (T9 закрыта, сессия `metaagent-008`) **Project type:** `existing` **MetaAgent version:** 3.0.0 @@ -29,7 +29,19 @@ - 14 литералов `:,.2f` в `services.py` / `info.py` / `config_cmd.py` заменены на `format_money()`; 0 литералов осталось. - i18n-шаблоны `transaction_add.ok` / `recurring_add.ok` переведены на `{amount_str}`. - +8 тестов в `tests/test_currency.py`; всего 75. -- Осознанно вне scope: `convert()` всё ещё квантует до 0.01 → `0.1 USD → JPY` ≈8.07 вместо ≈7.86 (кандидат T9). +- Осознанно вне scope: `convert()` всё ещё квантует до 0.01 → `0.1 USD → JPY` ≈8.07 вместо ≈7.86 (кандидат T10). + +## Что произошло 2026-11-11 (сессия `metaagent-008`) + +**T9: Excel как поверхность сборки модели.** Модель теперь можно собрать в Excel с нуля: + +- `cf template-xlsx` (или готовый `data/model_template.xlsx`) — каркас: `ModelInfo`, `Accounts`, `Transactions`, `Recurring`, `Assets`, `Liabilities`, `ExchangeRates` + лист «Инструкция», форматы чисел/дат, выпадающие списки (валюта, периодичность en/ru, счёт). +- `cf import-xlsx [--dry-run]` — толерантный импорт: алиасы заголовков ru/en, даты ячейками и текстом, числа `1 234,56`, счёт по имени или UUID, ошибки с адресом `лист!строка`, предупреждения (формулы без кэша, дубли имён, курсы по умолчанию). Файл с ошибками не сохраняется. +- `RecurringCashflow.account` — привязка регулярного платежа к счёту (пусто = все счета); `cf config recurring-add --account`, колонка «Счёт» в `info`/`recurring-list`. +- Прогноз: вызовы идемпотентны (каждый считается на свежей копии), `Итог: Баланс` — сумма балансов всех счетов за последний месяц (раньше — баланс последнего счёта). +- `ruff check .` — чисто (устранены 9 прежних замечаний). + +**Результат:** 118 тестов зелёные, e2e-сценарий Excel → модель → прогноз → экспорт проверен вручную. ## Архитектура (после рефактора) @@ -77,29 +89,31 @@ | domain | `account.py` (18 LOC), `transaction.py` (20), `asset.py` (11), `liability.py` (19), `recurring.py` (27), `scenario.py` (20) | pydantic.BaseModel + Decimal + валидаторы | | domain | `currency.py` (134) | ExchangeRate + CurrencyConverter (Decimal, ROUND_HALF_UP), `CURRENCY_DECIMALS` + `format_money()` | | domain | `model.py` (71) | FinancialModel — корневой агрегатор с SCHEMA_VERSION=1 | -| application | `forecast.py` (115) | ForecastService — Decimal-арифметика, помесячный прогноз | +| application | `forecast.py` (143) | ForecastService — Decimal-арифметика, идемпотентный помесячный прогноз, привязка по счёту | | application | `scenarios.py` (91) | ScenarioService — baseline/optimistic/pessimistic + what-if | | application | `repositories/model_repository.py` (20) | Protocol с load()/save() | | infrastructure | `cli/app.py` (45) | Entry point, регистрирует все команды | -| infrastructure | `cli/commands/*.py` | 9 файлов (init/forecast/scenario/whatif/compare/import_xlsx/export_xlsx/analyze/info) + config_cmd.py | +| infrastructure | `cli/commands/*.py` | 10 файлов (init/forecast/scenario/whatif/compare/template_xlsx/import_xlsx/export_xlsx/analyze/info) + config_cmd.py | | infrastructure | `cli/paths.py` (5) | MODEL_PATH, DATA_DIR | | infrastructure | `cli/services.py` (60) | build_services() — composition root + helpers | | infrastructure | `cli/i18n.py` (350) | ru/en словари | | infrastructure | `ai/assistant.py` (79) | AssistantService (заглушка, DI ForecastService) | | infrastructure | `repositories/json_file_repository.py` (20) | .json storage | -| infrastructure | `repositories/excel_repository.py` (138) | .xlsx storage | +| infrastructure | `repositories/excel_repository.py` (775) | .xlsx: импорт с валидацией/алиасами/резолвом счетов + экспорт | +| infrastructure | `repositories/excel_template.py` (222) | генератор каркаса + лист «Инструкция» | ## Статус тестов | Параметр | Значение | |---|---| -| Всего тестов | 75 | -| Пройдено | 75 ✅ (заявлено в коммите `d58547e`) | +| Всего тестов | 118 | +| Пройдено | 118 ✅ (динамический прогон 2026-11-11) | | Упало | 0 | -| Время | ~2.5s | -| Тестовых модулей | 9 | +| Время | ~3.5s | +| Тестовых модулей | 10 | +| Линтер | `ruff check .` — чисто | -⚠️ Проверено статически 2026-11-11 (75 функций `test_*` в `tests/`); динамический прогон на машине закрытия недоступен — нет установленных зависимостей и нет доступа к PyPI. +Прогон выполняется в офлайн-окружении: Python 3.12.13 + пакеты из uv cache (pydantic 2.13.5, typer 0.27.2, openpyxl 3.1.5, pytest 9.1.1, ruff 0.17.1); `PYTHONPATH` собирается из `%LOCALAPPDATA%/uv/cache/archive-v0`. ## Что было сделано в сессиях @@ -115,6 +129,8 @@ - ✅ README обновлён - ✅ ISO 4217-aware деньги: `format_money()` + `CURRENCY_DECIMALS`, 75/75 (T8, `d58547e`) - ✅ Лицензия MIT (`LICENSE`, copyright 2026 Jor Oqyude) +- ✅ Excel-каркас `data/model_template.xlsx` + импорт с валидацией, 118/118 (T9) +- ✅ ruff check . — чисто ## Что отсутствует / TODO @@ -123,8 +139,11 @@ - ❌ **FUTURE/** — нет директории с долгосрочными планами - ❌ **mypy** — не настроен - ❌ **Логирование** — только `rich.print` -- ❌ **T9 (кандидат)** — `CurrencyConverter.convert()` квантует до 0.01 → `0.1 USD → JPY` ≈8.07 вместо ≈7.86; квантовать только при отображении -- ❌ **Locale-aware форматирование** — разделитель тысяч жёстко `,`; для ru нужен пробел (T10+) +- ❌ **T10 (кандидат)** — `CurrencyConverter.convert()` квантует до 0.01 → `0.1 USD → JPY` ≈8.07 вместо ≈7.86; квантовать только при отображении +- ❌ **T11 (кандидат)** — locale-aware форматирование: разделитель тысяч жёстко `,`; для ru нужен пробел +- ❌ **Импорт не сливает модели** — `cf import-xlsx` заменяет `model.json` целиком +- ❌ **Обязательства не привязаны к счёту** — процент распределяется на все счета +- ❌ **Прогноз не выгружается в Excel** — только модель ## Известные ADR-кандидаты (для следующей сессии) @@ -137,7 +156,8 @@ ## Следующая сессия — что делать 1. **Зафиксировать ADR-001, ADR-002, ADR-003** через `/adr` — закрепить архитектурные решения. -2. **T9 (кандидат)** — убрать `quantize("0.01")` из `CurrencyConverter.convert()`; квантовать только при отображении. +2. **T10 (кандидат)** — убрать `quantize("0.01")` из `CurrencyConverter.convert()`; квантовать только при отображении. +3. **Экспорт прогноза в Excel** — лист `Forecast` в `export-xlsx` (P2). 3. **CI/CD** (P1) — добавить `.github/workflows/ci.yml` (pytest + ruff). 4. **mypy** (P1) — добавить `[tool.mypy]` в `pyproject.toml` для strict-проверки. 5. **pre-commit** (P2) — hooks для ruff. diff --git a/.agent/handoff-summary.md b/.agent/handoff-summary.md index 9a32b19..53bab68 100644 --- a/.agent/handoff-summary.md +++ b/.agent/handoff-summary.md @@ -1,12 +1,23 @@ # Handoff Summary -**Session:** `metaagent-005` + `metaagent-006` (T8) · закрытие: `metaagent-007` (2026-11-11) +**Session:** `metaagent-005` + `metaagent-006` (T8) + `metaagent-008` (T9) · закрытие: `metaagent-007` (2026-11-11) **Goal:** Обсуждение архитектуры и серьёзный refactor **Date:** 2026-10-08 → 2026-11-11 **MetaAgent version:** 3.0.0 --- +## T9 2026-11-11 (сессия `metaagent-008`) + +**Excel как поверхность сборки модели.** Модель собирается в Excel с нуля: каркас `data/model_template.xlsx` (листы данных + «Инструкция», форматы, выпадающие списки) → заполнение → `cf import-xlsx [--dry-run]` → `cf forecast`. + +- Импорт толерантный: заголовки ru/en, даты ячейками/текстом, числа `1 234,56`, счёт по имени или UUID; ошибки с адресом `лист!строка` блокируют запись, предупреждения (формулы, дубли имён, курсы по умолчанию) — нет. +- `RecurringCashflow.account` — регулярный платёж можно привязать к счёту (пусто = все счета). +- Исправлены баги прогноза: повторные вызовы больше не накапливают мутации, `Итог: Баланс` = сумма по всем счетам последнего месяца. +- 118 тестов, `ruff check .` чисто; e2e-сценарий проверен вручную. + +--- + ## Closeout 2026-11-11 (сессия `metaagent-007`) T8 была выполнена и закоммичена (`d58547e`, 2026-10-09), но METASTATE/archive не закрыты. Состояние выверено и синхронизировано: @@ -15,7 +26,7 @@ T8 была выполнена и закоммичена (`d58547e`, 2026-10-09) - `tasks/manifest.json` / `checkpoints.json` → session `metaagent-007`, 8/8 archived, 0 pending - Этот файл, `session-summary.md`, `project-state.md`, `README.md` обновлены: **75 тестов** (не 67), LICENSE = **MIT** - Решённое противоречие: код валюты без символа — **префикс** (`BHD 1.234`), а не suffix, как было записано в `req-T8.decisions` -- Заведён кандидат **T9**: `convert()` квантует до 0.01 → `0.1 USD → JPY` ≈8.07 вместо ≈7.86 +- Заведён кандидат **T10**: `convert()` квантует до 0.01 → `0.1 USD → JPY` ≈8.07 вместо ≈7.86 - ⚠️ Динамический прогон pytest/ruff при закрытии недоступен (нет зависимостей и доступа к PyPI); 75/75 — из коммита + статический подсчёт 75 функций `test_*` --- @@ -24,12 +35,12 @@ T8 была выполнена и закоммичена (`d58547e`, 2026-10-09) | Метрика | Значение | |---|---| -| Выполнено задач | 8/8 ✅ | +| Выполнено задач | 9/9 ✅ | | Pending | 0 | -| Approved requests | req-T1 … req-T8 (все в `.agent/archive/requests/`) | +| Approved requests | req-T1 … req-T9 (все в `.agent/archive/requests/`) | | Коммитов | 7 (feb77ef, c765f36, 363d440, 541a768, 3ef1061, d58547e, плюс 1 для T4/T6 — см. `git log`) | | Тестов до | 63 | -| Тестов после | 75 (+5 для репозиториев, +8 для format_money в T8) | +| Тестов после | 118 (+5 репозитории, +8 format_money, +35 Excel/CLI/прогноз в T9) | ## Что сделано @@ -52,16 +63,16 @@ T8 была выполнена и закоммичена (`d58547e`, 2026-10-09) **Стек:** Python 3.11+, pydantic 2.13, openpyxl 3.1, typer 0.27, rich 15, pytest 9.1. -**Тесты:** 75/75 ✅ (заявлено в `d58547e`; динамически не перепроверялось при закрытии). +**Тесты:** 118/118 ✅ (динамический прогон 2026-11-11). -**Известные ограничения:** AI stub (отклонено пользователем), нет CI/CD, нет mypy, нет pre-commit, нет логирования, `convert()` квантует до 0.01 (T9). +**Известные ограничения:** AI stub (отклонено пользователем), нет CI/CD, нет mypy, нет pre-commit, нет логирования, `convert()` квантует до 0.01 (T10), импорт заменяет модель целиком, обязательства не привязаны к счёту. ## Key Artifacts - **Project state:** `.agent/context/project-state.md` — текущее состояние - **Tasks:** `.agent/tasks/manifest.json` — все задачи archived -- **Archive tasks:** `.agent/archive/tasks/T1.json` … `T8.json` — полные описания -- **Archive requests:** `.agent/archive/requests/req-T1.json` … `req-T8.json` — все approved +- **Archive tasks:** `.agent/archive/tasks/T1.json` … `T9.json` — полные описания +- **Archive requests:** `.agent/archive/requests/req-T1.json` … `req-T9.json` — все approved - **Roadmap:** `.agent/roadmap/sources.md` — следующие шаги - **Archive index:** `.agent/archive/index.json` @@ -77,7 +88,9 @@ T8 была выполнена и закоммичена (`d58547e`, 2026-10-09) - **CI/CD:** `.github/workflows/ci.yml` (pytest + ruff) - **mypy:** strict-проверка в `pyproject.toml` -- **T9 (кандидат):** убрать `quantize("0.01")` из `convert()` +- **T10 (кандидат):** убрать `quantize("0.01")` из `convert()` +- **Excel-выгрузка прогноза:** лист `Forecast` в `export-xlsx` +- **Слияние при импорте:** обновлять модель из Excel без потери нераспознанных данных ### P2 — Полировка diff --git a/.agent/roadmap/sources.md b/.agent/roadmap/sources.md index 1181d09..faa881c 100644 --- a/.agent/roadmap/sources.md +++ b/.agent/roadmap/sources.md @@ -6,14 +6,15 @@ --- -## Статус на 2026-11-11 (после закрытия T8) +## Статус на 2026-11-11 (после T9) -Отработано из P0: A1+A10, A2+A3, A4, A5, A7+A8+A9 (T1–T7) + P1 currency display (T8, `d58547e`). +Отработано из P0: A1+A10, A2+A3, A4, A5, A7+A8+A9 (T1–T7) + P1 currency display (T8, `d58547e`) + Excel как поверхность сборки модели (T9). Остаётся: -- **T9 (кандидат):** `CurrencyConverter.convert()` квантует до 0.01 → `0.1 USD → JPY` ≈8.07 вместо ≈7.86 -- **T10+ (кандидат):** locale-aware разделитель тысяч (сейчас всегда `,`) +- **T10 (кандидат):** `CurrencyConverter.convert()` квантует до 0.01 → `0.1 USD → JPY` ≈8.07 вместо ≈7.86 +- **T11 (кандидат):** locale-aware разделитель тысяч (сейчас всегда `,`) +- **Excel follow-ups:** выгрузка прогноза в Excel, слияние при импорте, привязка обязательств к счёту - **P1:** CI/CD (`.github/`), mypy strict - **P2:** pre-commit, логирование вместо `rich.print` - **P0 из ADR:** ADR-001 (Repository), ADR-002 (слои), ADR-003 (schema versioning) diff --git a/.agent/session-summary.md b/.agent/session-summary.md index 676855c..328591b 100644 --- a/.agent/session-summary.md +++ b/.agent/session-summary.md @@ -1,6 +1,6 @@ # Session Summary -**Session:** `metaagent-005` (T1–T7) → `metaagent-006` (T8) → `metaagent-007` (closeout 2026-11-11) +**Session:** `metaagent-005` (T1–T7) → `metaagent-006` (T8) → `metaagent-007` (closeout) → `metaagent-008` (T9) **MetaAgent version:** 3.0.0 **Date:** 2026-10-08 → 2026-11-11 **Goal:** Обсуждение архитектуры и серьёзный refactor @@ -12,14 +12,14 @@ - [x] ROADMAP - [ ] DESIGN (skipped — existing project) - [x] DECOMPOSITION -- [x] EXECUTION (7 tasks + T8) +- [x] EXECUTION (7 tasks + T8 + T9) - [x] METASTATE - [x] HANDOFF ## Results -- **Tasks completed:** 8/8 (T1–T8, все archived; T8 закрыта 2026-11-11) -- **Requests approved:** 8 (req-T1 … req-T8, в `.agent/archive/requests/`) +- **Tasks completed:** 9/9 (T1–T9, все archived) +- **Requests approved:** 9 (req-T1 … req-T9, в `.agent/archive/requests/`) - **Commits:** 7 production commits + 1 README - `feb77ef` T1: restructure to domain/application/infrastructure + version=1 - `c765f36` T2: Pydantic v2 @@ -29,8 +29,8 @@ - `` T6: CLI decompose - `3ef1061` T7: Final validation + README - `d58547e` T8: ISO 4217 per-currency decimals + `format_money()` -- **Tests:** 75/75 (было 63 → 67 после T1–T7 → 75 после T8; +8 тестов форматтера) -- **CLI:** все команды работают, Excel round-trip OK +- **Tests:** 118/118 (63 → 67 → 75 после T8 → 118 после T9; Excel-импорт, CLI, консистентность прогноза) +- **CLI:** все команды работают; Excel: `template-xlsx`, `import-xlsx --dry-run`, round-trip OK ## Архитектурный рефактор (5 направлений) @@ -42,6 +42,7 @@ | A7+A8+A9 | DI + Repository | T4, T5 | | A5 | Декомпозиция CLI | T6 | | ISO 4217 | Per-currency decimals + `format_money()` (P1) | T8 | +| Excel | Каркас + толерантный импорт, модель собирается в Excel | T9 | ## Files Changed @@ -56,4 +57,4 @@ ## Next Следующий агент: читай `.agent/handoff-summary.md`. -Кандидаты: ADR-001 (Repository), ADR-002 (слои), ADR-003 (schema versioning), CI/CD, mypy, T9 (`convert()` quantize), locale-aware форматирование. Лицензия — сделана (MIT). +Кандидаты: ADR-001 (Repository), ADR-002 (слои), ADR-003 (schema versioning), CI/CD, mypy, T10 (`convert()` quantize), T11 (locale-aware), экспорт прогноза в Excel. Лицензия — сделана (MIT). diff --git a/.agent/tasks/manifest.json b/.agent/tasks/manifest.json index 0c11ac2..4eb4a54 100644 --- a/.agent/tasks/manifest.json +++ b/.agent/tasks/manifest.json @@ -1,10 +1,10 @@ { "$schema": "metaagent-task-manifest", "version": "3.0", - "session_id": "metaagent-007", + "session_id": "metaagent-008", "goal": "Серьёзный архитектурный рефактор: A1+A10 (слои+version), A2+A3 (pydantic), A4 (decimal), A7+A8+A9 (DI+repo), A5 (CLI decompose). P1: ISO 4217-aware currency display", "created_at": "2026-10-08T15:58:00Z", - "updated_at": "2026-11-11T11:50:09Z", + "updated_at": "2026-11-11T15:45:00Z", "tasks": [ { "id": "T1", "title": "Реструктуризация в domain/application/infrastructure + version=1", "status": "archived", "origin": "user:direct" }, { "id": "T2", "title": "Pydantic v2 — миграция моделей", "status": "archived", "origin": "user:direct" }, @@ -13,6 +13,7 @@ { "id": "T5", "title": "Dependency Injection в сервисах", "status": "archived", "origin": "user:direct" }, { "id": "T6", "title": "Декомпозиция CLI", "status": "archived", "origin": "user:direct" }, { "id": "T7", "title": "Финальная валидация", "status": "archived", "origin": "user:direct" }, - { "id": "T8", "title": "ISO 4217-aware форматирование денег (per-currency decimals)", "status": "archived", "origin": "user:direct" } + { "id": "T8", "title": "ISO 4217-aware форматирование денег (per-currency decimals)", "status": "archived", "origin": "user:direct" }, + { "id": "T9", "title": "Excel как поверхность сборки модели: шаблон-каркас + надёжный импорт", "status": "archived", "origin": "user:direct" } ] } diff --git a/.agent/tasks/manifest.md b/.agent/tasks/manifest.md index a644498..074e2f9 100644 --- a/.agent/tasks/manifest.md +++ b/.agent/tasks/manifest.md @@ -2,10 +2,10 @@ # Task Manifest -**Session:** `metaagent-005` (initial) → `metaagent-006` (T8 executed) → `metaagent-007` (T8 closed) -**Goal:** Серьёзный архитектурный рефактор -**Date:** 2026-10-08 (T1–T7) · 2026-10-09 (T8) · closed 2026-11-11 -**Total tasks:** 8 (8 archived, 0 pending) +**Session:** `metaagent-005` (initial) → `metaagent-006` (T8 executed) → `metaagent-007` (T8 closed) → `metaagent-008` (T9 done) +**Goal:** Серьёзный архитектурный рефактор, затем Excel как основная поверхность сборки модели +**Date:** 2026-10-08 (T1–T7) · 2026-10-09 (T8) · 2026-11-11 (T8 closed, T9) +**Total tasks:** 9 (9 archived, 0 pending) --- @@ -154,7 +154,44 @@ **Закрытые вопросы:** 1. Округление — `ROUND_HALF_UP` (совместимо с T3). -2. Разделитель тысяч — запятая `,` (сохранили поведение `:,.2f`); locale-aware (пробел для ru) — отдельная задача T10+. +2. Разделитель тысяч — запятая `,` (сохранили поведение `:,.2f`); locale-aware (пробел для ru) — отдельная задача T11. 3. Валюта без символа — **код-префикс** (`BHD 1.234`), как в acceptance criteria и в реализации. ⚠️ В `req-T8.decisions` изначально было записано `suffix` (`1,234.56 CHF`) — противоречие исправлено 2026-11-11 в пользу prefix. -**Сознательно вне scope:** `convert()` по-прежнему делает `quantize("0.01")`, поэтому `0.1 USD → JPY` даёт ≈8.07 вместо ≈7.86. Заведено как кандидат **T9** в `req-T8.follow_ups`. +**Сознательно вне scope:** `convert()` по-прежнему делает `quantize("0.01")`, поэтому `0.1 USD → JPY` даёт ≈8.07 вместо ≈7.86. Заведено как кандидат **T10** в `req-T8.follow_ups`. + +--- + +## T9: Excel как поверхность сборки модели (archived) + +**Зависимости:** T8 (`format_money`), T3 (Decimal), T6 (CLI decompose) +**Источник:** `user:direct` — «довести до состояния, чтобы можно было через excel строить модель, чтобы на excel каркасе стартовать» +**Файлы:** `infrastructure/repositories/excel_repository.py`, `infrastructure/repositories/excel_template.py` (new), `infrastructure/cli/commands/{template_xlsx,import_xlsx}.py`, `infrastructure/cli/{app,i18n,paths}.py`, `domain/recurring.py`, `application/forecast.py`, `tests/`, `README.md` + +**Проблема (проверено на реальном файле):** +- нет генератора каркаса — пользователь не может начать «с чистого Excel»; +- `Transactions.account` хранит имя, а `ForecastService` сравнивает с `str(account.id)` → ручные транзакции молча игнорируются; +- дата-ячейки импортируются как `2026-11-01 00:00:00`; +- отсутствие листа `ExchangeRates` обнуляет курсы по умолчанию; +- заголовки только на английском, ошибки без номера листа/строки; +- `RecurringCashflow` не умеет привязываться к счёту — платёж учитывается на каждом счёте. + +**Что:** +- `cf template-xlsx [path] [--force]` — каркас: 6 листов данных + `ModelInfo` + `Инструкция`, форматы чисел/дат, выпадающие списки (валюта, периодичность, счёт). +- Импорт: алиасы заголовков (ru/en), нормализация дат, чисел (`1 234,56`), ссылок на счёт по имени или UUID, warning'и (дубли имён, формулы без кэша, курсы по умолчанию), ошибки с `лист!строка`. +- `cf import-xlsx --dry-run` — валидация без записи `model.json`. +- `RecurringCashflow.account` (пусто = все счета) + матчинг транзакций и регулярных платежей по имени или UUID в `ForecastService`. + +**Acceptance:** +- [x] `cf template-xlsx` создаёт файл, который импортируется без ошибок и даёт пустую модель +- [x] Заполненный руками шаблон (счёт по имени, даты ячейками, без id) импортируется, транзакции попадают в прогноз +- [x] `cf import-xlsx --dry-run` не перезаписывает `model.json` +- [x] Ошибки строк показывают лист и номер строки; файл с ошибками не сохраняется +- [x] Round-trip: экспорт → импорт сохраняет id счетов и привязки +- [x] Тесты: 118 зелёных (было 75), ruff чистый + +**Результат (2026-11-11):** +- `ExcelRepository` переписан: канонические колонки + алиасы ru/en, даты (ячейки/ISO/DD.MM.YYYY), числа (`1 234,56`, символы, скобки), резолв счёта по имени/UUID, ошибки `лист!строка`, warning'и (формулы без кэша, дубли имён, курсы по умолчанию). +- `write_template()` + лист «Инструкция»; в репозитории лежит `data/model_template.xlsx`. +- CLI: `cf template-xlsx [--force]`, `cf import-xlsx --dry-run` (rich-таблица ошибок, без записи модели). +- `RecurringCashflow.account` (пусто = все счета) + матчинг по имени/UUID; `cf config recurring-add --account`, колонка «Счёт» в `info` и `recurring-list`. +- Прогноз: вызовы идемпотентны, `Итог: Баланс` = сумма по всем счетам последнего месяца (раньше — баланс последнего счёта и накопленные мутации между вызовами). diff --git a/README.md b/README.md index 0a28934..4f71b9e 100644 --- a/README.md +++ b/README.md @@ -41,22 +41,60 @@ cf info # Редактирование модели cf config account-add --name "Main" --balance 5000 cf config transaction-add --account Main --amount -1200 --category rent +cf config recurring-add --amount -1500 --account Main --frequency monthly cf config rate-set USD RUB 80.0 - # Импорт/экспорт Excel -cf import-xlsx data.xlsx +cf template-xlsx data/model_template.xlsx # создать каркас +cf import-xlsx data/my_finances.xlsx # собрать модель из Excel +cf import-xlsx data/my_finances.xlsx --dry-run # только проверить cf export-xlsx exports/report.xlsx ``` -### Пример: создание тестовых данных +## Сборка модели в Excel -Подготовьте Excel-файл с листами: `Accounts`, `Transactions`, `Recurring`, `Assets`, `Liabilities`. Заголовки колонок соответствуют полям моделей. Затем импортируйте: +Excel — основная поверхность, где удобно заполнять модель руками: шаблон → заполнение → импорт → прогноз. JSON остаётся рабочим хранилищем (`data/model.json`), Excel — способ ввода и выгрузки. + +Готовый каркас лежит в репозитории: `data/model_template.xlsx`. Заполните его и импортируйте; пересоздать пустой — `cf template-xlsx --force`. ```bash -cf import-xlsx my_finances.xlsx +cf template-xlsx # data/model_template.xlsx +cf import-xlsx data/model_template.xlsx # пустая модель (проверка каркаса) cf forecast --months 12 ``` +### Листы и колонки + +Заголовки можно писать по-русски или по-английски, регистр и `_`/`-`/пробелы не важны. Порядок колонок любой. + +| Лист | Колонки | Примечания | +|---|---|---| +| `ModelInfo` | `Property`, `Value` | `base_currency` — базовая валюта модели (по умолчанию `RUB`) | +| `Accounts` | `name` (название), `currency` (валюта), `balance` (баланс) | баланс не может быть отрицательным; `id` необязателен | +| `Transactions` | `date` (дата), `account` (счёт), `category`, `amount` (сумма), `description` | `account` — **имя счёта**; `amount` > 0 — доход, < 0 — расход | +| `Recurring` | `account` (счёт), `start_date`, `end_date`, `frequency`, `amount`, `category` | пустой `account` = платёж по всем счетам; `frequency`: daily / weekly / monthly / yearly (или ежедневно / еженедельно / ежемесячно / ежегодно) | +| `Assets` | `name`, `value` (стоимость), `growth_rate` (рост) | `growth_rate` — % годовых | +| `Liabilities` | `name`, `balance`, `interest` (ставка), `payment` (платёж) | `interest` — % годовых, `payment` — в месяц | +| `ExchangeRates` | `from_currency`, `to_currency`, `rate` | лист можно не заполнять — возьмутся курсы по умолчанию | +| `Инструкция` | — | краткая памятка внутри шаблона | + +Правила ввода: + +- `id` можно оставить пустым — он сгенерируется при импорте. Заполняйте только если переносите модель между файлами. +- Счёт в транзакциях указывается **по имени** (`Основной`), можно и UUID. +- Даты принимаются как даты Excel или текстом: `2026-11-01`, `01.11.2026`, `01/11/2026`. +- Числа — как числа Excel или текстом: `1 234,56`, `1,234.56`, `₽1 200,50`. +- Формулы должны быть пересчитаны и сохранены в Excel: иначе импорт предупредит, что значение не сохранено. +- Ошибки показываются с адресом `лист!строка`, файл с ошибками не сохраняется. `--dry-run` проверяет файл, не трогая `data/model.json`. + +### Минимальный пример + +1. `cf template-xlsx` — появится `data/model_template.xlsx`. +2. На листе `ModelInfo` укажите `base_currency = RUB`. +3. `Accounts`: `Основной` / `RUB` / `100000`. +4. `Transactions`: `01.11.2026` / `Основной` / `salary` / `50000`, затем `05.11.2026` / `Основной` / `rent` / `-35000`. +5. `Recurring`: `Основной` / `01.11.2026` / `monthly` / `-1500` / `subscriptions`. +6. `cf import-xlsx data/model_template.xlsx` → `cf forecast --months 12`. + ## Архитектура Проект разделён на три слоя по принципам Clean Architecture: diff --git a/application/forecast.py b/application/forecast.py index 4081440..0973946 100644 --- a/application/forecast.py +++ b/application/forecast.py @@ -1,5 +1,5 @@ from copy import deepcopy -from decimal import Decimal, ROUND_HALF_UP +from decimal import ROUND_HALF_UP, Decimal from domain import Account, FinancialModel @@ -16,15 +16,23 @@ _HUNDRED = Decimal("100") class ForecastService: def __init__(self, model: FinancialModel): - self.model = deepcopy(model) + # Источник не мутируется: каждый прогон работает на свежей копии, + # поэтому повторный вызов forecast_cashflow/summary даёт тот же результат. + self._source = deepcopy(model) + + @property + def model(self) -> FinancialModel: + """Копия исходной модели (для чтения; прогноз её не меняет).""" + return deepcopy(self._source) def forecast_cashflow(self, months: int = 12) -> list[dict]: if months < 1: raise ForecastError("months must be >= 1") + model = deepcopy(self._source) results = [] - for account in self.model.accounts: - monthly = self._project_account(account, months) + for account in model.accounts: + monthly = self._project_account(model, account, months) for m in range(months): results.append({ "account": account.name, @@ -38,7 +46,7 @@ class ForecastService: for m in range(months): total_growth = sum( a.value * a.growth_rate / _HUNDRED / _TWELVE - for a in self.model.assets + for a in model.assets ) month_rows = [r for r in results if r["month"] == m + 1] total_bal = sum(r["balance"] for r in month_rows) or _ONE @@ -48,32 +56,35 @@ class ForecastService: r["balance"] = _q(r["balance"] + total_growth * share) # Compound asset values for next month - for a in self.model.assets: + for a in model.assets: a.value = a.value + a.value * a.growth_rate / _HUNDRED / _TWELVE return results - def _project_account(self, account: Account, months: int) -> list[dict]: + def _project_account(self, model: FinancialModel, account: Account, months: int) -> list[dict]: balance = account.balance monthly = [] for m in range(months): income = _ZERO expenses = _ZERO - for t in self.model.transactions: - if t.account == str(account.id): + for t in model.transactions: + if _refers_to(t.account, account): if t.amount > 0: income += t.amount else: expenses += abs(t.amount) - for r in self.model.recurring: + for r in model.recurring: + # Пустой r.account — платёж общий для всех счетов (legacy-поведение). + if r.account and not _refers_to(r.account, account): + continue if r.amount > 0: income += r.amount else: expenses += abs(r.amount) - expenses += self._liability_cost(account) + expenses += self._liability_cost(model, account) balance = balance + income - expenses @@ -84,9 +95,9 @@ class ForecastService: }) return monthly - def _liability_cost(self, account: Account) -> Decimal: + def _liability_cost(self, model: FinancialModel, account: Account) -> Decimal: total = _ZERO - for liability in self.model.liabilities: + for liability in model.liabilities: interest_cost = liability.balance * liability.interest / _HUNDRED / _TWELVE total += interest_cost liability.balance = liability.balance - (liability.payment - interest_cost) @@ -99,11 +110,14 @@ class ForecastService: if not results: return {"total_balance": 0, "total_income": 0, "total_expenses": 0, "months": months} - final = results[-1] + last_month = max(r["month"] for r in results) + total_balance = sum( + (r["balance"] for r in results if r["month"] == last_month), _ZERO + ) all_income = sum(r["income"] for r in results) all_expenses = sum(r["expenses"] for r in results) return { - "total_balance": final["balance"], + "total_balance": _q(total_balance), "total_income": _q(all_income), "total_expenses": _q(all_expenses), "months": months, @@ -113,3 +127,17 @@ class ForecastService: def _q(v: Decimal) -> Decimal: """Quantize to 2 decimal places, ROUND_HALF_UP.""" return v.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + + +def _refers_to(ref: str, account: Account) -> bool: + """True if `ref` points at `account` — by UUID or by (case-insensitive) name. + + Excel-authored models reference accounts by name; JSON-authored and legacy + models use the account UUID string. Both are accepted. + """ + value = (ref or "").strip() + if not value: + return False + if value == str(account.id): + return True + return value.casefold() == account.name.strip().casefold() diff --git a/application/scenarios.py b/application/scenarios.py index 2efbaf7..3c6e2eb 100644 --- a/application/scenarios.py +++ b/application/scenarios.py @@ -1,8 +1,8 @@ from copy import deepcopy from decimal import Decimal -from domain import FinancialModel, ForecastScenario from application.forecast import ForecastService +from domain import FinancialModel, ForecastScenario class ScenarioError(Exception): diff --git a/data/model_template.xlsx b/data/model_template.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..2d781b45d0bae9cc2b666db61e1fa2c400e9ce48 GIT binary patch literal 37515 zcmWIWW@Zs#U|`^2m{XG->vr7NV=4m!!&wFf1_1^JhLrr|fTH|@V*SK|0=4=vhsxVBE3!}wQVz8Kk7Zn zH8wiV>u^o^m)+@83%eFRsa|Jzx3OoV6#o)=Ip)KQa<4bE8uD12d9;1Q%PV?r>80nV zIhAj+3RFA%D8j^Qqq_X+J2G4X&#P4Jx`n+hr)#tR?+!jK8a(gWsr)}Ftozw_iKBX9 zeURZk*-<$sGx4L7n;tYh(pA~K z`=}c4Nsrz6`BCM&yY98b82vZD@6%!8I79JKund#iD}!9M>%Uce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-&3Meuxmlln3ruO#vS%gl-D@<~4*V>msq50^Z7oZVLLU0E8*C z3$U63UL$~R3i?JKk*^RChy>)}oI;#Vvt%I%+ zy|sYQ*xU)W6O=|_Z3lGC=rsdE^ObI}=6F!^N*~z>a6N%;4tjx#Fz0Cx*5Wn5o0Scu RNPt0rL4$>X!M6{@0|0*0HsSyP literal 0 HcmV?d00001 diff --git a/domain/currency.py b/domain/currency.py index 1c87abd..c2cbe7b 100644 --- a/domain/currency.py +++ b/domain/currency.py @@ -1,4 +1,4 @@ -from decimal import Decimal, ROUND_HALF_UP +from decimal import ROUND_HALF_UP, Decimal from pydantic import BaseModel, Field, field_validator diff --git a/domain/recurring.py b/domain/recurring.py index c17d40a..ef3a36a 100644 --- a/domain/recurring.py +++ b/domain/recurring.py @@ -11,6 +11,9 @@ class RecurringCashflow(BaseModel): frequency: str = "monthly" amount: Decimal = Field(default=Decimal("0")) category: str = "" + # Пустая строка = платёж относится ко всем счетам (обратная совместимость). + # Имя счёта или его UUID — платёж учитывается только для этого счёта. + account: str = "" @field_validator("frequency") @classmethod diff --git a/infrastructure/ai/assistant.py b/infrastructure/ai/assistant.py index a33c757..70fd054 100644 --- a/infrastructure/ai/assistant.py +++ b/infrastructure/ai/assistant.py @@ -1,9 +1,9 @@ import json from decimal import Decimal -from infrastructure.ai import prompts -from domain import CurrencyConverter, FinancialModel from application.forecast import ForecastService +from domain import CurrencyConverter, FinancialModel +from infrastructure.ai import prompts class AssistantError(Exception): diff --git a/infrastructure/cli/app.py b/infrastructure/cli/app.py index 78aa209..26bedab 100644 --- a/infrastructure/cli/app.py +++ b/infrastructure/cli/app.py @@ -8,7 +8,6 @@ try: except (AttributeError, OSError): pass -from infrastructure.cli.i18n import setup_i18n, t from infrastructure.cli.commands import ( analyze, compare, @@ -19,8 +18,10 @@ from infrastructure.cli.commands import ( info, init, scenario, + template_xlsx, whatif, ) +from infrastructure.cli.i18n import setup_i18n, t setup_i18n() @@ -32,6 +33,7 @@ app.command(name="forecast")(forecast.forecast) app.command(name="scenario")(scenario.scenario) app.command(name="whatif")(whatif.whatif) app.command(name="compare")(compare.compare) +app.command(name="template-xlsx")(template_xlsx.template_xlsx) app.command(name="import-xlsx")(import_xlsx.import_xlsx) app.command(name="export-xlsx")(export_xlsx.export_xlsx) app.command(name="analyze")(analyze.analyze) diff --git a/infrastructure/cli/commands/__init__.py b/infrastructure/cli/commands/__init__.py index d67082e..63745db 100644 --- a/infrastructure/cli/commands/__init__.py +++ b/infrastructure/cli/commands/__init__.py @@ -8,6 +8,7 @@ from infrastructure.cli.commands import ( info, init, scenario, + template_xlsx, whatif, ) @@ -21,5 +22,6 @@ __all__ = [ "info", "init", "scenario", + "template_xlsx", "whatif", ] diff --git a/infrastructure/cli/commands/config_cmd.py b/infrastructure/cli/commands/config_cmd.py index 1d84779..86c7c1d 100644 --- a/infrastructure/cli/commands/config_cmd.py +++ b/infrastructure/cli/commands/config_cmd.py @@ -13,7 +13,7 @@ from domain import ( Transaction, ) from infrastructure.cli.i18n import t -from infrastructure.cli.services import load_model, save_model +from infrastructure.cli.services import account_label, load_model, save_model app = typer.Typer(name="config", help=t("config.help")) console = Console() @@ -242,12 +242,19 @@ def recurring_add( frequency: str = typer.Option("monthly", "--frequency", "-f", help=t("cmd.config.recurring_add.opt.frequency")), start_date: str = typer.Option("", "--start", "-s", help=t("cmd.config.recurring_add.opt.start")), end_date: str = typer.Option("", "--end", "-e", help=t("cmd.config.recurring_add.opt.end")), + account: str = typer.Option("", "--account", "-a", help=t("cmd.config.recurring_add.opt.account")), ) -> None: """Добавить регулярный платёж""" model = load_model() + account_id = "" + if account: + account_id = _resolve_account_id(model, account) or "" + if not account_id: + console.print(f"[red]{t('cmd.config.recurring_add.err', account=account)}[/red]") + raise typer.Exit(1) rc = RecurringCashflow( start_date=start_date or "", end_date=end_date or "", - frequency=frequency, amount=amount, category=category, + frequency=frequency, amount=amount, category=category, account=account_id, ) model.recurring.append(rc) save_model(model) @@ -266,6 +273,7 @@ def recurring_list() -> None: return table = Table(title=t("table.recurring.title")) table.add_column(t("table.recurring.col.id"), style="dim") + table.add_column(t("table.recurring.col.account")) table.add_column(t("table.recurring.col.start")) table.add_column(t("table.recurring.col.end")) table.add_column(t("table.recurring.col.period")) @@ -273,7 +281,8 @@ def recurring_list() -> None: table.add_column(t("table.recurring.col.category")) for r in model.recurring: amount_str = CurrencyConverter.format_money(r.amount, model.base_currency) - row = (str(r.id)[:8], r.start_date, r.end_date, r.frequency, amount_str, r.category) + owner = account_label(model, r.account, empty=t("table.recurring.all_accounts")) + row = (str(r.id)[:8], owner, r.start_date, r.end_date, r.frequency, amount_str, r.category) table.add_row(*row) console.print(table) @@ -410,8 +419,11 @@ def liability_remove( def _resolve_account_id(model, identifier: str) -> str | None: + value = (identifier or "").strip() + if not value: + return None for a in model.accounts: - if str(a.id) == identifier or a.name == identifier: + if value == str(a.id) or value.casefold() == a.name.strip().casefold(): return str(a.id) return None diff --git a/infrastructure/cli/commands/import_xlsx.py b/infrastructure/cli/commands/import_xlsx.py index 5415ec8..f9505fc 100644 --- a/infrastructure/cli/commands/import_xlsx.py +++ b/infrastructure/cli/commands/import_xlsx.py @@ -1,29 +1,75 @@ """cf import-xlsx — импорт данных из Excel.""" import typer +from rich.markup import escape +from rich.table import Table from infrastructure.cli.i18n import t from infrastructure.cli.services import console, save_model -from infrastructure.repositories import ExcelRepository, ExcelRepositoryError +from infrastructure.repositories import ExcelRepository, ExcelRepositoryError, ExcelRowError app = typer.Typer() _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]") + + @app.command(name="import-xlsx") 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/info.py b/infrastructure/cli/commands/info.py index 3722524..c599ead 100644 --- a/infrastructure/cli/commands/info.py +++ b/infrastructure/cli/commands/info.py @@ -4,7 +4,7 @@ from rich.table import Table from domain import CurrencyConverter from infrastructure.cli.i18n import t -from infrastructure.cli.services import console, load_model +from infrastructure.cli.services import account_label, console, load_model app = typer.Typer() @@ -51,12 +51,14 @@ def info() -> None: if model.recurring: tbl = Table(title=t("table.recurring.title")) + tbl.add_column(t("table.recurring.col.account")) tbl.add_column(t("table.recurring.col.period")) tbl.add_column(t("table.recurring.col.amount"), justify="right") tbl.add_column(t("table.recurring.col.category")) for r in model.recurring: amount_str = CurrencyConverter.format_money(r.amount, model.base_currency) - tbl.add_row(r.frequency, amount_str, r.category) + owner = account_label(model, r.account, empty=t("table.recurring.all_accounts")) + tbl.add_row(owner, r.frequency, amount_str, r.category) console.print(tbl) if model.assets: diff --git a/infrastructure/cli/commands/init.py b/infrastructure/cli/commands/init.py index 9e0cf96..d700ff4 100644 --- a/infrastructure/cli/commands/init.py +++ b/infrastructure/cli/commands/init.py @@ -1,10 +1,10 @@ """cf init — создать пустую модель.""" import typer +from domain import FinancialModel from infrastructure.cli.i18n import t from infrastructure.cli.paths import MODEL_PATH from infrastructure.cli.services import console, save_model -from domain import FinancialModel app = typer.Typer() diff --git a/infrastructure/cli/commands/template_xlsx.py b/infrastructure/cli/commands/template_xlsx.py new file mode 100644 index 0000000..eb18a70 --- /dev/null +++ b/infrastructure/cli/commands/template_xlsx.py @@ -0,0 +1,32 @@ +"""cf template-xlsx — создать Excel-шаблон модели для ручного заполнения.""" +from pathlib import Path + +import typer +from rich.markup import escape + +from infrastructure.cli.i18n import t +from infrastructure.cli.paths import TEMPLATE_PATH +from infrastructure.cli.services import console +from infrastructure.repositories import ExcelRepositoryError, write_template + +app = typer.Typer() + + +@app.command(name="template-xlsx") +def template_xlsx( + path: Path = typer.Argument(TEMPLATE_PATH, help=t("cmd.template.arg.path")), + force: bool = typer.Option(False, "--force", "-f", help=t("cmd.template.opt.force")), +) -> None: + """Создать Excel-шаблон для заполнения модели""" + if path.exists() and not force: + console.print(f"[red]{t('cmd.template.err.exists', path=escape(str(path)))}[/red]") + raise typer.Exit(1) + + try: + target = write_template(path, force=force) + except ExcelRepositoryError 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/i18n.py b/infrastructure/cli/i18n.py index 144c8ce..885cd0e 100644 --- a/infrastructure/cli/i18n.py +++ b/infrastructure/cli/i18n.py @@ -68,11 +68,36 @@ _r("cmd.compare.col.scenario", "Сценарий") _r("cmd.import.help", "Импорт данных из Excel") _r("cmd.import.arg.path", "Путь к .xlsx файлу") +_r("cmd.import.opt.dry_run", "Только проверить файл, не сохраняя модель") _r("cmd.import.ok", - "Импортировано: {accounts} счетов, {transactions} транзакций, " - "{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств") + "Импортировано: счета — {accounts}, транзакции — {transactions}, " + "регулярные платежи — {recurring}, активы — {assets}, обязательства — {liabilities}") _r("cmd.import.base_currency", "Базовая валюта: {currency}") _r("cmd.import.err", "Ошибка импорта: {error}") +_r("cmd.import.warn", "Предупреждение: {warning}") +_r("cmd.import.errors.title", "Ошибки в файле ({count}) — модель не сохранена:") +_r("cmd.import.errors.hint", "Первая ошибка: {first}. Исправьте файл и повторите импорт.") +_r("cmd.import.errors.col.sheet", "Лист") +_r("cmd.import.errors.col.row", "Строка") +_r("cmd.import.errors.col.field", "Поле") +_r("cmd.import.errors.col.message", "Ошибка") +_r("cmd.import.dry_run.title", "Проверка файла (--dry-run):") +_r("cmd.import.dry_run.ok", + "В файле: счета — {accounts}, транзакции — {transactions}, " + "регулярные платежи — {recurring}, активы — {assets}, обязательства — {liabilities}") +_r("cmd.import.dry_run.not_saved", "Модель не сохранена (--dry-run)") +_r("cmd.import.dry_run.base_currency", "Базовая валюта: {currency}") + +# ── cmd.template ────────────────────────────────────────────── + +_r("cmd.template.help", "Создать Excel-шаблон для заполнения модели") +_r("cmd.template.arg.path", "Путь для .xlsx шаблона") +_r("cmd.template.opt.force", "Перезаписать существующий файл") +_r("cmd.template.ok", "Шаблон создан: {path}") +_r("cmd.template.hint", "Заполните файл в Excel и импортируйте: cf import-xlsx {path}") +_r("cmd.template.err.exists", + "Файл уже существует: {path} — добавьте --force, чтобы перезаписать") +_r("cmd.template.err", "Ошибка создания шаблона: {error}") # ── cmd.export ──────────────────────────────────────────────── @@ -119,6 +144,8 @@ _r("table.transactions.col.description", "Описание") _r("table.recurring.title", "Регулярные платежи") _r("table.recurring.col.period", "Период") +_r("table.recurring.col.account", "Счёт") +_r("table.recurring.all_accounts", "все счета") _r("table.recurring.col.amount", "Сумма") _r("table.recurring.col.category", "Категория") _r("table.recurring.col.id", "ID") @@ -209,6 +236,8 @@ _r("cmd.config.recurring_add.opt.category", "Категория") _r("cmd.config.recurring_add.opt.frequency", "Периодичность") _r("cmd.config.recurring_add.opt.start", "Дата начала (YYYY-MM-DD)") _r("cmd.config.recurring_add.opt.end", "Дата окончания (YYYY-MM-DD)") +_r("cmd.config.recurring_add.opt.account", "Счёт (имя); пусто — платёж по всем счетам") +_r("cmd.config.recurring_add.err", "Счёт не найден: {account}") _r("cmd.config.recurring_add.ok", "Регулярный платёж на {amount_str} ({frequency})") _r("cmd.config.recurring_list.help", "Список регулярных платежей") diff --git a/infrastructure/cli/paths.py b/infrastructure/cli/paths.py index d172ee9..f2d5370 100644 --- a/infrastructure/cli/paths.py +++ b/infrastructure/cli/paths.py @@ -3,3 +3,4 @@ from pathlib import Path DATA_DIR: Path = Path("data") MODEL_PATH: Path = DATA_DIR / "model.json" +TEMPLATE_PATH: Path = DATA_DIR / "model_template.xlsx" diff --git a/infrastructure/cli/services.py b/infrastructure/cli/services.py index 0fb65b6..d1c1945 100644 --- a/infrastructure/cli/services.py +++ b/infrastructure/cli/services.py @@ -12,7 +12,6 @@ from infrastructure.ai.assistant import AssistantService from infrastructure.cli.paths import MODEL_PATH from infrastructure.repositories import JsonFileRepository - console = Console() _json_repo = JsonFileRepository() @@ -28,7 +27,9 @@ def save_model(model: FinancialModel) -> None: _json_repo.save(model, MODEL_PATH) -def build_services(model: FinancialModel) -> tuple[ForecastService, ScenarioService, AssistantService, CurrencyConverter]: +def build_services( + model: FinancialModel, +) -> tuple[ForecastService, ScenarioService, AssistantService, CurrencyConverter]: """Composition root: собрать граф сервисов с зависимостями.""" converter = CurrencyConverter(model.exchange_rates) forecast_service = ForecastService(model) @@ -39,6 +40,17 @@ def build_services(model: FinancialModel) -> tuple[ForecastService, ScenarioServ return forecast_service, scenario_service, assistant_service, converter +def account_label(model: FinancialModel, ref: str, *, empty: str = "") -> str: + """Человекочитаемое имя счёта по ссылке (UUID или имя); пусто → `empty`.""" + value = (ref or "").strip() + if not value: + return empty + for account in model.accounts: + if value == str(account.id) or value.casefold() == account.name.strip().casefold(): + return account.name + return value + + def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str, str]: target = currency or model.base_currency converter = CurrencyConverter(model.exchange_rates) diff --git a/infrastructure/repositories/__init__.py b/infrastructure/repositories/__init__.py index 02721f4..3b0e614 100644 --- a/infrastructure/repositories/__init__.py +++ b/infrastructure/repositories/__init__.py @@ -1,4 +1,17 @@ -from infrastructure.repositories.excel_repository import ExcelRepository, ExcelRepositoryError +from infrastructure.repositories.excel_repository import ( + ExcelImportResult, + ExcelRepository, + ExcelRepositoryError, + ExcelRowError, +) +from infrastructure.repositories.excel_template import write_template from infrastructure.repositories.json_file_repository import JsonFileRepository -__all__ = ["JsonFileRepository", "ExcelRepository", "ExcelRepositoryError"] +__all__ = [ + "JsonFileRepository", + "ExcelRepository", + "ExcelRepositoryError", + "ExcelImportResult", + "ExcelRowError", + "write_template", +] diff --git a/infrastructure/repositories/excel_repository.py b/infrastructure/repositories/excel_repository.py index 065c27e..32511c2 100644 --- a/infrastructure/repositories/excel_repository.py +++ b/infrastructure/repositories/excel_repository.py @@ -1,8 +1,36 @@ -"""ExcelRepository — хранит FinancialModel в .xlsx (5 листов + ModelInfo).""" +"""ExcelRepository — .xlsx как полноценная поверхность authoring. + +Файл содержит листы ``ModelInfo``, ``Accounts``, ``Transactions``, ``Recurring``, +``Assets``, ``Liabilities``, ``ExchangeRates``. При импорте заголовки принимаются +на русском и английском без учёта регистра, пробелов, ``_`` и ``-``. Пользователь +может заполнять файл руками (без колонки ``id``, счёта — по имени) и импортировать +его командой ``cf import-xlsx``. + +Публичный контракт: + +- ``ExcelRepository.load(path)`` — вернуть модель или поднять ``ExcelRepositoryError`` + с компактной сводкой ошибок; +- ``ExcelRepository.load_report(path)`` — никогда не падает на ошибках данных, + собирает их в ``ExcelImportResult`` (не больше 100 ошибок); +- ``ExcelRepository.save(model, path)`` — записать модель в .xlsx; +- ``write_template(path, force=False)`` — сгенерировать пустой шаблон (см. + ``infrastructure.repositories.excel_template``). +""" +from __future__ import annotations + +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 Workbook, load_workbook +from openpyxl.styles import Font +from openpyxl.utils import get_column_letter +from openpyxl.utils.exceptions import InvalidFileException +from pydantic import ValidationError from application.repositories.model_repository import ModelRepository from domain import ( @@ -15,124 +43,733 @@ from domain import ( Transaction, ) +# --------------------------------------------------------------------------- +# Схема листов +# --------------------------------------------------------------------------- -class ExcelRepositoryError(Exception): - pass +CANONICAL_COLUMNS: dict[str, tuple[str, ...]] = { + "Accounts": ("id", "name", "currency", "balance"), + "Transactions": ("id", "date", "account", "category", "amount", "description"), + "Recurring": ("id", "account", "start_date", "end_date", "frequency", "amount", "category"), + "Assets": ("id", "name", "value", "growth_rate"), + "Liabilities": ("id", "name", "balance", "interest", "payment"), + "ExchangeRates": ("from_currency", "to_currency", "rate"), +} +SHEET_ORDER: tuple[str, ...] = ("ModelInfo", *CANONICAL_COLUMNS) -_SHEET_CONFIG = { +# Канонический столбец -> принимаемые заголовки (ru + en). +_ALIASES: dict[str, dict[str, tuple[str, ...]]] = { "Accounts": { - "fields": ["id", "name", "currency", "balance"], - "cls": Account, + "id": ("id",), + "name": ("name", "название", "имя"), + "currency": ("currency", "валюта"), + "balance": ("balance", "баланс"), }, "Transactions": { - "fields": ["id", "date", "account", "category", "amount", "description"], - "cls": Transaction, + "id": ("id",), + "date": ("date", "дата"), + "account": ("account", "счёт", "счет", "account_name"), + "category": ("category", "категория"), + "amount": ("amount", "сумма"), + "description": ("description", "описание", "комментарий"), }, "Recurring": { - "fields": ["id", "start_date", "end_date", "frequency", "amount", "category"], - "cls": RecurringCashflow, + "id": ("id",), + "account": ("account", "счёт", "счет"), + "start_date": ("start_date", "дата_начала", "начало"), + "end_date": ("end_date", "дата_окончания", "конец"), + "frequency": ("frequency", "периодичность", "частота"), + "amount": ("amount", "сумма"), + "category": ("category", "категория"), }, "Assets": { - "fields": ["id", "name", "value", "growth_rate"], - "cls": Asset, + "id": ("id",), + "name": ("name", "название"), + "value": ("value", "стоимость"), + "growth_rate": ("growth_rate", "рост", "доходность"), }, "Liabilities": { - "fields": ["id", "name", "balance", "interest", "payment"], - "cls": Liability, + "id": ("id",), + "name": ("name", "название"), + "balance": ("balance", "баланс", "остаток"), + "interest": ("interest", "ставка", "процент"), + "payment": ("payment", "платёж", "платеж", "платёж_мес"), }, "ExchangeRates": { - "fields": ["from_currency", "to_currency", "rate"], - "cls": ExchangeRate, + "from_currency": ("from_currency", "из", "валюта_из"), + "to_currency": ("to_currency", "в", "валюта_в"), + "rate": ("rate", "курс"), }, } +# Тип значения канонического столбца. +FIELD_KINDS: dict[str, dict[str, str]] = { + "Accounts": {"id": "id", "name": "text", "currency": "currency", "balance": "decimal"}, + "Transactions": { + "id": "id", + "date": "date", + "account": "account", + "category": "text", + "amount": "decimal", + "description": "text", + }, + "Recurring": { + "id": "id", + "account": "account_optional", + "start_date": "date", + "end_date": "date", + "frequency": "frequency", + "amount": "decimal", + "category": "text", + }, + "Assets": {"id": "id", "name": "text", "value": "decimal", "growth_rate": "decimal"}, + "Liabilities": { + "id": "id", + "name": "text", + "balance": "decimal", + "interest": "decimal", + "payment": "decimal", + }, + "ExchangeRates": {"from_currency": "currency", "to_currency": "currency", "rate": "decimal"}, +} + +_MONEY_FORMAT = "#,##0.00" +_RATE_FORMAT = "0.00" +_DATE_FORMAT = "yyyy-mm-dd" + +# Форматы числовых ячеек: (лист, столбец) -> number_format. +CELL_NUMBER_FORMATS: dict[tuple[str, str], str] = { + ("Accounts", "balance"): _MONEY_FORMAT, + ("Transactions", "date"): _DATE_FORMAT, + ("Transactions", "amount"): _MONEY_FORMAT, + ("Recurring", "start_date"): _DATE_FORMAT, + ("Recurring", "end_date"): _DATE_FORMAT, + ("Recurring", "amount"): _MONEY_FORMAT, + ("Assets", "value"): _MONEY_FORMAT, + ("Assets", "growth_rate"): _RATE_FORMAT, + ("Liabilities", "balance"): _MONEY_FORMAT, + ("Liabilities", "interest"): _RATE_FORMAT, + ("Liabilities", "payment"): _MONEY_FORMAT, + ("ExchangeRates", "rate"): _RATE_FORMAT, + ("Accounts", "currency"): "@", +} + +COLUMN_WIDTHS: dict[str, int] = { + "id": 38, + "name": 26, + "currency": 10, + "balance": 16, + "date": 12, + "account": 22, + "category": 16, + "amount": 14, + "description": 40, + "start_date": 12, + "end_date": 12, + "frequency": 14, + "value": 16, + "growth_rate": 12, + "interest": 10, + "payment": 14, + "from_currency": 14, + "to_currency": 14, + "rate": 10, + "Property": 24, + "Value": 22, +} + +_TARGETS: dict[str, str] = { + "Accounts": "accounts", + "Transactions": "transactions", + "Recurring": "recurring", + "Assets": "assets", + "Liabilities": "liabilities", +} + +_SAVE_ATTR: dict[str, str] = {**_TARGETS, "ExchangeRates": "exchange_rates"} + +_DATE_FORMATS = ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%Y/%m/%d", "%d-%m-%Y") + +_FREQUENCIES = ("daily", "weekly", "monthly", "yearly") +_FREQUENCY_ALIASES = { + "день": "daily", + "ежедневно": "daily", + "неделя": "weekly", + "еженедельно": "weekly", + "месяц": "monthly", + "ежемесячно": "monthly", + "год": "yearly", + "ежегодно": "yearly", +} + +_MAX_ERRORS = 100 +_NON_NUMERIC = re.compile(r"[^0-9,.\-+]") + +# --------------------------------------------------------------------------- +# Публичные типы +# --------------------------------------------------------------------------- + + +class ExcelRepositoryError(Exception): + """Ошибка импорта/экспорта .xlsx (файл не найден, ошибки данных, шаблон есть).""" + + +@dataclass(frozen=True) +class ExcelRowError: + """Одна ошибка строки листа (row — 1-based номер строки в Excel).""" + + sheet: str + row: int + field: str + message: str + + def __str__(self) -> str: + prefix = f"{self.sheet}!{self.row}" + if self.field: + prefix += f" [{self.field}]" + return f"{prefix}: {self.message}" + + +@dataclass +class ExcelImportResult: + """Результат импорта: модель + накопленные ошибки строк + предупреждения.""" + + model: FinancialModel + errors: list[ExcelRowError] = field(default_factory=list) + warnings: list[str] = field(default_factory=list) + + +# --------------------------------------------------------------------------- +# Нормализация значений +# --------------------------------------------------------------------------- + + +def _norm_header(value: object) -> str: + """Ключ заголовка: без регистра/пробелов/``_``/``-``, ё == е.""" + if value is None: + return "" + text = str(value).strip().casefold().replace("ё", "е") + return re.sub(r"[\s_\-]+", "", text) + + +def _name_key(value: str) -> str: + return value.strip().casefold().replace("ё", "е") + + +def _is_empty(value: object) -> bool: + if value is None: + return True + if isinstance(value, str): + return not value.strip() + return False + + +def _parse_date(value: object) -> str: + """Вернуть ISO-дату ``YYYY-MM-DD``; время отбрасывается. Иначе ValueError.""" + 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 _DATE_FORMATS: + 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_decimal(value: object) -> Decimal: + """Разобрать число из ячейки: NBSP/пробелы, запятая, символы валют, (скобки).""" + 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("пустое число") + + 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}'") + + 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(".", "") + + try: + 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 _convert_value(kind: str, value: object) -> tuple[object | None, str | None]: + """Сконвертировать значение ячейки. Возвращает (значение, текст ошибки).""" + if kind == "id": + text = str(value).strip() + try: + return UUID(text), None + except ValueError: + return None, f"некорректный id '{text}' — ожидается UUID или пустая ячейка" + if kind == "text": + text = str(value).strip() + return (text or None), None + if kind == "currency": + text = str(value).strip().upper() + return (text or None), None + if kind == "date": + try: + return _parse_date(value), None + except ValueError as exc: + return None, str(exc) + if kind == "decimal": + try: + return _parse_decimal(value), None + except ValueError as exc: + return None, str(exc) + if kind == "frequency": + text = str(value).strip().casefold() + canonical = _FREQUENCY_ALIASES.get(text, text) + if canonical not in _FREQUENCIES: + return None, ( + f"недопустимая периодичность '{value}' — используйте " + + ", ".join(_FREQUENCIES) + ) + return canonical, None + if kind in {"account", "account_optional"}: + return str(value).strip(), None + # Неизвестный тип — оставляем как есть. + return value, None + + +# --------------------------------------------------------------------------- +# Внутренние структуры +# --------------------------------------------------------------------------- + + +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)) + + def warn(self, message: str) -> None: + if message not in self.warnings: + self.warnings.append(message) + + +@dataclass +class _AccountIndex: + 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) + + +# --------------------------------------------------------------------------- +# Репозиторий +# --------------------------------------------------------------------------- + class ExcelRepository(ModelRepository): + # -- импорт ------------------------------------------------------------- + def load(self, path: str | Path) -> FinancialModel: + """Прочитать модель; при ошибках данных поднять ``ExcelRepositoryError``.""" + result = self.load_report(path) + if result.errors: + shown = "; ".join(str(e) for e 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: + """Прочитать модель, собрав ошибки строк вместо исключения.""" p = Path(path) if not p.exists(): raise ExcelRepositoryError(f"File not found: {p}") - wb = load_workbook(p, read_only=True, data_only=True) + collector = _IssueCollector() model = FinancialModel() - model.exchange_rates = [] - for sheet_name, config in _SHEET_CONFIG.items(): - if sheet_name not in wb.sheetnames: - continue - ws = wb[sheet_name] - rows = list(ws.iter_rows(values_only=True)) - if len(rows) < 2: - continue - - headers = [str(h).strip().lower() if h else "" for h in rows[0]] - for row in rows[1:]: - if not any(v is not None for v in row): + try: + wb = load_workbook(p, data_only=True) + except (BadZipFile, InvalidFileException, KeyError, OSError) as exc: + raise ExcelRepositoryError(f"Не удалось открыть Excel-файл {p}: {exc}") from exc + try: + self._read_model_info(wb, model) + accounts, index = self._read_accounts(wb, collector) + model.accounts = accounts + for sheet_name, attribute in _TARGETS.items(): + if sheet_name == "Accounts": continue - data = {} - for i, header in enumerate(headers): - val = row[i] if i < len(row) else None - if val is not None: - data[header] = str(val) if not isinstance(val, (int, float)) else val - self._add_to_model(model, sheet_name, data, config["cls"]) + setattr(model, attribute, self._read_rows(wb, sheet_name, index, collector)) + self._read_exchange_rates(wb, model, collector) + self._check_formulas(wb, p, collector) + finally: + wb.close() - if "ModelInfo" in wb.sheetnames: - ws = wb["ModelInfo"] - rows = list(ws.iter_rows(values_only=True)) - for row in rows: - if row[0] and str(row[0]).strip().lower() == "base_currency" and len(row) > 1: - model.base_currency = str(row[1]).strip() + if collector.truncated: + collector.warn(f"ошибок больше {_MAX_ERRORS} — показаны первые {_MAX_ERRORS}") - wb.close() - return model + return ExcelImportResult(model=model, errors=collector.errors, warnings=collector.warnings) + + # -- экспорт ------------------------------------------------------------ def save(self, model: FinancialModel, path: str | Path) -> None: p = Path(path) + p.parent.mkdir(parents=True, exist_ok=True) + wb = Workbook() wb.remove(wb.active) - collections = { - "Accounts": model.accounts, - "Transactions": model.transactions, - "Recurring": model.recurring, - "Assets": model.assets, - "Liabilities": model.liabilities, - "ExchangeRates": model.exchange_rates, - } + self._write_sheet( + wb, + "ModelInfo", + ["Property", "Value"], + [["base_currency", model.base_currency]], + ) - for sheet_name, items in collections.items(): - config = _SHEET_CONFIG[sheet_name] - ws = wb.create_sheet(title=sheet_name) - ws.append(config["fields"]) - for item in items: - row = [ - str(getattr(item, f)) if isinstance(getattr(item, f), UUID) - else getattr(item, f) - for f in config["fields"] - ] - ws.append(row) - - ws_info = wb.create_sheet(title="ModelInfo") - ws_info.append(["Property", "Value"]) - ws_info.append(["base_currency", model.base_currency]) + name_by_id = {str(account.id): account.name for account in model.accounts} + for sheet_name in CANONICAL_COLUMNS: + items = getattr(model, _SAVE_ATTR[sheet_name], []) + rows = [self._row_values(sheet_name, item, name_by_id) for item in items] + self._write_sheet(wb, sheet_name, list(CANONICAL_COLUMNS[sheet_name]), rows) wb.save(p) - def _add_to_model(self, model: FinancialModel, sheet_name: str, data: dict, cls) -> None: + # -- чтение ------------------------------------------------------------- + + def _read_model_info(self, wb, model: FinancialModel) -> None: + if "ModelInfo" not in wb.sheetnames: + return + for row in wb["ModelInfo"].iter_rows(values_only=True): + if not row or _is_empty(row[0]): + continue + if _norm_header(row[0]) in {"basecurrency", "базоваявалюта"} and len(row) > 1: + if not _is_empty(row[1]): + model.base_currency = str(row[1]).strip() + + def _read_accounts( + self, wb, collector: _IssueCollector + ) -> tuple[list[Account], _AccountIndex]: + accounts: list[tuple[int, Account]] = [] + for row_number, data in self._sheet_rows(wb, "Accounts", collector): + instance = self._validate(Account, data, "Accounts", row_number, collector) + if instance is not None: + accounts.append((row_number, instance)) + + index = _AccountIndex() + first_row: dict[str, int] = {} + for row_number, account in accounts: + key = _name_key(account.name) + if key: + if key in index.by_name: + collector.warn( + f"Accounts: имя счёта '{account.name}' повторяется " + f"(строка {row_number}, первая — {first_row[key]}) — используется первый" + ) + else: + index.by_name[key] = str(account.id) + index.names.append(account.name) + first_row[key] = row_number + index.by_id.add(str(account.id)) + + return [account for _, account in accounts], index + + def _read_rows( + self, wb, sheet_name: str, index: _AccountIndex, collector: _IssueCollector + ) -> list: + cls = { + "Transactions": Transaction, + "Recurring": RecurringCashflow, + "Assets": Asset, + "Liabilities": Liability, + }[sheet_name] + required_account = sheet_name == "Transactions" + accounts_field = "account" if sheet_name in {"Transactions", "Recurring"} else None + + instances = [] + for row_number, data in self._sheet_rows(wb, sheet_name, collector): + if accounts_field is not None: + reference = data.pop(accounts_field, None) + if not reference: + if required_account: + collector.error( + sheet_name, + row_number, + accounts_field, + "счёт обязателен — укажите имя счёта из листа Accounts; " + f"известные счета: {index.describe()}", + ) + continue + data[accounts_field] = "" + else: + resolved = self._resolve_account( + reference, index, sheet_name, row_number, accounts_field, collector + ) + if resolved is None: + continue + data[accounts_field] = resolved + + instance = self._validate(cls, data, sheet_name, row_number, collector) + if instance is not None: + instances.append(instance) + return instances + + def _read_exchange_rates(self, wb, model: FinancialModel, collector: _IssueCollector) -> None: + rates = [] + for row_number, data in self._sheet_rows(wb, "ExchangeRates", collector): + instance = self._validate(ExchangeRate, data, "ExchangeRates", row_number, collector) + if instance is not None: + rates.append(instance) + + if rates: + model.exchange_rates = rates + elif "ExchangeRates" not in wb.sheetnames: + collector.warn("ExchangeRates: лист отсутствует — используются курсы по умолчанию") + else: + collector.warn("ExchangeRates: нет строк с курсами — используются курсы по умолчанию") + + def _resolve_account( + self, + reference: str, + index: _AccountIndex, + sheet_name: str, + row_number: int, + field_name: str, + collector: _IssueCollector, + ) -> str | None: + text = str(reference).strip() + key = _name_key(text) + if key in index.by_name: + return index.by_name[key] try: - instance = cls.model_validate(data) - except Exception as e: - raise ExcelRepositoryError(f"Failed to parse row in {sheet_name}: {e}") from e - if sheet_name == "Accounts": - model.accounts.append(instance) - elif sheet_name == "Transactions": - model.transactions.append(instance) - elif sheet_name == "Recurring": - model.recurring.append(instance) - elif sheet_name == "Assets": - model.assets.append(instance) - elif sheet_name == "Liabilities": - model.liabilities.append(instance) - elif sheet_name == "ExchangeRates": - model.exchange_rates.append(instance) + uuid = UUID(text) + except ValueError: + uuid = None + if uuid is not None and str(uuid) in index.by_id: + return str(uuid) + collector.error( + sheet_name, + row_number, + field_name, + f"неизвестный счёт '{text}'; известные счета: {index.describe()}", + ) + return None + + def _sheet_rows(self, wb, sheet_name: str, collector: _IssueCollector): + """Отдать (номер_строки, данные) для листа; ошибки конверсии — в collector.""" + if sheet_name not in wb.sheetnames: + return [] + ws = wb[sheet_name] + header = next(ws.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(header, sheet_name, collector) + if not columns: + collector.warn(f"{sheet_name}: не найдено ни одного известного столбца — лист пропущен") + return [] + + rows = [] + for offset, raw_row in enumerate(ws.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 field_name, column_index in columns.items(): + value = raw_row[column_index] if column_index < len(raw_row) else None + if _is_empty(value): + continue + converted, error = _convert_value(FIELD_KINDS[sheet_name][field_name], value) + if error is not None: + collector.error(sheet_name, row_number, field_name, error) + row_ok = False + continue + if converted is not None: + data[field_name] = converted + if row_ok: + rows.append((row_number, data)) + return rows + + def _map_columns( + self, header: tuple, sheet_name: str, collector: _IssueCollector + ) -> dict[str, int]: + lookup: dict[str, str] = {} + for canonical, aliases in _ALIASES[sheet_name].items(): + for alias in aliases: + lookup[_norm_header(alias)] = canonical + columns: dict[str, int] = {} + for column_index, raw in enumerate(header): + key = _norm_header(raw) + if not key: + continue + canonical = lookup.get(key) + if canonical is None: + collector.warn( + f"{sheet_name}: неизвестный столбец '{str(raw).strip()}' — пропущен" + ) + continue + if canonical in columns: + collector.warn( + f"{sheet_name}: столбец '{canonical}' задан дважды — используется первый" + ) + continue + columns[canonical] = column_index + return columns + + def _validate(self, cls, data: dict, sheet_name: str, row_number: int, collector: _IssueCollector): + try: + return 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(sheet_name, row_number, field_name, message) + except (TypeError, ValueError) as exc: + collector.error(sheet_name, row_number, "", str(exc)) + return None + + # -- формулы ------------------------------------------------------------ + + def _check_formulas(self, wb_data, path: Path, collector: _IssueCollector) -> None: + wb_formulas = load_workbook(path, data_only=False) + try: + for ws in wb_formulas.worksheets: + cached_ws = wb_data[ws.title] if ws.title in wb_data.sheetnames else None + for row in ws.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_ws[cell.coordinate].value if cached_ws is not None else None + if cached is None: + collector.warn( + f"{ws.title}!{cell.row}: формула без сохранённого значения — " + "пересчитайте и сохраните файл в Excel" + ) + finally: + wb_formulas.close() + + # -- запись ------------------------------------------------------------- + + def _row_values(self, sheet_name: str, item, name_by_id: dict[str, str]) -> list: + values = [] + for field_name in CANONICAL_COLUMNS[sheet_name]: + raw = getattr(item, field_name, None) + values.append(self._cell_value(sheet_name, field_name, raw, name_by_id)) + return values + + def _cell_value(self, sheet_name: str, field_name: str, raw, name_by_id: dict[str, str]): + kind = FIELD_KINDS[sheet_name][field_name] + if kind in {"account", "account_optional"}: + text = "" if raw is None else str(raw).strip() + if not text: + return None + # В Excel пишем имя счёта; неизвестную ссылку оставляем как есть. + return name_by_id.get(text, text) + if kind == "id": + return str(raw) + if kind == "date": + if _is_empty(raw): + return None + try: + return date.fromisoformat(_parse_date(raw)) + except ValueError: + return str(raw) + if kind == "decimal": + return float(raw) + if _is_empty(raw): + return None + return str(raw) if not isinstance(raw, str) else raw + + def _write_sheet(self, wb: Workbook, sheet_name: str, headers: list[str], rows: list[list]) -> None: + ws = wb.create_sheet(title=sheet_name) + ws.append(headers) + for cell in ws[1]: + cell.font = Font(bold=True) + for row in rows: + ws.append(row) + + for column_index, field_name in enumerate(headers, start=1): + letter = get_column_letter(column_index) + ws.column_dimensions[letter].width = COLUMN_WIDTHS.get(field_name, 18) + number_format = CELL_NUMBER_FORMATS.get((sheet_name, field_name)) + if number_format: + for row_number in range(2, len(rows) + 2): + ws.cell(row=row_number, column=column_index).number_format = number_format + + ws.freeze_panes = "A2" + last_row = max(len(rows) + 1, 1) + ws.auto_filter.ref = f"A1:{get_column_letter(len(headers))}{last_row}" + + +__all__ = [ + "CANONICAL_COLUMNS", + "CELL_NUMBER_FORMATS", + "COLUMN_WIDTHS", + "ExcelImportResult", + "ExcelRepository", + "ExcelRepositoryError", + "ExcelRowError", + "FIELD_KINDS", + "SHEET_ORDER", +] diff --git a/infrastructure/repositories/excel_template.py b/infrastructure/repositories/excel_template.py new file mode 100644 index 0000000..8b71e35 --- /dev/null +++ b/infrastructure/repositories/excel_template.py @@ -0,0 +1,222 @@ +"""Генератор пустого Excel-шаблона для ручного заполнения модели. + +``write_template(path)`` создаёт .xlsx только с заголовками листов, форматами +чисел и выпадающими списками, плюс лист «Инструкция» на русском. Шаблон +импортируется без ошибок и даёт пустую ``FinancialModel``. +""" +from __future__ import annotations + +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.currency import CURRENCY_DECIMALS +from infrastructure.repositories.excel_repository import ( + CANONICAL_COLUMNS, + CELL_NUMBER_FORMATS, + COLUMN_WIDTHS, + FIELD_KINDS, + ExcelRepositoryError, +) + +_TEMPLATE_ROWS = 500 +_VALIDATION_ROWS = 1000 +_ACCOUNT_RANGE = "=Accounts!$B$2:$B$500" +_INSTRUCTION_SHEET = "Инструкция" + +_FREQUENCIES_EN = ("daily", "weekly", "monthly", "yearly") +_FREQUENCIES_RU = ("ежедневно", "еженедельно", "ежемесячно", "ежегодно") + +# Подсказка по типу значения: (обязательно, формат / допустимые значения). +_KIND_HELP: dict[str, tuple[str, str]] = { + "id": ("нет", "UUID или пусто — id создаётся автоматически"), + "text": ("—", "текст"), + "currency": ("—", "код валюты: " + ", ".join(CURRENCY_DECIMALS)), + "decimal": ("—", "число, напр. 1 234,56"), + "date": ("—", "2026-01-31, 31.01.2026, 31/01/2026, 2026/01/31, 31-01-2026"), + "frequency": ( + "—", + "daily / weekly / monthly / yearly " + "(ежедневно / еженедельно / ежемесячно / ежегодно)", + ), + "account": ("да", "имя счёта из листа Accounts"), + "account_optional": ("нет", "имя счёта из Accounts; пусто = все счета"), +} + +_REQUIRED: dict[tuple[str, str], bool] = { + ("Accounts", "name"): True, + ("Transactions", "date"): True, + ("Transactions", "account"): True, + ("Transactions", "amount"): True, + ("Recurring", "start_date"): True, + ("Recurring", "frequency"): True, + ("Recurring", "amount"): True, + ("Assets", "name"): True, + ("Liabilities", "name"): True, + ("ExchangeRates", "from_currency"): True, + ("ExchangeRates", "to_currency"): True, + ("ExchangeRates", "rate"): True, +} + + +def _column_index(sheet_name: str, field_name: str) -> int: + return CANONICAL_COLUMNS[sheet_name].index(field_name) + 1 + + +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 _write_columns_sheet(wb: Workbook, sheet_name: str) -> None: + headers = list(CANONICAL_COLUMNS[sheet_name]) + ws = wb.create_sheet(title=sheet_name) + ws.append(headers) + for cell in ws[1]: + cell.font = Font(bold=True) + + for column_index, field_name in enumerate(headers, start=1): + letter = get_column_letter(column_index) + ws.column_dimensions[letter].width = COLUMN_WIDTHS.get(field_name, 18) + number_format = CELL_NUMBER_FORMATS.get((sheet_name, field_name)) + if number_format: + for row_number in range(2, _TEMPLATE_ROWS + 1): + ws.cell(row=row_number, column=column_index).number_format = number_format + + ws.freeze_panes = "A2" + ws.auto_filter.ref = f"A1:{get_column_letter(len(headers))}{_TEMPLATE_ROWS}" + + +def _add_validations(wb: Workbook) -> None: + currency = _list_validation(tuple(CURRENCY_DECIMALS), prompt="Код валюты, напр. RUB") + accounts_ws = wb["Accounts"] + account_currency_col = get_column_letter(_column_index("Accounts", "currency")) + accounts_ws.add_data_validation(currency) + currency.add(f"{account_currency_col}2:{account_currency_col}{_VALIDATION_ROWS}") + + transactions = wb["Transactions"] + tx_account_col = get_column_letter(_column_index("Transactions", "account")) + tx_account_validation = _account_validation() + transactions.add_data_validation(tx_account_validation) + tx_account_validation.add(f"{tx_account_col}2:{tx_account_col}{_VALIDATION_ROWS}") + + recurring = wb["Recurring"] + rec_account_col = get_column_letter(_column_index("Recurring", "account")) + rec_frequency_col = get_column_letter(_column_index("Recurring", "frequency")) + rec_account_validation = _account_validation() + recurring.add_data_validation(rec_account_validation) + rec_account_validation.add(f"{rec_account_col}2:{rec_account_col}{_VALIDATION_ROWS}") + + frequency = _list_validation( + _FREQUENCIES_EN + _FREQUENCIES_RU, + prompt="daily / weekly / monthly / yearly или ежедневно / еженедельно / ежемесячно / ежегодно", + ) + recurring.add_data_validation(frequency) + frequency.add(f"{rec_frequency_col}2:{rec_frequency_col}{_VALIDATION_ROWS}") + + +def _instruction_rows() -> 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") + line("") + + line("Правила заполнения") + line("• id можно оставить пустым — идентификатор создаётся автоматически.") + line("• счёт указывается по имени из листа Accounts (регистр и лишние пробелы не важны).") + line("• пустой счёт в Recurring = платёж относится ко всем счетам.") + line("• сумма со знаком: положительная = доход, отрицательная = расход.") + line("• даты: 2026-01-31, 31.01.2026, 31/01/2026, 2026/01/31, 31-01-2026 (время отбрасывается).") + line("• числа: 1 234,56 или 1234.56; символы валют и пробелы игнорируются; (100) = -100.") + line("• валюта: " + ", ".join(CURRENCY_DECIMALS) + ".") + line( + "• периодичность: " + ", ".join(_FREQUENCIES_EN) + " (можно по-русски: " + + ", ".join(_FREQUENCIES_RU) + ")." + ) + line("") + + rows.append(("Лист", "Столбец", "Обязательно", "Формат / допустимые значения")) + for sheet_name, fields in FIELD_KINDS.items(): + for field_name, kind in fields.items(): + required = "да" if _REQUIRED.get((sheet_name, field_name)) else _KIND_HELP[kind][0] + rows.append((sheet_name, field_name, required, _KIND_HELP[kind][1])) + return rows + + +def _write_instruction_sheet(wb: Workbook) -> None: + ws = wb.create_sheet(title=_INSTRUCTION_SHEET) + ws.column_dimensions["A"].width = 74 + ws.column_dimensions["B"].width = 22 + ws.column_dimensions["C"].width = 14 + ws.column_dimensions["D"].width = 64 + + title = ws.cell(row=1, column=1, value="Инструкция: заполнение Excel-шаблона") + title.font = Font(bold=True, size=14) + + for offset, values in enumerate(_instruction_rows(), 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_template(path: str | Path, *, force: bool = False) -> Path: + """Создать пустой шаблон .xlsx. Существующий файл — ошибка, если не ``force``.""" + target = Path(path) + if target.exists() and not force: + raise ExcelRepositoryError( + f"Файл уже существует: {target} — используйте force=True, чтобы перезаписать" + ) + target.parent.mkdir(parents=True, exist_ok=True) + + wb = Workbook() + wb.remove(wb.active) + + wb.create_sheet(title="ModelInfo") + info_ws = wb["ModelInfo"] + info_ws.append(["Property", "Value"]) + for cell in info_ws[1]: + cell.font = Font(bold=True) + info_ws.column_dimensions["A"].width = COLUMN_WIDTHS["Property"] + info_ws.column_dimensions["B"].width = COLUMN_WIDTHS["Value"] + info_ws.freeze_panes = "A2" + + for sheet_name in CANONICAL_COLUMNS: + _write_columns_sheet(wb, sheet_name) + + _add_validations(wb) + _write_instruction_sheet(wb) + + wb.save(target) + return target + + +__all__ = ["write_template"] diff --git a/tests/conftest.py b/tests/conftest.py index 4226bbb..3e462bd 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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() diff --git a/tests/test_cli.py b/tests/test_cli.py index beec93a..73a3284 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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() diff --git a/tests/test_excel_sync.py b/tests/test_excel_sync.py index 1a9013b..1560f0d 100644 --- a/tests/test_excel_sync.py +++ b/tests/test_excel_sync.py @@ -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) + diff --git a/tests/test_excel_template.py b/tests/test_excel_template.py new file mode 100644 index 0000000..408e016 --- /dev/null +++ b/tests/test_excel_template.py @@ -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() diff --git a/tests/test_forecast.py b/tests/test_forecast.py index 0a50bae..9d9a252 100644 --- a/tests/test_forecast.py +++ b/tests/test_forecast.py @@ -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) diff --git a/tests/test_model.py b/tests/test_model.py index 98995ea..587d41b 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -13,7 +13,6 @@ from domain import ( ) from infrastructure.repositories import JsonFileRepository - _repo = JsonFileRepository() diff --git a/tests/test_repositories.py b/tests/test_repositories.py index fc3f77b..a554158 100644 --- a/tests/test_repositories.py +++ b/tests/test_repositories.py @@ -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