🔍 Code Extractor

function get_document_review_cycles

Maturity: 58

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

File:
/tf/active/vicechatdev/CDocs/controllers/review_controller.py
Lines:
308 - 377
Complexity:
moderate

Purpose

This function fetches review cycle information for a controlled document from a Neo4j graph database. It verifies the document exists, retrieves all associated review cycles, optionally filters for active cycles (PENDING or IN_PROGRESS status), and returns comprehensive information including document metadata and review 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_review_cycles(
    document_uid: str,
    include_active_only: bool = False
) -> Dict[str, Any]:
    """
    Get all review cycles for a document.
    
    Args:
        document_uid: UID of document
        include_active_only: Whether to include only active review cycles
        
    Returns:
        Dictionary with review 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 review cycles - direct model access
        from CDocs.models.review import ReviewCycle
        review_cycles = ReviewCycle.get_reviews_for_document(document_uid)
        
        # Filter by status if needed
        if include_active_only:
            review_cycles = [rc for rc in review_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"],
            "review_cycles": [rc.to_dict() for rc in review_cycles]
        }
        
        # Add current active review if exists
        active_reviews = [rc for rc in review_cycles if rc.status in ["PENDING", "IN_PROGRESS"]]
        if active_reviews:
            result["active_review"] = active_reviews[0].to_dict()
            
        return result
    
    except ResourceNotFoundError:
        # Re-raise not found error
        raise
    except Exception as e:
        logger.error(f"Error retrieving review cycles for document {document_uid}: {e}")
        raise BusinessRuleError(f"Failed to retrieve review 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 ResourceNotFoundError is raised.

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

Return Value

Type: Dict[str, Any]

Returns a dictionary containing: 'document_uid' (str), 'document_number' (str), 'document_title' (str), 'review_cycles' (list of dictionaries with review cycle data), and optionally 'active_review' (dictionary) if there are any active review cycles. Each review cycle dictionary contains fields as defined by ReviewCycle.to_dict() method.

Dependencies

  • CDocs.db.db_operations
  • CDocs.models.review.ReviewCycle
  • CDocs.controllers.ResourceNotFoundError
  • CDocs.controllers.BusinessRuleError
  • logging

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.review import ReviewCycle

Condition: imported inside function to access ReviewCycle model methods

Required (conditional)

Usage Example

# Get all review cycles for a document
result = get_document_review_cycles(
    document_uid='DOC-12345-UUID',
    include_active_only=False
)
print(f"Document: {result['document_title']}")
print(f"Total review cycles: {len(result['review_cycles'])}")

# Get only active review cycles
active_result = get_document_review_cycles(
    document_uid='DOC-12345-UUID',
    include_active_only=True
)
if 'active_review' in active_result:
    print(f"Active review status: {active_result['active_review']['status']}")

Best Practices

  • Always handle ResourceNotFoundError when the document_uid might not exist
  • Use include_active_only=True when you only need current/pending reviews to reduce data transfer
  • The function uses direct database queries to avoid circular dependencies - be aware of this pattern if modifying
  • The function is decorated with log_controller_action for audit trail purposes
  • Active reviews are defined as those with status 'PENDING' or 'IN_PROGRESS'
  • The function catches and re-raises ResourceNotFoundError but wraps other exceptions in BusinessRuleError
  • Review cycles are returned in the order provided by ReviewCycle.get_reviews_for_document method

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_review_cycle 86.0% similar

    Retrieves comprehensive information about a review cycle, including optional reviewer assignments, comments, and associated document details.

    From: /tf/active/vicechatdev/CDocs/controllers/review_controller.py
  • function get_document_approval_cycles 85.2% 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.py
  • function get_document_approvals 83.4% 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_review 81.6% similar

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

    From: /tf/active/vicechatdev/CDocs/controllers/review_controller.py
  • function get_document 72.7% 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
← Back to Browse