🔍 Code Extractor

function create_review_panel

Maturity: 46

Factory function that creates and initializes a ReviewPanel instance with error handling, supporting both standalone and embedded modes for document review management.

File:
/tf/active/vicechatdev/CDocs/ui/review_panel.py
Lines:
2026 - 2075
Complexity:
moderate

Purpose

This function serves as a safe factory for creating ReviewPanel UI components in a Panel-based application. It handles initialization of the review panel with proper template setup, session management, user context, and graceful error recovery. It can operate in standalone mode (with its own template) or embedded mode (within a parent application). The function includes comprehensive error handling that returns a minimal functional panel if initialization fails, preventing application crashes.

Source Code

def create_review_panel(session_manager=None, parent_app=None, embedded=False):
    """Create and initialize a review panel instance"""
    try:
        import panel as pn
        
        # Create template for review panel (only used in standalone mode)
        review_bp = pn.template.BootstrapTemplate(
            title="Review Management",
            header_background="#3DCAB1"
        )
        
        # Create and initialize panel
        panel = ReviewPanel(
            template=review_bp,
            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_reviews'):
                panel._load_pending_reviews()
        
        return panel
    except Exception as e:
        import logging
        logger = logging.getLogger('CDocs.ui.review_panel')
        logger.error(f"Error creating review panel: {e}")
        import traceback
        logger.error(traceback.format_exc())
        
        # Return a minimal functioning panel
        import panel as pn
        minimal_panel = pn.Column(
            pn.pane.Markdown("# Review Management"),
            pn.pane.Markdown(f"**Error loading review 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 have limited functionality requiring manual user setup. Expected type: SessionManager or None.

parent_app: Optional reference to the parent application instance. When provided, the panel operates in embedded mode and can access parent app properties like current_user. Expected type: Application object with current_user attribute, or None.

embedded: Boolean flag indicating whether the panel should run in embedded mode (True) or standalone mode (False). Automatically set to True if parent_app is provided. Default: False.

Return Value

Returns a ReviewPanel instance (or minimal fallback panel on error) with the following key attributes: 'main_content' (the UI layout), 'user' (current user context), and 'set_user' method (for updating user context). 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.

Dependencies

  • panel
  • logging
  • traceback
  • types

Required Imports

import panel as pn
import logging
import traceback
import types

Conditional/Optional Imports

These imports are only needed under specific conditions:

import panel as pn

Condition: Required at function entry for creating the review panel template and UI components

Required (conditional)
import logging

Condition: Used in error handling to log exceptions

Required (conditional)
import traceback

Condition: Used in error handling to log full exception stack traces

Required (conditional)
import types

Condition: Used in error fallback to dynamically bind methods to minimal panel object

Required (conditional)

Usage Example

# Standalone mode
panel = create_review_panel()

# With session manager
from CDocs.auth.session_manager import SessionManager
session_mgr = SessionManager()
panel = create_review_panel(session_manager=session_mgr)

# Embedded in parent app
class MyApp:
    def __init__(self):
        self.current_user = DocUser(username='john_doe')
        self.review_panel = create_review_panel(parent_app=self, embedded=True)

# Explicitly embedded mode
panel = create_review_panel(embedded=True)

# Access the panel content
if hasattr(panel, 'main_content'):
    panel.main_content.servable()

# Set user manually if needed
from CDocs.models.user_extensions import DocUser
user = DocUser(username='reviewer1')
panel.set_user(user)

Best Practices

  • Always check if the returned panel has the expected attributes before using them, as error fallback returns a minimal panel
  • Provide either session_manager or parent_app for proper user context initialization
  • When using embedded mode, ensure parent_app has a current_user attribute set before calling this function
  • Monitor logs for 'CDocs.ui.review_panel' logger to catch initialization errors
  • The function auto-detects embedded mode when parent_app is provided, so explicit embedded=True is optional in that case
  • The minimal fallback panel maintains API compatibility with set_user method, but has limited functionality
  • If the panel needs to reload data after user assignment, ensure the ReviewPanel class implements _load_pending_reviews method
  • Consider wrapping calls to this function in try-except blocks for additional error handling at the application level

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_approval_panel 81.5% similar

    Factory function that creates and initializes an ApprovalPanel instance with error handling, supporting both standalone and embedded modes for document approval management.

    From: /tf/active/vicechatdev/CDocs/ui/approval_panel_bis.py
  • function create_approval_panel_v1 79.5% similar

    Factory function that creates and initializes an ApprovalPanel instance for managing document approvals, with error handling and fallback to a minimal panel on failure.

    From: /tf/active/vicechatdev/CDocs/ui/approval_panel.py
  • class ReviewPanel 68.4% similar

    Review management interface component

    From: /tf/active/vicechatdev/CDocs/ui/review_panel.py
  • function create_admin_panel 63.5% similar

    Factory function that creates and returns a configured AdminPanel instance with optional template, session management, parent application reference, and embedding mode.

    From: /tf/active/vicechatdev/CDocs/ui/admin_panel.py
  • function create_user_tasks_panel 62.1% similar

    Factory function that creates and initializes a UserTasksPanel instance, optionally setting the current user from a parent application.

    From: /tf/active/vicechatdev/CDocs/ui/user_tasks_panel.py
← Back to Browse