Markishime commited on
Commit
43e20d5
·
1 Parent(s): 02bbf6d

Fix: Add ANALYSIS_COMPLETE message sending and Firestore save with user ID

Browse files

- Added send_analysis_complete() function to send ANALYSIS_COMPLETE message to parent website
- Enhanced store_analysis_to_firestore() to reliably save with user_id for website queries
- Added logger import to cropdrive_integration.py (was missing, causing silent failures)
- Called send_analysis_complete() immediately after analysis completes in process_new_analysis()
- Improved error handling and logging throughout
- Ensures analysis results are saved to Firestore with user_id so website can fetch them
- Message format matches exact specification required by parent website

Files changed (2) hide show
  1. modules/results.py +286 -20
  2. utils/cropdrive_integration.py +163 -70
modules/results.py CHANGED
@@ -930,51 +930,82 @@ def validate_firestore_data(data):
930
  return False
931
 
932
  def store_analysis_to_firestore(analysis_results, result_id):
933
- """Store analysis results to Firestore with proper data flattening"""
 
 
 
 
 
 
 
 
 
 
934
  try:
935
  db = get_firestore_client()
936
  if not db:
 
937
  raise Exception("Firestore client not available")
938
 
939
- # Get user info from CropDrive integration (if available) or session state
 
 
 
 
 
940
  if CROPDRIVE_INTEGRATION_AVAILABLE:
941
- user_id = get_user_id()
942
- user_email = get_user_email()
943
- user_name = get_user_name()
944
- else:
945
- # Fallback to session state
 
 
 
 
 
 
946
  user_id = st.session_state.get('user_id', '')
947
  user_email = st.session_state.get('user_email', '')
948
  user_name = st.session_state.get('user_name', '')
 
 
949
 
950
- # If user_id is still empty, try to get from URL params (fallback)
951
  if not user_id:
952
  try:
953
  query_params = st.query_params
954
  user_id = query_params.get('userId', '')
955
  if user_id:
956
- logger.info(f"✅ Retrieved user_id from URL params for Firestore: {user_id}")
957
  # Also update session state for future use
958
  st.session_state.user_id = user_id
959
  if not user_email:
960
  user_email = query_params.get('userEmail', '')
961
  if user_email:
962
  st.session_state.user_email = user_email
 
 
 
 
963
  except Exception as e:
964
  logger.error(f"❌ Failed to get user_id from URL params: {e}")
965
 
966
- # Skip saving to Firestore if user is not authenticated (anonymous users)
 
967
  if not user_id:
968
- logger.warning("⚠️ Skipping Firestore storage - user ID not found (anonymous user)")
969
  logger.warning(f"⚠️ Session state user_id: {st.session_state.get('user_id', 'NOT SET')}")
970
  logger.warning(f"⚠️ Session state user_config: {st.session_state.get('user_config', {})}")
 
971
  return False
972
 
973
- # Create the document data structure for Firestore
 
974
  current_time = datetime.now()
975
  firestore_data = {
976
  'id': result_id,
977
- 'user_id': user_id, # Primary identifier from CropDrive
978
  'user_email': user_email if user_email else None,
979
  'user_name': user_name if user_name else None,
980
  'timestamp': current_time.isoformat(), # Convert to ISO string
@@ -984,7 +1015,9 @@ def store_analysis_to_firestore(analysis_results, result_id):
984
  'analysis_results': analysis_results
985
  }
986
 
987
- logger.info(f"💾 Storing analysis {result_id} for user_id: {user_id}, user_email: {user_email}")
 
 
988
 
989
  # Pre-process analysis_results to handle datetime objects and complex structures
990
  analysis_results = preprocess_analysis_results_for_firestore(analysis_results)
@@ -996,16 +1029,22 @@ def store_analysis_to_firestore(analysis_results, result_id):
996
  if not validate_firestore_data(firestore_data):
997
  logger.warning("Data validation failed, but proceeding with storage")
998
 
999
- # Store in the analysis_results collection
 
1000
  doc_ref = db.collection('analysis_results').document(result_id)
1001
  doc_ref.set(firestore_data)
1002
 
1003
  logger.info(f"✅ Analysis {result_id} stored to Firestore successfully")
 
 
1004
  return True
1005
 
1006
  except Exception as e:
1007
- logger.error(f"❌ Error storing analysis to Firestore: {e}")
1008
- raise e
 
 
 
1009
 
1010
 
1011
  def flatten_nested_arrays_for_firestore(data, preserve_keys=None):
