dashboard: printer supplies, expiring warranties, mis-numbered bays
Some checks failed
CI / backend (push) Failing after 8s
CI / naming (push) Successful in 2s
CI / frontend (push) Successful in 9s
CI / migrations-mysql (push) Failing after 7s

Wave one complete. Three cards, no new data and no migrations.

Printer supplies reuses the existing low-supplies query and its five-minute
cache; a Zabbix round-trip per printer on every dashboard load would make this
the slowest page in the app. One row per printer listing every depleted
cartridge, criticals first - a row per cartridge would report one printer three
times and read as three problems, and showing only the worst class would hide a
low cartridge behind a critical one on the same machine when whoever walks out
there wants to carry both.

While there: the low-supplies REPORT itself was including healthy cartridges. A
printer with one empty black and three full colour ones listed all four, so the
reader had to find the problem inside the row. It now lists only what needs
replacing, and the test that asserted the old behaviour now asserts the new.

Expiring warranties keeps already-expired entries on the list rather than
dropping them the day they lapse, which is how they get missed. Horizon is
warranty_expiringdays, default 90, because that suits a site budgeting
quarterly and nobody else.

Mis-numbered bays promotes check-shared-machines out of a CLI command nobody
will remember to run - it found seven bays that had been wrong for weeks. It
reports only numbers with NO child assets, so part markers legitimately sharing
an operation stay silent: that distinction is the whole card, and without it it
would list correct data beside faults and be ignored.

Printers also loses its dead component-named widget; notifications, network and
machines still have theirs.
This commit is contained in:
cproudlock
2026-08-11 14:13:26 -04:00
parent 6c975a107c
commit 7151b68bdd
9 changed files with 339 additions and 13 deletions

View File

@@ -994,3 +994,73 @@ def dashboard_quiet():
# down the list, not the order the rows came out of the table.
rows.sort(key=lambda r: (r['quietdays'] is not None, -(r['quietdays'] or 0)))
return success_response(rows[:50])
@computers_bp.route('/dashboard/sharedmachines', methods=['GET'])
@jwt_required()
@require_permission('computers.view')
def dashboard_sharedmachines():
"""Machine numbers claimed by more than one PC, with nothing filed under
them.
Several devices genuinely sharing a number is legitimate - part markers do
it - and those are modelled: each device is its own asset filed `partof` the
operation, so the operation has CHILD ASSETS. Two PCs carrying the same
machine number by mistake looks identical from a count and has none. That
distinction is the whole card; without it this would list correct data
alongside faults and get ignored.
Promoted from `flask relationships check-shared-machines`, which answers the
same question and which nobody will remember to run. This one found seven
mis-numbered bays that had been that way for weeks.
"""
from shopdb.api import AssetRelationship, RelationshipType
from sqlalchemy.orm import aliased
controls = RelationshipType.query.filter_by(
relationshiptype='controls').first()
partof = RelationshipType.query.filter_by(relationshiptype='partof').first()
if not controls:
return success_response([])
pcasset = aliased(Asset)
machineasset = aliased(Asset)
rows = (db.session.query(machineasset.assetid, machineasset.assetnumber,
pcasset.assetnumber)
.select_from(AssetRelationship)
.join(pcasset, AssetRelationship.sourceassetid == pcasset.assetid)
.join(machineasset,
AssetRelationship.targetassetid == machineasset.assetid)
.filter(AssetRelationship.relationshiptypeid ==
controls.relationshiptypeid,
AssetRelationship.label == 'collector:machine',
AssetRelationship.isactive.is_(True))
.all())
bymachine = {}
for assetid, machinenumber, pcnumber in rows:
bymachine.setdefault((assetid, machinenumber), []).append(pcnumber)
out = []
for (assetid, machinenumber), pcs in bymachine.items():
if len(pcs) < 2:
continue
children = 0
if partof:
children = (AssetRelationship.query
.filter_by(targetassetid=assetid,
relationshiptypeid=partof.relationshiptypeid,
isactive=True)
.count())
if children:
continue # modelled: the devices are assets in their own right
out.append({
'assetid': assetid,
'machinenumber': machinenumber,
'pccount': len(pcs),
'pcs': ', '.join(sorted(p for p in pcs if p)),
})
out.sort(key=lambda r: -r['pccount'])
return success_response(out)

