🔍 Code Extractor

function set_current_version_v1

Maturity: 67

Sets a specific version of a controlled document as the current/active version using Neo4j relationship management, with full audit logging and notifications.

File:
/tf/active/vicechatdev/CDocs single class/controllers/document_controller.py
Lines:
897 - 982
Complexity:
moderate

Purpose

This function manages document version control by designating a specific version as the current version of a controlled document. It validates the document and version existence, checks permissions, updates Neo4j relationships, logs the change in 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 workflow management.

Source Code

def set_current_version(
    user: DocUser,
    document_uid: str,
    version_uid: str
) -> Dict[str, Any]:
    """
    Set the current version of a document using Neo4j relationships.
    
    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 using relationship check
        is_current = document.is_current_version(version_uid)
        if is_current:
            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
        
        # Use document model method to set current version via relationship
        success = document.set_current_version(version)
        
        if not success:
            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 (document_uid) and exist in the database.

Return Value

Type: Dict[str, Any]

Returns a dictionary with keys: 'success' (bool indicating operation success), 'document_uid' (str echoing the document UID), 'version_uid' (str echoing the version UID), 'message' (str describing the outcome), and optionally 'previous_version' (dict 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
  • json
  • re
  • random
  • CDocs
  • document_auditor

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.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
from CDocs.controllers import ResourceNotFoundError, BusinessRuleError

# Assume user is authenticated and has proper permissions
user = DocUser.get_by_uid('user-123')
document_uid = 'doc-456'
version_uid = 'ver-789'

try:
    result = set_current_version(
        user=user,
        document_uid=document_uid,
        version_uid=version_uid
    )
    
    if result['success']:
        print(f"Successfully set version {result['version_uid']} as current")
        print(f"Message: {result['message']}")
        
        if result.get('previous_version'):
            prev = result['previous_version']
            print(f"Previous version: {prev['version_number']} (UID: {prev['uid']})")
    
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 this function (though decorator enforces this)
  • The function is decorated with @transaction, so database operations are atomic - no manual transaction management needed
  • Verify that version_uid belongs to the specified document_uid before calling to avoid validation errors
  • Check the 'previous_version' field in the response to track version history changes
  • The function automatically logs audit events and sends notifications - no additional logging needed
  • If the specified version is already current, the function returns success without making changes
  • Use the returned message field for user-facing feedback about the operation outcome
  • The function uses Neo4j relationships for version management - ensure database schema is properly initialized

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function set_current_version 98.3% similar

    Sets a specific version as the current version of a controlled document in a Neo4j-based document management system, with audit logging and notifications.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function set_current_version_v2 93.4% similar

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

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function create_document_version_v1 73.4% similar

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

    From: /tf/active/vicechatdev/CDocs copy/controllers/document_controller.py
  • function create_document_version_v2 72.5% 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 get_document_v3 70.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
← Back to Browse