function create_document_v4
Creates a new controlled document in the CDocs system with specified metadata, content, and properties, returning a status dictionary with the created document details.
/tf/active/vicechatdev/CDocs/controllers/document_controller.py
3216 - 3299
moderate
Purpose
This function serves as the primary entry point for creating controlled documents in a document management system. It handles document type and department code resolution, constructs document properties, creates the document record via the ControlledDocument model, and returns structured success/error information. It's designed for use in document management workflows where documents need to be created with specific metadata, ownership, and initial status.
Source Code
def create_document(user, title, doc_text=None, doc_type=None, department=None, doc_number=None,status="DRAFT", properties=None):
"""
Create a new controlled document.
Args:
user: User object or user ID
title: Document title
doc_text: Document content text
doc_type: Document type code or full name
department: Department code or full name
status: Initial document status
properties: Additional document properties
Returns:
Dictionary with created document and status info
"""
from CDocs.config import settings
try:
# Ensure we have valid codes, not full names
doc_type_code = settings.get_document_type_code(doc_type)
dept_code = settings.get_department_code(department)
# Create base properties
doc_props = {
'title': title,
'status': status
}
# Add document type and department
if doc_type_code:
doc_props['docType'] = doc_type_code
if dept_code:
doc_props['department'] = dept_code
# Add document text if provided
if doc_text:
doc_props['content'] = doc_text
# Add additional properties if provided
if properties and isinstance(properties, dict):
doc_props.update(properties)
# Create document
from CDocs.models.document import ControlledDocument
document = ControlledDocument.create(
title=title,
doc_type=doc_type_code,
department=dept_code,
owner=user,
doc_number=doc_number,
properties=doc_props
)
# Return result
if document:
return {
'status': 'success',
'message': 'Document created successfully',
'document': {
'uid': document.uid,
'title': document.title,
'doc_number': document.doc_number,
'doc_type': document.doc_type,
'department': document.department,
'created_date': document.created_date,
'status': document.status
}
}
else:
return {
'status': 'error',
'message': 'Failed to create document'
}
except Exception as e:
logger.error(f"Error creating document: {e}")
import traceback
logger.error(traceback.format_exc())
return {
'status': 'error',
'message': f'Error creating document: {str(e)}'
}
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
- | - | positional_or_keyword |
title |
- | - | positional_or_keyword |
doc_text |
- | None | positional_or_keyword |
doc_type |
- | None | positional_or_keyword |
department |
- | None | positional_or_keyword |
doc_number |
- | None | positional_or_keyword |
status |
- | 'DRAFT' | positional_or_keyword |
properties |
- | None | positional_or_keyword |
Parameter Details
user: User object or user ID that will be set as the document owner. This identifies who created and owns the document.
title: String representing the document title. This is a required field that provides the human-readable name for the document.
doc_text: Optional string containing the document's text content. If provided, it will be stored in the document properties under the 'content' key. Defaults to None.
doc_type: Optional document type identifier, can be either a code (e.g., 'SOP') or full name (e.g., 'Standard Operating Procedure'). The function will resolve this to the appropriate code. Defaults to None.
department: Optional department identifier, can be either a code or full name. The function will resolve this to the appropriate department code. Defaults to None.
doc_number: Optional string for a specific document number. If not provided, the system may auto-generate one based on configuration. Defaults to None.
status: String representing the initial document status. Defaults to 'DRAFT'. Common values include 'DRAFT', 'IN_REVIEW', 'APPROVED', 'PUBLISHED', etc.
properties: Optional dictionary containing additional custom properties to be merged into the document's property set. Must be a dict type if provided. Defaults to None.
Return Value
Returns a dictionary with keys: 'status' (string: 'success' or 'error'), 'message' (string: human-readable status message), and optionally 'document' (dict containing uid, title, doc_number, doc_type, department, created_date, and status fields) on success. On error, only status and message keys are present with error details.
Dependencies
CDocslogging
Required Imports
from CDocs.config import settings
from CDocs.models.document import ControlledDocument
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.config import settings
Condition: imported inside the function to resolve document type and department codes
Required (conditional)from CDocs.models.document import ControlledDocument
Condition: imported inside the function to create the document instance
Required (conditional)import traceback
Condition: imported inside exception handler for detailed error logging
Required (conditional)Usage Example
from CDocs.models.user_extensions import DocUser
from your_module import create_document
# Get or create a user
user = DocUser.get_by_username('john.doe')
# Create a simple document
result = create_document(
user=user,
title='Safety Procedures Manual',
doc_text='This document outlines safety procedures...',
doc_type='SOP',
department='Engineering',
status='DRAFT'
)
if result['status'] == 'success':
doc_uid = result['document']['uid']
print(f"Document created with UID: {doc_uid}")
else:
print(f"Error: {result['message']}")
# Create with additional properties
result = create_document(
user=user,
title='Quality Control Guidelines',
doc_type='QCP',
department='QA',
doc_number='QCP-2024-001',
properties={
'revision': '1.0',
'effective_date': '2024-01-01',
'tags': ['quality', 'compliance']
}
)
if result['status'] == 'success':
print(f"Document {result['document']['doc_number']} created successfully")
Best Practices
- Always check the 'status' field in the returned dictionary before accessing the 'document' field to avoid KeyError on failures
- Provide either document type codes or full names - the function will handle resolution automatically
- Use the properties parameter for custom metadata that doesn't fit standard fields
- The function handles exceptions gracefully and returns error details in the message field
- Ensure the user object/ID is valid before calling this function as it's required for document ownership
- The default status is 'DRAFT' which is appropriate for new documents in most workflows
- Document text (doc_text) is stored in properties['content'], not as a separate field
- The function logs errors with full tracebacks, so ensure logging is properly configured for debugging
- Consider wrapping this call in a try-except block if you need to handle unexpected errors beyond the function's error dictionary
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_document_v3 91.2% similar
-
function create_document 78.1% similar
-
function create_controlled_document 76.7% similar
-
function create_document_legacy 72.3% similar
-
function update_document 69.4% similar