function get_document_audit_trail
Retrieves the complete audit trail for a controlled document from a Neo4j graph database, including timestamps, user actions, and event details.
/tf/active/vicechatdev/document_controller_backup.py
1115 - 1172
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
loggingtypingCDocs.dbCDocs.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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_document_history 83.7% similar
-
function generate_audit_report 79.4% similar
-
function get_document_training_info 71.9% similar
-
function get_document 70.4% similar
-
function get_document_v5 69.7% similar