58 lines
No EOL
2.1 KiB
Python
58 lines
No EOL
2.1 KiB
Python
from typing import List, Optional, TYPE_CHECKING
|
||
if TYPE_CHECKING:
|
||
from .rooms import Room
|
||
|
||
from sqlalchemy import Identity, Integer, Unicode
|
||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||
|
||
from . import db
|
||
|
||
class RoomFunction(db.Model):
|
||
__tablename__ = 'Room Functions'
|
||
|
||
id: Mapped[int] = mapped_column("ID", Integer, Identity(start=1, increment=1), primary_key=True)
|
||
description: Mapped[Optional[str]] = mapped_column("Function", Unicode(255), nullable=True)
|
||
|
||
rooms: Mapped[List['Room']] = relationship('Room', back_populates='room_function')
|
||
|
||
def __init__(self, description: Optional[str] = None):
|
||
self.description = description
|
||
|
||
def __repr__(self):
|
||
return f"<RoomFunction(id={self.id}, description={repr(self.description)})>"
|
||
|
||
def serialize(self):
|
||
return {
|
||
'id': self.id,
|
||
'name': self.description
|
||
}
|
||
|
||
@classmethod
|
||
def sync_from_state(cls, submitted_items: list[dict]):
|
||
"""
|
||
Syncs the functions table with the provided list of dictionaries.
|
||
Adds new functions and removes functions that are not in the list.
|
||
"""
|
||
submitted = {
|
||
str(item.get("name", "")).strip()
|
||
for item in submitted_items
|
||
if isinstance(item, dict) and str(item.get("name", "")).strip()
|
||
}
|
||
|
||
existing_query = db.session.query(cls)
|
||
existing = {item.description: item for item in existing_query.all()}
|
||
|
||
existing_descriptions = set(existing.keys())
|
||
|
||
print(f"Existing functions: {existing_descriptions}")
|
||
print(f"Submitted functions: {submitted}")
|
||
print(f"Functions to add: {submitted - existing_descriptions}")
|
||
print(f"Functions to remove: {existing_descriptions - submitted}")
|
||
|
||
for description in submitted - existing_descriptions:
|
||
db.session.add(cls(description=description))
|
||
print(f"➕ Adding item: {description}")
|
||
|
||
for description in existing_descriptions - submitted:
|
||
db.session.delete(existing[description])
|
||
print(f"🗑️ Removing item: {description}") |