From 169dbba092e344f1cb628e2cb6ceb957aa28767c Mon Sep 17 00:00:00 2001 From: Lars Date: Sat, 28 Mar 2026 13:27:16 +0100 Subject: [PATCH] debug: Add comprehensive logging to trace historical value lookup --- backend/routers/goals.py | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/backend/routers/goals.py b/backend/routers/goals.py index d2edb4e..c17a089 100644 --- a/backend/routers/goals.py +++ b/backend/routers/goals.py @@ -514,11 +514,17 @@ def update_goal(goal_id: str, data: GoalUpdate, session: dict = Depends(require_ goal_row = cur.fetchone() if goal_row: goal_type = goal_row['goal_type'] + print(f"[DEBUG] Looking up historical value for {goal_type} on {data.start_date}") historical_value = _get_historical_value_for_goal_type(conn, pid, goal_type, data.start_date) + print(f"[DEBUG] Historical value result: {historical_value}") if historical_value is not None: updates.append("start_value = %s") params.append(historical_value) print(f"[INFO] Auto-populated start_value from {data.start_date}: {historical_value}") + else: + print(f"[WARN] No historical data found for {goal_type} around {data.start_date}") + else: + print(f"[ERROR] Could not find goal with id {goal_id}") if data.start_value is not None: updates.append("start_value = %s") @@ -696,12 +702,16 @@ def _get_historical_value_for_goal_type(conn, profile_id: str, goal_type: str, t # Get goal type configuration config = get_goal_type_config(conn, goal_type) if not config: + print(f"[DEBUG] No config found for goal_type: {goal_type}") return None source_table = config.get('source_table') source_column = config.get('source_column') + print(f"[DEBUG] Config: table={source_table}, column={source_column}") + if not source_table or not source_column: + print(f"[DEBUG] Missing source_table or source_column") return None # Query for value closest to target_date (±7 days window) @@ -716,26 +726,37 @@ def _get_historical_value_for_goal_type(conn, profile_id: str, goal_type: str, t else: date_col = 'date' - cur.execute(f""" + query = f""" SELECT {source_column} FROM {source_table} WHERE profile_id = %s AND {date_col} BETWEEN %s AND %s ORDER BY ABS({date_col} - %s::date) LIMIT 1 - """, ( + """ + params = ( profile_id, target_date - timedelta(days=7), target_date + timedelta(days=7), target_date - )) + ) + + print(f"[DEBUG] Query: {query}") + print(f"[DEBUG] Params: {params}") + + cur.execute(query, params) row = cur.fetchone() + print(f"[DEBUG] Query result: {row}") + if row: value = row[source_column] # Convert Decimal to float - return float(value) if value is not None else None + result = float(value) if value is not None else None + print(f"[DEBUG] Returning value: {result}") + return result + print(f"[DEBUG] No data found in date range") return None except Exception as e: print(f"[ERROR] Failed to get historical value for {goal_type} on {target_date}: {e}")