View File

@@ -1280,6 +1280,22 @@ class ComputersPlugin(BasePlugin):
'link': '/pcs/{computerid}',
},
},
{
'id': 'computers-sharedmachines',
'title': 'Machine numbers on two PCs',
'endpoint': '/api/computers/dashboard/sharedmachines',
'render': 'exceptions',
'severity': 'critical',
'permission': 'computers.view',
'empty': 'hide',
'position': 15,
'map': {
'title': 'machinenumber',
'detail': 'pcs',
'meta': [{'key': 'pccount', 'suffix': ' PCs'}],
'link': '/machines/{assetid}',
},
},
]
def get_navigation_items(self) -> List[Dict]:

View File

@@ -1005,12 +1005,17 @@ def _get_low_supplies_data():
model_number = model.modelnumber if model else None
modelnumberid = model.modelnumberid if model else None
# ONLY the supplies that need attention. A printer reporting one empty
# black cartridge alongside three full colour ones was listing all four,
# so the reader had to find the problem inside the row rather than being
# shown it. The whole report exists to answer "what needs replacing".
annotated = []
has_low = False
for s in supplies:
item = _annotate_supply(s, vendor_name, modelnumberid)
if item['status'] != 'ok':
has_low = True
if item['status'] == 'ok':
continue
has_low = True
annotated.append(item)
if has_low:
@@ -1388,3 +1393,45 @@ def delete_model_supply(modelsupplyid: int):
db.session.delete(supply)
db.session.commit()
return success_response(message='Supply deleted')
@printers_asset_bp.route('/dashboard/supplies', methods=['GET'])
@jwt_required()
@require_permission('printers.view')
def dashboard_supplies():
"""Printers needing a cartridge, flattened to one row per printer.
Reuses the existing low-supplies query and its five-minute cache, so the
card costs nothing extra: a Zabbix round-trip per printer on every dashboard
load would make this the slowest page in the app.
Critical first, then low. A printer with several depleted cartridges appears
once, listing them - a row per cartridge would report one printer three
times and read as three problems.
"""
data = _get_low_supplies_data()
rows = []
for printer in data.get('printers', []):
criticals = [s for s in printer['supplies'] if s['status'] == 'critical']
lows = [s for s in printer['supplies'] if s['status'] == 'low']
if not criticals and not lows:
continue
# Every depleted supply, criticals first. Listing only the worst class
# would hide a low cartridge behind a critical one on the same printer,
# and whoever walks out there wants to carry both.
worst = criticals + lows
rows.append({
'printerid': printer['printerid'],
'printername': printer['printername'] or printer['assetnumber'],
'location': printer['location'],
'status': 'critical' if criticals else 'low',
'supplies': ', '.join(
'{} {}%'.format(s.get('name') or s.get('type') or 'supply',
s.get('percent'))
for s in worst),
'iscritical': bool(criticals),
})
rows.sort(key=lambda r: (not r['iscritical'], r['printername']))
return success_response(rows)

View File

@@ -287,14 +287,28 @@ class PrintersPlugin(BasePlugin):
return [printerscli]
def get_dashboard_widgets(self) -> List[Dict]:
"""Return dashboard widget definitions."""
"""Dashboard card: printers needing a cartridge.
Replaces a declaration naming a component nobody wrote. Reuses the
low-supplies query and its cache - a Zabbix round-trip per printer on
every dashboard load would make this the slowest page in the app.
"""
return [
{
'name': 'Printer Status',
'component': 'PrinterStatusWidget',
'endpoint': '/api/printers/dashboard/summary',
'size': 'medium',
'position': 10,
'id': 'printers-supplies',
'title': 'Printer supplies',
'endpoint': '/api/printers/dashboard/supplies',
'render': 'exceptions',
'severity': 'warning',
'permission': 'printers.view',
'empty': 'hide',
'position': 40,
'map': {
'title': 'printername',
'detail': 'supplies',
'meta': [{'key': 'location'}, {'key': 'status'}],
'link': '/printers/{printerid}',
},
},
]

