🔍 Code Extractor

function generate_document_number_v1

Maturity: 57

Generates a unique document number by combining document type code, department code, and using a settings-based generation function, with UUID fallback on error.

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
470 - 492
Complexity:
moderate

Purpose

This function creates standardized, unique document identifiers for a document management system. It normalizes document type and department inputs into codes, delegates to a centralized settings function for number generation, and provides error resilience through UUID-based fallback numbering. Used when creating new documents to ensure consistent identification across the system.

Source Code

def generate_document_number(doc_type: str, department: str) -> str:
    """
    Generate a unique document number based on document type and department.
    
    Args:
        doc_type: Document type code or name
        department: Department code or name
        
    Returns:
        Generated document number
    """
    try:
        # Ensure we have codes, not names
        doc_type_code = settings.get_document_type_code(doc_type)
        dept_code = settings.get_department_code(department)
        
        # Use the settings function
        return settings.generate_document_number(doc_type_code, dept_code)
        
    except Exception as e:
        logger.error(f"Error generating document number: {e}")
        # Fallback to a UUID-based number if generation fails
        return f"{doc_type_code}-{dept_code}-{str(uuid.uuid4())[:8]}"

Parameters

Name Type Default Kind
doc_type str - positional_or_keyword
department str - positional_or_keyword

Parameter Details

doc_type: Document type identifier that can be either a code (e.g., 'SOP', 'WI') or full name (e.g., 'Standard Operating Procedure'). The function will normalize this to a code using settings.get_document_type_code(). Expected to be a non-empty string representing a valid document type in the system.

department: Department identifier that can be either a code (e.g., 'ENG', 'QA') or full name (e.g., 'Engineering', 'Quality Assurance'). The function will normalize this to a code using settings.get_department_code(). Expected to be a non-empty string representing a valid department in the system.

Return Value

Type: str

Returns a string containing the generated document number. Under normal operation, returns the result from settings.generate_document_number() which follows the system's document numbering convention. On error, returns a fallback format: '{doc_type_code}-{dept_code}-{8-character-uuid}' (e.g., 'SOP-ENG-a1b2c3d4'). The exact format of successful generation depends on the settings module implementation.

Dependencies

  • uuid
  • logging
  • CDocs.config.settings

Required Imports

import uuid
import logging
from CDocs.config import settings

Usage Example

import uuid
import logging
from CDocs.config import settings

# Ensure logger is configured
logger = logging.getLogger(__name__)

def generate_document_number(doc_type: str, department: str) -> str:
    try:
        doc_type_code = settings.get_document_type_code(doc_type)
        dept_code = settings.get_department_code(department)
        return settings.generate_document_number(doc_type_code, dept_code)
    except Exception as e:
        logger.error(f"Error generating document number: {e}")
        return f"{doc_type_code}-{dept_code}-{str(uuid.uuid4())[:8]}"

# Example usage:
doc_number = generate_document_number('SOP', 'Engineering')
print(f"Generated document number: {doc_number}")

# With codes instead of names:
doc_number2 = generate_document_number('WI', 'QA')
print(f"Generated document number: {doc_number2}")

Best Practices

  • Ensure the settings module has proper implementations of get_document_type_code(), get_department_code(), and generate_document_number() before using this function
  • Configure logging appropriately to capture error messages when document number generation fails
  • The function provides automatic fallback to UUID-based numbering, but this should be monitored as it may indicate configuration issues
  • Input validation should be performed at a higher level to ensure doc_type and department are valid before calling this function
  • The fallback mechanism uses doc_type_code and dept_code variables which may be undefined if get_document_type_code() or get_department_code() fail - consider wrapping the entire try block or handling these cases separately
  • Consider implementing retry logic or more specific exception handling if the settings functions have known failure modes
  • Document the expected format of document numbers in your system documentation for consistency

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function generate_document_number 85.4% similar

    Generates unique, sequential document numbers for a given document type and department using persistent counters stored in Neo4j database.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function _generate_document_number_fallback 71.3% similar

    Generates a fallback document number using in-memory counters when database access fails, creating unique identifiers based on document type, department, and year.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function get_next_document_number 69.6% similar

    Atomically retrieves and increments the next sequential document number for a specific document type and department combination from a Neo4j graph database.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function validate_document_number 62.5% similar

    Validates a custom document number by checking its format, length constraints, and uniqueness in the database, returning a dictionary with validation results.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function create_document_v3 56.2% similar

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

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