🔍 Code Extractor

function update_status_after_approval

Maturity: 62

Updates a controlled document's status after an approval workflow completes, determining the next status based on the approval decision and logging the change to the audit trail.

File:
/tf/active/vicechatdev/CDocs/controllers/document_controller.py
Lines:
432 - 484
Complexity:
moderate

Purpose

This function is part of a document management system's approval workflow. It automatically transitions a document to its next appropriate status (e.g., from IN_APPROVAL to APPROVED or PUBLISHED) after an approval cycle completes. It handles system-level status updates, logs lifecycle events for compliance, and returns detailed information about the status change. This is typically called by workflow automation rather than directly by users.

Source Code

def update_status_after_approval(
    document_uid: str,
    approval_uid: str,
    approval_decision: str
) -> Dict[str, Any]:
    """
    Update document status after an approval workflow completes.
    
    Args:
        document_uid: UID of the document
        approval_uid: UID of the completed approval
        approval_decision: Decision from the approval process
        
    Returns:
        Dictionary with update status
    """
    try:
        # Determine the next status
        next_status = get_status_after_approval(document_uid, approval_decision)
        
        # Get document
        document = ControlledDocument(uid=document_uid)
        if not document:
            raise ResourceNotFoundError(f"Document not found: {document_uid}")
        
        # Update document status
        document.status = next_status
        
        # Log the status change
        audit_trail.log_document_lifecycle_event(
            event_type="DOCUMENT_STATUS_CHANGED",
            user=None,  # System action
            document_uid=document_uid,
            details={
                "previous_status": document.status,
                "new_status": next_status,
                "reason": f"Approval workflow {approval_uid} completed with decision: {approval_decision}"
            }
        )
        
        return {
            "success": True,
            "document_uid": document_uid,
            "previous_status": document.status,
            "new_status": next_status,
            "message": f"Document status updated to {next_status} after approval"
        }
        
    except ResourceNotFoundError:
        raise
    except Exception as e:
        logger.error(f"Error updating document status after approval: {e}")
        raise BusinessRuleError(f"Failed to update document status: {e}")

Parameters

Name Type Default Kind
document_uid str - positional_or_keyword
approval_uid str - positional_or_keyword
approval_decision str - positional_or_keyword

Parameter Details

document_uid: Unique identifier (UID) string for the controlled document whose status needs to be updated. Must correspond to an existing ControlledDocument in the system.

approval_uid: Unique identifier (UID) string for the completed approval workflow/cycle. Used for audit trail logging to track which approval triggered the status change.

approval_decision: String representing the decision from the approval process (e.g., 'APPROVED', 'REJECTED', 'CONDITIONAL'). This value is used to determine the next appropriate document status via the get_status_after_approval helper function.

Return Value

Type: Dict[str, Any]

Returns a dictionary (Dict[str, Any]) containing: 'success' (bool) indicating operation success, 'document_uid' (str) echoing the input document UID, 'previous_status' (str) showing the document's status before update, 'new_status' (str) showing the updated status, and 'message' (str) with a human-readable description of the change. On error, raises ResourceNotFoundError if document doesn't exist or BusinessRuleError for other failures.

Dependencies

  • logging
  • uuid
  • os
  • tempfile
  • typing
  • datetime
  • io
  • panel
  • shutil
  • traceback
  • json
  • re
  • random
  • CDocs

Required Imports

from typing import Dict, Any
from CDocs.models.document import ControlledDocument
from CDocs.utils import audit_trail
from CDocs.controllers import log_controller_action, transaction, ResourceNotFoundError, BusinessRuleError
import logging

Usage Example

# Typically called by workflow automation after approval completes
from CDocs.controllers.document_controller import update_status_after_approval

# After an approval workflow completes with 'APPROVED' decision
try:
    result = update_status_after_approval(
        document_uid='doc-12345-abcde',
        approval_uid='approval-67890-fghij',
        approval_decision='APPROVED'
    )
    
    if result['success']:
        print(f"Document status updated from {result['previous_status']} to {result['new_status']}")
        print(f"Message: {result['message']}")
except ResourceNotFoundError as e:
    print(f"Document not found: {e}")
except BusinessRuleError as e:
    print(f"Failed to update status: {e}")

Best Practices

  • This function is decorated with @transaction, so it runs within a database transaction that will rollback on errors
  • The function is also decorated with @log_controller_action, which automatically logs the function call for audit purposes
  • Always handle ResourceNotFoundError and BusinessRuleError exceptions when calling this function
  • This is a system-level function (user=None in audit log) and should not be called directly by end users
  • The function relies on get_status_after_approval helper to determine the next status - ensure this function is properly implemented
  • The audit trail logs the previous status, but note there's a bug in the code: it logs document.status as previous_status after already updating it to next_status
  • Ensure the approval_decision parameter matches expected values that get_status_after_approval can handle
  • The function does not validate the approval_uid exists - it's only used for logging purposes

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_status_after_approval 86.8% similar

    Determines the next status for a controlled document based on an approval decision (APPROVED or REJECTED), transitioning documents through their lifecycle workflow.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function complete_approval_v1 79.5% similar

    Records a user's approval decision (APPROVED or REJECTED) for a document in an approval cycle, updating the approval status and document state accordingly.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller_bis.py
  • function update_document 76.6% similar

    Updates properties of a controlled document including title, description, status, owner, and metadata, with special handling for status transitions that require format conversions or publishing workflows.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function update_document_v1 75.5% similar

    Updates a controlled document's properties (title, description, status, owner, metadata) with validation, audit logging, and special handling for status transitions that require PDF publishing or training resets.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function update_approval_comment_v1 74.3% similar

    Updates an existing approval comment in a document approval workflow, allowing modification of comment text and status (e.g., marking as resolved) with permission checks and audit logging.

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