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

@@ -152,11 +152,12 @@ def register_blueprints(app: Flask):
def register_cli_commands(app: Flask):
"""Register Flask CLI commands."""
from .plugins.cli import plugin_cli
from .cli import db_cli, seed_cli
from .cli import db_cli, seed_cli, relationships_cli
app.cli.add_command(plugin_cli)
app.cli.add_command(db_cli)
app.cli.add_command(seed_cli)
app.cli.add_command(relationships_cli)
def register_error_handlers(app: Flask):

View File

@@ -1,7 +1,11 @@
"""Models (vendor model catalog) API endpoints - Full CRUD."""
from flask import Blueprint, request
import glob
import os
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.extensions import db
from shopdb.core.models import Model
@@ -18,6 +22,20 @@ from shopdb.utils.import_mode import apply_import_timestamps
models_bp = Blueprint('models', __name__)
# Uploaded model photos live in the instance dir and are served publicly
# (asset detail pages read the model image without auth). Same image set the
# map/branding uploads accept.
MODEL_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
# URL prefix an uploaded image resolves to. imageurl values with this prefix
# are our own files under the instance dir; anything else (external URLs or the
# shipped /images/models/* assets) is left on disk untouched.
MODEL_IMAGE_URL_PREFIX = '/api/models/image/'
def _modelimage_dir():
return os.path.join(current_app.instance_path, 'modelimages')
@models_bp.route('', methods=['GET'])
@jwt_required(optional=True)
@@ -162,3 +180,83 @@ def delete_model(model_id: int):
db.session.commit()
return success_response(message='Model deleted')
@models_bp.route('/<int:model_id>/image', methods=['POST'])
@jwt_required()
@require_role('admin')
def upload_model_image(model_id: int):
"""Upload (or replace) the photo for a model.
multipart/form-data: file=<image>. Saves to the instance modelimages dir as
model-<id><ext> (one image per model) and points model.imageurl at the
served URL. Re-upload replaces the old file even when the extension changes.
"""
m = db.session.get(Model, model_id)
if not m:
return error_response(
ErrorCodes.NOT_FOUND,
f'Model with ID {model_id} 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 MODEL_IMAGE_EXTENSIONS:
return error_response(ErrorCodes.VALIDATION_ERROR,
f'Unsupported image type {ext}')
imagedir = _modelimage_dir()
os.makedirs(imagedir, exist_ok=True)
# Wipe any prior model-<id>.* file so a new extension does not orphan the old
# one (one image per model).
for old in glob.glob(os.path.join(imagedir, secure_filename(f'model-{model_id}') + '.*')):
os.remove(old)
filename = secure_filename(f'model-{model_id}{ext}')
upload.save(os.path.join(imagedir, filename))
m.imageurl = f'{MODEL_IMAGE_URL_PREFIX}{filename}'
db.session.commit()
return success_response(m.to_dict(), message='Model image uploaded')
@models_bp.route('/image/<path:filename>', methods=['GET'])
def serve_model_image(filename):
"""Serve an uploaded model image (public - asset detail pages read it)."""
return send_from_directory(_modelimage_dir(), filename)
@models_bp.route('/<int:model_id>/image', methods=['DELETE'])
@jwt_required()
@require_role('admin')
def delete_model_image(model_id: int):
"""Clear a model image and delete the uploaded file if we own it.
External URLs and the shipped /images/models/* assets are never touched on
disk - only the imageurl field is cleared.
"""
m = db.session.get(Model, model_id)
if not m:
return error_response(
ErrorCodes.NOT_FOUND,
f'Model with ID {model_id} not found',
http_code=404
)
url = m.imageurl or ''
if url.startswith(MODEL_IMAGE_URL_PREFIX):
# secure_filename strips any traversal; the file lives in our dir only.
filename = secure_filename(url[len(MODEL_IMAGE_URL_PREFIX):])
path = os.path.join(_modelimage_dir(), filename)
if os.path.exists(path):
os.remove(path)
m.imageurl = None
db.session.commit()
return success_response(m.to_dict(), message='Model image removed')

View File

@@ -9,7 +9,7 @@ from .businessunit import BusinessUnit
from .dashboarddefault import DashboardDefault
from .location import Location, LocationType
from .operatingsystem import OperatingSystem
from .relationship import AssetRelationship, RelationshipType
from .relationship import AssetRelationship, RelationshipType, RelationshipTypePropagation
from .communication import Communication, CommunicationType
from .user import User, Role, Permission
from .application import Application, AppVersion
@@ -40,6 +40,7 @@ __all__ = [
# Relationships
'AssetRelationship',
'RelationshipType',
'RelationshipTypePropagation',
# Communication
'Communication',
'CommunicationType',