Rack: link items to devices, shelves, several racks, export; fix layout and light mode
Lint / JS (eslint) (push) Successful in 7s
Lint / Python (flake8) (push) Successful in 48s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 49s
Lint / Python (flake8) (pull_request) Successful in 51s
Test / Python Tests (pytest) (push) Successful in 1m2s
Lint / JS (eslint) (pull_request) Successful in 7s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 50s
Test / Python Tests (pytest) (pull_request) Successful in 53s

Cutsheet items gain a "Gandalf device" link, so an item named after the
product (UDM-Pro) shows the live device's faceplate, ports and status.
Cable checks, suggestions, tickets and the device page treat an item and
its linked device as one. Without this, product-named items drew as bare
name plates.

Items can sit on a shelf instead of a rack unit; the shelf draws what is
on it with live status. Items have a rack, the page shows a tab per rack
(config "racks"), and a rack can be downloaded as SVG or PNG.

The rack is centred, long runs of empty units fold into one band (with a
toggle), every device fills the 19" width, the UPS shows its front only,
and the rack keeps its own palette so it reads in light mode.

New cutsheet_items columns rack, shelf and device are added on first use.
Deleting a shelf, or making it something else, is refused while it holds
items; renaming it carries over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 21:44:59 -05:00
co-authored by Claude Opus 5.5
parent 4f353888f8
commit bdd68a397d
12 changed files with 540 additions and 64 deletions
+99 -22
View File
@@ -933,10 +933,14 @@ def _cutsheet_view() -> dict:
]
cable['a_text'] = cutsheet.describe_node(cutsheet._node(cable, 'a'))
cable['b_text'] = cutsheet.describe_node(cutsheet._node(cable, 'b'))
data['suggestions'] = cutsheet.undocumented(data['cables'], switches)
data['suggestions'] = cutsheet.undocumented(data['cables'], switches, items)
data['labels'] = cutsheet.labels_to_make(data['cables'], items, data['port_labels'])
data['next_label'] = cutsheet.next_label(data['cables'])
data['catalog'] = _cutsheet_catalog(link_stats, data['items'])
data['racks'] = [r['name'] for r in _racks(data['items'])]
snapshot = _state_json('network_snapshot')
data['devices'] = sorted(set(switches) | set(snapshot.get('hosts') or {})
| {u['name'] for u in snapshot.get('unifi') or [] if u.get('name')}, key=str.lower)
data['verdicts'] = cutsheet.VERDICTS
data['options'] = {'kinds': cutsheet.ITEM_KINDS, 'passive_kinds': cutsheet.PASSIVE_KINDS,
'statuses': cutsheet.STATUSES, 'cable_types': cutsheet.CABLE_TYPES}
@@ -947,10 +951,12 @@ def _cutsheet_view() -> dict:
def _cutsheet_for_device(name: str) -> list:
"""The cables that end on one device, for its port panel."""
view = _cutsheet_view()
# Cables may name the device or a cutsheet item linked to it
names = {name} | {i['name'] for i in view['items'] if i.get('device') == name}
out = []
for cable in view['cables']:
for end in ('a', 'b'):
if cable[f'{end}_device'] == name and cable['status'] != 'retired':
if cable[f'{end}_device'] in names and cable['status'] != 'retired':
out.append({
'port': cable[f'{end}_port'], 'side': cable[f'{end}_side'], 'id': cable['id'],
'label': cable['label'], 'status': cable['status'], 'verdict': cable['verdict'],
@@ -1066,17 +1072,51 @@ def rack_page():
return render_template('rack.html', user=user, can_edit='admin' in user['groups'])
def _rack_units() -> int:
try:
return max(1, min(int((_config().get('rack') or {}).get('units', 42)), 60))
except (TypeError, ValueError):
return 42
def _racks(items: list) -> list:
"""Every rack, in order: the configured ones, then any other name an item uses.
Config: "racks": [{"name": "Main", "units": 42}, ...]. Without it there is one rack,
named rack.name (default "Rack 1") with rack.units (default 42). An item with no rack
belongs to the first.
"""
def units(value, default=42):
try:
return max(1, min(int(value), 60))
except (TypeError, ValueError):
return default
cfg = _config()
single = cfg.get('rack') or {}
default_units = units(single.get('units', 42))
racks = [{'name': str(r.get('name') or '').strip(), 'units': units(r.get('units', default_units), default_units)}
for r in cfg.get('racks') or [] if isinstance(r, dict) and str(r.get('name') or '').strip()]
if not racks:
racks = [{'name': str(single.get('name') or 'Rack 1'), 'units': default_units}]
named = {r['name'] for r in racks}
for item in items:
if item.get('rack') and item['rack'] not in named:
named.add(item['rack'])
racks.append({'name': item['rack'], 'units': default_units})
return racks
def _device_status(name: str, snapshot: dict) -> str:
host = (snapshot.get('hosts') or {}).get(name)
if host:
return host.get('status') or 'unknown'
for d in snapshot.get('unifi') or []:
if d.get('name') == name:
return 'up' if d.get('connected') else 'down'
return 'unknown'
@app.route('/api/rack')
@require_auth
def api_rack():
"""The rack front: placed cutsheet items, live switch ports, and each port's cutsheet state."""
"""One rack's front: placed cutsheet items, live switch ports, and each port's cutsheet state.
Query: rack (name; default the first rack).
"""
view = _cutsheet_view()
link_stats = _state_json('link_stats')
switches = link_stats.get('unifi_switches') or {}
@@ -1085,6 +1125,17 @@ def api_rack():
online = {d['name']: d.get('connected', True) for d in snapshot.get('unifi') or []}
known = set(switches) | set(online) | set(snapshot.get('hosts') or {})
racks = _racks(view['items'])
default = racks[0]['name']
current = next((r for r in racks if r['name'] == request.args.get('rack', default)), None)
if current is None:
return jsonify({'error': 'No such rack'}), 404
def rack_of(item):
return item.get('rack') or default
for r in racks:
r['count'] = sum(1 for i in view['items'] if not i.get('shelf') and i.get('rack_u') and rack_of(i) == r['name'])
for cable in view['cables']:
cable['run'] = [h['cable_id'] for h in cable['path'] if 'cable_id' in h]
marks = cutsheet.port_marks(view['cables'])
@@ -1092,25 +1143,51 @@ def api_rack():
for pl in view['port_labels']:
labels.setdefault(pl['item_name'], {})[str(pl['port'])] = pl['label']
units = _rack_units()
layout = cutsheet.rack_layout(view['items'], units)
def dev(item):
# An item can be named after the product ("UDM-Pro") and linked to the live device
return item.get('device') or item['name']
def url(item):
return f'/device/{quote(dev(item), safe="")}' if dev(item) in known else f'/cutsheet#item-{item["id"]}'
on_shelf: dict = {}
for item in view['items']:
if item.get('shelf'):
on_shelf.setdefault(item['shelf'], []).append(item)
here = [i for i in view['items'] if not i.get('shelf') and rack_of(i) == current['name']]
layout = cutsheet.rack_layout(here, current['units'])
out = []
for item in layout['placed']:
name = item['name']
name, device = item['name'], dev(item)
entry = {k: item.get(k) for k in ('id', 'name', 'kind', 'port_count', 'rack_u', 'rack_height',
'rack_top', 'location', 'notes')}
entry['url'] = f'/device/{quote(name, safe="")}' if name in known else f'/cutsheet#item-{item["id"]}'
entry['ports'] = {port: m for (dev, port), m in marks.items() if dev == name}
entry['device'] = device
entry['linked'] = device in known
entry['url'] = url(item)
entry['status'] = _device_status(device, snapshot) if device in known else ''
# Cables may name either the item or the device it is linked to
entry['ports'] = {port: m for (d, port), m in marks.items() if d in (name, device)}
entry['labels'] = labels.get(name, {})
if name in switches:
sw = switches[name]
entry['switch'] = {'model': sw.get('model') or '', 'ports': sw.get('ports') or {},
'outlets': (unifi_info.get(name) or {}).get('outlets') or [],
'online': online.get(name, True)}
model = next((u.get('model') for u in snapshot.get('unifi') or [] if u.get('name') == device), '')
if device in switches or model:
sw = switches.get(device) or {}
entry['switch'] = {'model': sw.get('model') or model or '', 'ports': sw.get('ports') or {},
'outlets': (unifi_info.get(device) or {}).get('outlets') or [],
'online': online.get(device, True)}
if item['kind'] == 'shelf':
entry['contents'] = [
{'id': c['id'], 'name': c['name'], 'kind': c['kind'], 'url': url(c),
'status': _device_status(dev(c), snapshot) if dev(c) in known else '',
'model': next((u.get('model') for u in snapshot.get('unifi') or [] if u.get('name') == dev(c)), '')
or '', 'notes': c.get('notes') or ''}
for c in sorted(on_shelf.get(name, []), key=lambda c: c['name'].lower())
]
out.append(entry)
return jsonify({
'units': units, 'items': out, 'overlaps': layout['overlaps'], 'outside': layout['outside'],
'unplaced': sorted(i['name'] for i in view['items'] if not i.get('rack_u')),
'racks': racks, 'rack': current['name'], 'units': current['units'], 'items': out,
'overlaps': layout['overlaps'], 'outside': layout['outside'],
'unplaced': sorted(i['name'] for i in here if not i.get('rack_u')),
'updated': link_stats.get('updated'),
})
@@ -1151,7 +1228,7 @@ def api_cutsheet_delete_cable(cable_id: int):
@require_admin
@_cutsheet_write
def api_cutsheet_create_item():
item = cutsheet.validate_item(_json_body())
item = cutsheet.validate_item(_json_body(), _cutsheet_items())
item_id = db.cutsheet_create_item(item, _get_user()['username'])
return jsonify({'success': True, 'id': item_id})
@@ -1161,7 +1238,7 @@ def api_cutsheet_create_item():
@require_admin
@_cutsheet_write
def api_cutsheet_update_item(item_id: int):
item = cutsheet.validate_item(_json_body())
item = cutsheet.validate_item(_json_body(), _cutsheet_items())
if not db.cutsheet_update_item(item_id, item, _get_user()['username']):
return jsonify({'error': 'No such item'}), 404
return jsonify({'success': True})