Add photo management for models and employees; fix stale detail navigation
Some checks failed
CI / backend (push) Failing after 9s
CI / naming (push) Successful in 1s
CI / frontend (push) Successful in 7s

Model photos: upload/replace/delete on /api/models/<id>/image (admin),
stored under instance/modelimages/ with a public serve route; thumbnail
plus Upload/Replace/Remove controls in the Models settings modal; the
URL field remains as a manual alternative.

Employee photos, mode-aware: self-hosted directory employees get
upload/replace/delete (photo-<sso> under instance/employeephotos/,
employees plugin migration 0002); external directory mode passes the
HR-supplied picture URL through read-only (writes 409). One resolver
feeds both consumers - the shopfloor recognition/recert kiosk cards and
the employee detail hero - in either mode.

Navigation fix: router-view is keyed on route path, so following a
relationship link between two assets of the same type (machine ->
dualpath machine) reloads the page instead of showing stale content;
query-only URL changes still avoid a remount.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
cproudlock
2026-07-11 21:00:37 -04:00
parent 7dae281993
commit 1d21bf0206
19 changed files with 926 additions and 29 deletions

View File

@@ -8,11 +8,14 @@ never return more than the directory fields below.
"""
import csv
import glob
import io
import logging
import os
from flask import Blueprint, request
from flask import Blueprint, request, current_app, send_from_directory
from flask_jwt_extended import jwt_required
from werkzeug.utils import secure_filename
from shopdb.api import (
db,
@@ -33,6 +36,22 @@ employees_bp = Blueprint('employees', __name__)
# Columns safe to expose to the directory/recognition UI
_FIELDS = 'SSO, First_Name, Last_Name, Team, Role, Picture'
# Uploaded self-hosted employee photos live in the instance dir and are served
# publicly (kiosk recognition/recertification cards read them without auth).
EMPLOYEE_PHOTO_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
# URL prefix a served upload resolves to (self-hosted mode).
EMPLOYEE_PHOTO_URL_PREFIX = '/api/employees/photo/'
# URL prefix external HR relative picture paths resolve under. The HR employees
# table stores Picture as a relative path (e.g. 'Support/210009518.png') that
# the site serves from /static/employees/; this matches the shopfloor feed.
EMPLOYEE_PHOTO_STATIC_PREFIX = '/static/employees/'
def _employeephoto_dir():
return os.path.join(current_app.instance_path, 'employeephotos')
def _selfhosted():
"""True when the directory is the app-owned table, not an external HR DB."""
@@ -50,6 +69,74 @@ def _require_selfhosted():
return None
def _require_selfhosted_photo():
"""Guard for photo write endpoints - 409 when the directory is external.
In external mode the photo is owned by the HR database (read-only
pass-through), so upload/delete cannot apply here."""
if not _selfhosted():
return error_response(
ErrorCodes.CONFLICT,
'Employee directory is external; photos are supplied by the HR '
'database and cannot be uploaded or deleted here.',
http_code=409)
return None
def _external_photo_url(picture):
"""Turn an external HR Picture value into a usable URL, or None.
Absolute URLs and already-rooted paths pass through untouched (future
full-URL HR feeds); a bare relative path is served under the static prefix
(current WJ convention, e.g. 'Support/210009518.png')."""
if not picture:
return None
text = str(picture).strip()
if not text:
return None
if text.startswith(('http://', 'https://', '/')):
return text
return EMPLOYEE_PHOTO_STATIC_PREFIX + text
def _hr_picture(sso):
"""Raw Picture value for an SSO from the external HR directory. None on miss."""
try:
conn = employee_connection()
with conn.cursor() as cur:
cur.execute('SELECT Picture FROM employees WHERE SSO = %s', (int(sso),))
row = cur.fetchone()
conn.close()
return row.get('Picture') if row else None
except Exception:
return None
def resolve_employee_photo_url(sso, external_picture=None):
"""Single resolver both consumers share: the display photo URL for an SSO.
Self-hosted: the served upload URL when the employee has an uploaded photo,
else None (the legacy Picture text field does not drive the photo here).
External: the HR-supplied Picture resolved to a URL (pass external_picture to
avoid a re-query), else None. Returns None on any miss or bad SSO."""
if sso is None or not str(sso).isdigit():
return None
if _selfhosted():
emp = db.session.get(DirectoryEmployee, int(sso))
if emp and emp.photofilename:
return EMPLOYEE_PHOTO_URL_PREFIX + emp.photofilename
return None
picture = external_picture if external_picture is not None else _hr_picture(sso)
return _external_photo_url(picture)
def _with_photo_url(employee):
"""Add the resolved photourl to an employee dict (self-hosted or external)."""
employee['photourl'] = resolve_employee_photo_url(
employee.get('SSO'), employee.get('Picture'))
return employee
@employees_bp.route('/search', methods=['GET'])
def search_employees():
"""
@@ -76,7 +163,7 @@ def search_employees():
db.cast(DirectoryEmployee.sso, db.String).ilike(term)))
.order_by(DirectoryEmployee.lastname, DirectoryEmployee.firstname)
.limit(limit).all())
return success_response([e.to_dict() for e in rows])
return success_response([_with_photo_url(e.to_dict()) for e in rows])
try:
conn = employee_connection()
@@ -92,7 +179,7 @@ def search_employees():
''', (f'%{query}%', f'%{query}%', f'%{query}%', limit))
employees = cur.fetchall()
conn.close()
return success_response(employees)
return success_response([_with_photo_url(e) for e in employees])
except Exception:
logger.exception('Employee search failed')
return error_response(
@@ -116,7 +203,7 @@ def lookup_employee(sso):
if not emp:
return error_response(ErrorCodes.NOT_FOUND,
f'Employee with SSO {sso} not found', http_code=404)
return success_response(emp.to_dict())
return success_response(_with_photo_url(emp.to_dict()))
try:
conn = employee_connection()
@@ -135,7 +222,7 @@ def lookup_employee(sso):
http_code=404
)
return success_response(employee)
return success_response(_with_photo_url(employee))
except Exception:
logger.exception('Employee lookup failed for SSO %s', sso)
return error_response(
@@ -165,7 +252,7 @@ def lookup_employees():
if _selfhosted():
rows = DirectoryEmployee.query.filter(
DirectoryEmployee.sso.in_([int(s) for s in ssos])).all()
employees = [e.to_dict() for e in rows]
employees = [_with_photo_url(e.to_dict()) for e in rows]
names = ', '.join(f"{e['First_Name'].strip()} {e['Last_Name'].strip()}"
for e in employees)
return success_response({'employees': employees, 'names': names})
@@ -181,6 +268,7 @@ def lookup_employees():
employees = cur.fetchall()
conn.close()
employees = [_with_photo_url(e) for e in employees]
names = ', '.join(
f"{e['First_Name'].strip()} {e['Last_Name'].strip()}"
for e in employees
@@ -212,7 +300,7 @@ def list_directory():
return guard
rows = (DirectoryEmployee.query
.order_by(DirectoryEmployee.lastname, DirectoryEmployee.firstname).all())
return success_response([e.to_dict() for e in rows])
return success_response([_with_photo_url(e.to_dict()) for e in rows])
def _employee_from_payload(data):
@@ -337,3 +425,80 @@ def import_directory():
db.session.commit()
return success_response({'added': added, 'updated': updated, 'skipped': skipped},
message=f'Import done: {added} added, {updated} updated, {skipped} skipped.')
# =============================================================================
# Self-hosted employee photos (upload/replace/delete + public serve)
# =============================================================================
@employees_bp.route('/<int:sso>/photo', methods=['POST'])
@jwt_required()
@require_role('admin')
def upload_employee_photo(sso):
"""Upload (or replace) the photo for a self-hosted directory employee.
multipart/form-data: file=<image>. Saves to the instance employeephotos dir
as photo-<sso><ext> (one photo per person) and points photofilename at it.
Re-upload replaces the old file even when the extension changes. External
mode is a 409 (photo is owned by the HR database)."""
guard = _require_selfhosted_photo()
if guard:
return guard
emp = db.session.get(DirectoryEmployee, sso)
if not emp:
return error_response(ErrorCodes.NOT_FOUND, 'Employee not found', http_code=404)
upload = request.files.get('file')
if not upload or not upload.filename:
return error_response(ErrorCodes.VALIDATION_ERROR, 'No file provided')
ext = os.path.splitext(upload.filename)[1].lower()
if ext not in EMPLOYEE_PHOTO_EXTENSIONS:
return error_response(ErrorCodes.VALIDATION_ERROR,
f'Unsupported image type {ext}')
photodir = _employeephoto_dir()
os.makedirs(photodir, exist_ok=True)
# Wipe any prior photo-<sso>.* so a new extension does not orphan the old one.
for old in glob.glob(os.path.join(photodir, secure_filename(f'photo-{sso}') + '.*')):
os.remove(old)
filename = secure_filename(f'photo-{sso}{ext}')
upload.save(os.path.join(photodir, filename))
emp.photofilename = filename
db.session.commit()
return success_response(_with_photo_url(emp.to_dict()), message='Employee photo uploaded')
@employees_bp.route('/photo/<path:filename>', methods=['GET'])
def serve_employee_photo(filename):
"""Serve an uploaded employee photo (public - kiosk cards read it)."""
return send_from_directory(_employeephoto_dir(), filename)
@employees_bp.route('/<int:sso>/photo', methods=['DELETE'])
@jwt_required()
@require_role('admin')
def delete_employee_photo(sso):
"""Clear an employee photo and delete the uploaded file. External mode 409s."""
guard = _require_selfhosted_photo()
if guard:
return guard
emp = db.session.get(DirectoryEmployee, sso)
if not emp:
return error_response(ErrorCodes.NOT_FOUND, 'Employee not found', http_code=404)
if emp.photofilename:
# secure_filename strips any traversal; the file lives in our dir only.
path = os.path.join(_employeephoto_dir(), secure_filename(emp.photofilename))
if os.path.exists(path):
os.remove(path)
emp.photofilename = None
db.session.commit()
return success_response(_with_photo_url(emp.to_dict()), message='Employee photo removed')