🔍 Code Extractor

function _generate_document_number_fallback

Maturity: 57

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

File:
/tf/active/vicechatdev/CDocs/settings_prod.py
Lines:
654 - 694
Complexity:
moderate

Purpose

This function serves as a resilience mechanism for document numbering systems. When the primary database-driven numbering system is unavailable, it maintains document number generation using in-memory counters stored in DOCUMENT_NUMBERING dictionary. It supports configurable prefixes, numbering formats, and department-specific counters to ensure documents can still be created with unique identifiers during system failures or database outages.

Source Code

def _generate_document_number_fallback(doc_type: str, department: str) -> str:
    """
    Fallback method for document numbering when database access fails.
    Uses in-memory counters as a last resort.
    """
    from datetime import datetime
    
    logger.warning(f"Using fallback document numbering for {doc_type}/{department}")
    
    # Get document type info from config if available
    doc_info = DOCUMENT_CONFIG.get(doc_type, {})
    
    # If not found in config, use simple type name
    prefix = doc_info.get('prefix', doc_type)
    
    # Get counter for this department
    if department in DOCUMENT_NUMBERING['department_counters']:
        number = DOCUMENT_NUMBERING['department_counters'][department]
    else:
        # If department not found, initialize counter
        DOCUMENT_NUMBERING['department_counters'][department] = 1
        number = 1
        
    # Update counter for next use
    DOCUMENT_NUMBERING['department_counters'][department] = number + 1
    
    # Get current year
    current_year = datetime.now().year
    
    # Use document type specific numbering format if available, otherwise use default
    numbering_format = doc_info.get('numbering_format', 
                                   DOCUMENT_NUMBERING.get('numbering_format', 
                                                        '{prefix}-{dept}-{year}-{number:04d}'))
    
    # Format document number
    return numbering_format.format(
        prefix=prefix, 
        dept=department,
        year=current_year if DOCUMENT_NUMBERING.get('use_year_in_numbering', False) else "",
        number=number
    )

Parameters

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

Parameter Details

doc_type: String identifier for the type of document being numbered (e.g., 'invoice', 'report', 'memo'). Used to lookup configuration in DOCUMENT_CONFIG for prefix and numbering format. If not found in config, the doc_type itself is used as the prefix.

department: String identifier for the department generating the document (e.g., 'HR', 'Finance', 'IT'). Used to maintain separate counters per department in DOCUMENT_NUMBERING['department_counters']. If department doesn't exist in counters, it's initialized with counter value 1.

Return Value

Type: str

Returns a formatted string representing the unique document number. The format depends on the numbering_format configuration and may include prefix, department code, year, and sequential number. Example formats: 'INV-HR-2024-0001' or 'MEMO-IT-0042'. The sequential number is zero-padded to 4 digits by default.

Dependencies

  • datetime
  • logging

Required Imports

from datetime import datetime
import logging

Usage Example

# Setup required configuration
DOCUMENT_CONFIG = {
    'invoice': {
        'prefix': 'INV',
        'numbering_format': '{prefix}-{dept}-{year}-{number:04d}'
    }
}

DOCUMENT_NUMBERING = {
    'department_counters': {},
    'use_year_in_numbering': True,
    'numbering_format': '{prefix}-{dept}-{number:04d}'
}

import logging
from datetime import datetime

logger = logging.getLogger(__name__)

# Generate document number
doc_number = _generate_document_number_fallback('invoice', 'Finance')
print(doc_number)  # Output: 'INV-Finance-2024-0001'

# Generate another for same department
doc_number2 = _generate_document_number_fallback('invoice', 'Finance')
print(doc_number2)  # Output: 'INV-Finance-2024-0002'

# Generate for different department
doc_number3 = _generate_document_number_fallback('invoice', 'HR')
print(doc_number3)  # Output: 'INV-HR-2024-0001'

Best Practices

  • Ensure DOCUMENT_CONFIG and DOCUMENT_NUMBERING dictionaries are properly initialized before calling this function
  • This function modifies DOCUMENT_NUMBERING['department_counters'] in-place, so it maintains state across calls
  • In-memory counters are not persistent and will reset if the application restarts, making this truly a fallback mechanism only
  • Monitor logger warnings to detect when fallback numbering is being used, as it indicates database connectivity issues
  • Consider implementing counter persistence to a file or cache if fallback mode needs to survive application restarts
  • The function is not thread-safe; implement locking mechanisms if used in multi-threaded environments
  • Validate that department and doc_type strings don't contain characters that could break the numbering format
  • Set use_year_in_numbering to True in DOCUMENT_NUMBERING to include year in document numbers for better organization

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function generate_document_number 73.9% 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_v1 71.3% similar

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

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_next_document_number 62.8% 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 initialize_document_counters 58.6% similar

    Initializes document counters in Neo4j by analyzing existing ControlledDocument nodes and creating DocumentCounter nodes with values higher than the maximum existing document numbers for each department/type combination.

    From: /tf/active/vicechatdev/CDocs/db/schema_manager.py
  • function validate_document_number 55.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
← Back to Browse