🔍 Code Extractor

function delete_document

Maturity: 65

Deletes a controlled document from the system with permission checks, status validation, and audit logging.

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
407 - 466
Complexity:
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

  • logging
  • uuid
  • os
  • tempfile
  • typing
  • datetime
  • io
  • panel
  • shutil
  • traceback
  • CDocs
  • config

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function archive_document 70.8% similar

    Archives a controlled document by changing its status to ARCHIVED, ensuring a PDF version exists and logging the action with audit trail and notifications.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function publish_document 68.0% similar

    Publishes an approved controlled document by converting it to PDF with signatures and audit trail, uploading to FileCloud, and updating the document status to PUBLISHED.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_document 67.5% 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 update_document 65.6% similar

    Updates properties of a controlled document including title, description, status, owner, and metadata, with special handling for status transitions that require format conversions or publishing workflows.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function clone_document 64.8% similar

    Clones an existing controlled document to create either a new independent document or a new revision of the same document, optionally including the document's content.

    From: /tf/active/vicechatdev/document_controller_backup.py
← Back to Browse