function update_document_v2
Updates properties of a controlled document including title, description, status, owner, and metadata with permission checks, validation, and audit tracking.
/tf/active/vicechatdev/CDocs copy/controllers/document_controller.py
290 - 379
complex
Purpose
This function provides a secure, transactional way to modify document properties in a document management system. It enforces business rules including status transition validation, permission checks for status changes, and maintains an audit trail of all modifications. The function is designed for enterprise document control systems where changes must be tracked and validated against organizational policies.
Source Code
def update_document(
user: DocUser,
document_uid: str,
title: Optional[str] = None,
description: Optional[str] = None,
status: Optional[str] = None,
owner_uid: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Update a document's properties.
Args:
user: User making the update
document_uid: UID of document to update
title: New document title (optional)
description: New document description (optional)
status: New document status (optional)
owner_uid: New document owner UID (optional)
metadata: New document metadata (optional)
Returns:
Dictionary with update status
"""
try:
# Get document instance
document = ControlledDocument(uid=document_uid)
if not document:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Store original values for audit
original_values = {
'title': document.title,
'description': document.description,
'status': document.status,
'owner_uid': document.owner_uid
}
# Track what changed
changes = {}
# Update title if provided
if title is not None and title != document.title:
document.title = title
changes['title'] = {'old': original_values['title'], 'new': title}
# Update description if provided
if description is not None and description != document.description:
document.description = description
changes['description'] = {'old': original_values['description'], 'new': description}
# Update status if provided
if status is not None and status != document.status:
# Convert to status code if a name was provided
status_code = settings.get_document_status_code(status)
# Validate status
if not settings.is_valid_document_status(status_code):
raise ValidationError(f"Invalid document status: {status}")
# Check if status transition is allowed
if not settings.is_valid_status_transition(document.status, status_code):
raise BusinessRuleError(f"Invalid status transition from {document.status} to {status_code}")
# Check if user has permission for this status change
status_perm = f"CHANGE_STATUS_TO_{status_code}"
if not permissions.user_has_permission(user, status_perm):
raise PermissionError(f"User does not have permission to change status to {status_code}")
# Update status
document.status = status_code
changes['status'] = {'old': original_values['status'], 'new': status_code}
# Update owner if provided
# ...
# Return success response with changes
return {
"success": True,
"message": "Document updated successfully",
"document_uid": document_uid,
"changes": changes
}
except (ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError) as e:
# Re-raise known errors
raise
except Exception as e:
logger.error(f"Error updating document: {e}")
raise BusinessRuleError(f"Failed to update document: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
document_uid |
str | - | positional_or_keyword |
title |
Optional[str] | None | positional_or_keyword |
description |
Optional[str] | None | positional_or_keyword |
status |
Optional[str] | None | positional_or_keyword |
owner_uid |
Optional[str] | None | positional_or_keyword |
metadata |
Optional[Dict[str, Any]] | None | positional_or_keyword |
Parameter Details
user: DocUser object representing the authenticated user making the update. Used for permission checks and audit logging.
document_uid: Unique identifier (string) of the document to be updated. Must correspond to an existing ControlledDocument in the system.
title: Optional new title for the document (string). If provided and different from current title, the document title will be updated.
description: Optional new description for the document (string). If provided and different from current description, the document description will be updated.
status: Optional new status for the document (string). Can be either a status name or code. Must be a valid status and the transition from current status must be allowed. User must have permission for the specific status change.
owner_uid: Optional new owner UID (string) for the document. Allows transferring document ownership to another user. Implementation appears incomplete in provided code.
metadata: Optional dictionary containing additional metadata key-value pairs to update on the document. Implementation appears incomplete in provided code.
Return Value
Type: Dict[str, Any]
Returns a dictionary with keys: 'success' (boolean indicating operation success), 'message' (string describing the outcome), 'document_uid' (string echoing the updated document's UID), and 'changes' (dictionary mapping changed field names to objects containing 'old' and 'new' values for audit purposes).
Dependencies
logginguuidostempfiletypingdatetimeiopaneltracebackrandom
Required Imports
import logging
from typing import Dict, List, Any, Optional, Union, BinaryIO, Tuple
from datetime import datetime, timedelta
from CDocs import db
from CDocs.config import settings, permissions
from CDocs.models.document import ControlledDocument, DocumentVersion
from CDocs.models.user_extensions import DocUser
from CDocs.utils import document_processor, audit_trail, notifications
from CDocs.db.schema_manager import NodeLabels, RelTypes
from CDocs.controllers import require_permission, log_controller_action, transaction
from CDocs.controllers import PermissionError, ResourceNotFoundError, ValidationError, BusinessRuleError, IntegrationError
from CDocs.controllers.filecloud_controller import upload_document_to_filecloud, download_document_from_filecloud, get_document_metadata_from_filecloud
from CDocs.db.db_operations import get_document_versions_from_db
from CDocs.db import db_operations
from CDocs.models.review import ReviewCycle
from CDocs.models.approval import Approval
from CDocs.controllers.document_controller import download_document_version
Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import update_document
# Assume user and document already exist
user = DocUser(uid='user123')
document_uid = 'doc-456'
# Update document title and description
result = update_document(
user=user,
document_uid=document_uid,
title='Updated Document Title',
description='This document has been revised'
)
if result['success']:
print(f"Document updated: {result['message']}")
print(f"Changes made: {result['changes']}")
# Update document status
result = update_document(
user=user,
document_uid=document_uid,
status='APPROVED'
)
# Handle potential errors
try:
result = update_document(
user=user,
document_uid='nonexistent',
title='New Title'
)
except ResourceNotFoundError as e:
print(f"Document not found: {e}")
except PermissionError as e:
print(f"Permission denied: {e}")
except ValidationError as e:
print(f"Validation failed: {e}")
except BusinessRuleError as e:
print(f"Business rule violation: {e}")
Best Practices
- This function is decorated with @transaction, so it runs within a database transaction that will rollback on errors
- The function is decorated with @require_permission('EDIT_DOCUMENT', 'document_uid'), so permission checks happen before execution
- The function is decorated with @log_controller_action('update_document') for automatic audit logging
- Always handle the specific exception types (ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError) when calling this function
- Only provide parameters you want to update - None values are ignored, allowing partial updates
- Status changes require additional permissions beyond EDIT_DOCUMENT (CHANGE_STATUS_TO_* permissions)
- Status transitions are validated against business rules - not all status changes are allowed from every current status
- The function tracks changes and returns them in the response for audit purposes
- The owner_uid and metadata parameters appear to have incomplete implementations in the provided code
- Ensure the user object has proper authentication and the document_uid exists before calling
- The function will raise exceptions rather than returning error dictionaries, so use try-except blocks
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function update_document_v1 96.1% similar
-
function update_document 95.0% similar
-
function update_document_v3 94.5% similar
-
function update_document_v4 82.6% similar
-
function update_status_after_approval 75.3% similar