Make main the lean product a site receives

main was 16 days and 259 commits behind the line the product is actually built
on, at contract 0.30.0 against 0.35.0, with no per-PC credential code at all. It
was neither current nor curated - just stale. This brings it forward and, at the
same time, makes it mean something: main is what a receiving site installs, and
nothing else.

WHAT IT CARRIES. Twelve plugins - backups, computers, endpoints, guides,
knowledgebase, machines, network, notifications, printers, slides, tools,
warranty - plus applications, which is manifest-less core and always ships. The
only manifest dependency inside that set is endpoints on computers, and both are
in it, so the closure is self-contained.

WHAT IT DOES NOT. employees, geenforce, measuringtools, printedparts and usb
stay on the site line. So do the Windows installer tree, the VM rehearsal
helpers, the agent tooling config, one site's data loader, the internal audit
and findings records, and the planner spreadsheet. 1,135 tracked files against
1,438.

A REMOVAL THAT BREAKS THE APP IS NOT A REMOVAL, and two nearly shipped:

deploy/site-profile-universal.json still named all seventeen plugins. It is the
file docs/DEPLOY.md tells a site to provision from, so a fresh install would
have failed at `flask plugin apply-profile` with PluginError - the first thing a
receiving site does, broken by the branch meant to serve them. It now names the
twelve that exist, and its comment says the two must agree.

agent/ was never refreshed. Whoever populated this branch copied shopdb/,
plugins/, frontend/ and tests/ from the site line and left the agent tree at its
September state: 22 C# and PowerShell sources missing, including AgentCredentials,
EnrollmentService, AgentHttpFactory and the fleet-alert client, plus one file the
site line had deleted still present. The old tree is internally consistent, so it
compiles, and nothing in CI builds it - every gate was green over a server that
speaks enrollment and per-PC credentials to a bundled agent source that cannot.
Resynced whole.

DECISIONS THIS ENCODES, rather than defers:

- The plugin-authoring lab builds printedparts, whose manifest depends on
  employees, so it could not stay. The lab remains on the site line and main
  ships no build-along tutorial. That is a real loss for an adopting developer
  and is recorded here rather than discovered later.
- Recognition, Training and Recertification notifications are no longer seeded.
  Each splits one notification into a card per employee and renders a photo,
  which needs a plugin this branch does not bundle. Seeding them would offer an
  author a type that cannot resolve anybody. A site that installs employees gets
  them from that plugin's own seed.
- Windows/IIS is documented as the legacy path throughout, and the README leads
  with Docker, because that is what a receiving site gets.

The API description is regenerated for THIS branch - 347 paths and 483
operations, down from 415 and 573 - so the published contract describes what is
here rather than what the site line serves. docs/CONFIG.md lost the two
measuring-tool label keys the code no longer declares, which two lanes had
decided opposite ways.

Suite: 3124 passed, 6 skipped. Naming and style gates pass. The docs gates run
rather than skip, and every index line count is derived from the file it names.
This commit is contained in:
cproudlock
2026-09-19 11:24:40 -04:00
parent cb3975049c
commit 534f179ee6
675 changed files with 115759 additions and 60239 deletions

View File

@@ -11,7 +11,7 @@ from flask_jwt_extended import jwt_required
from shopdb.api import db, success_response, error_response, paginated_response, ErrorCodes, get_pagination_params, paginate_query
from ..models import Notification, NotificationType
from ..models.notification import _utc_iso
from ..models.notification import _utc_iso, ALERT_SCOPE_KEYS
from shopdb.api import require_permission, Setting, intarg
@@ -217,18 +217,17 @@ def _employee_name(sso):
"""Live directory name for an SSO; None on any miss. Used as the fallback
when a notification has no stored employeename (see the shopfloor feed)."""
try:
from plugins.employees.api.routes import resolve_employee_display_name
from shopdb.api import resolve_employee_display_name
return resolve_employee_display_name(sso)
except Exception:
return None
def _employee_picture(sso):
"""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."""
"""Resolved display photo URL for an SSO, via the shared core resolver so a
feed card and a lookup agree about the same person. None on any miss."""
try:
from plugins.employees.api.routes import resolve_employee_photo_url
from shopdb.api import resolve_employee_photo_url
return resolve_employee_photo_url(sso)
except Exception:
return None
@@ -405,6 +404,69 @@ def get_notification(notification_id: int):
return success_response(n.to_dict())
def _clean_alert_fields(data):
"""Validate and normalise alertfleet / alertscope / alerttimeout.
Returns (fields, error). fields holds only the keys present in data, with
null coerced to the column default. alertscope must be a JSON object (or a
string holding one) whose keys the endpoint matcher understands; empty or
null means the whole fleet.
"""
import json
fields = {}
if 'alertfleet' in data:
value = data['alertfleet']
if value is None:
value = False
if not isinstance(value, bool):
return None, 'alertfleet must be true or false'
fields['alertfleet'] = value
if 'alerttimeout' in data:
value = data['alerttimeout']
if value is None or value == '':
value = 0
if isinstance(value, bool):
return None, 'alerttimeout must be a whole number of seconds'
try:
value = int(value)
except (TypeError, ValueError):
return None, 'alerttimeout must be a whole number of seconds'
if value < 0:
return None, 'alerttimeout must not be negative'
fields['alerttimeout'] = value
if 'alertscope' in data:
scope = data['alertscope']
if isinstance(scope, str):
if not scope.strip():
scope = None
else:
try:
scope = json.loads(scope)
except ValueError:
return None, 'alertscope must be a JSON object'
if scope is not None:
if not isinstance(scope, dict):
return None, 'alertscope must be a JSON object'
unknown = sorted(set(scope) - ALERT_SCOPE_KEYS)
if unknown:
return None, (f'alertscope has unknown key(s): {", ".join(unknown)}. '
f'Allowed: {", ".join(sorted(ALERT_SCOPE_KEYS))}')
for key, wanted in scope.items():
values = wanted if isinstance(wanted, list) else [wanted]
if any(v is not None and not isinstance(v, (str, int, float))
or isinstance(v, bool) for v in values):
return None, (f'alertscope.{key} must be a string or a list '
f'of strings')
if not scope:
scope = None
fields['alertscope'] = scope
return fields, None
@notifications_bp.route('', methods=['POST'])
@require_permission('notifications.create')
def create_notification():
@@ -419,6 +481,10 @@ def create_notification():
if not notification_text:
return error_response(ErrorCodes.VALIDATION_ERROR, 'notification/message is required')
alert_fields, alert_error = _clean_alert_fields(data)
if alert_error:
return error_response(ErrorCodes.VALIDATION_ERROR, alert_error)
# Parse dates
starttime = datetime.now(timezone.utc).replace(tzinfo=None)
if data.get('starttime') or data.get('startdate'):
@@ -455,7 +521,10 @@ def create_notification():
isactive=True,
isshopfloor=data.get('isshopfloor', False),
employeesso=data.get('employeesso'),
employeename=data.get('employeename')
employeename=data.get('employeename'),
alertfleet=alert_fields.get('alertfleet', False),
alertscope=alert_fields.get('alertscope'),
alerttimeout=alert_fields.get('alerttimeout', 0)
)
db.session.add(n)
@@ -504,6 +573,12 @@ def update_notification(notification_id: int):
n.employeesso = data['employeesso']
if 'employeename' in data:
n.employeename = data['employeename']
alert_fields, alert_error = _clean_alert_fields(data)
if alert_error:
db.session.rollback()
return error_response(ErrorCodes.VALIDATION_ERROR, alert_error)
for field, value in alert_fields.items():
setattr(n, field, value)
# Parse and update dates
if 'starttime' in data or 'startdate' in data:

View File