@@ -1735,16 +1774,25 @@ def process_new_analysis(analysis_data, progress_bar, status_text, time_estimate
1735
 
1736
  logger.info(f"🔍 DEBUG - User info before Firestore save: user_id={display_user_id}, user_email={display_user_email}")
1737
 
1738
- # Store in Firestore for future access
 
1739
  firestore_saved = False
1740
  try:
 
 
 
 
1741
  firestore_saved = store_analysis_to_firestore(analysis_results, result_id)
 
1742
  if firestore_saved:
1743
  logger.info(f"✅ Successfully stored analysis {result_id} to Firestore")
 
 
1744
  else:
1745
- logger.warning(f"⚠️ Firestore storage skipped (no user_id or other reason)")
 
1746
  except Exception as e:
1747
- logger.error(f"❌ Failed to store analysis to Firestore: {e}")
1748
  import traceback
1749
  logger.error(f"Traceback: {traceback.format_exc()}")
1750
  # Continue with session state storage as fallback
@@ -1767,12 +1815,230 @@ def process_new_analysis(analysis_data, progress_bar, status_text, time_estimate
1767
  'firestore_saved': firestore_saved # Track if saved to Firestore
1768
  }
1769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1770
  return display_data
1771
 
1772
  except Exception as e:
1773
  st.error(f"Error processing analysis: {str(e)}")
1774
  return {'success': False, 'message': f'Processing error: {str(e)}'}
1775
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1776
  def get_analysis_results_from_data(results_data):
1777
  """Helper function to get analysis results from either results_data or session state"""
1778
  # Ensure results_data is a dictionary
 
930
  return False
931
 
932
  def store_analysis_to_firestore(analysis_results, result_id):
933
+ """
934
+ CRITICAL: Store analysis results to Firestore with user ID.
935
+ This function MUST save the analysis with the current user's ID so the website can fetch it.
936
+
937
+ Args:
938
+ analysis_results: The analysis results dict to save
939
+ result_id: Unique identifier for this analysis
940
+
941
+ Returns:
942
+ bool: True if saved successfully, False otherwise
943
+ """
944
  try:
945
  db = get_firestore_client()
946
  if not db:
947
+ logger.error("❌ Firestore client not available")
948
  raise Exception("Firestore client not available")
949
 
950
+ # CRITICAL: Get user ID from multiple sources (prioritize most reliable)
951
+ user_id = None
952
+ user_email = None
953
+ user_name = None
954
+
955
+ # Method 1: Try CropDrive integration first (most reliable)
956
  if CROPDRIVE_INTEGRATION_AVAILABLE:
957
+ try:
958
+ user_id = get_user_id()
959
+ user_email = get_user_email()
960
+ user_name = get_user_name()
961
+ if user_id:
962
+ logger.info(f"✅ Got user_id from CropDrive integration: {user_id}")
963
+ except Exception as e:
964
+ logger.warning(f"⚠️ CropDrive integration failed: {e}")
965
+
966
+ # Method 2: Try session state
967
+ if not user_id:
968
  user_id = st.session_state.get('user_id', '')
969
  user_email = st.session_state.get('user_email', '')
970
  user_name = st.session_state.get('user_name', '')
971
+ if user_id:
972
+ logger.info(f"✅ Got user_id from session state: {user_id}")
973
 
974
+ # Method 3: Try URL params (fallback)
975
  if not user_id:
976
  try:
977
  query_params = st.query_params
978
  user_id = query_params.get('userId', '')
979
  if user_id:
980
+ logger.info(f"✅ Retrieved user_id from URL params: {user_id}")
981
  # Also update session state for future use
982
  st.session_state.user_id = user_id
983
  if not user_email:
984
  user_email = query_params.get('userEmail', '')
985
  if user_email:
986
  st.session_state.user_email = user_email
987
+ if not user_name:
988
+ user_name = query_params.get('userName', '')
989
+ if user_name:
990
+ st.session_state.user_name = user_name
991
  except Exception as e:
992
  logger.error(f"❌ Failed to get user_id from URL params: {e}")
993
 
994
+ # CRITICAL: Skip saving to Firestore if user is not authenticated
995
+ # The website needs user_id to query and fetch analyses
996
  if not user_id:
997
+ logger.warning("⚠️ Skipping Firestore storage - user ID not found")
998
  logger.warning(f"⚠️ Session state user_id: {st.session_state.get('user_id', 'NOT SET')}")
999
  logger.warning(f"⚠️ Session state user_config: {st.session_state.get('user_config', {})}")
1000
+ logger.warning("⚠️ Analysis will not be accessible from website without user_id")
1001
  return False
1002
 
1003
+ # CRITICAL: Create the document data structure for Firestore
1004
+ # The website queries by 'user_id' field, so this MUST be included
1005
  current_time = datetime.now()
1006
  firestore_data = {
1007
  'id': result_id,
1008
+ 'user_id': user_id, # CRITICAL: Website queries by this field
1009
  'user_email': user_email if user_email else None,
1010
  'user_name': user_name if user_name else None,
1011
  'timestamp': current_time.isoformat(), # Convert to ISO string
 
1015
  'analysis_results': analysis_results
1016
  }
1017
 
1018
+ logger.info(f"💾 Storing analysis {result_id} to Firestore for user_id: {user_id}")
1019
+ logger.info(f"💾 User email: {user_email}, User name: {user_name}")
1020
+ logger.info(f"💾 Document will be queryable by: user_id == '{user_id}'")
1021
 
1022
  # Pre-process analysis_results to handle datetime objects and complex structures
1023
  analysis_results = preprocess_analysis_results_for_firestore(analysis_results)
 
1029
  if not validate_firestore_data(firestore_data):
1030
  logger.warning("Data validation failed, but proceeding with storage")
1031
 
1032
+ # CRITICAL: Store in the analysis_results collection
1033
+ # The website queries this collection with: where('user_id', '==', user_id)
1034
  doc_ref = db.collection('analysis_results').document(result_id)
1035
  doc_ref.set(firestore_data)
1036
 
1037
  logger.info(f"✅ Analysis {result_id} stored to Firestore successfully")
1038
+ logger.info(f"✅ Document ID: {result_id}, User ID: {user_id}")
1039
+ logger.info(f"✅ Website can now fetch this analysis with: where('user_id', '==', '{user_id}')")
1040
  return True
1041
 
1042
  except Exception as e:
1043
+ logger.error(f"❌ CRITICAL ERROR storing analysis to Firestore: {e}")
1044
+ import traceback
1045
+ logger.error(f"❌ Traceback: {traceback.format_exc()}")
1046
+ # Don't raise - return False so calling code knows save failed
1047
+ return False
1048
 
1049
 
1050
  def flatten_nested_arrays_for_firestore(data, preserve_keys=None):
 
1774
 
1775
  logger.info(f"🔍 DEBUG - User info before Firestore save: user_id={display_user_id}, user_email={display_user_email}")
1776
 
1777
+ # CRITICAL: Store in Firestore for website to fetch
1778
+ # This MUST happen with user_id so the website can query by user_id
1779
  firestore_saved = False
1780
  try:
1781
+ logger.info(f"💾 Attempting to save analysis {result_id} to Firestore...")
1782
+ logger.info(f"💾 Current user_id: {display_user_id}")
1783
+ logger.info(f"💾 Current user_email: {display_user_email}")
1784
+
1785
  firestore_saved = store_analysis_to_firestore(analysis_results, result_id)
1786
+
1787
  if firestore_saved:
1788
  logger.info(f"✅ Successfully stored analysis {result_id} to Firestore")
1789
+ logger.info(f"✅ Website can now fetch this analysis for user_id: {display_user_id}")
1790
+ logger.info(f"✅ Query: db.collection('analysis_results').where('user_id', '==', '{display_user_id}')")
1791
  else:
1792
+ logger.warning(f"⚠️ Firestore storage skipped - user_id not available")
1793
+ logger.warning(f"⚠️ Analysis will not be accessible from website")
1794
  except Exception as e:
1795
+ logger.error(f"❌ CRITICAL: Failed to store analysis to Firestore: {e}")
1796
  import traceback
1797
  logger.error(f"Traceback: {traceback.format_exc()}")
1798
  # Continue with session state storage as fallback
 
1815
  'firestore_saved': firestore_saved # Track if saved to Firestore
1816
  }
1817
 
1818
+ # CRITICAL: Send ANALYSIS_COMPLETE message IMMEDIATELY after analysis completes
1819
+ # This ensures results are saved to Firestore and upload counts are updated
1820
+ try:
1821
+ logger.info(f"📤 CRITICAL: Sending ANALYSIS_COMPLETE message after analysis completion...")
1822
+ logger.info(f"📤 Analysis ID: {result_id}, User ID: {display_user_id}")
1823
+
1824
+ # Prepare analysis_results in the format expected by send_analysis_complete
1825
+ analysis_data_for_message = {
1826
+ 'title': f'Analysis Report - {datetime.now().strftime("%Y-%m-%d")}',
1827
+ 'type': 'soil',
1828
+ 'summary': '',
1829
+ 'recommendations_count': 0,
1830
+ 'file_url': None,
1831
+ 'data': display_data,
1832
+ **analysis_results # Include all analysis results
1833
+ }
1834
+
1835
+ # Determine analysis type
1836
+ if display_data.get('soil_data') and display_data.get('leaf_data'):
1837
+ analysis_data_for_message['type'] = 'both'
1838
+ elif display_data.get('leaf_data'):
1839
+ analysis_data_for_message['type'] = 'leaf'
1840
+
1841
+ # Call send_analysis_complete with the prepared data
1842
+ send_analysis_complete(analysis_data_for_message)
1843
+ logger.info(f"✅ ANALYSIS_COMPLETE message sent successfully from process_new_analysis")
1844
+
1845
+ except Exception as e:
1846
+ logger.error(f"❌ CRITICAL ERROR sending ANALYSIS_COMPLETE in process_new_analysis: {e}")
1847
+ import traceback
1848
+ logger.error(f"Traceback: {traceback.format_exc()}")
1849
+ # Don't fail the analysis if message sending fails, but log it
1850
+
1851
  return display_data
