Implement sync_from_state methods for Area, Brand, Item, RoomFunction, and Room models; enhance entity management and foreign key resolution in settings
This commit is contained in:
parent
8a5c5db9e0
commit
7833c4828b
9 changed files with 359 additions and 186 deletions
145
models/rooms.py
145
models/rooms.py
|
@ -46,59 +46,116 @@ class Room(db.Model):
|
|||
}
|
||||
|
||||
@classmethod
|
||||
def sync_from_state(cls, submitted_rooms: list[dict], section_map: dict, function_map: dict, section_fallbacks: list, function_fallbacks: list):
|
||||
def sync_from_state(
|
||||
cls,
|
||||
submitted_rooms: list[dict],
|
||||
section_map: dict,
|
||||
function_map: dict,
|
||||
section_fallbacks: list,
|
||||
function_fallbacks: list
|
||||
):
|
||||
"""
|
||||
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_id(raw_id, fallback_list, id_map, label):
|
||||
try:
|
||||
resolved = int(raw_id)
|
||||
if resolved >= 0:
|
||||
if resolved in id_map.values():
|
||||
return resolved
|
||||
raise ValueError(f"ID {resolved} not found in {label}.")
|
||||
except Exception:
|
||||
pass
|
||||
def resolve_fk(raw_id, fallback_list, id_map, label):
|
||||
if not raw_id:
|
||||
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
|
||||
|
||||
submitted_clean = []
|
||||
seen_ids = set()
|
||||
|
||||
for room in submitted_rooms:
|
||||
if not isinstance(room, dict):
|
||||
continue
|
||||
name = str(room.get("name", "")).strip()
|
||||
if not name:
|
||||
continue
|
||||
|
||||
rid = room.get("id")
|
||||
section_id = room.get("section_id")
|
||||
function_id = room.get("function_id")
|
||||
|
||||
submitted_clean.append({
|
||||
"id": rid,
|
||||
"name": name,
|
||||
"section_id": section_id,
|
||||
"function_id": function_id
|
||||
})
|
||||
|
||||
if rid and not str(rid).startswith("room-"):
|
||||
try:
|
||||
seen_ids.add(int(rid))
|
||||
except ValueError:
|
||||
pass # It's an invalid non-temp string
|
||||
|
||||
index = abs(resolved + 1)
|
||||
try:
|
||||
entry = fallback_list[index]
|
||||
key = entry.get("name") if isinstance(entry, dict) else str(entry).strip()
|
||||
final_id = id_map.get(key)
|
||||
if final_id is None:
|
||||
raise ValueError(f"ID for {key} not found in {label}.")
|
||||
return final_id
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to resolve {label} ID: {e}") from e
|
||||
|
||||
existing_query = db.session.query(cls)
|
||||
existing = {room.name: room for room in existing_query.all()}
|
||||
existing_by_id = {room.id: room for room in existing_query.all()}
|
||||
existing_ids = set(existing_by_id.keys())
|
||||
|
||||
submitted = {
|
||||
str(room.get("name", "")).strip(): room
|
||||
for room in submitted_rooms
|
||||
if isinstance(room, dict) and str(room.get("name", "")).strip()
|
||||
}
|
||||
print(f"Existing room IDs: {existing_ids}")
|
||||
print(f"Submitted room IDs: {seen_ids}")
|
||||
|
||||
existing_names = set(existing.keys())
|
||||
submitted_names = set(submitted.keys())
|
||||
for entry in submitted_clean:
|
||||
rid = entry.get("id")
|
||||
name = entry["name"]
|
||||
|
||||
print(f"Existing rooms: {existing_names}")
|
||||
print(f"Submitted rooms: {submitted_names}")
|
||||
print(f"Rooms to add: {submitted_names - existing_names}")
|
||||
print(f"Rooms to remove: {existing_names - submitted_names}")
|
||||
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")
|
||||
|
||||
if not rid or str(rid).startswith("room-"):
|
||||
new_room = cls(name=name, area_id=resolved_section_id, function_id=resolved_function_id)
|
||||
db.session.add(new_room)
|
||||
print(f"➕ Adding room: {new_room}")
|
||||
else:
|
||||
try:
|
||||
rid_int = int(rid)
|
||||
except ValueError:
|
||||
print(f"⚠️ Invalid room ID format: {rid}")
|
||||
continue
|
||||
|
||||
room = existing_by_id.get(rid_int)
|
||||
if not room:
|
||||
print(f"⚠️ No matching room in DB for ID: {rid_int}")
|
||||
continue
|
||||
|
||||
updated = False
|
||||
if room.name != name:
|
||||
print(f"✏️ Updating room name {room.id}: '{room.name}' → '{name}'")
|
||||
room.name = name
|
||||
updated = True
|
||||
if room.area_id != resolved_section_id:
|
||||
print(f"✏️ Updating room area {room.id}: {room.area_id} → {resolved_section_id}")
|
||||
room.area_id = resolved_section_id
|
||||
updated = True
|
||||
if room.function_id != resolved_function_id:
|
||||
print(f"✏️ Updating room function {room.id}: {room.function_id} → {resolved_function_id}")
|
||||
room.function_id = resolved_function_id
|
||||
updated = True
|
||||
if not updated:
|
||||
print(f"✅ No changes to room {room.id}")
|
||||
|
||||
for existing_id in existing_ids - seen_ids:
|
||||
room = existing_by_id[existing_id]
|
||||
db.session.delete(room)
|
||||
print(f"🗑️ Removing room: {room.name}")
|
||||
|
||||
for name in submitted_names - existing_names:
|
||||
room_data = submitted[name]
|
||||
area_id = resolve_id(room_data.get("section_id", -1), section_fallbacks, section_map, "section") if room_data.get("section_id") is not None else None
|
||||
function_id = resolve_id(room_data.get("function_id", -1), function_fallbacks, function_map, "function") if room_data.get("function_id") is not None else None
|
||||
new_room = cls(name=name, area_id=area_id, function_id=function_id)
|
||||
db.session.add(new_room)
|
||||
print(f"➕ Adding room: {new_room}")
|
||||
|
||||
for name in existing_names - submitted_names:
|
||||
room_to_remove = existing[name]
|
||||
db.session.delete(room_to_remove)
|
||||
print(f"🗑️ Removing room: {room_to_remove}")
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue