68 lines
1.9 KiB
Python
68 lines
1.9 KiB
Python
|
|
"""
|
||
|
|
Numeric transformation utilities.
|
||
|
|
|
||
|
|
This module provides functions for handling numeric conversions and validations
|
||
|
|
in a consistent way across the application.
|
||
|
|
"""
|
||
|
|
|
||
|
|
from decimal import Decimal
|
||
|
|
from typing import Any, Optional
|
||
|
|
from logging import Logger
|
||
|
|
|
||
|
|
|
||
|
|
def safe_decimal_conversion(
|
||
|
|
value: Any,
|
||
|
|
field_name: str = "value",
|
||
|
|
logger: Optional[Logger] = None,
|
||
|
|
component_name: str = "numeric_utils"
|
||
|
|
) -> Optional[Decimal]:
|
||
|
|
"""
|
||
|
|
Safely convert value to Decimal with error handling.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
value: Value to convert
|
||
|
|
field_name: Name of field for error logging
|
||
|
|
logger: Optional logger for error messages
|
||
|
|
component_name: Name for logging
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
Decimal value or None if conversion failed
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
if value is None or value == "":
|
||
|
|
return None
|
||
|
|
return Decimal(str(value))
|
||
|
|
except Exception as e:
|
||
|
|
if logger:
|
||
|
|
logger.warning(f"{component_name}: Failed to convert {field_name} '{value}' to Decimal: {e}")
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def validate_numeric_range(
|
||
|
|
value: Decimal,
|
||
|
|
min_value: Optional[Decimal] = None,
|
||
|
|
max_value: Optional[Decimal] = None,
|
||
|
|
field_name: str = "value"
|
||
|
|
) -> bool:
|
||
|
|
"""
|
||
|
|
Validate that a numeric value falls within specified range.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
value: Value to validate
|
||
|
|
min_value: Optional minimum value
|
||
|
|
max_value: Optional maximum value
|
||
|
|
field_name: Name of field for error messages
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
True if value is within range, False otherwise
|
||
|
|
|
||
|
|
Raises:
|
||
|
|
ValueError: If value is outside allowed range
|
||
|
|
"""
|
||
|
|
if min_value is not None and value < min_value:
|
||
|
|
raise ValueError(f"{field_name} {value} is below minimum allowed value {min_value}")
|
||
|
|
|
||
|
|
if max_value is not None and value > max_value:
|
||
|
|
raise ValueError(f"{field_name} {value} exceeds maximum allowed value {max_value}")
|
||
|
|
|
||
|
|
return True
|