only get most recently added plans for scenario

This commit is contained in:
Daniel Roth 2026-02-20 13:39:07 +00:00
parent 1119eb24bc
commit ec01e1d190
2 changed files with 15 additions and 6 deletions

View file

@ -632,8 +632,19 @@ def get_plans_by_scenario_ids(ids: List[int]) -> List[PlanModel]:
return session_any.exec(stmt).scalars().all()
def get_plan_ids_by_scenario_ids(scenario_ids: List[int]) -> List[int]:
stmt = select(PlanModel.id).where(PlanModel.scenario_id.in_(scenario_ids))
def get_most_recent_plan_ids_by_scenario_ids(scenario_ids: List[int]) -> List[int]:
# NOTE: This statement works for Postgres only, because of the Distinct
stmt = (
select(PlanModel.id)
.where(PlanModel.scenario_id.in_(scenario_ids))
.distinct(PlanModel.scenario_id)
.order_by(
PlanModel.scenario_id,
PlanModel.created_at.desc(),
PlanModel.id.desc(),
)
)
with db_read_session() as session:
session_any: Any = session # Typehint as Any to satisfy Pylance...
return session_any.exec(stmt).scalars().all()

View file

@ -4,7 +4,7 @@ from typing import Dict, List, Optional, Tuple
from backend.app.db.functions.recommendations_functions import (
bulk_update_plans,
get_default_scenario_ids_for_portfolio,
get_plan_ids_by_scenario_ids,
get_most_recent_plan_ids_by_scenario_ids,
get_plans_by_portfolio_id,
get_plans_by_scenario_ids,
get_scenarios_by_portfolio_id,
@ -37,10 +37,8 @@ def process_portfolio(
)
plans: List[Plan] = _load_plans_for_portfolio(portfolio_id, scenarios_to_consider)
logger.info(f"Successfully loaded {len(plans)}")
plans_by_property: Dict[int, List[Plan]] = _group_plans_by_property(plans)
logger.info("Successfully grouped plans by property")
updated_plan_models: List[PlanModel] = []
updated_scenario_models: List[ScenarioModel] = []
@ -120,7 +118,7 @@ def _unset_defaults_for_scenarios_not_being_considered(
)
if len(scenarios_to_unset_default) > 0:
plans_to_unset_default: List[int] = get_plan_ids_by_scenario_ids(
plans_to_unset_default: List[int] = get_most_recent_plan_ids_by_scenario_ids(
scenarios_to_unset_default
)
for plan_id in plans_to_unset_default: