function delete_document
Deletes a controlled document from the system with permission checks, status validation, and audit logging.
/tf/active/vicechatdev/document_controller_backup.py
407 - 466
moderate
Purpose
This function provides a secure way to delete controlled documents from a document management system. It enforces business rules around document deletion based on status (PUBLISHED, EFFECTIVE, ARCHIVED documents require force flag and special permissions), validates user permissions, logs the deletion event to an audit trail, and returns a success status. It's designed for document lifecycle management in regulated environments where deletion must be controlled and auditable.
Source Code
def delete_document(user: DocUser, document_uid: str, force: bool = False) -> Dict[str, Any]:
"""
Delete a document from the system.
Args:
user: User deleting the document
document_uid: UID of document to delete
force: Whether to force deletion even for published documents
Returns:
Dictionary with deletion status
Raises:
ResourceNotFoundError: If document not found
PermissionError: If user doesn't have permission
BusinessRuleError: If deletion is not allowed
"""
try:
# Get document instance
document = ControlledDocument(uid=document_uid)
if not document:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Check if document can be deleted
if document.status in ["PUBLISHED", "EFFECTIVE", "ARCHIVED"] and not force:
if not permissions.user_has_permission(user, "FORCE_DELETE_DOCUMENT"):
raise BusinessRuleError(f"Cannot delete document with status {document.status}. Use force=True if you have permission.")
# Store document details for audit
doc_details = {
"doc_number": document.doc_number,
"title": document.title,
"doc_type": document.doc_type,
"department": document.department,
"status": document.status
}
# Delete document from database
document.delete()
# Log deletion event
audit_trail.log_document_lifecycle_event(
event_type="DOCUMENT_DELETED",
user=user,
document_uid=document_uid,
details=doc_details
)
return {
"success": True,
"document_uid": document_uid,
"message": f"Document {doc_details['doc_number']} deleted successfully"
}
except (ResourceNotFoundError, PermissionError, BusinessRuleError) as e:
# Re-raise known errors
raise
except Exception as e:
logger.error(f"Error deleting document {document_uid}: {e}")
raise BusinessRuleError(f"Failed to delete document: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
document_uid |
str | - | positional_or_keyword |
force |
bool | False | positional_or_keyword |
Parameter Details
user: DocUser object representing the authenticated user attempting to delete the document. Used for permission checks and audit logging.
document_uid: String containing the unique identifier (UID) of the document to be deleted. Must correspond to an existing document in the system.
force: Boolean flag (default False) that allows deletion of documents in protected statuses (PUBLISHED, EFFECTIVE, ARCHIVED). When True, requires the user to have FORCE_DELETE_DOCUMENT permission. Use with caution as it bypasses normal deletion restrictions.
Return Value
Type: Dict[str, Any]
Returns a dictionary with three keys: 'success' (bool, always True on successful deletion), 'document_uid' (str, the UID of the deleted document), and 'message' (str, a human-readable confirmation message including the document number). On error, raises an exception rather than returning a failure status.
Dependencies
logginguuidostempfiletypingdatetimeiopanelshutiltracebackCDocsconfig
Required Imports
from typing import Dict, Any
from CDocs.models.user_extensions import DocUser
from CDocs.models.document import ControlledDocument
from CDocs.config import permissions
from CDocs.utils import audit_trail
from CDocs.controllers import require_permission, log_controller_action, transaction
from CDocs.controllers import ResourceNotFoundError, PermissionError, BusinessRuleError
import logging
Usage Example
from CDocs.models.user_extensions import DocUser
from typing import Dict, Any
# Assuming delete_document function is imported and decorators are applied
# Example 1: Delete a draft document (normal deletion)
user = DocUser(uid='user123', username='john.doe')
document_uid = 'doc-abc-123'
try:
result = delete_document(user=user, document_uid=document_uid)
print(f"Success: {result['message']}")
except ResourceNotFoundError:
print("Document not found")
except PermissionError:
print("User lacks permission to delete")
except BusinessRuleError as e:
print(f"Cannot delete: {e}")
# Example 2: Force delete a published document (requires special permission)
try:
result = delete_document(user=user, document_uid=document_uid, force=True)
print(f"Forced deletion: {result['message']}")
except BusinessRuleError as e:
print(f"Force deletion failed: {e}")
Best Practices
- Always handle the three specific exception types (ResourceNotFoundError, PermissionError, BusinessRuleError) when calling this function
- Use force=True only when absolutely necessary and ensure the user has FORCE_DELETE_DOCUMENT permission
- The function is decorated with @transaction, so database operations are atomic - either all succeed or all rollback
- The function is decorated with @require_permission('DELETE_DOCUMENT', 'document_uid'), so basic permission checks happen before function execution
- Deletion events are automatically logged to the audit trail with document details preserved for compliance
- Documents in PUBLISHED, EFFECTIVE, or ARCHIVED status cannot be deleted without force=True and appropriate permissions
- The function stores document metadata before deletion to ensure audit trail has complete information
- Consider implementing soft-delete patterns for critical documents instead of hard deletion in production environments
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function archive_document 70.8% similar
-
function publish_document 68.0% similar
-
function get_document 67.5% similar
-
function update_document 65.6% similar
-
function clone_document 64.8% similar