🔍 Code Extractor

function delete_document_from_filecloud

Maturity: 63

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

File:
/tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
Lines:
1059 - 1114
Complexity:
moderate

Purpose

This function provides a controlled way to permanently delete documents from FileCloud storage. It verifies the document exists, retrieves its storage path, deletes the entire folder containing the document, and logs the deletion event for audit purposes. It enforces permission requirements through decorators and handles various error conditions including missing documents, permission issues, and FileCloud API failures.

Source Code

def delete_document_from_filecloud(
    user: DocUser,
    document_uid: str
) -> Dict[str, Any]:
    """
    Delete a document from FileCloud.
    
    Args:
        user: User performing the deletion
        document_uid: UID of the document to delete
        
    Returns:
        Dictionary with deletion status
        
    Raises:
        ResourceNotFoundError: If document not found
        PermissionError: If user doesn't have permission
        FileCloudError: If deletion fails
    """
    # Get document instance
    doc = ControlledDocument(uid=document_uid)
    if not doc:
        raise ResourceNotFoundError(f"Document not found: {document_uid}")
    
    # Get document folder path
    file_path = get_filecloud_document_path(doc)
    folder_path, _ = os.path.split(file_path)
    
    try:
        client = get_filecloud_client()
        
        # Delete document folder
        result = client.delete_file(folder_path, "")
        
        if not result.get('success', False):
            logger.error(f"Failed to delete document from FileCloud: {result.get('message', 'Unknown error')}")
            raise FileCloudError(f"Failed to delete document: {result.get('message', 'Unknown error')}")
        
        # Log audit event
        audit_trail.log_document_lifecycle_event(
            event_type="DOCUMENT_DELETED",
            user=user,
            document_uid=document_uid,
            details={"folder_path": folder_path}
        )
        
        return {
            "success": True,
            "document_uid": document_uid,
            "folder_path": folder_path,
            "message": "Document successfully deleted from FileCloud"
        }
        
    except Exception as e:
        logger.error(f"Error deleting document from FileCloud: {e}")
        raise FileCloudError(f"Error deleting document: {e}")

Parameters

Name Type Default Kind
user DocUser - positional_or_keyword
document_uid str - positional_or_keyword

Parameter Details

user: DocUser object representing the authenticated user performing the deletion. Used for permission validation and audit logging. Must be a valid DocUser instance with appropriate DELETE_DOCUMENT permissions.

document_uid: String containing the unique identifier (UID) of the document to be deleted. This UID is used to locate the document in the database and determine its FileCloud storage path. Must be a valid document UID that exists in the system.

Return Value

Type: Dict[str, Any]

Returns a dictionary (Dict[str, Any]) containing deletion status information. On success, includes: 'success' (bool, always True), 'document_uid' (str, the deleted document's UID), 'folder_path' (str, the FileCloud folder path that was deleted), and 'message' (str, confirmation message). If deletion fails, raises an exception instead of returning.

Dependencies

  • logging
  • os
  • json
  • uuid
  • tempfile
  • typing
  • time
  • CDocs.db
  • CDocs.config.settings
  • CDocs.config.permissions
  • CDocs.models.document
  • CDocs.models.user_extensions
  • CDocs.utils.document_processor
  • CDocs.utils.audit_trail
  • CDocs.utils.notifications
  • CDocs.controllers
  • CDocs.utils.metadata_catalog
  • CDocs.utils.FC_api

Required Imports

import logging
import os
from typing import Dict, Any
from CDocs.models.document import ControlledDocument
from CDocs.models.user_extensions import DocUser
from CDocs.utils import audit_trail
from CDocs.controllers import require_permission, log_controller_action, ResourceNotFoundError
from CDocs.utils.FC_api import FileCloudAPI

Usage Example

from CDocs.models.user_extensions import DocUser
from your_module import delete_document_from_filecloud

# Assume user is authenticated and has DELETE_DOCUMENT permission
user = DocUser.get_by_id(user_id=123)
document_uid = "doc-12345-abcde"

try:
    result = delete_document_from_filecloud(
        user=user,
        document_uid=document_uid
    )
    print(f"Success: {result['message']}")
    print(f"Deleted folder: {result['folder_path']}")
except ResourceNotFoundError as e:
    print(f"Document not found: {e}")
except PermissionError as e:
    print(f"Permission denied: {e}")
except FileCloudError as e:
    print(f"FileCloud error: {e}")

Best Practices

  • Always ensure the user has DELETE_DOCUMENT permission before calling this function (enforced by decorator)
  • Handle all three exception types: ResourceNotFoundError, PermissionError, and FileCloudError
  • This function deletes the entire folder containing the document, not just the file itself
  • Deletion is permanent and cannot be undone - consider implementing soft delete or backup mechanisms
  • The function logs audit events automatically, so deletion actions are tracked
  • Ensure proper error handling as FileCloud API failures will raise FileCloudError
  • The function requires helper functions (get_filecloud_client, get_filecloud_document_path) to be available in scope
  • Document must exist in the database before deletion can proceed
  • Consider implementing transaction rollback if database and FileCloud operations need to be atomic

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function delete_document 79.6% similar

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

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function set_document_permissions_in_filecloud 73.8% similar

    Sets user and group permissions for a document in FileCloud by updating access controls on the document's folder path and logging the permission changes to an audit trail.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function download_document_from_filecloud 70.9% similar

    Downloads a document version from FileCloud storage, with optional availability checking and audit logging for user-initiated downloads.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function upload_document_to_filecloud 69.7% similar

    Uploads a document version to FileCloud storage system with metadata, handling file creation, folder structure, and audit logging.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function remove_user_access 68.9% similar

    Removes a user's access permissions from a specific document version share in FileCloud by delegating to the FileCloud client's remove_user_from_share method.

    From: /tf/active/vicechatdev/CDocs/controllers/share_controller.py
← Back to Browse