🔍 Code Extractor

function create_document_v2

Maturity: 55

Creates a new controlled document in a document management system with specified properties, type, department, and status.

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
2521 - 2602
Complexity:
moderate

Purpose

This function serves as the primary entry point for creating controlled documents in the CDocs system. It handles document creation with validation of document types and departments, sets initial properties, and returns comprehensive status information. The function is designed for document management workflows where documents need to be tracked with metadata like type, department, owner, and status throughout their lifecycle.

Source Code

def create_document(user, title, doc_text=None, doc_type=None, department=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,
            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
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 will be displayed as the document's name.

doc_text: Optional string containing the document's content/body text. If provided, it will be stored in the 'content' property of the document. Default is None.

doc_type: Optional document type identifier. Can be either a document type code (short identifier) or full name. The function will convert full names to codes using settings. Default is None.

department: Optional department identifier. Can be either a department code (short identifier) or full name. The function will convert full names to codes using settings. Default is None.

status: String representing the initial document status. Default is 'DRAFT'. Common values include DRAFT, IN_REVIEW, IN_APPROVAL, APPROVED, PUBLISHED, EFFECTIVE, ARCHIVED, OBSOLETE.

properties: Optional dictionary containing additional custom properties to be added to the document. These properties will be merged with the base properties. Default is None.

Return Value

Returns a dictionary with status information. On success: {'status': 'success', 'message': 'Document created successfully', 'document': {dict with uid, title, doc_number, doc_type, department, created_date, status}}. On failure: {'status': 'error', 'message': 'error description string'}. The document dictionary contains all key metadata needed to reference and work with the newly created document.

Dependencies

  • logging
  • uuid
  • os
  • tempfile
  • typing
  • datetime
  • io
  • panel
  • shutil
  • traceback
  • CDocs
  • CDocs.config
  • CDocs.models.document
  • CDocs.models.user_extensions
  • CDocs.utils
  • CDocs.db.schema_manager
  • CDocs.controllers
  • CDocs.controllers.filecloud_controller
  • CDocs.db.db_operations
  • CDocs.utils.document_converter
  • CDocs.models.document_status
  • CDocs.utils.filecloud_integration
  • CDocs.models.review
  • CDocs.models.approval
  • config

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 get 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: used for error logging when exceptions occur

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_id('user123')

# Create a simple document
result = create_document(
    user=user,
    title='Quality Assurance Procedure',
    doc_text='This document describes the QA process...',
    doc_type='SOP',
    department='Quality',
    status='DRAFT'
)

if result['status'] == 'success':
    doc_uid = result['document']['uid']
    doc_number = result['document']['doc_number']
    print(f"Document created: {doc_number} (UID: {doc_uid})")
else:
    print(f"Error: {result['message']}")

# Create with additional properties
result = create_document(
    user=user,
    title='Safety Guidelines',
    doc_type='GUIDELINE',
    department='EHS',
    properties={
        'priority': 'high',
        'review_frequency': 'annual',
        'tags': ['safety', 'compliance']
    }
)

Best Practices

  • Always check the 'status' field in the returned dictionary before accessing the 'document' field to handle errors gracefully
  • Provide either document type codes or full names - the function will handle conversion automatically
  • Use the default 'DRAFT' status for new documents unless there's a specific workflow requirement
  • The 'properties' parameter allows extending document metadata without modifying the function signature
  • Ensure the user object or ID is valid before calling this function to avoid creation failures
  • The function logs errors automatically, but consider additional application-level logging for audit trails
  • Document UIDs returned in the response should be stored for future document operations
  • Handle exceptions at the calling level as the function returns error dictionaries rather than raising exceptions
  • The function performs code normalization (full names to codes) so either format can be used for doc_type and department

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_document 80.3% similar

    Creates a new controlled document in a document management system with versioning, audit trails, and optional initial content.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function update_document 71.8% similar

    Updates properties of a controlled document including title, description, status, owner, and metadata, with special handling for status transitions that require format conversions or publishing workflows.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function create_document_v1 65.3% similar

    Creates a new version of an existing document in a document management system, storing the file in FileCloud and tracking version metadata in Neo4j graph database.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function clone_document 64.7% similar

    Clones an existing controlled document to create either a new independent document or a new revision of the same document, optionally including the document's content.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function delete_document 63.4% similar

    Deletes a controlled document from the system with permission checks, status validation, and audit logging.

    From: /tf/active/vicechatdev/document_controller_backup.py
← Back to Browse