🔍 Code Extractor

function create_document_v3

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 specific metadata, ownership, and lifecycle status.

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 representing the document owner. This should be a valid DocUser instance or a user identifier that can be resolved to a user in the system.

title: String representing the document title. This is a required field that will be used as the primary identifier 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. Default is None.

doc_type: Optional document type identifier. Can be either a document type code (short identifier) or full name. The function will resolve it to the appropriate code using settings. Default is None.

department: Optional department identifier. Can be either a department code (short identifier) or full name. The function will resolve it to the appropriate code using settings. Default is None.

status: String representing the initial document status. Default is 'DRAFT'. Should be one of the valid document status values (DRAFT, IN_REVIEW, IN_APPROVAL, APPROVED, PUBLISHED, EFFECTIVE, ARCHIVED, OBSOLETE).

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

Return Value

Returns a dictionary with status information. On success: {'status': 'success', 'message': 'Document created successfully', 'document': {document_details}} where document_details includes uid, title, doc_number, doc_type, department, created_date, and status. On failure: {'status': 'error', 'message': error_description}. The return type is always a dictionary with 'status' and 'message' keys.

Dependencies

  • logging
  • uuid
  • os
  • tempfile
  • typing
  • datetime
  • io
  • panel
  • shutil
  • traceback
  • CDocs

Required Imports

import logging
import traceback

Conditional/Optional Imports

These imports are only needed under specific conditions:

from CDocs.config import settings

Condition: Always required - used to resolve document type and department codes

Required (conditional)
from CDocs.models.document import ControlledDocument

Condition: Always required - used to create the document instance

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='QA',
    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='GUIDE',
    department='SAFETY',
    properties={
        'priority': 'high',
        'tags': ['safety', 'compliance'],
        'review_cycle_days': 365
    }
)

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
  • When passing additional properties, ensure they are in a dictionary format and don't conflict with reserved property names (title, status, docType, department, content)
  • The function logs errors automatically, but consider implementing additional error handling in calling code
  • Ensure the user object or ID is valid before calling this function to avoid creation failures
  • The function is transactional - if document creation fails, no partial data will be persisted
  • Document numbers are auto-generated by the ControlledDocument.create() method
  • Consider validating document type and department codes exist in your settings before calling this function to provide better user feedback

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_document_v4 91.2% similar

    Creates a new controlled document in the CDocs system with specified metadata, content, and properties, returning a status dictionary with the created document details.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function create_document 80.7% 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 create_controlled_document 74.8% similar

    Creates a new controlled document node in a graph database with metadata, establishes relationships with the CDocs root node, and returns a ControlledDocument instance.

    From: /tf/active/vicechatdev/CDocs/FC_sync.py
  • function create_document_legacy 74.2% similar

    Creates a new controlled document in a document management system with versioning, audit trails, and notifications. Generates document nodes in a graph database with relationships to users and versions.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function create_document_v2 72.4% similar

    Creates a new version of a controlled document by generating version metadata, storing the file in FileCloud, updating the document's revision number, and creating an audit trail entry.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
← Back to Browse