function set_current_version
Sets a specific version of a controlled document as the current/active version, updating the document's currentVersionUID property and logging the change.
/tf/active/vicechatdev/document_controller_backup.py
797 - 888
moderate
Purpose
This function manages document version control by allowing authorized users to designate which version of a document should be considered current. It validates that both the document and version exist, checks if the version is already current to avoid redundant updates, maintains an audit trail of version changes, and notifies relevant parties of the update. This is critical for document management systems where tracking the active version of controlled documents is essential for compliance and operational purposes.
Source Code
def set_current_version(
user: DocUser,
document_uid: str,
version_uid: str
) -> Dict[str, Any]:
"""
Set the current version of a document.
Args:
user: User setting the current version
document_uid: UID of document
version_uid: UID of version to set as current
Returns:
Dictionary with update status
Raises:
ResourceNotFoundError: If document or version not found
PermissionError: If user doesn't have permission
BusinessRuleError: If operation is not allowed
"""
try:
# Get document instance
document = ControlledDocument(uid=document_uid)
if not document:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Get version instance
version = DocumentVersion(uid=version_uid)
if not version or version.document_uid != document_uid:
raise ResourceNotFoundError(f"Version not found for document: {version_uid}")
# Check if already the current version - use direct property comparison
# instead of calling a method that might not exist
current_version_uid = getattr(document, 'currentVersionUID', None)
if current_version_uid and current_version_uid == version_uid:
return {
"success": True,
"document_uid": document_uid,
"version_uid": version_uid,
"message": f"Version {version.version_number} is already the current version"
}
# Store previous current version for audit
previous_version = document.current_version
previous_version_uid = previous_version.uid if previous_version else None
previous_version_number = previous_version.version_number if previous_version else None
# Set as current version - use direct database update instead of calling a method
# that might not exist
from CDocs.db import db_operations
update_result = db_operations.update_node(
document_uid,
{'currentVersionUID': version_uid}
)
if not update_result:
raise BusinessRuleError("Failed to update document with new current version")
# Log event
audit_trail.log_document_lifecycle_event(
event_type="DOCUMENT_CURRENT_VERSION_CHANGED",
user=user,
document_uid=document_uid,
details={
"previous_version_uid": previous_version_uid,
"previous_version_number": previous_version_number,
"new_version_uid": version_uid,
"new_version_number": version.version_number
}
)
# Notify about version change
notifications.notify_document_update(document, "DOCUMENT_UPDATED")
return {
"success": True,
"document_uid": document_uid,
"version_uid": version_uid,
"message": f"Version {version.version_number} set as current version",
"previous_version": {
"uid": previous_version_uid,
"version_number": previous_version_number
} if previous_version_uid else None
}
except (ResourceNotFoundError, PermissionError, BusinessRuleError) as e:
# Re-raise known errors
raise
except Exception as e:
logger.error(f"Error setting current version: {e}")
raise BusinessRuleError(f"Failed to set current version: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
document_uid |
str | - | positional_or_keyword |
version_uid |
str | - | positional_or_keyword |
Parameter Details
user: DocUser object representing the authenticated user performing the version change. Must have MANAGE_VERSIONS permission for the specified document. Used for audit logging and permission validation.
document_uid: String containing the unique identifier (UID) of the controlled document whose current version is being changed. Must correspond to an existing ControlledDocument in the database.
version_uid: String containing the unique identifier (UID) of the DocumentVersion to set as current. Must belong to the specified document (version.document_uid must match document_uid).
Return Value
Type: Dict[str, Any]
Returns a dictionary with keys: 'success' (boolean indicating operation success), 'document_uid' (echoed document UID), 'version_uid' (echoed version UID), 'message' (human-readable status message including version number), and optionally 'previous_version' (dictionary with 'uid' and 'version_number' of the previously current version, or None if no previous version existed). On success, success=True; on failure, raises an exception rather than returning success=False.
Dependencies
logginguuidostempfiletypingdatetimeiopanelshutiltracebackCDocsconfig
Required Imports
from typing import Dict, Any
from CDocs.models.document import ControlledDocument, DocumentVersion
from CDocs.models.user_extensions import DocUser
from CDocs.utils import audit_trail, notifications
from CDocs.db import db_operations
from CDocs.controllers import require_permission, log_controller_action, transaction
from CDocs.controllers import ResourceNotFoundError, PermissionError, BusinessRuleError
import logging
Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import set_current_version
# Assuming user, document_uid, and version_uid are already defined
user = DocUser(uid='user123')
document_uid = 'doc-abc-123'
version_uid = 'ver-xyz-456'
try:
result = set_current_version(
user=user,
document_uid=document_uid,
version_uid=version_uid
)
if result['success']:
print(f"Success: {result['message']}")
if result.get('previous_version'):
print(f"Previous version: {result['previous_version']['version_number']}")
except ResourceNotFoundError as e:
print(f"Document or version not found: {e}")
except PermissionError as e:
print(f"Permission denied: {e}")
except BusinessRuleError as e:
print(f"Business rule violation: {e}")
Best Practices
- Always wrap calls in try-except blocks to handle ResourceNotFoundError, PermissionError, and BusinessRuleError exceptions
- Ensure the user has MANAGE_VERSIONS permission before calling (though decorator handles this)
- The function is transactional - all changes are rolled back if any step fails
- Verify that version_uid belongs to the specified document_uid before calling
- The function automatically logs audit events and sends notifications - no additional logging needed
- Check the 'success' field in the returned dictionary to confirm the operation completed
- If the version is already current, the function returns success without making changes
- The function uses direct database operations (db_operations.update_node) rather than model methods for reliability
- Previous version information is included in the response for rollback or audit purposes
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_document_v2 74.2% similar
-
function download_document_version 68.4% similar
-
function create_document_v2 67.6% similar
-
function get_document_edit_url_v1 67.2% similar