function notify_document_update
Sends notifications to interested users when a controlled document is created, updated, or has a status/version change. Identifies relevant users through database queries and dispatches notifications via the send_notification function.
/tf/active/vicechatdev/CDocs single class/utils/notifications.py
1225 - 1320
moderate
Purpose
This function serves as a notification dispatcher for document management systems. It queries a Neo4j graph database to find all users who should be notified about document changes (owners, department members, subscribers, and users with permissions), then creates and sends appropriate notifications based on the type of document event. It supports multiple notification types including document creation, updates, status changes, and version creation, with customizable messages and email templates for each type.
Source Code
def notify_document_update(document, notification_type: str) -> List[str]:
"""
Send document update notifications to interested users.
Args:
document: ControlledDocument instance
notification_type: Type of notification
Returns:
List of created notification UIDs
"""
try:
# Find users who should be notified of document updates
# This might include document owner, department users, etc.
query = """
MATCH (d:ControlledDocument {UID: $doc_uid})
// Document owner
OPTIONAL MATCH (u1:User {UID: d.ownerUID})
// Department users
OPTIONAL MATCH (u2:User)-[:HAS_ROLE]->(:Role)-[:FOR_DEPARTMENT]->(dept:Department {Code: d.department})
// Users with explicit document subscriptions
OPTIONAL MATCH (u3:User)-[:SUBSCRIBED_TO]->(d)
// Users with permission to this document
OPTIONAL MATCH (u4:User)-[:HAS_PERMISSION]->(:Permission)-[:FOR_DOCUMENT]->(d)
RETURN collect(distinct u1) + collect(distinct u2) + collect(distinct u3) + collect(distinct u4) as users
"""
result = db.run_query(query, {"doc_uid": document.uid})
if not result or 'users' not in result[0]:
logger.warning(f"No users to notify for document {document.uid}")
return []
users = result[0]['users']
user_uids = [user['UID'] for user in users if user and 'UID' in user]
if not user_uids:
logger.warning(f"No users to notify for document {document.uid}")
return []
# Get current version if available
current_version = document.current_version
version_number = current_version.version_number if current_version else "N/A"
# Prepare notification details
details = {
'doc_uid': document.uid,
'doc_number': document.doc_number,
'doc_type': document.doc_type,
'title': document.title,
'status': document.status,
'version_number': version_number
}
# Create message based on notification type
message = None
if notification_type == 'DOCUMENT_CREATED':
message = f"New document created: {document.doc_number} - {document.title}"
elif notification_type == 'DOCUMENT_UPDATED':
message = f"Document updated: {document.doc_number} - {document.title}"
elif notification_type == 'DOCUMENT_STATUS_CHANGED':
message = f"Document status changed to {document.status}: {document.doc_number} - {document.title}"
elif notification_type == 'VERSION_CREATED':
message = f"New version created: {document.doc_number} (v{version_number}) - {document.title}"
# Determine email template based on notification type
email_template = None
if notification_type == 'DOCUMENT_CREATED':
email_template = 'document_created'
elif notification_type == 'DOCUMENT_UPDATED':
email_template = 'document_updated'
elif notification_type == 'DOCUMENT_STATUS_CHANGED':
email_template = 'document_status_changed'
elif notification_type == 'VERSION_CREATED':
email_template = 'version_created'
# Send notification
return send_notification(
notification_type=notification_type,
users=user_uids,
resource_uid=document.uid,
resource_type='ControlledDocument',
message=message,
details=details,
send_email=True,
email_template=email_template
)
except Exception as e:
logger.error(f"Error sending document update notification: {e}")
return []
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
document |
- | - | positional_or_keyword |
notification_type |
str | - | positional_or_keyword |
Parameter Details
document: A ControlledDocument instance representing the document that triggered the notification. Must have attributes: uid (unique identifier), doc_number (document number), doc_type (document type), title (document title), status (current status), and current_version (optional version object with version_number attribute). This object is used to extract document details and query related users.
notification_type: String indicating the type of notification to send. Expected values are: 'DOCUMENT_CREATED' (new document), 'DOCUMENT_UPDATED' (document modified), 'DOCUMENT_STATUS_CHANGED' (status transition), or 'VERSION_CREATED' (new version published). This determines the notification message and email template used.
Return Value
Type: List[str]
Returns a List[str] containing the UIDs (unique identifiers) of all successfully created notifications. Each UID corresponds to a notification record created by the send_notification function. Returns an empty list if no users need to be notified, if an error occurs, or if notification creation fails.
Dependencies
loggingtypingCDocs.dbCDocs.config.settingsCDocs.models.user_extensions.DocUserCDocs.utils.audit_trailmodels.review.ReviewCyclemodels.approval.Approval
Required Imports
from typing import List
import logging
Usage Example
from typing import List
import logging
# Assuming db, send_notification, and logger are configured
# and ControlledDocument class is available
# Create or retrieve a document instance
document = ControlledDocument(
uid='doc-12345',
doc_number='DOC-001',
doc_type='Policy',
title='Security Policy',
status='Draft',
current_version=Version(version_number='1.0')
)
# Notify users about document creation
notification_uids = notify_document_update(
document=document,
notification_type='DOCUMENT_CREATED'
)
print(f"Created {len(notification_uids)} notifications")
# Notify about status change
document.status = 'Approved'
notification_uids = notify_document_update(
document=document,
notification_type='DOCUMENT_STATUS_CHANGED'
)
# Notify about new version
notification_uids = notify_document_update(
document=document,
notification_type='VERSION_CREATED'
)
Best Practices
- Ensure the document object passed has all required attributes (uid, doc_number, doc_type, title, status) to avoid AttributeError
- Use valid notification_type values from the supported set: 'DOCUMENT_CREATED', 'DOCUMENT_UPDATED', 'DOCUMENT_STATUS_CHANGED', 'VERSION_CREATED'
- The function handles exceptions gracefully and returns an empty list on error, so check the return value to verify notification success
- Monitor logs for warnings about users not found, as this may indicate database relationship issues
- Ensure the Neo4j database schema matches the expected node labels and relationship types
- The function deduplicates users automatically using 'collect(distinct)', preventing duplicate notifications
- Email templates must be configured in your email system matching the template names used
- Consider the performance impact of the complex Cypher query on large databases with many users and documents
- The send_notification function must be implemented and available in scope for this function to work
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function notify_document_update_v1 98.2% similar
-
function send_notification 67.5% similar
-
function update_document_v4 66.5% similar
-
function send_notification_v1 65.8% similar
-
function create_document_version 65.8% similar