🔍 Code Extractor

function get_document

Maturity: 68

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

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
244 - 303
Complexity:
moderate

Purpose

This function serves as the primary retrieval mechanism for controlled documents in a document management system. It fetches a document by its unique identifier and optionally enriches the response with related data including version history, review cycles, and approval workflows. The function is decorated with logging capabilities and is designed to support document control workflows in regulated environments where tracking document lifecycle, reviews, and approvals is critical.

Source Code

def get_document(
    document_uid: str,
    include_versions: bool = True,
    include_reviews: bool = True,
    include_approvals: bool = True
) -> Dict[str, Any]:
    """
    Get document details by UID.
    
    Args:
        document_uid: UID of document to retrieve
        include_versions: Whether to include version history
        include_reviews: Whether to include review cycles
        include_approvals: Whether to include approval cycles
        
    Returns:
        Dictionary with document details
        
    Raises:
        ResourceNotFoundError: If document not found
    """
    try:
        # Get document instance
        document = ControlledDocument(uid=document_uid)
        if not document:
            raise ResourceNotFoundError(f"Document not found: {document_uid}")
        
        # Convert to dictionary
        result = document.to_dict()
        
        # Get current version if any
        current_version = document.current_version
        if current_version:
            result["current_version"] = current_version.to_dict()
        
        # Add version history if requested
        if include_versions:
            versions = document.get_all_versions()
            result["versions"] = [v.to_dict() for v in versions]
        
        # Add review cycles if requested
        if include_reviews:
            from CDocs.models.review import ReviewCycle
            reviews = ReviewCycle.get_reviews_for_document(document_uid)
            result["reviews"] = [r.to_dict() for r in reviews]
        
        # Add approval cycles if requested
        if include_approvals:
            from CDocs.models.approval import Approval
            approvals = Approval.get_approvals_for_document(document_uid)
            result["approvals"] = [a.to_dict() for a in approvals]
        
        return result
        
    except ResourceNotFoundError:
        # Re-raise not found error
        raise
    except Exception as e:
        logger.error(f"Error retrieving document {document_uid}: {e}")
        raise BusinessRuleError(f"Failed to retrieve document: {e}")

Parameters

Name Type Default Kind
document_uid str - positional_or_keyword
include_versions bool True positional_or_keyword
include_reviews bool True positional_or_keyword
include_approvals bool True positional_or_keyword

Parameter Details

document_uid: Unique identifier (UID) string for the document to retrieve. This is a required parameter that must correspond to an existing document in the system. Expected to be a string, likely a UUID format.

include_versions: Boolean flag (default: True) that determines whether to include the complete version history of the document in the response. When True, all historical versions are fetched and included in the 'versions' key of the returned dictionary.

include_reviews: Boolean flag (default: True) that controls whether to fetch and include all review cycles associated with the document. When True, review cycle information is retrieved from the ReviewCycle model and added to the 'reviews' key.

include_approvals: Boolean flag (default: True) that determines whether to include approval cycle information in the response. When True, all approval workflows for the document are fetched from the Approval model and included in the 'approvals' key.

Return Value

Type: Dict[str, Any]

Returns a Dictionary with string keys and Any type values (Dict[str, Any]) containing comprehensive document details. The base dictionary includes all fields from the ControlledDocument.to_dict() method. If a current version exists, it's added under 'current_version' key. Optionally includes 'versions' (list of version dictionaries), 'reviews' (list of review cycle dictionaries), and 'approvals' (list of approval dictionaries) based on the boolean parameters. Each nested object is converted to a dictionary via its respective to_dict() method.

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

Conditional/Optional Imports

These imports are only needed under specific conditions:

from CDocs.models.review import ReviewCycle

Condition: only when include_reviews parameter is True

Optional
from CDocs.models.approval import Approval

Condition: only when include_approvals parameter is True

Optional

Usage Example

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

# Basic usage - get document with all related data
try:
    document_data = get_document(
        document_uid='550e8400-e29b-41d4-a716-446655440000'
    )
    print(f"Document title: {document_data.get('title')}")
    print(f"Number of versions: {len(document_data.get('versions', []))}")
    print(f"Number of reviews: {len(document_data.get('reviews', []))}")
except ResourceNotFoundError as e:
    print(f"Document not found: {e}")
except BusinessRuleError as e:
    print(f"Error retrieving document: {e}")

# Get document without version history
document_minimal = get_document(
    document_uid='550e8400-e29b-41d4-a716-446655440000',
    include_versions=False,
    include_reviews=False,
    include_approvals=False
)

# Get document with only reviews
document_with_reviews = get_document(
    document_uid='550e8400-e29b-41d4-a716-446655440000',
    include_versions=False,
    include_reviews=True,
    include_approvals=False
)

Best Practices

  • Always wrap calls in try-except blocks to handle ResourceNotFoundError and BusinessRuleError exceptions
  • Use the boolean parameters to optimize performance by only fetching needed related data (versions, reviews, approvals)
  • The function is decorated with @log_controller_action which automatically logs the operation - ensure logging is properly configured
  • Document UIDs should be validated before calling this function to ensure they are in the correct format
  • Be aware that including versions, reviews, and approvals can significantly increase response size and query time for documents with extensive history
  • The function re-raises ResourceNotFoundError specifically, allowing calling code to distinguish between 'not found' and other errors
  • All other exceptions are caught and wrapped in BusinessRuleError with the original error message
  • The current_version is always included if it exists, regardless of the include_versions parameter
  • Lazy imports of ReviewCycle and Approval models occur only when needed, reducing initial load time

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_v1 97.3% similar

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

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function get_document_v2 82.1% 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 get_document_v6 80.8% 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_metadata_from_filecloud 77.0% similar

    Retrieves metadata for a specific document (and optionally a specific version) from FileCloud storage system.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function get_document_v5 75.6% 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