assettrack/definitions/attributes/dateAttribute.py
candifloss 3acbb85b08 refactor: Modularize attribute class definitions
- Split `definitions/attribute.py` into separate files under `definitions/attributes/`.
- Added `__init__.py` for simplified imports.
- Improved code organization and maintainability.
2025-03-14 11:32:03 +05:30

51 lines
2.4 KiB
Python

from datetime import datetime
from typing import Optional
from dataclasses import dataclass, field
from .Attribute import Attribute
@dataclass
class dateAttribute(Attribute):
"""Class for date attributes."""
min_val: Optional[str] = None
max_val: Optional[str] = None
def __post_init__(self):
"""Post-initialization to set the HTML input type."""
self.html_input_type = "date"
self.valid_comparisons = {"lt", "gt", "le", "ge", "eq", "ne"}, # <, >, <=, >=, ==, !=
def _is_date(self, value: str) -> bool:
"""Check if a value is a valid date in YYYY-MM-DD format."""
try:
datetime.strptime(value, "%Y-%m-%d")
return True
except ValueError:
return False
def validate(self) -> Optional[str]:
"""Validate date-specific attributes."""
error = super().validate()
if error:
return error
if self.min_val is not None and not self._is_date(self.min_val):
return f"min_val must be a valid date (YYYY-MM-DD) for attribute '{self.attrib_name}'."
if self.max_val is not None and not self._is_date(self.max_val):
return f"max_val must be a valid date (YYYY-MM-DD) for attribute '{self.attrib_name}'."
if self.min_val is not None and self.max_val is not None:
min_date = datetime.strptime(self.min_val, "%Y-%m-%d")
max_date = datetime.strptime(self.max_val, "%Y-%m-%d")
if max_date < min_date:
return f"max_val cannot be earlier than min_val for attribute '{self.attrib_name}'."
if self.default_val is not None and not self._is_date(self.default_val):
return f"default_val must be a valid date (YYYY-MM-DD) for attribute '{self.attrib_name}'."
if self.default_val is not None:
default_date = datetime.strptime(self.default_val, "%Y-%m-%d")
if self.min_val is not None:
min_date = datetime.strptime(self.min_val, "%Y-%m-%d")
if default_date < min_date:
return f"default_val cannot be earlier than min_val for attribute '{self.attrib_name}'."
if self.max_val is not None:
max_date = datetime.strptime(self.max_val, "%Y-%m-%d")
if default_date > max_date:
return f"default_val cannot be later than max_val for attribute '{self.attrib_name}'."
return None