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/
.env
*.db

View file

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

View file

@ -16,4 +16,10 @@ class Brand(db.Model):
inventory: Mapped[List['Inventory']] = relationship('Inventory', back_populates='brand')
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}"
else:
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

@ -17,4 +17,11 @@ class Item(db.Model):
inventory: Mapped[List['Inventory']] = relationship('Inventory', back_populates='item')
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

@ -16,4 +16,10 @@ class RoomFunction(db.Model):
rooms: Mapped[List['Room']] = relationship('Room', back_populates='room_function')
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

@ -31,4 +31,12 @@ class Room(db.Model):
name = self.name or ""
func = self.room_function.description if self.room_function else ""
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):
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})>"
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}, " \
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})>"
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
}

231
routes.py
View file

@ -1,12 +1,10 @@
from flask import Blueprint, render_template, url_for, request, redirect, flash
from flask import current_app as app
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 typing import Callable, Any, List
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 datetime import datetime, timedelta
from .utils import eager_load_user_relationships, eager_load_inventory_relationships, eager_load_room_relationships, eager_load_worklog_relationships, chunk_list, add_named_entities
import pandas as pd
import traceback
import json
@ -400,6 +398,37 @@ def search():
@main.route('/settings', methods=['GET', 'POST'])
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':
print("⚠️⚠️⚠️ POST /settings reached! ⚠️⚠️⚠️")
form = request.form
@ -407,108 +436,124 @@ def settings():
try:
state = json.loads(form['formState'])
except Exception as e:
except Exception:
flash("Invalid form state submitted. JSON decode failed.", "danger")
traceback.print_exc()
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:
section_id = int(raw_section) if raw_section is not None else None
function_id = int(raw_function) if raw_function is not None else None
# Resolve negative or unmapped IDs
if section_id is None or section_id < 0:
section_idx = abs(section_id + 1) if section_id is not None else 0
section_name = state['sections'][section_idx]
section_id = section_map.get(section_name)
if not section_id:
raise ValueError(f"Unresolved section: {section_name}")
if function_id is None or function_id < 0:
function_idx = abs(function_id + 1) if function_id is not None else 0
function_name = state['functions'][function_idx]
function_id = function_map.get(function_name)
if not function_id:
raise ValueError(f"Unresolved function: {function_name}")
print(f"🏗️ Creating room '{name}' with section ID {section_id} and function ID {function_id}")
new_room = Room(name=name, area_id=section_id, function_id=function_id) # type: ignore
db.session.add(new_room)
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.")
with db.session.begin():
# === 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))
# === TYPES ===
existing_types = {i.description for i in db.session.query(Item).all()}
submitted_types = {
str(t.get("name") or t.get("description") or "").strip()
for t in state.get("types", [])
if isinstance(t, dict) and str(t.get("name") or t.get("description") or "").strip()
}
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))
# === SECTIONS ===
existing_sections = {a.name for a in db.session.query(Area).all()}
submitted_sections = {
str(s.get("name", "")).strip()
for s in state.get("sections", [])
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))
# === FUNCTIONS ===
existing_funcs = {f.description for f in db.session.query(RoomFunction).all()}
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:
db.session.rollback()
print("❌ COMMIT FAILED ❌")
traceback.print_exc()
flash(f"Error saving changes: {e}", "danger")
flash("Changes saved.", "success")
return redirect(url_for('main.settings'))
# === GET ===
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()
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()
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;
}
const option = new Option(value, value);
const option = createOption(value); // Already built to handle temp IDs
select.add(option);
formState[stateArray].push(value);
input.value = '';
@ -94,6 +94,11 @@ const ComboBoxWidget = (() => {
}
currentlyEditing = null;
} 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);
if (exists) {
alert(`"${newItem}" already exists.`);
@ -105,7 +110,7 @@ const ComboBoxWidget = (() => {
const key = config.stateArray ?? `${ns}s`; // fallback to pluralization
if (Array.isArray(formState?.[key])) {
formState[key].push(newItem);
formState[key].push({ name: newItem });
}
if (config.sort !== false) {

View file

@ -52,7 +52,12 @@
</div>
</div>
</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"
integrity="sha384-j1CDi7MgGQ12Z7Qab0qlWQ/Qqz24Gc6BM0thvEMVjHnfYGF0rmFCozFSxQBxwHKO"

View file

@ -3,138 +3,159 @@
{% block title %}{{ title }}{% endblock %}
{% block content %}
{{ breadcrumbs.breadcrumb_header(
title=title,
submit_button=True
) }}
<form method="POST" id="settingsForm" action="{{ url_for('main.settings') }}">
<input type="hidden" name="formState" id="formStateField">
{{ breadcrumbs.breadcrumb_header(
title=title,
submit_button=True
) }}
<div class="container">
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title">
Inventory Settings
</h5>
<div class="row">
<div class="col">
{{ combos.render_combobox(
id='brand',
options=brands,
label='Brands',
placeholder='Add a new brand'
) }}
</div>
<div class="col">
{{ combos.render_combobox(
id='type',
options=types,
label='Inventory Types',
placeholder='Add a new type'
) }}
</div>
<div class="container">
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title">
Inventory Settings
</h5>
<div class="row">
<div class="col">
{{ combos.render_combobox(
id='brand',
options=brands,
label='Brands',
placeholder='Add a new brand'
) }}
</div>
</div>
</div>
<div class="card">
<div class="card-body">
<h5 class="card-title">Location Settings</h5>
<div class="row">
<div class="col">
{{ combos.render_combobox(
id='section',
options=sections,
label='Sections',
placeholder='Add a new section'
) }}
</div>
<div class="col">
{{ combos.render_combobox(
id='function',
options=functions,
label='Functions',
placeholder='Add a new function'
) }}
</div>
</div>
<div class="row">
{% set room_editor %}
const roomEditor = new bootstrap.Modal(document.getElementById('roomEditor'));
const roomNameInput = document.getElementById('roomName');
roomNameInput.value = document.getElementById('room-input').value;
roomEditor.show();
{% endset %}
<div class="col">
{{ combos.render_combobox(
id='room',
options=rooms,
label='Rooms',
placeholder='Add a new room',
onAdd=room_editor
) }}
</div>
<div class="col">
{{ combos.render_combobox(
id='type',
options=types,
label='Inventory Types',
placeholder='Add a new type'
) }}
</div>
</div>
</div>
</div>
<div class="modal fade" id="roomEditor" data-bs-backdrop="static" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="roomEditorLabel">Room Editor</h1>
<div class="card">
<div class="card-body">
<h5 class="card-title">Location Settings</h5>
<div class="row">
<div class="col">
{{ combos.render_combobox(
id='section',
options=sections,
label='Sections',
placeholder='Add a new section'
) }}
</div>
<div class="modal-body">
<div class="row">
<div class="col">
<label for="roomName" class="form-label">Room Name</label>
<input type="text" class="form-input" id="roomName"
placeholder="Enter room name">
</div>
</div>
<div class="row">
<div class="col">
<label for="roomSection" class="form-label">Section</label>
<select id="roomSection" class="form-select">
<option value="">Select a section</option>
{% for section in sections %}
<option value="{{ section.id }}">{{ section.name }}</option>
{% endfor %}
</select>
</div>
<div class="col">
<label class="form-label">Function</label>
<select id="roomFunction" class="form-select">
<option value="">Select a function</option>
{% for function in functions %}
<option value="{{ function.id }}">{{ function.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col">
{{ combos.render_combobox(
id='function',
options=functions,
label='Functions',
placeholder='Add a new function'
) }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal"
id="roomEditorCancelButton">Cancel</button>
<button type="button" class="btn btn-primary" id="roomEditorSaveButton">Save</button>
</div>
<div class="row">
{% set room_editor %}
const roomEditor = new bootstrap.Modal(document.getElementById('roomEditor'));
const roomNameInput = document.getElementById('roomName');
roomNameInput.value = document.getElementById('room-input').value;
roomEditor.show();
document.getElementById('room-input').value = '';
{% endset %}
<div class="col">
{{ combos.render_combobox(
id='room',
options=rooms,
label='Rooms',
placeholder='Add a new room',
onAdd=room_editor
) }}
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal fade" id="roomEditor" data-bs-backdrop="static" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="roomEditorLabel">Room Editor</h1>
</div>
<div class="modal-body">
<div class="row">
<div class="col">
<label for="roomName" class="form-label">Room Name</label>
<input type="text" class="form-input" id="roomName" placeholder="Enter room name">
</div>
</div>
<div class="row">
<div class="col">
<label for="roomSection" class="form-label">Section</label>
<select id="roomSection" class="form-select">
<option value="">Select a section</option>
{% for section in sections %}
<option value="{{ section.id }}">{{ section.name }}</option>
{% endfor %}
</select>
</div>
<div class="col">
<label class="form-label">Function</label>
<select id="roomFunction" class="form-select">
<option value="">Select a function</option>
{% for function in functions %}
<option value="{{ function.id }}">{{ function.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal"
id="roomEditorCancelButton">Cancel</button>
<button type="button" class="btn btn-primary" id="roomEditorSaveButton">Save</button>
</div>
</div>
</div>
</div>
{% endblock %}
{% block script %}
const formState = {
brands: [],
types: [],
sections: [],
functions: [],
rooms: []
brands: {{ brands | tojson }},
types: {{ types | tojson }},
sections: {{ sections | tojson }},
functions: {{ functions | tojson }},
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', () => {
const modal = document.getElementById('roomEditor');
const saveButton = document.getElementById('roomEditorSaveButton');
@ -143,7 +164,7 @@
// Replace the whole submission logic with just JSON
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
@ -204,5 +225,4 @@
bootstrap.Modal.getInstance(modal).hide();
});
});
{% endblock %}
{% endblock %}

View file

@ -1,5 +1,6 @@
from sqlalchemy.orm import joinedload, selectinload
from .models import User, Room, Inventory, WorkLog
from . import db
def eager_load_user_relationships(query):
return query.options(
@ -31,3 +32,15 @@ def eager_load_worklog_relationships(query):
def chunk_list(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}")