Initial import: shopdb-flask multi-site asset platform
Flask + Vue rewrite of the classic-ASP shopdb, built as a plugin framework so sister GE Aerospace sites can adopt it. Product version 0.7.0-pre-0.8.0, plugin contract 0.11.0, 966 backend tests. Key entry points: - docs/INSTALL-WINDOWS-IIS.md - tested Windows + IIS install runbook (own-site and subpath deployment methods) - docs/PILOT-DEPLOY.md - production pilot: stand up + import + verify - docs/IMPORT-API.md - schema-agnostic legacy data import contract - scripts/site_imports/wjf/ - West Jefferson reference import loader - docs/adr/ - twelve accepted architecture decision records
This commit is contained in:
133
plugins/employees/README.md
Normal file
133
plugins/employees/README.md
Normal file
@@ -0,0 +1,133 @@
|
||||
# Employees plugin - directory database contract
|
||||
|
||||
Read-only lookups against a **separate** employee/HR directory database. Powers:
|
||||
|
||||
- Employee search (add people to a notification, browse the directory)
|
||||
- Single + batch SSO lookup
|
||||
- Recognition notifications (name + photo on the shopfloor / lobby displays)
|
||||
|
||||
The plugin never writes to this database. Use a read-only account.
|
||||
|
||||
> **This is the integration most likely to differ per site.** HR / directory
|
||||
> systems vary widely, so expect to map a site's schema to the contract below -
|
||||
> the `CREATE VIEW` recipe at the end is the normal way to do it.
|
||||
|
||||
## Connection
|
||||
|
||||
Credentials resolve **settings-first, then environment**, except the password
|
||||
which is env-only (never stored in the app database).
|
||||
|
||||
| Field | Setting key (editable in the setup wizard) | Env var (fallback) |
|
||||
| -------- | ------------------------------------------ | ---------------------- |
|
||||
| Host | `employee_db_host` | `EMPLOYEE_DB_HOST` |
|
||||
| Database | `employee_db_name` | `EMPLOYEE_DB_NAME` |
|
||||
| User | `employee_db_user` | `EMPLOYEE_DB_USER` |
|
||||
| Password | (not stored) | `EMPLOYEE_DB_PASSWORD` |
|
||||
|
||||
Set the password in `.env`; the setup wizard's Features step shows the exact
|
||||
line to paste. Engine is MySQL/MariaDB (pymysql).
|
||||
|
||||
## Required schema
|
||||
|
||||
The plugin runs these queries verbatim, so a site's database must expose a
|
||||
table (or **view** - see below) named `employees` with these columns:
|
||||
|
||||
| Column | Type | Notes |
|
||||
| ------------ | ------------------- | ------------------------------------------------- |
|
||||
| `SSO` | INT | Unique person id. Lookups require it to be numeric |
|
||||
| `First_Name` | VARCHAR | Displayed as the given name |
|
||||
| `Last_Name` | VARCHAR | Displayed as the surname; sort key |
|
||||
| `Team` | VARCHAR | Team / group label |
|
||||
| `Role` | VARCHAR | Job title / role |
|
||||
| `Picture` | VARCHAR | **Image filename** (see Photos) |
|
||||
|
||||
Queries actually executed:
|
||||
|
||||
```sql
|
||||
-- search
|
||||
SELECT SSO, First_Name, Last_Name, Team, Role, Picture
|
||||
FROM employees
|
||||
WHERE First_Name LIKE %s OR Last_Name LIKE %s OR CAST(SSO AS CHAR) LIKE %s
|
||||
ORDER BY Last_Name, First_Name LIMIT %s;
|
||||
|
||||
-- single / batch
|
||||
SELECT SSO, First_Name, Last_Name, Team, Role, Picture FROM employees WHERE SSO = %s;
|
||||
SELECT SSO, First_Name, Last_Name, Team, Role, Picture FROM employees WHERE SSO IN (...);
|
||||
```
|
||||
|
||||
Rows are returned to the API **with these exact column names**. The frontend
|
||||
(EmployeeSearch, NotificationForm, EmployeeDetail, ShopfloorDashboard) reads
|
||||
`SSO`, `First_Name`, `Last_Name`, `Team`, `Role`, `Picture` as-is - do not
|
||||
rename them in the response.
|
||||
|
||||
## Photos
|
||||
|
||||
`Picture` holds an **image filename** (e.g. `123456.jpg`), not a path or blob.
|
||||
The app renders it as `/static/employees/<Picture>`, so the image files must
|
||||
live in the app's `static/employees/` directory. Leave `Picture` empty/NULL for
|
||||
people with no photo; the UI falls back to initials.
|
||||
|
||||
## Two ways to provide the directory
|
||||
|
||||
**Option A - map an existing HR/directory database** (see the view recipe
|
||||
below). Use this when the site already has a system of record for people.
|
||||
|
||||
**Option B - self-hosted directory (managed in-app)** for sites with no HR
|
||||
database. Set `employee_directory_mode` to `selfhosted` and manage people under
|
||||
**Settings > Employee Directory** (add / edit / delete + CSV import) - no SQL
|
||||
needed. The app owns a `directoryemployees` table (migration 7d16); the lookup
|
||||
APIs read it automatically in this mode.
|
||||
|
||||
If you would rather load it with SQL, the canonical table is equivalent to:
|
||||
|
||||
```sql
|
||||
CREATE DATABASE shopdb_directory CHARACTER SET utf8mb4;
|
||||
USE shopdb_directory;
|
||||
|
||||
CREATE TABLE employees (
|
||||
SSO INT NOT NULL PRIMARY KEY,
|
||||
First_Name VARCHAR(100) NOT NULL,
|
||||
Last_Name VARCHAR(100) NOT NULL,
|
||||
Team VARCHAR(100) NULL,
|
||||
Role VARCHAR(100) NULL,
|
||||
Picture VARCHAR(255) NULL
|
||||
);
|
||||
|
||||
-- add people (or bulk-load from CSV with LOAD DATA INFILE)
|
||||
INSERT INTO employees (SSO, First_Name, Last_Name, Team, Role, Picture)
|
||||
VALUES (123456, 'Jane', 'Doe', 'Inspection', 'Quality Tech', '123456.jpg');
|
||||
```
|
||||
|
||||
Put photo files (named as in `Picture`) under the app's `static/employees/`.
|
||||
In self-hosted mode the `directoryemployees` table lives in the main app DB, so
|
||||
no separate database is required.
|
||||
|
||||
## Adapting a different site schema (recommended: a view)
|
||||
|
||||
Sites whose HR/directory database uses different table or column names should
|
||||
**not** be forced to rename anything. Instead, create a read-only **view**
|
||||
named `employees` that maps local columns to the names above:
|
||||
|
||||
```sql
|
||||
CREATE VIEW employees AS
|
||||
SELECT
|
||||
person_id AS SSO,
|
||||
given_name AS First_Name,
|
||||
surname AS Last_Name,
|
||||
department AS Team,
|
||||
job_title AS Role,
|
||||
photo_filename AS Picture
|
||||
FROM hr_people
|
||||
WHERE active = 1;
|
||||
```
|
||||
|
||||
Grant the app's read-only user `SELECT` on the view. No app code changes -
|
||||
point `employee_db_*` at that database and the plugin works.
|
||||
|
||||
Notes:
|
||||
- `SSO` must be numeric (single/batch lookup validate `isdigit()`).
|
||||
- Column-name case follows your database's identifier casing; match the names
|
||||
above exactly on case-sensitive platforms.
|
||||
- If the directory is unreachable or the `employees` object is missing, lookups
|
||||
return a 500 and the rest of the app keeps working (the feature degrades, it
|
||||
does not crash the app).
|
||||
5
plugins/employees/__init__.py
Normal file
5
plugins/employees/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""Employees plugin package."""
|
||||
|
||||
from .plugin import EmployeesPlugin
|
||||
|
||||
__all__ = ['EmployeesPlugin']
|
||||
5
plugins/employees/api/__init__.py
Normal file
5
plugins/employees/api/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""Employees plugin API."""
|
||||
|
||||
from .routes import employees_bp
|
||||
|
||||
__all__ = ['employees_bp']
|
||||
504
plugins/employees/api/routes.py
Normal file
504
plugins/employees/api/routes.py
Normal file
@@ -0,0 +1,504 @@
|
||||
"""Employee lookup API endpoints.
|
||||
|
||||
These read from the separate employee directory DB (employee_connection is core
|
||||
infrastructure exposed via shopdb.api, shared with search + notifications). The
|
||||
endpoints are intentionally reachable by the unauthenticated shopfloor kiosk
|
||||
displays (recognition wall), so they are not JWT-gated; keep them read-only and
|
||||
never return more than the directory fields below.
|
||||
"""
|
||||
|
||||
import csv
|
||||
import glob
|
||||
import io
|
||||
import logging
|
||||
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.api import (
|
||||
db,
|
||||
success_response,
|
||||
error_response,
|
||||
ErrorCodes,
|
||||
employee_connection,
|
||||
require_role,
|
||||
)
|
||||
from shopdb.api import Setting
|
||||
|
||||
from ..models import DirectoryEmployee
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
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."""
|
||||
row = Setting.query.filter_by(key='employee_directory_mode').first()
|
||||
return (row.value if row and row.value else 'external').lower() == 'selfhosted'
|
||||
|
||||
|
||||
def _require_selfhosted():
|
||||
"""Guard for management endpoints - only valid in self-hosted mode."""
|
||||
if not _selfhosted():
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Directory is in external mode; manage people in the source HR database.',
|
||||
http_code=400)
|
||||
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():
|
||||
"""
|
||||
Search employees by name.
|
||||
|
||||
Query parameters:
|
||||
- q: Search query (searches first and last name)
|
||||
- limit: Max results (default 10)
|
||||
"""
|
||||
query = request.args.get('q', '').strip()
|
||||
limit = min(int(request.args.get('limit', 10)), 50)
|
||||
|
||||
if len(query) < 2:
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Search query must be at least 2 characters'
|
||||
)
|
||||
|
||||
if _selfhosted():
|
||||
term = f'%{query}%'
|
||||
rows = (DirectoryEmployee.query
|
||||
.filter(db.or_(DirectoryEmployee.firstname.ilike(term),
|
||||
DirectoryEmployee.lastname.ilike(term),
|
||||
db.cast(DirectoryEmployee.sso, db.String).ilike(term)))
|
||||
.order_by(DirectoryEmployee.lastname, DirectoryEmployee.firstname)
|
||||
.limit(limit).all())
|
||||
return success_response([_with_photo_url(e.to_dict()) for e in rows])
|
||||
|
||||
try:
|
||||
conn = employee_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(f'''
|
||||
SELECT {_FIELDS}
|
||||
FROM employees
|
||||
WHERE First_Name LIKE %s
|
||||
OR Last_Name LIKE %s
|
||||
OR CAST(SSO AS CHAR) LIKE %s
|
||||
ORDER BY Last_Name, First_Name
|
||||
LIMIT %s
|
||||
''', (f'%{query}%', f'%{query}%', f'%{query}%', limit))
|
||||
employees = cur.fetchall()
|
||||
conn.close()
|
||||
return success_response([_with_photo_url(e) for e in employees])
|
||||
except Exception:
|
||||
logger.exception('Employee search failed')
|
||||
return error_response(
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
'Employee lookup failed',
|
||||
http_code=500
|
||||
)
|
||||
|
||||
|
||||
@employees_bp.route('/lookup/<sso>', methods=['GET'])
|
||||
def lookup_employee(sso):
|
||||
"""Look up a single employee by SSO."""
|
||||
if not sso.isdigit():
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'SSO must be numeric'
|
||||
)
|
||||
|
||||
if _selfhosted():
|
||||
emp = db.session.get(DirectoryEmployee, int(sso))
|
||||
if not emp:
|
||||
return error_response(ErrorCodes.NOT_FOUND,
|
||||
f'Employee with SSO {sso} not found', http_code=404)
|
||||
return success_response(_with_photo_url(emp.to_dict()))
|
||||
|
||||
try:
|
||||
conn = employee_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
f'SELECT {_FIELDS} FROM employees WHERE SSO = %s',
|
||||
(int(sso),)
|
||||
)
|
||||
employee = cur.fetchone()
|
||||
conn.close()
|
||||
|
||||
if not employee:
|
||||
return error_response(
|
||||
ErrorCodes.NOT_FOUND,
|
||||
f'Employee with SSO {sso} not found',
|
||||
http_code=404
|
||||
)
|
||||
|
||||
return success_response(_with_photo_url(employee))
|
||||
except Exception:
|
||||
logger.exception('Employee lookup failed for SSO %s', sso)
|
||||
return error_response(
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
'Employee lookup failed',
|
||||
http_code=500
|
||||
)
|
||||
|
||||
|
||||
@employees_bp.route('/lookup', methods=['GET'])
|
||||
def lookup_employees():
|
||||
"""
|
||||
Look up multiple employees by SSO list.
|
||||
|
||||
Query parameters:
|
||||
- sso: Comma-separated list of SSOs
|
||||
"""
|
||||
sso_list = request.args.get('sso', '')
|
||||
ssos = [s.strip() for s in sso_list.split(',') if s.strip().isdigit()]
|
||||
|
||||
if not ssos:
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'At least one valid SSO is required'
|
||||
)
|
||||
|
||||
if _selfhosted():
|
||||
rows = DirectoryEmployee.query.filter(
|
||||
DirectoryEmployee.sso.in_([int(s) for s in ssos])).all()
|
||||
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})
|
||||
|
||||
try:
|
||||
conn = employee_connection()
|
||||
with conn.cursor() as cur:
|
||||
placeholders = ','.join(['%s'] * len(ssos))
|
||||
cur.execute(
|
||||
f'SELECT {_FIELDS} FROM employees WHERE SSO IN ({placeholders})',
|
||||
[int(s) for s in ssos]
|
||||
)
|
||||
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
|
||||
)
|
||||
|
||||
return success_response({
|
||||
'employees': employees,
|
||||
'names': names
|
||||
})
|
||||
except Exception:
|
||||
logger.exception('Employee multi-lookup failed')
|
||||
return error_response(
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
'Employee lookup failed',
|
||||
http_code=500
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Self-hosted directory management (only when directory_mode=selfhosted)
|
||||
# =============================================================================
|
||||
|
||||
@employees_bp.route('/directory', methods=['GET'])
|
||||
@jwt_required(optional=True)
|
||||
def list_directory():
|
||||
"""Full self-hosted directory (for the management page)."""
|
||||
guard = _require_selfhosted()
|
||||
if guard:
|
||||
return guard
|
||||
rows = (DirectoryEmployee.query
|
||||
.order_by(DirectoryEmployee.lastname, DirectoryEmployee.firstname).all())
|
||||
return success_response([_with_photo_url(e.to_dict()) for e in rows])
|
||||
|
||||
|
||||
def _employee_from_payload(data):
|
||||
"""Build kwargs from a payload accepting either external-style (SSO,
|
||||
First_Name...) or plain (sso, firstname...) keys."""
|
||||
def pick(*keys):
|
||||
for key in keys:
|
||||
if data.get(key) not in (None, ''):
|
||||
return data.get(key)
|
||||
return None
|
||||
return {
|
||||
'sso': pick('sso', 'SSO'),
|
||||
'firstname': pick('firstname', 'First_Name'),
|
||||
'lastname': pick('lastname', 'Last_Name'),
|
||||
'team': pick('team', 'Team'),
|
||||
'role': pick('role', 'Role'),
|
||||
'picture': pick('picture', 'Picture'),
|
||||
}
|
||||
|
||||
|
||||
@employees_bp.route('/directory', methods=['POST'])
|
||||
@jwt_required()
|
||||
@require_role('admin')
|
||||
def create_directory_employee():
|
||||
guard = _require_selfhosted()
|
||||
if guard:
|
||||
return guard
|
||||
fields = _employee_from_payload(request.get_json() or {})
|
||||
if not (fields['sso'] and fields['firstname'] and fields['lastname']):
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR, 'sso, firstname and lastname are required')
|
||||
try:
|
||||
sso = int(fields['sso'])
|
||||
except (ValueError, TypeError):
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR, 'sso must be numeric')
|
||||
if db.session.get(DirectoryEmployee, sso):
|
||||
return error_response(ErrorCodes.CONFLICT, f'SSO {sso} already exists', http_code=409)
|
||||
emp = DirectoryEmployee(sso=sso, firstname=fields['firstname'], lastname=fields['lastname'],
|
||||
team=fields['team'], role=fields['role'], picture=fields['picture'])
|
||||
db.session.add(emp)
|
||||
db.session.commit()
|
||||
return success_response(emp.to_dict(), message='Employee added', http_code=201)
|
||||
|
||||
|
||||
@employees_bp.route('/directory/<int:sso>', methods=['PUT'])
|
||||
@jwt_required()
|
||||
@require_role('admin')
|
||||
def update_directory_employee(sso):
|
||||
guard = _require_selfhosted()
|
||||
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)
|
||||
fields = _employee_from_payload(request.get_json() or {})
|
||||
if fields['firstname']:
|
||||
emp.firstname = fields['firstname']
|
||||
if fields['lastname']:
|
||||
emp.lastname = fields['lastname']
|
||||
for key in ('team', 'role', 'picture'):
|
||||
if key in (request.get_json() or {}) or fields[key] is not None:
|
||||
setattr(emp, key, fields[key])
|
||||
db.session.commit()
|
||||
return success_response(emp.to_dict(), message='Employee updated')
|
||||
|
||||
|
||||
@employees_bp.route('/directory/<int:sso>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
@require_role('admin')
|
||||
def delete_directory_employee(sso):
|
||||
guard = _require_selfhosted()
|
||||
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)
|
||||
db.session.delete(emp)
|
||||
db.session.commit()
|
||||
return success_response(message='Employee removed')
|
||||
|
||||
|
||||
@employees_bp.route('/directory/import', methods=['POST'])
|
||||
@jwt_required()
|
||||
@require_role('admin')
|
||||
def import_directory():
|
||||
"""Bulk upsert from CSV. Accepts headers SSO,First_Name,Last_Name,Team,Role,
|
||||
Picture (case-insensitive; sso/firstname/... also accepted)."""
|
||||
guard = _require_selfhosted()
|
||||
if guard:
|
||||
return guard
|
||||
text = ''
|
||||
if 'file' in request.files:
|
||||
text = request.files['file'].read().decode('utf-8-sig', errors='replace')
|
||||
else:
|
||||
data = request.get_json(silent=True) or {}
|
||||
text = data.get('csv', '')
|
||||
if not text.strip():
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR, 'No CSV provided')
|
||||
|
||||
reader = csv.DictReader(io.StringIO(text))
|
||||
# Normalize headers to lower for tolerant matching.
|
||||
added = updated = skipped = 0
|
||||
for raw in reader:
|
||||
row = {(k or '').strip().lower(): (v or '').strip() for k, v in raw.items()}
|
||||
sso_raw = row.get('sso') or row.get('sso ')
|
||||
first = row.get('first_name') or row.get('firstname')
|
||||
last = row.get('last_name') or row.get('lastname')
|
||||
if not (sso_raw and sso_raw.isdigit() and first and last):
|
||||
skipped += 1
|
||||
continue
|
||||
sso = int(sso_raw)
|
||||
team = row.get('team') or None
|
||||
role = row.get('role') or None
|
||||
picture = row.get('picture') or None
|
||||
emp = db.session.get(DirectoryEmployee, sso)
|
||||
if emp:
|
||||
emp.firstname, emp.lastname, emp.team, emp.role, emp.picture = first, last, team, role, picture
|
||||
updated += 1
|
||||
else:
|
||||
db.session.add(DirectoryEmployee(sso=sso, firstname=first, lastname=last,
|
||||
team=team, role=role, picture=picture))
|
||||
added += 1
|
||||
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')
|
||||
15
plugins/employees/manifest.json
Normal file
15
plugins/employees/manifest.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "employees",
|
||||
"version": "1.0.0",
|
||||
"description": "Read-only employee directory lookup (separate HR database)",
|
||||
"author": "ShopDB Team",
|
||||
"dependencies": [],
|
||||
"core_version": ">=0.1.0,<1.0.0",
|
||||
"api_prefix": "/api/employees",
|
||||
"provides": {
|
||||
"features": [
|
||||
"employee_directory"
|
||||
]
|
||||
},
|
||||
"default_enabled": false
|
||||
}
|
||||
14
plugins/employees/migrations/env.py
Normal file
14
plugins/employees/migrations/env.py
Normal file
@@ -0,0 +1,14 @@
|
||||
"""Alembic environment for the employees plugin migration chain.
|
||||
|
||||
Delegates to the shared runner in shopdb.plugins.alembic_template, which
|
||||
filters the metadata to this plugin's tables and drives Alembic against the
|
||||
per-plugin version table alembic_version_employees. See ADR-008 for the
|
||||
ownership cutover between the core chain and per-plugin chains.
|
||||
"""
|
||||
import os
|
||||
|
||||
os.environ['PLUGIN_NAME'] = 'employees'
|
||||
|
||||
from shopdb.plugins.alembic_template import run_migrations # noqa: E402
|
||||
|
||||
run_migrations()
|
||||
24
plugins/employees/migrations/script.py.mako
Normal file
24
plugins/employees/migrations/script.py.mako
Normal file
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,28 @@
|
||||
"""employees plugin anchor (ownership cutover).
|
||||
|
||||
Stamp-only no-op. The core Alembic chain (baseline .. 7d16_directoryemployees)
|
||||
already created every table this plugin owns at the cutover point, so there is
|
||||
nothing to build here. This revision gives the plugin's own chain a base that
|
||||
`flask plugin upgrade-all` can stamp into alembic_version_employees. From this
|
||||
anchor forward, new employees schema changes land as 000N revisions in this
|
||||
directory, never in the core chain. See ADR-008.
|
||||
"""
|
||||
from alembic import op # noqa: F401
|
||||
import sqlalchemy as sa # noqa: F401
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'employees0001anchor'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# No-op: the core chain owns every table that exists at the cutover.
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
# No-op: this anchor never unwinds core-owned tables.
|
||||
pass
|
||||
@@ -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')
|
||||
5
plugins/employees/models/__init__.py
Normal file
5
plugins/employees/models/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""Employees plugin models."""
|
||||
|
||||
from .directory_employee import DirectoryEmployee
|
||||
|
||||
__all__ = ['DirectoryEmployee']
|
||||
43
plugins/employees/models/directory_employee.py
Normal file
43
plugins/employees/models/directory_employee.py
Normal file
@@ -0,0 +1,43 @@
|
||||
"""Self-hosted employee directory.
|
||||
|
||||
For sites with no external HR database. When employee_directory_mode is
|
||||
'selfhosted', the employee lookup APIs read this app-owned table instead of the
|
||||
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
|
||||
|
||||
|
||||
class DirectoryEmployee(db.Model):
|
||||
__tablename__ = 'directoryemployees'
|
||||
|
||||
sso = db.Column(db.Integer, primary_key=True, autoincrement=False)
|
||||
firstname = db.Column(db.String(100), nullable=False)
|
||||
lastname = db.Column(db.String(100), nullable=False)
|
||||
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,
|
||||
'Last_Name': self.lastname,
|
||||
'Team': self.team,
|
||||
'Role': self.role,
|
||||
'Picture': self.picture,
|
||||
'photofilename': self.photofilename,
|
||||
}
|
||||
98
plugins/employees/plugin.py
Normal file
98
plugins/employees/plugin.py
Normal file
@@ -0,0 +1,98 @@
|
||||
"""Employees plugin main class.
|
||||
|
||||
Blueprint-only plugin: a read-only employee directory lookup over a separate HR
|
||||
database. No model (the directory is an external DB) and no AssetType. The
|
||||
connection helper (employee_connection) stays core infrastructure in shopdb.api,
|
||||
shared with search and the notifications shopfloor feed.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Optional, Type
|
||||
|
||||
from flask import Flask, Blueprint
|
||||
|
||||
from shopdb.plugins.base import BasePlugin, PluginMeta
|
||||
|
||||
from .api import employees_bp
|
||||
from .models import DirectoryEmployee
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EmployeesPlugin(BasePlugin):
|
||||
"""Employees plugin - read-only HR directory lookup."""
|
||||
|
||||
def __init__(self):
|
||||
self._manifest = self._load_manifest()
|
||||
|
||||
def _load_manifest(self) -> Dict:
|
||||
"""Load plugin manifest from JSON file."""
|
||||
manifest_path = Path(__file__).parent / 'manifest.json'
|
||||
if manifest_path.exists():
|
||||
with open(manifest_path, 'r') as f:
|
||||
return json.load(f)
|
||||
return {}
|
||||
|
||||
@property
|
||||
def meta(self) -> PluginMeta:
|
||||
"""Return plugin metadata."""
|
||||
return PluginMeta(
|
||||
name=self._manifest.get('name', 'employees'),
|
||||
version=self._manifest.get('version', '1.0.0'),
|
||||
description=self._manifest.get(
|
||||
'description',
|
||||
'Read-only employee directory lookup'
|
||||
),
|
||||
author=self._manifest.get('author', 'ShopDB Team'),
|
||||
dependencies=self._manifest.get('dependencies', []),
|
||||
core_version=self._manifest.get('core_version', '>=0.1.0,<1.0.0'),
|
||||
api_prefix=self._manifest.get('api_prefix', '/api/employees'),
|
||||
)
|
||||
|
||||
def get_blueprint(self) -> Optional[Blueprint]:
|
||||
"""Return Flask Blueprint with API routes."""
|
||||
return employees_bp
|
||||
|
||||
def get_models(self) -> List[Type]:
|
||||
"""Self-hosted directory table (used when directory_mode=selfhosted).
|
||||
External mode reads a separate DB via employee_connection instead."""
|
||||
return [DirectoryEmployee]
|
||||
|
||||
def get_provisioning_note(self) -> Optional[Dict]:
|
||||
return {
|
||||
'mode_setting': 'employee_directory_mode',
|
||||
'tables': ['directoryemployees'],
|
||||
'note': ('Enabling this in self-hosted mode creates a '
|
||||
'"directoryemployees" table in the shopdb database (SSO, '
|
||||
'First_Name, Last_Name, Team, Role, Picture). It is '
|
||||
'referenced across the site: employee search, notification '
|
||||
'recognition (name + photo on the shopfloor/lobby displays), '
|
||||
'and USB check-in/out name resolution. Manage people under '
|
||||
'Settings > Employee Directory, or point at an existing HR '
|
||||
'database instead (external mode).'),
|
||||
'docs': 'plugins/employees/README.md',
|
||||
}
|
||||
|
||||
def get_config_schema(self) -> List[Dict]:
|
||||
"""Employee directory DB connection. Host/name/user are settings the
|
||||
wizard can edit; the password stays in .env (emitted, not stored)."""
|
||||
return [
|
||||
{'key': 'employee_db_host', 'label': 'Employee DB host', 'type': 'text',
|
||||
'secret': False, 'default': 'localhost',
|
||||
'help': 'This DB must expose an "employees" table or view with columns '
|
||||
'SSO, First_Name, Last_Name, Team, Role, Picture. '
|
||||
'See plugins/employees/README.md.'},
|
||||
{'key': 'employee_db_name', 'label': 'Employee DB name', 'type': 'text',
|
||||
'secret': False, 'default': 'wjf_employees'},
|
||||
{'key': 'employee_db_user', 'label': 'Employee DB user', 'type': 'text',
|
||||
'secret': False},
|
||||
{'key': 'employee_db_password', 'label': 'Employee DB password', 'type': 'password',
|
||||
'secret': True, 'envvar': 'EMPLOYEE_DB_PASSWORD',
|
||||
'help': 'Stored in .env, not the database. The wizard shows the line to paste.'},
|
||||
]
|
||||
|
||||
def init_app(self, app: Flask, db_instance) -> None:
|
||||
"""Initialize plugin with Flask app."""
|
||||
logger.info(f"Employees plugin initialized (v{self.meta.version})")
|
||||
Reference in New Issue
Block a user