function get_document_approvals
Retrieves all approval cycles associated with a specific document, with optional filtering for active cycles only.
/tf/active/vicechatdev/CDocs/controllers/approval_controller_bis.py
263 - 329
moderate
Purpose
This function fetches approval cycle information for a controlled document from a Neo4j graph database. It verifies the document exists, retrieves associated approval cycles, optionally filters for active cycles, and returns structured data including document metadata and approval cycle details. It's designed to avoid circular dependencies by using direct database queries instead of calling other controller functions.
Source Code
def get_document_approvals(
document_uid: str,
include_active_only: bool = False
) -> Dict[str, Any]:
"""
Get all approval cycles for a document.
Args:
document_uid: UID of the document
include_active_only: Whether to include only active approval cycles
Returns:
Dictionary with success flag and list of approval cycles
"""
try:
# IMPORTANT: Remove this call to break the circular dependency
# document = get_document(document_uid=document_uid)
# Instead, use direct database query to verify document exists
from CDocs.db import db_operations as db
# Check if document exists without calling get_document
doc_result = db.run_query(
"""
MATCH (d:ControlledDocument {UID: $doc_uid})
RETURN d.UID as uid, d.docNumber as docNumber, d.title as title
LIMIT 1
""",
{"doc_uid": document_uid}
)
if not doc_result or len(doc_result) == 0:
raise ResourceNotFoundError("Document not found")
document = {
"uid": doc_result[0]["uid"],
"docNumber": doc_result[0]["docNumber"],
"title": doc_result[0]["title"]
}
# Get approval cycles
approval_cycles = ApprovalCycle.get_approvals_for_document(document_uid)
# Filter active only if requested
if include_active_only:
approval_cycles = [cycle for cycle in approval_cycles if cycle.is_active]
# Convert to dictionaries
result = []
for cycle in approval_cycles:
cycle_dict = cycle.to_dict()
result.append(cycle_dict)
return {
"success": True,
"approvals": result,
"document_uid": document_uid,
"document_number": document.get("docNumber")
}
except ResourceNotFoundError as e:
logger.warning(f"Error getting document approvals: {e}")
return {"success": False, "message": str(e), "approvals": []}
except Exception as e:
logger.error(f"Unexpected error getting document approvals: {e}")
return {"success": False, "message": "An unexpected error occurred", "approvals": []}
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
document_uid |
str | - | positional_or_keyword |
include_active_only |
bool | False | positional_or_keyword |
Parameter Details
document_uid: Unique identifier (UID) string for the controlled document. This is used to query the Neo4j database for the document and its associated approval cycles. Must be a valid UID that exists in the database.
include_active_only: Boolean flag that determines whether to return all approval cycles or only active ones. When True, filters the results to include only approval cycles where is_active is True. Defaults to False, returning all approval cycles regardless of status.
Return Value
Type: Dict[str, Any]
Returns a dictionary with the following structure: {'success': bool, 'approvals': list, 'document_uid': str, 'document_number': str, 'message': str (optional)}. On success, 'success' is True, 'approvals' contains a list of approval cycle dictionaries (converted via to_dict()), 'document_uid' is the input UID, and 'document_number' is the document's number. On failure, 'success' is False, 'message' contains the error description, and 'approvals' is an empty list.
Dependencies
CDocstypingdatetimeloggingtraceback
Required Imports
from typing import Dict, Any
from CDocs.db import db_operations as db
from CDocs.models.approval import ApprovalCycle
from CDocs.controllers import log_controller_action, ResourceNotFoundError
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.db import db_operations as db
Condition: Required for direct database queries to verify document existence
Required (conditional)from CDocs.models.approval import ApprovalCycle
Condition: Required to call get_approvals_for_document and convert cycles to dictionaries
Required (conditional)from CDocs.controllers import ResourceNotFoundError
Condition: Required for exception handling when document is not found
Required (conditional)Usage Example
# Get all approval cycles for a document
result = get_document_approvals(
document_uid='DOC-12345-UID',
include_active_only=False
)
if result['success']:
print(f"Found {len(result['approvals'])} approval cycles")
for approval in result['approvals']:
print(f"Approval cycle: {approval}")
print(f"Document number: {result['document_number']}")
else:
print(f"Error: {result['message']}")
# Get only active approval cycles
active_result = get_document_approvals(
document_uid='DOC-12345-UID',
include_active_only=True
)
if active_result['success']:
print(f"Found {len(active_result['approvals'])} active approval cycles")
Best Practices
- This function intentionally avoids calling get_document() to prevent circular dependencies - use direct database queries when needed
- Always check the 'success' field in the returned dictionary before processing the 'approvals' list
- The function returns an empty approvals list on error rather than raising exceptions, making it safe for use in API endpoints
- Use include_active_only=True when you only need current/ongoing approval cycles to reduce data transfer
- The function logs warnings for ResourceNotFoundError and errors for unexpected exceptions - ensure logging is properly configured
- The decorator log_controller_action('get_document_approvals') should be applied to this function for audit trail purposes
- Ensure the ApprovalCycle model's to_dict() method returns all necessary fields for your use case
- The document_uid must be a valid UID string - validate input before calling this function in production code
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_document_approval_cycles 97.0% similar
-
function get_approval_cycle 86.1% similar
-
function get_document_review_cycles 83.4% similar
-
function get_approval 80.5% similar
-
function get_approval_cycle_v1 80.2% similar