- application/forecast.py: остатки обязательств и стоимость активов ведутся
в локальном состоянии расчёта (liability_balances / asset_values), а не
мутируются в self.model. Формула прогноза и порядок вызовов _liability_cost
(по одному на каждый счёт × месяц) сохранены — числа не изменились.
- summary(months, results=None): сводка теперь может считаться по уже
посчитанному набору результатов.
- infrastructure/cli/commands/forecast.py и infrastructure/ai/assistant.py:
сводка считается по тому же набору строк, который печатается/попадает
в промпт.
- tests/test_forecast.py: характеристика мутаций переписана на идемпотентность
(+2 теста: неизменность модели, «Итог» == последняя строка таблицы).
Было → стало (sample_model):
повторный forecast_cashflow(12) 13649.62 → 13087.98 (тот же, что первый)
сумма balance за 12 мес. (2-й вызов) 368465.98 → 361041.88
summary(12) после 2 прогнозов 13730.60/52867.46/19200.00
→ 13087.98/52149.97/20705.87
CLI «Итог: Баланс» (модель из data/) ₽50,776.75 → ₽50,717.22
(теперь совпадает с последней строкой таблицы; раньше расходилось)
81 lines
2.8 KiB
Python
81 lines
2.8 KiB
Python
import json
|
|
from decimal import Decimal
|
|
|
|
from application.forecast import ForecastService
|
|
from domain import CurrencyConverter, FinancialModel
|
|
from infrastructure.ai import prompts
|
|
|
|
|
|
class AssistantError(Exception):
|
|
pass
|
|
|
|
|
|
class _DecimalEncoder(json.JSONEncoder):
|
|
"""JSON-сериализатор: Decimal → str (для AI-промптов)."""
|
|
|
|
def default(self, o):
|
|
if isinstance(o, Decimal):
|
|
return str(o)
|
|
return super().default(o)
|
|
|
|
|
|
class AssistantService:
|
|
def __init__(
|
|
self,
|
|
model: FinancialModel,
|
|
forecast_service: ForecastService,
|
|
converter: CurrencyConverter | None = None,
|
|
display_currency: str | None = None,
|
|
):
|
|
self.model = model
|
|
self.forecast_service = forecast_service
|
|
self.converter = converter or CurrencyConverter(model.exchange_rates)
|
|
self.display_currency = display_currency or model.base_currency
|
|
|
|
def analyze(self, months: int = 12) -> dict:
|
|
forecast_result = self.forecast_service.forecast_cashflow(months)
|
|
# Сводка — по тому же набору строк, что и в промпте (D14).
|
|
summary = self.forecast_service.summary(months, results=forecast_result)
|
|
|
|
prompt = prompts.format_context(
|
|
model_json=json.dumps(self.model.to_dict(), indent=2, ensure_ascii=False, cls=_DecimalEncoder),
|
|
forecast_json=json.dumps(forecast_result, indent=2, ensure_ascii=False, cls=_DecimalEncoder),
|
|
months=months,
|
|
base_currency=self.model.base_currency,
|
|
display_currency=self.display_currency,
|
|
)
|
|
|
|
return {
|
|
"prompt": prompt,
|
|
"summary": summary,
|
|
"forecast": forecast_result,
|
|
"ai_response": None,
|
|
}
|
|
|
|
def advice(self, question: str, months: int = 12) -> dict:
|
|
forecast_result = self.forecast_service.forecast_cashflow(months)
|
|
|
|
prompt = prompts.ADVICE_PROMPT.format(
|
|
model_json=json.dumps(self.model.to_dict(), indent=2, ensure_ascii=False, cls=_DecimalEncoder),
|
|
forecast_json=json.dumps(forecast_result, indent=2, ensure_ascii=False, cls=_DecimalEncoder),
|
|
question=question,
|
|
base_currency=self.model.base_currency,
|
|
display_currency=self.display_currency,
|
|
)
|
|
|
|
return {
|
|
"prompt": prompt,
|
|
"ai_response": None,
|
|
}
|
|
|
|
def compare_scenarios(self, scenarios_json: str) -> dict:
|
|
prompt = prompts.SCENARIO_COMPARISON_PROMPT.format(
|
|
scenarios_json=scenarios_json,
|
|
base_currency=self.model.base_currency,
|
|
display_currency=self.display_currency,
|
|
)
|
|
return {
|
|
"prompt": prompt,
|
|
"ai_response": None,
|
|
}
|