Add user creation and update functionality; refactor user template and helpers

This commit is contained in:
Yaro Kasear 2025-07-07 15:36:15 -05:00
parent f4369348c5
commit 26e55b9a3e
6 changed files with 134 additions and 24 deletions

View file

@ -1,4 +1,4 @@
from typing import List, Optional, TYPE_CHECKING from typing import Any, List, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from .inventory import Inventory from .inventory import Inventory
from .rooms import Room from .rooms import Room
@ -55,3 +55,14 @@ class User(db.Model):
'staff': self.staff, 'staff': self.staff,
'active': self.active 'active': self.active
} }
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "User":
return cls(
staff=bool(data.get("staff", False)),
active=bool(data.get("active", False)),
last_name=data.get("last_name"),
first_name=data.get("first_name"),
location_id=data.get("location_id"),
supervisor_id=data.get("supervisor_id")
)

View file

@ -19,9 +19,7 @@ inventory_headers = {
} }
checked_box = ''' checked_box = '''
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check2" viewBox="0 0 16 16"> <i class="bi bi-check2"></i>
<path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0"/>
</svg>
''' '''
unchecked_box = '' unchecked_box = ''

View file

@ -11,15 +11,10 @@ from ..utils.load import eager_load_room_relationships
@main.route('/settings', methods=['GET', 'POST']) @main.route('/settings', methods=['GET', 'POST'])
def settings(): def settings():
if request.method == 'POST': if request.method == 'POST':
print("⚠️⚠️⚠️ POST /settings reached! ⚠️⚠️⚠️")
form = request.form form = request.form
print("📝 Raw form payload:", form)
try: try:
state = json.loads(form['formState']) state = json.loads(form['formState'])
import pprint
print("🧠 Parsed state:")
pprint.pprint(state, indent=2, width=120)
except Exception: 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()
@ -58,12 +53,9 @@ def settings():
function_map=function_map function_map=function_map
) )
print("✅ COMMIT executed.")
flash("Changes saved.", "success") flash("Changes saved.", "success")
except Exception as e: except Exception as e:
print("❌ COMMIT FAILED ❌")
traceback.print_exc()
flash(f"Error saving changes: {e}", "danger") flash(f"Error saving changes: {e}", "danger")
return redirect(url_for('main.settings')) return redirect(url_for('main.settings'))

View file

@ -1,4 +1,4 @@
from flask import render_template from flask import render_template, request, jsonify
from . import main from . import main
from .helpers import ACTIVE_STATUSES, user_headers, inventory_headers, worklog_headers from .helpers import ACTIVE_STATUSES, user_headers, inventory_headers, worklog_headers
@ -64,3 +64,60 @@ def user(id):
worklog_headers=filtered_worklog_headers, worklog_headers=filtered_worklog_headers,
worklog_rows=[{"id": log.id, "cells": [fn(log) for fn in filtered_worklog_headers.values()]} for log in worklog] worklog_rows=[{"id": log.id, "cells": [fn(log) for fn in filtered_worklog_headers.values()]} for log in worklog]
) )
@main.route("/user/new", methods=["GET"])
def new_user():
rooms = eager_load_room_relationships(db.session.query(Room)).all()
users = eager_load_user_relationships(db.session.query(User)).all()
user = User(
active=True
)
return render_template(
"user.html",
title="New User",
user=user,
users=users,
rooms=rooms
)
@main.route("/api/user", methods=["POST"])
def create_user():
try:
data = request.get_json(force=True)
new_user = User.from_dict(data)
db.session.add(new_user)
db.session.commit()
return jsonify({"success": True, "id": new_user.id}), 201
except Exception as e:
db.session.rollback()
return jsonify({"success": False, "error": str(e)}), 400
@main.route("/api/user/<int:id>", methods=["PUT"])
def update_user(id):
try:
data = request.get_json(force=True)
user = db.session.query(User).get(id)
if not user:
return jsonify({"success": False, "error": f"User with ID {id} not found."}), 404
user.staff = bool(data.get("staff", user.staff))
user.active = bool(data.get("active", user.active))
user.last_name = data.get("last_name", user.last_name)
user.first_name = data.get("first_name", user.first_name)
user.location_id = data.get("location_id", user.location_id)
user.supervisor_id = data.get("supervisor_id", user.supervisor_id)
db.session.commit()
return jsonify({"success": True, "id": user.id}), 200
except Exception as e:
db.session.rollback()
return jsonify({"success": False, "error": str(e)}), 400

View file

