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.
260 lines
10 KiB
Python
260 lines
10 KiB
Python
"""Notifications plugin main class."""
|
|
|
|
import json
|
|
import logging
|
|
from pathlib import Path
|
|
from typing import List, Dict, Optional, Type
|
|
|
|
from flask import Flask, Blueprint
|
|
import click
|
|
|
|
from shopdb.plugins.base import BasePlugin, PluginMeta
|
|
from shopdb.api import db
|
|
|
|
from .models import Notification, NotificationType, NotificationAcknowledgement
|
|
from .api import notifications_bp
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class NotificationsPlugin(BasePlugin):
|
|
"""
|
|
Notifications plugin - manages announcements and notifications.
|
|
|
|
Provides functionality for:
|
|
- Creating and managing notifications/announcements
|
|
- Displaying banner notifications
|
|
- Calendar view of notifications
|
|
"""
|
|
|
|
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', 'notifications'),
|
|
version=self._manifest.get('version', '1.0.0'),
|
|
description=self._manifest.get(
|
|
'description',
|
|
'Notifications and announcements management'
|
|
),
|
|
author=self._manifest.get('author', 'ShopDB Team'),
|
|
dependencies=self._manifest.get('dependencies', []),
|
|
core_version=self._manifest.get('core_version', '>=1.0.0'),
|
|
api_prefix=self._manifest.get('api_prefix', '/api/notifications'),
|
|
)
|
|
|
|
def get_blueprint(self) -> Optional[Blueprint]:
|
|
"""Return Flask Blueprint with API routes."""
|
|
return notifications_bp
|
|
|
|
def get_models(self) -> List[Type]:
|
|
"""Return list of SQLAlchemy model classes."""
|
|
return [Notification, NotificationType, NotificationAcknowledgement]
|
|
|
|
def init_app(self, app: Flask, db_instance) -> None:
|
|
"""Initialize plugin with Flask app."""
|
|
logger.info(f"Notifications plugin initialized (v{self.meta.version})")
|
|
|
|
def on_install(self, app: Flask) -> None:
|
|
"""Called when plugin is installed."""
|
|
with app.app_context():
|
|
self._ensure_notification_types()
|
|
logger.info("Notifications plugin installed")
|
|
|
|
def _ensure_notification_types(self) -> None:
|
|
"""Ensure default notification types exist.
|
|
|
|
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)
|
|
default_types = [
|
|
('Awareness', 'General awareness notification', '#17a2b8', 'none', None, None, False, False, 'standard'),
|
|
('Change', 'Planned change notification', '#ffc107', 'none', None, None, False, False, 'standard'),
|
|
('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'),
|
|
]
|
|
|
|
for (typename, typedescription, typecolor, expirymode, expirydays,
|
|
expiryhour, splitperemployee, showemployeephoto, displaystyle) in default_types:
|
|
existing = NotificationType.query.filter_by(typename=typename).first()
|
|
if not existing:
|
|
t = NotificationType(
|
|
typename=typename,
|
|
typedescription=typedescription,
|
|
typecolor=typecolor,
|
|
expirymode=expirymode,
|
|
expirydays=expirydays,
|
|
expiryhour=expiryhour,
|
|
expiryminute=0,
|
|
splitperemployee=splitperemployee,
|
|
showemployeephoto=showemployeephoto,
|
|
displaystyle=displaystyle
|
|
)
|
|
db.session.add(t)
|
|
logger.debug(f"Created notification type: {typename}")
|
|
|
|
db.session.commit()
|
|
|
|
def on_uninstall(self, app: Flask) -> None:
|
|
"""Called when plugin is uninstalled."""
|
|
logger.info("Notifications plugin uninstalled")
|
|
|
|
def get_cli_commands(self) -> List:
|
|
"""Return CLI commands for this plugin."""
|
|
|
|
@click.group('notifications')
|
|
def notifications_cli():
|
|
"""Notifications plugin commands."""
|
|
pass
|
|
|
|
@notifications_cli.command('list-types')
|
|
def list_types():
|
|
"""List all notification types."""
|
|
from flask import current_app
|
|
|
|
with current_app.app_context():
|
|
types = NotificationType.query.filter_by(isactive=True).all()
|
|
if not types:
|
|
click.echo('No notification types found.')
|
|
return
|
|
|
|
click.echo('Notification Types:')
|
|
for t in types:
|
|
click.echo(f" [{t.notificationtypeid}] {t.typename} ({t.color})")
|
|
|
|
@notifications_cli.command('stats')
|
|
def stats():
|
|
"""Show notification statistics."""
|
|
from flask import current_app
|
|
from datetime import datetime, timezone
|
|
|
|
with current_app.app_context():
|
|
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
|
|
|
total = Notification.query.filter(
|
|
Notification.isactive == True
|
|
).count()
|
|
|
|
active = Notification.query.filter(
|
|
Notification.isactive == True,
|
|
Notification.startdate <= now,
|
|
db.or_(
|
|
Notification.enddate.is_(None),
|
|
Notification.enddate >= now
|
|
)
|
|
).count()
|
|
|
|
click.echo(f"Total notifications: {total}")
|
|
click.echo(f"Currently active: {active}")
|
|
|
|
@notifications_cli.command('create')
|
|
@click.option('--title', required=True, help='Notification title')
|
|
@click.option('--message', required=True, help='Notification message')
|
|
@click.option('--type', 'type_name', default='General', help='Notification type')
|
|
def create_notification(title, message, type_name):
|
|
"""Create a new notification."""
|
|
from flask import current_app
|
|
|
|
with current_app.app_context():
|
|
ntype = NotificationType.query.filter_by(typename=type_name).first()
|
|
if not ntype:
|
|
click.echo(f"Error: Notification type '{type_name}' not found.")
|
|
return
|
|
|
|
n = Notification(
|
|
title=title,
|
|
message=message,
|
|
notificationtypeid=ntype.notificationtypeid
|
|
)
|
|
db.session.add(n)
|
|
db.session.commit()
|
|
|
|
click.echo(f"Created notification #{n.notificationid}: {title}")
|
|
|
|
return [notifications_cli]
|
|
|
|
def get_dashboard_widgets(self) -> List[Dict]:
|
|
"""Dashboard card: what the floor is being shown right now.
|
|
|
|
The items, not a count. "4 active notifications" tells an admin
|
|
nothing; knowing WHICH message is on the boards is the point, and it is
|
|
how a stale one gets noticed and taken down.
|
|
|
|
Replaces a declaration naming a component nobody wrote.
|
|
"""
|
|
return [
|
|
{
|
|
'id': 'notifications-active',
|
|
'viewall': '/notifications',
|
|
'title': 'Active notifications',
|
|
'shortname': 'Notification',
|
|
'endpoint': '/api/notifications/dashboard/active',
|
|
'render': 'list',
|
|
'severity': 'info',
|
|
'empty': 'hide',
|
|
'position': 60,
|
|
# Stacked, not inline: the type is a label and the message is
|
|
# prose. On one line the type gets truncated to make room for
|
|
# text that then gets truncated anyway, and neither is
|
|
# readable.
|
|
'layout': 'stacked',
|
|
'map': {
|
|
'title': 'typename',
|
|
'detail': 'message',
|
|
'detailtooltip': 'fullmessage',
|
|
'link': '/notifications/{notificationid}',
|
|
},
|
|
},
|
|
]
|
|
|
|
def get_navigation_items(self) -> List[Dict]:
|
|
"""Return navigation menu items."""
|
|
return [
|
|
{
|
|
'name': 'Notifications',
|
|
'icon': 'bell',
|
|
'route': '/notifications',
|
|
'permission': 'notifications.view',
|
|
'position': 5,
|
|
},
|
|
{
|
|
'name': 'Calendar',
|
|
'icon': 'calendar',
|
|
'route': '/calendar',
|
|
'permission': 'notifications.view',
|
|
'position': 6,
|
|
},
|
|
]
|
|
|
|
def get_permissions(self) -> List:
|
|
"""Return the RBAC permissions this plugin owns."""
|
|
return [
|
|
('notifications.view', 'View notifications', 'notifications'),
|
|
('notifications.create', 'Create notifications', 'notifications'),
|
|
('notifications.edit', 'Edit notifications', 'notifications'),
|
|
('notifications.delete', 'Delete notifications', 'notifications'),
|
|
]
|