diff --git a/README.arch.md b/README.arch.md index 46c15d1..f810206 100644 --- a/README.arch.md +++ b/README.arch.md @@ -159,6 +159,12 @@ Spreadsheet Export - Web UI; - Mobile App; - AI Financial Assistant. + +> **Статус после D27.** Блокирующей связи `infrastructure/ai/` → `infrastructure/cli/` +> больше нет: i18n вынесен в `infrastructure/i18n/`, и AI-слой переиспользуем +> без CLI. REST API и Web UI могут строиться поверх `application/` + +> `infrastructure/ai/` напрямую; направление зависимостей закреплено тестом +> `tests/test_architecture.py`. ## Структура репозитория diff --git a/README.md b/README.md index b8236d7..1530169 100644 --- a/README.md +++ b/README.md @@ -158,8 +158,11 @@ cashflow-forecast/ │ │ ├── app.py # Entry point │ │ ├── commands/ # 10 файлов команд + config sub-typer │ │ ├── paths.py # AppPaths — пути (CF_DATA_DIR) -│ │ ├── services.py # Composition root + helpers -│ │ └── i18n.py # ru-переводы (словарь "en" пуст, откат на ru) +│ │ └── services.py # Composition root + helpers +│ ├── i18n/ # Локализация (не зависит от CLI) +│ │ ├── __init__.py # t(), setup_i18n(), set_lang(), резолв языка +│ │ ├── ru.py # ru-словарь (единственный заполненный) +│ │ └── en.py # en-словарь (пуст → откат на ru) │ ├── ai/ # AI-ассистент (заглушка) │ │ ├── prompts.py │ │ └── assistant.py # AssistantService @@ -167,7 +170,7 @@ cashflow-forecast/ │ ├── json_file_repository.py │ └── excel_repository.py │ -├── tests/ # pytest, 229 тестов +├── tests/ # pytest, 236 тестов │ ├── conftest.py │ ├── test_model.py │ ├── test_forecast.py @@ -176,6 +179,7 @@ cashflow-forecast/ │ ├── test_ai.py │ ├── test_cli.py │ ├── test_cli_contract.py # Инвариант публичной поверхности CLI +│ ├── test_architecture.py # Направления зависимостей (нет AI → CLI) │ ├── test_excel_sync.py # Тесты ExcelRepository │ ├── test_i18n.py │ ├── test_paths.py # Пути и CF_DATA_DIR @@ -227,12 +231,17 @@ 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` — словарь только на русском. Английские - переводы не реализованы: словарь `"en"` пуст, поэтому `CF_LANG=en` **молча - откатывается на `ru`** (интерфейс остаётся русским, предупреждения нет). +- **i18n**: `infrastructure/i18n/` — рантайм (`t()`, `setup_i18n()`, `set_lang()`, + резолв языка) в `__init__.py`, словари в `ru.py` и `en.py`. Словарь только на + русском. Английские переводы не реализованы: словарь `"en"` пуст, поэтому + `CF_LANG=en` **молча откатывается на `ru`** (интерфейс остаётся русским, + предупреждения нет). Язык определяется при импорте модуля i18n — до первого вызова `t()`, поэтому `CF_LANG` действует и на строки, собираемые на этапе импорта команд. Как только в словаре появится непустой перевод, он будет выбран по `CF_LANG`. + Пакет не зависит от `infrastructure/cli/`: `infrastructure/ai/prompts.py` + импортирует `infrastructure.i18n`, поэтому AI-слой переиспользуем без CLI + (REST API / Web UI). Направление зависимостей закреплено `tests/test_architecture.py`. - **Тесты**: pytest, файлы состояния не пишутся в дерево репозитория (CWD теста переводится во временный каталог). diff --git a/infrastructure/ai/prompts.py b/infrastructure/ai/prompts.py index 12c107c..97fa051 100644 --- a/infrastructure/ai/prompts.py +++ b/infrastructure/ai/prompts.py @@ -1,4 +1,4 @@ -from infrastructure.cli.i18n import t +from infrastructure.i18n import t ANALYZE_PROMPT = t("prompt.analyze") ADVICE_PROMPT = t("prompt.advice") diff --git a/infrastructure/cli/app.py b/infrastructure/cli/app.py index 00af5a8..bfa5bc9 100644 --- a/infrastructure/cli/app.py +++ b/infrastructure/cli/app.py @@ -21,9 +21,9 @@ from infrastructure.cli.commands import ( scenario, whatif, ) -from infrastructure.cli.i18n import setup_i18n, t +from infrastructure.i18n import setup_i18n, t -setup_i18n() # язык уже определён при импорте infrastructure.cli.i18n (D20) +setup_i18n() # язык уже определён при импорте infrastructure.i18n (D20) app = typer.Typer(name="cf", help=t("app.help")) diff --git a/infrastructure/cli/commands/analyze.py b/infrastructure/cli/commands/analyze.py index 23f6acd..48cfd84 100644 --- a/infrastructure/cli/commands/analyze.py +++ b/infrastructure/cli/commands/analyze.py @@ -2,8 +2,8 @@ import typer -from infrastructure.cli.i18n import t from infrastructure.cli.services import build_services, console, load_model, resolve_currency +from infrastructure.i18n import t CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) diff --git a/infrastructure/cli/commands/compare.py b/infrastructure/cli/commands/compare.py index bf9f156..cef2ccb 100644 --- a/infrastructure/cli/commands/compare.py +++ b/infrastructure/cli/commands/compare.py @@ -4,7 +4,6 @@ import typer from pydantic import ValidationError from rich.table import Table -from infrastructure.cli.i18n import t from infrastructure.cli.services import ( build_services, console, @@ -14,6 +13,7 @@ from infrastructure.cli.services import ( load_model, resolve_currency, ) +from infrastructure.i18n import t CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) diff --git a/infrastructure/cli/commands/config_cmd.py b/infrastructure/cli/commands/config_cmd.py index f9207a3..6bdb8c0 100644 --- a/infrastructure/cli/commands/config_cmd.py +++ b/infrastructure/cli/commands/config_cmd.py @@ -15,8 +15,8 @@ from domain import ( RecurringCashflow, Transaction, ) -from infrastructure.cli.i18n import t 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")) diff --git a/infrastructure/cli/commands/export_xlsx.py b/infrastructure/cli/commands/export_xlsx.py index 729c544..6c63f50 100644 --- a/infrastructure/cli/commands/export_xlsx.py +++ b/infrastructure/cli/commands/export_xlsx.py @@ -2,9 +2,9 @@ import typer -from infrastructure.cli.i18n import t from infrastructure.cli.paths import AppPaths from infrastructure.cli.services import console, load_model +from infrastructure.i18n import t from infrastructure.repositories import ExcelRepository, ExcelRepositoryError _repo = ExcelRepository() diff --git a/infrastructure/cli/commands/forecast.py b/infrastructure/cli/commands/forecast.py index 6a0c5c6..0d9c86f 100644 --- a/infrastructure/cli/commands/forecast.py +++ b/infrastructure/cli/commands/forecast.py @@ -3,7 +3,6 @@ import typer from rich.table import Table -from infrastructure.cli.i18n import t from infrastructure.cli.services import ( build_services, console, @@ -12,6 +11,7 @@ from infrastructure.cli.services import ( load_model, resolve_currency, ) +from infrastructure.i18n import t CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) diff --git a/infrastructure/cli/commands/import_xlsx.py b/infrastructure/cli/commands/import_xlsx.py index 05cc3f5..c34deb5 100644 --- a/infrastructure/cli/commands/import_xlsx.py +++ b/infrastructure/cli/commands/import_xlsx.py @@ -2,8 +2,8 @@ import typer -from infrastructure.cli.i18n import t from infrastructure.cli.services import console, save_model +from infrastructure.i18n import t from infrastructure.repositories import ExcelRepository, ExcelRepositoryError _repo = ExcelRepository() diff --git a/infrastructure/cli/commands/info.py b/infrastructure/cli/commands/info.py index 3e8dd79..6870627 100644 --- a/infrastructure/cli/commands/info.py +++ b/infrastructure/cli/commands/info.py @@ -3,8 +3,8 @@ from rich.table import Table from domain import CurrencyConverter -from infrastructure.cli.i18n import t from infrastructure.cli.services import console, load_model +from infrastructure.i18n import t def info() -> None: diff --git a/infrastructure/cli/commands/init.py b/infrastructure/cli/commands/init.py index 499f83d..34a99d2 100644 --- a/infrastructure/cli/commands/init.py +++ b/infrastructure/cli/commands/init.py @@ -1,9 +1,9 @@ """cf init — создать пустую модель.""" from domain import FinancialModel -from infrastructure.cli.i18n import t from infrastructure.cli.paths import AppPaths from infrastructure.cli.services import console, save_model +from infrastructure.i18n import t def init() -> None: diff --git a/infrastructure/cli/commands/scenario.py b/infrastructure/cli/commands/scenario.py index d339587..c280a17 100644 --- a/infrastructure/cli/commands/scenario.py +++ b/infrastructure/cli/commands/scenario.py @@ -4,7 +4,6 @@ import typer from pydantic import ValidationError from application.scenarios import DEFAULT_SCENARIOS -from infrastructure.cli.i18n import t from infrastructure.cli.services import ( build_services, console, @@ -14,6 +13,7 @@ from infrastructure.cli.services import ( load_model, resolve_currency, ) +from infrastructure.i18n import t CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) diff --git a/infrastructure/cli/commands/whatif.py b/infrastructure/cli/commands/whatif.py index 202c1b7..0901ac7 100644 --- a/infrastructure/cli/commands/whatif.py +++ b/infrastructure/cli/commands/whatif.py @@ -3,7 +3,6 @@ import typer from pydantic import ValidationError -from infrastructure.cli.i18n import t from infrastructure.cli.services import ( build_services, console, @@ -13,6 +12,7 @@ from infrastructure.cli.services import ( load_model, resolve_currency, ) +from infrastructure.i18n import t CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) diff --git a/infrastructure/cli/services.py b/infrastructure/cli/services.py index af82dc9..c3d0401 100644 --- a/infrastructure/cli/services.py +++ b/infrastructure/cli/services.py @@ -13,8 +13,8 @@ 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 AppPaths +from infrastructure.i18n import t from infrastructure.repositories import JsonFileRepository console = Console() diff --git a/infrastructure/cli/i18n/__init__.py b/infrastructure/i18n/__init__.py similarity index 95% rename from infrastructure/cli/i18n/__init__.py rename to infrastructure/i18n/__init__.py index 764150a..2bd6ebb 100644 --- a/infrastructure/cli/i18n/__init__.py +++ b/infrastructure/i18n/__init__.py @@ -7,8 +7,8 @@ import os -from infrastructure.cli.i18n.en import MESSAGES as _EN_MESSAGES -from infrastructure.cli.i18n.ru import MESSAGES as _RU_MESSAGES +from infrastructure.i18n.en import MESSAGES as _EN_MESSAGES +from infrastructure.i18n.ru import MESSAGES as _RU_MESSAGES _TRANSLATIONS: dict[str, dict[str, str]] = {"ru": _RU_MESSAGES, "en": _EN_MESSAGES} diff --git a/infrastructure/cli/i18n/en.py b/infrastructure/i18n/en.py similarity index 100% rename from infrastructure/cli/i18n/en.py rename to infrastructure/i18n/en.py diff --git a/infrastructure/cli/i18n/ru.py b/infrastructure/i18n/ru.py similarity index 100% rename from infrastructure/cli/i18n/ru.py rename to infrastructure/i18n/ru.py diff --git a/tests/test_architecture.py b/tests/test_architecture.py new file mode 100644 index 0000000..b3edff0 --- /dev/null +++ b/tests/test_architecture.py @@ -0,0 +1,67 @@ +"""Инварианты направлений зависимостей внутри `infrastructure/` (D27). + +Смысл: `infrastructure/ai/` был связан с `infrastructure/cli/` только через +`infrastructure.cli.i18n`, из-за чего AI-слой нельзя было переиспользовать в +REST API / Web UI без затаскивания CLI. После выноса i18n в +`infrastructure/i18n/` горизонтальная связь «не-CLI → CLI» запрещена и +проверяется разбором AST, а не глазами. +""" + +import ast +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +INFRA_ROOT = REPO_ROOT / "infrastructure" +CLI_ROOT = INFRA_ROOT / "cli" +I18N_ROOT = INFRA_ROOT / "i18n" + +CLI_PREFIX = "infrastructure.cli" + + +def _iter_modules(): + for path in sorted(INFRA_ROOT.rglob("*.py")): + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + yield path, tree + + +def _cli_imports(tree: ast.Module) -> list[str]: + """Все импорты `infrastructure.cli.*` в модуле (from-import и import).""" + found: list[str] = [] + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module: + if node.module == CLI_PREFIX or node.module.startswith(CLI_PREFIX + "."): + found.append(node.module) + elif isinstance(node, ast.Import): + for alias in node.names: + if alias.name == CLI_PREFIX or alias.name.startswith(CLI_PREFIX + "."): + found.append(alias.name) + return found + + +class TestNoCliDependency: + def test_modules_outside_cli_do_not_import_cli(self): + offenders = {} + for path, tree in _iter_modules(): + if path == CLI_ROOT or CLI_ROOT in path.parents: + continue + imports = _cli_imports(tree) + if imports: + offenders[str(path.relative_to(REPO_ROOT))] = imports + assert not offenders, f"модули вне infrastructure/cli импортируют CLI: {offenders}" + + def test_i18n_package_does_not_import_cli(self): + assert I18N_ROOT.is_dir() + offenders = {} + for path in sorted(I18N_ROOT.rglob("*.py")): + imports = _cli_imports(ast.parse(path.read_text(encoding="utf-8"), filename=str(path))) + if imports: + offenders[str(path.relative_to(REPO_ROOT))] = imports + assert not offenders, f"infrastructure/i18n импортирует CLI: {offenders}" + + def test_ai_layer_does_not_import_cli(self): + offenders = {} + for path in sorted((INFRA_ROOT / "ai").rglob("*.py")): + imports = _cli_imports(ast.parse(path.read_text(encoding="utf-8"), filename=str(path))) + if imports: + offenders[str(path.relative_to(REPO_ROOT))] = imports + assert not offenders, f"infrastructure/ai импортирует CLI: {offenders}" diff --git a/tests/test_i18n.py b/tests/test_i18n.py index f931b01..c41adc5 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -2,7 +2,7 @@ import os import subprocess import sys -from infrastructure.cli.i18n import ( +from infrastructure.i18n import ( _TRANSLATIONS, Translator, get_lang, @@ -10,8 +10,8 @@ from infrastructure.cli.i18n import ( setup_i18n, t, ) -from infrastructure.cli.i18n.en import MESSAGES as EN_MESSAGES -from infrastructure.cli.i18n.ru import MESSAGES as RU_MESSAGES +from infrastructure.i18n.en import MESSAGES as EN_MESSAGES +from infrastructure.i18n.ru import MESSAGES as RU_MESSAGES class TestTranslator: @@ -117,7 +117,7 @@ class TestCfLang: 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'))" + code = "from infrastructure.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)