🔍 Code Extractor

function close_review_cycle_v1

Maturity: 59

Closes an active review cycle by canceling it and optionally updating the associated document and document version status to a target status (default: DRAFT).

File:
/tf/active/vicechatdev/CDocs single class/controllers/review_controller.py
Lines:
1885 - 1915
Complexity:
moderate

Purpose

This function is used to terminate a review cycle prematurely or upon completion, ensuring proper cleanup of the review process. It cancels the review cycle, and if requested, updates both the document version and parent document status to a specified target status. This is typically used when a review needs to be aborted, completed early, or when reverting a document back to draft status after review.

Source Code

def close_review_cycle(user: DocUser, review_uid: str, update_document_status: bool = True, 
                     target_status: str = "DRAFT") -> Dict[str, Any]:
    """Close a review cycle and update document status."""
    try:
        # Get review cycle
        review_cycle = ReviewCycle(uid=review_uid)
        if not review_cycle:
            raise ResourceNotFoundError(f"Review cycle not found: {review_uid}")
            
        # Cancel review cycle
        if not review_cycle.cancel_cycle():
            raise BusinessRuleError("Failed to cancel review cycle")
            
        # Update document status if requested
        if update_document_status:
            document_version = review_cycle.document_version
            if document_version:
                document_version.status = target_status
                
                # Also update parent document status
                document = document_version.document
                if document:
                    document.status = target_status
                    
        return {"success": True, "message": "Review cycle closed successfully"}
            
    except (ResourceNotFoundError, BusinessRuleError) as e:
        return {"success": False, "message": str(e)}
    except Exception as e:
        logger.error(f"Error closing review cycle: {e}")
        return {"success": False, "message": f"Error: {str(e)}"}

Parameters

Name Type Default Kind
user DocUser - positional_or_keyword
review_uid str - positional_or_keyword
update_document_status bool True positional_or_keyword
target_status str 'DRAFT' positional_or_keyword

Parameter Details

user: DocUser object representing the authenticated user performing the action. Used for authorization and audit trail purposes.

review_uid: String containing the unique identifier (UID) of the review cycle to be closed. Must correspond to an existing ReviewCycle record.

update_document_status: Boolean flag (default: True) that determines whether to update the status of the associated document and document version. When True, both statuses are updated to target_status.

target_status: String specifying the status to set for the document and document version (default: 'DRAFT'). Common values include 'DRAFT', 'APPROVED', 'REJECTED', etc., depending on the document workflow configuration.

Return Value

Type: Dict[str, Any]

Returns a dictionary with keys 'success' (boolean) and 'message' (string). On success, returns {'success': True, 'message': 'Review cycle closed successfully'}. On failure, returns {'success': False, 'message': <error description>} with details about what went wrong (e.g., review cycle not found, cancellation failed, or unexpected errors).

Dependencies

  • CDocs
  • logging
  • datetime
  • typing

Required Imports

from typing import Dict, Any
from CDocs.models.review import ReviewCycle
from CDocs.models.user_extensions import DocUser
from CDocs.controllers import ResourceNotFoundError, BusinessRuleError
import logging

Usage Example

from CDocs.models.user_extensions import DocUser
from CDocs.controllers.review_controller import close_review_cycle

# Get the current user
user = DocUser.query.get(user_id)

# Close a review cycle and revert document to DRAFT
result = close_review_cycle(
    user=user,
    review_uid='rev_12345',
    update_document_status=True,
    target_status='DRAFT'
)

if result['success']:
    print('Review cycle closed successfully')
else:
    print(f"Error: {result['message']}")

# Close review cycle without updating document status
result = close_review_cycle(
    user=user,
    review_uid='rev_67890',
    update_document_status=False
)

if not result['success']:
    # Handle error
    log_error(result['message'])

Best Practices

  • Always check the 'success' field in the returned dictionary before proceeding with dependent operations
  • Use appropriate target_status values that align with your document workflow configuration
  • Consider the implications of setting update_document_status=False, as this may leave documents in an inconsistent state
  • Ensure the user has appropriate permissions before calling this function (the decorator log_controller_action suggests permission checking may occur)
  • Handle both ResourceNotFoundError and BusinessRuleError exceptions if calling without relying on the function's error handling
  • Be aware that this function updates both document_version and parent document status when update_document_status=True
  • The function uses soft error handling (returns error dict) rather than raising exceptions, so always validate the response
  • Consider transaction management if this function is part of a larger workflow to ensure atomicity

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function cancel_review_cycle_v1 81.0% similar

    Cancels an active review cycle for a controlled document by calling the underlying controller's cancel_cycle method and returns a success status with a message.

    From: /tf/active/vicechatdev/CDocs single class/controllers/review_controller.py
  • function close_review_cycle 79.8% similar

    Closes a completed review cycle for a controlled document, with optional document status update, permission validation, and stakeholder notifications.

    From: /tf/active/vicechatdev/CDocs/controllers/review_controller.py
  • function complete_review_v1 73.2% similar

    Completes a document review cycle by recording a decision and optional comments, then returns the operation status.

    From: /tf/active/vicechatdev/CDocs single class/controllers/review_controller.py
  • function close_approval_cycle 70.0% similar

    Closes a completed approval cycle and optionally updates the associated document's status, with permission checks, audit logging, and notifications.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller.py
  • function create_review_cycle_v1 69.7% similar

    Creates a review cycle for a specific document version, assigning reviewers with configurable approval requirements and workflow settings.

    From: /tf/active/vicechatdev/CDocs single class/controllers/review_controller.py
← Back to Browse