🔍 Code Extractor

function get_document_approval_cycles

Maturity: 58

Retrieves all approval cycles associated with a specific document, with optional filtering for active cycles only.

File:
/tf/active/vicechatdev/CDocs/controllers/approval_controller.py
Lines:
287 - 356
Complexity:
moderate

Purpose

This function fetches approval cycle information for a controlled document from a Neo4j database. It verifies the document exists, retrieves all associated approval cycles, optionally filters for active cycles (PENDING or IN_PROGRESS status), and returns comprehensive approval data including document metadata and current active approval if present. It's designed to avoid circular dependencies by using direct database queries for document verification.

Source Code

def get_document_approval_cycles(
    document_uid: str,
    include_active_only: bool = False
) -> Dict[str, Any]:
    """
    Get all approval cycles for a document.
    
    Args:
        document_uid: UID of document
        include_active_only: Whether to include only active approval cycles
        
    Returns:
        Dictionary with approval cycles
        
    Raises:
        ResourceNotFoundError: If document not found
    """
    try:
        # Check if document exists using direct database query to verify document exists
        # (rather than calling get_document which could create circular dependencies)
        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(f"Document not found: {document_uid}")
            
        document_info = {
            "uid": doc_result[0]["uid"],
            "doc_number": doc_result[0]["docNumber"],
            "title": doc_result[0]["title"]
        }
            
        # Get all approval cycles - direct model access
        from CDocs.models.approval import ApprovalCycle
        approval_cycles = ApprovalCycle.get_approvals_for_document(document_uid)
        
        # Filter by status if needed
        if include_active_only:
            approval_cycles = [rc for rc in approval_cycles if rc.status in ["PENDING", "IN_PROGRESS"]]
        
        # Convert to dictionaries
        result = {
            "document_uid": document_uid,
            "document_number": document_info["doc_number"],
            "document_title": document_info["title"],
            "approval_cycles": [rc.to_dict() for rc in approval_cycles]
        }
        
        # Add current active approval if exists
        active_approvals = [rc for rc in approval_cycles if rc.status in ["PENDING", "IN_PROGRESS"]]
        if active_approvals:
            result["active_approval"] = active_approvals[0].to_dict()
            
        return result
    
    except ResourceNotFoundError:
        # Re-raise not found error
        raise
    except Exception as e:
        logger.error(f"Error retrieving approval cycles for document {document_uid}: {e}")
        raise BusinessRuleError(f"Failed to retrieve approval cycles: {e}")

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. Must correspond to an existing document in the database, otherwise raises ResourceNotFoundError.

include_active_only: Boolean flag that when set to True, filters the returned approval cycles to only include those with status 'PENDING' or 'IN_PROGRESS'. Defaults to False, which returns all approval cycles regardless of status.

Return Value

Type: Dict[str, Any]

Returns a dictionary containing: 'document_uid' (str), 'document_number' (str), 'document_title' (str), 'approval_cycles' (list of dicts with approval cycle data), and optionally 'active_approval' (dict) if an active approval cycle exists. Each approval cycle dict contains full cycle information as defined by ApprovalCycle.to_dict() method.

Dependencies

  • CDocs.db.db_operations
  • CDocs.models.approval.ApprovalCycle
  • CDocs.controllers (for ResourceNotFoundError, BusinessRuleError)
  • logging
  • typing

Required Imports

from typing import Dict, Any
from CDocs.controllers import ResourceNotFoundError, BusinessRuleError, log_controller_action
import logging

Conditional/Optional Imports

These imports are only needed under specific conditions:

from CDocs.db import db_operations as db

Condition: imported inside function to verify document exists via direct database query

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

Condition: imported inside function to retrieve approval cycles for the document

Required (conditional)

Usage Example

from CDocs.controllers.approval_controller import get_document_approval_cycles
from CDocs.controllers import ResourceNotFoundError, BusinessRuleError

try:
    # Get all approval cycles for a document
    result = get_document_approval_cycles(
        document_uid='doc-12345-abcde',
        include_active_only=False
    )
    
    print(f"Document: {result['document_number']} - {result['document_title']}")
    print(f"Total approval cycles: {len(result['approval_cycles'])}")
    
    if 'active_approval' in result:
        print(f"Active approval status: {result['active_approval']['status']}")
    
    # Get only active approval cycles
    active_result = get_document_approval_cycles(
        document_uid='doc-12345-abcde',
        include_active_only=True
    )
    
    for cycle in active_result['approval_cycles']:
        print(f"Cycle UID: {cycle['uid']}, Status: {cycle['status']}")
        
except ResourceNotFoundError as e:
    print(f"Document not found: {e}")
except BusinessRuleError as e:
    print(f"Error retrieving approval cycles: {e}")

Best Practices

  • Always wrap calls in try-except blocks to handle ResourceNotFoundError and BusinessRuleError exceptions
  • Validate document_uid format before calling if possible to avoid unnecessary database queries
  • Use include_active_only=True when only current/pending approvals are needed to reduce data transfer
  • The function uses direct database queries to avoid circular dependencies - maintain this pattern if modifying
  • Check for 'active_approval' key existence in result before accessing to avoid KeyError
  • The function is decorated with log_controller_action for audit purposes - ensure logging is properly configured
  • Active approvals are defined as status 'PENDING' or 'IN_PROGRESS' - be aware of this business logic when interpreting results

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_approvals 97.0% similar

    Retrieves all approval cycles associated with a specific document, with optional filtering for active cycles only.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller_bis.py
  • function get_document_review_cycles 85.2% similar

    Retrieves all review cycles associated with a specific document, with optional filtering for active cycles only.

    From: /tf/active/vicechatdev/CDocs/controllers/review_controller.py
  • function get_approval_cycle 84.5% similar

    Retrieves detailed information about an approval cycle by its UID, with optional inclusion of comments and associated document details.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller.py
  • function get_approval 81.4% similar

    Retrieves a specific approval cycle by its unique identifier (UID) with optional inclusion of associated document details and approval comments.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller.py
  • function get_approval_cycle_v1 79.1% similar

    Retrieves an approval cycle by its unique identifier (UID) and optionally includes associated comments and document information.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller_bis.py
← Back to Browse