function archive_document_v2
Archives a controlled document by changing its status to ARCHIVED, recording audit information, and notifying relevant parties.
/tf/active/vicechatdev/CDocs copy/controllers/document_controller.py
1064 - 1151
moderate
Purpose
This function manages the document archiving workflow in a controlled document management system. It validates that the document exists and is in an archivable state (PUBLISHED or EFFECTIVE), updates the document status to ARCHIVED, stores archiving metadata (who, when, why), logs the lifecycle event for audit purposes, and sends notifications. It enforces business rules and permissions through decorators, ensuring only authorized users can archive documents and that archiving occurs within a database transaction.
Source Code
def archive_document(
user: DocUser,
document_uid: str,
archive_reason: str,
archive_comment: Optional[str] = None
) -> Dict[str, Any]:
"""
Archive a document, changing its status to ARCHIVED.
Args:
user: User archiving the document
document_uid: UID of document to archive
archive_reason: Reason for archiving
archive_comment: Optional comment about archiving
Returns:
Dictionary with archive status
Raises:
ResourceNotFoundError: If document not found
ValidationError: If validation fails
PermissionError: If user doesn't have permission
BusinessRuleError: If archiving is not allowed
"""
try:
# Get document instance
document = ControlledDocument(uid=document_uid)
if not document:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Check if document can be archived
if document.status not in ["PUBLISHED", "EFFECTIVE"]:
raise BusinessRuleError(f"Cannot archive document with status {document.status}")
# Validate archive reason
if not archive_reason:
raise ValidationError("Archive reason is required")
# Store previous status for audit
previous_status = document.status
# Update document
document.status = "ARCHIVED"
document.modified_date = datetime.now()
# Add archive info to metadata
document.metadata = document.metadata or {}
document.metadata["archived_by"] = user.username
document.metadata["archived_date"] = datetime.now().isoformat()
document.metadata["archive_reason"] = archive_reason
document.metadata["archive_comment"] = archive_comment
# Save changes
document.save()
# Log archive event
audit_trail.log_document_lifecycle_event(
event_type="DOCUMENT_ARCHIVED",
user=user,
document_uid=document_uid,
details={
"previous_status": previous_status,
"archive_reason": archive_reason,
"archive_comment": archive_comment
}
)
# Notify about archiving
notifications.notify_document_update(document, "DOCUMENT_STATUS_CHANGED")
return {
"success": True,
"document_uid": document_uid,
"document_number": document.doc_number,
"title": document.title,
"previous_status": previous_status,
"new_status": "ARCHIVED",
"archive_reason": archive_reason,
"archive_comment": archive_comment,
"message": f"Document {document.doc_number} archived successfully"
}
except (ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError) as e:
# Re-raise known errors
raise
except Exception as e:
logger.error(f"Error archiving document {document_uid}: {e}")
raise BusinessRuleError(f"Failed to archive document: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
document_uid |
str | - | positional_or_keyword |
archive_reason |
str | - | positional_or_keyword |
archive_comment |
Optional[str] | None | positional_or_keyword |
Parameter Details
user: DocUser object representing the authenticated user performing the archive action. Used for permission checking, audit logging, and recording who archived the document.
document_uid: String containing the unique identifier (UID) of the document to be archived. Must correspond to an existing ControlledDocument in the system.
archive_reason: Required string explaining why the document is being archived. Cannot be empty. Examples: 'Superseded by newer version', 'No longer applicable', 'Regulatory change'.
archive_comment: Optional string providing additional context or details about the archiving decision. Can be None if no additional comments are needed.
Return Value
Type: Dict[str, Any]
Returns a dictionary containing archive operation results. Keys include: 'success' (bool, always True on successful completion), 'document_uid' (str, the archived document's UID), 'document_number' (str, the document's number/identifier), 'title' (str, document title), 'previous_status' (str, status before archiving like 'PUBLISHED' or 'EFFECTIVE'), 'new_status' (str, always 'ARCHIVED'), 'archive_reason' (str, the provided reason), 'archive_comment' (str or None, the provided comment), and 'message' (str, success message).
Dependencies
logginguuidostempfiletypingdatetimeiopanelCDocs
Required Imports
from typing import Dict, Any, Optional
from datetime import datetime
from CDocs.models.document import ControlledDocument
from CDocs.models.user_extensions import DocUser
from CDocs.utils import audit_trail
from CDocs.utils import notifications
from CDocs.controllers import require_permission, log_controller_action, transaction
from CDocs.controllers import ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError
import logging
Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import archive_document
# Assuming user and document_uid are already obtained
user = DocUser(username='john.doe')
document_uid = 'doc-12345-abcde'
try:
result = archive_document(
user=user,
document_uid=document_uid,
archive_reason='Superseded by version 2.0',
archive_comment='New regulatory requirements implemented in v2.0'
)
print(f"Success: {result['message']}")
print(f"Document {result['document_number']} status changed from {result['previous_status']} to {result['new_status']}")
except ResourceNotFoundError as e:
print(f"Document not found: {e}")
except ValidationError as e:
print(f"Validation error: {e}")
except PermissionError as e:
print(f"Permission denied: {e}")
except BusinessRuleError as e:
print(f"Business rule violation: {e}")
Best Practices
- Always provide a meaningful archive_reason as it is required and used for audit purposes
- Ensure the user has the 'ARCHIVE_DOCUMENT' permission before calling this function (enforced by decorator)
- Only documents with status 'PUBLISHED' or 'EFFECTIVE' can be archived; attempting to archive documents in other states will raise BusinessRuleError
- The function operates within a database transaction (via decorator), so failures will rollback all changes
- Archive metadata is stored in the document's metadata field and includes timestamp, user, reason, and comment
- Handle all four exception types (ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError) appropriately in calling code
- The function logs audit events automatically; no additional logging needed by caller
- Notifications are sent automatically to relevant parties about the status change
- The archive_reason should be descriptive enough for future reference and compliance purposes
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function archive_document_v1 95.6% similar
-
function archive_document 93.4% similar
-
function publish_document_v2 71.8% similar
-
function delete_document 70.9% similar
-
function publish_document_v3 69.0% similar