function get_document_v2
Retrieves comprehensive details of a controlled document by its UID, including optional version history, review cycles, and approval workflows.
/tf/active/vicechatdev/CDocs single class/controllers/document_controller.py
247 - 310
moderate
Purpose
This function serves as the primary retrieval mechanism for controlled documents in a document management system. It fetches a document's core metadata and can optionally include related data such as version history, review cycles, and approval workflows. The function is decorated with logging capabilities and handles various error scenarios including missing documents and approval retrieval failures. It's designed for use in document management workflows where complete document information needs to be accessed.
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:
# Use the approval_controller instead of direct model access
approval_result = get_document_approvals(document_uid)
result["approvals"] = approval_result.get("approval_workflows", [])
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 system. Must be a valid UID that exists in the database.
include_versions: Boolean flag (default: True) that determines whether to include the complete version history of the document in the response. When True, all document versions are retrieved and serialized into the result dictionary.
include_reviews: Boolean flag (default: True) that controls whether to include all review cycles associated with the document. When True, fetches ReviewCycle objects linked to this document and includes them in the response.
include_approvals: Boolean flag (default: True) that determines whether to include approval workflows for the document. When True, calls the approval_controller to retrieve approval data. Failures in approval retrieval are logged as warnings but don't fail the entire operation.
Return Value
Type: Dict[str, Any]
Returns a dictionary (Dict[str, Any]) containing the document's complete details. The base dictionary includes all fields from the document's to_dict() method. If a current version exists, it's added under 'current_version' key. Optional keys include: 'versions' (list of version dictionaries if include_versions=True), 'reviews' (list of review cycle dictionaries if include_reviews=True), and 'approvals' (list of approval workflow dictionaries if include_approvals=True). Returns empty list for approvals if retrieval fails.
Dependencies
logginguuidostempfiletypingdatetimeiopanelshutiltracebackjsonreCDocsconfig
Required Imports
from typing import Dict, Any
from CDocs.models.document import ControlledDocument
from CDocs.controllers import ResourceNotFoundError, BusinessRuleError
from CDocs.controllers.approval_controller import get_document_approvals
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
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 without related data
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 the boolean flags (include_versions, include_reviews, include_approvals) to optimize performance by only fetching needed data
- Be aware that approval retrieval failures are logged as warnings but don't fail the entire operation - check the 'approvals' key for empty list
- The function is decorated with @log_controller_action('get_document') so all calls are automatically logged
- Ensure the document_uid is valid before calling to avoid unnecessary database queries
- Consider the performance impact when setting all include_* flags to True for documents with extensive history
- The function re-raises ResourceNotFoundError specifically, so handle this separately from general BusinessRuleError
- Review cycles are imported lazily inside the function, so the ReviewCycle model is only loaded when include_reviews=True
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_document_v1 97.3% similar
-
function get_document 96.7% similar
-
function get_document_v3 84.4% similar
-
function get_document_v8 82.0% similar
-
function get_document_v4 79.3% similar