GuglielmoTor commited on
Commit
bf7d3b2
·
verified ·
1 Parent(s): 6faec7c

Update services/report_data_handler.py

Browse files
Files changed (1) hide show
  1. services/report_data_handler.py +30 -17
services/report_data_handler.py CHANGED
@@ -20,6 +20,7 @@ from config import (
20
  logging.basicConfig(level=logging.INFO)
21
  logger = logging.getLogger(__name__)
22
 
 
23
  def fetch_latest_agentic_analysis(org_urn: str) -> Tuple[Optional[pd.DataFrame], Optional[str]]:
24
  """
25
  Fetches all agentic analysis report data for a given org_urn from Bubble.
@@ -54,31 +55,39 @@ def fetch_latest_agentic_analysis(org_urn: str) -> Tuple[Optional[pd.DataFrame],
54
  return None, str(e)
55
 
56
 
57
- def fetch_and_reconstruct_data_from_bubble(report_series: pd.Series) -> Optional[Dict[str, Any]]:
58
  """
59
- MODIFIED: Takes a pandas Series of a single report, fetches all related child items
60
- (OKRs, KRs, Tasks) from Bubble, and reconstructs the full nested dictionary.
 
61
 
62
  Args:
63
  report_series: A pandas Series representing a single report to be processed.
 
64
 
65
  Returns:
66
- A dictionary containing the reconstructed data ('report_str', 'actionable_okrs'),
67
- or None if the report series is invalid or a critical error occurs.
 
68
  """
69
- logger.info("Starting data reconstruction from a single fetched Bubble report.")
70
  if report_series is None or report_series.empty:
71
  logger.warning("Cannot reconstruct data, the provided report Series is empty.")
72
- return None
73
 
74
- try:
75
- report_id = report_series.get('_id')
76
- if not report_id:
77
- logger.error("Fetched report series is missing a Bubble '_id', cannot reconstruct children.")
78
- return None
79
 
80
- logger.info(f"Reconstructing all related data for report, ID: {report_id}")
 
 
 
 
 
81
 
 
82
  # 1. Fetch all related OKRs using the report_id
83
  okrs_df, error = fetch_linkedin_posts_data_from_bubble(
84
  data_type=BUBBLE_OKR_TABLE_NAME,
@@ -88,7 +97,7 @@ def fetch_and_reconstruct_data_from_bubble(report_series: pd.Series) -> Optional
88
  )
89
  if error:
90
  logger.error(f"Error fetching OKRs for report_id {report_id}: {error}")
91
- return None # Fail reconstruction if children can't be fetched
92
 
93
  # 2. Fetch all related Key Results using the OKR IDs
94
  okr_ids = okrs_df['_id'].tolist() if not okrs_df.empty else []
@@ -138,9 +147,13 @@ def fetch_and_reconstruct_data_from_bubble(report_series: pd.Series) -> Optional
138
  "actionable_okrs": actionable_okrs,
139
  "report_id": report_id
140
  }
141
- logger.info(f"Successfully reconstructed nested data structure for report {report_id}.")
142
- return final_reconstructed_data
 
 
 
 
143
 
144
  except Exception as e:
145
  logger.exception(f"An unexpected error occurred during data reconstruction: {e}")
146
- return None
 
20
  logging.basicConfig(level=logging.INFO)
21
  logger = logging.getLogger(__name__)
22
 
23
+
24
  def fetch_latest_agentic_analysis(org_urn: str) -> Tuple[Optional[pd.DataFrame], Optional[str]]:
25
  """
26
  Fetches all agentic analysis report data for a given org_urn from Bubble.
 
55
  return None, str(e)
56
 
57
 
58
+ def fetch_and_reconstruct_data_from_bubble(report_series: pd.Series, session_cache: dict) -> Tuple[Optional[Dict[str, Any]], dict]:
59
  """
60
+ MODIFIED: Takes a pandas Series of a single report and a session-specific cache dictionary.
61
+ It fetches all related child items from Bubble, reconstructs the full nested dictionary,
62
+ and uses the cache to avoid redundant API calls.
63
 
64
  Args:
65
  report_series: A pandas Series representing a single report to be processed.
66
+ session_cache: The session-specific cache dictionary from a Gradio State.
67
 
68
  Returns:
69
+ A tuple containing:
70
+ - The reconstructed data dictionary.
71
+ - The updated session_cache dictionary.
72
  """
73
+ logger.info("Attempting to get or reconstruct data for a Bubble report using session cache.")
74
  if report_series is None or report_series.empty:
75
  logger.warning("Cannot reconstruct data, the provided report Series is empty.")
76
+ return None, session_cache
77
 
78
+ report_id = report_series.get('_id')
79
+ if not report_id:
80
+ logger.error("Fetched report series is missing a Bubble '_id', cannot reconstruct children.")
81
+ return None, session_cache
 
82
 
83
+ # --- CACHE CHECK ---
84
+ if report_id in session_cache:
85
+ logger.info(f"CACHE HIT: Found reconstructed data for report ID {report_id} in session cache.")
86
+ return session_cache[report_id], session_cache
87
+
88
+ logger.info(f"CACHE MISS: No data for report ID {report_id}. Starting reconstruction from Bubble.io.")
89
 
90
+ try:
91
  # 1. Fetch all related OKRs using the report_id
92
  okrs_df, error = fetch_linkedin_posts_data_from_bubble(
93
  data_type=BUBBLE_OKR_TABLE_NAME,
 
97
  )
98
  if error:
99
  logger.error(f"Error fetching OKRs for report_id {report_id}: {error}")
100
+ return None, session_cache
101
 
102
  # 2. Fetch all related Key Results using the OKR IDs
103
  okr_ids = okrs_df['_id'].tolist() if not okrs_df.empty else []
 
147
  "actionable_okrs": actionable_okrs,
148
  "report_id": report_id
149
  }
150
+
151
+ # --- STORE IN SESSION CACHE ---
152
+ session_cache[report_id] = final_reconstructed_data
153
+ logger.info(f"Successfully reconstructed and cached data for report {report_id} in the current session.")
154
+
155
+ return final_reconstructed_data, session_cache
156
 
157
  except Exception as e:
158
  logger.exception(f"An unexpected error occurred during data reconstruction: {e}")
159
+ return None, session_cache