function _generate_document_number_fallback
Generates a fallback document number using in-memory counters when database access fails, creating unique identifiers based on document type, department, and year.
/tf/active/vicechatdev/CDocs/settings_prod.py
654 - 694
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
datetimelogging
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function generate_document_number 73.9% similar
-
function generate_document_number_v1 71.3% similar
-
function get_next_document_number 62.8% similar
-
function initialize_document_counters 58.6% similar
-
function validate_document_number 55.5% similar