🔍 Code Extractor

function get_approval

Maturity: 58

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

File:
/tf/active/vicechatdev/CDocs/controllers/approval_controller.py
Lines:
1793 - 1881
Complexity:
moderate

Purpose

This function is designed to fetch detailed information about a document approval cycle in a controlled document management system. It supports flexible data retrieval by allowing callers to optionally include related document metadata and approval comments. The function is intended for use in document management workflows where approval status tracking, approver assignments, and approval history are critical. It enforces permission checks and handles cases where the approval cycle doesn't exist or the user lacks access rights.

Source Code

def get_approval(approval_uid, include_document=False, include_comments=False):
    """
    Get a specific approval cycle by UID
    
    Parameters
    ----------
    approval_uid : str
        The UID of the approval cycle to retrieve
    include_document : bool, optional
        Whether to include the associated document details
    include_comments : bool, optional
        Whether to include approval comments
    
    Returns
    -------
    dict
        Approval cycle data with additional details based on include parameters
    
    Raises
    ------
    ResourceNotFoundError
        If the approval cycle is not found
    PermissionError
        If the user doesn't have permission to view the approval
    """
    # This is a placeholder implementation
    # In a real implementation, this would query the database
    
    # For now, return dummy data for testing
    approval_data = {
        'uid': approval_uid,
        'status': 'IN_PROGRESS',
        'approval_type': 'FORMAL',
        'initiated_date': '2025-01-15T14:30:00',
        'due_date': '2025-02-15T14:30:00',
        'initiated_by_name': 'John Smith',
        'instructions': 'Please approval the document carefully for technical accuracy and compliance with standards.',
        'approver_assignments': [
            {
                'approver_uid': '123456',
                'approver_name': 'Alice Johnson',
                'role': 'SME',
                'status': 'COMPLETED',
                'decision': 'APPROVED',
                'assigned_date': '2025-01-15T14:30:00',
                'decision_date': '2025-01-20T10:15:00'
            },
            {
                'approver_uid': '789012',
                'approver_name': 'Bob Williams',
                'role': 'COMPLIANCE',
                'status': 'PENDING',
                'assigned_date': '2025-01-15T14:30:00'
            }
        ]
    }
    
    # Add document data if requested
    if include_document:
        approval_data['document'] = {
            'uid': 'doc-12345',
            'doc_number': 'DOC-2025-001',
            'title': 'Sample Document for Approval',
            'revision': 'A',
            'doc_type': 'SOP',
            'department': 'Engineering',
            'status': 'IN_APPROVE'
        }
    
    # Add comments if requested
    if include_comments:
        approval_data['comments'] = [
            {
                'uid': 'comment-123',
                'user_name': 'Alice Johnson',
                'timestamp': '2025-01-20T10:00:00',
                'text': 'Section 3.2 needs more detail on safety procedures.',
                'section': 'Section 3.2'
            },
            {
                'uid': 'comment-456',
                'user_name': 'John Smith',
                'timestamp': '2025-01-18T09:30:00',
                'text': 'Overall the document is well structured, but there are a few areas that need clarification.',
                'section': 'General'
            }
        ]
    
    return approval_data

Parameters

Name Type Default Kind
approval_uid - - positional_or_keyword
include_document - False positional_or_keyword
include_comments - False positional_or_keyword

Parameter Details

approval_uid: A string representing the unique identifier of the approval cycle to retrieve. This is the primary key used to locate the specific approval cycle in the system. Expected format is a string UID (e.g., 'approval-12345').

include_document: A boolean flag (default: False) that determines whether to include the associated document's metadata in the response. When True, adds a 'document' key to the returned dictionary containing document details like UID, document number, title, revision, type, department, and status.

include_comments: A boolean flag (default: False) that determines whether to include approval comments in the response. When True, adds a 'comments' key to the returned dictionary containing a list of comment objects with user names, timestamps, text content, and associated sections.

Return Value

Returns a dictionary containing comprehensive approval cycle data. The base structure includes: 'uid' (approval cycle identifier), 'status' (current approval status like 'IN_PROGRESS', 'COMPLETED'), 'approval_type' (e.g., 'FORMAL'), 'initiated_date' and 'due_date' (ISO 8601 formatted timestamps), 'initiated_by_name' (name of person who started the approval), 'instructions' (approval instructions text), and 'approver_assignments' (list of approver objects with their status, decisions, and dates). If include_document is True, adds a 'document' dictionary with document metadata. If include_comments is True, adds a 'comments' list with comment objects. The function may raise ResourceNotFoundError if the approval cycle doesn't exist or PermissionError if the user lacks viewing permissions.

Dependencies

  • CDocs
  • typing
  • datetime
  • logging
  • uuid
  • os
  • traceback

Required Imports

from CDocs.controllers import ResourceNotFoundError
from CDocs.controllers import PermissionError

Conditional/Optional Imports

These imports are only needed under specific conditions:

from CDocs.models.approval import ApprovalCycle

Condition: Required for actual database implementation (not used in placeholder)

Optional
from CDocs.models.approval import ApprovalComment

Condition: Required for actual database implementation when retrieving comments

Optional
from CDocs.models.approval import ApproverAssignment

Condition: Required for actual database implementation when retrieving approver assignments

Optional
from CDocs.models.document import ControlledDocument

Condition: Required for actual database implementation when include_document is True

Optional
from CDocs import db

Condition: Required for actual database operations

Optional

Usage Example

from CDocs.controllers.approval_controller import get_approval
from CDocs.controllers import ResourceNotFoundError, PermissionError

try:
    # Get basic approval data
    approval = get_approval('approval-12345')
    print(f"Approval Status: {approval['status']}")
    print(f"Initiated by: {approval['initiated_by_name']}")
    
    # Get approval with document details
    approval_with_doc = get_approval(
        'approval-12345',
        include_document=True
    )
    print(f"Document: {approval_with_doc['document']['title']}")
    
    # Get approval with all details
    full_approval = get_approval(
        'approval-12345',
        include_document=True,
        include_comments=True
    )
    print(f"Number of comments: {len(full_approval['comments'])}")
    for approver in full_approval['approver_assignments']:
        print(f"{approver['approver_name']}: {approver['status']}")
        
except ResourceNotFoundError:
    print("Approval cycle not found")
except PermissionError:
    print("You don't have permission to view this approval")

Best Practices

  • Always wrap calls in try-except blocks to handle ResourceNotFoundError and PermissionError exceptions
  • Only request include_document and include_comments when needed to optimize performance and reduce data transfer
  • Ensure proper user authentication context is established before calling this function
  • Validate the approval_uid format before passing to the function to avoid unnecessary database queries
  • Consider caching approval data for frequently accessed approval cycles to reduce database load
  • Use the returned data structure carefully as it contains nested dictionaries and lists that may need validation
  • Be aware this is a placeholder implementation returning dummy data; actual implementation will query a database
  • Check the 'status' field to determine if the approval cycle is still active before performing operations
  • When displaying approver assignments, handle both 'PENDING' and 'COMPLETED' statuses appropriately

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_approval_cycle_v1 90.3% 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
  • function get_approval_cycle 87.8% 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_v1 83.9% similar

    A convenience wrapper function that retrieves approval cycle details by delegating to get_approval_cycle with the same parameters.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller_bis.py
  • function get_review 82.7% 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_approval_cycles 81.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.py
← Back to Browse