1852
 
1853
  except Exception as e:
1854
  st.error(f"Error processing analysis: {str(e)}")
1855
  return {'success': False, 'message': f'Processing error: {str(e)}'}
1856
 
1857
+
1858
+ def send_analysis_complete(analysis_results):
1859
+ """
1860
+ CRITICAL: Send ANALYSIS_COMPLETE message to parent window immediately
1861
+ after analysis completes. This ensures results are saved to Firestore
1862
+ and upload counts are updated.
1863
+
1864
+ This function matches the exact specification required by the website.
1865
+
1866
+ Args:
1867
+ analysis_results: The analysis results dict with all analysis data
1868
+ """
1869
+ from streamlit.components.v1 import html
1870
+ import json
1871
+
1872
+ try:
1873
+ # Get user ID from session state (set from CONFIG message)
1874
+ user_id = st.session_state.get('user_id', '')
1875
+
1876
+ # Try to get from URL params as fallback
1877
+ if not user_id:
1878
+ try:
1879
+ query_params = st.query_params
1880
+ user_id = query_params.get('userId', '')
1881
+ except Exception:
1882
+ pass
1883
+
1884
+ # Try to get from CropDrive integration if available
1885
+ if not user_id:
1886
+ try:
1887
+ from utils.cropdrive_integration import get_user_id
1888
+ user_id = get_user_id()
1889
+ except ImportError:
1890
+ pass
1891
+
1892
+ # Determine analysis type from results
1893
+ analysis_type = 'soil' # Default
1894
+ if isinstance(analysis_results, dict):
1895
+ if analysis_results.get('soil_data') and analysis_results.get('leaf_data'):
1896
+ analysis_type = 'both'
1897
+ elif analysis_results.get('leaf_data'):
1898
+ analysis_type = 'leaf'
1899
+ elif analysis_results.get('type'):
1900
+ analysis_type = analysis_results.get('type')
1901
+
1902
+ # Extract summary and recommendations count
1903
+ summary = analysis_results.get('summary', '') if isinstance(analysis_results, dict) else ''
1904
+ recommendations_count = analysis_results.get('recommendations_count', 0) if isinstance(analysis_results, dict) else 0
1905
+
1906
+ # If summary not directly available, try to extract from step_by_step_analysis
1907
+ if not summary and isinstance(analysis_results, dict):
1908
+ step_analysis = analysis_results.get('step_by_step_analysis', [])
1909
+ if step_analysis:
1910
+ for step in step_analysis[:3]:
1911
+ if 'summary' in step:
1912
+ summary_text = step.get('summary', '')
1913
+ summary = summary_text[:200] + "..." if len(summary_text) > 200 else summary_text
1914
+ break
1915
+ elif 'key_findings' in step:
1916
+ findings = step.get('key_findings', [])
1917
+ if isinstance(findings, list) and findings:
1918
+ summary = findings[0][:200] + "..." if len(findings[0]) > 200 else findings[0]
1919
+ break
1920
+
1921
+ # If recommendations_count not available, count from step_by_step_analysis
1922
+ if recommendations_count == 0 and isinstance(analysis_results, dict):
1923
+ step_analysis = analysis_results.get('step_by_step_analysis', [])
1924
+ if step_analysis:
1925
+ for step in step_analysis:
1926
+ if 'recommendations' in step:
1927
+ recs = step['recommendations']
1928
+ if isinstance(recs, list):
1929
+ recommendations_count += len(recs)
1930
+ elif isinstance(recs, str):
1931
+ rec_lines = [r for r in recs.split('\n') if r.strip()]
1932
+ recommendations_count += len(rec_lines)
1933
+
1934
+ # Prepare the message - MUST match exact format expected by parent page
1935
+ message = {
1936
+ 'type': 'ANALYSIS_COMPLETE', # MUST be exactly this string
1937
+ 'userId': user_id, # From CONFIG message or session state
1938
+ 'title': analysis_results.get('title', f'Analysis Report - {datetime.now().strftime("%Y-%m-%d")}') if isinstance(analysis_results, dict) else f'Analysis Report - {datetime.now().strftime("%Y-%m-%d")}',
1939
+ 'analysisType': analysis_type,
1940
+ 'summary': summary or "Comprehensive soil and leaf analysis completed successfully.",
1941
+ 'recommendationsCount': recommendations_count,
1942
+ 'fileUrl': analysis_results.get('file_url') if isinstance(analysis_results, dict) else None,
1943
+ 'analysisData': analysis_results.get('data') if isinstance(analysis_results, dict) else analysis_results,
1944
+ 'timestamp': datetime.now().isoformat(),
1945
+ }
1946
+
1947
+ logger.info(f"📤 Sending ANALYSIS_COMPLETE message: userId={user_id}, type={analysis_type}")
1948
+ logger.info(f"📤 Message payload: {json.dumps(message, indent=2)}")
1949
+
1950
+ # CRITICAL: Use '*' as target origin to avoid browser errors
1951
+ # This matches the exact specification from the user
1952
+ html(f"""
1953
+ <script>
1954
+ console.log('📊 Sending ANALYSIS_COMPLETE message:', {json.dumps(message)});
1955
+ window.parent.postMessage({json.dumps(message)}, '*');
1956
+ console.log('✅ ANALYSIS_COMPLETE message sent successfully');
1957
+ </script>
1958
+ """, height=0)
1959
+
1960
+ logger.info(f"✅ ANALYSIS_COMPLETE message sent: userId={user_id}, type={analysis_type}")
1961
+
1962
+ except Exception as e:
1963
+ logger.error(f"❌ CRITICAL ERROR in send_analysis_complete: {e}")
1964
+ import traceback
1965
+ logger.error(f"Traceback: {traceback.format_exc()}")
1966
+ # Try to send a minimal message even if there's an error
1967
+ try:
1968
+ minimal_message = {
1969
+ 'type': 'ANALYSIS_COMPLETE',
1970
+ 'userId': st.session_state.get('user_id', ''),
1971
+ 'title': f'Analysis Report - {datetime.now().strftime("%Y-%m-%d")}',
1972
+ 'analysisType': 'soil',
1973
+ 'summary': 'Analysis completed successfully.',
1974
+ 'recommendationsCount': 0,
1975
+ 'fileUrl': None,
1976
+ 'analysisData': {},
1977
+ 'timestamp': datetime.now().isoformat(),
1978
+ }
1979
+ html(f"""
1980
+ <script>
1981
+ console.error('⚠️ Sending minimal ANALYSIS_COMPLETE message due to error');
1982
+ window.parent.postMessage({json.dumps(minimal_message)}, '*');
1983
+ </script>
1984
+ """, height=0)
1985
+ except Exception as fallback_error:
1986
+ logger.error(f"❌ Failed to send fallback ANALYSIS_COMPLETE: {fallback_error}")
1987
+
1988
+
1989
+ def _send_analysis_complete_inline(results_data, analysis_results=None):
1990
+ """
1991
+ Wrapper function that calls send_analysis_complete with proper data structure.
1992
+ This ensures compatibility with existing code.
1993
+ """
1994
+ try:
1995
+ # Prepare analysis_results dict in the format expected by send_analysis_complete
1996
+ if analysis_results:
1997
+ analysis_data = {
1998
+ 'title': results_data.get('title', f'Analysis Report - {datetime.now().strftime("%Y-%m-%d")}'),
1999
+ 'type': 'soil',
2000
+ 'summary': '',
2001
+ 'recommendations_count': 0,
2002
+ 'file_url': results_data.get('file_url'),
2003
+ 'data': {
2004
+ 'resultId': results_data.get('id'),
2005
+ 'timestamp': results_data.get('timestamp').isoformat() if hasattr(results_data.get('timestamp'), 'isoformat') else str(results_data.get('timestamp', datetime.now())),
2006
+ 'status': 'completed',
2007
+ 'userId': results_data.get('user_id'),
2008
+ 'firestoreSaved': results_data.get('firestore_saved', False)
2009
+ },
2010
+ **analysis_results # Include all analysis results
2011
+ }
2012
+ else:
2013
+ analysis_data = {
2014
+ 'title': results_data.get('title', f'Analysis Report - {datetime.now().strftime("%Y-%m-%d")}'),
2015
+ 'type': 'soil',
2016
+ 'summary': '',
2017
+ 'recommendations_count': 0,
2018
+ 'file_url': results_data.get('file_url'),
2019
+ 'data': results_data
2020
+ }
2021
+
2022
+ # Determine analysis type
2023
+ if results_data.get('soil_data') and results_data.get('leaf_data'):
2024
+ analysis_data['type'] = 'both'
2025
+ elif results_data.get('leaf_data'):
2026
+ analysis_data['type'] = 'leaf'
2027
+
2028
+ # Call the main send_analysis_complete function
2029
+ send_analysis_complete(analysis_data)
2030
+
2031
+ except Exception as e:
2032
+ logger.error(f"❌ Error in _send_analysis_complete_inline: {e}")
2033
+ import traceback
2034
+ logger.error(f"Traceback: {traceback.format_exc()}")
2035
+ # Fallback: try calling send_analysis_complete directly with results_data
2036
+ try:
2037
+ send_analysis_complete(results_data)
2038
+ except Exception as fallback_error:
2039
+ logger.error(f"❌ Fallback also failed: {fallback_error}")
2040
+
2041
+
2042
  def get_analysis_results_from_data(results_data):
