🔍 Code Extractor

function get_document_versions

Maturity: 54

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

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
644 - 692
Complexity:
moderate

Purpose

This function fetches a document version from the database and enriches it with contextual information from its parent document. It's used in document management systems to display version history, compare versions, or retrieve specific historical states of controlled documents. The function validates that both the version and its parent document exist, and determines if the requested version is the current active version.

Source Code

def get_document_version(version_uid: str) -> Dict[str, Any]:
    """
    Get document version details by UID.
    
    Args:
        version_uid: UID of version to retrieve
        
    Returns:
        Dictionary with version details
        
    Raises:
        ResourceNotFoundError: If version not found
    """
    try:
        # Get version instance
        version = DocumentVersion(uid=version_uid)
        if not version:
            raise ResourceNotFoundError(f"Version not found: {version_uid}")
            
        # Get document for context
        document = ControlledDocument(uid=version.document_uid)
        if not document:
            logger.warning(f"Document not found for version {version_uid}")
            
        # Prepare result
        result = version.to_dict()
        
        # Add document context
        if document:
            result["document"] = {
                "uid": document.uid,
                "doc_number": document.doc_number,
                "title": document.title,
                "doc_type": document.doc_type,
                "department": document.department,
                "status": document.status
            }
            
            # Check if this is the current version
            result["is_current_version"] = document.is_current_version(version_uid)
            
        return result
        
    except ResourceNotFoundError:
        # Re-raise not found error
        raise
    except Exception as e:
        logger.error(f"Error retrieving version {version_uid}: {e}")
        raise BusinessRuleError(f"Failed to retrieve version: {e}")

Parameters

Name Type Default Kind
version_uid str - positional_or_keyword

Parameter Details

version_uid: Unique identifier (UID) string for the document version to retrieve. This should be a valid UID that exists in the DocumentVersion database. The function will raise ResourceNotFoundError if the UID doesn't correspond to an existing version.

Return Value

Type: Dict[str, Any]

Returns a dictionary containing the complete version details from version.to_dict() plus additional fields: 'document' (nested dict with uid, doc_number, title, doc_type, department, status of the parent document) and 'is_current_version' (boolean indicating if this version is the currently active version of the document). Returns Dict[str, Any] type.

Dependencies

  • logging
  • typing
  • CDocs.models.document
  • CDocs.controllers
  • CDocs.config

Required Imports

from typing import Dict, Any
from CDocs.models.document import DocumentVersion, ControlledDocument
from CDocs.controllers import ResourceNotFoundError, BusinessRuleError
import logging

Usage Example

from CDocs.controllers.document_controller import get_document_version
from CDocs.controllers import ResourceNotFoundError, BusinessRuleError

try:
    version_uid = 'abc123-version-uid'
    version_details = get_document_version(version_uid)
    
    print(f"Version UID: {version_details['uid']}")
    print(f"Document Title: {version_details['document']['title']}")
    print(f"Is Current: {version_details['is_current_version']}")
    
    if version_details['is_current_version']:
        print("This is the active version")
    else:
        print("This is a historical version")
        
except ResourceNotFoundError as e:
    print(f"Version not found: {e}")
except BusinessRuleError as e:
    print(f"Error retrieving version: {e}")

Best Practices

  • Always wrap calls in try-except blocks to handle ResourceNotFoundError and BusinessRuleError exceptions
  • The function is decorated with log_controller_action which logs all invocations for audit purposes
  • Check the 'is_current_version' field to determine if you're working with the active version
  • The function gracefully handles missing parent documents by logging a warning but still returning version data
  • Use the returned 'document' nested dictionary to access parent document context without making additional queries
  • Ensure proper database transaction management when using this function in larger workflows
  • The function re-raises ResourceNotFoundError specifically to allow callers to distinguish between not-found vs other errors

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_versions_v1 88.2% similar

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

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_document 82.8% similar

    Retrieves comprehensive details of a controlled document by its UID, with optional inclusion of version history, review cycles, and approval cycles.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function download_document_version 74.7% 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 set_current_version 73.9% 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 get_document_download_url 70.0% similar

    Retrieves a download URL for a controlled document, automatically selecting between editable (Word) and PDF formats based on document status or explicit request.

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