Commit Graph
9 Commits
Author SHA1 Message Date
oqyude b15533f275 D9: SCHEMA_VERSION объявить как ClassVar[int] + регрессионные тесты
- domain/model.py: `SCHEMA_VERSION: int = 1` в pydantic v2 — это поле, а не
  метаданные класса (значение принималось в конструкторе:
  `FinancialModel(SCHEMA_VERSION=99)`). Теперь `ClassVar[int]` — поле
  исключено из model_fields/model_dump.
- Формат to_dict() и файла состояния НЕ изменился: `version` по-прежнему
  пишется вручную и равен 1 (зафиксировано тестами).
- tests/test_model.py: +6 регрессионных тестов (ClassVar, неизменяемость
  версии, набор ключей to_dict, round-trip to_dict/from_dict, legacy v0,
  отказ от неизвестной версии).
2026-10-25 05:17:32 +03:00
oqyude 339a751153 D7: убрать дрейф в комментариях и docstring
- infrastructure/repositories/excel_repository.py: docstring обещал «5 листов» —
  фактически 6 листов данных (Accounts, Transactions, Recurring, Assets,
  Liabilities, ExchangeRates) + служебный ModelInfo; перечислены явно
- domain/currency.py: комментарий «Internal arithmetic keeps full Decimal
  precision» не соответствовал коду — convert() квантует до 2 знаков
  (ROUND_HALF_UP) независимо от числа знаков валюты; поведение не менялось,
  комментарий теперь описывает факт (изменение — Tier 2, D15)
- infrastructure/cli/services.py: docstring fmt_amount утверждал, что symbol
  «retained for backward compatibility»; на деле параметр просто не читается —
  теперь это сказано прямо

Поведение кода не изменено (только комментарии и docstring).
2026-10-25 05:17:32 +03:00
oqyude af01efc41a style: привести код к ruff format (line-length 120)
Обнаружено на шаге 0: `ruff format --check .` НЕ был чистым в baseline
(24 файла расходились с форматом ruff). `ruff check .` был чистым.

Изменение только косметическое (переносы, пустая строка после docstring
модуля, склейка вызовов в пределах line-length=120 из [tool.ruff]);
поведение не меняется — pytest 81/81 зелёные, `ruff check .` — без ошибок.

Нужно, чтобы `ruff format --check .` стал рабочим гейтом (D13 CI).
2026-10-25 05:17:27 +03:00
oqyude 8af1d9a010 D2: починить lint-гейт — ruff check . проходит
Было: `ruff check .` → 10 ошибок, CI-гейт на ruff был бы красным сразу.
- 9× I001 (порядок импортов) — application/forecast.py:1,
  application/scenarios.py:1, domain/currency.py:1,
  infrastructure/ai/assistant.py:1, infrastructure/cli/app.py:11,
  infrastructure/cli/commands/init.py:2, infrastructure/cli/services.py:2,
  tests/test_model.py:1, tests/test_repositories.py:1
- 1× E501 — infrastructure/cli/services.py:30, сигнатура build_services
  перенесена на три строки

Поведение не меняется: переупорядочены только импорты, убраны пустые
строки, перенесена длинная сигнатура. Порядок импорта в app.py не влияет
на момент вызова setup_i18n() — он по-прежнему после импорта команд.

Проверка: 75/75 тестов зелёные, ruff check . — All checks passed.
2026-10-23 18:29:48 +03:00
oqyude d58547e8f8 T8: ISO 4217 per-currency decimals + format_money()
- Add CURRENCY_DECIMALS dict (JPY=0, BHD/KWD/OMR=3, rest=2) and DEFAULT_CURRENCY_DECIMALS=2
- Add CurrencyConverter.format_money() staticmethod with ROUND_HALF_UP; symbol-prefix for known, code-prefix for unknown
- Replace 14 :,.2f literals across services.py / info.py / config_cmd.py with format_money() calls
- Refactor 2 i18n templates (transaction_add.ok, recurring_add.ok): {amount:.2f} -> {amount_str}; callers pass pre-formatted string
- New _account_currency() helper for transaction currency lookup
- Extend test_currency.py: 8 new tests (JPY/BHD/USD/CHF/negative/zero/float-int/lowercase)
- 75/75 tests pass; 0 :,.2f literals remain in infrastructure/cli/
2026-10-09 19:24:47 +03:00
oqyude 3f7268d14c T4: Repository pattern — ModelRepository, JsonFileRepository, ExcelRepository
- application/repositories/model_repository.py: ModelRepository Protocol
  with load(path) and save(model, path)
- infrastructure/repositories/json_file_repository.py: JsonFileRepository
  (вынесен из FinancialModel.save/load)
- infrastructure/repositories/excel_repository.py: ExcelRepository
  (бывший ExcelSync, переименован)
- FinancialModel.save/load удалены — теперь только данные
- infrastructure/sync/ удалён (ExcelSync перенесён в repositories/)
- infrastructure/cli/main.py и config.py используют JsonFileRepository +
  ExcelRepository через локальные singletons
- test_excel_sync.py переименован в test для ExcelRepository
- Новый test_repositories.py: 5 тестов для JsonFileRepository + протокол
- test_model.py: использован JsonFileRepository

Tests: 68/68 pass (было 63 + 5 новых).
2026-10-08 16:50:06 +03:00
oqyude 363d440d53 T3: Decimal for money — all monetary fields migrated from float
- All domain monetary fields now use Decimal:
  - Account.balance, Asset.value, Asset.growth_rate
  - Liability.balance, Liability.interest, Liability.payment
  - Transaction.amount, RecurringCashflow.amount
  - ExchangeRate.rate
  - ForecastScenario.income_multiplier, expense_multiplier, growth_multiplier
- CurrencyConverter: all arithmetic in Decimal, quantize to 0.01 with ROUND_HALF_UP
- ForecastService: Decimal arithmetic throughout (income, expenses, balance, growth, liability cost)
- ScenarioService: Decimal multipliers, deepcopy safe with Decimal fields
- assistant.py: _DecimalEncoder for json.dumps (Decimal -> str in JSON)

Pydantic v2 + Decimal:
- model_dump(mode='json') converts Decimal to str (JSON-safe)
- model_validate() parses str back to Decimal
- Round-trip preserves precision (100.50 stays 100.50)

Tests: 63/63 pass.
2026-10-08 16:44:59 +03:00
oqyude c765f3672a T2: Pydantic v2 — replace @dataclass with BaseModel
- All domain models now use pydantic.BaseModel
- Removed manual to_dict()/from_dict() — use model_dump(mode='json')/model_validate()
- Added field validators:
  - Account.balance >= 0
  - Transaction.amount != 0
  - RecurringCashflow.amount != 0, frequency in {daily, weekly, monthly, yearly}
  - Liability.interest, payment >= 0
  - ExchangeRate.rate > 0
  - ForecastScenario.multipliers >= 0
- pydantic v2 native UUID handling (auto str in JSON)
- Updated excel_sync.py to use model_validate()
- Updated tests/test_model.py and tests/test_currency.py
- Added pydantic>=2.0 to pyproject.toml

Tests: 63/63 pass.
2026-10-08 16:42:04 +03:00
oqyude feb77ef217 T1: restructure to domain/application/infrastructure + schema version 1
- Move cashflow_model/ -> domain/
- Move engine/ -> application/
- Move cli/, sync/, ai/ -> infrastructure/
- Update all imports across codebase and tests
- Add version=1 to FinancialModel.to_dict() with migration hook in from_dict
- Update pyproject.toml: cf entry point and packages.find

Tests: 63/63 pass.
2026-10-08 16:34:10 +03:00