Refactor .gitignore; add patterns for SQLite database files and improve ignored file management
Enhance app initialization; set secret key from environment variable for better security practices Update work_log model import; change User import path for improved module structure Refactor routes; add new inventory item creation route and enhance settings handling with JSON form state Improve ComboBoxWidget; add handleComboAdd function for better option management and integrate with render_combobox macro Revamp settings template; implement form state management and improve modal functionality for room creation Add error template; create a new error handling page for better user feedback
This commit is contained in:
parent
142e909a88
commit
c6fc1a4795
9 changed files with 269 additions and 113 deletions
171
routes.py
171
routes.py
|
@ -1,4 +1,5 @@
|
|||
from flask import Blueprint, render_template, url_for, request, redirect
|
||||
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.orm import aliased
|
||||
|
@ -7,6 +8,8 @@ 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
|
||||
import pandas as pd
|
||||
import traceback
|
||||
import json
|
||||
|
||||
main = Blueprint('main', __name__)
|
||||
|
||||
|
@ -76,63 +79,8 @@ worklog_form_fields = {
|
|||
"notes": lambda log: {"label": "Notes", "type": "textarea", "value": log.notes or "", "rows": 15}
|
||||
}
|
||||
|
||||
def make_paginated_data(
|
||||
query,
|
||||
page: int,
|
||||
per_page=15
|
||||
):
|
||||
model = query.column_descriptions[0]['entity']
|
||||
items = (
|
||||
query.order_by(model.id)
|
||||
.limit(per_page)
|
||||
.offset((page - 1) * per_page)
|
||||
.all()
|
||||
)
|
||||
has_next = len(items) == per_page
|
||||
has_prev = page > 1
|
||||
total_items = query.count()
|
||||
total_pages = (total_items + per_page - 1) // per_page
|
||||
return {
|
||||
"items": items,
|
||||
"has_next": has_next,
|
||||
"has_prev": has_prev,
|
||||
"total_pages": total_pages,
|
||||
"page": page
|
||||
}
|
||||
|
||||
def render_paginated_table(
|
||||
query,
|
||||
page: int,
|
||||
title: str,
|
||||
headers: dict,
|
||||
entry_route: str,
|
||||
row_fn: Callable[[Any], List[dict]],
|
||||
endpoint: str,
|
||||
per_page=15,
|
||||
breadcrumb=[],
|
||||
extra_args={}
|
||||
):
|
||||
data = make_paginated_data(query, page, per_page)
|
||||
return render_template(
|
||||
"table.html",
|
||||
header=headers.keys(),
|
||||
rows=[{"id": item.id, "cells": row_fn(item)} for item in data['items']],
|
||||
title=title,
|
||||
has_next=data['has_next'],
|
||||
has_prev=data['has_prev'],
|
||||
page=page,
|
||||
endpoint=endpoint,
|
||||
total_pages=data['total_pages'],
|
||||
headers=headers,
|
||||
entry_route=entry_route,
|
||||
breadcrumb=breadcrumb,
|
||||
extra_args=extra_args
|
||||
)
|
||||
|
||||
@main.route("/")
|
||||
def index():
|
||||
cutoff = datetime.utcnow() - timedelta(days=14)
|
||||
|
||||
worklog_query = eager_load_worklog_relationships(
|
||||
db.session.query(WorkLog)
|
||||
).filter(
|
||||
|
@ -171,7 +119,6 @@ def index():
|
|||
else:
|
||||
pivot = pd.Series([0] * len(expected_conditions), index=expected_conditions)
|
||||
|
||||
|
||||
# Convert pandas/numpy int64s to plain old Python ints
|
||||
pivot = pivot.astype(int)
|
||||
labels = list(pivot.index)
|
||||
|
@ -210,7 +157,6 @@ def index():
|
|||
datasets=datasets
|
||||
)
|
||||
|
||||
|
||||
def link(text, endpoint, **values):
|
||||
return {"text": text, "url": url_for(endpoint, **values)}
|
||||
|
||||
|
@ -287,7 +233,7 @@ def inventory_index():
|
|||
|
||||
return render_template('inventory_index.html', title=f"Inventory ({category.capitalize()} Index)" if category else "Inventory", category=category, listing=listing)
|
||||
|
||||
@main.route("/inventory_item/<int:id>")
|
||||
@main.route("/inventory_item/<int:id>", methods=['GET', 'POST'])
|
||||
def inventory_item(id):
|
||||
inventory_query = db.session.query(Inventory)
|
||||
item = eager_load_inventory_relationships(inventory_query).filter(Inventory.id == id).first()
|
||||
|
@ -312,6 +258,23 @@ def inventory_item(id):
|
|||
types=types
|
||||
)
|
||||
|
||||
@main.route("/inventory_item/new", methods=['GET', 'POST'])
|
||||
def new_inventory_item():
|
||||
brands = db.session.query(Brand).all()
|
||||
users = eager_load_user_relationships(db.session.query(User)).all()
|
||||
rooms = eager_load_room_relationships(db.session.query(Room)).all()
|
||||
types = db.session.query(Item).all()
|
||||
|
||||
if request.method == 'POST':
|
||||
# Handle form submission logic here
|
||||
pass
|
||||
# If GET request, render the form for creating a new inventory item
|
||||
if not brands:
|
||||
return render_template("error.html", title="No Brands Found", message="Please add at least one brand before creating an inventory item.")
|
||||
|
||||
return render_template("inventory.html", title="New Inventory Item",
|
||||
brands=brands, users=users, rooms=rooms, types=types)
|
||||
|
||||
@main.route("/users")
|
||||
def list_users():
|
||||
query = eager_load_user_relationships(db.session.query(User)).order_by(User.last_name, User.first_name)
|
||||
|
@ -435,11 +398,99 @@ def search():
|
|||
|
||||
return render_template('search.html', title=f"Database Search ({query})" if query else "Database Search", results=results, query=query)
|
||||
|
||||
@main.route('/settings')
|
||||
@main.route('/settings', methods=['GET', 'POST'])
|
||||
def settings():
|
||||
if request.method == 'POST':
|
||||
print("⚠️⚠️⚠️ POST /settings reached! ⚠️⚠️⚠️")
|
||||
form = request.form
|
||||
print("📝 Raw form payload:", form)
|
||||
|
||||
try:
|
||||
state = json.loads(form['formState'])
|
||||
except Exception as e:
|
||||
flash("Invalid form state submitted. JSON decode failed.", "danger")
|
||||
traceback.print_exc()
|
||||
return redirect(url_for('main.settings'))
|
||||
|
||||
# === 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 else None
|
||||
function_id = int(raw_function) if raw_function else None
|
||||
|
||||
# Resolve negative or unmapped IDs
|
||||
if section_id is None or section_id < 0:
|
||||
section_name = state['sections'][abs(section_id + 1)]
|
||||
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_name = state['functions'][abs(function_id + 1)]
|
||||
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.")
|
||||
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()
|
||||
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()
|
||||
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)
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue