From 4bd19abbe9f7f94b030d0e003ad8fb9b005fdcbf Mon Sep 17 00:00:00 2001 From: oqyude Date: Sun, 15 Nov 2026 05:42:13 +0300 Subject: [PATCH] =?UTF-8?q?D31:=20=D1=81=D1=85=D0=B5=D0=BC=D0=B0=20v2=20?= =?UTF-8?q?=E2=80=94=20=D0=B2=D0=B0=D0=BB=D1=8E=D1=82=D0=B0=20=D1=83=20?= =?UTF-8?q?=D0=B4=D0=B5=D0=BD=D0=B5=D0=B6=D0=BD=D1=8B=D1=85=20=D0=B2=D0=B5?= =?UTF-8?q?=D0=BB=D0=B8=D1=87=D0=B8=D0=BD=20+=20display=5Fcurrency?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Transaction/RecurringCashflow/Asset/Liability получили поле currency (пусто = наследование: у операции — от счёта, у актива/обязательства — от базовой валюты модели); - Account.currency больше не по умолчанию USD: пусто = базовая валюта модели (новый счёт в рублёвой модели не становился долларовым); - FinancialModel.display_currency — валюта вывода по умолчанию, свойство output_currency; SCHEMA_VERSION 1 → 2, миграция v0/v1; - resolve_currency() в domain/currency.py — единое правило «явный → базовый»; - тесты: контракт схемы обновлён на v2, добавлены тесты миграции v1, display_currency и наследования валюты; - попутно: 3 теста были не платформонезависимы (Windows: разделитель пути в дефолте экспорта и cp1252 в subprocess-декодинге) — исправлены. --- domain/__init__.py | 9 ++++- domain/account.py | 8 +++- domain/asset.py | 9 ++++- domain/currency.py | 11 ++++++ domain/liability.py | 7 ++++ domain/model.py | 32 ++++++++++++++-- domain/recurring.py | 7 ++++ domain/transaction.py | 8 ++++ tests/test_cli_contract.py | 26 +++++++++++-- tests/test_i18n.py | 1 + tests/test_model.py | 76 +++++++++++++++++++++++++++++++++----- tests/test_repositories.py | 2 +- 12 files changed, 175 insertions(+), 21 deletions(-) diff --git a/domain/__init__.py b/domain/__init__.py index 41a6df5..74f4430 100644 --- a/domain/__init__.py +++ b/domain/__init__.py @@ -1,6 +1,12 @@ from domain.account import Account from domain.asset import Asset -from domain.currency import CURRENCY_SYMBOLS, CurrencyConverter, CurrencyError, ExchangeRate +from domain.currency import ( + CURRENCY_SYMBOLS, + CurrencyConverter, + CurrencyError, + ExchangeRate, + resolve_currency, +) from domain.liability import Liability from domain.model import FinancialModel from domain.recurring import RecurringCashflow @@ -19,4 +25,5 @@ __all__ = [ "CurrencyConverter", "CurrencyError", "CURRENCY_SYMBOLS", + "resolve_currency", ] diff --git a/domain/account.py b/domain/account.py index 6f9f7ce..b51a72d 100644 --- a/domain/account.py +++ b/domain/account.py @@ -12,9 +12,15 @@ class Account(BaseModel): id: UUID = Field(default_factory=uuid4) name: str = "" - currency: str = "USD" + # Валюта счёта. Пусто = базовая валюта модели (наследование при разборе). + currency: str = "" balance: Decimal = Field(default=Decimal("0")) + @field_validator("currency") + @classmethod + def _currency_upper(cls, v: str) -> str: + return v.strip().upper() + @field_validator("balance") @classmethod def _balance_non_negative(cls, v: Decimal) -> Decimal: diff --git a/domain/asset.py b/domain/asset.py index cd0d1df..2d2efd3 100644 --- a/domain/asset.py +++ b/domain/asset.py @@ -1,7 +1,7 @@ from decimal import Decimal from uuid import UUID, uuid4 -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, field_validator class Asset(BaseModel): @@ -14,3 +14,10 @@ class Asset(BaseModel): name: str = "" value: Decimal = Field(default=Decimal("0")) growth_rate: Decimal = Field(default=Decimal("0")) + # Валюта стоимости. Пусто = базовая валюта модели. + currency: str = "" + + @field_validator("currency") + @classmethod + def _currency_upper(cls, v: str) -> str: + return v.strip().upper() diff --git a/domain/currency.py b/domain/currency.py index 58a0584..c911235 100644 --- a/domain/currency.py +++ b/domain/currency.py @@ -41,6 +41,17 @@ CURRENCY_DECIMALS: dict[str, int] = { DEFAULT_CURRENCY_DECIMALS = 2 +def resolve_currency(explicit: str | None, fallback: str | None) -> str: + """Код валюты по правилу «явный → базовый → RUB». + + В модели валюта денежной величины может быть не задана: тогда она + наследуется (у операции — от счёта, у актива/обязательства — от базовой + валюты модели). Пустое значение никогда не означает «валюта не задана + вообще» — иначе расчёт молча ломался бы об отсутствии курса. + """ + return (explicit or fallback or "RUB").strip().upper() + + class ExchangeRate(BaseModel): # Валидация при присваивании: любое присваивание полю проверяется # валидатором модели, а значение приводится к объявленному типу diff --git a/domain/liability.py b/domain/liability.py index 3d495ab..2da26aa 100644 --- a/domain/liability.py +++ b/domain/liability.py @@ -15,6 +15,13 @@ class Liability(BaseModel): balance: Decimal = Field(default=Decimal("0")) interest: Decimal = Field(default=Decimal("0")) payment: Decimal = Field(default=Decimal("0")) + # Валюта всех денежных величин обязательства. Пусто = базовая валюта модели. + currency: str = "" + + @field_validator("currency") + @classmethod + def _currency_upper(cls, v: str) -> str: + return v.strip().upper() @field_validator("interest", "payment") @classmethod diff --git a/domain/model.py b/domain/model.py index 4dc2f7f..7ce8efa 100644 --- a/domain/model.py +++ b/domain/model.py @@ -4,7 +4,7 @@ from pydantic import BaseModel, ConfigDict, Field from domain.account import Account from domain.asset import Asset -from domain.currency import DEFAULT_RATES, ExchangeRate +from domain.currency import DEFAULT_RATES, ExchangeRate, resolve_currency from domain.liability import Liability from domain.recurring import RecurringCashflow from domain.scenario import ForecastScenario @@ -17,7 +17,15 @@ class FinancialModel(BaseModel): # (float в поле Decimal не остаётся float) — D17. model_config = ConfigDict(validate_assignment=True) - """Корневая модель финансового плана. + """Корень финансовой модели. + + Версии схемы: + + - **v0** — legacy, файлы без поля ``version``; + - **v1** — 2026-10: слои + pydantic, у денежных величин нет валюты; + - **v2** — 2026-11: у каждой денежной величины есть своя валюта + (``currency``), добавлена ``display_currency`` — валюта вывода по + умолчанию (D31). Сериализация (save/load) вынесена в `application.repositories.ModelRepository` — JsonFileRepository и ExcelRepository. Сам класс хранит только данные. @@ -27,9 +35,11 @@ class FinancialModel(BaseModel): # В pydantic v2 аннотация со значением (`SCHEMA_VERSION: int = 1`) объявляет # поле, поэтому значение можно было подменить при создании модели # (`FinancialModel(SCHEMA_VERSION=99)`). ClassVar исключает его из полей. - SCHEMA_VERSION: ClassVar[int] = 1 + SCHEMA_VERSION: ClassVar[int] = 2 base_currency: str = "RUB" + # Валюта вывода по умолчанию. Пусто = base_currency. + display_currency: str = "" accounts: list[Account] = Field(default_factory=list) transactions: list[Transaction] = Field(default_factory=list) recurring: list[RecurringCashflow] = Field(default_factory=list) @@ -38,11 +48,17 @@ class FinancialModel(BaseModel): scenarios: list[ForecastScenario] = Field(default_factory=list) exchange_rates: list[ExchangeRate] = Field(default_factory=lambda: [r.model_copy() for r in DEFAULT_RATES]) + @property + def output_currency(self) -> str: + """Валюта, в которой модель показывается по умолчанию (D31).""" + return resolve_currency(self.display_currency, self.base_currency) + def to_dict(self) -> dict: """Сериализация в dict с version и UUID-as-str (для JSON).""" return { "version": self.SCHEMA_VERSION, "base_currency": self.base_currency, + "display_currency": self.display_currency, "accounts": [a.model_dump(mode="json") for a in self.accounts], "transactions": [t.model_dump(mode="json") for t in self.transactions], "recurring": [r.model_dump(mode="json") for r in self.recurring], @@ -59,12 +75,15 @@ class FinancialModel(BaseModel): return cls._from_legacy(data) if version == 1: return cls._from_v1(data) + if version == 2: + return cls._from_v2(data) raise ValueError(f"Неподдерживаемая версия финансовой модели: {version}") @classmethod - def _from_v1(cls, data: dict) -> "FinancialModel": + def _from_v2(cls, data: dict) -> "FinancialModel": return cls( base_currency=data.get("base_currency", "RUB"), + display_currency=data.get("display_currency", ""), accounts=[Account.model_validate(a) for a in data.get("accounts", [])], transactions=[Transaction.model_validate(t) for t in data.get("transactions", [])], recurring=[RecurringCashflow.model_validate(r) for r in data.get("recurring", [])], @@ -74,6 +93,11 @@ class FinancialModel(BaseModel): exchange_rates=[ExchangeRate.model_validate(r) for r in data.get("exchange_rates", [])], ) + @classmethod + def _from_v1(cls, data: dict) -> "FinancialModel": + """v1 → v2: операции не знали своей валюты — она наследуется от счёта.""" + return cls._from_v2(data) + @classmethod def _from_legacy(cls, data: dict) -> "FinancialModel": # Legacy: файлы без version. Структура совпадает с v1. diff --git a/domain/recurring.py b/domain/recurring.py index 0806dfe..422d06b 100644 --- a/domain/recurring.py +++ b/domain/recurring.py @@ -34,6 +34,13 @@ class RecurringCashflow(BaseModel): frequency: str = "monthly" amount: Decimal = Field(default=Decimal("0")) category: str = "" + # Валюта суммы. Пусто = валюта счёта (или базовая валюта модели). + currency: str = "" + + @field_validator("currency") + @classmethod + def _currency_upper(cls, v: str) -> str: + return v.strip().upper() @field_validator("frequency") @classmethod diff --git a/domain/transaction.py b/domain/transaction.py index e970832..c4071ff 100644 --- a/domain/transaction.py +++ b/domain/transaction.py @@ -16,6 +16,14 @@ class Transaction(BaseModel): category: str = "" amount: Decimal = Field(default=Decimal("0")) description: str = "" + # Валюта суммы. Пусто = валюта счёта, к которому привязана операция + # (а если счёт не найден — базовая валюта модели). + currency: str = "" + + @field_validator("currency") + @classmethod + def _currency_upper(cls, v: str) -> str: + return v.strip().upper() @field_validator("amount") @classmethod diff --git a/tests/test_cli_contract.py b/tests/test_cli_contract.py index 7f058dd..f7e2085 100644 --- a/tests/test_cli_contract.py +++ b/tests/test_cli_contract.py @@ -12,6 +12,8 @@ default и required. """ +from pathlib import Path + import typer from typer.main import get_command @@ -142,7 +144,20 @@ def _command_names(typer_app: typer.Typer) -> set[str]: 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] + return [(p.name, tuple(p.opts), _default(p.default), p.required) for p in command.params] + + +def _default(value: object) -> object: + """Default параметра в виде, не зависящем от ОС. + + Click приводит строковые дефолты-пути к пути своей платформы, и на Windows + такой путь печатается с обратными слэшами («exports\\forecast.xlsx»). Для + сравнения контракта разделитель нормализуется — пользователю всё равно, + какой он. + """ + if isinstance(value, (str, Path)): + return str(value).replace("\\", "/") + return value class TestCliSurface: @@ -193,10 +208,15 @@ class TestCliParameters: assert param.help, f"config {name}: у параметра {param.name} пустая справка" def test_export_xlsx_default_path_is_unchanged(self): - """Дефолт `cf export-xlsx` — строка, которую видит пользователь в --help.""" + """Дефолт `cf export-xlsx` — строка, которую видит пользователь в --help. + + На Windows Typer приводит дефолт к `Path`, поэтому сравниваем + нормализованные пути, а не строки: «exports/forecast.xlsx» и + «exports\\forecast.xlsx» — один и тот же путь. + """ command = _click_app(app).commands["export-xlsx"] arg = next(p for p in command.params if p.name == "path") - assert arg.default == EXPECTED_EXPORT_DEFAULT + assert Path(str(arg.default)) == Path(EXPECTED_EXPORT_DEFAULT) def test_init_and_import_do_not_take_a_path(self): root = _click_app(app) diff --git a/tests/test_i18n.py b/tests/test_i18n.py index c41adc5..670142b 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -127,6 +127,7 @@ class TestCfLang: cwd=str(repo_root), capture_output=True, text=True, + encoding="utf-8", ) assert proc.returncode == 0, proc.stderr lines = proc.stdout.strip().splitlines() diff --git a/tests/test_model.py b/tests/test_model.py index e94d3dd..f095947 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -25,7 +25,10 @@ class TestAccount: a = Account(name="Test", balance=Decimal("100.0")) assert a.name == "Test" assert a.balance == Decimal("100.0") - assert a.currency == "USD" + # D31: валюта счёта не задана по умолчанию — она наследуется от + # базовой валюты модели. Раньше дефолтом был «USD», из-за чего новый + # счёт в рублёвой модели молча становился долларовым. + assert a.currency == "" def test_to_dict_roundtrip(self): a = Account(name="Test", balance=Decimal("100.0")) @@ -202,29 +205,29 @@ class TestValidateAssignment: class TestSchemaVersion: """Регрессии D9: SCHEMA_VERSION — ClassVar, а не поле pydantic. - Формат файла состояния (`to_dict()`) не меняется: там по-прежнему - пишется `{"version": 1, ...}`. + Формат файла состояния (`to_dict()`) — `{"version": 2, ...}` (D31). """ def test_schema_version_is_not_a_pydantic_field(self): assert "SCHEMA_VERSION" not in FinancialModel.model_fields - assert FinancialModel.SCHEMA_VERSION == 1 + assert FinancialModel.SCHEMA_VERSION == 2 def test_schema_version_cannot_be_overridden_at_construction(self): # Раньше `SCHEMA_VERSION: int = 1` было полем, и значение принималось - # в конструктор. Теперь лишний kwargs игнорируется, версия — 1. + # в конструктор. Теперь лишний kwargs игнорируется, версия — 2. model = FinancialModel(SCHEMA_VERSION=99) - assert FinancialModel.SCHEMA_VERSION == 1 - assert model.SCHEMA_VERSION == 1 - assert model.to_dict()["version"] == 1 + assert FinancialModel.SCHEMA_VERSION == 2 + assert model.SCHEMA_VERSION == 2 + assert model.to_dict()["version"] == 2 assert "SCHEMA_VERSION" not in model.model_dump() def test_to_dict_version_and_key_set(self): d = FinancialModel().to_dict() - assert d["version"] == 1 + assert d["version"] == 2 assert set(d.keys()) == { "version", "base_currency", + "display_currency", "accounts", "transactions", "recurring", @@ -258,7 +261,60 @@ class TestSchemaVersion: def test_from_dict_rejects_unknown_version(self): with pytest.raises(ValueError): - FinancialModel.from_dict({"version": 2}) + FinancialModel.from_dict({"version": 3}) + + +class TestSchemaVersion2: + """D31: схема v2 — валюта у денежных величин + валюта вывода.""" + + def test_v1_file_is_migrated(self): + # Файл состояния, записанный до D31, читается без ошибок: у операций + # просто нет своей валюты — она наследуется от счёта. + legacy = { + "version": 1, + "base_currency": "RUB", + "accounts": [ + { + "id": "00000000-0000-0000-0000-000000000001", + "name": "Счёт", + "currency": "RUB", + "balance": "100", + } + ], + "transactions": [ + { + "id": "00000000-0000-0000-0000-000000000002", + "date": "2026-01-01", + "account": "00000000-0000-0000-0000-000000000001", + "category": "salary", + "amount": "500", + "description": "", + } + ], + } + restored = FinancialModel.from_dict(legacy) + assert restored.transactions[0].currency == "" + assert restored.transactions[0].amount == Decimal("500") + assert restored.output_currency == "RUB" + + def test_display_currency_is_used_for_output(self): + assert FinancialModel(base_currency="RUB").output_currency == "RUB" + assert FinancialModel(base_currency="RUB", display_currency="USD").output_currency == "USD" + + def test_display_currency_survives_roundtrip(self, tmp_path: Path): + repo = JsonFileRepository() + model = FinancialModel(base_currency="RUB", display_currency="EUR") + p = tmp_path / "model.json" + repo.save(model, p) + assert repo.load(p).display_currency == "EUR" + + def test_operations_carry_own_currency(self): + txn = Transaction(amount=Decimal("10"), currency="usd") + assert txn.currency == "USD" + rec = RecurringCashflow(amount=Decimal("10"), currency=" eur ") + assert rec.currency == "EUR" + assert Asset(value=Decimal("1")).currency == "" + assert Liability(balance=Decimal("1")).currency == "" class TestPydanticValidators: diff --git a/tests/test_repositories.py b/tests/test_repositories.py index ec1de3b..5e867c6 100644 --- a/tests/test_repositories.py +++ b/tests/test_repositories.py @@ -32,7 +32,7 @@ class TestJsonFileRepository: with open(p) as f: data = json.load(f) - assert data["version"] == 1 + assert data["version"] == 2 def test_creates_parent_dirs(self, tmp_path: Path): repo = JsonFileRepository()