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:
parent
7833c4828b
commit
543494120c
9 changed files with 170 additions and 96 deletions
|
@ -38,45 +38,60 @@ class Area(db.Model):
|
|||
submitted_clean = []
|
||||
seen_ids = set()
|
||||
temp_id_map = {}
|
||||
|
||||
|
||||
for item in submitted_items:
|
||||
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})
|
||||
|
||||
# Record real (non-temp) IDs
|
||||
try:
|
||||
parsed_id = int(raw_id)
|
||||
if parsed_id >= 0:
|
||||
seen_ids.add(parsed_id)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
existing_query = db.session.query(cls)
|
||||
existing_by_id = {area.id: area for area in existing_query.all()}
|
||||
existing_ids = set(existing_by_id.keys())
|
||||
|
||||
|
||||
print(f"Existing area IDs: {existing_ids}")
|
||||
print(f"Submitted area IDs: {seen_ids}")
|
||||
|
||||
|
||||
for entry in submitted_clean:
|
||||
submitted_id = entry.get("id")
|
||||
submitted_id_raw = entry.get("id")
|
||||
submitted_name = entry["name"]
|
||||
|
||||
if is_temp_id(submitted_id):
|
||||
|
||||
if is_temp_id(submitted_id_raw):
|
||||
new_area = cls(name=submitted_name)
|
||||
db.session.add(new_area)
|
||||
db.session.flush() # Get the real ID
|
||||
temp_id_map[submitted_id] = new_area.id
|
||||
temp_id_map[submitted_id_raw] = new_area.id
|
||||
print(f"➕ Adding area: {submitted_name}")
|
||||
elif submitted_id in existing_by_id:
|
||||
area = existing_by_id[submitted_id]
|
||||
if area.name != submitted_name:
|
||||
print(f"✏️ Updating area {area.id}: '{area.name}' → '{submitted_name}'")
|
||||
area.name = submitted_name
|
||||
|
||||
else:
|
||||
try:
|
||||
submitted_id = int(submitted_id_raw)
|
||||
except (ValueError, TypeError):
|
||||
continue # Skip malformed ID
|
||||
|
||||
if submitted_id in existing_by_id:
|
||||
area = existing_by_id[submitted_id]
|
||||
if area.name != submitted_name:
|
||||
print(f"✏️ Updating area {area.id}: '{area.name}' → '{submitted_name}'")
|
||||
area.name = submitted_name
|
||||
|
||||
for existing_id in existing_ids - seen_ids:
|
||||
area = existing_by_id[existing_id]
|
||||
db.session.delete(area)
|
||||
print(f"🗑️ Removing area: {area.name}")
|
||||
|
||||
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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue