Implement sync_from_state method for Area, Brand, Item, RoomFunction, and Room models; streamline entity management in settings
This commit is contained in:
parent
87fa623cde
commit
8a5c5db9e0
11 changed files with 204 additions and 70 deletions
73
routes.py
73
routes.py
|
@ -398,67 +398,6 @@ def search():
|
|||
|
||||
@main.route('/settings', methods=['GET', 'POST'])
|
||||
def settings():
|
||||
def process_entities(entity_list, model, attr, key_name="name"):
|
||||
"""Upserts and deletes based on entity name field."""
|
||||
existing = {getattr(e, attr): e.id for e in db.session.query(model).all()}
|
||||
submitted = {
|
||||
str(e.get(key_name, "")).strip()
|
||||
for e in entity_list if isinstance(e, dict) and e.get(key_name)
|
||||
}
|
||||
|
||||
print(f"🔍 Existing: {existing}")
|
||||
print(f"🆕 Submitted: {submitted}")
|
||||
print(f"➕ To add: {submitted - set(existing)}")
|
||||
print(f"➖ To delete: {set(existing) - submitted}")
|
||||
|
||||
for name in submitted - set(existing):
|
||||
db.session.add(model(**{attr: name}))
|
||||
|
||||
for name in set(existing) - submitted:
|
||||
db.session.execute(delete(model).where(getattr(model, attr) == name))
|
||||
|
||||
return submitted # Might be useful for mapping fallback
|
||||
|
||||
def handle_rooms(rooms, section_map, function_map, section_fallbacks, function_fallbacks):
|
||||
existing_rooms = {r.name: r.id for r in db.session.query(Room).all()}
|
||||
submitted_rooms = {
|
||||
str(r.get("name", "")).strip(): r for r in rooms if r.get("name")
|
||||
}
|
||||
|
||||
print(f"🔍 Rooms in DB: {list(existing_rooms.keys())}")
|
||||
print(f"🆕 Rooms submitted: {list(submitted_rooms.keys())}")
|
||||
print(f"➖ To delete: {set(existing_rooms) - set(submitted_rooms)}")
|
||||
|
||||
for name, data in submitted_rooms.items():
|
||||
if name not in existing_rooms:
|
||||
section_id = resolve_id(data.get("section_id"), section_fallbacks, section_map, "section") if data.get("section_id") is not None else None
|
||||
function_id = resolve_id(data.get("function_id"), function_fallbacks, function_map, "function") if data.get("function_id") is not None else None
|
||||
db.session.add(Room(name=name, area_id=section_id, function_id=function_id))
|
||||
|
||||
for name in set(existing_rooms) - set(submitted_rooms):
|
||||
db.session.execute(delete(Room).where(Room.name == name))
|
||||
|
||||
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"{label.title()} ID {resolved} not found.")
|
||||
except Exception:
|
||||
pass # Continue to fallback logic
|
||||
|
||||
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"Unresolved {label}: {key}")
|
||||
return final_id
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed resolving {label} ID {raw_id}: {e}") from e
|
||||
|
||||
if request.method == 'POST':
|
||||
print("⚠️⚠️⚠️ POST /settings reached! ⚠️⚠️⚠️")
|
||||
form = request.form
|
||||
|
@ -473,17 +412,17 @@ def settings():
|
|||
|
||||
try:
|
||||
with db.session.begin():
|
||||
brand_names = process_entities(state.get("brands", []), Brand, "name")
|
||||
type_names = process_entities(state.get("types", []), Item, "description", "name")
|
||||
section_names = process_entities(state.get("sections", []), Area, "name")
|
||||
func_names = process_entities(state.get("functions", []), RoomFunction, "description")
|
||||
Brand.sync_from_state(state.get("brands", []))
|
||||
Item.sync_from_state(state.get("types", []))
|
||||
Area.sync_from_state(state.get("sections", []))
|
||||
RoomFunction.sync_from_state(state.get("functions", []))
|
||||
|
||||
# Refresh maps after inserts
|
||||
section_map = {a.name: a.id for a in db.session.query(Area).all()}
|
||||
function_map = {f.description: f.id for f in db.session.query(RoomFunction).all()}
|
||||
|
||||
handle_rooms(
|
||||
rooms=state.get("rooms", []),
|
||||
Room.sync_from_state(
|
||||
submitted_rooms=state.get("rooms", []),
|
||||
section_map=section_map,
|
||||
function_map=function_map,
|
||||
section_fallbacks=state.get("sections", []),
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue