feat: export switch port usage as PDF instead of a Ports tab

Switches get an "Export switch port usage" button that downloads an A4
landscape PDF: key figures, a front panel with one colour per VLAN label
(full colour = connected, pale = free, dashed with a cross = disabled,
text colour chosen for contrast), a VLAN legend and the full port list
with peers. The PDF follows the language of the user's NetBox
preferences (German or English). The Ports tab with its script and
styles is removed. ReportLab becomes a dependency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-30 09:25:29 +01:00
1 parent 8f2cc22f88
commit 8eb075db9f
13 files changed
+611 -452

No files matched your search

+47 -85
View File
@@ -1,27 +1,11 @@
import csv
from dcim.models import Device, Interface
from django.db.models import Q
from django.http import HttpResponse
from netbox.views import generic
from utilities.views import ViewTab, register_model_view
from django.shortcuts import get_object_or_404
from django.utils import timezone, translation
from django.views import View
from utilities.views import ContentTypePermissionRequiredMixin
from . import switch_ports
from .runtime import switch_ports_enabled
def _connected_query():
return Q(cable__isnull=False) | Q(mark_connected=True)
def ports_tab_badge(device):
""" "belegt/gesamt" of the physical ports; None hides the tab for devices that are no switches."""
if not switch_ports_enabled() or not switch_ports.is_switch(device):
return None
physical = Interface.objects.filter(device=device).exclude(type__in=switch_ports.VIRTUAL_TYPES)
total = physical.count()
connected = physical.filter(_connected_query(), enabled=True).count()
return f"{connected}/{total}"
from . import switch_port_pdf, switch_ports
def _describe(endpoint):
@@ -35,95 +19,73 @@ def _peer(interface):
"""Far end through patch panels if the path is complete, otherwise the directly cabled object."""
try:
endpoints = interface.connected_endpoints if interface._path_id else []
except Exception: # noqa: BLE001 - a broken path must not break the overview
except Exception: # noqa: BLE001 - a broken path must not break the export
endpoints = []
if not endpoints and interface.cable_id:
endpoints = interface.link_peers
if not endpoints:
return "", ""
first = endpoints[0]
text = ", ".join(_describe(endpoint) for endpoint in endpoints)
url = first.get_absolute_url() if hasattr(first, "get_absolute_url") else ""
return text, url
return ", ".join(_describe(endpoint) for endpoint in endpoints or [])
def collect_ports(device):
interfaces = (
Interface.objects.filter(device=device).select_related("lag", "cable", "_path", "module").order_by("_name")
)
def collect_ports(interfaces):
ports = []
for interface in interfaces:
peer, peer_url = _peer(interface)
connected = bool(interface.cable_id or interface.mark_connected)
peer = _peer(interface)
if not peer and interface.mark_connected:
peer = switch_ports.MARKED_CONNECTED
ports.append(
switch_ports.Port(
pk=interface.pk,
name=interface.name,
label=interface.label,
type=interface.type,
type_display=interface.get_type_display(),
type_display=str(interface.get_type_display()),
enabled=interface.enabled,
connected=connected,
connected=bool(interface.cable_id or interface.mark_connected),
mgmt_only=interface.mgmt_only,
description=interface.description,
peer=peer or ("als verbunden markiert" if interface.mark_connected else ""),
peer_url=peer_url,
peer=peer,
lag=interface.lag.name if interface.lag_id else "",
speed=f"{interface.speed // 1000} Mbit/s" if interface.speed else "",
url=interface.get_absolute_url(),
virtual=interface.type in switch_ports.VIRTUAL_TYPES,
)
)
return ports
@register_model_view(Device, "ports", path="ports")
class DevicePortsView(generic.ObjectView):
queryset = Device.objects.all()
template_name = "netbox_utilities/device_ports.html"
tab = ViewTab(
label="Ports",
badge=ports_tab_badge,
permission="dcim.view_interface",
weight=2040,
hide_if_empty=True,
def device_info(device):
rack = ""
if device.rack_id:
rack = str(device.rack)
if device.position:
rack += f" / U{device.position:g}"
return switch_port_pdf.DeviceInfo(
name=device.name or str(device),
site=str(device.site) if device.site_id else "",
rack=rack,
model=str(device.device_type),
)
def get(self, request, **kwargs):
if request.GET.get("export") == "csv":
instance = self.get_object(**kwargs)
return self.export_csv(instance)
return super().get(request, **kwargs)
def get_extra_context(self, request, instance):
ports = collect_ports(instance)
return {
"ports": ports,
"groups": switch_ports.build_groups(ports),
"virtual_ports": [port for port in ports if port.virtual],
"summary": switch_ports.summary(ports),
"legend": switch_ports.vlan_legend(ports),
"states": switch_ports.STATE_LABELS,
}
class SwitchPortsPDFView(ContentTypePermissionRequiredMixin, View):
"""PDF of the port usage of a switch, in the language of the user's NetBox preferences."""
@staticmethod
def export_csv(device):
response = HttpResponse(content_type="text/csv; charset=utf-8")
response["Content-Disposition"] = f'attachment; filename="{device.name or device.pk}-ports.csv"'
response.write("") # Excel opens UTF-8 correctly with a BOM
writer = csv.writer(response, delimiter=";")
writer.writerow(["Port", "Status", "VLAN (Label)", "Gegenstelle", "Beschreibung", "Typ", "LAG", "Speed"])
for port in collect_ports(device):
writer.writerow(
[
port.name,
port.state_label,
port.label,
port.peer,
port.description,
port.type_display,
port.lag,
port.speed,
]
)
def get_required_permission(self):
return "dcim.view_interface"
def get(self, request, pk):
device = get_object_or_404(
Device.objects.restrict(request.user, "view").select_related("site", "rack", "device_type"), pk=pk
)
interfaces = (
Interface.objects.restrict(request.user, "view")
.filter(device=device)
.select_related("lag", "cable", "_path")
.order_by("_name")
)
lang = switch_port_pdf.language(translation.get_language())
pdf = switch_port_pdf.build_pdf(
device_info(device), collect_ports(interfaces), lang=lang, generated=timezone.localtime()
)
filename = f"{switch_port_pdf.TEXTS[lang]['filename']}-{device.name or device.pk}.pdf".replace(" ", "_")
response = HttpResponse(pdf, content_type="application/pdf")
response["Content-Disposition"] = f'attachment; filename="{filename}"'
return response