Merge branch 'agent/tier1-debt' into dev via director

This commit is contained in:
oqyude committed 2026-10-25 16:26:44 +03:00
commit 0307533cef
51 files changed
+2158 -536

No files matched your search

+4 -2
View File
@@ -10,7 +10,8 @@
{ "id": "T4", "title": "Repository pattern — ModelRepository", "archived_at": "2026-10-08T17:05:00Z", "request": "req-T4" },
{ "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": "T7", "title": "Финальная валидация", "archived_at": "2026-10-08T17:05:00Z", "request": "req-T7", "commit": "3ef1061" },
{ "id": "T8", "title": "ISO 4217-aware форматирование денег (per-currency decimals)", "archived_at": "2026-10-25T12:00:00Z", "request": "req-T8", "commit": "d58547e" }
],
"requests": [
{ "id": "req-T1", "task_id": "T1", "status": "approved", "archived_at": "2026-10-08T17:05:00Z" },
@@ -19,7 +20,8 @@
{ "id": "req-T4", "task_id": "T4", "status": "approved", "archived_at": "2026-10-08T17:05:00Z" },
{ "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-T7", "task_id": "T7", "status": "approved", "archived_at": "2026-10-08T17:05:00Z" },
{ "id": "req-T8", "task_id": "T8", "status": "approved", "archived_at": "2026-10-25T12:00:00Z" }
],
"checkpoints": []
}
+10
View File
@@ -0,0 +1,10 @@
{
"id": "T8",
"title": "ISO 4217-aware форматирование денег (per-currency decimals)",
"status": "archived",
"origin": "user:direct",
"request": "req-T8",
"commit": "d58547e",
"summary": "Введены CURRENCY_DECIMALS (ISO 4217: JPY=0, BHD/KWD/OMR=3, остальные=2) и единая точка форматирования CurrencyConverter.format_money() с округлением ROUND_HALF_UP. Все 14 литералов :,.2f в infrastructure/cli/ заменены на format_money(); i18n-шаблоны cmd.config.transaction_add.ok и cmd.config.recurring_add.ok переработаны (передается уже отформатированная сумма). Добавлены тесты по JPY, BHD, USD, неизвестному коду и отрицательным суммам. Спецификация: .agent/archive/requests/req-T8.json.",
"archived_at": "2026-10-25T12:00:00Z"
}
+9 -4
View File
@@ -1,8 +1,8 @@
{
"metaagent_version": "3.0.0",
"session_id": "metaagent-005",
"session_id": "metaagent-008",
"target_repo": "/home/oqyude/External/Git/nifodea",
"goal": "Обсуждение архитектуры и серьёзный refactor",
"goal": "Исполнение плана технического долга D1-D30 (Tier 1 целиком, Tier 2 — однозначные пункты)",
"project_type": "existing",
"phases": {
"init": "completed",
@@ -21,7 +21,12 @@
{ "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": "T7", "title": "Финальная валидация", "status": "archived", "origin": "user:direct" },
{ "id": "T8", "title": "ISO 4217-aware форматирование денег (per-currency decimals)", "status": "archived", "origin": "user:direct" },
{ "id": "D1-D13", "title": "Tier 1 техдолга: D1, D6-D13 (13 пунктов, отдельные коммиты)", "status": "archived", "origin": "user:direct" },
{ "id": "D14,D15,D17,D19,D20,D21,D23", "title": "Tier 2 — однозначные пункты, разрешённые владельцем", "status": "archived", "origin": "user:direct" },
{ "id": "D16,D18,D22,D24", "title": "Tier 2 — ждут решения владельца", "status": "pending", "origin": "user:direct" },
{ "id": "D25-D30", "title": "Tier 3 — реструктуризация", "status": "pending", "origin": "user:direct" }
],
"last_updated": "2026-10-08T17:10:00Z"
"last_updated": "2026-10-25T12:00:00Z"
}
+86 -62
View File
@@ -1,11 +1,33 @@
# Project State
**Снимок на момент:** 2026-10-23T00:00 (после аудита техдолга, сессия metaagent-007)
**Снимок на момент:** 2026-10-25T12:00 (после исполнения плана техдолга, сессия metaagent-008)
**Project type:** `existing`
**MetaAgent version:** 3.0.0
---
## Что произошло в сессии 2026-10-25 (metaagent-008)
**Goal:** Исполнить разрешённые владельцем пункты плана D1–D30.
Выполнено:
1. **Tier 1 целиком** (D1, D6–D13) — 10 коммитов, плюс один служебный `style:` (baseline не соответствовал `ruff format --check .`).
2. **Tier 2 — однозначные пункты** (D14, D15, D17, D19, D20, D21, D23) — 7 коммитов.
3. **Синхронизация `.agent/**`** (D23): T8 → archived, статусы D1–D30, сводка сессии metaagent-008.
Осталось в Tier 2: D16, D18, D22, D24 — требуют решения владельца.
### Изменения чисел (утверждено владельцем в батче)
| Гипотеза | Было | Стало |
|---|---|---|
| D14 | прогноз мутирует активы: 1-й вызов — 5358.61, 2-й — 5388.37 | прогноз идемпотентен: оба вызова дают одно и то же |
| D14 | `summary()` после прогноза ≠ «Итог» в таблице (5420.61 ≠ 5358.61) | «Итог» = последняя строка таблицы |
| D15 | `convert()` квантует до 2 знаков: 0.1 USD → JPY = 8.00 | `convert()` без квантования: 0.1 USD → JPY = 8.0 (полная точность) |
| D15 | обратный курс 1/90 = ровно 10.00 | 1/90 — бесконечная дробь: 9.999999999999999999999999999 (на отображении → «€10.00») |
| D17 | `r.rate = -5` принимался, курс сохранялся float (-5.0) | отклоняется валидатором: «Ошибка валидации данных», код возврата 1 |
## Что произошло в сессии 2026-10-23 (metaagent-007)
**Goal:** Снять техдолг и предложить реструктуризацию (read-only аудит), затем исполнить
@@ -26,12 +48,12 @@
| Гипотеза | Результат |
|---|---|
| `SCHEMA_VERSION` — не pydantic-поле (`domain/model.py:19`) | **Опровергнута**: поле есть в `model_fields` и в `model_dump()`; `FinancialModel(SCHEMA_VERSION=99)` принимается |
| `validate_assignment` выключен → `config_cmd.py:55` обходит валидатор курса | **Подтверждена**: `r.rate = 90.5` кладёт `float` в поле `Decimal`; `r.rate = -5` принимается |
| `forecast_cashflow` мутирует активы → повторный вызов даёт другие числа | **Подтверждена**: 1-й вызов — 5358.61, 2-й — 5388.37; `summary()` после прогноза — 5420.61 ≠ 5358.61 |
| `SCHEMA_VERSION` — не pydantic-поле (`domain/model.py:19`) | **Опровергнута**: поле есть в `model_fields` и в `model_dump()`; `FinancialModel(SCHEMA_VERSION=99)` принимается → исправлено (D9) |
| `validate_assignment` выключен → `config_cmd.py` обходит валидатор курса | **Подтверждена**: `r.rate = 90.5` кладёт `float` в поле `Decimal`; `r.rate = -5` принимается → исправлено (D17) |
| `forecast_cashflow` мутирует активы → повторный вызов даёт другие числа | **Подтверждена**: 1-й вызов — 5358.61, 2-й — 5388.37 → исправлено (D14) |
| `summary()['total_balance']` — сумма по счетам | **Опровергнута**: при счетах 1000 и 3000 возвращается `3000.00` (последний счёт) |
| `convert()` теряет точность для JPY (баг из `manifest.md:140`) | **Подтверждена**: 0.1 USD → JPY = 8.00 (ожидается ≈7.86) |
| xlsx round-trip теряет значения | **Опровергнута**: balance/rate/asset value сохраняются точно; теряются только `scenarios` (листа нет в коде) |
| `convert()` теряет точность для JPY (баг из `manifest.md:140`) | **Подтверждена**: 0.1 USD → JPY = 8.00 → исправлено (D15) |
| xlsx round-trip теряет значения | **Опровергнута**: balance/rate/asset value сохраняются точно; теряются только `scenarios` (листа нет в коде) → D18 |
## Архитектура (не менялась)
@@ -41,13 +63,14 @@
│ Account, Transaction, Asset, Liability, │
│ Recurring, Scenario, FinancialModel, │
│ ExchangeRate, CurrencyConverter │
│ (pydantic.BaseModel, Decimal) │
│ (pydantic.BaseModel, Decimal, │
│ validate_assignment=True) │
└──────────────────┬──────────────────────────┘
│
┌──────────────────▼──────────────────────────┐
│ application/ — прикладные сервисы │
│ ForecastService, ScenarioService, │
│ ModelRepository (Protocol) │
│ ForecastService (без мутаций), │
│ ScenarioService, ModelRepository (Protocol)│
└──────────────────┬──────────────────────────┘
│
┌──────────────────▼──────────────────────────┐
@@ -58,99 +81,100 @@
```
Направление импортов чистое: нарушений «снизу вверх» нет. Единственная горизонтальная связь —
`infrastructure/ai/prompts.py:1` → `infrastructure.cli.i18n` (блокирует REST API / Web UI).
`infrastructure/ai/prompts.py:1` → `infrastructure.cli.i18n` (блокирует REST API / Web UI, Tier 3 — D27).
## Tech stack
| Слой | Технология | Версия (декларация) | Фактически в `.venv` |
|---|---|---|---|
| Язык | Python | `>=3.11` (`pyproject.toml:9`) | **3.15.1** |
| CLI | Typer | `>=0.9` | 0.27.1 |
| Язык | Python | `>=3.11` (`pyproject.toml:9`) | 3.14.7 |
| CLI | Typer | `>=0.9` | 0.27.3 |
| Excel | openpyxl | `>=3.1` | 3.1.5 |
| Терминал | rich | `>=13.0` | 15.0.0 |
| Валидация | pydantic | `>=2.0` | **не установлен** |
| Валидация | pydantic | `>=2.0` | 2.14.1 |
| Деньги | Decimal | stdlib | — |
| Тесты | pytest | — (вне `dependencies`) | 9.1.1 |
| Линтер | ruff | — (вне `dependencies`) | 0.16.2 |
| Тесты | pytest | dev-extra (`>=8.0`) | 9.1.1 |
| Линтер | ruff | dev-extra (`==0.17.2`) | 0.17.2 |
⚠ **Окружение `.venv` устарело**: установлен дорефакторинговый дистрибутив
(`entry_points.txt` → `cf = cli.main:app`, `top_level.txt` → `ai, cashflow_model, cli, engine, sync` —
все удалены в `4b9cf7d`), и **нет pydantic**. `import infrastructure.cli.app` падает с
`ModuleNotFoundError`. Проверка в этой сессии выполнялась в отдельном venv вне репозитория.
✅ **Окружение `.venv` починено**: создано с нуля (`python3 -m venv .venv` +
`pip install pydantic typer rich openpyxl pytest ruff`). Прежний `.venv` ставил дорефакторинговый
дистрибутив (entry point на `cli.main:app`, без pydantic) — `import infrastructure.cli.app` падал.
## Ключевые модули
| Слой | Модуль | Ответственность |
|---|---|---|
| domain | `account.py` (18), `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) + `format_money` |
| domain | `model.py` (71) | FinancialModel — корневой агрегатор с `SCHEMA_VERSION=1` |
| application | `forecast.py` (115) | ForecastService — помесячный прогноз |
| 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, регистрирует 9 команд + sub-typer `config` |
| infrastructure | `cli/commands/*.py` | 9 файлов команд + `config_cmd.py` (**19** подкоманд, 430 стр.) |
| infrastructure | `cli/paths.py` (5) | DATA_DIR, MODEL_PATH |
| infrastructure | `cli/services.py` (64) | `build_services()` — composition root + helpers |
| infrastructure | `cli/i18n.py` (350) | 176 ключей **только на ru**; `_e()` не вызывается ни разу |
| 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 (6 листов + ModelInfo) |
| domain | `account.py` (23), `transaction.py` (25), `asset.py` (16), `liability.py` (24), `recurring.py` (32), `scenario.py` (25) | pydantic.BaseModel + Decimal + валидаторы + `validate_assignment=True` |
| domain | `currency.py` (146) | ExchangeRate + CurrencyConverter (Decimal, без квантования) + `format_money` |
| domain | `model.py` (80) | FinancialModel — корневой агрегатор с `SCHEMA_VERSION: ClassVar[int] = 1` |
| application | `forecast.py` (151) | ForecastService — помесячный прогноз, без мутаций модели |
| application | `scenarios.py` (88) | ScenarioService — baseline/optimistic/pessimistic + what-if |
| application | `repositories/model_repository.py` (21) | Protocol с load()/save() |
| infrastructure | `cli/app.py` (46) | Entry point, регистрирует 9 команд + sub-typer `config` |
| infrastructure | `cli/commands/*.py` | 10 файлов команд + `config_cmd.py` (**19** подкоманд, 435 стр.) |
| infrastructure | `cli/paths.py` (9) | DATA_DIR, MODEL_PATH, EXPORTS_DIR |
| infrastructure | `cli/services.py` (83) | `build_services()` — composition root + helpers + `fail_validation()` |
| infrastructure | `cli/i18n.py` (382) | 176 ключей **только на ru**; язык определяется при импорте (D20) |
| infrastructure | `ai/assistant.py` (80) | AssistantService (заглушка, DI ForecastService) |
| infrastructure | `repositories/json_file_repository.py` (21) | .json storage |
| infrastructure | `repositories/excel_repository.py` (160) | .xlsx storage (6 листов + ModelInfo), создаёт родительский каталог |
## Статус тестов
| Параметр | Значение |
|---|---|
| Всего тестов | **75** |
| Пройдено | 75 ✅ (baseline сессии 007) |
| Всего тестов | **191** |
| Пройдено | 191 ✅ (75 были в сессии 007) |
| Упало | 0 |
| Тестовых модулей | 9 |
| Coverage-инструментария | **нет** (ни `pytest-cov`, ни `[tool.coverage]`) |
| Линт | `ruff check .` → **10 ошибок** (9× I001 порядок импортов, 1× E501) |
| Тестовых модулей | 11 (`tests/`, вкл. `__init__.py`) |
| Coverage | настроено: `[tool.coverage.run]` в `pyproject.toml` (D12) |
| Линт | `ruff check .` → чисто; `ruff format --check .` → чисто (D2 + `style:`) |
| CI | `.github/workflows/ci.yml` — pytest + ruff (D13) |
## Что сделано в сессии 007
## Что сделано в сессии 008
_(заполняется по мере исполнения — см. §«Что сделано в сессии 007» в `.agent/handoff-summary.md`)_
- ✅ Аудит техдолга завершён, план D1–D30 зафиксирован в `.agent/tasks/manifest.md`
- ✅ Метасостояние обновлено: `manifest.md`, `project-state.md`, `handoff-summary.md`
- ✅ Аудит техдолга завершён, план D1–D30 зафиксирован в `.agent/tasks/manifest.md` (сессия 007)
- ✅ Tier 1 исполнен полностью: D1–D13 (D2–D5 — сессия 007, D1/D6–D13 — сессия 008)
- ✅ Tier 2 исполнены однозначные пункты: D14, D15, D17, D19, D20, D21, D23
- ✅ Метасостояние синхронизировано: `manifest.md`, `manifest.json`, `archive/`, `checkpoints.json`,
`session-summary.md`, `project-state.md`, `handoff-summary.md`
- ✅ `.venv` пересоздан; dev-extra описан в `pyproject.toml`
## Что заблокировано и почему
| ID | Суть | Причина блокировки |
|---|---|---|
| D14–D16 | Правки расчёта (мутации, округление, классификация recurring) | **меняют числа на выходе** — нужно утверждение владельца |
| D17 | `validate_assignment=True` | **меняет поведение CLI** (отрицательный курс начнёт отклоняться) |
| D18 | Лист `Scenarios` в Excel | **меняет формат файла состояния** |
| D19 | `export-xlsx` в несуществующий каталог | **меняет поведение CLI** (traceback → понятная ошибка) |
| D20, D21 | Работающий `CF_LANG`, исправление пользовательской строки | **меняют вывод CLI** |
| D16 | Единая классификация recurring (знак vs категория) + учёт `frequency`/`start_date`/`end_date` | меняет числа прогноза — нужно принятое владельцем правило |
| D18 | Лист `Scenarios` в Excel | меняет формат файла состояния |
| D22 | Убрать `data/model.json` / `data/excel.xlsx` из git | «данные моделей» трогать запрещено |
| D23 | Синхронизация прочих `.agent/`-файлов | разрешено править только 3 файла из `.agent/` |
| D24 | `ScenarioError` / `AssistantError` | публичные имена в `__all__` — решение владельца |
| D24 | Публичные `ScenarioError` / `AssistantError` | публичные имена — решение владельца |
| D25–D30 | Tier 3 — реструктуризация | после стабилизации Tier 1/Tier 2 |
## Что отсутствует / TODO
- ❌ **AI-интеграция** — `AssistantService` не вызывает LLM API (отклонено пользователем)
- ❌ **CI/CD** — нет `.github/` (в работе: D13)
- ❌ **mypy** — не настроен
- ❌ **Логирование** — только `rich.print`
- ❌ **dev-зависимости** — pytest/ruff не объявлены в `pyproject.toml` (в работе: D12)
- ⚠ **LICENSE** — MIT присутствует и корректен; README утверждал обратное (исправлено: D8)
- ✅ **CI** — `.github/workflows/ci.yml` (D13)
- ✅ **dev-зависимости** — `pytest`, `ruff`, `coverage` в `pyproject.toml` (D12)
- ⚠ **LICENSE** — MIT присутствует и корректен; README исправлен (D8)
- ⚠ **`data/` в git** — решение владельца (D22); `.gitignore` уже игнорирует `/data/` и `/exports/`
## Известные ADR-кандидаты (для следующей сессии)
## Известные ADR-кандидаты
| ID | Тема |
|---|---|
| ADR-001 | Repository pattern — формализировать контракт `ModelRepository` |
| ADR-002 | Слоистая архитектура — границы domain/application/infrastructure |
| ADR-003 | Schema versioning — политика миграций модели + `SCHEMA_VERSION` как `ClassVar` |
| ADR-004 | Политика округления денег: где квантовать (конверсия vs отображение) — конфликт D15 |
| ADR-003 | Schema versioning — политика миграций модели + `SCHEMA_VERSION` как `ClassVar` (решено — D9) |
| ADR-004 | Политика округления денег: где квантовать (конверсия vs отображение) — решено (D15) |
## Следующая сессия — что делать
1. **Согласовать Tier 2** (D14–D21) — это правки, меняющие числа и поведение CLI.
До согласования D1–D13 (Tier 1) — готовая страховка: D11 кладёт числовые тесты-характеристики.
2. **Обновить `.venv`** — `pip install -e ".[dev]"` (после D12 добавит dev-extra).
3. **Выбрать судьбу `data/`** (D22) — где живут реальные данные пользователя.
4. **Решить по `.agent/`** (D30) — 60 из 127 файлов в продуктовом репозитории.
5. **Tier 3** (D25–D29) — после стабилизации Tier 1 и с инвариантом поверхности CLI.
1. **Решить по D16** — единая классификация recurring: по знаку (как сейчас) или по категории,
и учёт `frequency`/`start_date`/`end_date`.
2. **Решить по D18** — лист `Scenarios` в `.xlsx` (сейчас модель молча теряется при round-trip).
3. **Решить по D22** — судьба данных модели (`data/` в git vs вне репозитория).
4. **Решить по D24** — убрать ли оставить `ScenarioError`/`AssistantError`.
5. **Tier 3** (D25–D29) — с инвариантом поверхности CLI.
6. **Решить по `.agent/`** (D30) — 60 из 126 файлов в продуктовом репозитории.
+68 -47
View File
@@ -1,8 +1,8 @@
# Handoff Summary
**Session:** `metaagent-007`
**Goal:** Технический долг: аудит → план → исполнение безопасной части
**Date:** 2026-10-23
**Session:** `metaagent-008`
**Goal:** Технический долг: исполнить Tier 1 целиком и однозначные пункты Tier 2
**Date:** 2026-10-25
**MetaAgent version:** 3.0.0
---
@@ -11,17 +11,18 @@
| Метрика | Значение |
|---|---|
| Задач выявлено | 30 (D1–D30) |
| Tier 1 — выполнено | см. «Что сделано» ниже |
| Tier 2 — blocked | 11 (требуют согласования владельца) |
| Задач в плане | 30 (D1–D30) |
| Tier 1 — выполнено | 13/13 (D2–D5 — сессия 007, D1/D6–D13 — сессия 008) |
| Tier 2 — выполнено | 7/11 (D14, D15, D17, D19, D20, D21, D23) |
| Tier 2 — ждёт владельца | 4 (D16, D18, D22, D24) |
| Tier 3 — реструктуризация | 6 (позже) |
| Baseline тестов | 75/75 ✅ |
| Baseline линта | `ruff check .` → 10 ошибок (до D2) |
| Ветка | `dev` (пуш не выполнялся) |
| Baseline тестов | 75/75 ✅ → сейчас **191/191** ✅ |
| Baseline линта | `ruff check .` → 10 ошибок → сейчас чисто; `ruff format --check .` → 24 файла → сейчас чисто |
| Ветка | `agent/tier1-debt` (база `dev`), запушена в origin |
## Что было сделано
### 1. Аудит (read-only)
### 1. Аудит (read-only, сессия 007)
Полностью прочитаны 47 `.py`, оба README, `AGENTS.md`, `pyproject.toml`, `.gitignore`,
`LICENSE`, все мета-файлы `.agent/`, 10 файлов `tests/`. Проверены `git ls-files`, `git log`,
@@ -37,52 +38,71 @@
### 2. Эмпирическая проверка гипотез
Отдельное venv **вне репозитория** (`.venv` не трогали), `PYTHONDONTWRITEBYTECODE=1`,
pytest запускался из временного CWD — репозиторий не загрязнялся.
Подтверждено: `SCHEMA_VERSION` **является** pydantic-полем; `validate_assignment` выключен →
`config_cmd.py` обходит валидатор курса и пишет `float` в поле `Decimal`;
`forecast_cashflow` мутирует активы (2-й вызов: 5388.37 против 5358.61);
`summary()['total_balance']` — баланс последнего счёта, а не сумма; 0.1 USD → JPY = 8.00;
`ExcelRepository.save` падал с `FileNotFoundError` при отсутствии родительского каталога.
Подтверждено: `SCHEMA_VERSION` **является** pydantic-полем (комментарий `domain/model.py:19` неверен);
`validate_assignment` выключен → `config_cmd.py:55` обходит валидатор курса и пишет `float`
в поле `Decimal`; `forecast_cashflow` мутирует активы (2-й вызов: 5388.37 против 5358.61);
`summary()['total_balance']` — баланс последнего счёта, а не сумма (1000 + 3000 → 3000.00);
0.1 USD → JPY = 8.00 вместо ≈7.86 (баг из `manifest.md:140`); `ExcelRepository.save` падает с
`FileNotFoundError` при отсутствии родительского каталога.
Опровергнуто: xlsx round-trip **сохраняет** значения (balance, rate, asset value) — потеряется
только `scenarios` (листа нет в коде).
Опровергнуто: xlsx round-trip **сохраняет** значения — теряется только `scenarios`.
### 3. План
30 пунктов в `.agent/tasks/manifest.md` с ID, сутью, путём:строкой, типом, риском, пользой
и признаком «сразу / нужна страховка».
## Что сделано в сессии 007
## Что сделано в сессии 008
_(обновляется по мере исполнения)_
### Tier 1 — 13/13
| ID | Суть | Коммит |
|---|---|---|
| D1 | `.gitignore`: правила для `/data/`, `/exports/`, без шапки toptal | `9b53b25` |
| D2–D5 | lint-гейт, мёртвые `typer.Typer()`, `i18n._e()`, второй `Console()` | сессия 007 |
| D6 | константа `EXPORTS_DIR` | `2691bcd` |
| D7 | дрейф в комментариях и docstring | `339a751` |
| D8 | дрейф в документации (README, README.arch) | `11772f3` |
| D9 | `SCHEMA_VERSION` как `ClassVar[int]` + регрессионные тесты | `b15533f` |
| D10 | изоляция ФС в тестах (`tmp_path` + `monkeypatch.chdir`) | `bf76472` |
| D11 | тесты-характеристики (71 тест) | `2f02a5d` |
| D12 | `pyproject.toml`: dev-extra, pytest, coverage | `9562adb` |
| D13 | CI: pytest + ruff | `60ac925` |
| — | `style:` — приведение к `ruff format` (baseline был не чистым) | `af01efc` |
### Tier 2 — 7/11 (однозначные пункты, разрешённые владельцем)
| ID | Суть | Коммит |
|---|---|---|
| D14 | мутации убраны из расчёта; `summary()` — из того же набора результатов | `b4aa0c3` |
| D15 | `convert()` без квантования; округление только при отображении | `43ab568` |
| D17 | `validate_assignment=True`; курс пишется `Decimal`; понятная ошибка без traceback | `c702818` |
| D19 | `export-xlsx` создаёт отсутствующий каталог | `e992dde` |
| D20 | `CF_LANG` определяется до первого вызова `t()`; откат на `ru` | `f5db8c6` |
| D21 | исправлен битый путь в пользовательской строке | `f5d04c5` |
| D23 | синхронизация `.agent/**` (T8 → archived) | этот коммит |
## Что заблокировано
11 пунктов (D14–D24) — все меняют числа, вывод CLI или формат файла состояния.
Разрешение владельца обязательно до правки. Подробности и точные места — в
`.agent/context/project-state.md` → «Что заблокировано и почему».
4 пункта (D16, D18, D22, D24) — требуют решения владельца. Подробности и точные места —
в `.agent/context/project-state.md` → «Что заблокировано и почему».
## Требует решения владельца
| Вопрос | ID |
|---|---|
| Утвердить новые числа прогноза (убрать мутации, единое округление, единая классификация recurring)? | D14–D16 |
| Разрешить `validate_assignment=True` (CLI начнёт отклонять отрицательный курс)? | D17 |
| Единое правило классификации recurring (знак или категория) и учёт `frequency`/`start_date`/`end_date`? | D16 |
| Добавлять лист `Scenarios` в .xlsx (меняет формат файла состояния)? | D18 |
| Менять поведение `cf export-xlsx` при отсутствии каталога? | D19 |
| Доводить ли `CF_LANG` и пользовательские строки до рабочего состояния? | D20, D21 |
| Где живут реальные данные пользователя — `data/` в git или вне? | D22 |
| Удалять ли публичные `ScenarioError` / `AssistantError`? | D24 |
| Выносить ли `.agent/` (60 файлов, 47 % репозитория) из продуктового репо? | D30 |
| Выносить ли `.agent/` (60 файлов) из продуктового репо? | D30 |
## Key Artifacts
- **Состояние проекта:** `.agent/context/project-state.md`
- **Задачи и план:** `.agent/tasks/manifest.md` (раздел «Сессия metaagent-007»)
- **Манифест JSON:** `.agent/tasks/manifest.json` — ⚠ T8 всё ещё `pending` (см. D23)
- **Задачи и план:** `.agent/tasks/manifest.md` (раздел «Сессия metaagent-008»)
- **Манифест JSON:** `.agent/tasks/manifest.json` (T8 archived; `debt_tasks` — статусы D1–D30)
- **Сводка сессии:** `.agent/session-summary.md`
- **Архив задач:** `.agent/archive/tasks/`, `.agent/archive/index.json`
## Ключевые точки входа в код
@@ -90,6 +110,7 @@ _(обновляется по мере исполнения)_
|---|---|
| CLI entry | `infrastructure/cli/app.py` |
| Composition root | `infrastructure/cli/services.py:31` (`build_services`) |
| Обработка ошибок валидации | `infrastructure/cli/services.py` (`fail_validation`) |
| Корневая модель | `domain/model.py:12` (`FinancialModel`) |
| Прогноз | `application/forecast.py:17` (`ForecastService`) |
| Сценарии | `application/scenarios.py:37` (`ScenarioService`) |
@@ -100,30 +121,30 @@ _(обновляется по мере исполнения)_
## Полезные команды
```bash
# Окружение (уже создано в этой сессии)
python3 -m venv .venv
.venv/bin/python -m pip install -e ".[dev]"
# Тесты (из корня репозитория)
pytest
.venv/bin/python -m pytest -q
# Линт
ruff check .
ruff format --check .
.venv/bin/ruff check .
.venv/bin/ruff format --check .
# CLI
cf init
cf forecast --months 12
cf scenario baseline
cf compare --months 12
cf info
cf config account-add --name "Main" --balance 5000
.venv/bin/python -m infrastructure.cli.app init
.venv/bin/python -m infrastructure.cli.app forecast --months 12
.venv/bin/python -m infrastructure.cli.app scenario baseline
.venv/bin/python -m infrastructure.cli.app compare --months 12
.venv/bin/python -m infrastructure.cli.app info
# Git
git log --oneline -10
git status
```
⚠ Перед работой: `.venv` не соответствует `pyproject.toml` (нет pydantic, entry point указывает
на удалённый `cli.main`). Нужен `pip install -e ".[dev]"` — **выполняет владелец**,
`.venv` в этой сессии не трогали.
## Git
Ветка `dev`. Коммиты по плану — отдельные, независимо откатываемые. **Пуш не выполнялся.**
Ветка `agent/tier1-debt` (база `dev`). Коммиты по плану — отдельные, независимо откатываемые.
Пуш выполнен в `origin/agent/tier1-debt`. **`dev` не изменялся.**
+37 -36
View File
@@ -1,57 +1,58 @@
# Session Summary
**Session:** `metaagent-005`
**Session:** `metaagent-008`
**MetaAgent version:** 3.0.0
**Date:** 2026-10-08
**Goal:** Обсуждение архитектуры и серьёзный refactor
**Date:** 2026-10-25
**Goal:** Снятие технического долга: Tier 1 целиком + однозначные пункты Tier 2
## Phases Executed
- [x] INIT
- [x] ANALYSE
- [x] ROADMAP
- [x] INIT (состояние уже было подготовлено в сессии 007)
- [x] ANALYSE (аудит и план D1–D30 — сессия 007)
- [x] ROADMAP (план техдолга в `.agent/tasks/manifest.md`)
- [ ] DESIGN (skipped — existing project)
- [x] DECOMPOSITION
- [x] EXECUTION (7 tasks)
- [x] DECOMPOSITION (пункты разложены по батчам и по пунктам)
- [x] EXECUTION (16 commits — см. ниже)
- [x] METASTATE
- [x] HANDOFF
## Results
- **Tasks completed:** 7/7 (T1–T7, все archived)
- **Requests approved:** 7 (req-T1 … req-T7, в `.agent/archive/requests/`)
- **Commits:** 6 production commits + 1 README
- `feb77ef` T1: restructure to domain/application/infrastructure + version=1
- `c765f36` T2: Pydantic v2
- `363d440` T3: Decimal
- `<T4>` T4: Repository pattern
- `541a768` T5: DI
- `<T6>` T6: CLI decompose
- `3ef1061` T7: Final validation + README
- **Tests:** 67/67 ✅ (было 63, +5 для репозиториев)
- **CLI:** все команды работают, Excel round-trip OK
- **Пункты выполнены:** 13/13 Tier 1 (D1, D6–D13) + 7 пунктов Tier 2 (D14, D15, D17, D19, D20, D21, D23).
Раньше остался в Tier 2: D16, D18, D22, D24.
- **Коммиты:** 17, по одному на пункт (включая один `style:` — приведение кода к руфтормату)
- `9b53b25` D1, `af01efc` style, `2691bcd` D6, `339a751` D7, `b15533f` D9, `bf76472` D10,
`9562adb` D12, `60ac925` D13, `2f02a5d` D11, `11772f3` D8 — Tier 1
- `b4aa0c3` D14, `43ab568` D15, `c702818` D17, `e992dde` D19, `f5db8c6` D20, `f5d04c5` D21 — Tier 2
- **Тесты:** 75 → **191/191** ✅ (`pytest -q`); добавлено 116 тестов — тесты-характеристики (D11) и регрессии на поведение.
- **Линт:** `ruff check .` — чисто; `ruff format --check .` — чисто (в baseline был дирм: 24 файла расходились с форматом).
- **CLI:** проверено вручную: `cf init`, `forecast`, `scenario`, `compare`, `info`, `analyze`, `whatif`,
`export-xlsx` (в несуществующем каталоге), `config rate-set` (отрицательный курс — понятная ошибка, без traceback).
Вывод CLI сверен с базовым коммитом: `diff` на выводе без изменений.
## Архитектурный рефактор (5 направлений)
## Изменения чисел (владелец утвердил)
| ID | Что | Задача |
| ID | Было | Стало |
|---|---|---|
| A1+A10 | Слои + version | T1 |
| A2+A3 | Pydantic v2 | T2 |
| A4 | Decimal для денег | T3 |
| A7+A8+A9 | DI + Repository | T4, T5 |
| A5 | Декомпозиция CLI | T6 |
| D14 | Мутации из расчёта — прогноз идемпотентен, «Итог» = последняя строка | `b4aa0c3` |
| D15 | Одно правило округления — `convert()` без квантования | `43ab568` |
| D17 | `validate_assignment=True`, курс пишется Decimal | `c702818` |
| D19 | `export-xlsx` создаёт каталог | `e992dde` |
| D20 | `CF_LANG` определяется до первого `t()` | `f5db8c6` |
| D21 | Исправлен битый путь в пользовательской строке | `f5d04c5` |
| D23 | Синхронизация `.agent/**` (T8 → archived) | `D23` |
## Files Changed
- `domain/` (new, 8 файлов)
- `application/` (new, 3 файла + `repositories/model_repository.py`)
- `infrastructure/` (new: `cli/{app,paths,services,i18n}.py`, `cli/commands/{10 файлов}`, `ai/`, `repositories/{json,excel}_repository.py`)
- Удалены: `cashflow_model/`, `engine/`, `cli/`, `sync/`, `ai/` (старые имена)
- `tests/` (обновлены + `test_repositories.py` new)
- `pyproject.toml` (pydantic dep, новые entry-points, packages.find)
- `README.md` (полная перезапись под новую архитектуру)
- `application/forecast.py` — локальное состояние вместо вместо мутации (Д14), `summary(months, results=...)` (Д14)
- `domain/*.py` — `model_config = ConfigDict(validate_assignment=True)` (Д17); `convert()` без квантования (Д15)
- `infrastructure/cli/` — `EXPORTS_DIR` (Д6), `fail_validation()` (Д17), обработка резервации в `config_cmd.py` (Д17), измения `i18n.py` (Д20, Д21)
- `infrastructure/repositories/excel_repository.py` — создание родительского каталога (Д19)
- `tests/` — характеристики (Д11) и регрессии по Д14–Д21
- `.github/workflows/ci.yml`, `pyproject.toml`, `.gitignore` — CI, dev-экстра, игнор (Д12, Д13, Д1)
- `.agent/**` — синхронизация (Д23)
## Next
Следующий агент: читай `.agent/handoff-summary.md`.
Кандидаты: ADR-001 (Repository), ADR-002 (слои), ADR-003 (schema versioning), CI/CD, mypy, лицензия.
Следующий агент: читать `.agent/handoff-summary.md`.
Кандидаты на следующий батч: D16 (правило классификации recurring), D18, D22, D24, Tier 3.
+203 -11
View File
@@ -1,17 +1,209 @@
{
"$schema": "metaagent-task-manifest",
"version": "3.0",
"session_id": "metaagent-006",
"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",
"session_id": "metaagent-008",
"goal": "Исполнение плана технического долга D1-D30: Tier 1 полностью (D1, D6-D13), Tier 2 — однозначные пункты (D14, D15, D17, D19, D20, D21) и D23 (синхронизация .agent/**). Остальные пункты ждут решения владельца.",
"created_at": "2026-10-25T12:00: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" },
{ "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": "pending", "origin": "user:direct" }
{
"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"
}
],
"debt_tasks": [
{
"id": "D1",
"title": ".gitignore: правила для data/, exports/; без шапки toptal",
"status": "archived"
},
{
"id": "D2",
"title": "lint-гейт: ruff check . проходит",
"status": "archived"
},
{
"id": "D3",
"title": "9 мертвых typer.Typer()",
"status": "archived"
},
{
"id": "D4",
"title": "i18n._e() — мёртвый хелпер",
"status": "archived"
},
{
"id": "D5",
"title": "второй экземпляр Console()",
"status": "archived"
},
{
"id": "D6",
"title": "константа EXPORTS_DIR",
"status": "archived"
},
{
"id": "D7",
"title": "дрейф в комментариях и docstring",
"status": "archived"
},
{
"id": "D8",
"title": "дрейф в документации (README)",
"status": "archived"
},
{
"id": "D9",
"title": "SCHEMA_VERSION как ClassVar",
"status": "archived"
},
{
"id": "D10",
"title": "изоляция ФС в тестах (tmp_path)",
"status": "archived"
},
{
"id": "D11",
"title": "тесты-характеристики",
"status": "archived"
},
{
"id": "D12",
"title": "pyproject.toml: dev-extra, pytest, coverage",
"status": "archived"
},
{
"id": "D13",
"title": "CI: pytest + ruff",
"status": "archived"
},
{
"id": "D14",
"title": "убрать мутации из расчёта",
"status": "archived"
},
{
"id": "D15",
"title": "одно правило округления (convert без квантования)",
"status": "archived"
},
{
"id": "D17",
"title": "validate_assignment=True",
"status": "archived"
},
{
"id": "D19",
"title": "export-xlsx в несуществующий каталог",
"status": "archived"
},
{
"id": "D20",
"title": "CF_LANG определяется до первого вызова t()",
"status": "archived"
},
{
"id": "D21",
"title": "битый путь в пользовательской строке",
"status": "archived"
},
{
"id": "D23",
"title": "синхронизация .agent/**",
"status": "archived"
},
{
"id": "D16",
"title": "единая классификация recurring + учёт frequency/start_date/end_date",
"status": "blocked"
},
{
"id": "D18",
"title": "лист Scenarios в Excel",
"status": "blocked"
},
{
"id": "D22",
"title": "убрать data/model.json и data/excel.xlsx из git",
"status": "blocked"
},
{
"id": "D24",
"title": "публичные ScenarioError / AssistantError",
"status": "blocked"
},
{
"id": "D25",
"title": "config_cmd.py → пакет commands/config/",
"status": "deferred"
},
{
"id": "D26",
"title": "i18n.py → пакет i18n/{__init__,ru,en}.py",
"status": "deferred"
},
{
"id": "D27",
"title": "infrastructure/cli/i18n/ → infrastructure/i18n/",
"status": "deferred"
},
{
"id": "D28",
"title": "три словаря листов Excel → одна SheetSpec",
"status": "deferred"
},
{
"id": "D29",
"title": "paths.py → объект путей с базой из CF_DATA_DIR",
"status": "deferred"
},
{
"id": "D30",
"title": "решение по .agent/ в продуктовом репо",
"status": "deferred"
}
]
}
+60 -4
View File
@@ -1,9 +1,9 @@
# Task Manifest
**Session:** `metaagent-005` (initial) → `metaagent-006` (T8 pending)
**Goal:** Серьёзный архитектурный рефактор
**Date:** 2026-10-08
**Total tasks:** 8 (7 archived, 1 pending)
**Session:** `metaagent-005` (initial) → `metaagent-006` (T8) → `metaagent-008` (план техдолга D1–D30)
**Goal:** Серьёзный архитектурный рефактор → снятие технического долга (D1–D30)
**Date:** 2026-10-08 (создание) · 2026-10-25 (обновление, metaagent-008)
**Total tasks:** 8 (8 archived)
---
@@ -126,6 +126,8 @@
## T8: ISO 4217-aware форматирование денег (per-currency decimals)
**Статус:** ✅ выполнено (коммит `d58547e`, архив: `.agent/archive/tasks/T8.json`)
**Зависимости:** T3 (Decimal уже мигрирован)
**Файлы:** `domain/currency.py`, `infrastructure/cli/services.py`, `infrastructure/cli/commands/{info,config_cmd}.py`, `infrastructure/cli/i18n.py`, `tests/test_currency.py`, `tests/test_i18n.py`
@@ -208,3 +210,57 @@
| **D28** | Три параллельных словаря листов Excel → одна декларативная таблица `SheetSpec` | сегодня добавление листа = правка 3 мест | РЕСТР | средний | позже (после D18) |
| **D29** | `paths.py` → объект путей с базой из `CF_DATA_DIR` (дефолт `./data` — поведение не меняется) | CWD-relative путь — корень проблемы D10 и требования «запускать из корня» | РЕСТР | низкий | позже |
| **D30** | Решение по `.agent/` в продуктовом репо (60 из 127 файлов, 47 %, 341 КБ) | процесс-артефакты + копия фреймворка внутри продукта | РЕСТР | — | позже (решение владельца) |
# Сессия metaagent-008 — исполнение плана техдолга
**Date:** 2026-10-25
**Goal:** Исполнить разрешённые владельцем пункты плана D1–D30:
Tier 1 целиком (D1, D6–D13) и Tier 2 — однозначные пункты (D14, D15, D17, D19, D20, D21).
**Ветка:** `agent/tier1-debt` (база `dev`)
**Тесты:** 75 → 191 зелёных; `ruff check .` и `ruff format --check .` — чисто
## Статус пунктов
Эта статусы заменяют колонки в таблицах Tier 1/Tier 2/Tier 3 выше.
| ID | Статус |
|---|---|
| D1 | ✅ выполнено |
| D2 | ✅ выполнено (сессия 007) |
| D3 | ✅ выполнено (сессия 007) |
| D4 | ✅ выполнено (сессия 007) |
| D5 | ✅ выполнено (сессия 007) |
| D6 | ✅ выполнено |
| D7 | ✅ выполнено |
| D8 | ✅ выполнено |
| D9 | ✅ выполнено |
| D10 | ✅ выполнено |
| D11 | ✅ выполнено |
| D12 | ✅ выполнено |
| D13 | ✅ выполнено |
| D14 | ✅ выполнено |
| D15 | ✅ выполнено |
| D16 | ⏸ ждёт решения владельца (правило классификации recurring) |
| D17 | ✅ выполнено |
| D18 | ⏸ ждёт решения владельца (лист Scenarios в Excel) |
| D19 | ✅ выполнено |
| D20 | ✅ выполнено |
| D21 | ✅ выполнено |
| D22 | ⏸ ждёт решения владельца (`data/` — данные модели) |
| D23 | ✅ выполнено (синхронизация `.agent/**`) |
| D24 | ⏸ ждёт решения владельца (`ScenarioError` / `AssistantError`) |
| D25 | ⏳ позже (Tier 3) |
| D26 | ⏳ позже (Tier 3) |
| D27 | ⏳ позже (Tier 3) |
| D28 | ⏳ позже (Tier 3) |
| D29 | ⏳ позже (Tier 3) |
| D30 | ⏳ позже (Tier 3) |
## Что осталось
- **Tier 1** — закрыт полностью (13/13), включая D2–D5 — сессия 007.
- **Tier 2** — закрыто 7/11: D14, D15, D17, D19, D20, D21, D23. Остались D16, D18, D22, D24 — требуют решения владельца.
- **Tier 3** — не начинат (D25–D30).
Изменения чисел: D14 и D15 меняют числа прогноза и конверсии — новые значения зафиксированы тестами-характеристиками и сведены в таблицу «было → стало».
+40
View File
@@ -0,0 +1,40 @@
name: CI
on:
push:
branches:
- dev
- main
- master
- "agent/**"
pull_request:
workflow_dispatch:
jobs:
test:
name: pytest + ruff
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
cache-dependency-path: pyproject.toml
- name: Install project and dev tools
run: |
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
- name: ruff check
run: ruff check .
- name: ruff format
run: ruff format --check .
- name: pytest
run: pytest -q
+17 -122
View File
@@ -1,13 +1,7 @@
# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python
### Python ###
# Byte-compiled / optimized / DLL files
# ── Python ────────────────────────────────────────────────────────
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
@@ -18,8 +12,6 @@ dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
@@ -30,16 +22,6 @@ share/python-wheels/
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
@@ -55,76 +37,10 @@ coverage.xml
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
# Environments (секреты и локальные окружения)
.env
.env.*
!.env.example
.venv
env/
venv/
@@ -132,49 +48,28 @@ ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
# Type checkers / linters
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml
# ruff
.ruff_cache/
# LSP config files
pyrightconfig.json
# Editors
.idea/
.vscode/
.spyderproject
.spyproject
.ropeproject
# End of https://www.toptal.com/developers/gitignore/api/python
# ── Данные приложения (runtime, генерируются CLI) ─────────────────
# ВНИМАНИЕ: data/model.json и data/excel.xlsx уже отслеживаются git —
# правило ниже их НЕ отменяет (см. D22 в .agent/tasks/manifest.md).
/data/
/exports/
# ── Служебное ─────────────────────────────────────────────────────
# MetaAgent temp files
.temp/
+9
View File
@@ -1,5 +1,10 @@
# CashFlow Forecast
> ⚠️ **Исторический документ.** Это исходная архитектурная концепция проекта,
> зафиксированная до рефакторинга в слои `domain/` / `application/` /
> `infrastructure/`. Описание ниже — снимок исходного замысла, а не описание
> текущего кода. Актуальное состояние проекта — в [README.md](README.md).
Простой open-source проект для построения и анализа личной финансовой модели с использованием Spreadsheet, Python и AI.
## Идея
@@ -158,6 +163,10 @@ Spreadsheet Export
## Структура репозитория
> ⚠️ **Историческая структура** (до рефакторинга): каталоги `spreadsheet/`,
> `sync/`, `engine/`, `ai/` больше не существуют. Действующая структура
> проекта — в [README.md](README.md).
```
cashflow-forecast/
+63 -13
View File
@@ -35,6 +35,9 @@ cf whatif --income 1.2 --expense 0.9 --growth 1.0 --months 12
# Сравнение всех сценариев
cf compare --months 12
# AI-анализ модели (заглушка: печатает подготовленный промпт)
cf analyze --months 12
# Сводка модели
cf info
@@ -46,11 +49,40 @@ cf config rate-set USD RUB 80.0
# Импорт/экспорт Excel
cf import-xlsx data.xlsx
cf export-xlsx exports/report.xlsx
# Валюта отображения (--currency / -c) — у forecast, scenario, compare, whatif, analyze
cf forecast --months 12 --currency USD
# Язык интерфейса (CF_LANG). Переводы есть только для ru, поэтому
# CF_LANG=en молча откатывается на русский.
CF_LANG=ru cf info
```
Команды верхнего уровня: `init`, `forecast`, `scenario`, `whatif`, `compare`,
`analyze`, `info`, `import-xlsx`, `export-xlsx` и под-приложение `config`.
### Команды `cf config`
Редактирование модели — 19 подкоманд:
| Семейство | Подкоманды |
|---|---|
| Базовая валюта | `base-currency` (показать/задать) |
| Курсы валют | `rate-set`, `rate-list`, `rate-remove` |
| Счета | `account-add`, `account-list`, `account-remove` |
| Транзакции | `transaction-add`, `transaction-list`, `transaction-remove` |
| Регулярные платежи | `recurring-add`, `recurring-list`, `recurring-remove` |
| Активы | `asset-add`, `asset-list`, `asset-remove` |
| Обязательства | `liability-add`, `liability-list`, `liability-remove` |
Полный список с подсказками — `cf config --help`.
### Пример: создание тестовых данных
Подготовьте Excel-файл с листами: `Accounts`, `Transactions`, `Recurring`, `Assets`, `Liabilities`. Заголовки колонок соответствуют полям моделей. Затем импортируйте:
Подготовьте Excel-файл с листами: `Accounts`, `Transactions`, `Recurring`,
`Assets`, `Liabilities`, `ExchangeRates`. Заголовки колонок соответствуют полям
моделей. Лист `ModelInfo` (свойство `base_currency`) создаётся при экспорте и
читается при импорте, вручную его заполнять не нужно. Затем импортируйте:
```bash
cf import-xlsx my_finances.xlsx
@@ -106,10 +138,10 @@ cashflow-forecast/
├── infrastructure/ # Адаптеры к внешнему миру
│ ├── cli/ # Typer CLI (cf ...)
│ │ ├── app.py # Entry point
│ │ ├── commands/ # 9 файлов команд + config sub-typer
│ │ ├── paths.py # DATA_DIR, MODEL_PATH
│ │ ├── commands/ # 10 файлов команд + config sub-typer
│ │ ├── paths.py # DATA_DIR, MODEL_PATH, EXPORTS_DIR
│ │ ├── services.py # Composition root + helpers
│ │ └── i18n.py # ru/en переводы
│ │ └── i18n.py # ru-переводы (словарь "en" пуст, откат на ru)
│ ├── ai/ # AI-ассистент (заглушка)
│ │ ├── prompts.py
│ │ └── assistant.py # AssistantService
@@ -117,7 +149,7 @@ cashflow-forecast/
│ ├── json_file_repository.py
│ └── excel_repository.py
│
├── tests/ # pytest, 67 тестов
├── tests/ # pytest, 160 тестов
│ ├── conftest.py
│ ├── test_model.py
│ ├── test_forecast.py
@@ -125,6 +157,7 @@ cashflow-forecast/
│ ├── test_currency.py
│ ├── test_ai.py
│ ├── test_cli.py
│ ├── test_cli_contract.py # Инвариант публичной поверхности CLI
│ ├── test_excel_sync.py # Тесты ExcelRepository
│ ├── test_i18n.py
│ └── test_repositories.py # Тесты репозиториев
@@ -132,19 +165,26 @@ cashflow-forecast/
├── data/ # JSON-модели (runtime, версионируется SCHEMA_VERSION=1)
├── exports/ # Экспортированные .xlsx
├── .agent/ # Артефакты MetaAgent v3.0
├── .github/workflows/ci.yml # CI: pytest + ruff
├── pyproject.toml # Зависимости + entry point `cf`
└── README.arch.md # Оригинальная архитектурная концепция
└── README.arch.md # Оригинальная архитектурная концепция (исторический документ)
```
## Разработка
```bash
# Установка с dev-зависимостями (pytest, ruff, coverage)
pip install -e ".[dev]"
# Тесты
pytest
# Линтер (если доступен ruff)
# Линтер
ruff check .
# Проверка форматирования (как в CI)
ruff format --check .
# Автоформат
ruff format .
```
@@ -156,8 +196,9 @@ ruff format .
- typer — CLI
- rich — форматирование вывода
- pydantic >= 2.0 — валидация моделей
- pytest — тесты
- ruff — линтер (опционально)
- pytest — тесты (dev-extra)
- ruff — линтер и форматтер (dev-extra)
- coverage — покрытие (dev-extra)
## Архитектурные решения
@@ -167,12 +208,21 @@ ruff format .
- **Repository pattern**: `ModelRepository` Protocol, реализации `JsonFileRepository` и `ExcelRepository`.
- **DI**: Composition root в `infrastructure/cli/services.py:build_services()`.
- **Schema versioning**: `FinancialModel.to_dict()` пишет `version: 1`; `from_dict()` поддерживает legacy v0.
- **i18n**: `infrastructure/cli/i18n.py`, ru (default) + en (fallback).
- **i18n**: `infrastructure/cli/i18n.py` — словарь только на русском. Английские
переводы не реализованы: словарь `"en"` пуст, поэтому `CF_LANG=en` **молча
откатывается на `ru`** (интерфейс остаётся русским, предупреждения нет).
Язык определяется при импорте модуля i18n — до первого вызова `t()`, поэтому
`CF_LANG` действует и на строки, собираемые на этапе импорта команд.
Как только в словаре появится непустой перевод, он будет выбран по `CF_LANG`.
- **Тесты**: pytest, файлы состояния не пишутся в дерево репозитория (CWD теста
переводится во временный каталог).
## Известные ограничения (MVP)
- **AI-ассистент** — заглушка (`ai_response: None`). Промпты готовы, но не подключены к API.
- **Хранилище** — JSON-файлы (не подходит для многопользовательской работы).
- **Excel** — только `.xlsx` через openpyxl.
- **Лицензия** — не выбрана.
- **CI/CD** — не настроен.
- **Excel** — только `.xlsx` через openpyxl. Лист сценариев при экспорте/импорте
не сохраняется.
- **i18n** — только русский язык интерфейса; `CF_LANG=en` откатывается на `ru`.
- **Лицензия** — MIT (см. `LICENSE`).
- **CI** — настроен: `.github/workflows/ci.yml` (pytest + ruff).
+65 -29
View File
@@ -15,6 +15,13 @@ _HUNDRED = Decimal("100")
class ForecastService:
"""Помесячный прогноз денежных потоков.
Расчёт НЕ мутирует модель: `self.model` после `forecast_cashflow()` остаётся
байт-в-байт тем же, что до вызова, поэтому повторный прогноз на том же
экземпляре даёт идентичный результат (D14).
"""
def __init__(self, model: FinancialModel):
self.model = deepcopy(model)
@@ -22,23 +29,30 @@ class ForecastService:
if months < 1:
raise ForecastError("months must be >= 1")
# Локальное состояние расчёта — вместо мутации модели (D14).
# `liability_balances` — текущий остаток по каждому обязательству,
# `asset_values` — текущая стоимость каждого актива.
liability_balances = [li.balance for li in self.model.liabilities]
asset_values = [a.value for a in self.model.assets]
results = []
for account in self.model.accounts:
monthly = self._project_account(account, months)
monthly = self._project_account(account, months, liability_balances)
for m in range(months):
results.append({
"account": account.name,
"month": m + 1,
"balance": monthly[m]["balance"],
"income": monthly[m]["income"],
"expenses": monthly[m]["expenses"],
})
results.append(
{
"account": account.name,
"month": m + 1,
"balance": monthly[m]["balance"],
"income": monthly[m]["income"],
"expenses": monthly[m]["expenses"],
}
)
# Asset growth — once per month, distributed across accounts proportionally
for m in range(months):
total_growth = sum(
a.value * a.growth_rate / _HUNDRED / _TWELVE
for a in self.model.assets
value * a.growth_rate / _HUNDRED / _TWELVE for value, a in zip(asset_values, self.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
@@ -47,13 +61,14 @@ class ForecastService:
r["income"] = _q(r["income"] + total_growth * share)
r["balance"] = _q(r["balance"] + total_growth * share)
# Compound asset values for next month
for a in self.model.assets:
a.value = a.value + a.value * a.growth_rate / _HUNDRED / _TWELVE
# Compound asset values for next month (локально, модель не меняется)
asset_values = [
value + value * a.growth_rate / _HUNDRED / _TWELVE for value, a in zip(asset_values, self.model.assets)
]
return results
def _project_account(self, account: Account, months: int) -> list[dict]:
def _project_account(self, account: Account, months: int, liability_balances: list[Decimal]) -> list[dict]:
balance = account.balance
monthly = []
for m in range(months):
@@ -73,29 +88,46 @@ class ForecastService:
else:
expenses += abs(r.amount)
expenses += self._liability_cost(account)
expenses += self._liability_cost(liability_balances)
balance = balance + income - expenses
monthly.append({
"balance": _q(balance),
"income": _q(income),
"expenses": _q(expenses),
})
monthly.append(
{
"balance": _q(balance),
"income": _q(income),
"expenses": _q(expenses),
}
)
return monthly
def _liability_cost(self, account: Account) -> Decimal:
def _liability_cost(self, liability_balances: list[Decimal]) -> Decimal:
"""Проценты по обязательствам за один месяц.
Остатки обязательств ведутся в локальном списке `liability_balances`:
модель не изменяется (D14). Порядок и количество вызовов (по одному на
каждый счёт × месяц) сохранены, поэтому формула прогноза не изменилась.
"""
total = _ZERO
for liability in self.model.liabilities:
interest_cost = liability.balance * liability.interest / _HUNDRED / _TWELVE
for i, liability in enumerate(self.model.liabilities):
balance = liability_balances[i]
interest_cost = balance * liability.interest / _HUNDRED / _TWELVE
total += interest_cost
liability.balance = liability.balance - (liability.payment - interest_cost)
if liability.balance < 0:
liability.balance = _ZERO
balance = balance - (liability.payment - interest_cost)
if balance < 0:
balance = _ZERO
liability_balances[i] = balance
return total
def summary(self, months: int = 12) -> dict:
results = self.forecast_cashflow(months)
def summary(self, months: int = 12, results: list[dict] | None = None) -> dict:
"""Сводка по прогнозу.
`results` — уже посчитанный набор строк: если он передан, сводка
считается ровно по нему, поэтому «Итог» в CLI совпадает с последней
строкой таблицы (D14). Если не передан — прогноз считается заново.
"""
if results is None:
results = self.forecast_cashflow(months)
if not results:
return {"total_balance": 0, "total_income": 0, "total_expenses": 0, "months": months}
@@ -111,5 +143,9 @@ class ForecastService:
def _q(v: Decimal) -> Decimal:
"""Quantize to 2 decimal places, ROUND_HALF_UP."""
"""Quantize to 2 decimal places, ROUND_HALF_UP.
Единственная точка округления в прогнозе: применяется к значениям, которые
попадают в результат (сериализуемый вывод), а не к промежуточной арифметике.
"""
return v.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
@@ -3,6 +3,7 @@
Определяет контракт: load(path) -> FinancialModel, save(model, path) -> None.
Реализации: JsonFileRepository, ExcelRepository.
"""
from __future__ import annotations
from pathlib import Path
+1 -4
View File
@@ -83,9 +83,6 @@ class ScenarioService:
income_multiplier=to_d(income_mult),
expense_multiplier=to_d(expense_mult),
growth_multiplier=to_d(growth_mult),
description=(
f"What-if: income x{income_mult}, "
f"expense x{expense_mult}, growth x{growth_mult}"
),
description=(f"What-if: income x{income_mult}, expense x{expense_mult}, growth x{growth_mult}"),
)
return self.apply(scenario, months)
+6 -1
View File
@@ -1,10 +1,15 @@
from decimal import Decimal
from uuid import UUID, uuid4
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator
class Account(BaseModel):
# Валидация при присваивании: любое присваивание полю проверяется
# валидатором модели, а значение приводится к объявленному типу
# (float в поле Decimal не остаётся float) — D17.
model_config = ConfigDict(validate_assignment=True)
id: UUID = Field(default_factory=uuid4)
name: str = ""
currency: str = "USD"
+6 -1
View File
@@ -1,10 +1,15 @@
from decimal import Decimal
from uuid import UUID, uuid4
from pydantic import BaseModel, Field
from pydantic import BaseModel, ConfigDict, Field
class Asset(BaseModel):
# Валидация при присваивании: любое присваивание полю проверяется
# валидатором модели, а значение приводится к объявленному типу
# (float в поле Decimal не остаётся float) — D17.
model_config = ConfigDict(validate_assignment=True)
id: UUID = Field(default_factory=uuid4)
name: str = ""
value: Decimal = Field(default=Decimal("0"))
+16 -4
View File
@@ -1,6 +1,6 @@
from decimal import ROUND_HALF_UP, Decimal
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator
CURRENCY_SYMBOLS = {
"RUB": "₽",
@@ -15,8 +15,9 @@ CURRENCY_SYMBOLS = {
# ISO 4217 minor units per currency (https://en.wikipedia.org/wiki/ISO_4217).
# Keys are uppercase 3-letter codes, values are the number of decimal digits used
# when DISPLAYING the currency. Internal arithmetic keeps full Decimal precision
# (do not modify — see T8 decision `internal_precision`).
# when DISPLAYING the currency. Округление — только при отображении:
# `convert()` НЕ квантует результат (внутри — полная точность Decimal),
# а `format_money()` округляет по числу знаков валюты отсюда (D15).
#
# - 0 decimals: JPY (Japanese yen)
# - 2 decimals: most currencies (RUB, USD, EUR, GBP, CNY, KZT, UAH, ...)
@@ -41,6 +42,11 @@ DEFAULT_CURRENCY_DECIMALS = 2
class ExchangeRate(BaseModel):
# Валидация при присваивании: любое присваивание полю проверяется
# валидатором модели, а значение приводится к объявленному типу
# (float в поле Decimal не остаётся float) — D17.
model_config = ConfigDict(validate_assignment=True)
from_currency: str = "USD"
to_currency: str = "RUB"
rate: Decimal = Field(default=Decimal("80"))
@@ -95,11 +101,17 @@ class CurrencyConverter:
from_currency: str,
to_currency: str,
) -> Decimal:
"""Конвертировать сумму по курсу.
Результат НЕ округляется: внутри сохраняется полная точность Decimal
(D15). Округление применяется только при отображении — в
`format_money()`, где знаки берутся из `CURRENCY_DECIMALS`.
"""
a = Decimal(str(amount)) if not isinstance(amount, Decimal) else amount
if from_currency == to_currency:
return a
rate = self.get_rate(from_currency, to_currency)
return (a * rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return a * rate
def get_symbol(self, currency: str) -> str:
return CURRENCY_SYMBOLS.get(currency, currency)
+6 -1
View File
@@ -1,10 +1,15 @@
from decimal import Decimal
from uuid import UUID, uuid4
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator
class Liability(BaseModel):
# Валидация при присваивании: любое присваивание полю проверяется
# валидатором модели, а значение приводится к объявленному типу
# (float в поле Decimal не остаётся float) — D17.
model_config = ConfigDict(validate_assignment=True)
id: UUID = Field(default_factory=uuid4)
name: str = ""
balance: Decimal = Field(default=Decimal("0"))
+14 -5
View File
@@ -1,4 +1,6 @@
from pydantic import BaseModel, Field
from typing import ClassVar
from pydantic import BaseModel, ConfigDict, Field
from domain.account import Account
from domain.asset import Asset
@@ -10,13 +12,22 @@ from domain.transaction import Transaction
class FinancialModel(BaseModel):
# Валидация при присваивании: любое присваивание полю проверяется
# валидатором модели, а значение приводится к объявленному типу
# (float в поле Decimal не остаётся float) — D17.
model_config = ConfigDict(validate_assignment=True)
"""Корневая модель финансового плана.
Сериализация (save/load) вынесена в `application.repositories.ModelRepository` —
JsonFileRepository и ExcelRepository. Сам класс хранит только данные.
"""
SCHEMA_VERSION: int = 1 # NB: не Field — это class-level metadata, не pydantic field
# Версия схемы — метаданные класса, а НЕ поле pydantic.
# В pydantic v2 аннотация со значением (`SCHEMA_VERSION: int = 1`) объявляет
# поле, поэтому значение можно было подменить при создании модели
# (`FinancialModel(SCHEMA_VERSION=99)`). ClassVar исключает его из полей.
SCHEMA_VERSION: ClassVar[int] = 1
base_currency: str = "RUB"
accounts: list[Account] = Field(default_factory=list)
@@ -25,9 +36,7 @@ class FinancialModel(BaseModel):
assets: list[Asset] = Field(default_factory=list)
liabilities: list[Liability] = Field(default_factory=list)
scenarios: list[ForecastScenario] = Field(default_factory=list)
exchange_rates: list[ExchangeRate] = Field(
default_factory=lambda: [r.model_copy() for r in DEFAULT_RATES]
)
exchange_rates: list[ExchangeRate] = Field(default_factory=lambda: [r.model_copy() for r in DEFAULT_RATES])
def to_dict(self) -> dict:
"""Сериализация в dict с version и UUID-as-str (для JSON)."""
+6 -1
View File
@@ -1,10 +1,15 @@
from decimal import Decimal
from uuid import UUID, uuid4
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator
class RecurringCashflow(BaseModel):
# Валидация при присваивании: любое присваивание полю проверяется
# валидатором модели, а значение приводится к объявленному типу
# (float в поле Decimal не остаётся float) — D17.
model_config = ConfigDict(validate_assignment=True)
id: UUID = Field(default_factory=uuid4)
start_date: str = ""
end_date: str = ""
+6 -1
View File
@@ -1,10 +1,15 @@
from decimal import Decimal
from uuid import UUID, uuid4
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator
class ForecastScenario(BaseModel):
# Валидация при присваивании: любое присваивание полю проверяется
# валидатором модели, а значение приводится к объявленному типу
# (float в поле Decimal не остаётся float) — D17.
model_config = ConfigDict(validate_assignment=True)
id: UUID = Field(default_factory=uuid4)
name: str = "baseline"
income_multiplier: Decimal = Field(default=Decimal("1"))
+6 -1
View File
@@ -1,10 +1,15 @@
from decimal import Decimal
from uuid import UUID, uuid4
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator
class Transaction(BaseModel):
# Валидация при присваивании: любое присваивание полю проверяется
# валидатором модели, а значение приводится к объявленному типу
# (float в поле Decimal не остаётся float) — D17.
model_config = ConfigDict(validate_assignment=True)
id: UUID = Field(default_factory=uuid4)
date: str = ""
account: str = ""
+2 -1
View File
@@ -34,7 +34,8 @@ class AssistantService:
def analyze(self, months: int = 12) -> dict:
forecast_result = self.forecast_service.forecast_cashflow(months)
summary = self.forecast_service.summary(months)
# Сводка — по тому же набору строк, что и в промпте (D14).
summary = self.forecast_service.summary(months, results=forecast_result)
prompt = prompts.format_context(
model_json=json.dumps(self.model.to_dict(), indent=2, ensure_ascii=False, cls=_DecimalEncoder),
+2 -1
View File
@@ -1,4 +1,5 @@
"""Entry point приложения cf. Регистрирует все команды."""
import sys
import typer
@@ -22,7 +23,7 @@ from infrastructure.cli.commands import (
)
from infrastructure.cli.i18n import setup_i18n, t
setup_i18n()
setup_i18n() # язык уже определён при импорте infrastructure.cli.i18n (D20)
app = typer.Typer(name="cf", help=t("app.help"))
+1
View File
@@ -1,4 +1,5 @@
"""cf analyze — AI-анализ финансовой модели (заглушка)."""
import typer
from infrastructure.cli.i18n import t
+9 -1
View File
@@ -1,5 +1,7 @@
"""cf compare — сравнить все сценарии."""
import typer
from pydantic import ValidationError
from rich.table import Table
from infrastructure.cli.i18n import t
@@ -7,6 +9,7 @@ from infrastructure.cli.services import (
build_services,
console,
convert_value,
fail_validation,
fmt_amount,
load_model,
resolve_currency,
@@ -24,7 +27,12 @@ def compare(
target_curr, symbol = resolve_currency(model, currency)
_, scenario_service, _, converter = build_services(model)
base_curr = model.base_currency
results = scenario_service.compare(months)
try:
results = scenario_service.compare(months)
except ValidationError as e:
# Сценарий может обнулить суммы (множитель 0) — модель это
# отклоняет (валидация при присваивании, D17).
fail_validation(e)
table = Table(title=t("cmd.compare.title", currency=target_curr))
table.add_column(t("cmd.compare.col.scenario"), style="cyan")
+40 -33
View File
@@ -1,5 +1,9 @@
"""cf config — подкоманды для редактирования модели (базовая валюта, счета, транзакции, ...)."""
from decimal import Decimal
import typer
from pydantic import ValidationError
from rich.table import Table
from domain import (
@@ -12,7 +16,7 @@ from domain import (
Transaction,
)
from infrastructure.cli.i18n import t
from infrastructure.cli.services import console, load_model, save_model
from infrastructure.cli.services import console, fail_validation, load_model, save_model
app = typer.Typer(name="config", help=t("config.help"))
@@ -48,17 +52,27 @@ def rate_set(
"""Добавить или обновить курс валюты"""
model = load_model()
fc, tc = from_currency.upper(), to_currency.upper()
# Курс пишем Decimal: поле объявлено как Decimal, а float в него класть
# нельзя (D17).
rate_value = Decimal(str(rate))
existing = [r for r in model.exchange_rates if r.from_currency == fc and r.to_currency == tc]
if existing:
existing[0].rate = rate
else:
model.exchange_rates.append(ExchangeRate(
from_currency=fc,
to_currency=tc,
rate=rate,
))
try:
if existing:
existing[0].rate = rate_value
else:
model.exchange_rates.append(
ExchangeRate(
from_currency=fc,
to_currency=tc,
rate=rate_value,
)
)
except ValidationError as e:
# Отрицательный или нулевой курс отклоняет валидатор модели —
# показываем понятное сообщение вместо traceback (D17).
fail_validation(e)
save_model(model)
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_set.ok', fc=fc, tc=tc, rate=rate)}")
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_set.ok', fc=fc, tc=tc, rate=rate_value)}")
@app.command(name="rate-list")
@@ -86,10 +100,7 @@ def rate_remove(
model = load_model()
fc, tc = from_currency.upper(), to_currency.upper()
initial = len(model.exchange_rates)
model.exchange_rates = [
r for r in model.exchange_rates
if not (r.from_currency == fc and r.to_currency == tc)
]
model.exchange_rates = [r for r in model.exchange_rates if not (r.from_currency == fc and r.to_currency == tc)]
if len(model.exchange_rates) < initial:
save_model(model)
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_remove.ok', fc=fc, tc=tc)}")
@@ -143,10 +154,7 @@ def account_remove(
"""Удалить счёт по ID или названию"""
model = load_model()
initial = len(model.accounts)
model.accounts = [
a for a in model.accounts
if str(a.id) != identifier and a.name != identifier
]
model.accounts = [a for a in model.accounts if str(a.id) != identifier and a.name != identifier]
if len(model.accounts) < initial:
save_model(model)
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.account_remove.ok', id=identifier)}")
@@ -204,12 +212,14 @@ def transaction_list() -> None:
table.add_column(t("table.transactions.col.description"))
for tx in model.transactions:
account_name = _account_name(model, tx.account)
amount_str = CurrencyConverter.format_money(
tx.amount, _account_currency(model, tx.account)
)
amount_str = CurrencyConverter.format_money(tx.amount, _account_currency(model, tx.account))
table.add_row(
str(tx.id)[:8], tx.date, account_name, tx.category,
amount_str, tx.description,
str(tx.id)[:8],
tx.date,
account_name,
tx.category,
amount_str,
tx.description,
)
console.print(table)
@@ -244,8 +254,11 @@ def recurring_add(
"""Добавить регулярный платёж"""
model = load_model()
rc = RecurringCashflow(
start_date=start_date or "", end_date=end_date or "",
frequency=frequency, amount=amount, category=category,
start_date=start_date or "",
end_date=end_date or "",
frequency=frequency,
amount=amount,
category=category,
)
model.recurring.append(rc)
save_model(model)
@@ -334,10 +347,7 @@ def asset_remove(
"""Удалить актив по ID или названию"""
model = load_model()
initial = len(model.assets)
model.assets = [
a for a in model.assets
if str(a.id) != identifier and a.name != identifier
]
model.assets = [a for a in model.assets if str(a.id) != identifier and a.name != identifier]
if len(model.assets) < initial:
save_model(model)
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.asset_remove.ok', id=identifier)}")
@@ -392,10 +402,7 @@ def liability_remove(
"""Удалить обязательство по ID или названию"""
model = load_model()
initial = len(model.liabilities)
model.liabilities = [
li for li in model.liabilities
if str(li.id) != identifier and li.name != identifier
]
model.liabilities = [li for li in model.liabilities if str(li.id) != identifier and li.name != identifier]
if len(model.liabilities) < initial:
save_model(model)
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.liability_remove.ok', id=identifier)}")
+8 -1
View File
@@ -1,15 +1,22 @@
"""cf export-xlsx — экспорт модели в Excel."""
import typer
from infrastructure.cli.i18n import t
from infrastructure.cli.paths import EXPORTS_DIR
from infrastructure.cli.services import console, load_model
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
_repo = ExcelRepository()
# Значение по умолчанию остаётся ровно "exports/forecast.xlsx" (строка в help
# и в аргументе CLI не меняется) — собирается из EXPORTS_DIR во избежание
# дублирования литерала пути.
DEFAULT_EXPORT_PATH: str = str(EXPORTS_DIR / "forecast.xlsx")
def export_xlsx(
path: str = typer.Argument("exports/forecast.xlsx", help=t("cmd.export.arg.path")),
path: str = typer.Argument(DEFAULT_EXPORT_PATH, help=t("cmd.export.arg.path")),
) -> None:
"""Экспорт модели в Excel"""
model = load_model()
+14 -6
View File
@@ -1,4 +1,5 @@
"""cf forecast — прогноз денежных потоков."""
import typer
from rich.table import Table
@@ -25,7 +26,9 @@ def forecast(
forecast_service, _, _, converter = build_services(model)
base_curr = model.base_currency
results = forecast_service.forecast_cashflow(months)
summary = forecast_service.summary(months)
# Сводка считается по тому же набору строк, который печатается таблицей —
# «Итог» совпадает с последней строкой (D14).
summary = forecast_service.summary(months, results=results)
if results:
table = Table(title=t("cmd.forecast.title", months=months, currency=target_curr))
@@ -37,7 +40,8 @@ def forecast(
for r in results:
table.add_row(
r["account"], str(r["month"]),
r["account"],
str(r["month"]),
fmt_amount(convert_value(converter, r["balance"], base_curr, target_curr), target_curr, symbol),
fmt_amount(convert_value(converter, r["income"], base_curr, target_curr), target_curr, symbol),
fmt_amount(convert_value(converter, r["expenses"], base_curr, target_curr), target_curr, symbol),
@@ -47,7 +51,11 @@ def forecast(
cb = convert_value(converter, summary["total_balance"], base_curr, target_curr)
ci = convert_value(converter, summary["total_income"], base_curr, target_curr)
ce = convert_value(converter, summary["total_expenses"], base_curr, target_curr)
console.print(t("cmd.forecast.total",
balance=fmt_amount(cb, target_curr, symbol),
income=fmt_amount(ci, target_curr, symbol),
expenses=fmt_amount(ce, target_curr, symbol)))
console.print(
t(
"cmd.forecast.total",
balance=fmt_amount(cb, target_curr, symbol),
income=fmt_amount(ci, target_curr, symbol),
expenses=fmt_amount(ce, target_curr, symbol),
)
)
+11 -6
View File
@@ -1,4 +1,5 @@
"""cf import-xlsx — импорт данных из Excel."""
import typer
from infrastructure.cli.i18n import t
@@ -15,12 +16,16 @@ def import_xlsx(
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.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))
except ExcelRepositoryError as e:
console.print(f"[red]{t('cmd.import.err', error=str(e))}[/red]")
+1
View File
@@ -1,4 +1,5 @@
"""cf info — сводка всей финансовой модели."""
from rich.table import Table
from domain import CurrencyConverter
+9 -1
View File
@@ -1,5 +1,7 @@
"""cf scenario — применить именованный сценарий (baseline/optimistic/pessimistic)."""
import typer
from pydantic import ValidationError
from application.scenarios import DEFAULT_SCENARIOS
from infrastructure.cli.i18n import t
@@ -7,6 +9,7 @@ from infrastructure.cli.services import (
build_services,
console,
convert_value,
fail_validation,
fmt_amount,
load_model,
resolve_currency,
@@ -33,7 +36,12 @@ def scenario(
console.print(t("cmd.scenario.err.available", scenarios=", ".join(DEFAULT_SCENARIOS.keys())))
raise typer.Exit(1)
result = scenario_service.apply(scenario_obj, months)
try:
result = scenario_service.apply(scenario_obj, months)
except ValidationError as e:
# Сценарий может обнулить суммы (множитель 0) — модель это
# отклоняет (валидация при присваивании, D17).
fail_validation(e)
balance = convert_value(converter, result["total_balance"], base_curr, target_curr)
income = convert_value(converter, result["total_income"], base_curr, target_curr)
expenses = convert_value(converter, result["total_expenses"], base_curr, target_curr)
+9 -1
View File
@@ -1,11 +1,14 @@
"""cf whatif — what-if анализ с произвольными множителями."""
import typer
from pydantic import ValidationError
from infrastructure.cli.i18n import t
from infrastructure.cli.services import (
build_services,
console,
convert_value,
fail_validation,
fmt_amount,
load_model,
resolve_currency,
@@ -26,7 +29,12 @@ def whatif(
target_curr, symbol = resolve_currency(model, currency)
_, scenario_service, _, converter = build_services(model)
base_curr = model.base_currency
result = scenario_service.what_if(income, expense, growth, months)
try:
result = scenario_service.what_if(income, expense, growth, months)
except ValidationError as e:
# Множитель 0 обнуляет суммы транзакций — модель это отклоняет
# (валидация при присваивании, D17). Показываем сообщение, а не traceback.
fail_validation(e)
balance = convert_value(converter, result["total_balance"], base_curr, target_curr)
income_v = convert_value(converter, result["total_income"], base_curr, target_curr)
+93 -61
View File
@@ -68,9 +68,11 @@ _r("cmd.compare.col.scenario", "Сценарий")
_r("cmd.import.help", "Импорт данных из Excel")
_r("cmd.import.arg.path", "Путь к .xlsx файлу")
_r("cmd.import.ok",
"Импортировано: {accounts} счетов, {transactions} транзакций, "
"{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств")
_r(
"cmd.import.ok",
"Импортировано: {accounts} счетов, {transactions} транзакций, "
"{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств",
)
_r("cmd.import.base_currency", "Базовая валюта: {currency}")
_r("cmd.import.err", "Ошибка импорта: {error}")
@@ -88,7 +90,7 @@ _r("cmd.analyze.opt.months", "Количество месяцев для ана
_r("cmd.analyze.title.prompt", "Промпт для AI")
_r("cmd.analyze.title.summary", "Сводка")
_r("cmd.analyze.base_currency", "Базовая валюта: {currency}")
_r("cmd.analyze.stub", "AI-ответ: заглушка. Подключите реальный API в ai/assistant.py")
_r("cmd.analyze.stub", "AI-ответ: заглушка. Подключите реальный API в infrastructure/ai/assistant.py")
# ── cmd.info ──────────────────────────────────────────────────
@@ -251,62 +253,73 @@ _r("cmd.config.liability_remove.err", "Обязательство '{id}' не н
# ── global ─────────────────────────────────────────────────────
_r("global.ok", "OK")
_r("global.validation_error", "Ошибка валидации данных: {error}")
# ── prompts ───────────────────────────────────────────────────
_r("prompt.analyze", (
"Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n"
"\n"
"### Модель (JSON):\n"
"{model_json}\n"
"\n"
"### Прогноз на {months} месяцев:\n"
"{forecast_json}\n"
"\n"
"### Валюта:\n"
"Базовая валюта модели: {base_currency}\n"
"Отображаемая валюта: {display_currency}\n"
"\n"
"Дай анализ по пунктам:\n"
"1. Общее финансовое состояние\n"
"2. Тренд денежного потока (рост/падение)\n"
"3. Достаточность ликвидности\n"
"4. Рекомендации по улучшению"
))
_r(
"prompt.analyze",
(
"Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n"
"\n"
"### Модель (JSON):\n"
"{model_json}\n"
"\n"
"### Прогноз на {months} месяцев:\n"
"{forecast_json}\n"
"\n"
"### Валюта:\n"
"Базовая валюта модели: {base_currency}\n"
"Отображаемая валюта: {display_currency}\n"
"\n"
"Дай анализ по пунктам:\n"
"1. Общее финансовое состояние\n"
"2. Тренд денежного потока (рост/падение)\n"
"3. Достаточность ликвидности\n"
"4. Рекомендации по улучшению"
),
)
_r("prompt.advice", (
"Ты — финансовый AI-ассистент. Дай персональные рекомендации.\n"
"\n"
"### Модель:\n"
"{model_json}\n"
"\n"
"### Прогноз:\n"
"{forecast_json}\n"
"\n"
"### Валюта:\n"
"Базовая валюта модели: {base_currency}\n"
"Отображаемая валюта: {display_currency}\n"
"\n"
"Вопрос пользователя: {question}\n"
"\n"
"Ответь как опытный финансовый консультант."
))
_r(
"prompt.advice",
(
"Ты — финансовый AI-ассистент. Дай персональные рекомендации.\n"
"\n"
"### Модель:\n"
"{model_json}\n"
"\n"
"### Прогноз:\n"
"{forecast_json}\n"
"\n"
"### Валюта:\n"
"Базовая валюта модели: {base_currency}\n"
"Отображаемая валюта: {display_currency}\n"
"\n"
"Вопрос пользователя: {question}\n"
"\n"
"Ответь как опытный финансовый консультант."
),
)
_r("prompt.scenario_comparison", (
"Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n"
"\n"
"### Результаты сценариев:\n"
"{scenarios_json}\n"
"\n"
"### Валюта:\n"
"Базовая валюта модели: {base_currency}\n"
"Отображаемая валюта: {display_currency}\n"
"\n"
"Дай рекомендацию: какой сценарий наиболее вероятен и почему."
))
_r(
"prompt.scenario_comparison",
(
"Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n"
"\n"
"### Результаты сценариев:\n"
"{scenarios_json}\n"
"\n"
"### Валюта:\n"
"Базовая валюта модели: {base_currency}\n"
"Отображаемая валюта: {display_currency}\n"
"\n"
"Дай рекомендацию: какой сценарий наиболее вероятен и почему."
),
)
_current_lang = "ru"
_DEFAULT_LANG = "ru"
_current_lang = _DEFAULT_LANG
class Translator:
@@ -326,20 +339,39 @@ class Translator:
return template.format(**kwargs) if kwargs else template
_GLOBAL = Translator()
def _resolve_lang(lang: str | None = None) -> str:
"""Эффективный язык: запрошенный, если для него есть переводы, иначе ru.
Переводы существуют только для русского (словарь "en" пуст), поэтому
`CF_LANG=en` молча откатывается на `ru` — интерфейс остаётся русским.
Как только в словаре появится непустой перевод, он будет выбран.
"""
requested = lang if lang is not None else os.environ.get("CF_LANG", _DEFAULT_LANG)
if _TRANSLATIONS.get(requested):
return requested
return _DEFAULT_LANG
# Язык определяется ЗДЕСЬ, при импорте модуля, — до первого вызова t() в
# любом модуле CLI. Раньше язык выставлялся в setup_i18n(), который вызывался
# уже после импорта команд, поэтому CF_LANG не влиял на строки, собранные
# на этапе импорта (D20).
_current_lang = _resolve_lang()
_GLOBAL = Translator(_current_lang)
def setup_i18n() -> None:
lang = os.environ.get("CF_LANG", "ru")
if lang not in _TRANSLATIONS:
_TRANSLATIONS[lang] = {}
_GLOBAL.lang = lang
"""Переопределить язык по переменной окружения CF_LANG."""
global _current_lang
_current_lang = _resolve_lang()
_GLOBAL.lang = _current_lang
def set_lang(lang: str) -> None:
if lang not in _TRANSLATIONS:
_TRANSLATIONS[lang] = {}
_GLOBAL.lang = lang
"""Явно задать язык (с тем же откатом на ru, если переводов нет)."""
global _current_lang
_current_lang = _resolve_lang(lang)
_GLOBAL.lang = _current_lang
def get_lang() -> str:
+4
View File
@@ -1,5 +1,9 @@
"""Пути к данным и экспортам."""
from pathlib import Path
DATA_DIR: Path = Path("data")
MODEL_PATH: Path = DATA_DIR / "model.json"
# Каталог для экспортируемых .xlsx (по умолчанию — "./exports" относительно CWD).
EXPORTS_DIR: Path = Path("exports")
+27 -9
View File
@@ -1,14 +1,19 @@
"""Composition root + общие хелперы для CLI-команд."""
from __future__ import annotations
from decimal import Decimal
from typing import NoReturn
import typer
from pydantic import ValidationError
from rich.console import Console
from application.forecast import ForecastService
from application.scenarios import ScenarioService
from domain import CurrencyConverter, FinancialModel
from infrastructure.ai.assistant import AssistantService
from infrastructure.cli.i18n import t
from infrastructure.cli.paths import MODEL_PATH
from infrastructure.repositories import JsonFileRepository
@@ -17,6 +22,21 @@ console = Console()
_json_repo = JsonFileRepository()
def fail_validation(exc: ValidationError) -> NoReturn:
"""Показать ошибку валидации понятным сообщением и завершить команду.
Доменные модели валидируют и при присваивании (D17), поэтому «нельзя
положить отрицательный курс» — ожидаемая ошибка ввода, а не сбой
программы: пользователь получает понятное сообщение и код возврата 1
вместо traceback.
"""
details = "; ".join(
f"{'.'.join(str(part) for part in error['loc']) or 'значение'}: {error['msg']}" for error in exc.errors()
)
console.print(f"[red]{t('global.validation_error', error=details)}[/red]")
raise typer.Exit(1)
def load_model() -> FinancialModel:
if MODEL_PATH.exists():
return _json_repo.load(MODEL_PATH)
@@ -34,9 +54,7 @@ def build_services(
converter = CurrencyConverter(model.exchange_rates)
forecast_service = ForecastService(model)
scenario_service = ScenarioService(model)
assistant_service = AssistantService(
model, forecast_service=forecast_service, converter=converter
)
assistant_service = AssistantService(model, forecast_service=forecast_service, converter=converter)
return forecast_service, scenario_service, assistant_service, converter
@@ -47,9 +65,7 @@ def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str,
return target, symbol
def convert_value(
converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str
) -> Decimal:
def convert_value(converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str) -> Decimal:
if to_curr == from_curr:
return amount
return converter.convert(amount, from_curr, to_curr)
@@ -58,8 +74,10 @@ def convert_value(
def fmt_amount(amount: Decimal | float, currency: str, symbol: str = "") -> str:
"""Format money via the canonical display rule.
`symbol` is retained as a positional parameter for backward compatibility with
existing callers (compare.py / forecast.py / scenario.py / whatif.py); the
symbol/layout decision is centralised in `CurrencyConverter.format_money`.
`symbol` НЕ читается: символ и раскладку определяет
`CurrencyConverter.format_money` по коду валюты. Параметр оставлен только
ради совместимости с существующими вызовами
(compare.py / forecast.py / scenario.py / whatif.py), которые передают его
позиционно.
"""
return CurrencyConverter.format_money(amount, currency)
@@ -1,4 +1,9 @@
"""ExcelRepository — хранит FinancialModel в .xlsx (5 листов + ModelInfo)."""
"""ExcelRepository — хранит FinancialModel в .xlsx (6 листов данных + ModelInfo).
Листы данных: Accounts, Transactions, Recurring, Assets, Liabilities,
ExchangeRates. Плюс служебный лист ModelInfo (base_currency).
"""
from pathlib import Path
from uuid import UUID
@@ -89,6 +94,8 @@ class ExcelRepository(ModelRepository):
def save(self, model: FinancialModel, path: str | Path) -> None:
p = Path(path)
self._ensure_parent_dir(p)
wb = Workbook()
wb.remove(wb.active)
@@ -107,8 +114,7 @@ class ExcelRepository(ModelRepository):
ws.append(config["fields"])
for item in items:
row = [
str(getattr(item, f)) if isinstance(getattr(item, f), UUID)
else getattr(item, f)
str(getattr(item, f)) if isinstance(getattr(item, f), UUID) else getattr(item, f)
for f in config["fields"]
]
ws.append(row)
@@ -117,7 +123,23 @@ class ExcelRepository(ModelRepository):
ws_info.append(["Property", "Value"])
ws_info.append(["base_currency", model.base_currency])
wb.save(p)
try:
wb.save(p)
except OSError as e:
raise ExcelRepositoryError(f"Не удалось сохранить файл {p}: {e}") from e
@staticmethod
def _ensure_parent_dir(p: Path) -> None:
"""Создать родительский каталог файла, если его нет (D19).
Раньше экспорт в несуществующий каталог падал с сырым
`FileNotFoundError` из openpyxl — без понятного сообщения.
"""
parent = p.parent
try:
parent.mkdir(parents=True, exist_ok=True)
except OSError as e:
raise ExcelRepositoryError(f"Не удалось создать каталог {parent}: {e}") from e
def _add_to_model(self, model: FinancialModel, sheet_name: str, data: dict, cls) -> None:
try:
@@ -1,4 +1,5 @@
"""JsonFileRepository — хранит FinancialModel в .json (включая version)."""
import json
from pathlib import Path
+20
View File
@@ -14,6 +14,16 @@ dependencies = [
"pydantic>=2.0",
]
[project.optional-dependencies]
# Инструменты разработки: `pip install -e ".[dev]"`.
# ruff зафиксирован точной версией — вывод `ruff format` зависит от версии,
# иначе CI-гейт `ruff format --check .` может «поплыть» после обновления.
dev = [
"pytest>=8.0",
"ruff==0.17.2",
"coverage>=7.0",
]
[project.scripts]
cf = "infrastructure.cli.app:app"
@@ -29,3 +39,13 @@ select = ["E", "F", "I", "N", "W"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
[tool.coverage.run]
branch = true
source = ["application", "domain", "infrastructure"]
omit = ["*/tests/*"]
[tool.coverage.report]
show_missing = true
skip_covered = true
+37 -8
View File
@@ -1,3 +1,4 @@
from pathlib import Path
from uuid import uuid4
import pytest
@@ -14,6 +15,26 @@ from domain import (
)
@pytest.fixture(scope="session")
def repo_root() -> Path:
"""Корень репозитория (для проверок, что тесты не пишут в дерево)."""
return Path(__file__).resolve().parent.parent
@pytest.fixture(autouse=True)
def isolated_cwd(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Изоляция ФС: тесты не пишут в рабочее дерево репозитория.
CLI работает с относительными путями (`data/model.json`, `exports/...`),
поэтому достаточно перевести CWD во временный каталог — любой файл,
созданный командой, окажется в tmp_path, а не в дереве репозитория.
До D10 тесты писали в `./data/model.json` и `_cleanup()` удалял
отслеживаемый git файл.
"""
monkeypatch.chdir(tmp_path)
return tmp_path
@pytest.fixture
def sample_model() -> FinancialModel:
acc_id = uuid4()
@@ -25,24 +46,32 @@ def sample_model() -> FinancialModel:
],
transactions=[
Transaction(
date="2026-01-01", account=str(acc_id),
category="income", amount=3000.0,
date="2026-01-01",
account=str(acc_id),
category="income",
amount=3000.0,
description="Зарплата",
),
Transaction(
date="2026-01-05", account=str(acc_id),
category="rent", amount=-1200.0,
date="2026-01-05",
account=str(acc_id),
category="rent",
amount=-1200.0,
description="Аренда",
),
],
recurring=[
RecurringCashflow(
start_date="2026-01-01", frequency="monthly",
amount=500.0, category="income",
start_date="2026-01-01",
frequency="monthly",
amount=500.0,
category="income",
),
RecurringCashflow(
start_date="2026-01-01", frequency="monthly",
amount=-200.0, category="subscription",
start_date="2026-01-01",
frequency="monthly",
amount=-200.0,
category="subscription",
),
],
assets=[
+48
View File
@@ -17,3 +17,51 @@ class TestAssistantService:
result = assistant.advice("Как мне сэкономить?", months=6)
assert "prompt" in result
assert "ai_response" in result
class TestAssistantCompareScenarios:
"""Фиксация точного текста промпта сравнения сценариев.
Это характеристика существующего поведения: промпт меняется только
вместе с изменением шаблона в infrastructure/ai/prompts.py.
"""
def test_compare_scenarios_prompt_exact(self, sample_model):
assistant = AssistantService(sample_model, forecast_service=ForecastService(sample_model))
result = assistant.compare_scenarios('{"baseline": {"total_balance": "100.00"}}')
assert set(result) == {"prompt", "ai_response"}
assert result["ai_response"] is None
expected = (
"Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n"
"\n"
"### Результаты сценариев:\n"
'{"baseline": {"total_balance": "100.00"}}\n'
"\n"
"### Валюта:\n"
"Базовая валюта модели: RUB\n"
"Отображаемая валюта: RUB\n"
"\n"
"Дай рекомендацию: какой сценарий наиболее вероятен и почему."
)
assert result["prompt"] == expected
assert len(result["prompt"]) == 251
def test_compare_scenarios_uses_display_currency(self, sample_model):
assistant = AssistantService(
sample_model,
forecast_service=ForecastService(sample_model),
display_currency="USD",
)
prompt = assistant.compare_scenarios('{"baseline": {"total_balance": "100.00"}}')["prompt"]
assert "Отображаемая валюта: USD" in prompt
assert "Базовая валюта модели: RUB" in prompt
def test_compare_scenarios_embeds_given_json(self, sample_model):
scenarios_json = '{"optimistic": {"total_balance": "1.00"}, "pessimistic": {"total_balance": "2.00"}}'
assistant = AssistantService(sample_model, forecast_service=ForecastService(sample_model))
prompt = assistant.compare_scenarios(scenarios_json)["prompt"]
assert scenarios_json in prompt
+140 -47
View File
@@ -1,31 +1,24 @@
from pathlib import Path
from typer.testing import CliRunner
from infrastructure.cli.app import app
from infrastructure.cli.paths import MODEL_PATH
runner = CliRunner()
def _cleanup():
if MODEL_PATH.exists():
MODEL_PATH.unlink()
class TestCli:
def test_init(self):
_cleanup()
result = runner.invoke(app, ["init"])
assert result.exit_code == 0
assert "Пустая модель" in result.stdout
def test_forecast_after_init(self):
_cleanup()
runner.invoke(app, ["init"])
result = runner.invoke(app, ["forecast", "--months", "3"])
assert result.exit_code == 0
def test_forecast_with_currency(self):
_cleanup()
runner.invoke(app, ["init"])
result = runner.invoke(app, ["forecast", "--months", "3", "--currency", "USD"])
assert result.exit_code == 0
@@ -40,14 +33,12 @@ class TestCli:
assert result.exit_code == 0
def test_info_empty(self):
_cleanup()
runner.invoke(app, ["init"])
result = runner.invoke(app, ["info"])
assert result.exit_code == 0
assert "Базовая валюта" in result.stdout
def test_config_base_currency_set(self):
_cleanup()
runner.invoke(app, ["init"])
result = runner.invoke(app, ["config", "base-currency", "EUR"])
assert result.exit_code == 0
@@ -57,14 +48,12 @@ class TestCli:
assert "EUR" in info.stdout
def test_config_base_currency_show(self):
_cleanup()
runner.invoke(app, ["init"])
result = runner.invoke(app, ["config", "base-currency"])
assert result.exit_code == 0
assert "RUB" in result.stdout
def test_config_account_crud(self):
_cleanup()
runner.invoke(app, ["init"])
args = ["config", "account-add", "--name", "Тестовый", "--balance", "1000"]
@@ -82,17 +71,24 @@ class TestCli:
assert "Тестовый" not in lst2.stdout
def test_config_transaction_crud(self):
_cleanup()
runner.invoke(app, ["init"])
runner.invoke(app, ["config", "account-add", "--name", "Счёт", "--balance", "0"])
add = runner.invoke(app, [
"config", "transaction-add",
"--account", "Счёт",
"--amount", "5000",
"--category", "income",
"--description", "Зарплата",
])
add = runner.invoke(
app,
[
"config",
"transaction-add",
"--account",
"Счёт",
"--amount",
"5000",
"--category",
"income",
"--description",
"Зарплата",
],
)
assert add.exit_code == 0
assert "доход" in add.stdout
@@ -100,15 +96,21 @@ class TestCli:
assert "Зарплата" in lst.stdout
def test_config_asset_crud(self):
_cleanup()
runner.invoke(app, ["init"])
add = runner.invoke(app, [
"config", "asset-add",
"--name", "Квартира",
"--value", "5000000",
"--growth", "5",
])
add = runner.invoke(
app,
[
"config",
"asset-add",
"--name",
"Квартира",
"--value",
"5000000",
"--growth",
"5",
],
)
assert add.exit_code == 0
assert "Квартира" in add.stdout
@@ -116,36 +118,48 @@ class TestCli:
assert "Квартира" in lst.stdout
def test_config_liability_crud(self):
_cleanup()
runner.invoke(app, ["init"])
add = runner.invoke(app, [
"config", "liability-add",
"--name", "Кредит",
"--balance", "100000",
"--interest", "10",
"--payment", "5000",
])
add = runner.invoke(
app,
[
"config",
"liability-add",
"--name",
"Кредит",
"--balance",
"100000",
"--interest",
"10",
"--payment",
"5000",
],
)
assert add.exit_code == 0
assert "Кредит" in add.stdout
def test_config_recurring_crud(self):
_cleanup()
runner.invoke(app, ["init"])
add = runner.invoke(app, [
"config", "recurring-add",
"--amount", "-500",
"--category", "аренда",
"--frequency", "monthly",
])
add = runner.invoke(
app,
[
"config",
"recurring-add",
"--amount",
"-500",
"--category",
"аренда",
"--frequency",
"monthly",
],
)
assert add.exit_code == 0
lst = runner.invoke(app, ["config", "recurring-list"])
assert "аренда" in lst.stdout
def test_config_rate_crud(self):
_cleanup()
runner.invoke(app, ["init"])
set_r = runner.invoke(app, ["config", "rate-set", "EUR", "RUB", "90"])
@@ -156,14 +170,93 @@ class TestCli:
assert "90" in lst.stdout
def test_info_with_data(self):
_cleanup()
runner.invoke(app, ["init"])
acc_args = ["config", "account-add", "--name", "Основной", "--balance", "50000"]
runner.invoke(app, acc_args)
asset_args = ["config", "asset-add", "--name", "Акции",
"--value", "100000", "--growth", "8.0"]
asset_args = ["config", "asset-add", "--name", "Акции", "--value", "100000", "--growth", "8.0"]
runner.invoke(app, asset_args)
result = runner.invoke(app, ["info"])
assert "Основной" in result.stdout
assert "Акции" in result.stdout
class TestExportXlsx:
"""D19: `cf export-xlsx` в несуществующий каталог создаёт каталог."""
def test_export_creates_missing_directory(self, tmp_path: Path):
target = tmp_path / "missing" / "out.xlsx"
result = runner.invoke(app, ["export-xlsx", str(target)])
assert result.exit_code == 0
assert target.exists()
assert "Traceback" not in result.stdout
def test_export_default_path_creates_exports_dir(self, tmp_path: Path):
result = runner.invoke(app, ["export-xlsx"])
assert result.exit_code == 0
assert (tmp_path / "exports" / "forecast.xlsx").exists()
def test_export_to_unwritable_location_reports_error(self, tmp_path: Path):
blocker = tmp_path / "blocker"
blocker.write_text("not a directory", encoding="utf-8")
result = runner.invoke(app, ["export-xlsx", str(blocker / "out.xlsx")])
assert result.exit_code == 1
assert "Ошибка экспорта" in result.stdout
assert "Traceback" not in result.stdout
class TestValidationErrors:
"""D17: ошибка валидации — понятное сообщение и код 1, без traceback."""
def test_config_rate_set_with_negative_rate_fails_cleanly(self):
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "--", "-5"])
assert result.exit_code == 1
assert "Ошибка валидации" in result.stdout
assert "rate must be positive" in result.stdout
assert "Traceback" not in result.stdout
assert result.exception is None or isinstance(result.exception, SystemExit)
def test_config_rate_set_with_negative_rate_does_not_save_model(self):
runner.invoke(app, ["init"])
before = (Path.cwd() / "data" / "model.json").read_text(encoding="utf-8")
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "--", "-5"])
assert result.exit_code == 1
after = (Path.cwd() / "data" / "model.json").read_text(encoding="utf-8")
assert before == after, "Невалидный курс не должен сохраняться в модель"
def test_config_rate_set_stores_decimal_rate(self):
import json
runner.invoke(app, ["init"])
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "90"])
assert result.exit_code == 0
data = json.loads((Path.cwd() / "data" / "model.json").read_text(encoding="utf-8"))
rate = data["exchange_rates"][0]["rate"]
# Decimal сериализуется строкой, а не числом float.
assert isinstance(rate, str)
assert rate == "90.0"
def test_config_rate_set_with_valid_rate_succeeds(self):
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "90"])
assert result.exit_code == 0
assert "Traceback" not in result.stdout
class TestFilesystemIsolation:
"""Регрессии D10: CLI-тесты не пишут в дерево репозитория."""
def test_cli_writes_model_into_tmp_cwd(self, isolated_cwd: Path):
result = runner.invoke(app, ["init"])
assert result.exit_code == 0
assert (isolated_cwd / "data" / "model.json").exists()
def test_cli_does_not_touch_tracked_repo_files(self, repo_root: Path, isolated_cwd: Path):
tracked = repo_root / "data" / "model.json"
before = tracked.read_bytes() if tracked.exists() else None
result = runner.invoke(app, ["init"])
assert result.exit_code == 0
after = tracked.read_bytes() if tracked.exists() else None
assert before == after, "CLI-тест изменил отслеживаемый data/model.json в дереве репозитория"
+1
View File
@@ -6,6 +6,7 @@ CLI (D3 — удаление мёртвых typer.Typer(), D25 — разбие
на пакет): если набор изменился, поведение CLI изменилось без
согласования — тест обязан упасть.
"""
import typer
from typer.main import get_command
+115 -2
View File
@@ -50,9 +50,16 @@ class TestCurrencyConverter:
converter.set_rate("USD", "RUB", 0)
def test_inverse_auto(self):
# D15: конверсия больше не квантует, поэтому обратный курс (1/90) —
# бесконечная десятичная дробь, и результат НЕ ровно 10.
# До D15 quantize("0.01") скрывал это и давал ровно 10.00.
rate = ExchangeRate(from_currency="EUR", to_currency="RUB", rate=90.0)
converter = CurrencyConverter([rate])
assert converter.convert(900, "RUB", "EUR") == 10.0
result = converter.convert(900, "RUB", "EUR")
assert result == Decimal("9.999999999999999999999999999")
assert str(result) == "9.999999999999999999999999999"
# На отображении округление по знакам валюты даёт те же 10.00.
assert converter.format_money(result, "EUR") == "€10.00"
def test_get_symbol(self, sample_converter):
assert sample_converter.get_symbol("USD") == "$"
@@ -71,7 +78,9 @@ class TestCurrencyConverter:
converter = CurrencyConverter(rates)
assert converter.convert(10, "USD", "RUB") == 800.0
assert converter.convert(10, "EUR", "RUB") == 900.0
assert converter.convert(900, "RUB", "EUR") == 10.0
# D15: обратный курс EUR→RUB (1/90) даёт 9.999999999999999999999999999
# вместо прежних ровно 10.0 (раньше квантование скрывало погрешность).
assert converter.convert(900, "RUB", "EUR") == Decimal("9.999999999999999999999999999")
class TestFormatMoney:
@@ -110,3 +119,107 @@ class TestFormatMoney:
def test_case_insensitive_currency_code(self, sample_converter):
# Defensive: lower-case codes are accepted; storage stays upper-case.
assert sample_converter.format_money(Decimal("100"), "usd") == "$100.00"
class TestRoundingBoundaries:
"""Границы округления `.5` — текущее поведение (D11).
Режим округления — ROUND_HALF_UP (0.5 → 1, а не «к чётному»).
* `format_money` квантизует по числу знаков ISO 4217:
JPY — 0 знаков, BHD/KWD/OMR — 3 знака, остальные — 2;
неизвестный код → 2 знака (`DEFAULT_CURRENCY_DECIMALS`).
* `convert()` квантует результат до 2 знаков ROUND_HALF_UP
независимо от числа знаков целевой валюты (см. Tier 2 (D15) ниже).
"""
@pytest.mark.parametrize(
("amount", "currency", "expected"),
[
# USD — 2 знака, ROUND_HALF_UP
(Decimal("0.005"), "USD", "$0.01"),
(Decimal("0.015"), "USD", "$0.02"),
(Decimal("0.025"), "USD", "$0.03"),
(Decimal("1.005"), "USD", "$1.01"),
(Decimal("2.675"), "USD", "$2.68"),
(Decimal("100.999"), "USD", "$101.00"),
(Decimal("100.995"), "USD", "$101.00"),
# JPY — 0 знаков
(Decimal("0.5"), "JPY", "¥1"),
(Decimal("1.5"), "JPY", "¥2"),
(Decimal("2.5"), "JPY", "¥3"),
(Decimal("-0.5"), "JPY", "-¥1"),
# BHD — 3 знака, символа нет → префикс с пробелом
(Decimal("0.0005"), "BHD", "BHD 0.001"),
(Decimal("1.2345"), "BHD", "BHD 1.235"),
# Неизвестный код (CHF) — 2 знака по умолчанию
(Decimal("0.125"), "CHF", "CHF 0.13"),
# Знак минуса — перед символом
(Decimal("-0.005"), "USD", "-$0.01"),
(Decimal("-1.005"), "USD", "-$1.01"),
# RUB — 2 знака
(Decimal("0.5"), "RUB", "₽0.50"),
(Decimal("0.05"), "RUB", "₽0.05"),
],
)
def test_format_money_half_up_boundaries(self, amount, currency, expected):
assert CurrencyConverter.format_money(amount, currency) == expected
@pytest.mark.parametrize(
("amount", "expected", "expected_str"),
[
# USD→RUB, курс 80: точное умножение, БЕЗ quantize (D15).
(Decimal("0.005"), Decimal("0.4000"), "0.4000"),
(Decimal("0.015"), Decimal("1.2000"), "1.2000"),
(Decimal("0.125"), Decimal("10.0000"), "10.0000"),
(Decimal("2.675"), Decimal("214.0000"), "214.0000"),
(Decimal("1"), Decimal("80.0"), "80.0"),
],
)
def test_convert_keeps_full_precision(self, sample_converter, amount, expected, expected_str):
# D15: convert() больше не квантует результат — внутри остаётся полная
# точность Decimal. Значение равно прежнему, но представление другое:
# раньше было quantize("0.01"), теперь результат сохраняет точность
# произведения (0.005 * 80.0 = 0.4000, а не «0.40»).
result = sample_converter.convert(amount, "USD", "RUB")
assert result == expected
assert str(result) == expected_str
def test_convert_does_not_round_away_precision(self, sample_converter):
"""D15: конверсия не округляет результат до 2 знаков.
До D15 `convert()` квантовал до `Decimal("0.01")` и терял точность:
0.0001 USD → 0.01 вместо 0.00800.
"""
result = sample_converter.convert(Decimal("0.0001"), "USD", "RUB")
assert result == Decimal("0.00800")
assert str(result) == "0.00800"
# Курс с тремя знаками: 90.125 раньше превращался в 90.13.
precise = CurrencyConverter([ExchangeRate(from_currency="EUR", to_currency="RUB", rate=Decimal("90.125"))])
assert precise.convert(Decimal("1"), "EUR", "RUB") == Decimal("90.125")
def test_convert_to_jpy_has_no_intermediate_rounding(self):
"""D15: 0.1 USD → JPY = amount × rate без промежуточного округления."""
converter = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="JPY", rate=Decimal("80"))])
result = converter.convert(Decimal("0.1"), "USD", "JPY")
assert result == Decimal("8.0")
assert str(result) == "8.0"
# Курс 78.6: 0.1 * 78.6 = 7.86 — тоже без промежуточного округления.
by_786 = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="JPY", rate=Decimal("78.6"))])
assert by_786.convert(Decimal("0.1"), "USD", "JPY") == Decimal("7.86")
def test_format_money_rounds_after_conversion(self, sample_converter):
"""D15: округление — только при отображении, по знакам ISO 4217.
`convert()` даёт полную точность, `format_money()` округляет по числу
знаков целевой валюты.
"""
converted = sample_converter.convert(Decimal("0.0001"), "USD", "RUB")
assert str(converted) == "0.00800"
assert sample_converter.format_money(converted, "RUB") == "₽0.01"
# JPY — 0 знаков: 8.0 → «¥8».
jpy = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="JPY", rate=Decimal("80"))])
assert jpy.format_money(jpy.convert(Decimal("0.1"), "USD", "JPY"), "JPY") == "¥8"
+143
View File
@@ -1,8 +1,16 @@
from decimal import Decimal
from pathlib import Path
import pytest
from openpyxl import load_workbook
from domain import FinancialModel
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
# ВНИМАНИЕ: лист Scenarios НЕ поддерживается при экспорте/импорте .xlsx —
# сценарии прогноза теряются при round-trip. Это известное поведение,
# изменение — Tier 2 (D18). Намеренно здесь НЕ проверяется.
class TestExcelRepository:
def test_export_creates_file(self, sample_model, tmp_path: Path):
@@ -47,3 +55,138 @@ class TestExcelRepository:
p = tmp_path / "empty.xlsx"
repo.save(model, p)
assert p.exists()
class TestExportCreatesParentDir:
"""D19: экспорт в несуществующий каталог создаёт каталог и пишет файл.
Раньше `cf export-xlsx exports/report.xlsx` в каталоге без `exports/`
падал с сырым `FileNotFoundError` из openpyxl.
"""
def test_save_creates_missing_parent_dir(self, sample_model, tmp_path: Path):
repo = ExcelRepository()
target = tmp_path / "nested" / "deeper" / "out.xlsx"
assert not target.parent.exists()
repo.save(sample_model, target)
assert target.parent.is_dir()
assert target.exists()
def test_save_to_bare_filename_in_cwd(self, sample_model, tmp_path: Path, monkeypatch):
repo = ExcelRepository()
monkeypatch.chdir(tmp_path)
repo.save(sample_model, "out.xlsx")
assert (tmp_path / "out.xlsx").exists()
def test_save_reports_unreadable_parent_as_domain_error(self, sample_model, tmp_path: Path):
# Родительский путь занят файлом — каталог создать нельзя.
blocker = tmp_path / "blocker"
blocker.write_text("not a directory", encoding="utf-8")
repo = ExcelRepository()
with pytest.raises(ExcelRepositoryError) as exc_info:
repo.save(sample_model, blocker / "out.xlsx")
message = str(exc_info.value)
assert "Не удалось создать каталог" in message
assert "blocker" in message
assert not isinstance(exc_info.value, FileNotFoundError)
class TestExcelRoundTripByValues:
"""Round-trip .xlsx ПО ЗНАЧЕНИЯМ, а не только по количеству строк (D11).
Тесты-характеристики: фиксируют текущее поведение ExcelRepository.
Числа сравниваются по значению (Decimal("5000") == Decimal("5000.00")),
а не по записи (числу знаков/экспоненте).
"""
@staticmethod
def _roundtrip(sample_model, tmp_path: Path):
"""Сохранить модель в .xlsx и прочитать её обратно."""
repo = ExcelRepository()
p = tmp_path / "values.xlsx"
repo.save(sample_model, p)
return repo.load(p)
def test_base_currency_value(self, sample_model, tmp_path: Path):
loaded = self._roundtrip(sample_model, tmp_path)
assert loaded.base_currency == "RUB"
def test_accounts_values(self, sample_model, tmp_path: Path):
loaded = self._roundtrip(sample_model, tmp_path)
assert len(loaded.accounts) == 2
assert [a.name for a in loaded.accounts] == ["Основной счёт", "Сбережения"]
assert [a.currency for a in loaded.accounts] == ["RUB", "RUB"]
# Сравнение по значению: Decimal("5000") == Decimal("5000.00").
assert loaded.accounts[0].balance == Decimal("5000")
assert loaded.accounts[1].balance == Decimal("10000")
def test_account_id_is_preserved(self, sample_model, tmp_path: Path):
loaded = self._roundtrip(sample_model, tmp_path)
assert str(loaded.accounts[0].id) == str(sample_model.accounts[0].id)
def test_transactions_values(self, sample_model, tmp_path: Path):
loaded = self._roundtrip(sample_model, tmp_path)
assert len(loaded.transactions) == 2
assert [t.date for t in loaded.transactions] == ["2026-01-01", "2026-01-05"]
assert [t.category for t in loaded.transactions] == ["income", "rent"]
assert loaded.transactions[0].amount == Decimal("3000")
assert loaded.transactions[1].amount == Decimal("-1200")
assert [t.description for t in loaded.transactions] == ["Зарплата", "Аренда"]
# Ссылка на счёт хранится строкой с UUID основного счёта.
assert loaded.transactions[0].account == str(sample_model.accounts[0].id)
assert loaded.transactions[1].account == str(sample_model.accounts[0].id)
def test_recurring_values(self, sample_model, tmp_path: Path):
loaded = self._roundtrip(sample_model, tmp_path)
assert len(loaded.recurring) == 2
assert [r.frequency for r in loaded.recurring] == ["monthly", "monthly"]
assert loaded.recurring[0].amount == Decimal("500")
assert loaded.recurring[1].amount == Decimal("-200")
assert [r.category for r in loaded.recurring] == ["income", "subscription"]
assert [r.start_date for r in loaded.recurring] == ["2026-01-01", "2026-01-01"]
assert [r.end_date for r in loaded.recurring] == ["", ""]
def test_assets_values(self, sample_model, tmp_path: Path):
loaded = self._roundtrip(sample_model, tmp_path)
assert len(loaded.assets) == 1
assert loaded.assets[0].name == "Акции"
assert loaded.assets[0].value == Decimal("50000")
assert loaded.assets[0].growth_rate == Decimal("8")
def test_liabilities_values(self, sample_model, tmp_path: Path):
loaded = self._roundtrip(sample_model, tmp_path)
assert len(loaded.liabilities) == 1
assert loaded.liabilities[0].name == "Кредит"
assert loaded.liabilities[0].balance == Decimal("20000")
assert loaded.liabilities[0].interest == Decimal("5")
assert loaded.liabilities[0].payment == Decimal("500")
def test_exchange_rates_values(self, sample_model, tmp_path: Path):
loaded = self._roundtrip(sample_model, tmp_path)
assert len(loaded.exchange_rates) == 1
assert loaded.exchange_rates[0].from_currency == "USD"
assert loaded.exchange_rates[0].to_currency == "RUB"
assert loaded.exchange_rates[0].rate == Decimal("80")
def test_written_sheet_names(self, sample_model, tmp_path: Path):
repo = ExcelRepository()
p = tmp_path / "sheets.xlsx"
repo.save(sample_model, p)
wb = load_workbook(p)
try:
assert wb.sheetnames == [
"Accounts",
"Transactions",
"Recurring",
"Assets",
"Liabilities",
"ExchangeRates",
"ModelInfo",
]
finally:
wb.close()
+154
View File
@@ -1,7 +1,12 @@
from decimal import Decimal
import pytest
from application.forecast import ForecastError, ForecastService
_MAIN_ACCOUNT = "Основной счёт"
_SAVINGS_ACCOUNT = "Сбережения"
class TestForecastService:
def test_forecast_returns_results(self, sample_model):
@@ -34,3 +39,152 @@ class TestForecastService:
service = ForecastService(empty_model)
results = service.forecast_cashflow(months=3)
assert results == []
class TestForecastCharacterization:
"""Фиксация текущих чисел движка прогноза.
Это характеристика существующего поведения, а не спецификация: числа
меняются только вместе с изменением самого движка. Движок мутирует
свои assets/liabilities (известная проблема Tier 2, D14), поэтому все
проверки ниже выполняются на СВЕЖЕМ экземпляре ForecastService.
"""
def test_forecast_cashflow_12_months_exact_values(self, sample_model):
service = ForecastService(sample_model)
results = service.forecast_cashflow(months=12)
# Порядок строк: сначала все 12 месяцев «Основного счёта»,
# затем все 12 месяцев «Сбережений».
expected = [
(_MAIN_ACCOUNT, 1, Decimal("7152.22"), Decimal("3635.55"), Decimal("1483.33")),
(_MAIN_ACCOUNT, 2, Decimal("9190.44"), Decimal("3655.37"), Decimal("1481.60")),
(_MAIN_ACCOUNT, 3, Decimal("11226.72"), Decimal("3671.50"), Decimal("1479.85")),
(_MAIN_ACCOUNT, 4, Decimal("13262.08"), Decimal("3684.97"), Decimal("1478.10")),
(_MAIN_ACCOUNT, 5, Decimal("15297.25"), Decimal("3696.48"), Decimal("1476.35")),
(_MAIN_ACCOUNT, 6, Decimal("17332.67"), Decimal("3706.48"), Decimal("1474.58")),
(_MAIN_ACCOUNT, 7, Decimal("19368.69"), Decimal("3715.31"), Decimal("1472.81")),
(_MAIN_ACCOUNT, 8, Decimal("21405.57"), Decimal("3723.22"), Decimal("1471.03")),
(_MAIN_ACCOUNT, 9, Decimal("23443.48"), Decimal("3730.37"), Decimal("1469.24")),
(_MAIN_ACCOUNT, 10, Decimal("25482.59"), Decimal("3736.92"), Decimal("1467.45")),
(_MAIN_ACCOUNT, 11, Decimal("27522.98"), Decimal("3742.96"), Decimal("1465.64")),
(_MAIN_ACCOUNT, 12, Decimal("29564.76"), Decimal("3748.57"), Decimal("1463.83")),
(_SAVINGS_ACCOUNT, 1, Decimal("10435.76"), Decimal("697.78"), Decimal("262.02")),
(_SAVINGS_ACCOUNT, 2, Decimal("10657.97"), Decimal("680.18"), Decimal("260.19")),
(_SAVINGS_ACCOUNT, 3, Decimal("10885.72"), Decimal("666.29"), Decimal("258.36")),
(_SAVINGS_ACCOUNT, 4, Decimal("11117.99"), Decimal("655.07"), Decimal("256.52")),
(_SAVINGS_ACCOUNT, 5, Decimal("11354.08"), Decimal("645.83"), Decimal("254.67")),
(_SAVINGS_ACCOUNT, 6, Decimal("11593.54"), Decimal("638.11"), Decimal("252.81")),
(_SAVINGS_ACCOUNT, 7, Decimal("11836.06"), Decimal("631.58"), Decimal("250.95")),
(_SAVINGS_ACCOUNT, 8, Decimal("12081.39"), Decimal("625.99"), Decimal("249.08")),
(_SAVINGS_ACCOUNT, 9, Decimal("12329.36"), Decimal("621.16"), Decimal("247.20")),
(_SAVINGS_ACCOUNT, 10, Decimal("12579.84"), Decimal("616.96"), Decimal("245.32")),
(_SAVINGS_ACCOUNT, 11, Decimal("12832.74"), Decimal("613.28"), Decimal("243.42")),
(_SAVINGS_ACCOUNT, 12, Decimal("13087.98"), Decimal("610.04"), Decimal("241.52")),
]
actual = [(r["account"], r["month"], r["balance"], r["income"], r["expenses"]) for r in results]
assert len(results) == 24
assert actual == expected
def test_summary_6_exact_values(self, sample_model):
service = ForecastService(sample_model)
assert service.summary(months=6) == {
"total_balance": Decimal("11527.64"),
"total_income": Decimal("26033.66"),
"total_expenses": Decimal("10483.81"),
"months": 6,
}
def test_summary_12_exact_values(self, sample_model):
service = ForecastService(sample_model)
assert service.summary(months=12) == {
"total_balance": Decimal("13087.98"),
"total_income": Decimal("52149.97"),
"total_expenses": Decimal("20705.87"),
"months": 12,
}
def test_repeated_forecast_is_idempotent(self, sample_model):
# D14: движок больше не мутирует свои assets/liabilities, поэтому
# повторный forecast_cashflow на ТОМ ЖЕ экземпляре сервиса даёт
# идентичный результат. До D14 второй вызов давал 13649.62 вместо
# 13087.98 (сумма 368465.98 вместо 361041.88).
service = ForecastService(sample_model)
first = service.forecast_cashflow(months=12)
second = service.forecast_cashflow(months=12)
assert first == second
assert first[-1]["balance"] == Decimal("13087.98")
assert second[-1]["balance"] == Decimal("13087.98")
assert sum(r["balance"] for r in first) == Decimal("361041.88")
assert sum(r["balance"] for r in second) == Decimal("361041.88")
def test_forecast_does_not_mutate_model(self, sample_model):
# D14: модель сервиса после прогноза байт-в-байт та же, что до.
service = ForecastService(sample_model)
before = service.model.model_dump_json()
service.forecast_cashflow(months=12)
service.summary(months=12)
assert service.model.model_dump_json() == before
# И модель, переданная в сервис, тоже не меняется (сервис работает
# на копии — и не трогает оригинал).
original = sample_model.model_dump_json()
ForecastService(sample_model).forecast_cashflow(months=12)
assert sample_model.model_dump_json() == original
def test_summary_after_forecast_matches_summary_alone(self, sample_model):
# D14: сводка больше не расходится с прогнозом. До D14 после двух
# прогнозов summary давал 13730.60 / 52867.46 / 19200.00 вместо
# 13087.98 / 52149.97 / 20705.87.
service = ForecastService(sample_model)
service.forecast_cashflow(months=12)
service.forecast_cashflow(months=12)
summary = service.summary(months=12)
assert summary == {
"total_balance": Decimal("13087.98"),
"total_income": Decimal("52149.97"),
"total_expenses": Decimal("20705.87"),
"months": 12,
}
# На свежем экземпляре — те же числа.
fresh = ForecastService(sample_model)
assert fresh.summary(months=12)["total_balance"] == Decimal("13087.98")
def test_summary_total_balance_is_last_table_row(self, sample_model):
# D14: «Итог» в CLI обязан совпадать с последней строкой таблицы —
# сводка считается по тому же набору результатов.
service = ForecastService(sample_model)
results = service.forecast_cashflow(months=12)
summary = service.summary(months=12, results=results)
assert summary["total_balance"] == results[-1]["balance"]
# Сводка без переданных результатов даёт то же самое (расчёт идемпотентен).
assert service.summary(months=12) == summary
def test_forecast_output_is_quantized_to_two_decimals(self, sample_model):
# D15: округление в прогнозе осталось только в точке сериализации
# (`_q()`), поэтому JSON-вывод стабилен: все денежные значения —
# ровно два знака после запятой.
service = ForecastService(sample_model)
results = service.forecast_cashflow(months=12)
assert results
for row in results:
for key in ("balance", "income", "expenses"):
assert row[key].as_tuple().exponent == -2
summary = service.summary(months=12)
for key in ("total_balance", "total_income", "total_expenses"):
assert summary[key].as_tuple().exponent == -2
def test_horizon_changes_numbers(self, sample_model):
# Стоимость обязательства амортизируется по одному вызову на каждый
# (счёт × месяц), поэтому суммарное число вызовов зависит от
# горизонта — это текущее поведение (Tier 2, D16).
six = ForecastService(sample_model).summary(months=6)
twelve = ForecastService(sample_model).summary(months=12)
assert six["total_balance"] == Decimal("11527.64")
assert twelve["total_balance"] == Decimal("13087.98")
+90 -2
View File
@@ -1,4 +1,15 @@
from infrastructure.cli.i18n import Translator, get_lang, set_lang, setup_i18n, t
import os
import subprocess
import sys
from infrastructure.cli.i18n import (
_TRANSLATIONS,
Translator,
get_lang,
set_lang,
setup_i18n,
t,
)
class TestTranslator:
@@ -20,9 +31,16 @@ class TestTranslator:
assert tr.t("nonexistent.key") == "nonexistent.key"
def test_set_lang(self):
# D20: язык, для которого нет переводов, молча откатывается на ru
# (словарь "en" пуст), поэтому эффективный язык — ru.
setup_i18n()
set_lang("en")
assert get_lang() == "en"
assert get_lang() == "ru"
def test_set_lang_ru(self):
setup_i18n()
set_lang("ru")
assert get_lang() == "ru"
def test_t_function(self):
setup_i18n()
@@ -42,3 +60,73 @@ class TestTranslator:
tr = Translator("de")
result = tr.t("cmd.init.help")
assert "финансовую" in result # fallback to ru
class TestUserFacingPaths:
"""D21: пути в пользовательских строках указывают на существующие файлы."""
def test_analyze_stub_points_to_existing_file(self, repo_root):
import re
message = t("cmd.analyze.stub")
paths = re.findall(r"[\w/]+\.py", message)
assert paths, f"В строке не найден путь: {message!r}"
for rel_path in paths:
assert (repo_root / rel_path).is_file(), f"Путь {rel_path} не существует"
def test_analyze_stub_mentions_real_assistant_path(self):
assert "infrastructure/ai/assistant.py" in t("cmd.analyze.stub")
class TestCfLang:
"""D20: `CF_LANG` определяется до первого вызова `t()`."""
def test_default_language_is_ru(self, monkeypatch):
monkeypatch.delenv("CF_LANG", raising=False)
setup_i18n()
assert get_lang() == "ru"
def test_cf_lang_en_falls_back_to_ru(self, monkeypatch):
# Словарь "en" пуст — откат на ru без предупреждения.
monkeypatch.setenv("CF_LANG", "en")
setup_i18n()
assert get_lang() == "ru"
assert "финансовую" in t("cmd.init.help")
def test_cf_lang_unknown_value_falls_back_to_ru(self, monkeypatch):
monkeypatch.setenv("CF_LANG", "de")
setup_i18n()
assert get_lang() == "ru"
def test_language_with_translations_is_selected(self, monkeypatch):
# Механизм рабочий: как только в словаре появляется перевод,
# он выбирается по CF_LANG.
monkeypatch.setenv("CF_LANG", "en")
monkeypatch.setitem(_TRANSLATIONS, "en", {"cmd.init.help": "Create an empty financial model"})
try:
setup_i18n()
assert get_lang() == "en"
assert t("cmd.init.help") == "Create an empty financial model"
finally:
_TRANSLATIONS["en"] = {}
setup_i18n()
assert get_lang() == "ru"
def test_cf_lang_is_resolved_at_import_time(self, repo_root):
# t() вызывается на этапе импорта модулей команд — язык должен быть
# определён уже тогда, иначе CF_LANG не влияет на вывод.
code = "from infrastructure.cli.i18n import get_lang, t;print(get_lang());print(t('cmd.init.help'))"
env = dict(os.environ)
env["CF_LANG"] = "en"
env["PYTHONPATH"] = str(repo_root)
proc = subprocess.run(
[sys.executable, "-c", code],
env=env,
cwd=str(repo_root),
capture_output=True,
text=True,
)
assert proc.returncode == 0, proc.stderr
lines = proc.stdout.strip().splitlines()
assert lines[0] == "ru"
assert "финансовую" in lines[1]
+311
View File
@@ -1,5 +1,9 @@
from decimal import Decimal
from pathlib import Path
from uuid import UUID
import pytest
from pydantic import ValidationError
from domain import (
Account,
@@ -60,6 +64,7 @@ class TestFinancialModel:
def test_base_currency_backward_compat(self, tmp_path: Path):
import json
p = tmp_path / "legacy.json"
with open(p, "w") as f:
json.dump({"accounts": []}, f)
@@ -115,3 +120,309 @@ class TestFinancialModel:
assert len(loaded.liabilities) == 1
assert len(loaded.scenarios) == 1
assert len(loaded.exchange_rates) == 1
class TestValidateAssignment:
"""D17: модели домена валидируют присваивание (validate_assignment=True).
Раньше `r.rate = -5` молча принимался, а `config_cmd.py` писал в поле
Decimal значение типа float — валидатор при этом не срабатывал.
"""
def test_negative_rate_is_rejected_on_assignment(self):
rate = ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))
with pytest.raises(ValidationError) as exc_info:
rate.rate = Decimal("-5")
assert "rate must be positive" in str(exc_info.value)
# Значение не изменилось — невалидное присваивание отклонено целиком.
assert rate.rate == Decimal("80")
def test_zero_rate_is_rejected_on_assignment(self):
rate = ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))
with pytest.raises(ValidationError):
rate.rate = Decimal("0")
assert rate.rate == Decimal("80")
def test_float_in_decimal_field_does_not_stay_float(self):
# Присваивание float в поле Decimal не «проходит» как float:
# значение приводится к объявленному типу (Decimal) валидатором.
rate = ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))
rate.rate = 90.5
assert isinstance(rate.rate, Decimal)
assert not isinstance(rate.rate, float)
assert rate.rate == Decimal("90.5")
def test_account_balance_rejected_on_assignment(self):
account = Account(name="A", balance=Decimal("100"))
with pytest.raises(ValidationError) as exc_info:
account.balance = Decimal("-1")
assert "balance must be non-negative" in str(exc_info.value)
assert account.balance == Decimal("100")
def test_transaction_amount_rejected_on_assignment(self):
txn = Transaction(amount=Decimal("100"))
with pytest.raises(ValidationError) as exc_info:
txn.amount = Decimal("0")
assert "amount must be non-zero" in str(exc_info.value)
assert txn.amount == Decimal("100")
def test_recurring_amount_and_frequency_rejected_on_assignment(self):
recurring = RecurringCashflow(amount=Decimal("100"), frequency="monthly")
with pytest.raises(ValidationError):
recurring.amount = Decimal("0")
with pytest.raises(ValidationError):
recurring.frequency = "hourly"
assert recurring.amount == Decimal("100")
assert recurring.frequency == "monthly"
def test_liability_interest_and_payment_rejected_on_assignment(self):
liability = Liability(name="L", balance=Decimal("100"), interest=Decimal("5"), payment=Decimal("10"))
with pytest.raises(ValidationError):
liability.interest = Decimal("-1")
with pytest.raises(ValidationError):
liability.payment = Decimal("-1")
assert liability.interest == Decimal("5")
assert liability.payment == Decimal("10")
def test_scenario_multiplier_rejected_on_assignment(self):
scenario = ForecastScenario(name="s", income_multiplier=Decimal("1"))
with pytest.raises(ValidationError):
scenario.income_multiplier = Decimal("-1")
assert scenario.income_multiplier == Decimal("1")
def test_financial_model_assignment_is_validated(self):
model = FinancialModel()
model.base_currency = "EUR"
assert model.base_currency == "EUR"
with pytest.raises(ValidationError):
model.exchange_rates = [ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("-1"))]
class TestSchemaVersion:
"""Регрессии D9: SCHEMA_VERSION — ClassVar, а не поле pydantic.
Формат файла состояния (`to_dict()`) не меняется: там по-прежнему
пишется `{"version": 1, ...}`.
"""
def test_schema_version_is_not_a_pydantic_field(self):
assert "SCHEMA_VERSION" not in FinancialModel.model_fields
assert FinancialModel.SCHEMA_VERSION == 1
def test_schema_version_cannot_be_overridden_at_construction(self):
# Раньше `SCHEMA_VERSION: int = 1` было полем, и значение принималось
# в конструктор. Теперь лишний kwargs игнорируется, версия — 1.
model = FinancialModel(SCHEMA_VERSION=99)
assert FinancialModel.SCHEMA_VERSION == 1
assert model.SCHEMA_VERSION == 1
assert model.to_dict()["version"] == 1
assert "SCHEMA_VERSION" not in model.model_dump()
def test_to_dict_version_and_key_set(self):
d = FinancialModel().to_dict()
assert d["version"] == 1
assert set(d.keys()) == {
"version",
"base_currency",
"accounts",
"transactions",
"recurring",
"assets",
"liabilities",
"scenarios",
"exchange_rates",
}
def test_to_dict_from_dict_roundtrip(self):
model = FinancialModel(
base_currency="EUR",
accounts=[Account(name="A", currency="EUR", balance=Decimal("10.5"))],
transactions=[Transaction(amount=Decimal("-3.25"), category="rent")],
recurring=[RecurringCashflow(amount=Decimal("7"), frequency="weekly")],
assets=[Asset(name="S", value=Decimal("100"), growth_rate=Decimal("8.5"))],
liabilities=[Liability(name="L", balance=Decimal("50"), interest=Decimal("5"), payment=Decimal("1"))],
scenarios=[ForecastScenario(name="sc")],
exchange_rates=[ExchangeRate(from_currency="EUR", to_currency="RUB", rate=Decimal("90"))],
)
restored = FinancialModel.from_dict(model.to_dict())
assert restored.to_dict() == model.to_dict()
assert restored.base_currency == "EUR"
assert restored.accounts[0].balance == Decimal("10.5")
assert restored.transactions[0].amount == Decimal("-3.25")
def test_from_dict_accepts_legacy_without_version(self):
restored = FinancialModel.from_dict({"base_currency": "USD", "accounts": []})
assert restored.base_currency == "USD"
assert restored.accounts == []
def test_from_dict_rejects_unknown_version(self):
with pytest.raises(ValueError):
FinancialModel.from_dict({"version": 2})
class TestPydanticValidators:
"""Фиксация текущего поведения всех 7 валидаторов pydantic в домене (D11).
Это тесты-характеристики: они фиксируют ТЕКУЩЕЕ поведение как есть.
Валидаторы НЕ «чинятся» — если текст ошибки изменится, тесты нужно будет
переписать осознанно.
Проверяется и сообщение об ошибке, чтобы из `ValidationError` было видно,
какой именно валидатор сработал.
"""
# --- 1. Account.balance — неотрицательный ---
def test_account_balance_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
Account(balance=Decimal("-1"))
assert "balance must be non-negative" in str(exc_info.value)
def test_account_balance_allows_zero(self):
assert Account(balance=Decimal("0")).balance == Decimal("0")
def test_account_balance_rejects_small_negative(self):
with pytest.raises(ValidationError) as exc_info:
Account(balance=Decimal("-0.01"))
assert "balance must be non-negative" in str(exc_info.value)
# --- 2. Transaction.amount — ненулевой (отрицательные разрешены) ---
def test_transaction_amount_rejects_zero(self):
with pytest.raises(ValidationError) as exc_info:
Transaction(amount=Decimal("0"))
assert "amount must be non-zero" in str(exc_info.value)
def test_transaction_amount_allows_negative(self):
# Расходы записываются отрицательными суммами — это валидное значение.
assert Transaction(amount=Decimal("-0.01")).amount == Decimal("-0.01")
# --- 3. RecurringCashflow.frequency — из фиксированного множества ---
def test_recurring_frequency_allows_known_value(self):
assert RecurringCashflow(frequency="monthly").frequency == "monthly"
def test_recurring_frequency_rejects_unknown_value(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(frequency="hourly")
assert "unknown frequency: hourly" in str(exc_info.value)
def test_recurring_frequency_rejects_empty_string(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(frequency="")
assert "unknown frequency:" in str(exc_info.value)
# --- 4. RecurringCashflow.amount — ненулевой ---
def test_recurring_amount_rejects_zero(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(amount=Decimal("0"))
assert "amount must be non-zero" in str(exc_info.value)
def test_recurring_amount_allows_non_zero(self):
assert RecurringCashflow(amount=Decimal("1")).amount == Decimal("1")
# --- 5. Liability.interest / Liability.payment — неотрицательные ---
def test_liability_interest_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
Liability(interest=Decimal("-1"))
text = str(exc_info.value)
assert "must be non-negative" in text
assert "interest" in text
def test_liability_payment_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
Liability(payment=Decimal("-1"))
text = str(exc_info.value)
assert "must be non-negative" in text
assert "payment" in text
def test_liability_allows_zero_interest_and_payment(self):
liab = Liability(interest=Decimal("0"), payment=Decimal("0"))
assert liab.interest == Decimal("0")
assert liab.payment == Decimal("0")
# --- 6. ForecastScenario — множители неотрицательные ---
def test_scenario_income_multiplier_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ForecastScenario(income_multiplier=Decimal("-1"))
text = str(exc_info.value)
assert "multiplier must be non-negative" in text
assert "income_multiplier" in text
def test_scenario_expense_multiplier_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ForecastScenario(expense_multiplier=Decimal("-1"))
text = str(exc_info.value)
assert "multiplier must be non-negative" in text
assert "expense_multiplier" in text
def test_scenario_growth_multiplier_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ForecastScenario(growth_multiplier=Decimal("-1"))
text = str(exc_info.value)
assert "multiplier must be non-negative" in text
assert "growth_multiplier" in text
def test_scenario_allows_zero_multipliers(self):
scenario = ForecastScenario(
income_multiplier=Decimal("0"),
expense_multiplier=Decimal("0"),
growth_multiplier=Decimal("0"),
)
assert scenario.income_multiplier == Decimal("0")
assert scenario.expense_multiplier == Decimal("0")
assert scenario.growth_multiplier == Decimal("0")
# --- 7. ExchangeRate.rate — строго положительный ---
def test_exchange_rate_rejects_zero(self):
with pytest.raises(ValidationError) as exc_info:
ExchangeRate(rate=Decimal("0"))
assert "rate must be positive" in str(exc_info.value)
def test_exchange_rate_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ExchangeRate(rate=Decimal("-1"))
assert "rate must be positive" in str(exc_info.value)
def test_exchange_rate_allows_small_positive(self):
assert ExchangeRate(rate=Decimal("0.01")).rate == Decimal("0.01")
class TestDecimalCoercionAndIds:
"""Приведение типов и идентификаторы сущностей — текущее поведение (D11)."""
def test_decimal_fields_accept_strings(self):
# pydantic v2 в нестрогом режиме приводит строку к Decimal без потери
# точности (Decimal("100.50"), а не float).
assert Account(balance="100.50").balance == Decimal("100.50")
assert Transaction(amount="-12.34").amount == Decimal("-12.34")
assert RecurringCashflow(amount="7.25").amount == Decimal("7.25")
assert Asset(value="1000.5").value == Decimal("1000.5")
assert Liability(balance="500.75").balance == Decimal("500.75")
assert ForecastScenario(income_multiplier="1.5").income_multiplier == Decimal("1.5")
assert ExchangeRate(rate="90.25").rate == Decimal("90.25")
def test_entities_have_uuid_ids(self):
# У всех сущностей, кроме ExchangeRate, есть поле id типа UUID.
for entity in (
Account(),
Transaction(),
RecurringCashflow(),
Asset(),
Liability(),
ForecastScenario(),
):
assert isinstance(entity.id, UUID)
# str(UUID) — валидный UUID, который можно разобрать обратно.
assert UUID(str(entity.id)) == entity.id
def test_exchange_rate_has_no_id_field(self):
# В отличие от остальных сущностей, у ExchangeRate поля id нет
# (в листе ExchangeRates тоже нет колонки id — только from/to/rate).
assert "id" not in ExchangeRate.model_fields
assert not hasattr(ExchangeRate(), "id")
+2 -3
View File
@@ -29,6 +29,7 @@ class TestJsonFileRepository:
p = tmp_path / "v.json"
repo.save(model, p)
import json
with open(p) as f:
data = json.load(f)
assert data["version"] == 1
@@ -46,9 +47,7 @@ class TestJsonFileRepository:
def test_decimal_preserved(self, tmp_path: Path):
repo = JsonFileRepository()
model = FinancialModel(
assets=[Asset(name="Stocks", value=Decimal("12345.67"), growth_rate=Decimal("8.5"))]
)
model = FinancialModel(assets=[Asset(name="Stocks", value=Decimal("12345.67"), growth_rate=Decimal("8.5"))])
p = tmp_path / "decimal.json"
repo.save(model, p)
loaded = repo.load(p)
+101
View File
@@ -1,5 +1,17 @@
from decimal import Decimal
from application.scenarios import DEFAULT_SCENARIOS, ScenarioService
_BALANCE = "total_balance"
_INCOME = "total_income"
_EXPENSES = "total_expenses"
_DESCRIPTIONS = {
"baseline": "Базовый сценарий без изменений",
"optimistic": "Оптимистичный: доход +15%, расход -5%, рост активов +20%",
"pessimistic": "Пессимистичный: доход -15%, расход +10%, рост активов -20%",
}
class TestScenarioService:
def test_baseline(self, sample_model):
@@ -19,3 +31,92 @@ class TestScenarioService:
service = ScenarioService(sample_model)
result = service.what_if(income_mult=1.2, expense_mult=0.9, months=6)
assert result["scenario"] == "what-if"
class TestScenarioCharacterization:
"""Фиксация текущих чисел сервиса сценариев.
Это характеристика существующего поведения, а не спецификация: числа
меняются только вместе с изменением самого движка прогноза.
"""
def test_default_scenarios_numbers_6_months(self, sample_model):
expected = {
"baseline": (Decimal("11527.64"), Decimal("26033.66"), Decimal("10483.81")),
"optimistic": (Decimal("12051.96"), Decimal("30048.49"), Decimal("10003.81")),
"pessimistic": (Decimal("10943.69"), Decimal("22021.49"), Decimal("11443.81")),
}
for name, scenario in DEFAULT_SCENARIOS.items():
# СВЕЖИЙ ScenarioService на каждый сценарий.
result = ScenarioService(sample_model).apply(scenario, months=6)
assert result["scenario"] == name
assert result["scenario_description"] == _DESCRIPTIONS[name]
assert result["months"] == 6
assert (
result[_BALANCE],
result[_INCOME],
result[_EXPENSES],
) == expected[name]
def test_default_scenarios_numbers_12_months(self, sample_model):
expected = {
"baseline": (Decimal("13087.98"), Decimal("52149.97"), Decimal("20705.87")),
"optimistic": (Decimal("14119.08"), Decimal("60216.93"), Decimal("19745.87")),
"pessimistic": (Decimal("11938.83"), Decimal("44095.56"), Decimal("22625.87")),
}
for name, scenario in DEFAULT_SCENARIOS.items():
# СВЕЖИЙ ScenarioService на каждый сценарий.
result = ScenarioService(sample_model).apply(scenario, months=12)
assert result["scenario"] == name
assert result["scenario_description"] == _DESCRIPTIONS[name]
assert result["months"] == 12
assert (
result[_BALANCE],
result[_INCOME],
result[_EXPENSES],
) == expected[name]
def test_what_if_numbers(self, sample_model):
description = "What-if: income x1.2, expense x0.9, growth x1.0"
six = ScenarioService(sample_model).what_if(income_mult=1.2, expense_mult=0.9, months=6)
assert six == {
_BALANCE: Decimal("12231.75"),
_INCOME: Decimal("30833.63"),
_EXPENSES: Decimal("9523.81"),
"months": 6,
"scenario": "what-if",
"scenario_description": description,
}
twelve = ScenarioService(sample_model).what_if(income_mult=1.2, expense_mult=0.9, months=12)
assert twelve == {
_BALANCE: Decimal("14514.02"),
_INCOME: Decimal("61749.97"),
_EXPENSES: Decimal("18785.87"),
"months": 12,
"scenario": "what-if",
"scenario_description": description,
}
def test_compare_matches_apply(self, sample_model):
comparison = ScenarioService(sample_model).compare(months=12)
assert set(comparison) == {"baseline", "optimistic", "pessimistic"}
for name, scenario in DEFAULT_SCENARIOS.items():
# apply() на СВЕЖЕМ сервисе даёт те же числа, что и compare().
single = ScenarioService(sample_model).apply(scenario, months=12)
for key in (_BALANCE, _INCOME, _EXPENSES):
assert comparison[name][key] == single[key]
def test_scenario_service_is_not_mutated_by_apply(self, sample_model):
# apply() работает на копии модели, поэтому сервис не «тратит»
# обязательство: повторный apply() того же сценария даёт те же числа.
service = ScenarioService(sample_model)
first = service.apply(DEFAULT_SCENARIOS["baseline"], months=6)
second = service.apply(DEFAULT_SCENARIOS["baseline"], months=6)
assert first == second
assert first[_BALANCE] == Decimal("11527.64")