function create_approval_panel
Factory function that creates and initializes an ApprovalPanel instance with error handling, supporting both standalone and embedded modes for document approval management.
/tf/active/vicechatdev/CDocs/ui/approval_panel_bis.py
1901 - 1948
moderate
Purpose
This function serves as a factory to instantiate an ApprovalPanel component for managing document approvals in a controlled documents system. It handles initialization in both standalone mode (with its own Bootstrap template) and embedded mode (as part of a parent application). The function includes comprehensive error handling that returns a minimal functional panel if initialization fails, ensuring the application remains operational. It automatically detects embedded mode, sets up user context from parent applications, and triggers initial data loading.
Source Code
def create_approval_panel(session_manager=None, parent_app=None, embedded=False):
"""Create and initialize the approval panel"""
try:
# Create template for approval panel (only used in standalone mode)
template = pn.template.BootstrapTemplate(
site="Controlled Documents",
title="Approval Management",
sidebar_width=300,
)
# Create and initialize panel
panel = ApprovalPanel(
template=template,
session_manager=session_manager,
parent_app=parent_app,
embedded=embedded or parent_app is not None # Auto-detect embedded mode
)
# If parent_app has a current_user, set it directly
if parent_app and hasattr(parent_app, 'current_user') and parent_app.current_user:
panel.user = parent_app.current_user
# Reload data if method exists
if hasattr(panel, '_load_pending_approvals'):
panel._load_pending_approvals()
return panel # Return the panel instance, not the template
except Exception as e:
import logging
logger = logging.getLogger('CDocs.ui.approval_panel')
logger.error(f"Error creating approval panel: {e}")
import traceback
logger.error(traceback.format_exc())
# Return a minimal functioning panel
minimal_panel = pn.Column(
pn.pane.Markdown("# Approval Management"),
pn.pane.Markdown(f"**Error loading approval panel:** {str(e)}")
)
minimal_panel.main_content = minimal_panel
# Add minimal set_user method to avoid errors
def minimal_set_user(obj, user):
obj.user = user
import types
minimal_panel.set_user = types.MethodType(minimal_set_user, minimal_panel)
return minimal_panel
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_manager |
- | None | positional_or_keyword |
parent_app |
- | None | positional_or_keyword |
embedded |
- | False | positional_or_keyword |
Parameter Details
session_manager: Optional SessionManager instance for handling user authentication and session state. If None, the panel may operate with limited functionality or rely on parent_app for session management. Expected type: SessionManager or None.
parent_app: Optional reference to a parent application object that contains this panel. Used to access shared resources like current_user and to determine if the panel should run in embedded mode. Expected type: Application object with 'current_user' attribute or None.
embedded: Boolean flag indicating whether the panel should run in embedded mode (as part of a larger application) or standalone mode (with its own template). Defaults to False. Auto-detected as True if parent_app is provided. Expected type: bool.
Return Value
Returns an initialized ApprovalPanel instance with a 'main_content' attribute containing the UI components. In case of initialization errors, returns a minimal Panel Column object with error message display and a stub 'set_user' method to maintain API compatibility. The returned object always has 'main_content' and 'set_user' attributes regardless of success or failure.
Dependencies
panelparampandasloggingtracebacktypesdatetime
Required Imports
import panel as pn
import logging
import traceback
import types
from CDocs.models.user_extensions import DocUser
from CDocs.auth.session_manager import SessionManager
from CDocs.controllers.approval_controller import get_user_pending_approvals, get_user_assigned_approvals, get_approval, complete_approval, cancel_approval_cycle, extend_approval_deadline, add_approver_to_active_approval, get_approval_cycle, create_approval_cycle, add_approval_comment, update_approval_comment, get_document_approvals, get_approval_statistics
from CDocs.controllers.document_controller import get_document, get_document_view_url, search_documents
from CDocs.controllers import ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError
from CDocs.config import settings, permissions
from CDocs.ui.components.document_access_controls import DocumentAccessControls
Conditional/Optional Imports
These imports are only needed under specific conditions:
import logging
Condition: imported inside exception handler for error logging
Required (conditional)import traceback
Condition: imported inside exception handler for detailed error stack traces
Required (conditional)import types
Condition: imported inside exception handler to dynamically create methods on minimal panel
Required (conditional)Usage Example
# Standalone mode
approval_panel = create_approval_panel()
approval_panel.servable()
# Embedded mode with session manager
from CDocs.auth.session_manager import SessionManager
session_mgr = SessionManager()
approval_panel = create_approval_panel(session_manager=session_mgr, embedded=True)
# Embedded in parent application
class MyApp:
def __init__(self):
self.current_user = DocUser(username='john.doe', email='john@example.com')
self.approval_panel = create_approval_panel(parent_app=self)
app = MyApp()
app.approval_panel.main_content.servable()
# Set user after creation
panel = create_approval_panel()
user = DocUser(username='jane.smith', email='jane@example.com')
panel.set_user(user)
Best Practices
- Always handle the returned panel gracefully as it may be a minimal error panel rather than a full ApprovalPanel instance
- Check for the existence of methods before calling them, as the minimal panel only implements 'set_user'
- Provide either session_manager or parent_app with current_user for proper authentication context
- Monitor logs under 'CDocs.ui.approval_panel' logger for initialization errors
- The function auto-detects embedded mode when parent_app is provided, so explicit embedded=True is optional in that case
- Ensure ApprovalPanel class is properly defined before calling this factory function
- The returned panel's main_content attribute should be used for rendering in embedded scenarios
- Call set_user() method after creation if user context changes or wasn't available during initialization
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_approval_panel_v1 96.8% similar
-
function create_review_panel 81.5% similar
-
function create_admin_panel 71.0% similar
-
class ApprovalPanel 70.5% similar
-
class ApprovalPanel_v1 70.0% similar