function delete_document_from_filecloud
Deletes a document and its associated folder from FileCloud storage, with permission checks, audit logging, and error handling.
/tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
1059 - 1114
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
loggingosjsonuuidtempfiletypingtimeCDocs.dbCDocs.config.settingsCDocs.config.permissionsCDocs.models.documentCDocs.models.user_extensionsCDocs.utils.document_processorCDocs.utils.audit_trailCDocs.utils.notificationsCDocs.controllersCDocs.utils.metadata_catalogCDocs.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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function delete_document 79.6% similar
-
function set_document_permissions_in_filecloud 73.8% similar
-
function download_document_from_filecloud 70.9% similar
-
function upload_document_to_filecloud 69.7% similar
-
function remove_user_access 68.9% similar