🔍 Code Extractor

function add_existing_section_to_document

Maturity: 49

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

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
1397 - 1482
Complexity:
complex

Purpose

This endpoint allows authenticated users to add text sections to their documents with flexible positioning (append, insert before/after reference sections, or at specific positions). It supports creating copies of sections to avoid duplicates, validates ownership and access permissions, and returns the updated document state. The function handles complex positioning logic including relative positioning to reference sections and prevents duplicate section additions unless explicitly requested.

Source Code

def add_existing_section_to_document(document_id):
    """Add a text section to a document with enhanced positioning and sharing options"""
    user_email = get_current_user()
    data = request.get_json()
    
    # 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
    
    try:
        text_section_id = data.get('text_section_id')
        position = data.get('position', -1)  # -1 means append at end
        insert_mode = data.get('insert_mode', 'after')  # 'before', 'after', 'replace'
        reference_section_id = data.get('reference_section_id')  # ID of section to position relative to
        create_copy = data.get('create_copy', False)  # Whether to create a copy or reference the original
        
        if not text_section_id:
            return jsonify({'error': 'text_section_id is required'}), 400
        
        # Verify text section exists and user has access
        text_section = text_section_service.get_text_section(text_section_id)
        if not text_section:
            return jsonify({'error': 'Text section not found'}), 404
        
        # Allow access to text sections owned by the same user or shared sections
        if text_section.owner != user_email:
            return jsonify({'error': 'Access denied to text section'}), 403
        
        # Check if section is already in document to prevent duplicates
        existing_sections = [ds.section_id for ds in document.sections if ds.section_type == SectionType.TEXT]
        if text_section_id in existing_sections and not create_copy:
            return jsonify({'error': 'Text section already exists in document. Use create_copy=true to add a duplicate.'}), 400
        
        actual_section_id = text_section_id
        
        # Create copy if requested
        if create_copy:
            copied_section = text_section_service.duplicate_text_section(
                text_section_id,
                user_email,
                f"Copy of {text_section.title}"
            )
            if not copied_section:
                return jsonify({'error': 'Failed to create copy of text section'}), 500
            actual_section_id = copied_section.id
        
        # Calculate insertion position
        final_position = position
        if reference_section_id and insert_mode in ['before', 'after']:
            # Find position of reference section
            ref_position = None
            for i, doc_section in enumerate(document.sections):
                if (doc_section.section_type == SectionType.TEXT and 
                    doc_section.section_id == reference_section_id):
                    ref_position = i
                    break
            
            if ref_position is not None:
                if insert_mode == 'before':
                    final_position = ref_position
                elif insert_mode == 'after':
                    final_position = ref_position + 1
        
        success = document_service.add_text_section_to_document(
            document_id=document_id,
            text_section_id=actual_section_id,
            position=final_position
        )
        
        if success:
            # Get updated document to return current state
            updated_document, text_sections = document_service.get_document_with_text_sections(document_id)
            return jsonify({
                'success': True,
                'section_id': actual_section_id,
                'position': final_position,
                'created_copy': create_copy,
                'document': updated_document.to_dict() if updated_document else None
            })
        else:
            return jsonify({'error': 'Failed to add section to document'}), 500
            
    except Exception as e:
        logger.error(f"Error adding section to document: {e}")
        return jsonify({'error': str(e)}), 400

Parameters

Name Type Default Kind
document_id - - positional_or_keyword

Parameter Details

document_id: String identifier of the target document (from URL path). Must be owned by the authenticated user.

text_section_id: Required string in request JSON body. ID of the text section to add to the document.

position: Optional integer in request JSON body. Specifies absolute position for insertion (-1 means append at end). Default: -1.

insert_mode: Optional string in request JSON body. Defines positioning mode: 'before', 'after', or 'replace'. Used with reference_section_id. Default: 'after'.

reference_section_id: Optional string in request JSON body. ID of an existing section in the document to position relative to. Used with insert_mode.

create_copy: Optional boolean in request JSON body. If true, creates a duplicate of the text section instead of referencing the original. Allows adding the same section multiple times. Default: false.

Return Value

Returns a JSON response tuple with (response_object, status_code). Success (200): {'success': true, 'section_id': string (ID of added/copied section), 'position': integer (final position), 'created_copy': boolean, 'document': dict (updated document state)}. Error responses: 400 for validation errors or exceptions, 403 for access denied, 404 for document/section not found, 500 for operation failures.

Dependencies

  • flask
  • logging
  • models
  • services

Required Imports

from flask import request, jsonify
from models import SectionType
import logging

Conditional/Optional Imports

These imports are only needed under specific conditions:

from auth.azure_auth import require_auth, get_current_user

Condition: Required for authentication decorator and user identification

Required (conditional)
from services import DocumentService, TextSectionService

Condition: Required for document and text section operations

Required (conditional)

Usage Example

# Example API call to add a text section
import requests

# Add section at end of document
response = requests.post(
    'https://api.example.com/api/documents/doc123/sections/add',
    headers={'Authorization': 'Bearer <token>'},
    json={
        'text_section_id': 'section456',
        'position': -1
    }
)

# Add section after a reference section
response = requests.post(
    'https://api.example.com/api/documents/doc123/sections/add',
    headers={'Authorization': 'Bearer <token>'},
    json={
        'text_section_id': 'section456',
        'insert_mode': 'after',
        'reference_section_id': 'section789'
    }
)

# Create a copy and add it
response = requests.post(
    'https://api.example.com/api/documents/doc123/sections/add',
    headers={'Authorization': 'Bearer <token>'},
    json={
        'text_section_id': 'section456',
        'create_copy': True,
        'position': 2
    }
)

if response.status_code == 200:
    data = response.json()
    print(f"Section added at position {data['position']}")
    print(f"Copy created: {data['created_copy']}")

Best Practices

  • Always verify document ownership before allowing modifications to prevent unauthorized access
  • Use create_copy=true when adding the same section multiple times to avoid duplicate reference errors
  • Validate text_section_id exists and user has access before attempting to add to document
  • Handle positioning carefully: use reference_section_id with insert_mode for relative positioning, or position for absolute positioning
  • Check the returned 'created_copy' flag to know if a new section was created or existing one was referenced
  • Implement proper error handling for all service layer calls as they may fail due to database or business logic constraints
  • The endpoint returns the full updated document state, use this to refresh client-side document representation
  • Position -1 is a special value meaning 'append at end', useful for default behavior
  • The function prevents duplicate section additions by default; override with create_copy=true if intentional duplicates are needed

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_text_section_for_document 89.1% 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 add_existing_data_section_to_document 83.5% similar

    Flask API endpoint that adds an existing data section to a document after verifying ownership and access permissions for both the document and data section.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function add_data_section_to_document 83.0% similar

    Flask API endpoint that adds a data section to a document, either by creating a new data section or linking an existing one, with ownership verification.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_create_section 81.9% similar

    Flask API endpoint that creates a new section within a specified document, handling section positioning, type, level, title, and content with proper authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function create_text_section 80.2% similar

    Flask API endpoint that creates a new text section with specified title, type, level, and content for an authenticated user.

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