fix(excel): импорт курсов дополняет дефолтные, а не заменяет их (Н4)
Импорт создавал модель с DEFAULT_RATES, а затем лист «Курсы валют» целиком заменял список — даже пустой. После `cf template-xlsx` → `cf import-xlsx` в модели не оставалось ни одного курса, включая USD → RUB = 80, хотя README обещал обратное. Теперь курсы из листа накладываются на дефолтные: пара из файла обновляет такую же дефолтную, остальные дефолтные сохраняются. Было → стало (пустой шаблон): exchange_rates = [] → [USD → RUB = 80]. Файл с EUR → RUB = 90: [EUR → RUB = 90] → [USD → RUB = 80, EUR → RUB = 90]. Refs: review/2026-11-29-review.md §2 Н4, §6 R4.
This commit is contained in:
1 parent
c887a1e3ff
commit
120ef4ee76
2 files changed
+52
-3
No files matched your search
@@ -31,7 +31,8 @@ from openpyxl.utils.exceptions import InvalidFileException
|
|||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from application.repositories.model_repository import ModelRepository
|
from application.repositories.model_repository import ModelRepository
|
||||||
from domain import Account, FinancialModel
|
from domain import Account, ExchangeRate, FinancialModel
|
||||||
|
from domain.currency import DEFAULT_RATES
|
||||||
from domain.recurrence import normalize_frequency
|
from domain.recurrence import normalize_frequency
|
||||||
from infrastructure.repositories.excel_schema import (
|
from infrastructure.repositories.excel_schema import (
|
||||||
ACCOUNT,
|
ACCOUNT,
|
||||||
@@ -106,6 +107,21 @@ class _IssueCollector:
|
|||||||
self.warnings.append(message)
|
self.warnings.append(message)
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_exchange_rates(sheet_rates: list[ExchangeRate]) -> list[ExchangeRate]:
|
||||||
|
"""Дополнить курсы по умолчанию курсами из листа (Н4).
|
||||||
|
|
||||||
|
Пара из листа заменяет такую же дефолтную (пользователь мог обновить
|
||||||
|
USD → RUB), но отсутствующие в листе пары остаются: пустой лист больше
|
||||||
|
не означает «курсов нет».
|
||||||
|
"""
|
||||||
|
merged: dict[tuple[str, str], ExchangeRate] = {
|
||||||
|
(rate.from_currency.upper(), rate.to_currency.upper()): rate.model_copy() for rate in DEFAULT_RATES
|
||||||
|
}
|
||||||
|
for rate in sheet_rates:
|
||||||
|
merged[(rate.from_currency.upper(), rate.to_currency.upper())] = rate
|
||||||
|
return list(merged.values())
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Разбор значений ячеек
|
# Разбор значений ячеек
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -295,7 +311,14 @@ class ExcelRepository(ModelRepository):
|
|||||||
for spec in SHEETS:
|
for spec in SHEETS:
|
||||||
if not isinstance(spec, SheetSpec) or spec.collection == "accounts":
|
if not isinstance(spec, SheetSpec) or spec.collection == "accounts":
|
||||||
continue
|
continue
|
||||||
setattr(model, spec.collection, self._read_sheet(spec, workbook, index, collector))
|
rows = self._read_sheet(spec, workbook, index, collector)
|
||||||
|
if spec.collection == "exchange_rates":
|
||||||
|
# Пустой лист «Курсы валют» не должен стирать курсы по
|
||||||
|
# умолчанию: иначе любой валютный счёт выпадает из
|
||||||
|
# прогноза (Н4).
|
||||||
|
model.exchange_rates = _merge_exchange_rates(rows)
|
||||||
|
else:
|
||||||
|
setattr(model, spec.collection, rows)
|
||||||
self._check_formulas(file_path, workbook, collector)
|
self._check_formulas(file_path, workbook, collector)
|
||||||
finally:
|
finally:
|
||||||
workbook.close()
|
workbook.close()
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import pytest
|
|||||||
from openpyxl import load_workbook
|
from openpyxl import load_workbook
|
||||||
|
|
||||||
import infrastructure.repositories.excel_repository as excel_repository
|
import infrastructure.repositories.excel_repository as excel_repository
|
||||||
from domain import Account, FinancialModel, ForecastScenario
|
from domain import Account, ExchangeRate, FinancialModel, ForecastScenario
|
||||||
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
|
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
|
||||||
from infrastructure.repositories.excel_repository import InfoSheetSpec, SheetSpec
|
from infrastructure.repositories.excel_repository import InfoSheetSpec, SheetSpec
|
||||||
|
|
||||||
@@ -60,6 +60,32 @@ class TestExcelRepository:
|
|||||||
assert len(loaded.liabilities) == len(sample_model.liabilities)
|
assert len(loaded.liabilities) == len(sample_model.liabilities)
|
||||||
assert len(loaded.exchange_rates) == len(sample_model.exchange_rates)
|
assert len(loaded.exchange_rates) == len(sample_model.exchange_rates)
|
||||||
|
|
||||||
|
def test_empty_rates_sheet_keeps_default_rates(self, tmp_path: Path):
|
||||||
|
# Н4: пустой лист «Курсы валют» раньше стирал DEFAULT_RATES, и любой
|
||||||
|
# валютный счёт молча выпадал из прогноза.
|
||||||
|
repo = ExcelRepository()
|
||||||
|
p = tmp_path / "no_rates.xlsx"
|
||||||
|
repo.save(FinancialModel(exchange_rates=[]), p)
|
||||||
|
|
||||||
|
loaded = repo.load(p)
|
||||||
|
assert len(loaded.exchange_rates) == 1
|
||||||
|
assert loaded.exchange_rates[0].from_currency == "USD"
|
||||||
|
assert loaded.exchange_rates[0].to_currency == "RUB"
|
||||||
|
assert loaded.exchange_rates[0].rate == Decimal("80")
|
||||||
|
|
||||||
|
def test_rates_from_sheet_are_added_to_defaults(self, tmp_path: Path):
|
||||||
|
repo = ExcelRepository()
|
||||||
|
p = tmp_path / "extra_rate.xlsx"
|
||||||
|
model = FinancialModel(
|
||||||
|
exchange_rates=[ExchangeRate(from_currency="EUR", to_currency="RUB", rate=Decimal("90"))]
|
||||||
|
)
|
||||||
|
repo.save(model, p)
|
||||||
|
|
||||||
|
loaded = repo.load(p)
|
||||||
|
pairs = {(r.from_currency, r.to_currency) for r in loaded.exchange_rates}
|
||||||
|
assert ("USD", "RUB") in pairs
|
||||||
|
assert ("EUR", "RUB") in pairs
|
||||||
|
|
||||||
def test_roundtrip_preserves_base_currency(self, tmp_path: Path):
|
def test_roundtrip_preserves_base_currency(self, tmp_path: Path):
|
||||||
repo = ExcelRepository()
|
repo = ExcelRepository()
|
||||||
model = FinancialModel(base_currency="EUR")
|
model = FinancialModel(base_currency="EUR")
|
||||||
|
|||||||
Reference in new issue
Block a user