Compare commits
2
Commits
bd23b03c08
...
4e55a350b6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e55a350b6 | ||
|
|
3d4ee910b4 |
No files matched your search
+10
-5
@@ -2,7 +2,7 @@
|
||||
"metaagent_version": "3.0.0",
|
||||
"session_id": "metaagent-008",
|
||||
"target_repo": "/home/oqyude/External/Git/nifodea",
|
||||
"goal": "Исполнение плана технического долга D1-D30: Tier 1 целиком, Tier 2 целиком (включая D16a/D16b), Tier 3 — D28, D29, D30 (решение владельца)",
|
||||
"goal": "Исполнение плана технического долга D1-D30: Tier 1 целиком, Tier 2 целиком (включая D16a/D16b), Tier 3 целиком — D25-D27 (батч Tier 3b), D28, D29, D30 (решение владельца); D22 — данные модели остаются в git.",
|
||||
"project_type": "existing",
|
||||
"phases": {
|
||||
"init": "completed",
|
||||
@@ -113,10 +113,15 @@
|
||||
},
|
||||
{
|
||||
"id": "D25-D27",
|
||||
"title": "Tier 3 — оставшаяся реструктуризация (config_cmd, i18n)",
|
||||
"status": "pending",
|
||||
"origin": "user:direct"
|
||||
"title": "Tier 3b — config_cmd.py → пакет commands/config/, i18n → пакет, вынос i18n из cli",
|
||||
"status": "archived",
|
||||
"origin": "user:direct",
|
||||
"commits": [
|
||||
"9c069b9",
|
||||
"bd23b03",
|
||||
"3d4ee91"
|
||||
]
|
||||
}
|
||||
],
|
||||
"last_updated": "2026-10-25T13:55:00Z"
|
||||
"last_updated": "2026-10-25T14:20:07Z"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# Project State
|
||||
|
||||
**Снимок на момент:** 2026-10-25T13:55 (после батча Tier 3a, ветка `agent/tier3-a`, сессия metaagent-008)
|
||||
**Снимок на момент:** 2026-10-25T14:20 (после батча Tier 3b, ветка `agent/tier3-b`, сессия metaagent-008 — план D1–D30 закрыт)
|
||||
**Project type:** `existing`
|
||||
**MetaAgent version:** 3.0.0
|
||||
|
||||
@@ -17,8 +17,9 @@
|
||||
3. **Синхронизация `.agent/**`** (D23): T8 → archived, статусы D1–D30, сводка сессии metaagent-008.
|
||||
4. **Батч Tier 2b** (ветка `agent/tier2-rest`): D16a (единое правило классификации recurring), D18 (лист `Scenarios` в Excel), D24 (удаление неиспользуемых публичных исключений).
|
||||
5. **Батч Tier 3a** (ветка `agent/tier3-a`): D16b (периодичность и границы recurring), D28 (`SheetSpec` — одна таблица листов Excel), D29 (`AppPaths` + `CF_DATA_DIR`), D30 (решение владельца: `.agent/` остаётся как есть).
|
||||
6. **Батч Tier 3b** (ветка `agent/tier3-b`): D26 (`i18n.py` → пакет `{__init__,ru,en}.py`), D27 (`infrastructure/i18n/`, снята связь AI → CLI), D25 (`config_cmd.py` → пакет `commands/config/` по семействам). Поверхность CLI не менялась.
|
||||
|
||||
Tier 2 закрыт полностью (12/12). Tier 3: D28, D29 выполнены; D30 решён. Остались D25–D27.
|
||||
Tier 2 закрыт полностью (12/12). Tier 3 закрыт полностью (6/6): D25, D26, D27, D28, D29, D30. План D1–D30 закрыт.
|
||||
|
||||
### Изменения чисел (утверждено владельцем в батче)
|
||||
|
||||
@@ -87,13 +88,14 @@ D11-характеристика на `sample_model` не изменилась:
|
||||
│
|
||||
┌──────────────────▼──────────────────────────┐
|
||||
│ infrastructure/ — внешний мир │
|
||||
│ cli/ (Typer), ai/ (Assistant), │
|
||||
│ repositories/ (JsonFile, Excel) │
|
||||
│ cli/ (Typer), i18n/ (словари+рантайм), │
|
||||
│ ai/ (Assistant), repositories/ │
|
||||
└─────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Направление импортов чистое: нарушений «снизу вверх» нет. Единственная горизонтальная связь —
|
||||
`infrastructure/ai/prompts.py:1` → `infrastructure.cli.i18n` (блокирует REST API / Web UI, Tier 3 — D27).
|
||||
Направление импортов чистое: нарушений «снизу вверх» нет. Горизонтальных связей тоже нет:
|
||||
`infrastructure/ai/` и `infrastructure/i18n/` не импортируют `infrastructure/cli/` (D27; инвариант —
|
||||
`tests/test_architecture.py`). REST API / Web UI больше не заблокированы связью AI → CLI.
|
||||
|
||||
## Tech stack
|
||||
|
||||
@@ -123,10 +125,10 @@ D11-характеристика на `sample_model` не изменилась:
|
||||
| application | `scenarios.py` (88) | ScenarioService — baseline/optimistic/pessimistic + what-if; `start_month` пробрасывается в прогноз |
|
||||
| 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/commands/*.py` | 9 файлов команд + пакет `commands/config/` (7 семейств, 10 модулей, **19** подкоманд; крупнейший — `transactions.py`, 106 стр.; `_app.py` — единственный `typer.Typer()`) |
|
||||
| infrastructure | `cli/paths.py` (40) | `AppPaths`: `data_dir` из `CF_DATA_DIR` (дефолт `./data`), `model_path`, `exports_dir` (D29) |
|
||||
| infrastructure | `cli/services.py` (83) | `build_services()` — composition root + helpers + `fail_validation()` |
|
||||
| infrastructure | `cli/i18n.py` (382) | 176 ключей **только на ru**; язык определяется при импорте (D20) |
|
||||
| infrastructure | `i18n/__init__.py` (76), `i18n/ru.py` (225), `i18n/en.py` (9) | рантайм `t()`/`setup_i18n()`/`set_lang()` + словари; 177 ключей **только на ru**, `en` пуст; язык определяется при импорте (D20, D26, D27) |
|
||||
| infrastructure | `ai/assistant.py` (80) | AssistantService (заглушка, DI ForecastService) |
|
||||
| infrastructure | `repositories/json_file_repository.py` (21) | .json storage |
|
||||
| infrastructure | `repositories/excel_repository.py` (194) | .xlsx storage: `SHEETS`/`SheetSpec` — одна таблица для записи и чтения (7 листов + ModelInfo), создаёт родительский каталог |
|
||||
@@ -135,10 +137,10 @@ D11-характеристика на `sample_model` не изменилась:
|
||||
|
||||
| Параметр | Значение |
|
||||
|---|---|
|
||||
| Всего тестов | **229** |
|
||||
| Пройдено | 229 ✅ (75 были в сессии 007) |
|
||||
| Всего тестов | **241** |
|
||||
| Пройдено | 241 ✅ (75 были в сессии 007) |
|
||||
| Упало | 0 |
|
||||
| Тестовых модулей | 12 (`tests/`, вкл. `__init__.py` и новый `test_paths.py`) |
|
||||
| Тестовых модулей | 12 `test_*.py` + `conftest.py`/`__init__.py` (вкл. `test_architecture.py` и `test_cli_contract.py`) |
|
||||
| Coverage | настроено: `[tool.coverage.run]` в `pyproject.toml` (D12) |
|
||||
| Линт | `ruff check .` → чисто; `ruff format --check .` → чисто (D2 + `style:`) |
|
||||
| CI | `.github/workflows/ci.yml` — pytest + ruff (D13) |
|
||||
@@ -150,22 +152,23 @@ D11-характеристика на `sample_model` не изменилась:
|
||||
- ✅ Tier 2 исполнены однозначные пункты: D14, D15, D17, D19, D20, D21, D23
|
||||
- ✅ Батч Tier 2b: D16a (единое правило по знаку), D18 (лист `Scenarios`), D24 (удалены мёртвые исключения)
|
||||
- ✅ Батч Tier 3a: D16b (периодичность/границы recurring), D28 (`SheetSpec`), D29 (`AppPaths`/`CF_DATA_DIR`), D30 (`.agent/` остаётся как есть)
|
||||
- ✅ Батч Tier 3b: D26 (i18n → пакет), D27 (`infrastructure/i18n/`, AI без CLI), D25 (`commands/config/`); поверхность CLI доказана контрактным тестом (имя, опции, default, required всех 28 leaf-команд)
|
||||
- ✅ Метасостояние синхронизировано: `manifest.md`, `manifest.json`, `archive/`, `checkpoints.json`,
|
||||
`session-summary.md`, `project-state.md`, `handoff-summary.md`
|
||||
- ✅ `.venv` пересоздан; dev-extra описан в `pyproject.toml`
|
||||
|
||||
## Что заблокировано и почему
|
||||
|
||||
| ID | Суть | Причина блокировки |
|
||||
|---|---|---|
|
||||
| D25–D27 | Tier 3 — `config_cmd.py` → пакет, `i18n.py` → пакет, вынос i18n из `cli` | следующий батч (после стабилизации остального) |
|
||||
|
||||
D22 не блокировка: 📌 решение владельца — `data/model.json` и `data/excel.xlsx` остаются в git.
|
||||
D30 решён: `.agent/` остаётся в репозитории как есть.
|
||||
Ничего не заблокировано: план D1–D30 закрыт (Tier 1 13/13, Tier 2 12/12, Tier 3 6/6).
|
||||
D22 — 📌 решение владельца: `data/model.json` и `data/excel.xlsx` остаются в git.
|
||||
D30 — 📌 решение владельца: `.agent/` остаётся в репозитории как есть.
|
||||
REST API / Web UI больше не заблокированы: после D27 `infrastructure/ai/` и `infrastructure/i18n/`
|
||||
не зависят от `infrastructure/cli/`.
|
||||
|
||||
## Что отсутствует / TODO
|
||||
|
||||
- ❌ **AI-интеграция** — `AssistantService` не вызывает LLM API (отклонено пользователем)
|
||||
- ❌ **REST API / Web UI** — не реализованы; после D27 ничто не мешает использовать `application/` и `infrastructure/ai/` без CLI
|
||||
- ❌ **mypy** — не настроен
|
||||
- ❌ **Логирование** — только `rich.print`
|
||||
- ✅ **CI** — `.github/workflows/ci.yml` (D13)
|
||||
@@ -184,12 +187,12 @@ D30 решён: `.agent/` остаётся в репозитории как ес
|
||||
|
||||
## Следующая сессия — что делать
|
||||
|
||||
1. **Tier 3, оставшееся:** D25 (`config_cmd.py` → пакет `commands/config/`), D26 (`i18n.py` →
|
||||
пакет `i18n/{__init__,ru,en}.py`), D27 (`infrastructure/cli/i18n/` → `infrastructure/i18n/`).
|
||||
Инвариант поверхности CLI (`tests/test_cli_contract.py`) обязателен.
|
||||
2. **D19-язык** — привести сообщения к единому языку позже (вне текущих батчей).
|
||||
1. **План D1–D30 закрыт** — открытых пунктов техдолга нет.
|
||||
2. **D19-язык** — привести сообщения к единому языку позже (вне плана).
|
||||
3. **REST API / Web UI** — разблокированы D27: `application/` + `infrastructure/ai/` +
|
||||
`infrastructure/i18n/` переиспользуются без CLI.
|
||||
|
||||
Решено ранее: D16a — классификация recurring только по знаку, D16b — периодичность и границы
|
||||
recurring, D18 — лист `Scenarios` добавлен, D22 — данные модели остаются в git,
|
||||
D24 — мёртвые исключения удалены, D28 — `SheetSpec`, D29 — `AppPaths`/`CF_DATA_DIR`,
|
||||
D30 — `.agent/` остаётся как есть.
|
||||
D30 — `.agent/` остаётся как есть, D25–D27 — батч Tier 3b (структура без изменения поверхности).
|
||||
@@ -1,7 +1,7 @@
|
||||
# Handoff Summary
|
||||
|
||||
**Session:** `metaagent-008`
|
||||
**Goal:** Технический долг: исполнить Tier 1 целиком и однозначные пункты Tier 2
|
||||
**Goal:** Технический долг D1–D30: Tier 1, Tier 2, Tier 3 — план закрыт
|
||||
**Date:** 2026-10-25
|
||||
**MetaAgent version:** 3.0.0
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
| Tier 1 — выполнено | 13/13 (D2–D5 — сессия 007, D1/D6–D13 — сессия 008) |
|
||||
| Tier 2 — выполнено | **12/12** (D14, D15, D16a, D16b, D17, D18, D19, D20, D21, D23, D24) |
|
||||
| Tier 2 — решение владельца | D22: данные модели остаются в git |
|
||||
| Tier 3 — выполнено / решено | D28, D29 выполнены; D30 — решение владельца (`.agent/` остаётся как есть) |
|
||||
| Tier 3 — осталось | D25, D26, D27 (следующий батч) |
|
||||
| Baseline тестов | 75/75 ✅ → сейчас **229/229** ✅ |
|
||||
| Tier 3 — выполнено / решено | **6/6**: D25, D26, D27 (батч Tier 3b), D28, D29; D30 — решение владельца |
|
||||
| Tier 3 — осталось | — |
|
||||
| Baseline тестов | 75/75 ✅ → сейчас **241/241** ✅ |
|
||||
| Baseline линта | `ruff check .` → 10 ошибок → сейчас чисто; `ruff format --check .` → 24 файла → сейчас чисто |
|
||||
| Ветка | `agent/tier1-debt` (база `dev`) → `agent/tier2-rest` → `agent/tier3-a` |
|
||||
| Ветка | `agent/tier1-debt` (база `dev`) → `agent/tier2-rest` → `agent/tier3-a` → `agent/tier3-b` |
|
||||
|
||||
## Что было сделано
|
||||
|
||||
@@ -119,10 +119,36 @@
|
||||
- **D30:** решение владельца 2026-10-25 — `.agent/` остаётся в репозитории как есть;
|
||||
зафиксировано только в `manifest.md`/`manifest.json`.
|
||||
|
||||
### Батч Tier 3b (ветка `agent/tier3-b`, база `dev` cf61359)
|
||||
|
||||
- **D26:** `i18n.py` (382 стр.) → пакет `infrastructure/cli/i18n/`: `__init__.py` (76) —
|
||||
рантайм (`t()`, `Translator`, `setup_i18n()`, `set_lang()`, `get_lang()`, резолв языка,
|
||||
fallback на `ru`); `ru.py` (225) — плоский словарь (177 ключей, тексты байт-в-байт прежние);
|
||||
`en.py` (9) — пустой словарь. Публичный API и ключи не менялись, `CF_LANG=en` по-прежнему
|
||||
тихо откатывается на `ru`. Тесты: каждый ключ `ru` рендерится; каждый отсутствующий в `en`
|
||||
ключ при `CF_LANG=en` отдаёт русский; `set(en) ⊆ set(ru)` (пустой `en` валиден).
|
||||
Коммит `9c069b9`.
|
||||
- **D27:** пакет перенесён в `infrastructure/i18n/`, все импорты обновлены.
|
||||
`infrastructure/ai/prompts.py` импортирует `infrastructure.i18n` — горизонтальная связь
|
||||
AI → CLI снята. `tests/test_architecture.py` разбирает AST всего `infrastructure/`:
|
||||
ни один модуль вне `infrastructure/cli/` не импортирует `infrastructure.cli.*`
|
||||
(отдельно проверены `i18n/` и `ai/`). README и README.arch обновлены; REST API / Web UI
|
||||
больше не заблокированы. Коммит `bd23b03`.
|
||||
- **D25:** `config_cmd.py` (435 стр., 19 подкоманд) → `infrastructure/cli/commands/config/`:
|
||||
`base_currency` (22), `rates` (79), `accounts` (59), `transactions` (106), `recurring` (70),
|
||||
`assets` (58), `liabilities` (62), `_helpers.py` (51), `_app.py` (13), `__init__.py` (28).
|
||||
В пакете ровно один `typer.Typer()` (`_app.py`); общие хелперы — `print_ok`/`print_error`/
|
||||
`print_warning` + единый `remove_items`; поиск счёта — приватные функции `transactions.py`;
|
||||
регистрация — декораторами, подключение — корневой `app.py`. Коммит `3d4ee91`.
|
||||
- **Инвариант поверхности CLI:** `tests/test_cli_contract.py` теперь фиксирует для всех
|
||||
28 leaf-команд (9 верхнего уровня + 19 `config`) имя, опции (длинные/короткие), default
|
||||
и required; снимок click-поверхности до/после батча совпал полностью. Поведение 19 подкоманд
|
||||
`cf config` сверено с baseline-прогоном (diff вывода с нормализованными UUID — пустой).
|
||||
|
||||
## Что заблокировано
|
||||
|
||||
Ничего не заблокировано. Tier 2 закрыт полностью. Tier 3: D28/D29 выполнены,
|
||||
D30 решён, остались D25–D27.
|
||||
Ничего не заблокировано. План D1–D30 закрыт: Tier 1 — 13/13, Tier 2 — 12/12,
|
||||
Tier 3 — 6/6 (D25–D27 — батч Tier 3b). REST API / Web UI разблокированы D27.
|
||||
|
||||
## Требует решения владельца
|
||||
|
||||
@@ -149,6 +175,9 @@ D30 решён, остались D25–D27.
|
||||
| Прогноз | `application/forecast.py:39` (`ForecastService`, `start_month`) |
|
||||
| Сценарии | `application/scenarios.py:33` (`ScenarioService`) |
|
||||
| AI (заглушка) | `infrastructure/ai/assistant.py:22` (`AssistantService`) |
|
||||
| i18n (рантайм) | `infrastructure/i18n/__init__.py` (`t()`, `setup_i18n()`, `set_lang()`) |
|
||||
| i18n (словари) | `infrastructure/i18n/ru.py`, `infrastructure/i18n/en.py` |
|
||||
| Команды `cf config` | `infrastructure/cli/commands/config/` (`_app.py` — Typer, семейства сущностей) |
|
||||
| JSON storage | `infrastructure/repositories/json_file_repository.py:9` |
|
||||
| Excel storage | `infrastructure/repositories/excel_repository.py:152` (`ExcelRepository`), спецификация — `SHEETS` |
|
||||
| Пути / CF_DATA_DIR | `infrastructure/cli/paths.py:20` (`AppPaths`) |
|
||||
@@ -182,6 +211,6 @@ git status
|
||||
## Git
|
||||
|
||||
Ветки: `agent/tier1-debt` (база `dev`), `agent/tier2-rest` (база — `dev` 0307533),
|
||||
`agent/tier3-a` (база — `dev` abcd84c). Коммиты по плану — отдельные, независимо
|
||||
откатываемые. Пуш — `origin/agent/tier3-a`.
|
||||
`agent/tier3-a` (база — `dev` abcd84c), `agent/tier3-b` (база — `dev` cf61359).
|
||||
Коммиты по плану — отдельные, независимо откатываемые. Пуш — `origin/agent/tier3-b`.
|
||||
**`dev`/`main` не изменялись.**
|
||||
+25
-14
@@ -3,7 +3,7 @@
|
||||
**Session:** `metaagent-008`
|
||||
**MetaAgent version:** 3.0.0
|
||||
**Date:** 2026-10-25
|
||||
**Goal:** Снятие технического долга: Tier 1 целиком + однозначные пункты Tier 2
|
||||
**Goal:** Снятие технического долга D1–D30: Tier 1, Tier 2, Tier 3 (план закрыт)
|
||||
|
||||
## Phases Executed
|
||||
|
||||
@@ -19,22 +19,26 @@
|
||||
## Results
|
||||
|
||||
- **Пункты выполнены:** 13/13 Tier 1 (D1, D6–D13) + **12/12 Tier 2** (D14, D15, D16a,
|
||||
D16b, D17, D18, D19, D20, D21, D23, D24) + Tier 3: D28, D29, D30 (решение владельца —
|
||||
`.agent/` остаётся как есть). D22 закрыт решением владельца (данные модели остаются в git).
|
||||
Остались D25–D27.
|
||||
- **Коммиты:** 25, по одному на пункт (включая один `style:` — приведение кода к руфтормату)
|
||||
и отдельный коммит синхронизации `.agent/**`
|
||||
D16b, D17, D18, D19, D20, D21, D23, D24) + **6/6 Tier 3** (D25, D26, D27 — батч Tier 3b;
|
||||
D28, D29; D30 — решение владельца). D22 закрыт решением владельца (данные модели остаются
|
||||
в git). Открытых пунктов плана нет.
|
||||
- **Коммиты:** 29, по одному на пункт (включая один `style:` — приведение кода к руфтормату)
|
||||
и отдельные коммиты синхронизации `.agent/**` (после Tier 3a и Tier 3b)
|
||||
- `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
|
||||
- `e7d14ba` D16a, `387cb55` D18, `ac9ee0d` D24 — батч Tier 2b
|
||||
- `f50106c` D16b, `f41fc19` D28, `6470978` D29, `8300faa` D30 — батч Tier 3a
|
||||
- синхронизация `.agent/**` после батча Tier 3a — отдельный коммит
|
||||
- **Тесты:** 75 → **229/229** ✅ (`pytest -q`); добавлено 28 тестов в батче Tier 3a
|
||||
(периодичность/границы recurring, спецификация листов, пути/CF_DATA_DIR).
|
||||
- `9c069b9` D26, `bd23b03` D27, `3d4ee91` D25 — батч Tier 3b
|
||||
- синхронизация `.agent/**` после батчей Tier 3a и Tier 3b — отдельные коммиты
|
||||
- **Тесты:** 75 → **241/241** ✅ (`pytest -q`); +28 в батче Tier 3a и +12 в батче Tier 3b
|
||||
(словари/fallback, AST-инварианты зависимостей, контракт поверхности всех 28 leaf-команд).
|
||||
- **Линт:** `ruff check .` — чисто; `ruff format --check .` — чисто.
|
||||
- **CLI:** проверено вручную: `cf init`, `forecast`, `scenario`, `compare`, `info`, `analyze`, `whatif`,
|
||||
`export-xlsx` (round-trip с `import-xlsx`), `config rate-set` (отрицательный курс — понятная ошибка, без traceback).
|
||||
- **CLI:** проверено вручную: `cf init`, `forecast --months 12`, `scenario baseline`,
|
||||
`compare --months 12`, `info`, `analyze`, `whatif`, `export-xlsx` → `import-xlsx` (round-trip),
|
||||
все 19 подкоманд `cf config` (добавление/список/удаление по каждому семейству, курсы,
|
||||
базовая валюта), `cf config rate-set -- USD RUB -5` (понятная ошибка валидации, код 1,
|
||||
без traceback) и `rate-set USD RUB 0`.
|
||||
|
||||
## Изменения чисел (владелец утвердил)
|
||||
|
||||
@@ -54,6 +58,9 @@
|
||||
| D28 | 7 листов + ModelInfo описываются одной таблицей `SHEETS`; `save()`/`load()` без ручных веток | `f41fc19` |
|
||||
| D29 | `AppPaths`; база данных из `CF_DATA_DIR` (дефолт `./data`), экспорты остаются `./exports` | `6470978` |
|
||||
| D30 | Решение владельца: `.agent/` остаётся в репозитории как есть | `8300faa` |
|
||||
| D26 | `i18n.py` → пакет `{__init__,ru,en}.py`; 177 ключей и тексты не менялись, `en` пуст | `9c069b9` |
|
||||
| D27 | `infrastructure/cli/i18n/` → `infrastructure/i18n/`; AI больше не импортирует CLI | `bd23b03` |
|
||||
| D25 | `config_cmd.py` → пакет `commands/config/` (7 семейств, 19 подкоманд); поверхность CLI без изменений | `3d4ee91` |
|
||||
|
||||
## Files Changed
|
||||
|
||||
@@ -61,9 +68,12 @@
|
||||
- `domain/recurring.py` — делители периодичности, `monthly_amount()`, `is_active_in_month()` (Д16b)
|
||||
- `application/scenarios.py` — классификация по знаку (Д16a); проброс `start_month` (Д16b)
|
||||
- `domain/*.py` — `model_config = ConfigDict(validate_assignment=True)` (Д17); `convert()` без квантования (Д15)
|
||||
- `infrastructure/cli/` — `fail_validation()` (Д17), `EXPORTS_DIR` (Д6), i18n (Д20, Д21); `AppPaths` (Д29)
|
||||
- `infrastructure/cli/` — `fail_validation()` (Д17), `EXPORTS_DIR` (Д6); `AppPaths` (Д29);
|
||||
пакет `commands/config/` (Д25); `app.py`/`commands/__init__.py` — подключение пакета
|
||||
- `infrastructure/i18n/` — рантайм i18n (Д26), перенос из `cli` (Д27), словари `ru`/`en`
|
||||
- `infrastructure/repositories/excel_repository.py` — создание родительского каталога (Д19), лист `Scenarios` (Д18), `SHEETS`/`SheetSpec` (Д28)
|
||||
- `tests/` — характеристики (Д11) и регрессии по Д14–Д21, Д16a/Д16b, Д18, Д28, Д29
|
||||
- `tests/` — характеристики (Д11) и регрессии по Д14–Д21, Д16a/Д16b, Д18, Д28, Д29;
|
||||
`test_cli_contract.py` — имя/опции/default/required всех команд (Д25); `test_architecture.py` — AST-инварианты зависимостей и Typer (Д25, Д27)
|
||||
- `.github/workflows/ci.yml`, `pyproject.toml`, `.gitignore` — CI, dev-экстра, игнор (Д12, Д13, Д1)
|
||||
- `README.md` — структура, листы Excel, переменные окружения `CF_DATA_DIR`/`CF_LANG` (Д8, Д28, Д29)
|
||||
- `.agent/**` — синхронизация (Д23 + батчи Tier 2b/Tier 3a)
|
||||
@@ -71,5 +81,6 @@
|
||||
## Next
|
||||
|
||||
Следующий агент: читать `.agent/handoff-summary.md`.
|
||||
Кандидаты на следующий батч: D25–D27 (Tier 3 — `config_cmd.py`, `i18n.py`, вынос i18n из `cli`).
|
||||
План D1–D30 закрыт. Вне плана: D19-язык (единый язык сообщений) и расширение словаря частот.
|
||||
REST API / Web UI разблокированы D27 — можно строить поверх `application/` и `infrastructure/ai/`.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"$schema": "metaagent-task-manifest",
|
||||
"version": "3.0",
|
||||
"session_id": "metaagent-008",
|
||||
"goal": "Исполнение плана технического долга D1-D30: Tier 1 полностью (D1, D6-D13), Tier 2 полностью (D14-D24, включая D16a/D16b), Tier 3 — D28, D29 выполнены, D30 решён (оставить .agent/ как есть); D25-D27 остаются на следующий батч; D22 — решение владельца: данные модели остаются в git.",
|
||||
"goal": "Исполнение плана технического долга D1-D30: Tier 1 полностью (D1, D6-D13), Tier 2 полностью (D14-D24, включая D16a/D16b), Tier 3 полностью (D25-D30, включая D28/D29 и решения владельца D22/D30); батч Tier 3b — D25, D26, D27.",
|
||||
"created_at": "2026-10-25T12:00:00Z",
|
||||
"tasks": [
|
||||
{
|
||||
@@ -183,17 +183,20 @@
|
||||
{
|
||||
"id": "D25",
|
||||
"title": "config_cmd.py → пакет commands/config/",
|
||||
"status": "deferred"
|
||||
"status": "archived",
|
||||
"commit": "3d4ee91"
|
||||
},
|
||||
{
|
||||
"id": "D26",
|
||||
"title": "i18n.py → пакет i18n/{__init__,ru,en}.py",
|
||||
"status": "deferred"
|
||||
"status": "archived",
|
||||
"commit": "9c069b9"
|
||||
},
|
||||
{
|
||||
"id": "D27",
|
||||
"title": "infrastructure/cli/i18n/ → infrastructure/i18n/",
|
||||
"status": "deferred"
|
||||
"status": "archived",
|
||||
"commit": "bd23b03"
|
||||
},
|
||||
{
|
||||
"id": "D28",
|
||||
|
||||
@@ -251,9 +251,9 @@ Tier 1 целиком (D1, D6–D13) и Tier 2 — однозначные пун
|
||||
| D22 | 📌 решение владельца: данные модели остаются в git (`data/model.json`, `data/excel.xlsx`) |
|
||||
| D23 | ✅ выполнено (синхронизация `.agent/**`) |
|
||||
| D24 | ✅ выполнено (`ScenarioError` / `AssistantError` удалены) |
|
||||
| D25 | ⏳ позже (Tier 3) |
|
||||
| D26 | ⏳ позже (Tier 3) |
|
||||
| D27 | ⏳ позже (Tier 3) |
|
||||
| D25 | ✅ выполнено (батч Tier 3b: пакет `commands/config/`, 7 семейств) |
|
||||
| D26 | ✅ выполнено (батч Tier 3b: i18n → пакет `{__init__,ru,en}.py`) |
|
||||
| D27 | ✅ выполнено (батч Tier 3b: `infrastructure/i18n/`, AI больше не зависит от CLI) |
|
||||
| D28 | ✅ выполнено (`SHEETS`/`SheetSpec` — одна таблица для записи и чтения) |
|
||||
| D29 | ✅ выполнено (`AppPaths` + `CF_DATA_DIR`) |
|
||||
| D30 | 📌 решено 2026-10-25: `.agent/` остаётся в репозитории как есть (без перемещений, удалений и `.gitignore`-правил) |
|
||||
@@ -301,14 +301,29 @@ D16b меняет числа там, где `frequency ≠ monthly` или за
|
||||
| monthly 500, `end_date=2026-03-15` | 500.00 все 12 месяцев, итог 6000.00 | 500.00 янв–март, 0.00 дальше, итог 1500.00 |
|
||||
| monthly 500, `start_date=2026-03-01`, `end_date=2026-06-30` | итог 6000.00 | платежи март–июнь, итог 2000.00 |
|
||||
|
||||
## Что осталось
|
||||
### Батч Tier 3b (ветка `agent/tier3-b`, база `dev` cf61359)
|
||||
|
||||
| ID | Суть | Коммит |
|
||||
|---|---|---|
|
||||
| D26 | `i18n.py` (382 стр.) → пакет `infrastructure/cli/i18n/`: `__init__.py` — только рантайм (`t()`, `Translator`, `setup_i18n()`, `set_lang()`, `get_lang()`, резолв языка, fallback на `ru`), `ru.py` — плоский словарь (177 ключей, строки байт-в-байт прежние), `en.py` — пустой словарь. Публичный API и ключи не менялись; `CF_LANG=en` по-прежнему тихо откатывается на `ru`. Тесты: каждый ключ `ru` рендерится в непустую строку; каждый ключ, отсутствующий в `en`, при `CF_LANG=en` отдаёт русский; `set(en) ⊆ set(ru)` (пустой `en` валиден). | `9c069b9` |
|
||||
| D27 | `infrastructure/cli/i18n/` → `infrastructure/i18n/`, все импорты обновлены. `infrastructure/ai/prompts.py` импортирует `infrastructure.i18n` — горизонтальная связь AI → CLI снята. AST-инвариант `tests/test_architecture.py`: ни один модуль вне `infrastructure/cli/` не импортирует `infrastructure.cli.*` (отдельно проверены `infrastructure/i18n/` и `infrastructure/ai/`). README и README.arch обновлены; зафиксировано, что REST API / Web UI больше не заблокированы связью AI → CLI. | `bd23b03` |
|
||||
| D25 | `config_cmd.py` (435 стр., 19 подкоманд) → пакет `infrastructure/cli/commands/config/` по семействам: `base_currency` (1), `rates` (3), `accounts` (3), `transactions` (3), `recurring` (3), `assets` (3), `liabilities` (3). В пакете ровно один `typer.Typer()` — `_app.py`; общие хелперы (`print_ok`/`print_error`/`print_warning`, единый `remove_items`) — `_helpers.py`; поиск счёта — приватные функции `transactions.py`. Регистрация — декораторами `@app.command()`, подключение — `app.py` (`add_typer`). Поверхность CLI не изменилась: вывод 19 подкоманд совпал с baseline (diff с нормализованными UUID), click-поверхность идентична. `tests/test_cli_contract.py` усилен: имя, опции (длинные/короткие), default и required каждой из 28 leaf-команд (9 верхнего уровня + 19 `config`). | `3d4ee91` |
|
||||
|
||||
Инвариант поверхности CLI доказан: `tests/test_cli_contract.py` сравнивает click-представление
|
||||
всех leaf-команд по `(имя, опции, default, required)`; JSON-снимок поверхности до/после
|
||||
батча — без различий. Дополнительно `tests/test_architecture.py` запрещает мёртвые
|
||||
`typer.Typer()` и горизонтальные импорты в CLI.
|
||||
|
||||
## Итог по плану
|
||||
|
||||
- **Tier 1** — закрыт полностью (13/13), включая D2–D5 — сессия 007.
|
||||
- **Tier 2** — закрыт полностью (12/12): D14, D15, D16a, D16b, D17, D18, D19, D20, D21, D23, D24.
|
||||
D22 закрыт решением владельца: данные модели остаются в git.
|
||||
- **Tier 3** — D28 и D29 выполнены, D30 решён (оставить `.agent/` как есть).
|
||||
Остались D25 (`config_cmd.py` → пакет), D26 (`i18n.py` → пакет), D27 (вынос i18n из `cli`).
|
||||
- **Tier 3** — закрыт полностью (6/6): D25, D26, D27 (батч Tier 3b), D28, D29, D30 (батч Tier 3a).
|
||||
- **Вне плана (не входило в батч):** D19-язык (единый язык сообщений) и расширение словаря
|
||||
частот — по-прежнему отдельная задача; тексты сообщений в батче не менялись.
|
||||
|
||||
Изменения чисел: D14 и D15 меняют числа прогноза и конверсии, D16a — числа сценариев
|
||||
при расхождении category и знака, D16b — периодичность и границы recurring.
|
||||
Батч Tier 3b — чистая реструктуризация: числа и тексты не менялись.
|
||||
Новые значения зафиксированы тестами-характеристиками и сведены в таблицы «было → стало».
|
||||
@@ -156,7 +156,8 @@ cashflow-forecast/
|
||||
├── infrastructure/ # Адаптеры к внешнему миру
|
||||
│ ├── cli/ # Typer CLI (cf ...)
|
||||
│ │ ├── app.py # Entry point
|
||||
│ │ ├── commands/ # 10 файлов команд + config sub-typer
|
||||
│ │ ├── commands/ # 9 файлов команд
|
||||
│ │ │ └── config/ # cf config: 7 семейств сущностей (19 подкоманд)
|
||||
│ │ ├── paths.py # AppPaths — пути (CF_DATA_DIR)
|
||||
│ │ └── services.py # Composition root + helpers
|
||||
│ ├── i18n/ # Локализация (не зависит от CLI)
|
||||
@@ -170,7 +171,7 @@ cashflow-forecast/
|
||||
│ ├── json_file_repository.py
|
||||
│ └── excel_repository.py
|
||||
│
|
||||
├── tests/ # pytest, 236 тестов
|
||||
├── tests/ # pytest, 241 тест
|
||||
│ ├── conftest.py
|
||||
│ ├── test_model.py
|
||||
│ ├── test_forecast.py
|
||||
|
||||
@@ -12,7 +12,7 @@ except (AttributeError, OSError):
|
||||
from infrastructure.cli.commands import (
|
||||
analyze,
|
||||
compare,
|
||||
config_cmd,
|
||||
config,
|
||||
export_xlsx,
|
||||
forecast,
|
||||
import_xlsx,
|
||||
@@ -39,7 +39,7 @@ app.command(name="analyze")(analyze.analyze)
|
||||
app.command(name="info")(info.info)
|
||||
|
||||
# Под-приложение config
|
||||
app.add_typer(config_cmd.app, name="config")
|
||||
app.add_typer(config.app, name="config")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from infrastructure.cli.commands import (
|
||||
analyze,
|
||||
compare,
|
||||
config_cmd,
|
||||
config,
|
||||
export_xlsx,
|
||||
forecast,
|
||||
import_xlsx,
|
||||
@@ -14,7 +14,7 @@ from infrastructure.cli.commands import (
|
||||
__all__ = [
|
||||
"analyze",
|
||||
"compare",
|
||||
"config_cmd",
|
||||
"config",
|
||||
"export_xlsx",
|
||||
"forecast",
|
||||
"import_xlsx",
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Пакет `cf config` — подкоманды управления моделью.
|
||||
|
||||
В пакете ровно один объект Typer — `app` (см. `_app.py`). Подкоманды
|
||||
регистрируются декораторами `@app.command()` в модулях семейств сущностей
|
||||
(`base_currency`, `rates`, `accounts`, `transactions`, `recurring`, `assets`,
|
||||
`liabilities`); модули импортируются здесь ради побочного эффекта — так
|
||||
регистрация происходит один раз при первом импорте пакета.
|
||||
|
||||
Наружу пакет отдаёт только `app`: его подключает к корневому CLI
|
||||
`infrastructure/cli/app.py` (`app.add_typer(config.app, name="config")`).
|
||||
"""
|
||||
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
|
||||
# isort: off
|
||||
# Порядок импортов задаёт порядок регистрации команд, а значит и порядок
|
||||
# их показа в `cf config --help` — он должен совпадать с прежним монолитом.
|
||||
from infrastructure.cli.commands.config import base_currency # noqa: F401
|
||||
from infrastructure.cli.commands.config import rates # noqa: F401
|
||||
from infrastructure.cli.commands.config import accounts # noqa: F401
|
||||
from infrastructure.cli.commands.config import transactions # noqa: F401
|
||||
from infrastructure.cli.commands.config import recurring # noqa: F401
|
||||
from infrastructure.cli.commands.config import assets # noqa: F401
|
||||
from infrastructure.cli.commands.config import liabilities # noqa: F401
|
||||
|
||||
# isort: on
|
||||
|
||||
__all__ = ["app"]
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Единственный объект Typer для всего пакета `config`.
|
||||
|
||||
Подкоманды регистрируются декораторами `@app.command()` в модулях семейств
|
||||
(`base_currency`, `rates`, `accounts`, ...). Модуль `_app.py` — единственное
|
||||
место в пакете, где создаётся `typer.Typer()`: мёртвых Typer-объектов в
|
||||
пакете быть не должно (D3), иначе часть команд не попадёт в CLI.
|
||||
"""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.i18n import t
|
||||
|
||||
app = typer.Typer(name="config", help=t("config.help"))
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Общая «клейкая» часть CLI-пакета `config`.
|
||||
|
||||
Только инфраструктурные помощники: форматирование сообщений и единая
|
||||
реализация удаления элементов модели. Логики конкретных команд здесь нет —
|
||||
она живёт в модулях семейств (`base_currency`, `rates`, `accounts`, ...).
|
||||
"""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.services import console, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
def print_ok(message: str) -> None:
|
||||
"""Сообщение об успехе в едином формате: `[green]OK[/green] <текст>`."""
|
||||
console.print(f"[green]{t('global.ok')}[/green] {message}")
|
||||
|
||||
|
||||
def print_error(message: str) -> None:
|
||||
"""Сообщение об ошибке в едином формате: `[red]<текст>[/red]`."""
|
||||
console.print(f"[red]{message}[/red]")
|
||||
|
||||
|
||||
def print_warning(message: str) -> None:
|
||||
"""Предупреждение в едином формате: `[yellow]<текст>[/yellow]`."""
|
||||
console.print(f"[yellow]{message}[/yellow]")
|
||||
|
||||
|
||||
def remove_items(
|
||||
model,
|
||||
field: str,
|
||||
predicate,
|
||||
*,
|
||||
identifier: str,
|
||||
ok_key: str,
|
||||
err_key: str,
|
||||
) -> None:
|
||||
"""Удалить элементы `model.field`, для которых `predicate` истинно.
|
||||
|
||||
`predicate(item)` — «этот элемент удалить»: элементы, для которых он
|
||||
ложен, остаются. Если ничего не удалено — сообщение об ошибке и
|
||||
`typer.Exit(1)`; иначе модель сохраняется и печатается подтверждение.
|
||||
"""
|
||||
items = getattr(model, field)
|
||||
kept = [item for item in items if not predicate(item)]
|
||||
if len(kept) == len(items):
|
||||
print_error(t(err_key, id=identifier))
|
||||
raise typer.Exit(1)
|
||||
setattr(model, field, kept)
|
||||
save_model(model)
|
||||
print_ok(t(ok_key, id=identifier))
|
||||
@@ -0,0 +1,59 @@
|
||||
"""`cf config account-*` — счета: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import Account, CurrencyConverter
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def account_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.account_add.opt.name")),
|
||||
balance: float = typer.Option(0.0, "--balance", "-b", help=t("cmd.config.account_add.opt.balance")),
|
||||
currency: str = typer.Option("", "--currency", "-c", help=t("cmd.config.account_add.opt.currency")),
|
||||
) -> None:
|
||||
"""Добавить счёт"""
|
||||
model = load_model()
|
||||
curr = currency.upper() if currency else model.base_currency
|
||||
account = Account(name=name, balance=balance, currency=curr)
|
||||
model.accounts.append(account)
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.account_add.ok", name=name, balance=balance, currency=curr))
|
||||
|
||||
|
||||
@app.command(name="account-list")
|
||||
def account_list() -> None:
|
||||
"""Список счетов"""
|
||||
model = load_model()
|
||||
if not model.accounts:
|
||||
print_warning(t("cmd.config.account_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.accounts_config.title"))
|
||||
table.add_column(t("table.accounts_config.col.id"), style="dim")
|
||||
table.add_column(t("table.accounts_config.col.name"), style="cyan")
|
||||
table.add_column(t("table.accounts_config.col.currency"))
|
||||
table.add_column(t("table.accounts_config.col.balance"), justify="right")
|
||||
for a in model.accounts:
|
||||
balance_str = CurrencyConverter.format_money(a.balance, a.currency)
|
||||
table.add_row(str(a.id)[:8], a.name, a.currency, balance_str)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="account-remove")
|
||||
def account_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.account_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить счёт по ID или названию"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"accounts",
|
||||
lambda a: str(a.id) == identifier or a.name == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.account_remove.ok",
|
||||
err_key="cmd.config.account_remove.err",
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""`cf config asset-*` — активы: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import Asset, CurrencyConverter
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def asset_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.asset_add.opt.name")),
|
||||
value: float = typer.Option(0.0, "--value", "-v", help=t("cmd.config.asset_add.opt.value")),
|
||||
growth_rate: float = typer.Option(0.0, "--growth", "-g", help=t("cmd.config.asset_add.opt.growth")),
|
||||
) -> None:
|
||||
"""Добавить актив"""
|
||||
model = load_model()
|
||||
asset = Asset(name=name, value=value, growth_rate=growth_rate)
|
||||
model.assets.append(asset)
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.asset_add.ok", name=name, value=value))
|
||||
|
||||
|
||||
@app.command(name="asset-list")
|
||||
def asset_list() -> None:
|
||||
"""Список активов"""
|
||||
model = load_model()
|
||||
if not model.assets:
|
||||
print_warning(t("cmd.config.asset_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.assets.title"))
|
||||
table.add_column(t("table.assets.col.id"), style="dim")
|
||||
table.add_column(t("table.assets.col.name"), style="cyan")
|
||||
table.add_column(t("table.assets.col.value"), justify="right")
|
||||
table.add_column(t("table.assets.col.growth"), justify="right")
|
||||
for a in model.assets:
|
||||
value_str = CurrencyConverter.format_money(a.value, model.base_currency)
|
||||
table.add_row(str(a.id)[:8], a.name, value_str, f"{a.growth_rate:.1f}%")
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="asset-remove")
|
||||
def asset_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.asset_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить актив по ID или названию"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"assets",
|
||||
lambda a: str(a.id) == identifier or a.name == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.asset_remove.ok",
|
||||
err_key="cmd.config.asset_remove.err",
|
||||
)
|
||||
@@ -0,0 +1,22 @@
|
||||
"""`cf config base-currency` — показать или установить базовую валюту модели."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def base_currency(
|
||||
currency: str = typer.Argument(None, help=t("cmd.config.base_currency.arg")),
|
||||
) -> None:
|
||||
"""Показать или установить базовую валюту модели"""
|
||||
model = load_model()
|
||||
if currency:
|
||||
model.base_currency = currency.upper()
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.base_currency.ok", currency=model.base_currency))
|
||||
else:
|
||||
console.print(t("cmd.config.base_currency.show", currency=f"[bold]{model.base_currency}[/bold]"))
|
||||
@@ -0,0 +1,62 @@
|
||||
"""`cf config liability-*` — обязательства: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter, Liability
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def liability_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.liability_add.opt.name")),
|
||||
balance: float = typer.Option(0.0, "--balance", "-b", help=t("cmd.config.liability_add.opt.balance")),
|
||||
interest: float = typer.Option(0.0, "--interest", "-i", help=t("cmd.config.liability_add.opt.interest")),
|
||||
payment: float = typer.Option(0.0, "--payment", "-p", help=t("cmd.config.liability_add.opt.payment")),
|
||||
) -> None:
|
||||
"""Добавить обязательство"""
|
||||
model = load_model()
|
||||
liability = Liability(name=name, balance=balance, interest=interest, payment=payment)
|
||||
model.liabilities.append(liability)
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.liability_add.ok", name=name, balance=balance))
|
||||
|
||||
|
||||
@app.command(name="liability-list")
|
||||
def liability_list() -> None:
|
||||
"""Список обязательств"""
|
||||
model = load_model()
|
||||
if not model.liabilities:
|
||||
print_warning(t("cmd.config.liability_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.liabilities.title"))
|
||||
table.add_column(t("table.liabilities.col.id"), style="dim")
|
||||
table.add_column(t("table.liabilities.col.name"), style="cyan")
|
||||
table.add_column(t("table.liabilities.col.balance"), justify="right")
|
||||
table.add_column(t("table.liabilities.col.rate"), justify="right")
|
||||
table.add_column(t("table.liabilities.col.payment"), justify="right")
|
||||
for li in model.liabilities:
|
||||
balance_str = CurrencyConverter.format_money(li.balance, model.base_currency)
|
||||
payment_str = CurrencyConverter.format_money(li.payment, model.base_currency)
|
||||
row = (str(li.id)[:8], li.name, balance_str, f"{li.interest:.1f}%", payment_str)
|
||||
table.add_row(*row)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="liability-remove")
|
||||
def liability_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.liability_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить обязательство по ID или названию"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"liabilities",
|
||||
lambda li: str(li.id) == identifier or li.name == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.liability_remove.ok",
|
||||
err_key="cmd.config.liability_remove.err",
|
||||
)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""`cf config rate-*` — курсы валют: добавление, список, удаление."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from domain import ExchangeRate
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_error, print_ok, print_warning
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def rate_set(
|
||||
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
|
||||
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
|
||||
rate: float = typer.Argument(..., help=t("cmd.config.rate_set.arg.rate")),
|
||||
) -> None:
|
||||
"""Добавить или обновить курс валюты"""
|
||||
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]
|
||||
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)
|
||||
print_ok(t("cmd.config.rate_set.ok", fc=fc, tc=tc, rate=rate_value))
|
||||
|
||||
|
||||
@app.command(name="rate-list")
|
||||
def rate_list() -> None:
|
||||
"""Список курсов валют"""
|
||||
model = load_model()
|
||||
if not model.exchange_rates:
|
||||
print_warning(t("cmd.config.rate_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.rates.title"))
|
||||
table.add_column(t("table.rates.col.from"), style="cyan")
|
||||
table.add_column(t("table.rates.col.to"), style="cyan")
|
||||
table.add_column(t("table.rates.col.rate"), justify="right")
|
||||
for r in model.exchange_rates:
|
||||
table.add_row(r.from_currency, r.to_currency, str(r.rate))
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="rate-remove")
|
||||
def rate_remove(
|
||||
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
|
||||
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
|
||||
) -> None:
|
||||
"""Удалить курс валюты"""
|
||||
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)]
|
||||
if len(model.exchange_rates) < initial:
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.rate_remove.ok", fc=fc, tc=tc))
|
||||
else:
|
||||
print_error(t("cmd.config.rate_remove.err", fc=fc, tc=tc))
|
||||
raise typer.Exit(1)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""`cf config recurring-*` — регулярные платежи: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter, RecurringCashflow
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def recurring_add(
|
||||
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.recurring_add.opt.amount")),
|
||||
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.recurring_add.opt.category")),
|
||||
frequency: str = typer.Option("monthly", "--frequency", "-f", help=t("cmd.config.recurring_add.opt.frequency")),
|
||||
start_date: str = typer.Option("", "--start", "-s", help=t("cmd.config.recurring_add.opt.start")),
|
||||
end_date: str = typer.Option("", "--end", "-e", help=t("cmd.config.recurring_add.opt.end")),
|
||||
) -> None:
|
||||
"""Добавить регулярный платёж"""
|
||||
model = load_model()
|
||||
rc = RecurringCashflow(
|
||||
start_date=start_date or "",
|
||||
end_date=end_date or "",
|
||||
frequency=frequency,
|
||||
amount=amount,
|
||||
category=category,
|
||||
)
|
||||
model.recurring.append(rc)
|
||||
save_model(model)
|
||||
amount_str = CurrencyConverter.format_money(abs(amount), model.base_currency)
|
||||
print_ok(t("cmd.config.recurring_add.ok", amount_str=amount_str, frequency=frequency))
|
||||
|
||||
|
||||
@app.command(name="recurring-list")
|
||||
def recurring_list() -> None:
|
||||
"""Список регулярных платежей"""
|
||||
model = load_model()
|
||||
if not model.recurring:
|
||||
print_warning(t("cmd.config.recurring_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.recurring.title"))
|
||||
table.add_column(t("table.recurring.col.id"), style="dim")
|
||||
table.add_column(t("table.recurring.col.start"))
|
||||
table.add_column(t("table.recurring.col.end"))
|
||||
table.add_column(t("table.recurring.col.period"))
|
||||
table.add_column(t("table.recurring.col.amount"), justify="right")
|
||||
table.add_column(t("table.recurring.col.category"))
|
||||
for r in model.recurring:
|
||||
amount_str = CurrencyConverter.format_money(r.amount, model.base_currency)
|
||||
row = (str(r.id)[:8], r.start_date, r.end_date, r.frequency, amount_str, r.category)
|
||||
table.add_row(*row)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="recurring-remove")
|
||||
def recurring_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.recurring_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить регулярный платёж по ID"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"recurring",
|
||||
lambda r: str(r.id) == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.recurring_remove.ok",
|
||||
err_key="cmd.config.recurring_remove.err",
|
||||
)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""`cf config transaction-*` — транзакции: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter, Transaction
|
||||
from infrastructure.cli.commands.config._app import app
|
||||
from infrastructure.cli.commands.config._helpers import print_error, print_ok, print_warning, remove_items
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@app.command()
|
||||
def transaction_add(
|
||||
account: str = typer.Option(..., "--account", "-a", help=t("cmd.config.transaction_add.opt.account")),
|
||||
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.transaction_add.opt.amount")),
|
||||
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.transaction_add.opt.category")),
|
||||
description: str = typer.Option("", "--description", "-d", help=t("cmd.config.transaction_add.opt.description")),
|
||||
date: str = typer.Option("", "--date", "-D", help=t("cmd.config.transaction_add.opt.date")),
|
||||
) -> None:
|
||||
"""Добавить транзакцию"""
|
||||
model = load_model()
|
||||
account_id = _resolve_account_id(model, account)
|
||||
if not account_id:
|
||||
print_error(t("cmd.config.transaction_add.err", account=account))
|
||||
raise typer.Exit(1)
|
||||
txn = Transaction(
|
||||
date=date or "",
|
||||
account=account_id,
|
||||
category=category,
|
||||
amount=amount,
|
||||
description=description,
|
||||
)
|
||||
model.transactions.append(txn)
|
||||
save_model(model)
|
||||
kind = t("cmd.config.transaction_add.kind.income") if amount >= 0 else t("cmd.config.transaction_add.kind.expense")
|
||||
amount_str = CurrencyConverter.format_money(abs(amount), _account_currency(model, account_id))
|
||||
print_ok(t("cmd.config.transaction_add.ok", kind=kind, amount_str=amount_str, account=account))
|
||||
|
||||
|
||||
@app.command(name="transaction-list")
|
||||
def transaction_list() -> None:
|
||||
"""Список транзакций"""
|
||||
model = load_model()
|
||||
if not model.transactions:
|
||||
print_warning(t("cmd.config.transaction_list.empty"))
|
||||
return
|
||||
table = Table(title=t("table.transactions.title"))
|
||||
table.add_column(t("table.accounts_config.col.id"), style="dim")
|
||||
table.add_column(t("table.transactions.col.date"))
|
||||
table.add_column(t("table.accounts_config.col.name"))
|
||||
table.add_column(t("table.transactions.col.category"))
|
||||
table.add_column(t("table.transactions.col.amount"), justify="right")
|
||||
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))
|
||||
table.add_row(
|
||||
str(tx.id)[:8],
|
||||
tx.date,
|
||||
account_name,
|
||||
tx.category,
|
||||
amount_str,
|
||||
tx.description,
|
||||
)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="transaction-remove")
|
||||
def transaction_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.transaction_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить транзакцию по ID"""
|
||||
model = load_model()
|
||||
remove_items(
|
||||
model,
|
||||
"transactions",
|
||||
lambda tx: str(tx.id) == identifier,
|
||||
identifier=identifier,
|
||||
ok_key="cmd.config.transaction_remove.ok",
|
||||
err_key="cmd.config.transaction_remove.err",
|
||||
)
|
||||
|
||||
|
||||
# ── helpers ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _resolve_account_id(model, identifier: str) -> str | None:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == identifier or a.name == identifier:
|
||||
return str(a.id)
|
||||
return None
|
||||
|
||||
|
||||
def _account_name(model, account_id: str) -> str:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == account_id:
|
||||
return a.name
|
||||
return account_id[:8]
|
||||
|
||||
|
||||
def _account_currency(model, account_id: str) -> str:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == account_id:
|
||||
return a.currency
|
||||
return model.base_currency
|
||||
@@ -1,435 +0,0 @@
|
||||
"""cf config — подкоманды для редактирования модели (базовая валюта, счета, транзакции, ...)."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from domain import (
|
||||
Account,
|
||||
Asset,
|
||||
CurrencyConverter,
|
||||
ExchangeRate,
|
||||
Liability,
|
||||
RecurringCashflow,
|
||||
Transaction,
|
||||
)
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
app = typer.Typer(name="config", help=t("config.help"))
|
||||
|
||||
|
||||
# ── base-currency ──────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def base_currency(
|
||||
currency: str = typer.Argument(None, help=t("cmd.config.base_currency.arg")),
|
||||
) -> None:
|
||||
"""Показать или установить базовую валюту модели"""
|
||||
model = load_model()
|
||||
if currency:
|
||||
model.base_currency = currency.upper()
|
||||
save_model(model)
|
||||
ok = t("global.ok")
|
||||
msg = t("cmd.config.base_currency.ok", currency=model.base_currency)
|
||||
console.print(f"[green]{ok}[/green] {msg}")
|
||||
else:
|
||||
console.print(t("cmd.config.base_currency.show", currency=f"[bold]{model.base_currency}[/bold]"))
|
||||
|
||||
|
||||
# ── rate ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def rate_set(
|
||||
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
|
||||
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
|
||||
rate: float = typer.Argument(..., help=t("cmd.config.rate_set.arg.rate")),
|
||||
) -> None:
|
||||
"""Добавить или обновить курс валюты"""
|
||||
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]
|
||||
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_value)}")
|
||||
|
||||
|
||||
@app.command(name="rate-list")
|
||||
def rate_list() -> None:
|
||||
"""Список курсов валют"""
|
||||
model = load_model()
|
||||
if not model.exchange_rates:
|
||||
console.print(f"[yellow]{t('cmd.config.rate_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.rates.title"))
|
||||
table.add_column(t("table.rates.col.from"), style="cyan")
|
||||
table.add_column(t("table.rates.col.to"), style="cyan")
|
||||
table.add_column(t("table.rates.col.rate"), justify="right")
|
||||
for r in model.exchange_rates:
|
||||
table.add_row(r.from_currency, r.to_currency, str(r.rate))
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="rate-remove")
|
||||
def rate_remove(
|
||||
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
|
||||
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
|
||||
) -> None:
|
||||
"""Удалить курс валюты"""
|
||||
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)]
|
||||
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)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.rate_remove.err', fc=fc, tc=tc)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── account ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def account_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.account_add.opt.name")),
|
||||
balance: float = typer.Option(0.0, "--balance", "-b", help=t("cmd.config.account_add.opt.balance")),
|
||||
currency: str = typer.Option("", "--currency", "-c", help=t("cmd.config.account_add.opt.currency")),
|
||||
) -> None:
|
||||
"""Добавить счёт"""
|
||||
model = load_model()
|
||||
curr = currency.upper() if currency else model.base_currency
|
||||
account = Account(name=name, balance=balance, currency=curr)
|
||||
model.accounts.append(account)
|
||||
save_model(model)
|
||||
ok = t("global.ok")
|
||||
msg = t("cmd.config.account_add.ok", name=name, balance=balance, currency=curr)
|
||||
console.print(f"[green]{ok}[/green] {msg}")
|
||||
|
||||
|
||||
@app.command(name="account-list")
|
||||
def account_list() -> None:
|
||||
"""Список счетов"""
|
||||
model = load_model()
|
||||
if not model.accounts:
|
||||
console.print(f"[yellow]{t('cmd.config.account_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.accounts_config.title"))
|
||||
table.add_column(t("table.accounts_config.col.id"), style="dim")
|
||||
table.add_column(t("table.accounts_config.col.name"), style="cyan")
|
||||
table.add_column(t("table.accounts_config.col.currency"))
|
||||
table.add_column(t("table.accounts_config.col.balance"), justify="right")
|
||||
for a in model.accounts:
|
||||
balance_str = CurrencyConverter.format_money(a.balance, a.currency)
|
||||
table.add_row(str(a.id)[:8], a.name, a.currency, balance_str)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="account-remove")
|
||||
def account_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.account_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить счёт по 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]
|
||||
if len(model.accounts) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.account_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.account_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── transaction ────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def transaction_add(
|
||||
account: str = typer.Option(..., "--account", "-a", help=t("cmd.config.transaction_add.opt.account")),
|
||||
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.transaction_add.opt.amount")),
|
||||
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.transaction_add.opt.category")),
|
||||
description: str = typer.Option("", "--description", "-d", help=t("cmd.config.transaction_add.opt.description")),
|
||||
date: str = typer.Option("", "--date", "-D", help=t("cmd.config.transaction_add.opt.date")),
|
||||
) -> None:
|
||||
"""Добавить транзакцию"""
|
||||
model = load_model()
|
||||
account_id = _resolve_account_id(model, account)
|
||||
if not account_id:
|
||||
console.print(f"[red]{t('cmd.config.transaction_add.err', account=account)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
txn = Transaction(
|
||||
date=date or "",
|
||||
account=account_id,
|
||||
category=category,
|
||||
amount=amount,
|
||||
description=description,
|
||||
)
|
||||
model.transactions.append(txn)
|
||||
save_model(model)
|
||||
kind = t("cmd.config.transaction_add.kind.income") if amount >= 0 else t("cmd.config.transaction_add.kind.expense")
|
||||
amount_str = CurrencyConverter.format_money(abs(amount), _account_currency(model, account_id))
|
||||
ok = t("global.ok")
|
||||
msg = t("cmd.config.transaction_add.ok", kind=kind, amount_str=amount_str, account=account)
|
||||
console.print(f"[green]{ok}[/green] {msg}")
|
||||
|
||||
|
||||
@app.command(name="transaction-list")
|
||||
def transaction_list() -> None:
|
||||
"""Список транзакций"""
|
||||
model = load_model()
|
||||
if not model.transactions:
|
||||
console.print(f"[yellow]{t('cmd.config.transaction_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.transactions.title"))
|
||||
table.add_column(t("table.accounts_config.col.id"), style="dim")
|
||||
table.add_column(t("table.transactions.col.date"))
|
||||
table.add_column(t("table.accounts_config.col.name"))
|
||||
table.add_column(t("table.transactions.col.category"))
|
||||
table.add_column(t("table.transactions.col.amount"), justify="right")
|
||||
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))
|
||||
table.add_row(
|
||||
str(tx.id)[:8],
|
||||
tx.date,
|
||||
account_name,
|
||||
tx.category,
|
||||
amount_str,
|
||||
tx.description,
|
||||
)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="transaction-remove")
|
||||
def transaction_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.transaction_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить транзакцию по ID"""
|
||||
model = load_model()
|
||||
initial = len(model.transactions)
|
||||
model.transactions = [t for t in model.transactions if str(t.id) != identifier]
|
||||
if len(model.transactions) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.transaction_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.transaction_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── recurring ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def recurring_add(
|
||||
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.recurring_add.opt.amount")),
|
||||
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.recurring_add.opt.category")),
|
||||
frequency: str = typer.Option("monthly", "--frequency", "-f", help=t("cmd.config.recurring_add.opt.frequency")),
|
||||
start_date: str = typer.Option("", "--start", "-s", help=t("cmd.config.recurring_add.opt.start")),
|
||||
end_date: str = typer.Option("", "--end", "-e", help=t("cmd.config.recurring_add.opt.end")),
|
||||
) -> None:
|
||||
"""Добавить регулярный платёж"""
|
||||
model = load_model()
|
||||
rc = RecurringCashflow(
|
||||
start_date=start_date or "",
|
||||
end_date=end_date or "",
|
||||
frequency=frequency,
|
||||
amount=amount,
|
||||
category=category,
|
||||
)
|
||||
model.recurring.append(rc)
|
||||
save_model(model)
|
||||
amount_str = CurrencyConverter.format_money(abs(amount), model.base_currency)
|
||||
ok = t("global.ok")
|
||||
msg = t("cmd.config.recurring_add.ok", amount_str=amount_str, frequency=frequency)
|
||||
console.print(f"[green]{ok}[/green] {msg}")
|
||||
|
||||
|
||||
@app.command(name="recurring-list")
|
||||
def recurring_list() -> None:
|
||||
"""Список регулярных платежей"""
|
||||
model = load_model()
|
||||
if not model.recurring:
|
||||
console.print(f"[yellow]{t('cmd.config.recurring_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.recurring.title"))
|
||||
table.add_column(t("table.recurring.col.id"), style="dim")
|
||||
table.add_column(t("table.recurring.col.start"))
|
||||
table.add_column(t("table.recurring.col.end"))
|
||||
table.add_column(t("table.recurring.col.period"))
|
||||
table.add_column(t("table.recurring.col.amount"), justify="right")
|
||||
table.add_column(t("table.recurring.col.category"))
|
||||
for r in model.recurring:
|
||||
amount_str = CurrencyConverter.format_money(r.amount, model.base_currency)
|
||||
row = (str(r.id)[:8], r.start_date, r.end_date, r.frequency, amount_str, r.category)
|
||||
table.add_row(*row)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="recurring-remove")
|
||||
def recurring_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.recurring_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить регулярный платёж по ID"""
|
||||
model = load_model()
|
||||
initial = len(model.recurring)
|
||||
model.recurring = [r for r in model.recurring if str(r.id) != identifier]
|
||||
if len(model.recurring) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.recurring_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.recurring_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── asset ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def asset_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.asset_add.opt.name")),
|
||||
value: float = typer.Option(0.0, "--value", "-v", help=t("cmd.config.asset_add.opt.value")),
|
||||
growth_rate: float = typer.Option(0.0, "--growth", "-g", help=t("cmd.config.asset_add.opt.growth")),
|
||||
) -> None:
|
||||
"""Добавить актив"""
|
||||
model = load_model()
|
||||
asset = Asset(name=name, value=value, growth_rate=growth_rate)
|
||||
model.assets.append(asset)
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.asset_add.ok', name=name, value=value)}")
|
||||
|
||||
|
||||
@app.command(name="asset-list")
|
||||
def asset_list() -> None:
|
||||
"""Список активов"""
|
||||
model = load_model()
|
||||
if not model.assets:
|
||||
console.print(f"[yellow]{t('cmd.config.asset_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.assets.title"))
|
||||
table.add_column(t("table.assets.col.id"), style="dim")
|
||||
table.add_column(t("table.assets.col.name"), style="cyan")
|
||||
table.add_column(t("table.assets.col.value"), justify="right")
|
||||
table.add_column(t("table.assets.col.growth"), justify="right")
|
||||
for a in model.assets:
|
||||
value_str = CurrencyConverter.format_money(a.value, model.base_currency)
|
||||
table.add_row(str(a.id)[:8], a.name, value_str, f"{a.growth_rate:.1f}%")
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="asset-remove")
|
||||
def asset_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.asset_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить актив по 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]
|
||||
if len(model.assets) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.asset_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.asset_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── liability ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.command()
|
||||
def liability_add(
|
||||
name: str = typer.Option(..., "--name", "-n", help=t("cmd.config.liability_add.opt.name")),
|
||||
balance: float = typer.Option(0.0, "--balance", "-b", help=t("cmd.config.liability_add.opt.balance")),
|
||||
interest: float = typer.Option(0.0, "--interest", "-i", help=t("cmd.config.liability_add.opt.interest")),
|
||||
payment: float = typer.Option(0.0, "--payment", "-p", help=t("cmd.config.liability_add.opt.payment")),
|
||||
) -> None:
|
||||
"""Добавить обязательство"""
|
||||
model = load_model()
|
||||
liability = Liability(name=name, balance=balance, interest=interest, payment=payment)
|
||||
model.liabilities.append(liability)
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.liability_add.ok', name=name, balance=balance)}")
|
||||
|
||||
|
||||
@app.command(name="liability-list")
|
||||
def liability_list() -> None:
|
||||
"""Список обязательств"""
|
||||
model = load_model()
|
||||
if not model.liabilities:
|
||||
console.print(f"[yellow]{t('cmd.config.liability_list.empty')}[/yellow]")
|
||||
return
|
||||
table = Table(title=t("table.liabilities.title"))
|
||||
table.add_column(t("table.liabilities.col.id"), style="dim")
|
||||
table.add_column(t("table.liabilities.col.name"), style="cyan")
|
||||
table.add_column(t("table.liabilities.col.balance"), justify="right")
|
||||
table.add_column(t("table.liabilities.col.rate"), justify="right")
|
||||
table.add_column(t("table.liabilities.col.payment"), justify="right")
|
||||
for li in model.liabilities:
|
||||
balance_str = CurrencyConverter.format_money(li.balance, model.base_currency)
|
||||
payment_str = CurrencyConverter.format_money(li.payment, model.base_currency)
|
||||
row = (str(li.id)[:8], li.name, balance_str, f"{li.interest:.1f}%", payment_str)
|
||||
table.add_row(*row)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command(name="liability-remove")
|
||||
def liability_remove(
|
||||
identifier: str = typer.Argument(..., help=t("cmd.config.liability_remove.arg")),
|
||||
) -> None:
|
||||
"""Удалить обязательство по 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]
|
||||
if len(model.liabilities) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.liability_remove.ok', id=identifier)}")
|
||||
else:
|
||||
console.print(f"[red]{t('cmd.config.liability_remove.err', id=identifier)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
# ── helpers ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _resolve_account_id(model, identifier: str) -> str | None:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == identifier or a.name == identifier:
|
||||
return str(a.id)
|
||||
return None
|
||||
|
||||
|
||||
def _account_name(model, account_id: str) -> str:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == account_id:
|
||||
return a.name
|
||||
return account_id[:8]
|
||||
|
||||
|
||||
def _account_currency(model, account_id: str) -> str:
|
||||
for a in model.accounts:
|
||||
if str(a.id) == account_id:
|
||||
return a.currency
|
||||
return model.base_currency
|
||||
@@ -65,3 +65,37 @@ class TestNoCliDependency:
|
||||
if imports:
|
||||
offenders[str(path.relative_to(REPO_ROOT))] = imports
|
||||
assert not offenders, f"infrastructure/ai импортирует CLI: {offenders}"
|
||||
|
||||
|
||||
COMMANDS_ROOT = CLI_ROOT / "commands"
|
||||
CONFIG_PKG = COMMANDS_ROOT / "config"
|
||||
|
||||
|
||||
def _typer_instantiations(path: Path) -> list[int]:
|
||||
"""Номера строк, где модуль создаёт `typer.Typer(...)` (D3: мёртвые Typer'ы)."""
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
lines = []
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "Typer":
|
||||
lines.append(node.lineno)
|
||||
return lines
|
||||
|
||||
|
||||
class TestTyperRegistration:
|
||||
"""D25: один Typer-объект на пакет `config`, остальные модули только декорируют."""
|
||||
|
||||
def test_config_package_creates_exactly_one_typer(self):
|
||||
hits = {path: _typer_instantiations(path) for path in sorted(CONFIG_PKG.rglob("*.py"))}
|
||||
hits = {path: lines for path, lines in hits.items() if lines}
|
||||
assert set(hits) == {CONFIG_PKG / "_app.py"}, f"Typer создаётся не только в _app.py: {sorted(map(str, hits))}"
|
||||
assert len(hits[CONFIG_PKG / "_app.py"]) == 1
|
||||
|
||||
def test_other_command_modules_do_not_create_typer_apps(self):
|
||||
offenders = {}
|
||||
for path in sorted(COMMANDS_ROOT.rglob("*.py")):
|
||||
if CONFIG_PKG in path.parents:
|
||||
continue
|
||||
lines = _typer_instantiations(path)
|
||||
if lines:
|
||||
offenders[str(path.relative_to(REPO_ROOT))] = lines
|
||||
assert not offenders, f"модули команд создают собственные Typer: {offenders}"
|
||||
+118
-9
@@ -1,17 +1,22 @@
|
||||
"""Инвариант публичной поверхности CLI.
|
||||
|
||||
Фиксирует набор команд, подкоманд и дефолтных путей, которые видит
|
||||
пользователь. Обязан проходить ДО и ПОСЛЕ любых рефакторингов структуры
|
||||
CLI (D3 — удаление мёртвых typer.Typer(), D25 — разбиение config_cmd.py
|
||||
на пакет): если набор изменился, поведение CLI изменилось без
|
||||
согласования — тест обязан упасть.
|
||||
Фиксирует набор команд, подкоманд, их аргументов/опций и значений по умолчанию —
|
||||
всё, что видит пользователь. Обязан проходить ДО и ПОСЛЕ любых рефакторингов
|
||||
структуры CLI (D3 — удаление мёртвых `typer.Typer()`, D25 — разбиение
|
||||
`config_cmd.py` на пакет `commands/config/`, D26/D27 — вынос i18n): если
|
||||
поверхность изменилась, поведение CLI изменилось без согласования — тест
|
||||
обязан упасть.
|
||||
|
||||
Проверяется по click-представлению (то, что реально исполняется), а не по
|
||||
исходникам: имя команды, порядок и имена параметров, длинные/короткие опции,
|
||||
default и required.
|
||||
"""
|
||||
|
||||
import typer
|
||||
from typer.main import get_command
|
||||
|
||||
from infrastructure.cli.app import app
|
||||
from infrastructure.cli.commands import config_cmd
|
||||
from infrastructure.cli.commands.config import app as config_app
|
||||
|
||||
EXPECTED_COMMANDS = {
|
||||
"init",
|
||||
@@ -49,6 +54,83 @@ EXPECTED_CONFIG_COMMANDS = {
|
||||
|
||||
EXPECTED_EXPORT_DEFAULT = "exports/forecast.xlsx"
|
||||
|
||||
# (имя параметра, опции в порядке объявления, default, required)
|
||||
EXPECTED_PARAMS = {
|
||||
"init": [],
|
||||
"forecast": [("months", ("--months", "-m"), 12, False), ("currency", ("--currency", "-c"), None, False)],
|
||||
"scenario": [
|
||||
("name", ("name",), "baseline", False),
|
||||
("months", ("--months", "-m"), 12, False),
|
||||
("currency", ("--currency", "-c"), None, False),
|
||||
],
|
||||
"whatif": [
|
||||
("income", ("--income", "-i"), 1.0, False),
|
||||
("expense", ("--expense", "-e"), 1.0, False),
|
||||
("growth", ("--growth", "-g"), 1.0, False),
|
||||
("months", ("--months", "-m"), 12, False),
|
||||
("currency", ("--currency", "-c"), None, False),
|
||||
],
|
||||
"compare": [("months", ("--months", "-m"), 12, False), ("currency", ("--currency", "-c"), None, False)],
|
||||
"import-xlsx": [("path", ("path",), None, True)],
|
||||
"export-xlsx": [("path", ("path",), EXPECTED_EXPORT_DEFAULT, False)],
|
||||
"analyze": [("months", ("--months", "-m"), 12, False), ("currency", ("--currency", "-c"), None, False)],
|
||||
"info": [],
|
||||
}
|
||||
|
||||
EXPECTED_CONFIG_PARAMS = {
|
||||
"base-currency": [("currency", ("currency",), None, False)],
|
||||
"rate-set": [
|
||||
("from_currency", ("from_currency",), None, True),
|
||||
("to_currency", ("to_currency",), None, True),
|
||||
("rate", ("rate",), None, True),
|
||||
],
|
||||
"rate-list": [],
|
||||
"rate-remove": [
|
||||
("from_currency", ("from_currency",), None, True),
|
||||
("to_currency", ("to_currency",), None, True),
|
||||
],
|
||||
"account-add": [
|
||||
("name", ("--name", "-n"), None, True),
|
||||
("balance", ("--balance", "-b"), 0.0, False),
|
||||
("currency", ("--currency", "-c"), "", False),
|
||||
],
|
||||
"account-list": [],
|
||||
"account-remove": [("identifier", ("identifier",), None, True)],
|
||||
"transaction-add": [
|
||||
("account", ("--account", "-a"), None, True),
|
||||
("amount", ("--amount", "-m"), None, True),
|
||||
("category", ("--category", "-c"), "", False),
|
||||
("description", ("--description", "-d"), "", False),
|
||||
("date", ("--date", "-D"), "", False),
|
||||
],
|
||||
"transaction-list": [],
|
||||
"transaction-remove": [("identifier", ("identifier",), None, True)],
|
||||
"recurring-add": [
|
||||
("amount", ("--amount", "-m"), None, True),
|
||||
("category", ("--category", "-c"), "", False),
|
||||
("frequency", ("--frequency", "-f"), "monthly", False),
|
||||
("start_date", ("--start", "-s"), "", False),
|
||||
("end_date", ("--end", "-e"), "", False),
|
||||
],
|
||||
"recurring-list": [],
|
||||
"recurring-remove": [("identifier", ("identifier",), None, True)],
|
||||
"asset-add": [
|
||||
("name", ("--name", "-n"), None, True),
|
||||
("value", ("--value", "-v"), 0.0, False),
|
||||
("growth_rate", ("--growth", "-g"), 0.0, False),
|
||||
],
|
||||
"asset-list": [],
|
||||
"asset-remove": [("identifier", ("identifier",), None, True)],
|
||||
"liability-add": [
|
||||
("name", ("--name", "-n"), None, True),
|
||||
("balance", ("--balance", "-b"), 0.0, False),
|
||||
("interest", ("--interest", "-i"), 0.0, False),
|
||||
("payment", ("--payment", "-p"), 0.0, False),
|
||||
],
|
||||
"liability-list": [],
|
||||
"liability-remove": [("identifier", ("identifier",), None, True)],
|
||||
}
|
||||
|
||||
|
||||
def _click_app(typer_app: typer.Typer):
|
||||
"""Развернуть Typer-приложение в click-команду (то, что видит пользователь)."""
|
||||
@@ -59,12 +141,16 @@ def _command_names(typer_app: typer.Typer) -> set[str]:
|
||||
return set(_click_app(typer_app).commands.keys())
|
||||
|
||||
|
||||
def _params(command) -> list[tuple[str, tuple[str, ...], object, bool]]:
|
||||
return [(p.name, tuple(p.opts), p.default, p.required) for p in command.params]
|
||||
|
||||
|
||||
class TestCliSurface:
|
||||
def test_top_level_commands(self):
|
||||
assert _command_names(app) == EXPECTED_COMMANDS | {"config"}
|
||||
|
||||
def test_config_subcommands(self):
|
||||
assert _command_names(config_cmd.app) == EXPECTED_CONFIG_COMMANDS
|
||||
assert _command_names(config_app) == EXPECTED_CONFIG_COMMANDS
|
||||
|
||||
def test_config_subapp_reachable_from_root(self):
|
||||
root = _click_app(app)
|
||||
@@ -78,11 +164,34 @@ class TestCliSurface:
|
||||
continue # sub-typer (config) — у группы callback'а нет by design
|
||||
assert command.callback is not None, f"команда {name} без callback"
|
||||
|
||||
for name, command in _click_app(config_cmd.app).commands.items():
|
||||
for name, command in _click_app(config_app).commands.items():
|
||||
assert command.callback is not None, f"команда config {name} без callback"
|
||||
|
||||
|
||||
class TestDefaultPaths:
|
||||
class TestCliParameters:
|
||||
"""Имя, опции и default каждой команды/подкоманды — часть контракта."""
|
||||
|
||||
def test_top_level_parameters_and_defaults(self):
|
||||
root = _click_app(app)
|
||||
actual = {name: _params(command) for name, command in root.commands.items() if not hasattr(command, "commands")}
|
||||
assert actual == EXPECTED_PARAMS
|
||||
|
||||
def test_config_parameters_and_defaults(self):
|
||||
actual = {name: _params(command) for name, command in _click_app(config_app).commands.items()}
|
||||
assert actual == EXPECTED_CONFIG_PARAMS
|
||||
|
||||
def test_every_parameter_has_help(self):
|
||||
"""Справка опции не должна теряться при переносе команд между модулями."""
|
||||
root = _click_app(app)
|
||||
for name, command in root.commands.items():
|
||||
if hasattr(command, "commands"):
|
||||
continue
|
||||
for param in command.params:
|
||||
assert param.help, f"{name}: у параметра {param.name} пустая справка"
|
||||
for name, command in _click_app(config_app).commands.items():
|
||||
for param in command.params:
|
||||
assert param.help, f"config {name}: у параметра {param.name} пустая справка"
|
||||
|
||||
def test_export_xlsx_default_path_is_unchanged(self):
|
||||
"""Дефолт `cf export-xlsx` — строка, которую видит пользователь в --help."""
|
||||
command = _click_app(app).commands["export-xlsx"]
|
||||
|
||||
+2
-2
@@ -125,8 +125,8 @@ class TestFinancialModel:
|
||||
class TestValidateAssignment:
|
||||
"""D17: модели домена валидируют присваивание (validate_assignment=True).
|
||||
|
||||
Раньше `r.rate = -5` молча принимался, а `config_cmd.py` писал в поле
|
||||
Decimal значение типа float — валидатор при этом не срабатывал.
|
||||
Раньше `r.rate = -5` молча принимался, а команда `cf config rate-set`
|
||||
писала в поле Decimal значение типа float — валидатор при этом не срабатывал.
|
||||
"""
|
||||
|
||||
def test_negative_rate_is_rejected_on_assignment(self):
|
||||
|
||||
Reference in new issue
Block a user