@@ -217,6 +217,46 @@
</label>
<small class="form-hint">Display on TV dashboard</small>
</div>
<div class="form-group">
<label>
<input
type="checkbox"
v-model="form.alertfleet"
:disabled="isDetail || !form.isactive"
/>
Alert Fleet
</label>
<small class="form-hint">Push this notification to shop floor PCs</small>
</div>
</div>
<div v-if="form.alertfleet" class="fleet-alert-options">
<div class="form-group">
<label for="alertscope">Alert Scope (JSON)</label>
<textarea
id="alertscope"
v-model="alertScopeText"
class="form-control"
rows="3"
:disabled="isDetail"
placeholder='{"assettype": "computer", "location": "Building A"}'
></textarea>
<small class="form-hint">Optional: Filter alerts by asset type, location, or business unit (JSON format)</small>
</div>
<div class="form-group">
<label for="alerttimeout">Auto-dismiss Timeout (minutes)</label>
<input
id="alerttimeout"
v-model.number="form.alerttimeout"
type="number"
class="form-control"
min="0"
:disabled="isDetail"
/>
<small class="form-hint">Minutes until auto-dismiss (0 = manual acknowledgment only)</small>
</div>
</div>
<div v-if="error" class="error-message">{{ error }}</div>
@@ -282,13 +322,42 @@ const form = ref({
// loads its own stored value (see loadNotification), so this never flips a
// setting somebody deliberately turned off.
isshopfloor: true,
employeesso: ''
employeesso: '',
alertfleet: false,
alertscope: null,
alerttimeout: 0
})
// Site timezone (settings key site_timezone) so form times show/enter in the
// site's wall clock, not the viewer's browser zone. Loaded in onMounted.
const siteTimezone = ref(DEFAULT_TZ)
// Alert scope as text for editing (converts to/from JSON)
const alertScopeText = ref('')
watch(() => form.value.alertscope, (newVal) => {
if (newVal && typeof newVal === 'object') {
alertScopeText.value = JSON.stringify(newVal, null, 2)
} else if (newVal && typeof newVal === 'string') {
alertScopeText.value = newVal
} else {
alertScopeText.value = ''
}
}, { immediate: true })
watch(alertScopeText, (newVal) => {
if (!newVal.trim()) {
form.value.alertscope = null
return
}
try {
form.value.alertscope = JSON.parse(newVal)
} catch (e) {
// Keep the text as-is until it's valid JSON
form.value.alertscope = newVal
}
})
function selectedTypeName() {
const selectedType = types.value.find(t => t.notificationtypeid === parseInt(form.value.notificationtypeid))
return selectedType?.typename?.toLowerCase() || ''
@@ -349,7 +418,10 @@ onMounted(async () => {
endtime: formatDateForInput(n.endtime),
isactive: n.isactive !== false,
isshopfloor: n.isshopfloor || false,
employeesso: n.employeesso || ''
employeesso: n.employeesso || '',
alertfleet: n.alertfleet || false,
alertscope: n.alertscope || null,
alerttimeout: n.alerttimeout !== undefined ? n.alerttimeout : 0
}
// Parse existing employee data: SSOs are comma-joined and names are
@@ -527,7 +599,10 @@ async function saveNotification() {
endtime: utcFromZonedInput(form.value.endtime, siteTimezone.value),
isactive: form.value.isactive,
isshopfloor: form.value.isshopfloor,
employeesso: form.value.employeesso || null
employeesso: form.value.employeesso || null,
alertfleet: form.value.alertfleet || false,
alertscope: form.value.alertscope || null,
alerttimeout: form.value.alerttimeout !== undefined ? form.value.alerttimeout : 0
}
// For employee-photo types, also send employeename

View File

@@ -0,0 +1,102 @@
"""Add fleet alert support to notifications plugin.
Adds alertfleet, alertscope, and alerttimeout columns to the notifications table
to support fleet-wide alert broadcasting. Creates notificationacknowledgements
table to track which assets have acknowledged fleet alerts.
Fleet alerts can be scoped to specific asset types, locations, or business units
via the alertscope TEXT field (JSON string). alerttimeout=0 means no auto-dismiss (manual only).
Idempotent: column and table creation are skipped when they already exist.
Revision ID: notifications0006fleetalerts
Revises: notifications0005boardorder
"""
from alembic import op
import sqlalchemy as sa
revision = 'notifications0006fleetalerts'
down_revision = 'notifications0005boardorder'
branch_labels = None
depends_on = None
def _column_names(insp, table):
return {c['name'] for c in insp.get_columns(table)}
def upgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
existing_tables = set(insp.get_table_names())
# Add alertfleet, alertscope, alerttimeout to notifications table
if 'notifications' in existing_tables:
cols = _column_names(insp, 'notifications')
if 'alertfleet' not in cols:
op.add_column('notifications',
sa.Column('alertfleet', sa.Boolean(), nullable=False,
server_default=sa.false()))
if 'alertscope' not in cols:
op.add_column('notifications',
sa.Column('alertscope', sa.Text, nullable=True))
if 'alerttimeout' not in cols:
op.add_column('notifications',
sa.Column('alerttimeout', sa.Integer(), nullable=False,
server_default='0'))
# Create notificationacknowledgements table
if 'notificationacknowledgements' not in existing_tables:
op.create_table(
'notificationacknowledgements',
sa.Column('notificationacknowledgementid', sa.Integer(), nullable=False),
sa.Column('notificationid', sa.Integer(), nullable=False),
sa.Column('assetid', sa.Integer(), nullable=False),
sa.Column('acknowledgedat', sa.DateTime(), nullable=False,
server_default=sa.text('NOW()')),
sa.PrimaryKeyConstraint('notificationacknowledgementid'),
sa.ForeignKeyConstraint(['notificationid'],
['notifications.notificationid'],
ondelete='CASCADE'),
sa.ForeignKeyConstraint(['assetid'], ['assets.assetid'],
ondelete='CASCADE'),
sa.UniqueConstraint('notificationid', 'assetid',
name='uq_notification_asset')
)
op.create_index('idx_notificationack_notification',
'notificationacknowledgements',
['notificationid'])
op.create_index('idx_notificationack_asset',
'notificationacknowledgements',
['assetid'])
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
existing_tables = set(insp.get_table_names())
# Drop notificationacknowledgements table
if 'notificationacknowledgements' in existing_tables:
op.drop_index('idx_notificationack_asset',
table_name='notificationacknowledgements')
op.drop_index('idx_notificationack_notification',
table_name='notificationacknowledgements')
op.drop_table('notificationacknowledgements')
# Drop alert columns from notifications table
if 'notifications' in existing_tables:
cols = _column_names(insp, 'notifications')
if 'alerttimeout' in cols:
op.drop_column('notifications', 'alerttimeout')
if 'alertscope' in cols:
op.drop_column('notifications', 'alertscope')
if 'alertfleet' in cols:
op.drop_column('notifications', 'alertfleet')

View File

@@ -1,5 +1,6 @@
"""Notifications plugin models."""
from .notification import Notification, NotificationType
from .acknowledgement import NotificationAcknowledgement
__all__ = ['Notification', 'NotificationType']
__all__ = ['Notification', 'NotificationType', 'NotificationAcknowledgement']

View File

@@ -0,0 +1,52 @@
"""Notification acknowledgement tracking for fleet alerts."""
from datetime import datetime, timezone
from shopdb.api import db
class NotificationAcknowledgement(db.Model):
"""
Tracks which assets have acknowledged fleet alerts.
Matches existing notificationacknowledgements table.
"""
__tablename__ = 'notificationacknowledgements'
__table_args__ = (
db.UniqueConstraint('notificationid', 'assetid', name='uq_notification_asset'),
)
notificationacknowledgementid = db.Column(db.Integer, primary_key=True)
notificationid = db.Column(
db.Integer,
db.ForeignKey('notifications.notificationid', ondelete='CASCADE'),
nullable=False,
index=True
)
assetid = db.Column(
db.Integer,
db.ForeignKey('assets.assetid', ondelete='CASCADE'),
nullable=False,
index=True
)
acknowledgedat = db.Column(
db.DateTime,
nullable=False,
default=lambda: datetime.now(timezone.utc).replace(tzinfo=None)
)
# Relationships
notification = db.relationship('Notification', backref='acknowledgements')
asset = db.relationship('Asset', backref='notification_acknowledgements')
def __repr__(self):
return f"<NotificationAcknowledgement {self.notificationacknowledgementid}>"
def to_dict(self):
"""Convert to dictionary following ShopDB patterns."""
return {
'notificationacknowledgementid': self.notificationacknowledgementid,
'notificationid': self.notificationid,
'assetid': self.assetid,
'acknowledgedat': self.acknowledgedat.replace(
tzinfo=timezone.utc
).isoformat() if self.acknowledgedat else None
}

View File

@@ -1,12 +1,54 @@
"""Notifications plugin models - adapted to existing database schema."""
import json
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
from sqlalchemy import Text
from sqlalchemy.types import TypeDecorator
from shopdb.api import db
class JSONText(TypeDecorator):
"""A dict on the Python side, TEXT in the database.
MySQL 5.6 has no JSON type and a site still runs it, so every JSON-bearing
column in this product is TEXT. Declared here rather than imported from the
computers plugin: notifications declares no dependency on computers, and a
cross-plugin import would be a hidden one.
"""
impl = Text
cache_ok = True
def process_bind_param(self, value, dialect):
if value is None:
return None
return json.dumps(value, separators=(',', ':'))
def process_result_value(self, value, dialect):
if value is None or value == '':
return None
try:
return json.loads(value)
except (TypeError, ValueError):
# Hand-edited or written before this column held JSON. Return the
# raw text rather than raising: a scope that cannot be parsed
# should be visible and fixable, and the endpoints matcher already
# treats a non-dict scope as matching nothing.
return value
_DEFAULT_TZ = 'America/New_York'
# Keys a fleet alert's alertscope may use. Must stay equal to the set the
# endpoints matcher (_ALERT_SCOPE_KEYS in plugins/endpoints/api/routes.py)
# understands; a test pins the two together.
ALERT_SCOPE_KEYS = frozenset({'hostname', 'assettype', 'computertype',
'location', 'businessunit'})
def _site_zone():
"""Site-configured IANA zone (settings key site_timezone) for calendar day
@@ -146,6 +188,16 @@ class Notification(db.Model):
# ~11 people are listed.
employeesso = db.Column(db.Text, nullable=True)
employeename = db.Column(db.Text, nullable=True)
# Matches migration 0006: NOT NULL with server defaults.
alertfleet = db.Column(db.Boolean, nullable=False, default=False,
server_default=db.false())
# JSONText, not db.JSON: migration 0006 ships this column as TEXT because a
# site still runs MySQL 5.6, which has no JSON type. db.JSON here meant
# create-all built a JSON column the migration path never produces, so the
# model and the shipped schema disagreed about the same column.
alertscope = db.Column(JSONText, nullable=True)
alerttimeout = db.Column(db.Integer, nullable=False, default=0,
server_default='0')
# Relationships
notificationtype = db.relationship('NotificationType', backref='notifications')
@@ -194,7 +246,10 @@ class Notification(db.Model):
'isshopfloor': bool(self.isshopfloor) if self.isshopfloor is not None else False,
'employeesso': self.employeesso,
'employeename': self.employeename,
'iscurrent': self.is_current
'iscurrent': self.is_current,
'alertfleet': bool(self.alertfleet) if self.alertfleet is not None else False,
'alertscope': self.alertscope,
'alerttimeout': self.alerttimeout
}
# Add type info

View File

@@ -11,7 +11,7 @@ import click
from shopdb.plugins.base import BasePlugin, PluginMeta
from shopdb.api import db
from .models import Notification, NotificationType
from .models import Notification, NotificationType, NotificationAcknowledgement
from .api import notifications_bp
logger = logging.getLogger(__name__)
@@ -60,7 +60,7 @@ class NotificationsPlugin(BasePlugin):
def get_models(self) -> List[Type]:
"""Return list of SQLAlchemy model classes."""
return [Notification, NotificationType]
return [Notification, NotificationType, NotificationAcknowledgement]
def init_app(self, app: Flask, db_instance) -> None:
"""Initialize plugin with Flask app."""
@@ -75,10 +75,17 @@ class NotificationsPlugin(BasePlugin):
def _ensure_notification_types(self) -> None:
"""Ensure default notification types exist.
For the special shopfloor types (recognition, training,
recertification) the typecolor is a keyword the dashboard maps to a
style and the feed uses to split multi-employee cards per employee;
generic types use a hex color.
The three employee-facing types - Recognition, Training and
Recertification - are NOT seeded on this branch. Each splits one
notification into a card per employee and renders an employee photo,
which needs the employees plugin, and this branch does not bundle it
(see deploy/site-profile-universal.json). Seeding them here would offer
an author a type that cannot resolve anybody: the form would list it,
the feed would split on a directory that is not there, and the failure
would arrive later and further away than the choice that caused it.
A site that installs the employees plugin gets them from that plugin's
own seed, so nothing is lost by their absence here.
"""
# (typename, typedescription, typecolor, expirymode, expirydays,
# expiryhour, splitperemployee, showemployeephoto, displaystyle)
@@ -88,9 +95,6 @@ class NotificationsPlugin(BasePlugin):
('Incident', 'Incident or outage notification', '#dc3545', 'none', None, None, False, False, 'standard'),
('Maintenance', 'Scheduled maintenance notification', '#6c757d', 'none', None, None, False, False, 'standard'),
('General', 'General announcement', '#28a745', 'none', None, None, False, False, 'standard'),
('Recognition', 'Employee recognition (clears at 8 AM Eastern)', '#ffc107', 'dailytime', None, 8, True, True, 'carousel'),
('Training', 'Training notice (one card per employee)', '#17a2b8', 'none', None, None, True, True, 'carousel'),
('Recertification', 'Employees due to retake a training course (shows two weeks)', '#0d6efd', 'duration', 14, None, True, True, 'grid'),
]
for (typename, typedescription, typecolor, expirymode, expirydays,