🔍 Code Extractor

function get_available_sections_for_document

Maturity: 49

Flask API endpoint that retrieves text sections available to add to a specific document by filtering out sections already included in that document.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
1760 - 1790
Complexity:
moderate

Purpose

This endpoint serves as part of a document management system, allowing users to discover which of their text sections can still be added to a particular document. It enforces ownership verification to ensure users can only access their own documents and sections, then performs a set difference operation to return only sections not currently in the document.

Source Code

def get_available_sections_for_document(document_id):
    """Get text sections that can be added to a document (not already included)"""
    try:
        user_email = get_current_user()
        
        # Verify document ownership
        document = document_service.get_document(document_id)
        if not document or document.owner != user_email:
            return jsonify({'error': 'Document not found or access denied'}), 404
        
        # Get all user's text sections
        all_sections = text_section_service.get_user_text_sections(user_email)
        
        # Get sections already in document
        existing_section_ids = {ds.section_id for ds in document.sections}
        
        # Filter out sections already in document
        available_sections = [
            section.to_dict() for section in all_sections 
            if section.id not in existing_section_ids
        ]
        
        return jsonify({
            'success': True,
            'available_sections': available_sections,
            'document_id': document_id
        })
        
    except Exception as e:
        logger.error(f"Error getting available sections: {e}")
        return jsonify({'error': str(e)}), 400

Parameters

Name Type Default Kind
document_id - - positional_or_keyword

Parameter Details

document_id: String identifier (likely UUID) of the document for which to retrieve available sections. Used to fetch the document and filter out sections already associated with it.

Return Value

Returns a Flask JSON response tuple. On success (200): {'success': True, 'available_sections': [list of section dictionaries], 'document_id': document_id}. On authorization failure (404): {'error': 'Document not found or access denied'}. On exception (400): {'error': error_message_string}. Each section dictionary contains the serialized representation from the section.to_dict() method.

Dependencies

  • flask
  • logging
  • typing

Required Imports

from flask import jsonify
import logging

Usage Example

# Example Flask route usage (already decorated in source)
# Client-side request:
import requests

# Assuming authentication is handled via session/cookies
response = requests.get(
    'http://localhost:5000/api/documents/abc-123-def/sections/available',
    cookies={'session': 'your_session_token'}
)

if response.status_code == 200:
    data = response.json()
    available_sections = data['available_sections']
    for section in available_sections:
        print(f"Section ID: {section['id']}, Title: {section.get('title', 'N/A')}")
else:
    print(f"Error: {response.json().get('error')}")

Best Practices

  • Always verify document ownership before returning sensitive data to prevent unauthorized access
  • Use set comprehension for efficient filtering of existing section IDs
  • Implement proper error logging for debugging production issues
  • Return appropriate HTTP status codes (404 for not found/unauthorized, 400 for general errors)
  • Consider pagination if users have large numbers of text sections to avoid performance issues
  • The function assumes document.sections contains DocumentSection objects with section_id attributes
  • Ensure the require_auth decorator is properly implemented to prevent unauthenticated access
  • Consider caching user sections if this endpoint is called frequently
  • The to_dict() method on TextSection should not expose sensitive internal data

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_text_sections 86.4% similar

    Flask API endpoint that retrieves all text and data sections for a specific document, verifying user ownership and returning sections sorted by position.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_document_v4 79.1% similar

    Flask API endpoint that retrieves a specific document with its text and data sections, including optional sharing information, for authenticated users.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function create_text_section_for_document 78.4% similar

    Flask API endpoint that creates or adds text sections to a document with three action modes: creating new sections, adding existing sections, or duplicating existing sections.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_text_sections 78.0% similar

    Flask API endpoint that retrieves text sections for the authenticated user with optional filtering by type, search query, tags, and uniqueness.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function add_existing_section_to_document 77.4% similar

    Flask API endpoint that adds an existing text section to a document with advanced positioning options, copy creation, and access control validation.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse