D31: схема v2 — валюта у денежных величин + display_currency
- 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-декодинге) — исправлены.
This commit is contained in:
1 parent
e26ed28068
commit
4bd19abbe9
12 files changed
+175
-21
No files matched your search
+8
-1
@@ -1,6 +1,12 @@
|
|||||||
from domain.account import Account
|
from domain.account import Account
|
||||||
from domain.asset import Asset
|
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.liability import Liability
|
||||||
from domain.model import FinancialModel
|
from domain.model import FinancialModel
|
||||||
from domain.recurring import RecurringCashflow
|
from domain.recurring import RecurringCashflow
|
||||||
@@ -19,4 +25,5 @@ __all__ = [
|
|||||||
"CurrencyConverter",
|
"CurrencyConverter",
|
||||||
"CurrencyError",
|
"CurrencyError",
|
||||||
"CURRENCY_SYMBOLS",
|
"CURRENCY_SYMBOLS",
|
||||||
|
"resolve_currency",
|
||||||
]
|
]
|
||||||
+7
-1
@@ -12,9 +12,15 @@ class Account(BaseModel):
|
|||||||
|
|
||||||
id: UUID = Field(default_factory=uuid4)
|
id: UUID = Field(default_factory=uuid4)
|
||||||
name: str = ""
|
name: str = ""
|
||||||
currency: str = "USD"
|
# Валюта счёта. Пусто = базовая валюта модели (наследование при разборе).
|
||||||
|
currency: str = ""
|
||||||
balance: Decimal = Field(default=Decimal("0"))
|
balance: Decimal = Field(default=Decimal("0"))
|
||||||
|
|
||||||
|
@field_validator("currency")
|
||||||
|
@classmethod
|
||||||
|
def _currency_upper(cls, v: str) -> str:
|
||||||
|
return v.strip().upper()
|
||||||
|
|
||||||
@field_validator("balance")
|
@field_validator("balance")
|
||||||
@classmethod
|
@classmethod
|
||||||
def _balance_non_negative(cls, v: Decimal) -> Decimal:
|
def _balance_non_negative(cls, v: Decimal) -> Decimal:
|
||||||
|
|||||||
+8
-1
@@ -1,7 +1,7 @@
|
|||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||||
|
|
||||||
|
|
||||||
class Asset(BaseModel):
|
class Asset(BaseModel):
|
||||||
@@ -14,3 +14,10 @@ class Asset(BaseModel):
|
|||||||
name: str = ""
|
name: str = ""
|
||||||
value: Decimal = Field(default=Decimal("0"))
|
value: Decimal = Field(default=Decimal("0"))
|
||||||
growth_rate: 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()
|
||||||
@@ -41,6 +41,17 @@ CURRENCY_DECIMALS: dict[str, int] = {
|
|||||||
DEFAULT_CURRENCY_DECIMALS = 2
|
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):
|
class ExchangeRate(BaseModel):
|
||||||
# Валидация при присваивании: любое присваивание полю проверяется
|
# Валидация при присваивании: любое присваивание полю проверяется
|
||||||
# валидатором модели, а значение приводится к объявленному типу
|
# валидатором модели, а значение приводится к объявленному типу
|
||||||
|
|||||||
@@ -15,6 +15,13 @@ class Liability(BaseModel):
|
|||||||
balance: Decimal = Field(default=Decimal("0"))
|
balance: Decimal = Field(default=Decimal("0"))
|
||||||
interest: Decimal = Field(default=Decimal("0"))
|
interest: Decimal = Field(default=Decimal("0"))
|
||||||
payment: 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")
|
@field_validator("interest", "payment")
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|||||||
+28
-4
@@ -4,7 +4,7 @@ from pydantic import BaseModel, ConfigDict, Field
|
|||||||
|
|
||||||
from domain.account import Account
|
from domain.account import Account
|
||||||
from domain.asset import Asset
|
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.liability import Liability
|
||||||
from domain.recurring import RecurringCashflow
|
from domain.recurring import RecurringCashflow
|
||||||
from domain.scenario import ForecastScenario
|
from domain.scenario import ForecastScenario
|
||||||
@@ -17,7 +17,15 @@ class FinancialModel(BaseModel):
|
|||||||
# (float в поле Decimal не остаётся float) — D17.
|
# (float в поле Decimal не остаётся float) — D17.
|
||||||
model_config = ConfigDict(validate_assignment=True)
|
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` —
|
Сериализация (save/load) вынесена в `application.repositories.ModelRepository` —
|
||||||
JsonFileRepository и ExcelRepository. Сам класс хранит только данные.
|
JsonFileRepository и ExcelRepository. Сам класс хранит только данные.
|
||||||
@@ -27,9 +35,11 @@ class FinancialModel(BaseModel):
|
|||||||
# В pydantic v2 аннотация со значением (`SCHEMA_VERSION: int = 1`) объявляет
|
# В pydantic v2 аннотация со значением (`SCHEMA_VERSION: int = 1`) объявляет
|
||||||
# поле, поэтому значение можно было подменить при создании модели
|
# поле, поэтому значение можно было подменить при создании модели
|
||||||
# (`FinancialModel(SCHEMA_VERSION=99)`). ClassVar исключает его из полей.
|
# (`FinancialModel(SCHEMA_VERSION=99)`). ClassVar исключает его из полей.
|
||||||
SCHEMA_VERSION: ClassVar[int] = 1
|
SCHEMA_VERSION: ClassVar[int] = 2
|
||||||
|
|
||||||
base_currency: str = "RUB"
|
base_currency: str = "RUB"
|
||||||
|
# Валюта вывода по умолчанию. Пусто = base_currency.
|
||||||
|
display_currency: str = ""
|
||||||
accounts: list[Account] = Field(default_factory=list)
|
accounts: list[Account] = Field(default_factory=list)
|
||||||
transactions: list[Transaction] = Field(default_factory=list)
|
transactions: list[Transaction] = Field(default_factory=list)
|
||||||
recurring: list[RecurringCashflow] = 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)
|
scenarios: list[ForecastScenario] = Field(default_factory=list)
|
||||||
exchange_rates: list[ExchangeRate] = Field(default_factory=lambda: [r.model_copy() for r in DEFAULT_RATES])
|
exchange_rates: list[ExchangeRate] = Field(default_factory=lambda: [r.model_copy() for r in DEFAULT_RATES])
|
||||||
|
|
||||||
|
@property
|
||||||
|
def output_currency(self) -> str:
|
||||||
|
"""Валюта, в которой модель показывается по умолчанию (D31)."""
|
||||||
|
return resolve_currency(self.display_currency, self.base_currency)
|
||||||
|
|
||||||
def to_dict(self) -> dict:
|
def to_dict(self) -> dict:
|
||||||
"""Сериализация в dict с version и UUID-as-str (для JSON)."""
|
"""Сериализация в dict с version и UUID-as-str (для JSON)."""
|
||||||
return {
|
return {
|
||||||
"version": self.SCHEMA_VERSION,
|
"version": self.SCHEMA_VERSION,
|
||||||
"base_currency": self.base_currency,
|
"base_currency": self.base_currency,
|
||||||
|
"display_currency": self.display_currency,
|
||||||
"accounts": [a.model_dump(mode="json") for a in self.accounts],
|
"accounts": [a.model_dump(mode="json") for a in self.accounts],
|
||||||
"transactions": [t.model_dump(mode="json") for t in self.transactions],
|
"transactions": [t.model_dump(mode="json") for t in self.transactions],
|
||||||
"recurring": [r.model_dump(mode="json") for r in self.recurring],
|
"recurring": [r.model_dump(mode="json") for r in self.recurring],
|
||||||
@@ -59,12 +75,15 @@ class FinancialModel(BaseModel):
|
|||||||
return cls._from_legacy(data)
|
return cls._from_legacy(data)
|
||||||
if version == 1:
|
if version == 1:
|
||||||
return cls._from_v1(data)
|
return cls._from_v1(data)
|
||||||
|
if version == 2:
|
||||||
|
return cls._from_v2(data)
|
||||||
raise ValueError(f"Неподдерживаемая версия финансовой модели: {version}")
|
raise ValueError(f"Неподдерживаемая версия финансовой модели: {version}")
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _from_v1(cls, data: dict) -> "FinancialModel":
|
def _from_v2(cls, data: dict) -> "FinancialModel":
|
||||||
return cls(
|
return cls(
|
||||||
base_currency=data.get("base_currency", "RUB"),
|
base_currency=data.get("base_currency", "RUB"),
|
||||||
|
display_currency=data.get("display_currency", ""),
|
||||||
accounts=[Account.model_validate(a) for a in data.get("accounts", [])],
|
accounts=[Account.model_validate(a) for a in data.get("accounts", [])],
|
||||||
transactions=[Transaction.model_validate(t) for t in data.get("transactions", [])],
|
transactions=[Transaction.model_validate(t) for t in data.get("transactions", [])],
|
||||||
recurring=[RecurringCashflow.model_validate(r) for r in data.get("recurring", [])],
|
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", [])],
|
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
|
@classmethod
|
||||||
def _from_legacy(cls, data: dict) -> "FinancialModel":
|
def _from_legacy(cls, data: dict) -> "FinancialModel":
|
||||||
# Legacy: файлы без version. Структура совпадает с v1.
|
# Legacy: файлы без version. Структура совпадает с v1.
|
||||||
|
|||||||
@@ -34,6 +34,13 @@ class RecurringCashflow(BaseModel):
|
|||||||
frequency: str = "monthly"
|
frequency: str = "monthly"
|
||||||
amount: Decimal = Field(default=Decimal("0"))
|
amount: Decimal = Field(default=Decimal("0"))
|
||||||
category: str = ""
|
category: str = ""
|
||||||
|
# Валюта суммы. Пусто = валюта счёта (или базовая валюта модели).
|
||||||
|
currency: str = ""
|
||||||
|
|
||||||
|
@field_validator("currency")
|
||||||
|
@classmethod
|
||||||
|
def _currency_upper(cls, v: str) -> str:
|
||||||
|
return v.strip().upper()
|
||||||
|
|
||||||
@field_validator("frequency")
|
@field_validator("frequency")
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|||||||
@@ -16,6 +16,14 @@ class Transaction(BaseModel):
|
|||||||
category: str = ""
|
category: str = ""
|
||||||
amount: Decimal = Field(default=Decimal("0"))
|
amount: Decimal = Field(default=Decimal("0"))
|
||||||
description: str = ""
|
description: str = ""
|
||||||
|
# Валюта суммы. Пусто = валюта счёта, к которому привязана операция
|
||||||
|
# (а если счёт не найден — базовая валюта модели).
|
||||||
|
currency: str = ""
|
||||||
|
|
||||||
|
@field_validator("currency")
|
||||||
|
@classmethod
|
||||||
|
def _currency_upper(cls, v: str) -> str:
|
||||||
|
return v.strip().upper()
|
||||||
|
|
||||||
@field_validator("amount")
|
@field_validator("amount")
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|||||||
@@ -12,6 +12,8 @@
|
|||||||
default и required.
|
default и required.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import typer
|
import typer
|
||||||
from typer.main import get_command
|
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]]:
|
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:
|
class TestCliSurface:
|
||||||
@@ -193,10 +208,15 @@ class TestCliParameters:
|
|||||||
assert param.help, f"config {name}: у параметра {param.name} пустая справка"
|
assert param.help, f"config {name}: у параметра {param.name} пустая справка"
|
||||||
|
|
||||||
def test_export_xlsx_default_path_is_unchanged(self):
|
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"]
|
command = _click_app(app).commands["export-xlsx"]
|
||||||
arg = next(p for p in command.params if p.name == "path")
|
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):
|
def test_init_and_import_do_not_take_a_path(self):
|
||||||
root = _click_app(app)
|
root = _click_app(app)
|
||||||
|
|||||||
@@ -127,6 +127,7 @@ class TestCfLang:
|
|||||||
cwd=str(repo_root),
|
cwd=str(repo_root),
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
assert proc.returncode == 0, proc.stderr
|
assert proc.returncode == 0, proc.stderr
|
||||||
lines = proc.stdout.strip().splitlines()
|
lines = proc.stdout.strip().splitlines()
|
||||||
|
|||||||
+66
-10
@@ -25,7 +25,10 @@ class TestAccount:
|
|||||||
a = Account(name="Test", balance=Decimal("100.0"))
|
a = Account(name="Test", balance=Decimal("100.0"))
|
||||||
assert a.name == "Test"
|
assert a.name == "Test"
|
||||||
assert a.balance == Decimal("100.0")
|
assert a.balance == Decimal("100.0")
|
||||||
assert a.currency == "USD"
|
# D31: валюта счёта не задана по умолчанию — она наследуется от
|
||||||
|
# базовой валюты модели. Раньше дефолтом был «USD», из-за чего новый
|
||||||
|
# счёт в рублёвой модели молча становился долларовым.
|
||||||
|
assert a.currency == ""
|
||||||
|
|
||||||
def test_to_dict_roundtrip(self):
|
def test_to_dict_roundtrip(self):
|
||||||
a = Account(name="Test", balance=Decimal("100.0"))
|
a = Account(name="Test", balance=Decimal("100.0"))
|
||||||
@@ -202,29 +205,29 @@ class TestValidateAssignment:
|
|||||||
class TestSchemaVersion:
|
class TestSchemaVersion:
|
||||||
"""Регрессии D9: SCHEMA_VERSION — ClassVar, а не поле pydantic.
|
"""Регрессии D9: SCHEMA_VERSION — ClassVar, а не поле pydantic.
|
||||||
|
|
||||||
Формат файла состояния (`to_dict()`) не меняется: там по-прежнему
|
Формат файла состояния (`to_dict()`) — `{"version": 2, ...}` (D31).
|
||||||
пишется `{"version": 1, ...}`.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def test_schema_version_is_not_a_pydantic_field(self):
|
def test_schema_version_is_not_a_pydantic_field(self):
|
||||||
assert "SCHEMA_VERSION" not in FinancialModel.model_fields
|
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):
|
def test_schema_version_cannot_be_overridden_at_construction(self):
|
||||||
# Раньше `SCHEMA_VERSION: int = 1` было полем, и значение принималось
|
# Раньше `SCHEMA_VERSION: int = 1` было полем, и значение принималось
|
||||||
# в конструктор. Теперь лишний kwargs игнорируется, версия — 1.
|
# в конструктор. Теперь лишний kwargs игнорируется, версия — 2.
|
||||||
model = FinancialModel(SCHEMA_VERSION=99)
|
model = FinancialModel(SCHEMA_VERSION=99)
|
||||||
assert FinancialModel.SCHEMA_VERSION == 1
|
assert FinancialModel.SCHEMA_VERSION == 2
|
||||||
assert model.SCHEMA_VERSION == 1
|
assert model.SCHEMA_VERSION == 2
|
||||||
assert model.to_dict()["version"] == 1
|
assert model.to_dict()["version"] == 2
|
||||||
assert "SCHEMA_VERSION" not in model.model_dump()
|
assert "SCHEMA_VERSION" not in model.model_dump()
|
||||||
|
|
||||||
def test_to_dict_version_and_key_set(self):
|
def test_to_dict_version_and_key_set(self):
|
||||||
d = FinancialModel().to_dict()
|
d = FinancialModel().to_dict()
|
||||||
assert d["version"] == 1
|
assert d["version"] == 2
|
||||||
assert set(d.keys()) == {
|
assert set(d.keys()) == {
|
||||||
"version",
|
"version",
|
||||||
"base_currency",
|
"base_currency",
|
||||||
|
"display_currency",
|
||||||
"accounts",
|
"accounts",
|
||||||
"transactions",
|
"transactions",
|
||||||
"recurring",
|
"recurring",
|
||||||
@@ -258,7 +261,60 @@ class TestSchemaVersion:
|
|||||||
|
|
||||||
def test_from_dict_rejects_unknown_version(self):
|
def test_from_dict_rejects_unknown_version(self):
|
||||||
with pytest.raises(ValueError):
|
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:
|
class TestPydanticValidators:
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ class TestJsonFileRepository:
|
|||||||
|
|
||||||
with open(p) as f:
|
with open(p) as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
assert data["version"] == 1
|
assert data["version"] == 2
|
||||||
|
|
||||||
def test_creates_parent_dirs(self, tmp_path: Path):
|
def test_creates_parent_dirs(self, tmp_path: Path):
|
||||||
repo = JsonFileRepository()
|
repo = JsonFileRepository()
|
||||||
|
|||||||
Reference in new issue
Block a user