function smartstat_save_to_document
Flask route handler that saves SmartStat statistical analysis results back to a data section document, generating a final report with queries, results, and plots.
/tf/active/vicechatdev/vice_ai/new_app.py
5765 - 5843
complex
Purpose
This endpoint is part of a document analysis workflow where SmartStat performs statistical analysis on data. It generates a final report from the analysis session, saves the results (including markdown content and plots) to the associated data section, updates metadata, and redirects the user to the workspace with the updated document. It includes session recovery logic and ownership verification for security.
Source Code
def smartstat_save_to_document(session_id):
"""Save SmartStat analysis results back to data section (legacy - saves all)"""
user_email = get_current_user()
# Verify session exists - recreate if needed
session = smartstat_service.get_session(session_id)
if not session:
logger.warning(f"Session {session_id} not found - attempting to recover")
all_sections = data_section_service.get_user_data_sections(user_email)
data_section = next((ds for ds in all_sections if ds.analysis_session_id == session_id), None)
if data_section:
session = SmartStatSession(session_id, data_section.id, data_section.title)
smartstat_service.sessions[session_id] = session
else:
return jsonify({'error': 'Session not found'}), 404
# Verify data section ownership
data_section = data_section_service.get_data_section(session.data_section_id)
if not data_section or data_section.owner != user_email:
return jsonify({'error': 'Access denied'}), 403
try:
# Generate final report
report_result = smartstat_service.generate_final_report(session_id)
if not report_result['success']:
return jsonify({'error': 'Failed to generate report'}), 500
report = report_result['report']
# Compile results for data section body (title is already shown in UI header)
body_content = f"**Analysis Completed:** {report['completed_at']}\n\n"
for section in report['sections']:
body_content += f"## Query {section['number']}: {section['query']}\n\n"
body_content += f"{section['results']}\n\n"
# Note: plots are stored in metadata.all_plots and displayed separately
# Store raw markdown - frontend will render with marked.js
# Update data section with results
data_section = data_section_service.get_data_section(session.data_section_id)
data_section.current_content = body_content # Store markdown, not HTML
data_section.analysis_conclusions = body_content # Also update conclusions
# Store full report in metadata
if not data_section.metadata:
data_section.metadata = {}
data_section.metadata['report'] = report
data_section.metadata['all_plots'] = report['all_plots']
data_section_service.update_data_section(data_section)
# Find which document contains this data section
document_id = None
conn = db_manager._get_connection()
cursor = conn.execute(
"SELECT document_id FROM document_sections WHERE section_id = ? AND section_type = 'data'",
(session.data_section_id,)
)
row = cursor.fetchone()
if row:
document_id = row[0]
# Redirect to workspace with document parameter if found
if document_id:
redirect_url = f"{url_for('workspace')}?document={document_id}"
else:
redirect_url = url_for('workspace')
return jsonify({
'success': True,
'message': 'Analysis results saved to document',
'redirect_url': redirect_url
})
except Exception as e:
logger.error(f"Error saving SmartStat results: {e}")
return jsonify({'error': str(e)}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_id |
- | - | positional_or_keyword |
Parameter Details
session_id: String identifier for the SmartStat analysis session. Used to retrieve the session state, associated data section, and analysis results. Must correspond to an existing or recoverable session.
Return Value
Returns a Flask JSON response. On success (200): {'success': True, 'message': 'Analysis results saved to document', 'redirect_url': '<workspace_url>'}. On error: {'error': '<error_message>'} with status codes 404 (session not found), 403 (access denied), or 500 (generation/save failure).
Dependencies
flasklogginguuiddatetimetyping
Required Imports
from flask import jsonify, url_for
import logging
from services import DataSectionService
from smartstat_service import SmartStatService, SmartStatSession
from models import DatabaseManager
Usage Example
# This is a Flask route handler, typically called via HTTP POST request
# Example client-side JavaScript call:
fetch('/api/smartstat/abc-123-session-id/save-to-document', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
window.location.href = data.redirect_url;
} else {
console.error('Save failed:', data.error);
}
});
# Server-side setup required:
# app = Flask(__name__)
# smartstat_service = SmartStatService()
# data_section_service = DataSectionService()
# db_manager = DatabaseManager()
#
# @app.route('/api/smartstat/<session_id>/save-to-document', methods=['POST'])
# @require_auth
# def smartstat_save_to_document(session_id):
# # Function implementation as shown
Best Practices
- Always verify user authentication and ownership before allowing data modifications
- Implement session recovery logic to handle edge cases where sessions may be lost
- Store both raw markdown content and metadata separately for flexibility in rendering
- Use proper error handling and logging for debugging production issues
- Return appropriate HTTP status codes (403 for access denied, 404 for not found, 500 for server errors)
- Provide redirect URLs in responses to guide user navigation after operations
- Validate that the data section exists and belongs to the authenticated user before saving
- Store plot data in metadata for separate rendering rather than embedding in content
- Use database transactions when updating multiple related records
- Consider implementing idempotency to handle duplicate save requests safely
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function smartstat_save_selective 85.5% similar
-
function smartstat_workspace 77.0% similar
-
function save_data_section_analysis 76.3% similar
-
function smartstat_upload_data 73.9% similar
-
function smartstat_get_history 73.3% similar