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 0000000..2d781b4 Binary files /dev/null and b/data/model_template.xlsx differ 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