Refactor models to implement ValidatableMixin; add validation logic for state management in Area, Brand, Item, Room, and RoomFunction classes

This commit is contained in:
Yaro Kasear 2025-06-25 14:52:49 -05:00
parent 8de21bae9c
commit d7e38cb8da
9 changed files with 196 additions and 9 deletions

View file

@ -10,8 +10,11 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from . import db
class Room(db.Model):
from ..utils.validation import ValidatableMixin
class Room(ValidatableMixin, db.Model):
__tablename__ = 'Rooms'
VALIDATION_LABEL = "Room"
id: Mapped[int] = mapped_column("ID", Integer, Identity(start=1, increment=1), primary_key=True)
name: Mapped[Optional[str]] = mapped_column("Room", Unicode(255), nullable=True)
@ -141,4 +144,38 @@ class Room(db.Model):
room = existing_by_id[existing_id]
db.session.delete(room)
print(f"🗑️ Removing room: {room.name}")
@classmethod
def validate_state(cls, submitted_items: list[dict]) -> list[str]:
errors = []
for index, item in enumerate(submitted_items):
label = f"Room #{index + 1}"
if not isinstance(item, dict):
errors.append(f"{label} is not a valid object.")
continue
name = item.get("name")
if not name or not str(name).strip():
errors.append(f"{label} is missing a name.")
raw_id = item.get("id")
if raw_id is not None:
try:
_ = int(raw_id)
except (ValueError, TypeError):
if not str(raw_id).startswith("room-"):
errors.append(f"{label} has an invalid ID: {raw_id}")
# These fields are FK IDs, so we're just checking for valid formats here.
for fk_field, fk_label in [("section_id", "Section"), ("function_id", "Function")]:
fk_val = item.get(fk_field)
if fk_val is not None:
try:
_ = int(fk_val)
except (ValueError, TypeError):
if not isinstance(fk_val, str) or not fk_val.startswith("temp-"):
errors.append(f"{label} has invalid {fk_label} ID: {fk_val}")
return errors