Add photo management for models and employees; fix stale detail navigation
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:
@@ -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')
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Add photofilename to directoryemployees (self-hosted employee photos).
|
||||
|
||||
The core chain (7d16_directoryemployees) created directoryemployees WITHOUT a
|
||||
photofilename column. This plugin revision adds it, so BOTH fresh installs (core
|
||||
chain builds the table, then this adds the column) and existing installs get it.
|
||||
Guarded/idempotent: skips when the table is absent (plugin disabled) or the
|
||||
column already exists (e.g. a test DB built by db.create_all() from the model).
|
||||
|
||||
Revision ID: employees0002photo
|
||||
Revises: employees0001anchor
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'employees0002photo'
|
||||
down_revision = 'employees0001anchor'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if 'directoryemployees' not in insp.get_table_names():
|
||||
return
|
||||
cols = {c['name'] for c in insp.get_columns('directoryemployees')}
|
||||
if 'photofilename' not in cols:
|
||||
op.add_column('directoryemployees',
|
||||
sa.Column('photofilename', sa.String(length=255), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if 'directoryemployees' not in insp.get_table_names():
|
||||
return
|
||||
cols = {c['name'] for c in insp.get_columns('directoryemployees')}
|
||||
if 'photofilename' in cols:
|
||||
op.drop_column('directoryemployees', 'photofilename')
|
||||
@@ -6,6 +6,11 @@ external directory, and the directory is managed in-app (CRUD + CSV import).
|
||||
|
||||
to_dict emits the same keys the external contract returns (SSO, First_Name,
|
||||
Last_Name, Team, Role, Picture) so the frontend and both modes share one shape.
|
||||
|
||||
photofilename holds the basename of an uploaded photo (photo-<sso><ext>) served
|
||||
from instance/employeephotos/. It is distinct from the legacy Picture text
|
||||
field: in self-hosted mode the displayed photo comes from uploads (photofilename)
|
||||
via the shared resolver, not from Picture.
|
||||
"""
|
||||
|
||||
from shopdb.api import db
|
||||
@@ -20,9 +25,13 @@ class DirectoryEmployee(db.Model):
|
||||
team = db.Column(db.String(100))
|
||||
role = db.Column(db.String(100))
|
||||
picture = db.Column(db.String(255))
|
||||
# basename of an uploaded photo (photo-<sso><ext>); None when no upload
|
||||
photofilename = db.Column(db.String(255))
|
||||
|
||||
def to_dict(self):
|
||||
# Keys match the external employees contract the frontend consumes.
|
||||
# photofilename is extra (self-hosted upload); the resolved display URL
|
||||
# is added as photourl by the API layer via resolve_employee_photo_url.
|
||||
return {
|
||||
'SSO': self.sso,
|
||||
'First_Name': self.firstname,
|
||||
@@ -30,4 +39,5 @@ class DirectoryEmployee(db.Model):
|
||||
'Team': self.team,
|
||||
'Role': self.role,
|
||||
'Picture': self.picture,
|
||||
'photofilename': self.photofilename,
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ from zoneinfo import ZoneInfo
|
||||
from flask import Blueprint, request
|
||||
from flask_jwt_extended import jwt_required
|
||||
|
||||
from shopdb.api import db, success_response, error_response, paginated_response, ErrorCodes, get_pagination_params, paginate_query, employee_connection
|
||||
from shopdb.api import db, success_response, error_response, paginated_response, ErrorCodes, get_pagination_params, paginate_query
|
||||
|
||||
from ..models import Notification, NotificationType
|
||||
|
||||
@@ -150,16 +150,12 @@ def _config_version():
|
||||
|
||||
|
||||
def _employee_picture(sso):
|
||||
"""Best-effort Picture blob for an SSO from the HR directory. None on any miss."""
|
||||
if not (sso and str(sso).isdigit()):
|
||||
return None
|
||||
"""Resolved display photo URL for an SSO, via the shared employees-plugin
|
||||
resolver so kiosk cards match EmployeeDetail in both directory modes
|
||||
(self-hosted upload URL or external HR URL). None on any miss."""
|
||||
try:
|
||||
conn = employee_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute('SELECT Picture FROM employees WHERE SSO = %s', (int(sso),))
|
||||
emp = cur.fetchone()
|
||||
conn.close()
|
||||
return emp.get('Picture') if emp else None
|
||||
from plugins.employees.api.routes import resolve_employee_photo_url
|
||||
return resolve_employee_photo_url(sso)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
Reference in New Issue
Block a user