Refactor entity synchronization logic in Area, Brand, Item, RoomFunction, and Room models; improve ID handling and streamline foreign key resolution in settings

This commit is contained in:
Yaro Kasear 2025-06-25 11:23:33 -05:00
parent 7833c4828b
commit 543494120c
9 changed files with 170 additions and 96 deletions

View file

@ -38,12 +38,18 @@ class Brand(db.Model):
if not isinstance(item, dict):
continue
name = str(item.get("name", "")).strip()
raw_id = item.get("id")
if not name:
continue
submitted_clean.append({"id": item.get("id"), "name": name})
if isinstance(item.get("id"), int) and item["id"] >= 0:
seen_ids.add(item["id"])
submitted_clean.append({"id": raw_id, "name": name})
try:
parsed_id = int(raw_id)
if parsed_id >= 0:
seen_ids.add(parsed_id)
except (ValueError, TypeError):
pass
existing_by_id = {b.id: b for b in db.session.query(cls).all()}
existing_ids = set(existing_by_id.keys())
@ -60,16 +66,26 @@ class Brand(db.Model):
db.session.flush()
temp_id_map[submitted_id] = obj.id
print(f" Adding brand: {name}")
elif submitted_id in existing_by_id:
obj = existing_by_id[submitted_id]
if obj.name != name:
print(f"✏️ Updating brand {obj.id}: '{obj.name}''{name}'")
obj.name = name
else:
try:
parsed_id = int(submitted_id)
except (ValueError, TypeError):
continue
if parsed_id in existing_by_id:
obj = existing_by_id[parsed_id]
if obj.name != name:
print(f"✏️ Updating brand {obj.id}: '{obj.name}''{name}'")
obj.name = name
for id_to_remove in existing_ids - seen_ids:
db.session.delete(existing_by_id[id_to_remove])
print(f"🗑️ Removing brand ID {id_to_remove}")
return temp_id_map
id_map = {
**{str(i): i for i in seen_ids}, # "1" → 1
**{str(temp): real for temp, real in temp_id_map.items()} # "temp-1" → 5
}
return id_map