🔍 Code Extractor

function create_audit_entry

Maturity: 68

Creates an audit trail entry for document actions, logging user activity, document changes, and lifecycle events with fallback mechanisms.

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
2323 - 2387
Complexity:
moderate

Purpose

This function provides a robust audit logging mechanism for document management systems. It attempts to use a dedicated audit_trail module for logging document lifecycle events, but falls back to direct database entry creation if the module is unavailable. It captures user information, action types, timestamps, and additional details, creating both audit nodes and relationships to documents in a graph database. This ensures comprehensive tracking of all document-related activities for compliance, security, and historical record-keeping purposes.

Source Code

def create_audit_entry(user: DocUser, document_uid: str, action: str, details: Any = None) -> bool:
    """
    Create an audit trail entry for document actions.
    
    Args:
        user: User who performed the action
        document_uid: UID of the document being acted upon
        action: Type of action performed
        details: Additional details about the action
        
    Returns:
        Boolean indicating success
    """
    try:
        # Try to use the existing audit_trail module if available
        try:
            
            return audit_trail.log_document_lifecycle_event(
                event_type=action,
                user=user,
                document_uid=document_uid,
                details=details
            )
        except (ImportError, AttributeError):
            # Fallback to direct database entry if audit_trail module not available

            
            # Create audit entry properties
            properties = {
                'UID': str(uuid.uuid4()),
                'action': action,
                'timestamp': datetime.now(),
                'documentUID': document_uid,
                'details': str(details) if details else ""
            }
            
            # Add user information if available
            if user:
                if hasattr(user, 'UID'):
                    properties['userUID'] = user.uid
                if hasattr(user, 'username'):
                    properties['username'] = user.username
                elif hasattr(user, 'name'):
                    properties['username'] = user.name
            
            # Create the audit node

            audit_data = db.create_node(NodeLabels.AUDIT_ENTRY, properties)
            
            # Create relationship to document
            if audit_data:

                db.create_relationship(
                    document_uid,
                    audit_data['UID'],
                    RelTypes.HAS_AUDIT
                )
                
            return audit_data is not None
            
    except Exception as e:
        logger.error(f"Error creating audit entry: {e}")
        import traceback
        logger.error(traceback.format_exc())
        return False

Parameters

Name Type Default Kind
user DocUser - positional_or_keyword
document_uid str - positional_or_keyword
action str - positional_or_keyword
details Any None positional_or_keyword

Parameter Details

user: DocUser object representing the user who performed the action. Should have attributes like 'UID', 'username', or 'name'. Can be None if the action is system-generated.

document_uid: String containing the unique identifier (UID) of the document being acted upon. Must be a valid document UID that exists in the database.

action: String describing the type of action performed (e.g., 'created', 'updated', 'approved', 'published', 'archived'). This becomes the event_type in the audit trail.

details: Optional parameter of any type containing additional context about the action. Can be a dictionary, string, or any serializable object. Will be converted to string for storage. Defaults to None.

Return Value

Type: bool

Returns a boolean value indicating whether the audit entry was successfully created. Returns True if the audit entry was logged successfully (either through audit_trail module or direct database entry), False if any error occurred during the process. Errors are logged but do not raise exceptions.

Dependencies

  • uuid
  • datetime
  • logging
  • traceback
  • CDocs.db
  • CDocs.models.user_extensions
  • CDocs.utils.audit_trail
  • CDocs.db.schema_manager

Required Imports

import uuid
from datetime import datetime
import logging
import traceback
from CDocs import db
from CDocs.models.user_extensions import DocUser
from CDocs.db.schema_manager import NodeLabels, RelTypes

Conditional/Optional Imports

These imports are only needed under specific conditions:

from CDocs.utils import audit_trail

Condition: Attempted first for primary audit logging; if ImportError or AttributeError occurs, function falls back to direct database operations

Optional

Usage Example

import logging
from datetime import datetime
from CDocs.models.user_extensions import DocUser
from your_module import create_audit_entry

# Setup logger
logger = logging.getLogger(__name__)

# Create a user object
user = DocUser()
user.uid = 'user-123'
user.username = 'john.doe'

# Create audit entry for document creation
success = create_audit_entry(
    user=user,
    document_uid='doc-456',
    action='created',
    details={'version': '1.0', 'status': 'draft'}
)

if success:
    print('Audit entry created successfully')
else:
    print('Failed to create audit entry')

# Create audit entry with minimal information
success = create_audit_entry(
    user=None,
    document_uid='doc-789',
    action='system_update'
)

# Create audit entry for approval action
success = create_audit_entry(
    user=user,
    document_uid='doc-456',
    action='approved',
    details='Approved by quality manager'
)

Best Practices

  • Always check the return value to ensure audit entries are being created successfully
  • Provide meaningful action strings that clearly describe the operation performed
  • Include relevant details in the details parameter for comprehensive audit trails
  • Ensure the logger is properly configured before calling this function to capture error messages
  • The function handles exceptions gracefully and returns False on error, so it won't crash your application
  • User object can be None for system-generated actions, but provide it when available for better audit trails
  • The function attempts to use audit_trail.log_document_lifecycle_event first, which may have additional features
  • Document UIDs must exist in the database for relationship creation to succeed
  • Details parameter is converted to string, so complex objects should be serializable
  • Consider monitoring audit entry creation failures as they may indicate database connectivity issues

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function log_document_lifecycle_event 70.4% similar

    Logs a document lifecycle event to an audit trail by delegating to a generic log_event function with document-specific parameters.

    From: /tf/active/vicechatdev/CDocs/utils/audit_trail.py
  • function log_user_action 68.4% similar

    Creates an audit event node in a graph database to log user actions, connecting it to both an audit trail and the user who performed the action.

    From: /tf/active/vicechatdev/CDocs/utils/audit_trail.py
  • function get_document_audit_trail 66.4% similar

    Retrieves the complete audit trail for a controlled document from a Neo4j graph database, including timestamps, user actions, and event details.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function generate_audit_report 63.8% similar

    Generates a comprehensive audit report for a controlled document by aggregating document metadata, version history, review cycles, approvals, and categorized audit events.

    From: /tf/active/vicechatdev/CDocs/utils/audit_trail.py
  • function get_document_history 63.2% similar

    Retrieves the complete audit history for a document by querying events across document, version, review, comment, and approval nodes in a Neo4j graph database.

    From: /tf/active/vicechatdev/CDocs/utils/audit_trail.py
← Back to Browse