function get_document_edit_url_v1
Generates a FileCloud URL to view or edit a controlled document, selecting the appropriate file format (PDF or Word) based on document status and version availability.
/tf/active/vicechatdev/CDocs/controllers/document_controller.py
2362 - 2497
moderate
Purpose
This function retrieves a specific version of a controlled document and generates a FileCloud URL for viewing or editing. It intelligently selects between PDF and Word formats based on document status: published/archived documents prefer PDF for read-only viewing, while editable documents prefer Word format. It also logs document access events for audit trail purposes and handles various error conditions including missing documents, versions, or files.
Source Code
def get_document_edit_url(
document_uid: str,
user: Optional[DocUser] = None,
version_uid: Optional[str] = None
) -> Dict[str, Any]:
"""
Get a URL to view or edit a document in FileCloud.
Works for both editable and non-editable documents.
Parameters
----------
user : DocUser
User requesting the URL
document_uid : str
ID of the document
version_uid : str, optional
ID of a specific version (default is current version)
Returns
-------
Dict[str, Any]
Dictionary with the view/edit URL
"""
try:
# Get document
document = ControlledDocument(uid=document_uid)
if not document:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Get version
version = None
if version_uid:
version = DocumentVersion(uid=version_uid)
if not version or version.document_uid != document_uid:
raise ResourceNotFoundError(f"Version not found: {version_uid}")
else:
version = document.current_version
if not version:
raise ResourceNotFoundError(f"No versions found for document: {document_uid}")
# Determine appropriate file path based on document status and version availability
file_path = None
is_editable = False
file_type = "PDF"
# For published/archived documents, prefer PDF
if document.status in [STATUS_PUBLISHED, STATUS_EFFECTIVE, STATUS_ARCHIVED, STATUS_OBSOLETE]:
if version.pdf_file_path:
file_path = version.pdf_file_path
is_editable = False
file_type = "PDF"
elif version.word_file_path:
file_path = version.word_file_path
is_editable = True
file_type = "Editable"
# For editable documents, prefer Word format
elif document.is_editable():
if version.word_file_path:
file_path = version.word_file_path
is_editable = True
file_type = "Editable"
elif version.pdf_file_path:
file_path = version.pdf_file_path
is_editable = False
file_type = "PDF"
# For any other case, use whatever is available
else:
if version.pdf_file_path:
file_path = version.pdf_file_path
is_editable = False
file_type = "PDF"
elif version.word_file_path:
file_path = version.word_file_path
is_editable = True
file_type = "Editable"
if not file_path:
raise BusinessRuleError("No file available for this document version")
# Generate URL for FileCloud
try:
filename = os.path.basename(file_path)
# Escape spaces in filename with + for the first part
encoded_filename = filename.replace(' ', '+')
# Encode path for the second part (after #expl-tabl.)
# Extract directory path without filename
directory_path = os.path.dirname(file_path)
# Ensure path ends with '/'
if directory_path and not directory_path.endswith('/'):
directory_path += '/'
encoded_path = directory_path.replace(' ', '%20')
# Construct the full URL
file_url = f"https://filecloud.vicebio.com/ui/core/index.html?filter={encoded_filename}#expl-tabl.{encoded_path}"
# Log access event
try:
event_type = "DOCUMENT_VIEWED"
audit_trail.log_document_lifecycle_event(
event_type=event_type,
user=user,
document_uid=document_uid,
details={
"version_uid": version.uid,
"version_number": version.version_number,
"file_type": file_type,
"is_editable": is_editable
}
)
except Exception as audit_err:
logger.warning(f"Failed to log document view event: {str(audit_err)}")
return {
'success': True,
'document_uid': document_uid,
'document_number': document.doc_number,
'version_uid': version.uid,
'version_number': version.version_number,
'edit_url': file_url,
'file_type': file_type,
'is_editable': is_editable,
'can_edit': document.is_editable() and is_editable
}
except Exception as e:
logger.error(f"Error generating URL: {str(e)}")
raise BusinessRuleError(f"Failed to generate URL: {str(e)}")
except (ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError) as e:
# Re-raise known errors
raise
except Exception as e:
logger.error(f"Error getting document URL: {str(e)}")
raise BusinessRuleError(f"Failed to get URL: {str(e)}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
document_uid |
str | - | positional_or_keyword |
user |
Optional[DocUser] | None | positional_or_keyword |
version_uid |
Optional[str] | None | positional_or_keyword |
Parameter Details
document_uid: Unique identifier (string) of the controlled document to retrieve. Must correspond to an existing ControlledDocument in the system.
user: Optional DocUser object representing the user requesting the URL. Used for audit logging of document access events. Can be None if user context is not available.
version_uid: Optional unique identifier (string) for a specific document version. If not provided, the current/latest version of the document will be used. Must belong to the specified document if provided.
Return Value
Type: Dict[str, Any]
Returns a dictionary containing: 'success' (bool, always True on success), 'document_uid' (str), 'document_number' (str), 'version_uid' (str), 'version_number' (str/int), 'edit_url' (str, the FileCloud URL), 'file_type' (str, either 'PDF' or 'Editable'), 'is_editable' (bool, whether the file format is editable), and 'can_edit' (bool, whether user can edit based on document status and file type). Raises ResourceNotFoundError if document/version not found, BusinessRuleError if no file available or URL generation fails.
Dependencies
loggingostypingCDocs.models.documentCDocs.models.user_extensionsCDocs.utils.audit_trailCDocs.controllersCDocs.models.document_status
Required Imports
import os
from typing import Dict, Any, Optional
from CDocs.models.document import ControlledDocument, DocumentVersion
from CDocs.models.user_extensions import DocUser
from CDocs.utils import audit_trail
from CDocs.controllers import ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError
from CDocs.models.document_status import STATUS_PUBLISHED, STATUS_EFFECTIVE, STATUS_ARCHIVED, STATUS_OBSOLETE
import logging
Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import get_document_edit_url
# Get URL for current version of a document
user = DocUser(uid='user123')
result = get_document_edit_url(
document_uid='doc-uuid-12345',
user=user
)
print(f"Document URL: {result['edit_url']}")
print(f"File type: {result['file_type']}")
print(f"Can edit: {result['can_edit']}")
# Get URL for specific version
result = get_document_edit_url(
document_uid='doc-uuid-12345',
user=user,
version_uid='version-uuid-67890'
)
print(f"Version {result['version_number']} URL: {result['edit_url']}")
Best Practices
- Always handle ResourceNotFoundError and BusinessRuleError exceptions when calling this function
- Provide user parameter when available for proper audit trail logging
- The function prioritizes PDF for published/archived documents and Word for editable documents - understand this logic when interpreting results
- Check the 'can_edit' field in the response to determine if the user should be allowed to edit the document
- The generated URL uses FileCloud-specific URL encoding (+ for spaces in filename, %20 in path) - do not modify the URL format
- Audit logging failures are logged as warnings but do not prevent URL generation - monitor logs for audit issues
- The function requires that documents have either a PDF or Word file path - ensure files are properly uploaded before calling
- URL generation assumes FileCloud server at 'https://filecloud.vicebio.com' - modify if using different server
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_document_edit_url 91.9% similar
-
function get_document_download_url 84.3% similar
-
function download_document_version 77.6% similar
-
function download_document_version_v1 76.0% similar
-
function convert_document_to_pdf_v1 75.1% similar