🔍 Code Extractor

function set_current_version

Maturity: 67

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

File:
/tf/active/vicechatdev/CDocs/controllers/document_controller.py
Lines:
1046 - 1132
Complexity:
moderate

Purpose

This function manages document version control by updating the current version relationship in Neo4j. It validates that both the document and version exist, checks if the version is already current, stores the previous version for audit purposes, updates the relationship, logs the change to the audit trail, and sends notifications. This is critical for document lifecycle management in regulated environments where version control and audit trails are required.

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="VERSION_UPDATED",
            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. Used for permission checks (via decorator) and audit logging. Must be a valid DocUser instance with appropriate MANAGE_VERSIONS permission.

document_uid: String containing the unique identifier (UID) of the controlled document whose current version is being updated. 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 previous current version, or None if no previous version existed). On error, raises an exception rather than returning an error dictionary.

Dependencies

  • logging
  • uuid
  • os
  • tempfile
  • typing
  • datetime
  • io
  • panel
  • shutil
  • traceback
  • json
  • re
  • random
  • CDocs

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 log_controller_action, require_permission, transaction, ResourceNotFoundError, 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='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['message']}")
        if result.get('previous_version'):
            print(f"Previous version was: {result['previous_version']['version_number']}")
except ResourceNotFoundError as e:
    print(f"Document or version not found: {e}")
except BusinessRuleError as e:
    print(f"Operation failed: {e}")
except PermissionError as e:
    print(f"Permission denied: {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 (enforced by decorator but good to verify in UI)
  • The function is decorated with @transaction, so database operations are atomic - no need for manual transaction management
  • Check the 'success' field in the returned dictionary before proceeding with dependent operations
  • The function automatically logs audit events and sends notifications - do not duplicate these actions
  • Verify that version_uid belongs to the specified document_uid before calling to avoid ResourceNotFoundError
  • The function is idempotent - calling it multiple times with the same version_uid will not cause errors
  • Previous version information is included in the response for rollback or audit purposes - store this if needed
  • The @log_controller_action decorator automatically logs the operation - additional logging is optional

Related Versions

Other versions of this component:

  • set_current_version

    From: /tf/active/vicechatdev/document_controller_backup.py | Maturity: N/A

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_v2 71.0% 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 create_document_v1 70.9% 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 create_document_v2 69.6% similar

    Creates a new version of a controlled document by generating version metadata, storing the file in FileCloud, updating the document's revision number, and creating an audit trail entry.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function get_document_v5 68.9% similar

    Retrieves all versions of a controlled document from a Neo4j graph database, including metadata about which version is current.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
← Back to Browse