🔍 Code Extractor

function ensure_document_folders_v1

Maturity: 56

Creates a hierarchical folder structure in FileCloud for storing controlled documents, organized by department, document type, and document number.

File:
/tf/active/vicechatdev/CDocs single class/controllers/filecloud_controller.py
Lines:
149 - 212
Complexity:
moderate

Purpose

This function ensures that all necessary folders exist in FileCloud storage before uploading or managing controlled documents. It creates a standardized folder hierarchy (root/department/doc_type/doc_number) to organize documents systematically. The function handles both ControlledDocument instances and document UIDs, checks for existing folders to avoid duplication, and creates missing folders in the hierarchy. It's typically used as part of document upload or initialization workflows in a document management system.

Source Code

def ensure_document_folders(document: Union[ControlledDocument, str]) -> Dict[str, str]:
    """
    Ensure all required folders exist in FileCloud for document storage.
    
    Args:
        document: ControlledDocument instance or document UID
        
    Returns:
        Dictionary of created folder paths
        
    Raises:
        ResourceNotFoundError: If document not found
        FileCloudError: If folder creation fails
    """
    # Get document instance if UID provided
    if isinstance(document, str):
        doc = ControlledDocument(uid=document)
        if not doc:
            raise ResourceNotFoundError(f"Document not found: {document}")
    else:
        doc = document
    
    client = get_filecloud_client()
    
    # Define folder hierarchy
    root_folder = f"/{settings.FILECLOUD_ROOT_FOLDER}"
    department_folder = f"{root_folder}/{doc.department}"
    doc_type_folder = f"{department_folder}/{doc.doc_type}"
    document_folder = f"{doc_type_folder}/{doc.doc_number}"
    
    folders = {
        "root": root_folder,
        "department": department_folder,
        "doc_type": doc_type_folder,
        "document": document_folder
    }
    

    # Create each folder if it doesn't exist
    for folder_name, folder_path in folders.items():
        try:
            # First check if folder exists
            folder_exists = False
            try:
                check_result = client.check_folder_exists(folder_path)
                logger.info(f"Checking folder existence: {folder_path} - Result: {check_result}")
                folder_exists = isinstance(check_result, bool) and check_result
            except Exception:
                folder_exists = False
            
            # Create folder if it doesn't exist
            if not folder_exists:
                logger.info(f"Creating folder: {folder_path}")
                result = client.create_folder(path="/".join(folder_path.split('/')[:-1]), folder_name=folder_path.split('/')[-1])
                
                if not result.get('success', False):
                    logger.error(f"Failed to create folder {folder_path}: {result.get('message', 'Unknown error')}")
                    raise FileCloudError(f"Failed to create folder {folder_path}")
            
        except Exception as e:
            logger.error(f"Error creating folder {folder_path}: {e}")
            raise FileCloudError(f"Error creating folder structure: {e}")
    
    return folders

Parameters

Name Type Default Kind
document Union[ControlledDocument, str] - positional_or_keyword

Parameter Details

document: Either a ControlledDocument model instance or a string containing the document's unique identifier (UID). If a string UID is provided, the function will attempt to retrieve the corresponding ControlledDocument from the database. The document object must have 'department', 'doc_type', and 'doc_number' attributes to construct the folder hierarchy.

Return Value

Type: Dict[str, str]

Returns a dictionary with string keys and string values representing the created folder paths. Keys include 'root' (base FileCloud folder), 'department' (department-specific folder), 'doc_type' (document type folder), and 'document' (specific document folder). Values are the full paths to each folder level in the hierarchy (e.g., '/root_folder/Engineering/SOP/DOC-001').

Dependencies

  • CDocs
  • FC_api

Required Imports

from typing import Dict, Union
from CDocs.models.document import ControlledDocument
from CDocs.controllers import ResourceNotFoundError
from CDocs.controllers import log_controller_action
from CDocs.config import settings
from FC_api import FileCloudAPI
import logging

Usage Example

from CDocs.models.document import ControlledDocument
from CDocs.controllers import ensure_document_folders

# Using with a ControlledDocument instance
doc = ControlledDocument(
    uid='doc-12345',
    department='Engineering',
    doc_type='SOP',
    doc_number='DOC-001'
)

try:
    folders = ensure_document_folders(doc)
    print(f"Created folders: {folders}")
    # Output: {'root': '/documents', 'department': '/documents/Engineering', 
    #          'doc_type': '/documents/Engineering/SOP', 
    #          'document': '/documents/Engineering/SOP/DOC-001'}
except ResourceNotFoundError as e:
    print(f"Document not found: {e}")
except FileCloudError as e:
    print(f"Folder creation failed: {e}")

# Using with a document UID string
folders = ensure_document_folders('doc-12345')

Best Practices

  • Always wrap calls to this function in try-except blocks to handle ResourceNotFoundError and FileCloudError exceptions
  • Ensure the FileCloud client is properly authenticated before calling this function
  • The function is idempotent - it safely checks for existing folders before creating them, so it can be called multiple times
  • The document object must have valid 'department', 'doc_type', and 'doc_number' attributes populated
  • Consider calling this function before any document upload operations to ensure the target folder structure exists
  • The function is decorated with @log_controller_action, so all operations are automatically logged for audit purposes
  • Folder paths are constructed using forward slashes regardless of the operating system

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function ensure_document_folders 95.3% similar

    Ensures all required folder hierarchies exist in FileCloud storage for a controlled document, creating them if they don't exist.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function get_filecloud_document_path 71.3% similar

    Constructs and returns the FileCloud storage path for a controlled document, either for a specific version or the current version.

    From: /tf/active/vicechatdev/CDocs single class/controllers/filecloud_controller.py
  • function get_filecloud_document_path_v1 69.6% similar

    Constructs and returns the FileCloud storage path for a controlled document, supporting both custom and standard folder structures with version-specific file paths.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function upload_document_to_filecloud_v1 66.9% similar

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

    From: /tf/active/vicechatdev/CDocs single class/controllers/filecloud_controller.py
  • function create_folder 66.4% similar

    Creates a nested folder structure in FileCloud by iterating through path elements and checking/creating directories as needed.

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