function update_approval_comment_v1
Updates an existing approval comment in a document approval workflow, allowing modification of comment text and status (e.g., marking as resolved) with permission checks and audit logging.
/tf/active/vicechatdev/CDocs/controllers/approval_controller_bis.py
543 - 625
moderate
Purpose
This function manages the update lifecycle of approval comments within a document approval cycle. It enforces permission-based access control where only the comment author can update text, while approvers and users with MANAGE_APPROVALS permission can update status. It maintains audit trails for compliance and creates a complete record of comment modifications.
Source Code
def update_approval_comment(
user: DocUser,
comment_uid: str,
comment_text: Optional[str] = None,
status: Optional[str] = None
) -> Dict[str, Any]:
"""
Update an existing approval comment.
Args:
user: The user updating the comment
comment_uid: UID of the comment
comment_text: New text for the comment
status: New status for the comment (e.g. RESOLVED)
Returns:
Dictionary with success flag and updated comment
"""
try:
# Get comment
comment = ApprovalComment(uid=comment_uid)
if not comment:
raise ResourceNotFoundError("Comment not found")
# Get approval cycle
approval_cycle = ApprovalCycle(uid=comment.approval_cycle_uid)
if not approval_cycle:
raise ResourceNotFoundError("Approval cycle not found")
# Check permissions
is_commenter = comment.commenter_uid == user.uid
is_approver = approval_cycle.is_approver(user.uid)
has_permission = permissions.user_has_permission(user, "MANAGE_APPROVALS")
# Only comment author, approvers, or users with manage permissions can update comments
if not (is_commenter or is_approver or has_permission):
raise PermissionError("You do not have permission to update this comment")
# Update comment text if provided (only author can update text)
if comment_text is not None:
if not is_commenter and not has_permission:
raise PermissionError("Only the comment author can update comment text")
# Update the comment text
comment._data['text'] = comment_text
comment.save()
# Update status if provided (e.g. marking as resolved)
if status is not None:
if status == 'RESOLVED':
comment.resolution = "Marked as resolved"
# Create audit trail entry
document_uid = approval_cycle.document_uid
if document_uid:
audit_trail.log_event(
user=user,
resource_uid=document_uid,
resource_type='AppovalCycle',
event_type="APPROVAL_COMMENT_UPDATED",
details={
"approval_cycle_uid": approval_cycle.uid,
"comment_uid": comment.uid,
"updated_text": comment_text is not None,
"updated_status": status
}
)
return {
"success": True,
"message": "Comment updated successfully",
"comment": comment.to_dict()
}
except (ResourceNotFoundError, PermissionError) as e:
logger.warning(f"Error updating approval comment: {e}")
return {"success": False, "message": str(e)}
except Exception as e:
logger.error(f"Unexpected error updating approval comment: {e}")
import traceback
logger.error(traceback.format_exc())
return {"success": False, "message": "An unexpected error occurred"}
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
comment_uid |
str | - | positional_or_keyword |
comment_text |
Optional[str] | None | positional_or_keyword |
status |
Optional[str] | None | positional_or_keyword |
Parameter Details
user: DocUser object representing the authenticated user attempting to update the comment. Used for permission validation and audit logging.
comment_uid: Unique identifier (string) of the ApprovalComment to be updated. Must correspond to an existing comment in the system.
comment_text: Optional string containing the new text content for the comment. If provided, only the original comment author or users with MANAGE_APPROVALS permission can update it. Pass None to leave text unchanged.
status: Optional string representing the new status for the comment. Currently supports 'RESOLVED' to mark comments as resolved. Pass None to leave status unchanged.
Return Value
Type: Dict[str, Any]
Returns a dictionary with keys: 'success' (boolean indicating operation success), 'message' (string with human-readable result description), and optionally 'comment' (dictionary representation of the updated comment via to_dict() method). On failure, only 'success' and 'message' keys are present.
Dependencies
CDocstypingdatetimeloggingtraceback
Required Imports
from typing import Dict, Any, Optional
import logging
from CDocs.models.approval import ApprovalComment, ApprovalCycle
from CDocs.models.user_extensions import DocUser
from CDocs.config import permissions
from CDocs.utils import audit_trail
from CDocs.controllers import log_controller_action, PermissionError, ResourceNotFoundError
Conditional/Optional Imports
These imports are only needed under specific conditions:
import traceback
Condition: Used in exception handling blocks for detailed error logging when unexpected errors occur
Required (conditional)Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.approval_controller import update_approval_comment
# Get authenticated user
user = DocUser(uid='user_123')
# Update comment text only
result = update_approval_comment(
user=user,
comment_uid='comment_456',
comment_text='Updated comment with additional feedback'
)
if result['success']:
print(f"Comment updated: {result['comment']['text']}")
else:
print(f"Error: {result['message']}")
# Mark comment as resolved
result = update_approval_comment(
user=user,
comment_uid='comment_456',
status='RESOLVED'
)
# Update both text and status
result = update_approval_comment(
user=user,
comment_uid='comment_456',
comment_text='Final version looks good',
status='RESOLVED'
)
Best Practices
- Always check the 'success' field in the returned dictionary before accessing the 'comment' field to avoid KeyError
- Only the original comment author can update comment text unless they have MANAGE_APPROVALS permission
- Approvers in the approval cycle and users with MANAGE_APPROVALS permission can update comment status
- The function uses the @log_controller_action decorator for automatic action logging
- All updates are logged to the audit trail with the resource type 'AppovalCycle' (note: typo in original code)
- Pass None for parameters you don't want to update rather than omitting them
- Handle PermissionError and ResourceNotFoundError exceptions appropriately in calling code
- The function returns error messages in the dictionary rather than raising exceptions for easier API integration
- Status updates currently support 'RESOLVED' - check documentation for other supported statuses
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function update_approval_comment 92.7% similar
-
function update_review_comment 84.6% similar
-
function add_approval_comment_v1 79.3% similar
-
function add_approval_comment 77.1% similar
-
function update_status_after_approval 74.3% similar