🔍 Code Extractor

function get_user_assigned_approvals

Maturity: 67

Retrieves and paginates approval cycles assigned to a specific user, with optional filtering by status and completion state.

File:
/tf/active/vicechatdev/CDocs/controllers/approval_controller_bis.py
Lines:
332 - 416
Complexity:
moderate

Purpose

This function fetches all approval cycles where a user is assigned as an approver. It supports filtering by approval status, optionally includes completed approvals, and provides pagination. The function enriches approval cycle data with user-specific assignment details and associated document information, returning a structured response with success status and metadata.

Source Code

def get_user_assigned_approvals(
    user: DocUser,
    status_filter: Optional[Union[str, List[str]]] = None,
    include_completed: bool = False,
    limit: int = 100,
    offset: int = 0
) -> Dict[str, Any]:
    """
    Get approvals assigned to a user.
    
    Args:
        user: The user to get approvals for
        status_filter: Filter by approval status
        include_completed: Whether to include completed approvals
        limit: Maximum number of approvals to return
        offset: Offset for pagination
        
    Returns:
        Dictionary with success flag and list of approvals
    """
    try:
        # Convert status filter to list if it's a string
        if status_filter and isinstance(status_filter, str):
            status_filter = [status_filter]
            
        # Get approver assignments for the user
        assignments = ApproverAssignment.get_assignments_for_approver(user.uid, include_completed=include_completed)
        
        # Group by approval cycle
        approval_cycles = {}
        for assignment in assignments:
            cycle_uid = assignment.approval_cycle_uid
            if cycle_uid not in approval_cycles:
                cycle = ApprovalCycle(uid=cycle_uid)
                if cycle and (not status_filter or cycle.status in status_filter):
                    approval_cycles[cycle_uid] = cycle
                    
        # Convert cycles to dictionaries with assignment info
        result = []
        for cycle_uid, cycle in approval_cycles.items():
            cycle_dict = cycle.to_dict()
            
            # Add user's specific assignment
            user_assignment = cycle.get_approver_assignment(user.uid)
            if user_assignment:
                cycle_dict["my_assignment"] = user_assignment.to_dict()
                
                # Get document info
                document_uid = cycle.document_uid
                if document_uid:
                    from CDocs.controllers.document_controller import get_document
                    document = get_document(document_uid=document_uid)
                    if document:
                        cycle_dict["document"] = {
                            "uid": document_uid,
                            "docNumber": document.get("docNumber"),
                            "title": document.get("title"),
                            "status": document.get("status")
                        }
                        
                result.append(cycle_dict)
                
        # Sort by due date (most urgent first)
        result.sort(key=lambda x: x.get("dueDate", "9999-12-31"))
        
        # Apply pagination
        paginated_result = result[offset:offset + limit]
        
        return {
            "success": True,
            "approvals": paginated_result,
            "total": len(result),
            "limit": limit,
            "offset": offset
        }
        
    except Exception as e:
        logger.error(f"Error getting user assigned approvals: {e}")
        import traceback
        logger.error(traceback.format_exc())
        return {
            "success": False, 
            "message": "An unexpected error occurred",
            "approvals": []
        }

Parameters

Name Type Default Kind
user DocUser - positional_or_keyword
status_filter Optional[Union[str, List[str]]] None positional_or_keyword
include_completed bool False positional_or_keyword
limit int 100 positional_or_keyword
offset int 0 positional_or_keyword

Parameter Details

user: A DocUser object representing the user whose assigned approvals should be retrieved. Must be a valid user instance with a uid attribute.

status_filter: Optional filter to limit results by approval cycle status. Can be a single status string (e.g., 'pending') or a list of status strings (e.g., ['pending', 'in_progress']). If None, no status filtering is applied.

include_completed: Boolean flag indicating whether to include completed approval cycles in the results. Defaults to False, meaning only active/incomplete approvals are returned.

limit: Maximum number of approval cycles to return in the response. Used for pagination. Defaults to 100. Must be a positive integer.

offset: Number of approval cycles to skip before returning results. Used for pagination to retrieve subsequent pages. Defaults to 0.

Return Value

Type: Dict[str, Any]

Returns a dictionary with the following structure: {'success': bool, 'approvals': list, 'total': int, 'limit': int, 'offset': int, 'message': str (only on error)}. On success, 'approvals' contains a list of approval cycle dictionaries enriched with 'my_assignment' (user's specific assignment details) and 'document' (document metadata including uid, docNumber, title, status). Results are sorted by due date (most urgent first) and paginated. On error, returns success=False with an error message and empty approvals list.

Dependencies

  • typing
  • datetime
  • logging
  • traceback
  • CDocs

Required Imports

from typing import Dict, List, Any, Optional, Union
from CDocs.models.user_extensions import DocUser
from CDocs.models.approval import ApprovalCycle, ApproverAssignment
import logging
import traceback

Conditional/Optional Imports

These imports are only needed under specific conditions:

from CDocs.controllers.document_controller import get_document

Condition: imported inside the function when document information needs to be retrieved for approval cycles with associated documents

Required (conditional)

Usage Example

from CDocs.models.user_extensions import DocUser
from your_module import get_user_assigned_approvals

# Get a user instance
user = DocUser(uid='user123')

# Get all pending approvals for the user
result = get_user_assigned_approvals(
    user=user,
    status_filter='pending',
    include_completed=False,
    limit=20,
    offset=0
)

if result['success']:
    print(f"Found {result['total']} approvals")
    for approval in result['approvals']:
        print(f"Document: {approval['document']['title']}")
        print(f"Due: {approval.get('dueDate')}")
        print(f"My status: {approval['my_assignment']['status']}")
else:
    print(f"Error: {result['message']}")

# Get approvals with multiple status filters
result = get_user_assigned_approvals(
    user=user,
    status_filter=['pending', 'in_progress'],
    include_completed=True,
    limit=50,
    offset=0
)

Best Practices

  • Always check the 'success' field in the returned dictionary before processing the 'approvals' list
  • Handle pagination properly by tracking 'total', 'limit', and 'offset' values for multi-page results
  • The function converts single string status_filter to a list internally, but passing a list is more explicit for multiple statuses
  • Results are sorted by due date automatically, with missing due dates treated as far future (9999-12-31)
  • The function catches all exceptions and returns a safe error response, but logs detailed error information for debugging
  • Consider the performance impact when setting high limit values or when users have many assigned approvals
  • The function performs lazy loading of document information, which may result in multiple database queries
  • Ensure the user object has a valid uid before calling this function to avoid query errors

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_user_pending_approvals 84.2% similar

    Retrieves all pending approval assignments for a specific user, with optional filtering by completion status and date range, returning structured approval data for UI display.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller.py
  • function get_user_assigned_approvals_v1 83.7% similar

    Retrieves all approval assignments for a specific user with optional filtering by status, including associated approval cycles, documents, and version information.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller.py
  • function get_user_pending_approvals_v1 80.1% similar

    Retrieves a filtered list of approval cycles pending action from a specific user, ensuring the user has current approval authority for each returned item.

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller_bis.py
  • function get_user_assigned_reviews 69.9% similar

    Retrieves all review assignments for a specific user with optional filtering by status, including associated review cycle, document, and version details.

    From: /tf/active/vicechatdev/CDocs/controllers/review_controller.py
  • function get_user_pending_reviews 69.2% similar

    Retrieves all pending (and optionally completed) document reviews assigned to a specific user, with support for date filtering and pagination.

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