function create_controlled_document
Creates a new controlled document node in a graph database with metadata, establishes relationships with the CDocs root node, and returns a ControlledDocument instance.
/tf/active/vicechatdev/CDocs/FC_sync.py
194 - 274
moderate
Purpose
This function is the primary entry point for creating controlled documents in a document management system. It handles document metadata extraction, generates unique identifiers, creates a graph database node with properties, establishes hierarchical relationships with the CDocs root, and instantiates a ControlledDocument object. It's designed for quality assurance and compliance systems where document control, versioning, and audit trails are critical. The function supports custom document paths, department categorization, and document type classification (e.g., SOP, Work Instructions).
Source Code
def create_controlled_document(metadata: Dict, file_path: str, admin_user: DocUser) -> Optional[ControlledDocument]:
"""
Create a new controlled document in the system.
Args:
metadata: Document metadata
file_path: Path to the document file in FileCloud
admin_user: Admin user performing the action
Returns:
ControlledDocument: Created document or None if creation failed
"""
try:
# Extract fields
doc_uid = metadata.get("doc_uid", str(uuid.uuid4()))
title = metadata.get("title", "Untitled Document")
doc_type = metadata.get("doc_type", "SOP")
department = metadata.get("department", "QA")
doc_number = metadata.get("doc_number", "")
status = metadata.get("status", "DRAFT")
custom_path = metadata.get("custom_path", "")
cdoc_uid = metadata.get("cdoc_uid", str(uuid.uuid4()))
revision= metadata.get("revision", "0.0")
# Create document properties
properties = {
"UID": doc_uid,
"docNumber": doc_number,
"title": title,
"docType": doc_type,
"department": department,
"status": status,
"revision": "0.1",
"createdDate": datetime.now(),
"modifiedDate": datetime.now(),
"isPublic": False
}
# Add custom_path property if provided
if custom_path:
properties["custom_path"] = custom_path
logger.info(f"Using custom path for document: {custom_path}")
# Set owner and creator information
if admin_user:
properties["ownerUID"] = admin_user.uid
properties["creatorUID"] = admin_user.uid
if hasattr(admin_user, 'name'):
properties["ownerName"] = admin_user.name
properties["creatorName"] = admin_user.name
# Create document node
logger.debug(f"Creating document node with properties: {properties}")
doc_data = db.create_node("ControlledDocument", properties)
if not doc_data:
logger.error("Failed to create document node")
return None
# Find CDocs root node and create relationship
cdocs_result = db.run_query("MATCH (c:CDocs) RETURN c.UID as uid LIMIT 1")
if cdocs_result and 'uid' in cdocs_result[0]:
db.create_relationship(
cdocs_result[0]['uid'],
properties["UID"],
"HAS_DOCUMENT"
)
else:
logger.warning("CDocs root node not found, document won't be connected to the root")
# Create document instance
document = ControlledDocument(doc_data)
logger.info(f"Created controlled document: {doc_number} - {title}")
return document
except Exception as e:
logger.error(f"Error creating controlled document: {e}")
import traceback
logger.error(traceback.format_exc())
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
metadata |
Dict | - | positional_or_keyword |
file_path |
str | - | positional_or_keyword |
admin_user |
DocUser | - | positional_or_keyword |
Parameter Details
metadata: Dictionary containing document metadata fields. Expected keys include: 'doc_uid' (unique document identifier, auto-generated if missing), 'title' (document title, defaults to 'Untitled Document'), 'doc_type' (document classification like 'SOP', defaults to 'SOP'), 'department' (owning department, defaults to 'QA'), 'doc_number' (human-readable document number), 'status' (document lifecycle status, defaults to 'DRAFT'), 'custom_path' (optional custom storage path in FileCloud), 'cdoc_uid' (controlled document UID), and 'revision' (version number, defaults to '0.0'). All fields are optional with sensible defaults.
file_path: String representing the path to the document file in FileCloud storage system. This parameter is accepted but not actively used in the current implementation - it appears to be reserved for future file handling functionality or used by calling functions.
admin_user: DocUser object representing the administrator performing the document creation action. Must have 'uid' attribute for ownership tracking. Optional 'name' attribute is used if available for human-readable creator/owner names. Can be None, though this will result in documents without owner/creator information.
Return Value
Type: Optional[ControlledDocument]
Returns a ControlledDocument instance if creation succeeds, containing the newly created document with all properties set including auto-generated UIDs, timestamps, and relationships. Returns None if document creation fails at any stage (node creation failure, database errors, or exceptions). The ControlledDocument object provides methods for document lifecycle management, version control, and metadata access.
Dependencies
uuiddatetimeloggingtracebacktypingCDocs.db.db_operationsCDocs.models.documentCDocs.models.user_extensions
Required Imports
import uuid
from datetime import datetime
from typing import Dict, Optional
from CDocs.db import db_operations as db
from CDocs.models.document import ControlledDocument
from CDocs.models.user_extensions import DocUser
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
import traceback
Condition: only used in exception handling for detailed error logging
OptionalUsage Example
from datetime import datetime
from typing import Dict, Optional
import uuid
from CDocs.db import db_operations as db
from CDocs.models.document import ControlledDocument
from CDocs.models.user_extensions import DocUser
import logging
# Setup logger
logger = logging.getLogger(__name__)
# Create admin user
admin = DocUser({'uid': 'user123', 'name': 'John Admin'})
# Prepare document metadata
metadata = {
'title': 'Quality Control Procedure',
'doc_type': 'SOP',
'department': 'QA',
'doc_number': 'QA-SOP-001',
'status': 'DRAFT',
'custom_path': '/quality/procedures',
'revision': '1.0'
}
# Create controlled document
document = create_controlled_document(
metadata=metadata,
file_path='/filecloud/documents/QA-SOP-001.pdf',
admin_user=admin
)
if document:
print(f'Document created: {document.doc_number}')
print(f'Document UID: {document.uid}')
else:
print('Failed to create document')
Best Practices
- Always provide a DocUser object with valid 'uid' attribute to ensure proper ownership tracking and audit trails
- Include 'doc_number' in metadata for human-readable document identification, as auto-generated UIDs are not user-friendly
- Ensure the CDocs root node exists in the database before calling this function to maintain proper document hierarchy
- Handle None return values appropriately - check if document creation succeeded before proceeding with additional operations
- Use meaningful 'status' values that align with your document lifecycle workflow (e.g., 'DRAFT', 'REVIEW', 'APPROVED', 'OBSOLETE')
- The 'file_path' parameter is currently unused in the implementation but should be provided for future compatibility
- Monitor logs for warnings about missing CDocs root node, as this indicates documents won't be properly connected to the hierarchy
- Consider wrapping calls in try-except blocks even though the function handles exceptions internally, as database connectivity issues may occur
- The function sets revision to '0.1' regardless of the metadata 'revision' value - be aware of this override behavior
- Custom paths should follow FileCloud path conventions if provided in metadata
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_document 82.4% similar
-
function create_document_legacy 81.2% similar
-
function create_document_v4 76.7% similar
-
function create_document_v3 74.8% similar
-
function create_document_v2 66.0% similar