2043
  """Helper function to get analysis results from either results_data or session state"""
2044
  # Ensure results_data is a dictionary
utils/cropdrive_integration.py CHANGED
@@ -6,6 +6,10 @@ Handles communication with parent window when embedded in CropDrive website
6
  import streamlit as st
7
  from streamlit.components.v1 import html
8
  import json
 
 
 
 
9
 
10
  # ============================================================================
11
  # STEP 1: JavaScript for parent window communication
@@ -274,7 +278,8 @@ def send_analysis_complete(
274
  analysis_data: dict = None
275
  ):
276
  """
277
- Send analysis completion message to parent window (CropDrive website)
 
278
 
279
  Args:
280
  title: Report title (required)
@@ -286,77 +291,165 @@ def send_analysis_complete(
286
  """
287
  from datetime import datetime
288
 
289
- # Include user ID in the analysis complete message
290
- user_id = get_user_id()
291
- user_email = get_user_email()
292
-
293
- # Log user info for debugging
294
- logger.info(f"🔍 DEBUG send_analysis_complete - user_id: {user_id}, user_email: {user_email}")
295
-
296
- # Warn if user_id is missing (critical for parent page to save analysis)
297
- if not user_id:
298
- logger.warning("⚠️ WARNING: user_id is empty when sending ANALYSIS_COMPLETE message!")
299
- logger.warning(f"⚠️ Session state user_id: {st.session_state.get('user_id', 'NOT SET')}")
300
- logger.warning(f"⚠️ Session state user_config: {st.session_state.get('user_config', {})}")
301
- # Try to get from URL params as fallback
302
- try:
303
- query_params = st.query_params
304
- user_id = query_params.get('userId', '')
305
- if user_id:
306
- logger.info(f"✅ Retrieved user_id from URL params: {user_id}")
307
- except Exception as e:
308
- logger.error(f"❌ Failed to get user_id from URL params: {e}")
309
-
310
- # Ensure analysis_data includes timestamp if not already present
311
- if analysis_data is None:
312
- analysis_data = {}
313
-
314
- # Add timestamp if not already in analysis_data
315
- if 'timestamp' not in analysis_data:
316
- analysis_data['timestamp'] = datetime.now().isoformat()
317
-
318
- # Ensure userId is in analysis_data as well (for redundancy)
319
- if 'userId' not in analysis_data:
320
- analysis_data['userId'] = user_id
321
-
322
- message = {
323
- 'type': 'ANALYSIS_COMPLETE',
324
- 'userId': user_id, # CRITICAL: Must match current authenticated user
325
- 'title': title,
326
- 'analysisType': analysis_type,
327
- 'summary': summary or '',
328
- 'recommendationsCount': recommendations_count,
329
- 'fileUrl': file_url,
330
- 'analysisData': analysis_data or {},
331
- 'timestamp': datetime.now().isoformat()
332
- }
333
-
334
- # Log the complete message for debugging
335
- logger.info(f"📤 Sending ANALYSIS_COMPLETE message: userId={user_id}, title={title}, type={analysis_type}")
336
-
337
- # IMPORTANT: Use '*' as target origin to avoid origin mismatch errors
338
- # The parent page will verify the message origin on its side
339
- send_js = f"""
340
- <script>
341
- (function() {{
342
- const message = {json.dumps(message)};
343
- console.log('📤 Sending ANALYSIS_COMPLETE message:', message);
344
- console.log('📤 Message userId:', message.userId);
345
- console.log('📤 Message type:', message.type);
346
 
347
- // Send message to parent window
348
- window.parent.postMessage(message, '*');
349
 
350
- // Also log after sending
351
- console.log('✅ ANALYSIS_COMPLETE message sent successfully');
352
- }})();
353
- </script>
354
- """
355
-
356
- html(send_js, height=0)
357
-
358
- # Also log in Python
359
- logger.info(f"✅ ANALYSIS_COMPLETE message HTML injected for user_id: {user_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
 
361
  # ============================================================================
362
  # STEP 4: Handle plan-based features
 
6
  import streamlit as st
7
  from streamlit.components.v1 import html
8
  import json
9
+ import logging
10
+
11
+ # Configure logger
12
+ logger = logging.getLogger(__name__)
13
 
14
  # ============================================================================
15
  # STEP 1: JavaScript for parent window communication
 
278
  analysis_data: dict = None
279
  ):
