function start_document_approval_workflow
Initiates an approval workflow for a document in FileCloud, validating document existence, preparing workflow metadata, and logging the workflow start event.
/tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
1118 - 1201
moderate
Purpose
This function serves as the primary entry point for starting document approval workflows in a FileCloud-integrated document management system. It validates user permissions, retrieves the document from the database, prepares comprehensive workflow metadata including document attributes, initiates the workflow via FileCloud API, and creates an audit trail entry. Use this when implementing document approval processes that require external workflow management through FileCloud.
Source Code
def start_document_approval_workflow(
user: DocUser,
document_uid: str,
workflow_name: str,
workflow_data: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Start an approval workflow for a document in FileCloud.
Args:
user: User starting the workflow
document_uid: UID of the document
workflow_name: Name of workflow to start
workflow_data: Optional additional workflow data
Returns:
Dictionary with workflow information
Raises:
ResourceNotFoundError: If document not found
PermissionError: If user doesn't have permission
FileCloudError: If workflow start fails
"""
# Get document instance
doc = ControlledDocument(uid=document_uid)
if not doc:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Get file path
file_path = get_filecloud_document_path(doc)
# Prepare workflow data
wf_data = workflow_data or {}
wf_data.update({
"doc_uid": doc.uid,
"doc_number": doc.doc_number,
"title": doc.title,
"doc_type": doc.doc_type,
"department": doc.department,
"status": doc.status,
"initiator": user.username
})
try:
client = get_filecloud_client()
# Start workflow
result = client.start_document_workflow(
file_path=file_path,
workflow_name=workflow_name,
workflow_data=wf_data
)
if not result.get('success', False):
logger.error(f"Failed to start workflow in FileCloud: {result.get('message', 'Unknown error')}")
raise FileCloudError(f"Failed to start workflow: {result.get('message', 'Unknown error')}")
workflow_id = result.get('workflow_id')
# Log audit event
audit_trail.log_document_lifecycle_event(
event_type="DOCUMENT_WORKFLOW_STARTED",
user=user,
document_uid=document_uid,
details={
"file_path": file_path,
"workflow_name": workflow_name,
"workflow_id": workflow_id,
"workflow_data": wf_data
}
)
return {
"success": True,
"document_uid": document_uid,
"file_path": file_path,
"workflow_name": workflow_name,
"workflow_id": workflow_id,
"workflow_data": wf_data
}
except Exception as e:
logger.error(f"Error starting document workflow in FileCloud: {e}")
raise FileCloudError(f"Error starting document workflow: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
document_uid |
str | - | positional_or_keyword |
workflow_name |
str | - | positional_or_keyword |
workflow_data |
Optional[Dict[str, Any]] | None | positional_or_keyword |
Parameter Details
user: DocUser object representing the authenticated user initiating the workflow. Must have 'MANAGE_APPROVAL_WORKFLOWS' permission. Used for audit logging and permission validation.
document_uid: String containing the unique identifier (UID) of the document to start the workflow for. Must correspond to an existing ControlledDocument in the database.
workflow_name: String specifying the name of the workflow template to start in FileCloud. Must match a pre-configured workflow name in the FileCloud system.
workflow_data: Optional dictionary containing additional custom data to pass to the workflow. Will be merged with automatically generated document metadata (doc_uid, doc_number, title, doc_type, department, status, initiator). Defaults to None if not provided.
Return Value
Type: Dict[str, Any]
Returns a dictionary with keys: 'success' (boolean, always True on successful execution), 'document_uid' (string, the document UID), 'file_path' (string, FileCloud path to the document), 'workflow_name' (string, name of started workflow), 'workflow_id' (string/int, unique identifier for the workflow instance returned by FileCloud), and 'workflow_data' (dict, complete workflow data including merged custom and document metadata).
Dependencies
loggingtypingCDocs.dbCDocs.config.settingsCDocs.config.permissionsCDocs.models.documentCDocs.models.user_extensionsCDocs.utils.audit_trailCDocs.controllersCDocs.utils.FC_api
Required Imports
from typing import Dict, Any, Optional
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, PermissionError, ResourceNotFoundError
from CDocs.utils.FC_api import FileCloudAPI
Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_workflows import start_document_approval_workflow
# Assume user is authenticated and has required permissions
user = DocUser.query.filter_by(username='john.doe').first()
document_uid = 'DOC-2024-001'
workflow_name = 'standard_approval'
# Optional: provide custom workflow data
custom_data = {
'priority': 'high',
'deadline': '2024-12-31',
'approvers': ['manager@company.com', 'director@company.com']
}
try:
result = start_document_approval_workflow(
user=user,
document_uid=document_uid,
workflow_name=workflow_name,
workflow_data=custom_data
)
print(f"Workflow started successfully: {result['workflow_id']}")
print(f"Document path: {result['file_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 wrap calls in try-except blocks to handle ResourceNotFoundError, PermissionError, and FileCloudError exceptions
- Ensure the user object has been authenticated and has the 'MANAGE_APPROVAL_WORKFLOWS' permission before calling
- Verify that the workflow_name matches a pre-configured workflow in FileCloud to avoid runtime errors
- The workflow_data parameter should not contain keys that conflict with automatically generated metadata (doc_uid, doc_number, title, doc_type, department, status, initiator) as they will be overwritten
- Monitor the audit trail logs for workflow start events to track document lifecycle
- Ensure FileCloud API client is properly configured with valid credentials before calling this function
- The function requires both decorators (@log_controller_action and @require_permission) to be properly configured in the application
- Handle the returned workflow_id appropriately for tracking and monitoring workflow progress
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_approval_cycle 72.4% similar
-
function complete_approval_v1 66.7% similar
-
function process_document_signing 66.5% similar
-
function set_document_permissions_in_filecloud 66.5% similar
-
function complete_approval 65.7% similar