🔍 Code Extractor

function set_current_version

Maturity: 66

Sets a specific version of a controlled document as the current/active version, updating the document's currentVersionUID property and logging the change.

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
797 - 888
Complexity:
moderate

Purpose

This function manages document version control by allowing authorized users to designate which version of a document should be considered current. It validates that both the document and version exist, checks if the version is already current to avoid redundant updates, updates the database, logs the change to the audit trail, and sends notifications. This is critical for document management systems where tracking the active version of controlled documents is essential for compliance and operational purposes.

Source Code

def set_current_version(
    user: DocUser,
    document_uid: str,
    version_uid: str
) -> Dict[str, Any]:
    """
    Set the current version of a document.
    
    Args:
        user: User setting the current version
        document_uid: UID of document
        version_uid: UID of version to set as current
        
    Returns:
        Dictionary with update status
        
    Raises:
        ResourceNotFoundError: If document or version not found
        PermissionError: If user doesn't have permission
        BusinessRuleError: If operation is not allowed
    """
    try:
        # Get document instance
        document = ControlledDocument(uid=document_uid)
        if not document:
            raise ResourceNotFoundError(f"Document not found: {document_uid}")
            
        # Get version instance
        version = DocumentVersion(uid=version_uid)
        if not version or version.document_uid != document_uid:
            raise ResourceNotFoundError(f"Version not found for document: {version_uid}")
            
        # Check if already the current version - use direct property comparison
        # instead of calling a method that might not exist
        current_version_uid = getattr(document, 'currentVersionUID', None)
        if current_version_uid and current_version_uid == version_uid:
            return {
                "success": True,
                "document_uid": document_uid,
                "version_uid": version_uid,
                "message": f"Version {version.version_number} is already the current version"
            }
            
        # Store previous current version for audit
        previous_version = document.current_version
        previous_version_uid = previous_version.uid if previous_version else None
        previous_version_number = previous_version.version_number if previous_version else None
        
        # Set as current version - use direct database update instead of calling a method
        # that might not exist
        from CDocs.db import db_operations
        update_result = db_operations.update_node(
            document_uid, 
            {'currentVersionUID': version_uid}
        )
        
        if not update_result:
            raise BusinessRuleError("Failed to update document with new current version")
        
        # Log event
        audit_trail.log_document_lifecycle_event(
            event_type="DOCUMENT_CURRENT_VERSION_CHANGED",
            user=user,
            document_uid=document_uid,
            details={
                "previous_version_uid": previous_version_uid,
                "previous_version_number": previous_version_number,
                "new_version_uid": version_uid,
                "new_version_number": version.version_number
            }
        )
        
        # Notify about version change
        notifications.notify_document_update(document, "DOCUMENT_UPDATED")
        
        return {
            "success": True,
            "document_uid": document_uid,
            "version_uid": version_uid,
            "message": f"Version {version.version_number} set as current version",
            "previous_version": {
                "uid": previous_version_uid,
                "version_number": previous_version_number
            } if previous_version_uid else None
        }
        
    except (ResourceNotFoundError, PermissionError, BusinessRuleError) as e:
        # Re-raise known errors
        raise
    except Exception as e:
        logger.error(f"Error setting current version: {e}")
        raise BusinessRuleError(f"Failed to set current version: {e}")

Parameters

Name Type Default Kind
user DocUser - positional_or_keyword
document_uid str - positional_or_keyword
version_uid str - positional_or_keyword

Parameter Details

user: DocUser object representing the authenticated user performing the version change. Must have MANAGE_VERSIONS permission for the specified document. Used for audit logging and permission checks.

document_uid: String containing the unique identifier (UID) of the controlled document whose current version is being changed. Must correspond to an existing ControlledDocument in the database.

version_uid: String containing the unique identifier (UID) of the DocumentVersion to set as current. Must belong to the specified document (version.document_uid must match document_uid).

Return Value

Type: Dict[str, Any]

Returns a dictionary with keys: 'success' (boolean indicating operation success), 'document_uid' (echoed document UID), 'version_uid' (echoed version UID), 'message' (human-readable status message), and optionally 'previous_version' (dictionary with 'uid' and 'version_number' of the previously current version, or None if no previous version existed). On success, success=True; on failure, raises an exception rather than returning success=False.

Dependencies

  • logging
  • uuid
  • os
  • tempfile
  • typing
  • datetime
  • io
  • panel
  • shutil
  • traceback
  • CDocs
  • config

Required Imports

from typing import Dict, Any
from CDocs.models.document import ControlledDocument, DocumentVersion
from CDocs.models.user_extensions import DocUser
from CDocs.utils import audit_trail, notifications
from CDocs.db import db_operations
from CDocs.controllers import require_permission, log_controller_action, transaction
from CDocs.controllers import ResourceNotFoundError, PermissionError, BusinessRuleError
import logging

Usage Example

from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import set_current_version

# Assume user, document_uid, and version_uid are already obtained
user = DocUser(uid='user123')
document_uid = 'doc-abc-123'
version_uid = 'ver-xyz-456'

try:
    result = set_current_version(
        user=user,
        document_uid=document_uid,
        version_uid=version_uid
    )
    
    if result['success']:
        print(f"Success: {result['message']}")
        if result.get('previous_version'):
            print(f"Previous version: {result['previous_version']['version_number']}")
except ResourceNotFoundError as e:
    print(f"Document or version not found: {e}")
except PermissionError as e:
    print(f"Permission denied: {e}")
except BusinessRuleError as e:
    print(f"Business rule violation: {e}")

Best Practices

  • Always wrap calls in try-except blocks to handle ResourceNotFoundError, PermissionError, and BusinessRuleError exceptions
  • Ensure the user has MANAGE_VERSIONS permission before calling (though decorator handles this)
  • Verify that version_uid belongs to the specified document_uid to avoid cross-document version assignment
  • The function is transactional, so database changes will be rolled back on error
  • Check the 'success' field in the returned dictionary before proceeding with dependent operations
  • The function handles idempotency - setting an already-current version returns success without making changes
  • Audit trail entries are automatically created for compliance tracking
  • Notifications are sent automatically to relevant stakeholders when version changes occur
  • Use the returned 'previous_version' data for rollback scenarios or user confirmation dialogs

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_versions 73.9% similar

    Retrieves detailed information about a specific document version by its UID, including associated document context and version status.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function download_document_version 69.1% similar

    Downloads a specific version of a controlled document from FileCloud storage, with optional audit trail and watermark inclusion, and logs the download event.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_document_versions_v1 67.0% similar

    Retrieves all versions of a document from the database given its unique identifier (UID).

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function create_document_v1 66.3% similar

    Creates a new version of an existing document in a document management system, storing the file in FileCloud and tracking version metadata in Neo4j graph database.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function update_document 66.1% similar

    Updates properties of a controlled document including title, description, status, owner, and metadata, with special handling for status transitions that require format conversions or publishing workflows.

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