280
  """
281
+ CRITICAL: Send analysis completion message to parent window (CropDrive website)
282
+ This message MUST be sent after every analysis completes to save results to Firestore.
283
 
284
  Args:
285
  title: Report title (required)
 
291
  """
292
  from datetime import datetime
293
 
294
+ try:
295
+ # Include user ID in the analysis complete message
296
+ user_id = get_user_id()
297
+ user_email = get_user_email()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
 
299
+ # Log user info for debugging
300
+ logger.info(f"🔍 DEBUG send_analysis_complete - user_id: {user_id}, user_email: {user_email}")
301
 
302
+ # Warn if user_id is missing (critical for parent page to save analysis)
303
+ if not user_id:
304
+ logger.warning("⚠️ WARNING: user_id is empty when sending ANALYSIS_COMPLETE message!")
305
+ logger.warning(f"⚠️ Session state user_id: {st.session_state.get('user_id', 'NOT SET')}")
306
+ logger.warning(f"⚠️ Session state user_config: {st.session_state.get('user_config', {})}")
307
+ # Try to get from URL params as fallback
308
+ try:
309
+ query_params = st.query_params
310
+ user_id = query_params.get('userId', '')
311
+ if user_id:
312
+ logger.info(f"✅ Retrieved user_id from URL params: {user_id}")
313
+ except Exception as e:
314
+ logger.error(f"❌ Failed to get user_id from URL params: {e}")
315
+
316
+ # Ensure analysis_data includes timestamp if not already present
317
+ if analysis_data is None:
318
+ analysis_data = {}
319
+
320
+ # Add timestamp if not already in analysis_data
321
+ if 'timestamp' not in analysis_data:
322
+ analysis_data['timestamp'] = datetime.now().isoformat()
323
+
324
+ # Ensure userId is in analysis_data as well (for redundancy)
325
+ if 'userId' not in analysis_data:
326
+ analysis_data['userId'] = user_id
327
+
328
+ # CRITICAL: Build message with exact format expected by parent page
329
+ message = {
330
+ 'type': 'ANALYSIS_COMPLETE', # MUST be exactly this string
331
+ 'userId': user_id or '', # CRITICAL: Must match current authenticated user
332
+ 'title': title or f'Analysis Report - {datetime.now().strftime("%Y-%m-%d")}',
333
+ 'analysisType': analysis_type or 'soil', # 'soil', 'leaf', or 'both'
334
+ 'summary': summary or '',
335
+ 'recommendationsCount': int(recommendations_count) if recommendations_count else 0,
336
+ 'fileUrl': file_url or None,
337
+ 'analysisData': analysis_data or {},
338
+ 'timestamp': datetime.now().isoformat()
339
+ }
340
+
341
+ # Log the complete message for debugging
342
+ logger.info(f"📤 Sending ANALYSIS_COMPLETE message: userId={user_id}, title={title}, type={analysis_type}")
343
+ logger.info(f"📤 Message payload: {json.dumps(message, indent=2)}")
344
+
345
+ # CRITICAL: Use '*' as target origin to avoid origin mismatch errors
346
+ # The parent page will verify the message origin on its side
347
+ # Use multiple methods to ensure message is sent even if one fails
348
+ send_js = f"""
349
+ <script>
350
+ (function() {{
351
+ try {{
352
+ const message = {json.dumps(message)};
353
+ console.log('📊 Sending ANALYSIS_COMPLETE message:', message);
354
+ console.log('📊 Message userId:', message.userId);
355
+ console.log('📊 Message type:', message.type);
356
+
357
+ // Method 1: Direct postMessage (primary method)
358
+ if (window.parent && window.parent !== window) {{
359
+ window.parent.postMessage(message, '*');
360
+ console.log('✅ ANALYSIS_COMPLETE message sent via window.parent.postMessage');
361
+ }} else {{
362
+ console.warn('⚠️ window.parent not available, trying alternative methods');
363
+ }}
364
+
365
+ // Method 2: Try top.postMessage as fallback
366
+ if (window.top && window.top !== window && window.top !== window.parent) {{
367
+ try {{
368
+ window.top.postMessage(message, '*');
369
+ console.log('✅ ANALYSIS_COMPLETE message sent via window.top.postMessage');
370
+ }} catch (e) {{
371
+ console.warn('⚠️ window.top.postMessage failed:', e);
372
+ }}
373
+ }}
374
+
375
+ // Method 3: Try with a small delay (in case parent isn't ready)
376
+ setTimeout(function() {{
377
+ if (window.parent && window.parent !== window) {{
378
+ window.parent.postMessage(message, '*');
379
+ console.log('✅ ANALYSIS_COMPLETE message sent via delayed postMessage');
380
+ }}
381
+ }}, 100);
382
+
383
+ // Method 4: Try again after a longer delay
384
+ setTimeout(function() {{
385
+ if (window.parent && window.parent !== window) {{
386
+ window.parent.postMessage(message, '*');
387
+ console.log('✅ ANALYSIS_COMPLETE message sent via second delayed postMessage');
388
+ }}
389
+ }}, 500);
390
+
391
+ console.log('✅ ANALYSIS_COMPLETE message send attempts completed');
392
+ }} catch (error) {{
393
+ console.error('❌ Error sending ANALYSIS_COMPLETE message:', error);
394
+ // Try one more time with basic postMessage
395
+ try {{
396
+ const message = {json.dumps(message)};
397
+ window.parent.postMessage(message, '*');
398
+ console.log('✅ ANALYSIS_COMPLETE message sent via fallback method');
399
+ }} catch (e) {{
400
+ console.error('❌ All methods failed to send ANALYSIS_COMPLETE:', e);
401
+ }}
402
+ }}
403
+ }})();
404
+ </script>
405
+ """
406
+
407
+ # Inject the JavaScript
408
+ html(send_js, height=0)
409
+
410
+ # Also log in Python
411
+ logger.info(f"✅ ANALYSIS_COMPLETE message HTML injected for user_id: {user_id}")
412
+
413
+ # Show success message to user
414
+ st.success("✅ Analysis completed! Results are being saved...")
415
+
416
+ except Exception as e:
417
+ # CRITICAL: Log error but don't fail silently
418
+ logger.error(f"❌ CRITICAL ERROR in send_analysis_complete: {e}")
419
+ import traceback
420
+ logger.error(f"❌ Traceback: {traceback.format_exc()}")
421
+
422
+ # Try to send a minimal message even if there's an error
423
+ try:
424
+ minimal_message = {
425
+ 'type': 'ANALYSIS_COMPLETE',
426
+ 'userId': get_user_id() or '',
427
+ 'title': title or 'Analysis Report',
428
+ 'analysisType': analysis_type or 'soil',
429
+ 'summary': summary or '',
430
+ 'recommendationsCount': 0,
431
+ 'fileUrl': None,
432
+ 'analysisData': {},
433
+ 'timestamp': datetime.now().isoformat()
434
+ }
435
+
436
+ fallback_js = f"""
437
+ <script>
438
+ try {{
439
+ const message = {json.dumps(minimal_message)};
440
+ console.error('⚠️ Sending minimal ANALYSIS_COMPLETE message due to error');
441
+ if (window.parent && window.parent !== window) {{
442
+ window.parent.postMessage(message, '*');
443
+ console.log('✅ Minimal ANALYSIS_COMPLETE message sent');
444
+ }}
445
+ }} catch (e) {{
446
+ console.error('❌ Failed to send minimal ANALYSIS_COMPLETE:', e);
447
+ }}
448
+ </script>
449
+ """
450
+ html(fallback_js, height=0)
451
+ except Exception as fallback_error:
452
+ logger.error(f"❌ Failed to send fallback ANALYSIS_COMPLETE message: {fallback_error}")
453
 
454
  # ============================================================================
455
  # STEP 4: Handle plan-based features