🔍 Code Extractor

function get_user_pending_approvals

Maturity: 68

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.

File:
/tf/active/vicechatdev/CDocs/controllers/approval_controller.py
Lines:
1886 - 1958
Complexity:
moderate

Purpose

This function serves as a controller action to fetch and format approval assignments for a user in a document management system. It queries approval assignments based on status (pending/active/completed), applies optional date filters, and transforms the data into a UI-friendly format containing approval cycle, document, and approver information. It's designed for dashboard views where users need to see their pending approval tasks.

Source Code

def get_user_pending_approvals(
    user: DocUser,
    include_completed: bool = False,
    date_from: Optional[str] = None,
    date_to: Optional[str] = None,
    limit: int = 100,
    offset: int = 0
) -> Dict[str, Any]:
    """
    Get all pending approvals for a user.
    
    Args:
        user: User to get approvals for
        include_completed: Whether to include completed approvals
        date_from: Optional start date for filter (ISO format)
        date_to: Optional end date for filter (ISO format)
        limit: Maximum results to return
        offset: Number of results to skip
        
    Returns:
        Dictionary with user's pending approvals
    """
    try:
        # Determine status filter
        status_filter = ["PENDING", "ACTIVE"]
        if include_completed:
            status_filter.append("COMPLETED")
        
        # Get user's approver assignments
        assignments = get_user_assigned_approvals(
            user=user,
            status_filter=status_filter,
            limit=limit,
            offset=offset
        )
        
        # Extract assignments from result
        result_assignments = assignments.get('assignments', [])
        
        # Process for UI display
        approvals = []
        for assignment_data in result_assignments:
            # Check date filters if provided
            if date_from or date_to:
                # Get approval cycle dates
                approval_cycle = assignment_data.get('approval_cycle', {})
                initiated_date = approval_cycle.get('initiated_date')
                
                # Skip if before date_from
                if date_from and initiated_date and initiated_date < date_from:
                    continue
                    
                # Skip if after date_to
                if date_to and initiated_date and initiated_date > date_to:
                    continue
            
            # Prepare approval data for UI
            approvals.append({
                'approval': assignment_data.get('approval_cycle', {}),
                'document': assignment_data.get('document', {}),
                'approver': assignment_data.get('assignment', {})
            })
        
        return {
            'success': True,
            'count': len(approvals),
            'total': assignments.get('total', 0),
            'approvals': approvals
        }
        
    except Exception as e:
        logger.error(f"Error getting user pending approvals: {e}")
        raise BusinessRuleError(f"Failed to get pending approvals: {e}")

Parameters

Name Type Default Kind
user DocUser - positional_or_keyword
include_completed bool False positional_or_keyword
date_from Optional[str] None positional_or_keyword
date_to Optional[str] None positional_or_keyword
limit int 100 positional_or_keyword
offset int 0 positional_or_keyword

Parameter Details

user: DocUser object representing the user whose pending approvals should be retrieved. This is the approver, not the document owner.

include_completed: Boolean flag (default False) that determines whether to include completed approvals in the results. When True, returns both pending and completed approvals; when False, only returns pending and active approvals.

date_from: Optional ISO format date string (e.g., '2024-01-01') that filters approvals to only include those initiated on or after this date. If None, no lower date bound is applied.

date_to: Optional ISO format date string (e.g., '2024-12-31') that filters approvals to only include those initiated on or before this date. If None, no upper date bound is applied.

limit: Integer (default 100) specifying the maximum number of approval records to return. Used for pagination.

offset: Integer (default 0) specifying the number of records to skip before returning results. Used for pagination in conjunction with limit.

Return Value

Type: Dict[str, Any]

Returns a dictionary with keys: 'success' (bool indicating operation success), 'count' (int of approvals returned in current page), 'total' (int of total approvals matching criteria), and 'approvals' (list of dicts, each containing 'approval' (approval cycle data), 'document' (document metadata), and 'approver' (assignment details)). Raises BusinessRuleError on failure.

Dependencies

  • logging
  • uuid
  • os
  • typing
  • datetime
  • traceback
  • CDocs
  • CDocs.config
  • CDocs.models
  • CDocs.utils
  • CDocs.controllers

Required Imports

from typing import Dict, Any, Optional
from CDocs.models.user_extensions import DocUser
from CDocs.controllers import log_controller_action, BusinessRuleError
import logging

Usage Example

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

# Get a user object (assume user_id is known)
user = DocUser.query.get(user_id)

# Get pending approvals for the user
result = get_user_pending_approvals(
    user=user,
    include_completed=False,
    date_from='2024-01-01',
    date_to='2024-12-31',
    limit=50,
    offset=0
)

if result['success']:
    print(f"Found {result['count']} approvals out of {result['total']} total")
    for approval_item in result['approvals']:
        approval_cycle = approval_item['approval']
        document = approval_item['document']
        approver = approval_item['approver']
        print(f"Document: {document.get('title')}, Status: {approval_cycle.get('status')}")

Best Practices

  • Always handle the BusinessRuleError exception when calling this function to gracefully manage failures
  • Use pagination (limit and offset) when dealing with users who may have many approvals to avoid performance issues
  • Ensure date_from and date_to are in ISO format (YYYY-MM-DD) for proper date comparison
  • The function depends on get_user_assigned_approvals being available in the same scope - ensure this dependency is met
  • The decorator log_controller_action will automatically log this action, so ensure logging is properly configured
  • Date filtering is applied after initial query, so for large datasets, consider implementing date filtering at the database level for better performance
  • The returned 'count' may be less than 'total' due to pagination and date filtering applied post-query

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_user_pending_approvals_v1 84.7% 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_approvals 84.2% similar

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

    From: /tf/active/vicechatdev/CDocs/controllers/approval_controller_bis.py
  • function get_user_pending_reviews 84.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
  • function get_user_assigned_approvals_v1 77.3% 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_approval_statistics 66.8% similar

    Retrieves and calculates approval cycle statistics for a specified date range, including counts by status, average completion time, and overdue approvals.

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