View File

@@ -5,7 +5,7 @@ never stored. Warranties link to assets many-to-many via warrantyassets, though
the common case is one warranty per asset.
"""
from datetime import date, datetime, timezone
from datetime import date, datetime, timedelta, timezone
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
@@ -391,3 +391,54 @@ def warranty_report():
'counts': {k: len(v) for k, v in buckets.items()},
'buckets': buckets,
})
@warranty_bp.route('/dashboard/expiring', methods=['GET'])
@jwt_required()
@require_permission('warranty.view')
def dashboard_expiring():
"""Warranties running out, and ones that already have.
Already-expired first, then soonest. Expired stays on the list rather than
dropping off: a machine out of warranty is a purchasing decision someone
still has to make, and silently removing it the day it lapses is how it gets
missed entirely.
Horizon is a setting because 90 days suits a site that budgets quarterly and
nobody else (ADR-015).
"""
from shopdb.api import Setting
days = 90
setting = Setting.query.filter_by(key='warranty_expiringdays').first()
if setting and (setting.value or '').strip():
try:
days = int(setting.value)
except (TypeError, ValueError):
pass
today = date.today()
horizon = today + timedelta(days=days)
rows = []
query = (db.session.query(Warranty, WarrantyAsset, Asset)
.join(WarrantyAsset, WarrantyAsset.warrantyid == Warranty.warrantyid)
.join(Asset, Asset.assetid == WarrantyAsset.assetid)
.filter(Warranty.isactive.is_(True),
Warranty.enddate.isnot(None),
Warranty.enddate <= horizon,
Asset.isactive.is_(True)))
for warranty, _link, asset in query.all():
remaining = (warranty.enddate - today).days
rows.append({
'assetid': asset.assetid,
'assetnumber': asset.assetnumber or asset.name or str(asset.assetid),
'enddate': warranty.enddate.isoformat(),
'provider': warranty.provider,
'daysleft': remaining,
'state': 'expired' if remaining < 0 else 'expiring',
})
rows.sort(key=lambda r: r['daysleft'])
return success_response(rows[:50])

View File

@@ -114,6 +114,49 @@ class WarrantyPlugin(BasePlugin):
},
]
def get_dashboard_widgets(self) -> List[Dict]:
"""Dashboard card: warranties running out, and ones already expired.
Expired stays listed rather than dropping off. A machine out of
warranty is a purchasing decision someone still has to make, and
removing it the day it lapses is how it gets missed entirely.
"""
return [
{
'id': 'warranty-expiring',
'title': 'Warranties expiring',
'endpoint': '/api/warranty/dashboard/expiring',
'render': 'exceptions',
'severity': 'info',
'permission': 'warranty.view',
'empty': 'hide',
'position': 50,
'map': {
'title': 'assetnumber',
'detail': 'state',
'meta': [
{'key': 'enddate', 'label': 'ends', 'format': 'date'},
{'key': 'provider'},
],
'link': '/assets/{assetid}',
},
},
]
def get_settings_defaults(self) -> List[Dict]:
"""Settings this plugin owns."""
return [
{
'key': 'warranty_expiringdays',
'value': '90',
'valuetype': 'integer',
'category': 'warranty',
'description': 'Days ahead to list an expiring warranty on the '
'dashboard. Already-expired warranties are always '
'listed.',
},
]
def get_permissions(self) -> List:
"""Return the RBAC permissions this plugin owns."""
return [