🔍 Code Extractor

function get_document_audit_trail

Maturity: 56

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

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
1115 - 1172
Complexity:
moderate

Purpose

This function queries a Neo4j database to fetch all audit events related to a specific controlled document. It returns a chronologically ordered list of audit entries showing who performed what actions on the document and when. The function enriches audit data by resolving user UIDs to user names and handles errors gracefully by returning an empty list if the document doesn't exist or if an error occurs.

Source Code

def get_document_audit_trail(document_uid: str) -> List[Dict[str, Any]]:
    """
    Get the audit trail for a document
    
    Parameters
    ----------
    document_uid : str
        ID of the document
        
    Returns
    -------
    List[Dict[str, Any]]
        Audit trail entries
    """
    try:
        # Query audit events related to the document
        query = """
        MATCH (d:ControlledDocument {UID: $document_uid})<-[:RELATES_TO]-(e:AuditEvent)
        RETURN e
        ORDER BY e.timestamp ASC
        """
        
        result = db.run_query(query, {"document_uid": document_uid})
        
        if not result:
            return []
            
        # Format the audit entries
        audit_entries = []
        for record in result:
            if 'e' in record:
                event = record['e']
                
                # Extract user details if available
                user_name = None
                if 'userUID' in event:
                    user_query = "MATCH (u:User {UID: $user_uid}) RETURN u.name as name"
                    user_result = db.run_query(user_query, {"user_uid": event['userUID']})
                    if user_result and 'name' in user_result[0]:
                        user_name = user_result[0]['name']
                
                # Format the event for the audit trail
                audit_entry = {
                    'timestamp': event.get('timestamp', ''),
                    'user': event.get('userUID', ''),
                    'user_name': user_name or 'Unknown User',
                    'action': event.get('eventType', ''),
                    'comment': event.get('message', ''),
                    'details': event.get('details', {})
                }
                
                audit_entries.append(audit_entry)
                
        return audit_entries
        
    except Exception as e:
        logger.error(f"Error retrieving audit trail for document {document_uid}: {str(e)}")
        return []

Parameters

Name Type Default Kind
document_uid str - positional_or_keyword

Parameter Details

document_uid: Unique identifier (UID) string for the controlled document whose audit trail is being retrieved. This should match the UID property of a ControlledDocument node in the Neo4j database.

Return Value

Type: List[Dict[str, Any]]

Returns a List of dictionaries, where each dictionary represents an audit trail entry with the following keys: 'timestamp' (when the event occurred), 'user' (user UID who performed the action), 'user_name' (resolved user name or 'Unknown User'), 'action' (type of event/action performed), 'comment' (message associated with the event), and 'details' (additional event details as a dictionary). Returns an empty list if no audit events exist or if an error occurs.

Dependencies

  • logging
  • typing
  • CDocs.db
  • CDocs.config.settings

Required Imports

from typing import List, Dict, Any
import logging
from CDocs import db

Usage Example

from typing import List, Dict, Any
from CDocs import db
import logging

logger = logging.getLogger(__name__)

# Retrieve audit trail for a document
document_uid = "doc-12345-abcde"
audit_trail = get_document_audit_trail(document_uid)

# Process the audit trail
if audit_trail:
    for entry in audit_trail:
        print(f"{entry['timestamp']}: {entry['user_name']} performed {entry['action']}")
        if entry['comment']:
            print(f"  Comment: {entry['comment']}")
        if entry['details']:
            print(f"  Details: {entry['details']}")
else:
    print("No audit trail found or error occurred")

Best Practices

  • Always check if the returned list is empty before processing audit entries
  • The function returns an empty list on errors, so check logs for detailed error information
  • User names are resolved through additional database queries, which may impact performance for large audit trails
  • The function handles missing user information gracefully by defaulting to 'Unknown User'
  • Audit entries are returned in chronological order (ASC) by timestamp
  • Consider caching user name lookups if calling this function frequently for documents with many audit events
  • Ensure proper database indexing on ControlledDocument.UID and User.UID for optimal performance
  • The function is read-only and safe to call without transaction management

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_history 83.7% 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
  • function generate_audit_report 79.4% 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_training_info 71.9% similar

    Retrieves comprehensive training information for a specific controlled document, including training configuration, assigned users, completion status, and statistics.

    From: /tf/active/vicechatdev/CDocs/controllers/training_controller.py
  • function get_document 70.4% similar

    Retrieves comprehensive details of a controlled document by its UID, with optional inclusion of version history, review cycles, and approval cycles.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_document_v5 69.7% similar

    Retrieves all versions of a controlled document from a Neo4j graph database, including metadata about which version is current.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
← Back to Browse