🔍 Code Extractor

function delete_document

Maturity: 67

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 status dictionary. 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. Must be a valid DocUser instance with appropriate permissions.

document_uid: String containing the unique identifier (UID) of the document to be deleted. Must correspond to an existing document in the system, otherwise ResourceNotFoundError is raised.

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 one of the documented exceptions instead of returning.

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

# Basic deletion (draft or non-protected document)
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")
except BusinessRuleError as e:
    print(f"Business rule violation: {e}")

# Force deletion of published document (requires special permission)
try:
    result = delete_document(
        user=user,
        document_uid='doc-published-456',
        force=True
    )
    print(f"Forced deletion: {result['message']}")
except PermissionError:
    print("User lacks FORCE_DELETE_DOCUMENT permission")

Best Practices

  • Always wrap calls in try-except blocks to handle ResourceNotFoundError, PermissionError, and BusinessRuleError
  • Use force=True sparingly and only when absolutely necessary, as it bypasses important business rules
  • Ensure the user object has been properly authenticated before calling this function
  • 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 permission checks happen before execution
  • Deletion of PUBLISHED, EFFECTIVE, or ARCHIVED documents requires both force=True AND the FORCE_DELETE_DOCUMENT permission
  • All deletions are logged to the audit trail with document details for compliance and traceability
  • The function permanently deletes the document - consider implementing soft delete or archival for production systems
  • Document details are captured before deletion to ensure audit trail has complete information even after the document is removed

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function delete_document_from_filecloud 79.6% similar

    Deletes a document and its associated folder from FileCloud storage, with permission checks, audit logging, and error handling.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function archive_document_v1 71.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 archive_document 69.9% similar

    Archives a controlled document by changing its status and all versions to ARCHIVED, moving the published PDF to an archived location with metadata, and logging the archival event.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function disable_document_training 68.5% similar

    Disables the training requirement for a specific controlled document, verifying user permissions and logging the action to the audit trail.

    From: /tf/active/vicechatdev/CDocs/controllers/training_controller.py
  • function get_document 67.6% 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
← Back to Browse