Implement sync_from_state method for Area, Brand, Item, RoomFunction, and Room models; streamline entity management in settings

This commit is contained in:
Yaro Kasear 2025-06-24 13:09:41 -05:00
parent 87fa623cde
commit 8a5c5db9e0
11 changed files with 204 additions and 70 deletions

View file

@ -26,3 +26,33 @@ class Area(db.Model):
'id': self.id,
'name': self.name
}
@classmethod
def sync_from_state(cls, submitted_items: list[dict]):
"""
Syncs the Area table with the provided list of dictionaries.
Adds new areas and removes areas 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 = {area.name: area for area in existing_query.all()}
existing_names = set(existing.keys())
print(f"Existing areas: {existing_names}")
print(f"Submitted areas: {submitted}")
print(f"Areas to add: {submitted - existing_names}")
print(f"Areas to remove: {existing_names - submitted}")
for name in submitted - existing_names:
db.session.add(cls(name=name))
print(f" Adding area: {name}")
for name in existing_names - submitted:
db.session.delete(existing[name])
print(f"🗑️ Removing area: {name}")