🔍 Code Extractor

function move_section

Maturity: 53

Flask API endpoint that moves a section (text or data) up or down within a document's section order, with authentication and ownership verification.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
1597 - 1667
Complexity:
moderate

Purpose

This endpoint allows authenticated users to reorder sections within their documents by moving a section one position up or down. It verifies document and section ownership, validates the move direction, and updates the document structure accordingly. It handles both text sections and data sections, providing a unified interface for section reordering.

Source Code

def move_section(section_id):
    """Move a section to a new order position within a document"""
    try:
        user_email = get_current_user()
        data = request.get_json()
        direction = data.get('direction')  # 'up' or 'down'
        document_id = data.get('document_id')  # Need document context
        
        if not direction or not document_id:
            return jsonify({'error': 'direction and document_id are required'}), 400
        
        # 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
        
        # Verify section ownership - check both text and data sections
        section_obj = None
        section_type = None
        
        # Try text section first
        text_section = text_section_service.get_text_section(section_id)
        if text_section and text_section.owner == user_email:
            section_obj = text_section
            section_type = SectionType.TEXT
        else:
            # Try data section
            data_section = data_section_service.get_data_section(section_id)
            if data_section and data_section.owner == user_email:
                section_obj = data_section
                section_type = SectionType.DATA
        
        if not section_obj:
            return jsonify({'error': 'Section not found or access denied'}), 404
        
        # Find the document section that references this section
        doc_section = None
        current_position = -1
        for i, ds in enumerate(document.sections):
            if ds.section_id == section_id:
                doc_section = ds
                current_position = i
                break
        
        if doc_section is None:
            return jsonify({'error': 'Section not found in document'}), 404
        
        # Calculate new position
        if direction == 'up' and current_position > 0:
            new_position = current_position - 1
        elif direction == 'down' and current_position < len(document.sections) - 1:
            new_position = current_position + 1
        else:
            return jsonify({'error': 'Cannot move section in that direction'}), 400
        
        # Move the section
        success = document_service.move_section_in_document(
            document_id=document_id,
            doc_section_id=doc_section.id,
            new_position=new_position
        )
        
        if success:
            logger.info(f"Section moved: {section_id} to position {new_position}")
            return jsonify({'success': True})
        else:
            return jsonify({'error': 'Failed to move section'}), 500
            
    except Exception as e:
        logger.error(f"Error moving section: {e}")
        return jsonify({'error': str(e)}), 400

Parameters

Name Type Default Kind
section_id - - positional_or_keyword

Parameter Details

section_id: String identifier (path parameter) of the section to move. Can be either a text section ID or data section ID. The function will automatically determine the section type and verify ownership before proceeding with the move operation.

Return Value

Returns a Flask JSON response tuple. On success: ({'success': True}, 200). On error: ({'error': 'error message'}, status_code) where status_code is 400 for validation errors, 404 for not found/access denied, or 500 for server errors. The function logs the operation and returns appropriate HTTP status codes for different failure scenarios.

Dependencies

  • flask
  • logging
  • typing

Required Imports

from flask import request, jsonify
import logging
from models import SectionType
from services import TextSectionService, DataSectionService, DocumentService

Usage Example

# Client-side usage example (JavaScript fetch):

# Move a section up in the document
fetch('/api/sections/section-123/move', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>'
  },
  body: JSON.stringify({
    direction: 'up',
    document_id: 'doc-456'
  })
})
.then(response => response.json())
.then(data => {
  if (data.success) {
    console.log('Section moved successfully');
  } else {
    console.error('Error:', data.error);
  }
});

# Move a section down
fetch('/api/text-sections/section-789/move', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>'
  },
  body: JSON.stringify({
    direction: 'down',
    document_id: 'doc-456'
  })
})
.then(response => response.json())
.then(data => console.log(data));

Best Practices

  • Always include both 'direction' and 'document_id' in the request body to avoid 400 errors
  • Valid direction values are 'up' or 'down' only
  • The endpoint verifies ownership at multiple levels: document ownership and section ownership
  • Sections at the top cannot be moved up, and sections at the bottom cannot be moved down
  • The function handles both text sections and data sections transparently
  • The endpoint is accessible via two routes: /api/sections/<section_id>/move and /api/text-sections/<section_id>/move
  • Authentication is required via the require_auth decorator
  • The function uses the document_service.move_section_in_document method which should handle the actual database update
  • Error responses include descriptive messages to help diagnose issues
  • All operations are logged for audit and debugging purposes
  • The section must exist in the document's sections list to be moved

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_move_section 93.7% similar

    Flask API endpoint that moves a document section up or down in the section order, with authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function add_existing_section_to_document 76.1% 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
  • function update_text_section 75.8% similar

    Flask API endpoint that updates either the title or content of a text section, with ownership verification and version tracking.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_create_section 75.3% 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 api_update_section 74.9% similar

    REST API endpoint that updates an existing section within a document, allowing modification of title, content, type, and level properties with authentication and authorization checks.

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