Enhance Room model and settings form: improve foreign key validation and handle potential duplicates in deletion logic

This commit is contained in:
Yaro Kasear 2025-07-07 08:11:30 -05:00
parent 81b220ff44
commit a1d3f58081
2 changed files with 32 additions and 14 deletions

View file

@ -56,7 +56,6 @@ class Room(ValidatableMixin, db.Model):
Supports add, update, and delete. Supports add, update, and delete.
""" """
def resolve_fk(key, fk_map, label): 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}") print(f"Resolving {label} ID: {key} using map: {fk_map}")
if key is None: if key is None:
return None return None
@ -141,12 +140,27 @@ class Room(ValidatableMixin, db.Model):
print(f"✅ No changes to room {room.id}") print(f"✅ No changes to room {room.id}")
for existing_id in existing_ids - seen_ids: for existing_id in existing_ids - seen_ids:
room = existing_by_id[existing_id] room = existing_by_id.get(existing_id)
if not room:
continue
# Skip if a newly added room matches this one — likely duplicate
if any(
r["name"] == room.name and
resolve_fk(r["section_id"], section_map, "section") == room.area_id and
resolve_fk(r["function_id"], function_map, "function") == room.function_id
for r in submitted_clean
if r.get("id") is None or str(r.get("id")).startswith("room-")
):
print(f"⚠️ Skipping deletion of likely duplicate: {room}")
continue
db.session.delete(room) db.session.delete(room)
print(f"🗑️ Removing room: {room.name}") print(f"🗑️ Removing room: {room}")
@classmethod @classmethod
def validate_state(cls, submitted_items: list[dict]) -> list[str]: def validate_state(cls, submitted_items: list[dict]) -> list[str]:
print("VALIDATING")
errors = [] errors = []
for index, item in enumerate(submitted_items): for index, item in enumerate(submitted_items):
@ -171,11 +185,15 @@ class Room(ValidatableMixin, db.Model):
# These fields are FK IDs, so we're just checking for valid formats here. # These fields are FK IDs, so we're just checking for valid formats here.
for fk_field, fk_label in [("section_id", "Section"), ("function_id", "Function")]: for fk_field, fk_label in [("section_id", "Section"), ("function_id", "Function")]:
fk_val = item.get(fk_field) fk_val = item.get(fk_field)
if fk_val is not None:
if fk_val is None:
continue # Let the DB enforce nullability
try: try:
_ = int(fk_val) _ = int(fk_val)
except (ValueError, TypeError): except (ValueError, TypeError):
if not isinstance(fk_val, str) or not fk_val.startswith("temp-"): fk_val_str = str(fk_val)
if not fk_val_str.startswith("temp-"):
errors.append(f"{label} has invalid {fk_label} ID: {fk_val}") errors.append(f"{label} has invalid {fk_label} ID: {fk_val}")
return errors return errors

View file

@ -163,7 +163,7 @@
} }
function sanitizeFk(val) { function sanitizeFk(val) {
if (val && val !== "null" && val !== "") { if (val && val !== "null" && val !== "" && val !== "None") {
return /^\d+$/.test(val) ? parseInt(val, 10) : val; return /^\d+$/.test(val) ? parseInt(val, 10) : val;
} }
return null; return null;
@ -180,8 +180,8 @@
const result = { const result = {
name, name,
...(id ? { id } : {}), ...(id ? { id } : {}),
...(sectionId ? { section_id: sectionId } : {}), section_id: sectionId,
...(functionId ? { function_id: functionId } : {}) function_id: functionId
}; };
return result; return result;