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

@ -49,36 +49,25 @@ class Room(db.Model):
def sync_from_state(
cls,
submitted_rooms: list[dict],
section_map: dict,
function_map: dict,
section_fallbacks: list,
function_fallbacks: list
section_map: dict[int, int],
function_map: dict[int, int]
):
"""
Syncs the Rooms table with the submitted room list.
Resolves foreign keys using section_map and function_map.
Supports add, update, and delete.
"""
def resolve_fk(raw_id, fallback_list, id_map, label):
if not raw_id:
def resolve_fk(key, fk_map, label):
# Print the fucking map so we can see what we're working with
print(f"Resolving {label} ID: {key} using map: {fk_map}")
if key is None:
return None
# 🛠 Handle SQLAlchemy model objects and dicts both
name_entry = next(
(getattr(item, "name", None) or item.get("name")
for item in fallback_list
if str(getattr(item, "id", None) or item.get("id")) == str(raw_id)),
None
)
if name_entry is None:
raise ValueError(f"Unable to resolve {label} ID: {raw_id}")
resolved_id = id_map.get(name_entry)
if resolved_id is None:
raise ValueError(f"{label.capitalize()} '{name_entry}' not found in ID map.")
return resolved_id
key = str(key)
if key.startswith("temp") or not key.isdigit():
if key in fk_map:
return fk_map[key]
raise ValueError(f"Unable to resolve {label} ID: {key}")
return int(key) # It's already a real ID
submitted_clean = []
seen_ids = set()
@ -105,7 +94,7 @@ class Room(db.Model):
try:
seen_ids.add(int(rid))
except ValueError:
pass # It's an invalid non-temp string
pass # Not valid? Not seen.
existing_query = db.session.query(cls)
existing_by_id = {room.id: room for room in existing_query.all()}
@ -118,8 +107,8 @@ class Room(db.Model):
rid = entry.get("id")
name = entry["name"]
resolved_section_id = resolve_fk(entry.get("section_id"), section_fallbacks, section_map, "section")
resolved_function_id = resolve_fk(entry.get("function_id"), function_fallbacks, function_map, "function")
resolved_section_id = resolve_fk(entry.get("section_id"), section_map, "section")
resolved_function_id = resolve_fk(entry.get("function_id"), function_map, "function")
if not rid or str(rid).startswith("room-"):
new_room = cls(name=name, area_id=resolved_section_id, function_id=resolved_function_id)
@ -158,4 +147,3 @@ class Room(db.Model):
db.session.delete(room)
print(f"🗑️ Removing room: {room.name}")