🔍 Code Extractor

function get_document_v1

Maturity: 66

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

File:
/tf/active/vicechatdev/CDocs/controllers/document_controller.py
Lines:
324 - 391
Complexity:
moderate

Purpose

This function serves as the primary retrieval endpoint for controlled documents in a document management system. It fetches a document's core metadata and optionally enriches it with related data such as version history, review cycles, and approval workflows. The function is designed for document management workflows where complete document context is needed, such as displaying document details in a UI, generating reports, or preparing documents for workflow transitions. It handles circular dependency issues by using direct model access for approvals and includes comprehensive error handling for missing resources.

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:
            try:
                # IMPORTANT: To avoid circular dependency, use direct model access instead
                # approval_result = get_document_approvals(document_uid)
                # result["approvals"] = approval_result.get("approval_workflows", [])
                
                # Direct model access
                approval_cycles = ApprovalCycle.get_approvals_for_document(document_uid)
                result["approvals"] = [cycle.to_dict() for cycle in approval_cycles]
            except Exception as e:
                logger.warning(f"Error retrieving approvals for document {document_uid}: {e}")
                result["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 the primary key used to locate the document in the database. Must be a valid UID that exists in the system, otherwise ResourceNotFoundError will be raised.

include_versions: Boolean flag (default: True) that determines whether to include the complete version history of the document in the response. When True, fetches all document versions and includes them in the 'versions' key of the returned dictionary. Set to False to improve performance when version history is not needed.

include_reviews: Boolean flag (default: True) that controls whether to include all review cycles associated with the document. When True, retrieves ReviewCycle objects for the document and includes them in the 'reviews' key. Set to False to reduce data payload when review information is not required.

include_approvals: Boolean flag (default: True) that determines whether to include approval workflow cycles for the document. When True, fetches ApprovalCycle objects and includes them in the 'approvals' key. Uses direct model access to avoid circular dependencies. Errors in approval retrieval are logged but don't fail the entire operation.

Return Value

Type: Dict[str, Any]

Returns a Dictionary with string keys and Any type values containing comprehensive document details. The base dictionary includes all fields from the ControlledDocument.to_dict() method. Additionally includes: 'current_version' (dict or None) with the current document version details; 'versions' (list of dicts) if include_versions=True, containing all version history; 'reviews' (list of dicts) if include_reviews=True, containing all review cycles; 'approvals' (list of dicts) if include_approvals=True, containing all approval workflows (empty list if retrieval fails). The structure allows for flexible consumption by UI components, APIs, or other system modules.

Dependencies

  • logging
  • typing
  • CDocs.models.document
  • CDocs.models.review
  • CDocs.models.approval
  • CDocs.controllers

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=True

Required (conditional)
from CDocs.models.approval import ApprovalCycle

Condition: only when include_approvals=True

Required (conditional)

Usage Example

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

try:
    # Get full document details with all related data
    document = get_document(
        document_uid='doc-12345-abcde',
        include_versions=True,
        include_reviews=True,
        include_approvals=True
    )
    
    print(f"Document Title: {document.get('title')}")
    print(f"Current Version: {document.get('current_version', {}).get('version_number')}")
    print(f"Number of versions: {len(document.get('versions', []))}")
    print(f"Number of reviews: {len(document.get('reviews', []))}")
    print(f"Number of approvals: {len(document.get('approvals', []))}")
    
    # Get minimal document details for performance
    minimal_doc = get_document(
        document_uid='doc-12345-abcde',
        include_versions=False,
        include_reviews=False,
        include_approvals=False
    )
    
except ResourceNotFoundError as e:
    print(f"Document not found: {e}")
except BusinessRuleError as e:
    print(f"Error retrieving document: {e}")

Best Practices

  • Always wrap calls in try-except blocks to handle ResourceNotFoundError and BusinessRuleError exceptions
  • Use include_* flags judiciously to optimize performance - only request data you actually need
  • The function handles approval retrieval errors gracefully by returning an empty list, but check logs for warnings if approvals are unexpectedly empty
  • Be aware that this function uses direct model access for approvals to avoid circular dependencies - do not refactor to use get_document_approvals() controller function
  • The log_controller_action decorator logs all invocations, so sensitive document UIDs will appear in logs
  • Current version is included by default even when include_versions=False, providing the most recent version without full history
  • Consider caching results if calling repeatedly for the same document UID within a short timeframe
  • Ensure proper database transaction management when using this function as part of larger workflows

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document 97.3% 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 get_document_v2 83.7% 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 81.5% 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.4% 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 76.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