@ -157,7 +157,7 @@
const id = document.querySelector("#inventoryId").value; const id = document.querySelector("#inventoryId").value;
const isEdit = id && id !== "None"; const isEdit = id && id !== "None";
const endpoint = isEdit ? `/api/inventory/${id}` : "/api/inventory" const endpoint = isEdit ? `/api/inventory/${id}` : "/api/inventory";
const method = isEdit ? "PUT" : "POST"; const method = isEdit ? "PUT" : "POST";
const response = await fetch(endpoint, { const response = await fetch(endpoint, {

View file

@ -10,23 +10,25 @@
title=title, title=title,
breadcrumbs=[ breadcrumbs=[
{'label': 'Users', 'url': url_for('main.list_users')} {'label': 'Users', 'url': url_for('main.list_users')}
] ],
save_button = True
) }} ) }}
{% if not user.active %} {% if not user.active %}
<div class="alert alert-danger">This user is inactive. You will not be able to make any changes to this record.</div> <div class="alert alert-danger">This user is inactive. You will not be able to make any changes to this record.</div>
{% endif %} {% endif %}
<input type="hidden" id="userId" value="{{ user.id }}">
<div class="container"> <div class="container">
<form action="POST"> <form action="POST">
<div class="row"> <div class="row">
<div class="col-6"> <div class="col-6">
<label for="lastName" class="form-label">Last Name</label> <label for="lastName" class="form-label">Last Name</label>
<input type="text" class="form-control" id="lastName" placeholder="Doe" value="{{ user.last_name }}"{% if not user.active %} disabled readonly{% endif %}> <input type="text" class="form-control" id="lastName" name="lastName" placeholder="Doe" value="{{ user.last_name if user.last_name else '' }}"{% if not user.active %} disabled readonly{% endif %}>
</div> </div>
<div class="col-6"> <div class="col-6">
<label for="firstName" class="form-label">First Name</label> <label for="firstName" class="form-label">First Name</label>
<input type="text" class="form-control" id="firstName" placeholder="John" value="{{ user.first_name }}"{% if not user.active %} disabled readonly{% endif %}> <input type="text" class="form-control" id="firstName" name="firstName" placeholder="John" value="{{ user.first_name if user.first_name else '' }}"{% if not user.active %} disabled readonly{% endif %}>
</div> </div>
</div> </div>
@ -61,11 +63,11 @@ breadcrumbs=[
</div> </div>
<div class="row mt-4"> <div class="row mt-4">
<div class="col-6"> <div class="col-6">
<input type="checkbox" class="form-check-input" id="activeCheck"{% if user.active %} checked{% endif %}> <input type="checkbox" class="form-check-input" id="activeCheck" name="activeCheck"{% if user.active %} checked{% endif %}>
<label for="activeCheck" class="form-check-label">Active</label> <label for="activeCheck" class="form-check-label">Active</label>
</div> </div>
<div class="col-6"> <div class="col-6">
<input type="checkbox" class="form-check-input" id="staffCheck"{% if user.staff %} checked{% endif %}{% if not user.active %} disabled readonly{% endif %}> <input type="checkbox" class="form-check-input" id="staffCheck" name="staffCheck"{% if user.staff %} checked{% endif %}{% if not user.active %} disabled readonly{% endif %}>
<label for="staffCheck" class="form-check-label">Staff</label> <label for="staffCheck" class="form-check-label">Staff</label>
</div> </div>
</div> </div>
@ -88,3 +90,53 @@ breadcrumbs=[
</div> </div>
</div> </div>
{% endblock %} {% endblock %}
{% block script %}
const saveButton = document.getElementById("saveButton");
const deleteButton = document.getElementById("deleteButton");
if (saveButton) {
saveButton.addEventListener("click", async (e) => {
e.preventDefault();
const payload = {
staff: document.querySelector("input[name='staffCheck']").checked,
active: document.querySelector("input[name='activeCheck']").checked,
last_name: document.querySelector("input[name='lastName']").value,
first_name: document.querySelector("input[name='firstName']").value,
supervisor_id: parseInt(document.querySelector("select[name='supervisor']").value) || null,
location_id: parseInt(document.querySelector("select[name='location']").value) || null
};
try {
const id = document.querySelector("#userId").value;
const isEdit = id && id !== "None";
const endpoint = isEdit ? `/api/user/${id}` : "/api/user";
const method = isEdit ? "PUT" : "POST";
const response = await fetch(endpoint, {
method,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
const result = await response.json();
if (result.success) {
localStorage.setItem("toastMessage", JSON.stringify({
message: isEdit ? "User updated!" : "User created!",
type: "success"
}));
window.location.href = `/user/${result.id}`;
} else {
renderToast({ message: `Error: ${result.error}`, type: "danger" });
}
} catch (err) {
console.error(err);
}
});
}
{% endblock %}