diff --git a/backend/app/db/functions/recommendations_functions.py b/backend/app/db/functions/recommendations_functions.py index 7ffcf603..900b5b9f 100644 --- a/backend/app/db/functions/recommendations_functions.py +++ b/backend/app/db/functions/recommendations_functions.py @@ -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() diff --git a/backend/categorisation/processor.py b/backend/categorisation/processor.py index e90c3b08..ea12bc3b 100644 --- a/backend/categorisation/processor.py +++ b/backend/categorisation/processor.py @@ -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: