Refactor code structure; improve organization and readability across multiple files

This commit is contained in:
Yaro Kasear 2025-06-23 14:51:21 -05:00
parent 774c28e761
commit acacf39f8e
14 changed files with 380 additions and 217 deletions

2
.gitignore vendored
View file

@ -1,4 +1,4 @@
__pycache__/ **/__pycache__/
.venv/ .venv/
.env .env
*.db *.db

View file

@ -17,3 +17,9 @@ class Area(db.Model):
def __repr__(self): def __repr__(self):
return f"<Area(id={self.id}, name={repr(self.name)})>" return f"<Area(id={self.id}, name={repr(self.name)})>"
def serialize(self):
return {
'id': self.id,
'name': self.name
}

View file

@ -17,3 +17,9 @@ class Brand(db.Model):
def __repr__(self): def __repr__(self):
return f"<Brand(id={self.id}, name={repr(self.name)})>" return f"<Brand(id={self.id}, name={repr(self.name)})>"
def serialize(self):
return {
'id': self.id,
'name': self.name
}

View file

@ -69,3 +69,21 @@ class Inventory(db.Model):
return f"Serial: {self.serial}" return f"Serial: {self.serial}"
else: else:
return f"ID: {self.id}" return f"ID: {self.id}"
def serialize(self) -> dict[str, Any]:
return {
'id': self.id,
'timestamp': self.timestamp.isoformat() if self.timestamp else None,
'condition': self.condition,
'needed': self.needed,
'type_id': self.type_id,
'inventory_name': self.inventory_name,
'serial': self.serial,
'model': self.model,
'notes': self.notes,
'owner_id': self.owner_id,
'brand_id': self.brand_id,
'location_id': self.location_id,
'barcode': self.barcode,
'shared': self.shared
}

View file

@ -18,3 +18,10 @@ class Item(db.Model):
def __repr__(self): def __repr__(self):
return f"<Item(id={self.id}, description={repr(self.description)}, category={repr(self.category)})>" return f"<Item(id={self.id}, description={repr(self.description)}, category={repr(self.category)})>"
def serialize(self):
return {
'id': self.id,
'name': self.description,
'category': self.category
}

View file

@ -17,3 +17,9 @@ class RoomFunction(db.Model):
def __repr__(self): def __repr__(self):
return f"<RoomFunction(id={self.id}, description={repr(self.description)})>" return f"<RoomFunction(id={self.id}, description={repr(self.description)})>"
def serialize(self):
return {
'id': self.id,
'name': self.description
}

View file

@ -32,3 +32,11 @@ class Room(db.Model):
func = self.room_function.description if self.room_function else "" func = self.room_function.description if self.room_function else ""
return f"{name} - {func}".strip(" -") return f"{name} - {func}".strip(" -")
def serialize(self):
return {
'id': self.id,
'name': self.name,
'area_id': self.area_id,
'function_id': self.function_id
}

View file

@ -34,3 +34,14 @@ class User(db.Model):
def __repr__(self): def __repr__(self):
return f"<User(id={self.id}, first_name={repr(self.first_name)}, last_name={repr(self.last_name)}, " \ return f"<User(id={self.id}, first_name={repr(self.first_name)}, last_name={repr(self.last_name)}, " \
f"location={repr(self.location)}, staff={self.staff}, active={self.active})>" f"location={repr(self.location)}, staff={self.staff}, active={self.active})>"
def serialize(self):
return {
'id': self.id,
'first_name': self.first_name,
'last_name': self.last_name,
'location_id': self.location_id,
'supervisor_id': self.supervisor_id,
'staff': self.staff,
'active': self.active
}

View file

@ -32,3 +32,16 @@ class WorkLog(db.Model):
return f"<WorkLog(id={self.id}, start_time={self.start_time}, end_time={self.end_time}, " \ return f"<WorkLog(id={self.id}, start_time={self.start_time}, end_time={self.end_time}, " \
f"notes={repr(self.notes)}, complete={self.complete}, followup={self.followup}, " \ f"notes={repr(self.notes)}, complete={self.complete}, followup={self.followup}, " \
f"contact_id={self.contact_id}, analysis={self.analysis}, work_item_id={self.work_item_id})>" f"contact_id={self.contact_id}, analysis={self.analysis}, work_item_id={self.work_item_id})>"
def serialize(self):
return {
'id': self.id,
'start_time': self.start_time.isoformat() if self.start_time else None,
'end_time': self.end_time.isoformat() if self.end_time else None,
'notes': self.notes,
'complete': self.complete,
'followup': self.followup,
'contact_id': self.contact_id,
'analysis': self.analysis,
'work_item_id': self.work_item_id
}

223
routes.py
View file

@ -1,12 +1,10 @@
from flask import Blueprint, render_template, url_for, request, redirect, flash from flask import Blueprint, render_template, url_for, request, redirect, flash
from flask import current_app as app from flask import current_app as app
from .models import Brand, Item, Inventory, RoomFunction, User, WorkLog, Room, Area from .models import Brand, Item, Inventory, RoomFunction, User, WorkLog, Room, Area
from sqlalchemy import or_ from sqlalchemy import or_, delete
from sqlalchemy.orm import aliased from sqlalchemy.orm import aliased
from typing import Callable, Any, List
from . import db from . import db
from .utils import eager_load_user_relationships, eager_load_inventory_relationships, eager_load_room_relationships, eager_load_worklog_relationships, chunk_list from .utils import eager_load_user_relationships, eager_load_inventory_relationships, eager_load_room_relationships, eager_load_worklog_relationships, chunk_list, add_named_entities
from datetime import datetime, timedelta
import pandas as pd import pandas as pd
import traceback import traceback
import json import json
@ -400,6 +398,37 @@ def search():
@main.route('/settings', methods=['GET', 'POST']) @main.route('/settings', methods=['GET', 'POST'])
def settings(): def settings():
def add_named_entities(items: list[str], model, attr: str, mapper: dict | None = None):
for name in items:
clean = name.strip()
if clean:
new_obj = model(**{attr: clean}) # type: ignore
db.session.add(new_obj)
if mapper is not None:
db.session.flush()
mapper[clean] = new_obj.id
def resolve_id(raw_id, fallback_list, id_map, label):
try:
resolved_id = int(raw_id)
except (TypeError, ValueError):
resolved_id = None
if resolved_id is not None and resolved_id >= 0:
return resolved_id
index = abs(resolved_id + 1) if resolved_id is not None else 0
try:
entry = fallback_list[index]
key = entry["name"] if isinstance(entry, dict) else str(entry).strip()
except (IndexError, KeyError, TypeError):
raise ValueError(f"Invalid {label} index or format at index {index}: {entry}")
final_id = id_map.get(key)
if not final_id:
raise ValueError(f"Unresolved {label}: {key}")
return final_id
if request.method == 'POST': if request.method == 'POST':
print("⚠️⚠️⚠️ POST /settings reached! ⚠️⚠️⚠️") print("⚠️⚠️⚠️ POST /settings reached! ⚠️⚠️⚠️")
form = request.form form = request.form
@ -407,108 +436,124 @@ def settings():
try: try:
state = json.loads(form['formState']) state = json.loads(form['formState'])
except Exception as e: except Exception:
flash("Invalid form state submitted. JSON decode failed.", "danger") flash("Invalid form state submitted. JSON decode failed.", "danger")
traceback.print_exc() traceback.print_exc()
return redirect(url_for('main.settings')) return redirect(url_for('main.settings'))
# === 0. Create new Brands ===
for name in state.get('brands', []):
clean = name.strip()
if clean:
print(f"🧪 Creating new brand: {clean}")
new_brand = Brand(name=clean) # type: ignore
db.session.add(new_brand)
# === 0.5 Create new Types ===
for name in state.get('types', []):
clean = name.strip()
if clean:
print(f"🧪 Creating new item type: {clean}")
new_type = Item(description=clean) # type: ignore
db.session.add(new_type)
# === 1. Create new Sections ===
section_map = {}
for name in state.get('sections', []):
clean = name.strip()
if clean:
print(f"🧪 Creating new section: {clean}")
new_section = Area(name=clean) # type: ignore
db.session.add(new_section)
db.session.flush()
section_map[clean] = new_section.id
print(f"✅ New section '{clean}' ID: {new_section.id}")
# === 2. Create new Functions ===
function_map = {}
for name in state.get('functions', []):
clean = name.strip()
if clean:
print(f"🧪 Creating new function: {clean}")
new_function = RoomFunction(description=clean) # type: ignore
db.session.add(new_function)
db.session.flush()
function_map[clean] = new_function.id
print(f"✅ New function '{clean}' ID: {new_function.id}")
# === 3. Create new Rooms ===
for idx, room in enumerate(state.get('rooms', [])):
name = room.get('name', '').strip()
raw_section = room.get('section_id')
raw_function = room.get('function_id')
if not name:
print(f"⚠️ Skipping room at index {idx} due to missing name.")
continue
try: try:
section_id = int(raw_section) if raw_section is not None else None with db.session.begin():
function_id = int(raw_function) if raw_function is not None else None # === BRANDS ===
existing_brands = {b.name for b in db.session.query(Brand).all()}
submitted_brands = {
str(b.get("name", "")).strip()
for b in state.get("brands", [])
if isinstance(b, dict) and str(b.get("name", "")).strip()
}
print(f"🔍 Brands in DB: {existing_brands}")
print(f"🆕 Brands submitted: {submitted_brands}")
print(f" Brands to delete: {existing_brands - submitted_brands}")
for name in submitted_brands - existing_brands:
db.session.add(Brand(name=name))
for name in existing_brands - submitted_brands:
print(f"🗑️ Deleting brand: {name}")
db.session.execute(delete(Brand).where(Brand.name == name))
# Resolve negative or unmapped IDs # === TYPES ===
if section_id is None or section_id < 0: existing_types = {i.description for i in db.session.query(Item).all()}
section_idx = abs(section_id + 1) if section_id is not None else 0 submitted_types = {
section_name = state['sections'][section_idx] str(t.get("name") or t.get("description") or "").strip()
section_id = section_map.get(section_name) for t in state.get("types", [])
if not section_id: if isinstance(t, dict) and str(t.get("name") or t.get("description") or "").strip()
raise ValueError(f"Unresolved section: {section_name}") }
print(f"🔍 Types in DB: {existing_types}")
print(f"🆕 Types submitted: {submitted_types}")
print(f" Types to delete: {existing_types - submitted_types}")
for desc in submitted_types - existing_types:
db.session.add(Item(description=desc))
for desc in existing_types - submitted_types:
print(f"🗑️ Deleting type: {desc}")
db.session.execute(delete(Item).where(Item.description == desc))
if function_id is None or function_id < 0: # === SECTIONS ===
function_idx = abs(function_id + 1) if function_id is not None else 0 existing_sections = {a.name for a in db.session.query(Area).all()}
function_name = state['functions'][function_idx] submitted_sections = {
function_id = function_map.get(function_name) str(s.get("name", "")).strip()
if not function_id: for s in state.get("sections", [])
raise ValueError(f"Unresolved function: {function_name}") if isinstance(s, dict) and str(s.get("name", "")).strip()
}
print(f"🔍 Sections in DB: {existing_sections}")
print(f"🆕 Sections submitted: {submitted_sections}")
print(f" Sections to delete: {existing_sections - submitted_sections}")
for name in submitted_sections - existing_sections:
db.session.add(Area(name=name))
for name in existing_sections - submitted_sections:
print(f"🗑️ Deleting section: {name}")
db.session.execute(delete(Area).where(Area.name == name))
print(f"🏗️ Creating room '{name}' with section ID {section_id} and function ID {function_id}") # === FUNCTIONS ===
new_room = Room(name=name, area_id=section_id, function_id=function_id) # type: ignore existing_funcs = {f.description for f in db.session.query(RoomFunction).all()}
db.session.add(new_room) submitted_funcs = {
str(f.get("name", "")).strip()
for f in state.get("functions", [])
if isinstance(f, dict) and str(f.get("name", "")).strip()
}
print(f"🔍 Functions in DB: {existing_funcs}")
print(f"🆕 Functions submitted: {submitted_funcs}")
print(f" Functions to delete: {existing_funcs - submitted_funcs}")
for desc in submitted_funcs - existing_funcs:
db.session.add(RoomFunction(description=desc))
for desc in existing_funcs - submitted_funcs:
print(f"🗑️ Deleting function: {desc}")
db.session.execute(delete(RoomFunction).where(RoomFunction.description == desc))
# === REPOPULATE MAPS ===
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()}
# === ROOMS ===
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 state.get("rooms", [])
if str(r.get("name", "")).strip()
}
print(f"🔍 Rooms in DB: {list(existing_rooms.keys())}")
print(f"🆕 Rooms submitted: {list(submitted_rooms.keys())}")
print(f" Rooms to delete: {set(existing_rooms.keys()) - set(submitted_rooms.keys())}")
for name, room_data in submitted_rooms.items():
if name not in existing_rooms:
section_id = resolve_id(room_data.get("section_id"), state["sections"], section_map, "section") if room_data.get("section_id") is not None else None
function_id = resolve_id(room_data.get("function_id"), state["functions"], function_map, "function") if room_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.keys()) - set(submitted_rooms.keys()):
print(f"🗑️ Deleting room: {name}")
db.session.execute(delete(Room).where(Room.name == name))
print("✅ COMMIT executed.")
flash("Changes saved.", "success")
except Exception as e: except Exception as e:
print(f"❌ Failed to process room at index {idx}: {e}")
traceback.print_exc()
flash(f"Error processing room '{name}': {e}", "danger")
# === 4. Commit changes ===
try:
print("🚀 Attempting commit...")
db.session.commit()
print("✅ Commit succeeded.")
except Exception as e:
db.session.rollback()
print("❌ COMMIT FAILED ❌") print("❌ COMMIT FAILED ❌")
traceback.print_exc() traceback.print_exc()
flash(f"Error saving changes: {e}", "danger") flash(f"Error saving changes: {e}", "danger")
flash("Changes saved.", "success")
return redirect(url_for('main.settings')) return redirect(url_for('main.settings'))
# === GET === # === GET ===
brands = db.session.query(Brand).order_by(Brand.name).all() brands = db.session.query(Brand).order_by(Brand.name).all()
types = db.session.query(Item.id, Item.description.label("name")).order_by(Item.description).all() types = db.session.query(Item).order_by(Item.description).all()
sections = db.session.query(Area).order_by(Area.name).all() sections = db.session.query(Area).order_by(Area.name).all()
functions = db.session.query(RoomFunction.id, RoomFunction.description.label("name")).order_by(RoomFunction.description).all() functions = db.session.query(RoomFunction).order_by(RoomFunction.description).all()
rooms = eager_load_room_relationships(db.session.query(Room).order_by(Room.name)).all() rooms = eager_load_room_relationships(db.session.query(Room).order_by(Room.name)).all()
return render_template('settings.html', title="Settings", brands=brands, types=types, sections=sections, functions=functions, rooms=rooms)
return render_template('settings.html',
title="Settings",
brands=[b.serialize() for b in brands],
types=[{"id": t.id, "name": t.description} for t in types],
sections=[s.serialize() for s in sections],
functions=[f.serialize() for f in functions],
rooms=[r.serialize() for r in rooms],
)

View file

@ -30,7 +30,7 @@ const ComboBoxWidget = (() => {
return; return;
} }
const option = new Option(value, value); const option = createOption(value); // Already built to handle temp IDs
select.add(option); select.add(option);
formState[stateArray].push(value); formState[stateArray].push(value);
input.value = ''; input.value = '';
@ -94,6 +94,11 @@ const ComboBoxWidget = (() => {
} }
currentlyEditing = null; currentlyEditing = null;
} else { } else {
if (config.onAdd) {
config.onAdd(newItem, list, createOption);
return; // Skip the default logic!
}
const exists = Array.from(list.options).some(opt => opt.textContent === newItem); const exists = Array.from(list.options).some(opt => opt.textContent === newItem);
if (exists) { if (exists) {
alert(`"${newItem}" already exists.`); alert(`"${newItem}" already exists.`);
@ -105,7 +110,7 @@ const ComboBoxWidget = (() => {
const key = config.stateArray ?? `${ns}s`; // fallback to pluralization const key = config.stateArray ?? `${ns}s`; // fallback to pluralization
if (Array.isArray(formState?.[key])) { if (Array.isArray(formState?.[key])) {
formState[key].push(newItem); formState[key].push({ name: newItem });
} }
if (config.sort !== false) { if (config.sort !== false) {

View file

@ -52,7 +52,12 @@
</div> </div>
</div> </div>
</nav> </nav>
<main class="container-flex m-5">{% block content %}{% endblock %}</main> <main class="container-flex m-5">
<form method="POST" id="settingsForm" action="{{ url_for('main.settings') }}">
{% block content %}{% endblock %}
<input type="hidden" name="formState" id="formStateField">
</form>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js" <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js"
integrity="sha384-j1CDi7MgGQ12Z7Qab0qlWQ/Qqz24Gc6BM0thvEMVjHnfYGF0rmFCozFSxQBxwHKO" integrity="sha384-j1CDi7MgGQ12Z7Qab0qlWQ/Qqz24Gc6BM0thvEMVjHnfYGF0rmFCozFSxQBxwHKO"

View file

@ -3,10 +3,6 @@
{% block title %}{{ title }}{% endblock %} {% block title %}{{ title }}{% endblock %}
{% block content %} {% block content %}
<form method="POST" id="settingsForm" action="{{ url_for('main.settings') }}">
<input type="hidden" name="formState" id="formStateField">
{{ breadcrumbs.breadcrumb_header( {{ breadcrumbs.breadcrumb_header(
title=title, title=title,
submit_button=True submit_button=True
@ -66,6 +62,8 @@
roomNameInput.value = document.getElementById('room-input').value; roomNameInput.value = document.getElementById('room-input').value;
roomEditor.show(); roomEditor.show();
document.getElementById('room-input').value = '';
{% endset %} {% endset %}
<div class="col"> <div class="col">
{{ combos.render_combobox( {{ combos.render_combobox(
@ -90,8 +88,7 @@
<div class="row"> <div class="row">
<div class="col"> <div class="col">
<label for="roomName" class="form-label">Room Name</label> <label for="roomName" class="form-label">Room Name</label>
<input type="text" class="form-input" id="roomName" <input type="text" class="form-input" id="roomName" placeholder="Enter room name">
placeholder="Enter room name">
</div> </div>
</div> </div>
<div class="row"> <div class="row">
@ -123,18 +120,42 @@
</div> </div>
</div> </div>
</div> </div>
</form>
{% endblock %} {% endblock %}
{% block script %} {% block script %}
const formState = { const formState = {
brands: [], brands: {{ brands | tojson }},
types: [], types: {{ types | tojson }},
sections: [], sections: {{ sections | tojson }},
functions: [], functions: {{ functions | tojson }},
rooms: [] rooms: {{ rooms | tojson }},
}; };
function buildFormState() {
function extractOptions(id) {
const select = document.getElementById(`${id}-list`);
return Array.from(select.options).map(opt => ({ name: opt.textContent.trim(), id: parseInt(opt.value) || undefined }));
}
const roomOptions = Array.from(document.getElementById('room-list').options);
const rooms = roomOptions.map(opt => {
const data = opt.dataset;
return {
name: opt.textContent.trim(),
section_id: data.sectionId ? parseInt(data.sectionId) : null,
function_id: data.functionId ? parseInt(data.functionId) : null
};
});
return {
brands: extractOptions("brand"),
types: extractOptions("type"),
sections: extractOptions("section"),
functions: extractOptions("function"),
rooms
};
}
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('roomEditor'); const modal = document.getElementById('roomEditor');
const saveButton = document.getElementById('roomEditorSaveButton'); const saveButton = document.getElementById('roomEditorSaveButton');
@ -143,7 +164,7 @@
// Replace the whole submission logic with just JSON // Replace the whole submission logic with just JSON
form.addEventListener('submit', () => { form.addEventListener('submit', () => {
document.getElementById('formStateField').value = JSON.stringify(formState); document.getElementById('formStateField').value = JSON.stringify(buildFormState());
}); });
// Modal populates dropdowns fresh from the page every time it opens // Modal populates dropdowns fresh from the page every time it opens
@ -205,4 +226,3 @@
}); });
}); });
{% endblock %} {% endblock %}

View file

@ -1,5 +1,6 @@
from sqlalchemy.orm import joinedload, selectinload from sqlalchemy.orm import joinedload, selectinload
from .models import User, Room, Inventory, WorkLog from .models import User, Room, Inventory, WorkLog
from . import db
def eager_load_user_relationships(query): def eager_load_user_relationships(query):
return query.options( return query.options(
@ -31,3 +32,15 @@ def eager_load_worklog_relationships(query):
def chunk_list(lst, chunk_size): def chunk_list(lst, chunk_size):
return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)] return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
def add_named_entities(items: list[str], model, attr: str, mapper: dict | None = None):
for name in items:
clean = name.strip()
if clean:
print(f"Creating new {attr}: {clean}")
new_obj = model(**{attr: clean})
db.session.add(new_obj)
if mapper is not None:
db.session.flush()
mapper[clean] = new_obj.id
print(f"New {attr} '{clean}' added with ID {new_obj.id}")