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

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